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/TargetInstrInfo.h" 46 #include "llvm/CodeGen/ValueTypes.h" 47 #include "llvm/IR/Attributes.h" 48 #include "llvm/IR/Constants.h" 49 #include "llvm/IR/DataLayout.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/GetElementPtrTypeIterator.h" 54 #include "llvm/IR/GlobalValue.h" 55 #include "llvm/IR/IRBuilder.h" 56 #include "llvm/IR/Instruction.h" 57 #include "llvm/IR/Instructions.h" 58 #include "llvm/IR/Intrinsics.h" 59 #include "llvm/IR/Module.h" 60 #include "llvm/IR/OperandTraits.h" 61 #include "llvm/IR/Type.h" 62 #include "llvm/IR/Use.h" 63 #include "llvm/IR/Value.h" 64 #include "llvm/MC/MCRegisterInfo.h" 65 #include "llvm/Support/Casting.h" 66 #include "llvm/Support/CodeGen.h" 67 #include "llvm/Support/CommandLine.h" 68 #include "llvm/Support/Compiler.h" 69 #include "llvm/Support/Debug.h" 70 #include "llvm/Support/ErrorHandling.h" 71 #include "llvm/Support/KnownBits.h" 72 #include "llvm/Support/MathExtras.h" 73 #include "llvm/Support/raw_ostream.h" 74 #include "llvm/Target/TargetCallingConv.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 // Returns true if the given Op is the overflow flag result of an overflow 1976 // intrinsic operation. 1977 static bool isOverflowIntrOpRes(SDValue Op) { 1978 unsigned Opc = Op.getOpcode(); 1979 return (Op.getResNo() == 1 && 1980 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 1981 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)); 1982 } 1983 1984 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 1985 SDValue Sel = Op.getOperand(0); 1986 SDValue Other = Op.getOperand(1); 1987 SDLoc dl(Sel); 1988 1989 // If the operand is an overflow checking operation, invert the condition 1990 // code and kill the Not operation. I.e., transform: 1991 // (xor (overflow_op_bool, 1)) 1992 // --> 1993 // (csel 1, 0, invert(cc), overflow_op_bool) 1994 // ... which later gets transformed to just a cset instruction with an 1995 // inverted condition code, rather than a cset + eor sequence. 1996 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) { 1997 // Only lower legal XALUO ops. 1998 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) 1999 return SDValue(); 2000 2001 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2002 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2003 AArch64CC::CondCode CC; 2004 SDValue Value, Overflow; 2005 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); 2006 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2007 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, 2008 CCVal, Overflow); 2009 } 2010 // If neither operand is a SELECT_CC, give up. 2011 if (Sel.getOpcode() != ISD::SELECT_CC) 2012 std::swap(Sel, Other); 2013 if (Sel.getOpcode() != ISD::SELECT_CC) 2014 return Op; 2015 2016 // The folding we want to perform is: 2017 // (xor x, (select_cc a, b, cc, 0, -1) ) 2018 // --> 2019 // (csel x, (xor x, -1), cc ...) 2020 // 2021 // The latter will get matched to a CSINV instruction. 2022 2023 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 2024 SDValue LHS = Sel.getOperand(0); 2025 SDValue RHS = Sel.getOperand(1); 2026 SDValue TVal = Sel.getOperand(2); 2027 SDValue FVal = Sel.getOperand(3); 2028 2029 // FIXME: This could be generalized to non-integer comparisons. 2030 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 2031 return Op; 2032 2033 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 2034 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 2035 2036 // The values aren't constants, this isn't the pattern we're looking for. 2037 if (!CFVal || !CTVal) 2038 return Op; 2039 2040 // We can commute the SELECT_CC by inverting the condition. This 2041 // might be needed to make this fit into a CSINV pattern. 2042 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 2043 std::swap(TVal, FVal); 2044 std::swap(CTVal, CFVal); 2045 CC = ISD::getSetCCInverse(CC, true); 2046 } 2047 2048 // If the constants line up, perform the transform! 2049 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 2050 SDValue CCVal; 2051 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 2052 2053 FVal = Other; 2054 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 2055 DAG.getConstant(-1ULL, dl, Other.getValueType())); 2056 2057 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 2058 CCVal, Cmp); 2059 } 2060 2061 return Op; 2062 } 2063 2064 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 2065 EVT VT = Op.getValueType(); 2066 2067 // Let legalize expand this if it isn't a legal type yet. 2068 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 2069 return SDValue(); 2070 2071 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 2072 2073 unsigned Opc; 2074 bool ExtraOp = false; 2075 switch (Op.getOpcode()) { 2076 default: 2077 llvm_unreachable("Invalid code"); 2078 case ISD::ADDC: 2079 Opc = AArch64ISD::ADDS; 2080 break; 2081 case ISD::SUBC: 2082 Opc = AArch64ISD::SUBS; 2083 break; 2084 case ISD::ADDE: 2085 Opc = AArch64ISD::ADCS; 2086 ExtraOp = true; 2087 break; 2088 case ISD::SUBE: 2089 Opc = AArch64ISD::SBCS; 2090 ExtraOp = true; 2091 break; 2092 } 2093 2094 if (!ExtraOp) 2095 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 2096 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 2097 Op.getOperand(2)); 2098 } 2099 2100 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 2101 // Let legalize expand this if it isn't a legal type yet. 2102 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 2103 return SDValue(); 2104 2105 SDLoc dl(Op); 2106 AArch64CC::CondCode CC; 2107 // The actual operation that sets the overflow or carry flag. 2108 SDValue Value, Overflow; 2109 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 2110 2111 // We use 0 and 1 as false and true values. 2112 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2113 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2114 2115 // We use an inverted condition, because the conditional select is inverted 2116 // too. This will allow it to be selected to a single instruction: 2117 // CSINC Wd, WZR, WZR, invert(cond). 2118 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2119 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 2120 CCVal, Overflow); 2121 2122 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 2123 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 2124 } 2125 2126 // Prefetch operands are: 2127 // 1: Address to prefetch 2128 // 2: bool isWrite 2129 // 3: int locality (0 = no locality ... 3 = extreme locality) 2130 // 4: bool isDataCache 2131 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 2132 SDLoc DL(Op); 2133 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 2134 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 2135 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2136 2137 bool IsStream = !Locality; 2138 // When the locality number is set 2139 if (Locality) { 2140 // The front-end should have filtered out the out-of-range values 2141 assert(Locality <= 3 && "Prefetch locality out-of-range"); 2142 // The locality degree is the opposite of the cache speed. 2143 // Put the number the other way around. 2144 // The encoding starts at 0 for level 1 2145 Locality = 3 - Locality; 2146 } 2147 2148 // built the mask value encoding the expected behavior. 2149 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 2150 (!IsData << 3) | // IsDataCache bit 2151 (Locality << 1) | // Cache level bits 2152 (unsigned)IsStream; // Stream bit 2153 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 2154 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 2155 } 2156 2157 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 2158 SelectionDAG &DAG) const { 2159 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 2160 2161 RTLIB::Libcall LC; 2162 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 2163 2164 return LowerF128Call(Op, DAG, LC); 2165 } 2166 2167 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 2168 SelectionDAG &DAG) const { 2169 if (Op.getOperand(0).getValueType() != MVT::f128) { 2170 // It's legal except when f128 is involved 2171 return Op; 2172 } 2173 2174 RTLIB::Libcall LC; 2175 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 2176 2177 // FP_ROUND node has a second operand indicating whether it is known to be 2178 // precise. That doesn't take part in the LibCall so we can't directly use 2179 // LowerF128Call. 2180 SDValue SrcVal = Op.getOperand(0); 2181 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 2182 SDLoc(Op)).first; 2183 } 2184 2185 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 2186 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2187 // Any additional optimization in this function should be recorded 2188 // in the cost tables. 2189 EVT InVT = Op.getOperand(0).getValueType(); 2190 EVT VT = Op.getValueType(); 2191 unsigned NumElts = InVT.getVectorNumElements(); 2192 2193 // f16 vectors are promoted to f32 before a conversion. 2194 if (InVT.getVectorElementType() == MVT::f16) { 2195 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 2196 SDLoc dl(Op); 2197 return DAG.getNode( 2198 Op.getOpcode(), dl, Op.getValueType(), 2199 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 2200 } 2201 2202 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2203 SDLoc dl(Op); 2204 SDValue Cv = 2205 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 2206 Op.getOperand(0)); 2207 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 2208 } 2209 2210 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2211 SDLoc dl(Op); 2212 MVT ExtVT = 2213 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 2214 VT.getVectorNumElements()); 2215 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 2216 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 2217 } 2218 2219 // Type changing conversions are illegal. 2220 return Op; 2221 } 2222 2223 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 2224 SelectionDAG &DAG) const { 2225 if (Op.getOperand(0).getValueType().isVector()) 2226 return LowerVectorFP_TO_INT(Op, DAG); 2227 2228 // f16 conversions are promoted to f32 when full fp16 is not supported. 2229 if (Op.getOperand(0).getValueType() == MVT::f16 && 2230 !Subtarget->hasFullFP16()) { 2231 SDLoc dl(Op); 2232 return DAG.getNode( 2233 Op.getOpcode(), dl, Op.getValueType(), 2234 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); 2235 } 2236 2237 if (Op.getOperand(0).getValueType() != MVT::f128) { 2238 // It's legal except when f128 is involved 2239 return Op; 2240 } 2241 2242 RTLIB::Libcall LC; 2243 if (Op.getOpcode() == ISD::FP_TO_SINT) 2244 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2245 else 2246 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2247 2248 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2249 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first; 2250 } 2251 2252 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2253 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2254 // Any additional optimization in this function should be recorded 2255 // in the cost tables. 2256 EVT VT = Op.getValueType(); 2257 SDLoc dl(Op); 2258 SDValue In = Op.getOperand(0); 2259 EVT InVT = In.getValueType(); 2260 2261 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2262 MVT CastVT = 2263 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2264 InVT.getVectorNumElements()); 2265 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2266 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2267 } 2268 2269 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2270 unsigned CastOpc = 2271 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2272 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2273 In = DAG.getNode(CastOpc, dl, CastVT, In); 2274 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2275 } 2276 2277 return Op; 2278 } 2279 2280 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2281 SelectionDAG &DAG) const { 2282 if (Op.getValueType().isVector()) 2283 return LowerVectorINT_TO_FP(Op, DAG); 2284 2285 // f16 conversions are promoted to f32 when full fp16 is not supported. 2286 if (Op.getValueType() == MVT::f16 && 2287 !Subtarget->hasFullFP16()) { 2288 SDLoc dl(Op); 2289 return DAG.getNode( 2290 ISD::FP_ROUND, dl, MVT::f16, 2291 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), 2292 DAG.getIntPtrConstant(0, dl)); 2293 } 2294 2295 // i128 conversions are libcalls. 2296 if (Op.getOperand(0).getValueType() == MVT::i128) 2297 return SDValue(); 2298 2299 // Other conversions are legal, unless it's to the completely software-based 2300 // fp128. 2301 if (Op.getValueType() != MVT::f128) 2302 return Op; 2303 2304 RTLIB::Libcall LC; 2305 if (Op.getOpcode() == ISD::SINT_TO_FP) 2306 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2307 else 2308 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2309 2310 return LowerF128Call(Op, DAG, LC); 2311 } 2312 2313 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2314 SelectionDAG &DAG) const { 2315 // For iOS, we want to call an alternative entry point: __sincos_stret, 2316 // which returns the values in two S / D registers. 2317 SDLoc dl(Op); 2318 SDValue Arg = Op.getOperand(0); 2319 EVT ArgVT = Arg.getValueType(); 2320 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2321 2322 ArgListTy Args; 2323 ArgListEntry Entry; 2324 2325 Entry.Node = Arg; 2326 Entry.Ty = ArgTy; 2327 Entry.IsSExt = false; 2328 Entry.IsZExt = false; 2329 Args.push_back(Entry); 2330 2331 const char *LibcallName = 2332 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 2333 SDValue Callee = 2334 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2335 2336 StructType *RetTy = StructType::get(ArgTy, ArgTy); 2337 TargetLowering::CallLoweringInfo CLI(DAG); 2338 CLI.setDebugLoc(dl) 2339 .setChain(DAG.getEntryNode()) 2340 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2341 2342 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2343 return CallResult.first; 2344 } 2345 2346 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2347 if (Op.getValueType() != MVT::f16) 2348 return SDValue(); 2349 2350 assert(Op.getOperand(0).getValueType() == MVT::i16); 2351 SDLoc DL(Op); 2352 2353 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2354 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2355 return SDValue( 2356 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2357 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2358 0); 2359 } 2360 2361 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2362 if (OrigVT.getSizeInBits() >= 64) 2363 return OrigVT; 2364 2365 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2366 2367 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2368 switch (OrigSimpleTy) { 2369 default: llvm_unreachable("Unexpected Vector Type"); 2370 case MVT::v2i8: 2371 case MVT::v2i16: 2372 return MVT::v2i32; 2373 case MVT::v4i8: 2374 return MVT::v4i16; 2375 } 2376 } 2377 2378 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2379 const EVT &OrigTy, 2380 const EVT &ExtTy, 2381 unsigned ExtOpcode) { 2382 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2383 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2384 // 64-bits we need to insert a new extension so that it will be 64-bits. 2385 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2386 if (OrigTy.getSizeInBits() >= 64) 2387 return N; 2388 2389 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2390 EVT NewVT = getExtensionTo64Bits(OrigTy); 2391 2392 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2393 } 2394 2395 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2396 bool isSigned) { 2397 EVT VT = N->getValueType(0); 2398 2399 if (N->getOpcode() != ISD::BUILD_VECTOR) 2400 return false; 2401 2402 for (const SDValue &Elt : N->op_values()) { 2403 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2404 unsigned EltSize = VT.getScalarSizeInBits(); 2405 unsigned HalfSize = EltSize / 2; 2406 if (isSigned) { 2407 if (!isIntN(HalfSize, C->getSExtValue())) 2408 return false; 2409 } else { 2410 if (!isUIntN(HalfSize, C->getZExtValue())) 2411 return false; 2412 } 2413 continue; 2414 } 2415 return false; 2416 } 2417 2418 return true; 2419 } 2420 2421 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2422 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2423 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2424 N->getOperand(0)->getValueType(0), 2425 N->getValueType(0), 2426 N->getOpcode()); 2427 2428 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2429 EVT VT = N->getValueType(0); 2430 SDLoc dl(N); 2431 unsigned EltSize = VT.getScalarSizeInBits() / 2; 2432 unsigned NumElts = VT.getVectorNumElements(); 2433 MVT TruncVT = MVT::getIntegerVT(EltSize); 2434 SmallVector<SDValue, 8> Ops; 2435 for (unsigned i = 0; i != NumElts; ++i) { 2436 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2437 const APInt &CInt = C->getAPIntValue(); 2438 // Element types smaller than 32 bits are not legal, so use i32 elements. 2439 // The values are implicitly truncated so sext vs. zext doesn't matter. 2440 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2441 } 2442 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2443 } 2444 2445 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2446 return N->getOpcode() == ISD::SIGN_EXTEND || 2447 isExtendedBUILD_VECTOR(N, DAG, true); 2448 } 2449 2450 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2451 return N->getOpcode() == ISD::ZERO_EXTEND || 2452 isExtendedBUILD_VECTOR(N, DAG, false); 2453 } 2454 2455 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2456 unsigned Opcode = N->getOpcode(); 2457 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2458 SDNode *N0 = N->getOperand(0).getNode(); 2459 SDNode *N1 = N->getOperand(1).getNode(); 2460 return N0->hasOneUse() && N1->hasOneUse() && 2461 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2462 } 2463 return false; 2464 } 2465 2466 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2467 unsigned Opcode = N->getOpcode(); 2468 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2469 SDNode *N0 = N->getOperand(0).getNode(); 2470 SDNode *N1 = N->getOperand(1).getNode(); 2471 return N0->hasOneUse() && N1->hasOneUse() && 2472 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2473 } 2474 return false; 2475 } 2476 2477 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2478 // Multiplications are only custom-lowered for 128-bit vectors so that 2479 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2480 EVT VT = Op.getValueType(); 2481 assert(VT.is128BitVector() && VT.isInteger() && 2482 "unexpected type for custom-lowering ISD::MUL"); 2483 SDNode *N0 = Op.getOperand(0).getNode(); 2484 SDNode *N1 = Op.getOperand(1).getNode(); 2485 unsigned NewOpc = 0; 2486 bool isMLA = false; 2487 bool isN0SExt = isSignExtended(N0, DAG); 2488 bool isN1SExt = isSignExtended(N1, DAG); 2489 if (isN0SExt && isN1SExt) 2490 NewOpc = AArch64ISD::SMULL; 2491 else { 2492 bool isN0ZExt = isZeroExtended(N0, DAG); 2493 bool isN1ZExt = isZeroExtended(N1, DAG); 2494 if (isN0ZExt && isN1ZExt) 2495 NewOpc = AArch64ISD::UMULL; 2496 else if (isN1SExt || isN1ZExt) { 2497 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2498 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2499 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2500 NewOpc = AArch64ISD::SMULL; 2501 isMLA = true; 2502 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2503 NewOpc = AArch64ISD::UMULL; 2504 isMLA = true; 2505 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2506 std::swap(N0, N1); 2507 NewOpc = AArch64ISD::UMULL; 2508 isMLA = true; 2509 } 2510 } 2511 2512 if (!NewOpc) { 2513 if (VT == MVT::v2i64) 2514 // Fall through to expand this. It is not legal. 2515 return SDValue(); 2516 else 2517 // Other vector multiplications are legal. 2518 return Op; 2519 } 2520 } 2521 2522 // Legalize to a S/UMULL instruction 2523 SDLoc DL(Op); 2524 SDValue Op0; 2525 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2526 if (!isMLA) { 2527 Op0 = skipExtensionForVectorMULL(N0, DAG); 2528 assert(Op0.getValueType().is64BitVector() && 2529 Op1.getValueType().is64BitVector() && 2530 "unexpected types for extended operands to VMULL"); 2531 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2532 } 2533 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2534 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2535 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2536 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2537 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2538 EVT Op1VT = Op1.getValueType(); 2539 return DAG.getNode(N0->getOpcode(), DL, VT, 2540 DAG.getNode(NewOpc, DL, VT, 2541 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2542 DAG.getNode(NewOpc, DL, VT, 2543 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2544 } 2545 2546 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2547 SelectionDAG &DAG) const { 2548 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2549 SDLoc dl(Op); 2550 switch (IntNo) { 2551 default: return SDValue(); // Don't custom lower most intrinsics. 2552 case Intrinsic::thread_pointer: { 2553 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2554 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2555 } 2556 case Intrinsic::aarch64_neon_abs: 2557 return DAG.getNode(ISD::ABS, dl, Op.getValueType(), 2558 Op.getOperand(1)); 2559 case Intrinsic::aarch64_neon_smax: 2560 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2561 Op.getOperand(1), Op.getOperand(2)); 2562 case Intrinsic::aarch64_neon_umax: 2563 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2564 Op.getOperand(1), Op.getOperand(2)); 2565 case Intrinsic::aarch64_neon_smin: 2566 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2567 Op.getOperand(1), Op.getOperand(2)); 2568 case Intrinsic::aarch64_neon_umin: 2569 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2570 Op.getOperand(1), Op.getOperand(2)); 2571 } 2572 } 2573 2574 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 2575 SelectionDAG &DAG) const { 2576 DEBUG(dbgs() << "Custom lowering: "); 2577 DEBUG(Op.dump()); 2578 2579 switch (Op.getOpcode()) { 2580 default: 2581 llvm_unreachable("unimplemented operand"); 2582 return SDValue(); 2583 case ISD::BITCAST: 2584 return LowerBITCAST(Op, DAG); 2585 case ISD::GlobalAddress: 2586 return LowerGlobalAddress(Op, DAG); 2587 case ISD::GlobalTLSAddress: 2588 return LowerGlobalTLSAddress(Op, DAG); 2589 case ISD::SETCC: 2590 return LowerSETCC(Op, DAG); 2591 case ISD::BR_CC: 2592 return LowerBR_CC(Op, DAG); 2593 case ISD::SELECT: 2594 return LowerSELECT(Op, DAG); 2595 case ISD::SELECT_CC: 2596 return LowerSELECT_CC(Op, DAG); 2597 case ISD::JumpTable: 2598 return LowerJumpTable(Op, DAG); 2599 case ISD::ConstantPool: 2600 return LowerConstantPool(Op, DAG); 2601 case ISD::BlockAddress: 2602 return LowerBlockAddress(Op, DAG); 2603 case ISD::VASTART: 2604 return LowerVASTART(Op, DAG); 2605 case ISD::VACOPY: 2606 return LowerVACOPY(Op, DAG); 2607 case ISD::VAARG: 2608 return LowerVAARG(Op, DAG); 2609 case ISD::ADDC: 2610 case ISD::ADDE: 2611 case ISD::SUBC: 2612 case ISD::SUBE: 2613 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 2614 case ISD::SADDO: 2615 case ISD::UADDO: 2616 case ISD::SSUBO: 2617 case ISD::USUBO: 2618 case ISD::SMULO: 2619 case ISD::UMULO: 2620 return LowerXALUO(Op, DAG); 2621 case ISD::FADD: 2622 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 2623 case ISD::FSUB: 2624 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 2625 case ISD::FMUL: 2626 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 2627 case ISD::FDIV: 2628 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 2629 case ISD::FP_ROUND: 2630 return LowerFP_ROUND(Op, DAG); 2631 case ISD::FP_EXTEND: 2632 return LowerFP_EXTEND(Op, DAG); 2633 case ISD::FRAMEADDR: 2634 return LowerFRAMEADDR(Op, DAG); 2635 case ISD::RETURNADDR: 2636 return LowerRETURNADDR(Op, DAG); 2637 case ISD::INSERT_VECTOR_ELT: 2638 return LowerINSERT_VECTOR_ELT(Op, DAG); 2639 case ISD::EXTRACT_VECTOR_ELT: 2640 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 2641 case ISD::BUILD_VECTOR: 2642 return LowerBUILD_VECTOR(Op, DAG); 2643 case ISD::VECTOR_SHUFFLE: 2644 return LowerVECTOR_SHUFFLE(Op, DAG); 2645 case ISD::EXTRACT_SUBVECTOR: 2646 return LowerEXTRACT_SUBVECTOR(Op, DAG); 2647 case ISD::SRA: 2648 case ISD::SRL: 2649 case ISD::SHL: 2650 return LowerVectorSRA_SRL_SHL(Op, DAG); 2651 case ISD::SHL_PARTS: 2652 return LowerShiftLeftParts(Op, DAG); 2653 case ISD::SRL_PARTS: 2654 case ISD::SRA_PARTS: 2655 return LowerShiftRightParts(Op, DAG); 2656 case ISD::CTPOP: 2657 return LowerCTPOP(Op, DAG); 2658 case ISD::FCOPYSIGN: 2659 return LowerFCOPYSIGN(Op, DAG); 2660 case ISD::AND: 2661 return LowerVectorAND(Op, DAG); 2662 case ISD::OR: 2663 return LowerVectorOR(Op, DAG); 2664 case ISD::XOR: 2665 return LowerXOR(Op, DAG); 2666 case ISD::PREFETCH: 2667 return LowerPREFETCH(Op, DAG); 2668 case ISD::SINT_TO_FP: 2669 case ISD::UINT_TO_FP: 2670 return LowerINT_TO_FP(Op, DAG); 2671 case ISD::FP_TO_SINT: 2672 case ISD::FP_TO_UINT: 2673 return LowerFP_TO_INT(Op, DAG); 2674 case ISD::FSINCOS: 2675 return LowerFSINCOS(Op, DAG); 2676 case ISD::MUL: 2677 return LowerMUL(Op, DAG); 2678 case ISD::INTRINSIC_WO_CHAIN: 2679 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2680 case ISD::VECREDUCE_ADD: 2681 case ISD::VECREDUCE_SMAX: 2682 case ISD::VECREDUCE_SMIN: 2683 case ISD::VECREDUCE_UMAX: 2684 case ISD::VECREDUCE_UMIN: 2685 case ISD::VECREDUCE_FMAX: 2686 case ISD::VECREDUCE_FMIN: 2687 return LowerVECREDUCE(Op, DAG); 2688 } 2689 } 2690 2691 //===----------------------------------------------------------------------===// 2692 // Calling Convention Implementation 2693 //===----------------------------------------------------------------------===// 2694 2695 #include "AArch64GenCallingConv.inc" 2696 2697 /// Selects the correct CCAssignFn for a given CallingConvention value. 2698 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2699 bool IsVarArg) const { 2700 switch (CC) { 2701 default: 2702 report_fatal_error("Unsupported calling convention."); 2703 case CallingConv::WebKit_JS: 2704 return CC_AArch64_WebKit_JS; 2705 case CallingConv::GHC: 2706 return CC_AArch64_GHC; 2707 case CallingConv::C: 2708 case CallingConv::Fast: 2709 case CallingConv::PreserveMost: 2710 case CallingConv::CXX_FAST_TLS: 2711 case CallingConv::Swift: 2712 if (Subtarget->isTargetWindows() && IsVarArg) 2713 return CC_AArch64_Win64_VarArg; 2714 if (!Subtarget->isTargetDarwin()) 2715 return CC_AArch64_AAPCS; 2716 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS; 2717 case CallingConv::Win64: 2718 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 2719 } 2720 } 2721 2722 CCAssignFn * 2723 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 2724 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 2725 : RetCC_AArch64_AAPCS; 2726 } 2727 2728 SDValue AArch64TargetLowering::LowerFormalArguments( 2729 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2730 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2731 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2732 MachineFunction &MF = DAG.getMachineFunction(); 2733 MachineFrameInfo &MFI = MF.getFrameInfo(); 2734 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()); 2735 2736 // Assign locations to all of the incoming arguments. 2737 SmallVector<CCValAssign, 16> ArgLocs; 2738 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2739 *DAG.getContext()); 2740 2741 // At this point, Ins[].VT may already be promoted to i32. To correctly 2742 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 2743 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 2744 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 2745 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 2746 // LocVT. 2747 unsigned NumArgs = Ins.size(); 2748 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 2749 unsigned CurArgIdx = 0; 2750 for (unsigned i = 0; i != NumArgs; ++i) { 2751 MVT ValVT = Ins[i].VT; 2752 if (Ins[i].isOrigArg()) { 2753 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 2754 CurArgIdx = Ins[i].getOrigArgIndex(); 2755 2756 // Get type of the original argument. 2757 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 2758 /*AllowUnknown*/ true); 2759 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 2760 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 2761 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 2762 ValVT = MVT::i8; 2763 else if (ActualMVT == MVT::i16) 2764 ValVT = MVT::i16; 2765 } 2766 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 2767 bool Res = 2768 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 2769 assert(!Res && "Call operand has unhandled type"); 2770 (void)Res; 2771 } 2772 assert(ArgLocs.size() == Ins.size()); 2773 SmallVector<SDValue, 16> ArgValues; 2774 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2775 CCValAssign &VA = ArgLocs[i]; 2776 2777 if (Ins[i].Flags.isByVal()) { 2778 // Byval is used for HFAs in the PCS, but the system should work in a 2779 // non-compliant manner for larger structs. 2780 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2781 int Size = Ins[i].Flags.getByValSize(); 2782 unsigned NumRegs = (Size + 7) / 8; 2783 2784 // FIXME: This works on big-endian for composite byvals, which are the common 2785 // case. It should also work for fundamental types too. 2786 unsigned FrameIdx = 2787 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 2788 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 2789 InVals.push_back(FrameIdxN); 2790 2791 continue; 2792 } 2793 2794 if (VA.isRegLoc()) { 2795 // Arguments stored in registers. 2796 EVT RegVT = VA.getLocVT(); 2797 2798 SDValue ArgValue; 2799 const TargetRegisterClass *RC; 2800 2801 if (RegVT == MVT::i32) 2802 RC = &AArch64::GPR32RegClass; 2803 else if (RegVT == MVT::i64) 2804 RC = &AArch64::GPR64RegClass; 2805 else if (RegVT == MVT::f16) 2806 RC = &AArch64::FPR16RegClass; 2807 else if (RegVT == MVT::f32) 2808 RC = &AArch64::FPR32RegClass; 2809 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 2810 RC = &AArch64::FPR64RegClass; 2811 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 2812 RC = &AArch64::FPR128RegClass; 2813 else 2814 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 2815 2816 // Transform the arguments in physical registers into virtual ones. 2817 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2818 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 2819 2820 // If this is an 8, 16 or 32-bit value, it is really passed promoted 2821 // to 64 bits. Insert an assert[sz]ext to capture this, then 2822 // truncate to the right size. 2823 switch (VA.getLocInfo()) { 2824 default: 2825 llvm_unreachable("Unknown loc info!"); 2826 case CCValAssign::Full: 2827 break; 2828 case CCValAssign::BCvt: 2829 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 2830 break; 2831 case CCValAssign::AExt: 2832 case CCValAssign::SExt: 2833 case CCValAssign::ZExt: 2834 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt 2835 // nodes after our lowering. 2836 assert(RegVT == Ins[i].VT && "incorrect register location selected"); 2837 break; 2838 } 2839 2840 InVals.push_back(ArgValue); 2841 2842 } else { // VA.isRegLoc() 2843 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 2844 unsigned ArgOffset = VA.getLocMemOffset(); 2845 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; 2846 2847 uint32_t BEAlign = 0; 2848 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 2849 !Ins[i].Flags.isInConsecutiveRegs()) 2850 BEAlign = 8 - ArgSize; 2851 2852 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 2853 2854 // Create load nodes to retrieve arguments from the stack. 2855 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2856 SDValue ArgValue; 2857 2858 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 2859 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 2860 MVT MemVT = VA.getValVT(); 2861 2862 switch (VA.getLocInfo()) { 2863 default: 2864 break; 2865 case CCValAssign::BCvt: 2866 MemVT = VA.getLocVT(); 2867 break; 2868 case CCValAssign::SExt: 2869 ExtType = ISD::SEXTLOAD; 2870 break; 2871 case CCValAssign::ZExt: 2872 ExtType = ISD::ZEXTLOAD; 2873 break; 2874 case CCValAssign::AExt: 2875 ExtType = ISD::EXTLOAD; 2876 break; 2877 } 2878 2879 ArgValue = DAG.getExtLoad( 2880 ExtType, DL, VA.getLocVT(), Chain, FIN, 2881 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 2882 MemVT); 2883 2884 InVals.push_back(ArgValue); 2885 } 2886 } 2887 2888 // varargs 2889 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2890 if (isVarArg) { 2891 if (!Subtarget->isTargetDarwin() || IsWin64) { 2892 // The AAPCS variadic function ABI is identical to the non-variadic 2893 // one. As a result there may be more arguments in registers and we should 2894 // save them for future reference. 2895 // Win64 variadic functions also pass arguments in registers, but all float 2896 // arguments are passed in integer registers. 2897 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 2898 } 2899 2900 // This will point to the next argument passed via stack. 2901 unsigned StackOffset = CCInfo.getNextStackOffset(); 2902 // We currently pass all varargs at 8-byte alignment. 2903 StackOffset = ((StackOffset + 7) & ~7); 2904 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 2905 } 2906 2907 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2908 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2909 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 2910 // This is a non-standard ABI so by fiat I say we're allowed to make full 2911 // use of the stack area to be popped, which must be aligned to 16 bytes in 2912 // any case: 2913 StackArgSize = alignTo(StackArgSize, 16); 2914 2915 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 2916 // a multiple of 16. 2917 FuncInfo->setArgumentStackToRestore(StackArgSize); 2918 2919 // This realignment carries over to the available bytes below. Our own 2920 // callers will guarantee the space is free by giving an aligned value to 2921 // CALLSEQ_START. 2922 } 2923 // Even if we're not expected to free up the space, it's useful to know how 2924 // much is there while considering tail calls (because we can reuse it). 2925 FuncInfo->setBytesInStackArgArea(StackArgSize); 2926 2927 return Chain; 2928 } 2929 2930 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 2931 SelectionDAG &DAG, 2932 const SDLoc &DL, 2933 SDValue &Chain) const { 2934 MachineFunction &MF = DAG.getMachineFunction(); 2935 MachineFrameInfo &MFI = MF.getFrameInfo(); 2936 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2937 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2938 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()); 2939 2940 SmallVector<SDValue, 8> MemOps; 2941 2942 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 2943 AArch64::X3, AArch64::X4, AArch64::X5, 2944 AArch64::X6, AArch64::X7 }; 2945 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 2946 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 2947 2948 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 2949 int GPRIdx = 0; 2950 if (GPRSaveSize != 0) { 2951 if (IsWin64) { 2952 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 2953 if (GPRSaveSize & 15) 2954 // The extra size here, if triggered, will always be 8. 2955 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 2956 } else 2957 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); 2958 2959 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 2960 2961 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 2962 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 2963 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 2964 SDValue Store = DAG.getStore( 2965 Val.getValue(1), DL, Val, FIN, 2966 IsWin64 2967 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 2968 GPRIdx, 2969 (i - FirstVariadicGPR) * 8) 2970 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 2971 MemOps.push_back(Store); 2972 FIN = 2973 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 2974 } 2975 } 2976 FuncInfo->setVarArgsGPRIndex(GPRIdx); 2977 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 2978 2979 if (Subtarget->hasFPARMv8() && !IsWin64) { 2980 static const MCPhysReg FPRArgRegs[] = { 2981 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 2982 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 2983 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 2984 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 2985 2986 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 2987 int FPRIdx = 0; 2988 if (FPRSaveSize != 0) { 2989 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); 2990 2991 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 2992 2993 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 2994 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 2995 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 2996 2997 SDValue Store = DAG.getStore( 2998 Val.getValue(1), DL, Val, FIN, 2999 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 3000 MemOps.push_back(Store); 3001 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 3002 DAG.getConstant(16, DL, PtrVT)); 3003 } 3004 } 3005 FuncInfo->setVarArgsFPRIndex(FPRIdx); 3006 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 3007 } 3008 3009 if (!MemOps.empty()) { 3010 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 3011 } 3012 } 3013 3014 /// LowerCallResult - Lower the result values of a call into the 3015 /// appropriate copies out of appropriate physical registers. 3016 SDValue AArch64TargetLowering::LowerCallResult( 3017 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 3018 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3019 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 3020 SDValue ThisVal) const { 3021 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3022 ? RetCC_AArch64_WebKit_JS 3023 : RetCC_AArch64_AAPCS; 3024 // Assign locations to each value returned by this call. 3025 SmallVector<CCValAssign, 16> RVLocs; 3026 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3027 *DAG.getContext()); 3028 CCInfo.AnalyzeCallResult(Ins, RetCC); 3029 3030 // Copy all of the result registers out of their specified physreg. 3031 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3032 CCValAssign VA = RVLocs[i]; 3033 3034 // Pass 'this' value directly from the argument to return value, to avoid 3035 // reg unit interference 3036 if (i == 0 && isThisReturn) { 3037 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 3038 "unexpected return calling convention register assignment"); 3039 InVals.push_back(ThisVal); 3040 continue; 3041 } 3042 3043 SDValue Val = 3044 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 3045 Chain = Val.getValue(1); 3046 InFlag = Val.getValue(2); 3047 3048 switch (VA.getLocInfo()) { 3049 default: 3050 llvm_unreachable("Unknown loc info!"); 3051 case CCValAssign::Full: 3052 break; 3053 case CCValAssign::BCvt: 3054 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3055 break; 3056 } 3057 3058 InVals.push_back(Val); 3059 } 3060 3061 return Chain; 3062 } 3063 3064 /// Return true if the calling convention is one that we can guarantee TCO for. 3065 static bool canGuaranteeTCO(CallingConv::ID CC) { 3066 return CC == CallingConv::Fast; 3067 } 3068 3069 /// Return true if we might ever do TCO for calls with this calling convention. 3070 static bool mayTailCallThisCC(CallingConv::ID CC) { 3071 switch (CC) { 3072 case CallingConv::C: 3073 case CallingConv::PreserveMost: 3074 case CallingConv::Swift: 3075 return true; 3076 default: 3077 return canGuaranteeTCO(CC); 3078 } 3079 } 3080 3081 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 3082 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 3083 const SmallVectorImpl<ISD::OutputArg> &Outs, 3084 const SmallVectorImpl<SDValue> &OutVals, 3085 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3086 if (!mayTailCallThisCC(CalleeCC)) 3087 return false; 3088 3089 MachineFunction &MF = DAG.getMachineFunction(); 3090 const Function *CallerF = MF.getFunction(); 3091 CallingConv::ID CallerCC = CallerF->getCallingConv(); 3092 bool CCMatch = CallerCC == CalleeCC; 3093 3094 // Byval parameters hand the function a pointer directly into the stack area 3095 // we want to reuse during a tail call. Working around this *is* possible (see 3096 // X86) but less efficient and uglier in LowerCall. 3097 for (Function::const_arg_iterator i = CallerF->arg_begin(), 3098 e = CallerF->arg_end(); 3099 i != e; ++i) 3100 if (i->hasByValAttr()) 3101 return false; 3102 3103 if (getTargetMachine().Options.GuaranteedTailCallOpt) 3104 return canGuaranteeTCO(CalleeCC) && CCMatch; 3105 3106 // Externally-defined functions with weak linkage should not be 3107 // tail-called on AArch64 when the OS does not support dynamic 3108 // pre-emption of symbols, as the AAELF spec requires normal calls 3109 // to undefined weak functions to be replaced with a NOP or jump to the 3110 // next instruction. The behaviour of branch instructions in this 3111 // situation (as used for tail calls) is implementation-defined, so we 3112 // cannot rely on the linker replacing the tail call with a return. 3113 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3114 const GlobalValue *GV = G->getGlobal(); 3115 const Triple &TT = getTargetMachine().getTargetTriple(); 3116 if (GV->hasExternalWeakLinkage() && 3117 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 3118 return false; 3119 } 3120 3121 // Now we search for cases where we can use a tail call without changing the 3122 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 3123 // concept. 3124 3125 // I want anyone implementing a new calling convention to think long and hard 3126 // about this assert. 3127 assert((!isVarArg || CalleeCC == CallingConv::C) && 3128 "Unexpected variadic calling convention"); 3129 3130 LLVMContext &C = *DAG.getContext(); 3131 if (isVarArg && !Outs.empty()) { 3132 // At least two cases here: if caller is fastcc then we can't have any 3133 // memory arguments (we'd be expected to clean up the stack afterwards). If 3134 // caller is C then we could potentially use its argument area. 3135 3136 // FIXME: for now we take the most conservative of these in both cases: 3137 // disallow all variadic memory operands. 3138 SmallVector<CCValAssign, 16> ArgLocs; 3139 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3140 3141 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 3142 for (const CCValAssign &ArgLoc : ArgLocs) 3143 if (!ArgLoc.isRegLoc()) 3144 return false; 3145 } 3146 3147 // Check that the call results are passed in the same way. 3148 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 3149 CCAssignFnForCall(CalleeCC, isVarArg), 3150 CCAssignFnForCall(CallerCC, isVarArg))) 3151 return false; 3152 // The callee has to preserve all registers the caller needs to preserve. 3153 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3154 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3155 if (!CCMatch) { 3156 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3157 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3158 return false; 3159 } 3160 3161 // Nothing more to check if the callee is taking no arguments 3162 if (Outs.empty()) 3163 return true; 3164 3165 SmallVector<CCValAssign, 16> ArgLocs; 3166 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3167 3168 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 3169 3170 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3171 3172 // If the stack arguments for this call do not fit into our own save area then 3173 // the call cannot be made tail. 3174 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3175 return false; 3176 3177 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3178 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 3179 return false; 3180 3181 return true; 3182 } 3183 3184 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 3185 SelectionDAG &DAG, 3186 MachineFrameInfo &MFI, 3187 int ClobberedFI) const { 3188 SmallVector<SDValue, 8> ArgChains; 3189 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 3190 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 3191 3192 // Include the original chain at the beginning of the list. When this is 3193 // used by target LowerCall hooks, this helps legalize find the 3194 // CALLSEQ_BEGIN node. 3195 ArgChains.push_back(Chain); 3196 3197 // Add a chain value for each stack argument corresponding 3198 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 3199 UE = DAG.getEntryNode().getNode()->use_end(); 3200 U != UE; ++U) 3201 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 3202 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 3203 if (FI->getIndex() < 0) { 3204 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 3205 int64_t InLastByte = InFirstByte; 3206 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 3207 3208 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 3209 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 3210 ArgChains.push_back(SDValue(L, 1)); 3211 } 3212 3213 // Build a tokenfactor for all the chains. 3214 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 3215 } 3216 3217 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 3218 bool TailCallOpt) const { 3219 return CallCC == CallingConv::Fast && TailCallOpt; 3220 } 3221 3222 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 3223 /// and add input and output parameter nodes. 3224 SDValue 3225 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 3226 SmallVectorImpl<SDValue> &InVals) const { 3227 SelectionDAG &DAG = CLI.DAG; 3228 SDLoc &DL = CLI.DL; 3229 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3230 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3231 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3232 SDValue Chain = CLI.Chain; 3233 SDValue Callee = CLI.Callee; 3234 bool &IsTailCall = CLI.IsTailCall; 3235 CallingConv::ID CallConv = CLI.CallConv; 3236 bool IsVarArg = CLI.IsVarArg; 3237 3238 MachineFunction &MF = DAG.getMachineFunction(); 3239 bool IsThisReturn = false; 3240 3241 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3242 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3243 bool IsSibCall = false; 3244 3245 if (IsTailCall) { 3246 // Check if it's really possible to do a tail call. 3247 IsTailCall = isEligibleForTailCallOptimization( 3248 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3249 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) 3250 report_fatal_error("failed to perform tail call elimination on a call " 3251 "site marked musttail"); 3252 3253 // A sibling call is one where we're under the usual C ABI and not planning 3254 // to change that but can still do a tail call: 3255 if (!TailCallOpt && IsTailCall) 3256 IsSibCall = true; 3257 3258 if (IsTailCall) 3259 ++NumTailCalls; 3260 } 3261 3262 // Analyze operands of the call, assigning locations to each operand. 3263 SmallVector<CCValAssign, 16> ArgLocs; 3264 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 3265 *DAG.getContext()); 3266 3267 if (IsVarArg) { 3268 // Handle fixed and variable vector arguments differently. 3269 // Variable vector arguments always go into memory. 3270 unsigned NumArgs = Outs.size(); 3271 3272 for (unsigned i = 0; i != NumArgs; ++i) { 3273 MVT ArgVT = Outs[i].VT; 3274 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3275 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 3276 /*IsVarArg=*/ !Outs[i].IsFixed); 3277 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 3278 assert(!Res && "Call operand has unhandled type"); 3279 (void)Res; 3280 } 3281 } else { 3282 // At this point, Outs[].VT may already be promoted to i32. To correctly 3283 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3284 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3285 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 3286 // we use a special version of AnalyzeCallOperands to pass in ValVT and 3287 // LocVT. 3288 unsigned NumArgs = Outs.size(); 3289 for (unsigned i = 0; i != NumArgs; ++i) { 3290 MVT ValVT = Outs[i].VT; 3291 // Get type of the original argument. 3292 EVT ActualVT = getValueType(DAG.getDataLayout(), 3293 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 3294 /*AllowUnknown*/ true); 3295 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 3296 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3297 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3298 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3299 ValVT = MVT::i8; 3300 else if (ActualMVT == MVT::i16) 3301 ValVT = MVT::i16; 3302 3303 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3304 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 3305 assert(!Res && "Call operand has unhandled type"); 3306 (void)Res; 3307 } 3308 } 3309 3310 // Get a count of how many bytes are to be pushed on the stack. 3311 unsigned NumBytes = CCInfo.getNextStackOffset(); 3312 3313 if (IsSibCall) { 3314 // Since we're not changing the ABI to make this a tail call, the memory 3315 // operands are already available in the caller's incoming argument space. 3316 NumBytes = 0; 3317 } 3318 3319 // FPDiff is the byte offset of the call's argument area from the callee's. 3320 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3321 // by this amount for a tail call. In a sibling call it must be 0 because the 3322 // caller will deallocate the entire stack and the callee still expects its 3323 // arguments to begin at SP+0. Completely unused for non-tail calls. 3324 int FPDiff = 0; 3325 3326 if (IsTailCall && !IsSibCall) { 3327 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 3328 3329 // Since callee will pop argument stack as a tail call, we must keep the 3330 // popped size 16-byte aligned. 3331 NumBytes = alignTo(NumBytes, 16); 3332 3333 // FPDiff will be negative if this tail call requires more space than we 3334 // would automatically have in our incoming argument space. Positive if we 3335 // can actually shrink the stack. 3336 FPDiff = NumReusableBytes - NumBytes; 3337 3338 // The stack pointer must be 16-byte aligned at all times it's used for a 3339 // memory operation, which in practice means at *all* times and in 3340 // particular across call boundaries. Therefore our own arguments started at 3341 // a 16-byte aligned SP and the delta applied for the tail call should 3342 // satisfy the same constraint. 3343 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 3344 } 3345 3346 // Adjust the stack pointer for the new arguments... 3347 // These operations are automatically eliminated by the prolog/epilog pass 3348 if (!IsSibCall) 3349 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 3350 3351 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 3352 getPointerTy(DAG.getDataLayout())); 3353 3354 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3355 SmallVector<SDValue, 8> MemOpChains; 3356 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3357 3358 // Walk the register/memloc assignments, inserting copies/loads. 3359 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 3360 ++i, ++realArgIdx) { 3361 CCValAssign &VA = ArgLocs[i]; 3362 SDValue Arg = OutVals[realArgIdx]; 3363 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 3364 3365 // Promote the value if needed. 3366 switch (VA.getLocInfo()) { 3367 default: 3368 llvm_unreachable("Unknown loc info!"); 3369 case CCValAssign::Full: 3370 break; 3371 case CCValAssign::SExt: 3372 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3373 break; 3374 case CCValAssign::ZExt: 3375 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3376 break; 3377 case CCValAssign::AExt: 3378 if (Outs[realArgIdx].ArgVT == MVT::i1) { 3379 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 3380 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3381 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 3382 } 3383 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3384 break; 3385 case CCValAssign::BCvt: 3386 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3387 break; 3388 case CCValAssign::FPExt: 3389 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3390 break; 3391 } 3392 3393 if (VA.isRegLoc()) { 3394 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 3395 Outs[0].VT == MVT::i64) { 3396 assert(VA.getLocVT() == MVT::i64 && 3397 "unexpected calling convention register assignment"); 3398 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 3399 "unexpected use of 'returned'"); 3400 IsThisReturn = true; 3401 } 3402 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3403 } else { 3404 assert(VA.isMemLoc()); 3405 3406 SDValue DstAddr; 3407 MachinePointerInfo DstInfo; 3408 3409 // FIXME: This works on big-endian for composite byvals, which are the 3410 // common case. It should also work for fundamental types too. 3411 uint32_t BEAlign = 0; 3412 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 3413 : VA.getValVT().getSizeInBits(); 3414 OpSize = (OpSize + 7) / 8; 3415 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 3416 !Flags.isInConsecutiveRegs()) { 3417 if (OpSize < 8) 3418 BEAlign = 8 - OpSize; 3419 } 3420 unsigned LocMemOffset = VA.getLocMemOffset(); 3421 int32_t Offset = LocMemOffset + BEAlign; 3422 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3423 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3424 3425 if (IsTailCall) { 3426 Offset = Offset + FPDiff; 3427 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 3428 3429 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3430 DstInfo = 3431 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 3432 3433 // Make sure any stack arguments overlapping with where we're storing 3434 // are loaded before this eventual operation. Otherwise they'll be 3435 // clobbered. 3436 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 3437 } else { 3438 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3439 3440 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3441 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 3442 LocMemOffset); 3443 } 3444 3445 if (Outs[i].Flags.isByVal()) { 3446 SDValue SizeNode = 3447 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 3448 SDValue Cpy = DAG.getMemcpy( 3449 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 3450 /*isVol = */ false, /*AlwaysInline = */ false, 3451 /*isTailCall = */ false, 3452 DstInfo, MachinePointerInfo()); 3453 3454 MemOpChains.push_back(Cpy); 3455 } else { 3456 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 3457 // promoted to a legal register type i32, we should truncate Arg back to 3458 // i1/i8/i16. 3459 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 3460 VA.getValVT() == MVT::i16) 3461 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 3462 3463 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 3464 MemOpChains.push_back(Store); 3465 } 3466 } 3467 } 3468 3469 if (!MemOpChains.empty()) 3470 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3471 3472 // Build a sequence of copy-to-reg nodes chained together with token chain 3473 // and flag operands which copy the outgoing args into the appropriate regs. 3474 SDValue InFlag; 3475 for (auto &RegToPass : RegsToPass) { 3476 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3477 RegToPass.second, InFlag); 3478 InFlag = Chain.getValue(1); 3479 } 3480 3481 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3482 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3483 // node so that legalize doesn't hack it. 3484 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3485 auto GV = G->getGlobal(); 3486 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) == 3487 AArch64II::MO_GOT) { 3488 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); 3489 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3490 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) { 3491 assert(Subtarget->isTargetWindows() && 3492 "Windows is the only supported COFF target"); 3493 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT); 3494 } else { 3495 const GlobalValue *GV = G->getGlobal(); 3496 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3497 } 3498 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3499 if (getTargetMachine().getCodeModel() == CodeModel::Large && 3500 Subtarget->isTargetMachO()) { 3501 const char *Sym = S->getSymbol(); 3502 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 3503 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3504 } else { 3505 const char *Sym = S->getSymbol(); 3506 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 3507 } 3508 } 3509 3510 // We don't usually want to end the call-sequence here because we would tidy 3511 // the frame up *after* the call, however in the ABI-changing tail-call case 3512 // we've carefully laid out the parameters so that when sp is reset they'll be 3513 // in the correct location. 3514 if (IsTailCall && !IsSibCall) { 3515 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3516 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 3517 InFlag = Chain.getValue(1); 3518 } 3519 3520 std::vector<SDValue> Ops; 3521 Ops.push_back(Chain); 3522 Ops.push_back(Callee); 3523 3524 if (IsTailCall) { 3525 // Each tail call may have to adjust the stack by a different amount, so 3526 // this information must travel along with the operation for eventual 3527 // consumption by emitEpilogue. 3528 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3529 } 3530 3531 // Add argument registers to the end of the list so that they are known live 3532 // into the call. 3533 for (auto &RegToPass : RegsToPass) 3534 Ops.push_back(DAG.getRegister(RegToPass.first, 3535 RegToPass.second.getValueType())); 3536 3537 // Add a register mask operand representing the call-preserved registers. 3538 const uint32_t *Mask; 3539 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3540 if (IsThisReturn) { 3541 // For 'this' returns, use the X0-preserving mask if applicable 3542 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 3543 if (!Mask) { 3544 IsThisReturn = false; 3545 Mask = TRI->getCallPreservedMask(MF, CallConv); 3546 } 3547 } else 3548 Mask = TRI->getCallPreservedMask(MF, CallConv); 3549 3550 assert(Mask && "Missing call preserved mask for calling convention"); 3551 Ops.push_back(DAG.getRegisterMask(Mask)); 3552 3553 if (InFlag.getNode()) 3554 Ops.push_back(InFlag); 3555 3556 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3557 3558 // If we're doing a tall call, use a TC_RETURN here rather than an 3559 // actual call instruction. 3560 if (IsTailCall) { 3561 MF.getFrameInfo().setHasTailCall(); 3562 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 3563 } 3564 3565 // Returns a chain and a flag for retval copy to use. 3566 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 3567 InFlag = Chain.getValue(1); 3568 3569 uint64_t CalleePopBytes = 3570 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 3571 3572 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3573 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 3574 InFlag, DL); 3575 if (!Ins.empty()) 3576 InFlag = Chain.getValue(1); 3577 3578 // Handle result values, copying them out of physregs into vregs that we 3579 // return. 3580 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3581 InVals, IsThisReturn, 3582 IsThisReturn ? OutVals[0] : SDValue()); 3583 } 3584 3585 bool AArch64TargetLowering::CanLowerReturn( 3586 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 3587 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3588 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3589 ? RetCC_AArch64_WebKit_JS 3590 : RetCC_AArch64_AAPCS; 3591 SmallVector<CCValAssign, 16> RVLocs; 3592 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 3593 return CCInfo.CheckReturn(Outs, RetCC); 3594 } 3595 3596 SDValue 3597 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3598 bool isVarArg, 3599 const SmallVectorImpl<ISD::OutputArg> &Outs, 3600 const SmallVectorImpl<SDValue> &OutVals, 3601 const SDLoc &DL, SelectionDAG &DAG) const { 3602 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3603 ? RetCC_AArch64_WebKit_JS 3604 : RetCC_AArch64_AAPCS; 3605 SmallVector<CCValAssign, 16> RVLocs; 3606 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3607 *DAG.getContext()); 3608 CCInfo.AnalyzeReturn(Outs, RetCC); 3609 3610 // Copy the result values into the output registers. 3611 SDValue Flag; 3612 SmallVector<SDValue, 4> RetOps(1, Chain); 3613 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 3614 ++i, ++realRVLocIdx) { 3615 CCValAssign &VA = RVLocs[i]; 3616 assert(VA.isRegLoc() && "Can only return in registers!"); 3617 SDValue Arg = OutVals[realRVLocIdx]; 3618 3619 switch (VA.getLocInfo()) { 3620 default: 3621 llvm_unreachable("Unknown loc info!"); 3622 case CCValAssign::Full: 3623 if (Outs[i].ArgVT == MVT::i1) { 3624 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 3625 // value. This is strictly redundant on Darwin (which uses "zeroext 3626 // i1"), but will be optimised out before ISel. 3627 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3628 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3629 } 3630 break; 3631 case CCValAssign::BCvt: 3632 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3633 break; 3634 } 3635 3636 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 3637 Flag = Chain.getValue(1); 3638 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3639 } 3640 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3641 const MCPhysReg *I = 3642 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3643 if (I) { 3644 for (; *I; ++I) { 3645 if (AArch64::GPR64RegClass.contains(*I)) 3646 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 3647 else if (AArch64::FPR64RegClass.contains(*I)) 3648 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3649 else 3650 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3651 } 3652 } 3653 3654 RetOps[0] = Chain; // Update chain. 3655 3656 // Add the flag if we have it. 3657 if (Flag.getNode()) 3658 RetOps.push_back(Flag); 3659 3660 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 3661 } 3662 3663 //===----------------------------------------------------------------------===// 3664 // Other Lowering Code 3665 //===----------------------------------------------------------------------===// 3666 3667 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 3668 SelectionDAG &DAG, 3669 unsigned Flag) const { 3670 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag); 3671 } 3672 3673 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 3674 SelectionDAG &DAG, 3675 unsigned Flag) const { 3676 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 3677 } 3678 3679 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 3680 SelectionDAG &DAG, 3681 unsigned Flag) const { 3682 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), 3683 N->getOffset(), Flag); 3684 } 3685 3686 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 3687 SelectionDAG &DAG, 3688 unsigned Flag) const { 3689 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 3690 } 3691 3692 // (loadGOT sym) 3693 template <class NodeTy> 3694 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, 3695 unsigned Flags) const { 3696 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 3697 SDLoc DL(N); 3698 EVT Ty = getPointerTy(DAG.getDataLayout()); 3699 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); 3700 // FIXME: Once remat is capable of dealing with instructions with register 3701 // operands, expand this into two nodes instead of using a wrapper node. 3702 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 3703 } 3704 3705 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 3706 template <class NodeTy> 3707 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, 3708 unsigned Flags) const { 3709 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 3710 SDLoc DL(N); 3711 EVT Ty = getPointerTy(DAG.getDataLayout()); 3712 const unsigned char MO_NC = AArch64II::MO_NC; 3713 return DAG.getNode( 3714 AArch64ISD::WrapperLarge, DL, Ty, 3715 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), 3716 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), 3717 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), 3718 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); 3719 } 3720 3721 // (addlow (adrp %hi(sym)) %lo(sym)) 3722 template <class NodeTy> 3723 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3724 unsigned Flags) const { 3725 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 3726 SDLoc DL(N); 3727 EVT Ty = getPointerTy(DAG.getDataLayout()); 3728 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); 3729 SDValue Lo = getTargetNode(N, Ty, DAG, 3730 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); 3731 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 3732 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 3733 } 3734 3735 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 3736 SelectionDAG &DAG) const { 3737 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 3738 const GlobalValue *GV = GN->getGlobal(); 3739 const AArch64II::TOF TargetFlags = 3740 (GV->hasDLLImportStorageClass() ? AArch64II::MO_DLLIMPORT 3741 : AArch64II::MO_NO_FLAG); 3742 unsigned char OpFlags = 3743 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 3744 3745 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 3746 "unexpected offset in global node"); 3747 3748 // This also catches the large code model case for Darwin. 3749 if ((OpFlags & AArch64II::MO_GOT) != 0) { 3750 return getGOT(GN, DAG, TargetFlags); 3751 } 3752 3753 SDValue Result; 3754 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 3755 Result = getAddrLarge(GN, DAG, TargetFlags); 3756 } else { 3757 Result = getAddr(GN, DAG, TargetFlags); 3758 } 3759 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3760 SDLoc DL(GN); 3761 if (GV->hasDLLImportStorageClass()) 3762 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3763 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3764 return Result; 3765 } 3766 3767 /// \brief Convert a TLS address reference into the correct sequence of loads 3768 /// and calls to compute the variable's address (for Darwin, currently) and 3769 /// return an SDValue containing the final node. 3770 3771 /// Darwin only has one TLS scheme which must be capable of dealing with the 3772 /// fully general situation, in the worst case. This means: 3773 /// + "extern __thread" declaration. 3774 /// + Defined in a possibly unknown dynamic library. 3775 /// 3776 /// The general system is that each __thread variable has a [3 x i64] descriptor 3777 /// which contains information used by the runtime to calculate the address. The 3778 /// only part of this the compiler needs to know about is the first xword, which 3779 /// contains a function pointer that must be called with the address of the 3780 /// entire descriptor in "x0". 3781 /// 3782 /// Since this descriptor may be in a different unit, in general even the 3783 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 3784 /// is: 3785 /// adrp x0, _var@TLVPPAGE 3786 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 3787 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 3788 /// ; the function pointer 3789 /// blr x1 ; Uses descriptor address in x0 3790 /// ; Address of _var is now in x0. 3791 /// 3792 /// If the address of _var's descriptor *is* known to the linker, then it can 3793 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 3794 /// a slight efficiency gain. 3795 SDValue 3796 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 3797 SelectionDAG &DAG) const { 3798 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 3799 3800 SDLoc DL(Op); 3801 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 3802 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3803 3804 SDValue TLVPAddr = 3805 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3806 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 3807 3808 // The first entry in the descriptor is a function pointer that we must call 3809 // to obtain the address of the variable. 3810 SDValue Chain = DAG.getEntryNode(); 3811 SDValue FuncTLVGet = DAG.getLoad( 3812 MVT::i64, DL, Chain, DescAddr, 3813 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3814 /* Alignment = */ 8, 3815 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant | 3816 MachineMemOperand::MODereferenceable); 3817 Chain = FuncTLVGet.getValue(1); 3818 3819 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 3820 MFI.setAdjustsStack(true); 3821 3822 // TLS calls preserve all registers except those that absolutely must be 3823 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 3824 // silly). 3825 const uint32_t *Mask = 3826 Subtarget->getRegisterInfo()->getTLSCallPreservedMask(); 3827 3828 // Finally, we can make the call. This is just a degenerate version of a 3829 // normal AArch64 call node: x0 takes the address of the descriptor, and 3830 // returns the address of the variable in this thread. 3831 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 3832 Chain = 3833 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3834 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 3835 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3836 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 3837 } 3838 3839 /// When accessing thread-local variables under either the general-dynamic or 3840 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 3841 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 3842 /// is a function pointer to carry out the resolution. 3843 /// 3844 /// The sequence is: 3845 /// adrp x0, :tlsdesc:var 3846 /// ldr x1, [x0, #:tlsdesc_lo12:var] 3847 /// add x0, x0, #:tlsdesc_lo12:var 3848 /// .tlsdesccall var 3849 /// blr x1 3850 /// (TPIDR_EL0 offset now in x0) 3851 /// 3852 /// The above sequence must be produced unscheduled, to enable the linker to 3853 /// optimize/relax this sequence. 3854 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 3855 /// above sequence, and expanded really late in the compilation flow, to ensure 3856 /// the sequence is produced as per above. 3857 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 3858 const SDLoc &DL, 3859 SelectionDAG &DAG) const { 3860 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3861 3862 SDValue Chain = DAG.getEntryNode(); 3863 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3864 3865 Chain = 3866 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 3867 SDValue Glue = Chain.getValue(1); 3868 3869 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 3870 } 3871 3872 SDValue 3873 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 3874 SelectionDAG &DAG) const { 3875 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 3876 assert(Subtarget->useSmallAddressing() && 3877 "ELF TLS only supported in small memory model"); 3878 // Different choices can be made for the maximum size of the TLS area for a 3879 // module. For the small address model, the default TLS size is 16MiB and the 3880 // maximum TLS size is 4GiB. 3881 // FIXME: add -mtls-size command line option and make it control the 16MiB 3882 // vs. 4GiB code sequence generation. 3883 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3884 3885 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 3886 3887 if (DAG.getTarget().Options.EmulatedTLS) 3888 return LowerToTLSEmulatedModel(GA, DAG); 3889 3890 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 3891 if (Model == TLSModel::LocalDynamic) 3892 Model = TLSModel::GeneralDynamic; 3893 } 3894 3895 SDValue TPOff; 3896 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3897 SDLoc DL(Op); 3898 const GlobalValue *GV = GA->getGlobal(); 3899 3900 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 3901 3902 if (Model == TLSModel::LocalExec) { 3903 SDValue HiVar = DAG.getTargetGlobalAddress( 3904 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3905 SDValue LoVar = DAG.getTargetGlobalAddress( 3906 GV, DL, PtrVT, 0, 3907 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3908 3909 SDValue TPWithOff_lo = 3910 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 3911 HiVar, 3912 DAG.getTargetConstant(0, DL, MVT::i32)), 3913 0); 3914 SDValue TPWithOff = 3915 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, 3916 LoVar, 3917 DAG.getTargetConstant(0, DL, MVT::i32)), 3918 0); 3919 return TPWithOff; 3920 } else if (Model == TLSModel::InitialExec) { 3921 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3922 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 3923 } else if (Model == TLSModel::LocalDynamic) { 3924 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 3925 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 3926 // the beginning of the module's TLS region, followed by a DTPREL offset 3927 // calculation. 3928 3929 // These accesses will need deduplicating if there's more than one. 3930 AArch64FunctionInfo *MFI = 3931 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 3932 MFI->incNumLocalDynamicTLSAccesses(); 3933 3934 // The call needs a relocation too for linker relaxation. It doesn't make 3935 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3936 // the address. 3937 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 3938 AArch64II::MO_TLS); 3939 3940 // Now we can calculate the offset from TPIDR_EL0 to this module's 3941 // thread-local area. 3942 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3943 3944 // Now use :dtprel_whatever: operations to calculate this variable's offset 3945 // in its thread-storage area. 3946 SDValue HiVar = DAG.getTargetGlobalAddress( 3947 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3948 SDValue LoVar = DAG.getTargetGlobalAddress( 3949 GV, DL, MVT::i64, 0, 3950 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3951 3952 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 3953 DAG.getTargetConstant(0, DL, MVT::i32)), 3954 0); 3955 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 3956 DAG.getTargetConstant(0, DL, MVT::i32)), 3957 0); 3958 } else if (Model == TLSModel::GeneralDynamic) { 3959 // The call needs a relocation too for linker relaxation. It doesn't make 3960 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3961 // the address. 3962 SDValue SymAddr = 3963 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3964 3965 // Finally we can make a call to calculate the offset from tpidr_el0. 3966 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3967 } else 3968 llvm_unreachable("Unsupported ELF TLS access model"); 3969 3970 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 3971 } 3972 3973 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 3974 SelectionDAG &DAG) const { 3975 if (Subtarget->isTargetDarwin()) 3976 return LowerDarwinGlobalTLSAddress(Op, DAG); 3977 if (Subtarget->isTargetELF()) 3978 return LowerELFGlobalTLSAddress(Op, DAG); 3979 3980 llvm_unreachable("Unexpected platform trying to use TLS"); 3981 } 3982 3983 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3984 SDValue Chain = Op.getOperand(0); 3985 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3986 SDValue LHS = Op.getOperand(2); 3987 SDValue RHS = Op.getOperand(3); 3988 SDValue Dest = Op.getOperand(4); 3989 SDLoc dl(Op); 3990 3991 // Handle f128 first, since lowering it will result in comparing the return 3992 // value of a libcall against zero, which is just what the rest of LowerBR_CC 3993 // is expecting to deal with. 3994 if (LHS.getValueType() == MVT::f128) { 3995 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3996 3997 // If softenSetCCOperands returned a scalar, we need to compare the result 3998 // against zero to select between true and false values. 3999 if (!RHS.getNode()) { 4000 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4001 CC = ISD::SETNE; 4002 } 4003 } 4004 4005 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4006 // instruction. 4007 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS)) { 4008 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 4009 "Unexpected condition code."); 4010 // Only lower legal XALUO ops. 4011 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4012 return SDValue(); 4013 4014 // The actual operation with overflow check. 4015 AArch64CC::CondCode OFCC; 4016 SDValue Value, Overflow; 4017 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 4018 4019 if (CC == ISD::SETNE) 4020 OFCC = getInvertedCondCode(OFCC); 4021 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 4022 4023 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 4024 Overflow); 4025 } 4026 4027 if (LHS.getValueType().isInteger()) { 4028 assert((LHS.getValueType() == RHS.getValueType()) && 4029 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 4030 4031 // If the RHS of the comparison is zero, we can potentially fold this 4032 // to a specialized branch. 4033 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 4034 if (RHSC && RHSC->getZExtValue() == 0) { 4035 if (CC == ISD::SETEQ) { 4036 // See if we can use a TBZ to fold in an AND as well. 4037 // TBZ has a smaller branch displacement than CBZ. If the offset is 4038 // out of bounds, a late MI-layer pass rewrites branches. 4039 // 403.gcc is an example that hits this case. 4040 if (LHS.getOpcode() == ISD::AND && 4041 isa<ConstantSDNode>(LHS.getOperand(1)) && 4042 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 4043 SDValue Test = LHS.getOperand(0); 4044 uint64_t Mask = LHS.getConstantOperandVal(1); 4045 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 4046 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 4047 Dest); 4048 } 4049 4050 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 4051 } else if (CC == ISD::SETNE) { 4052 // See if we can use a TBZ to fold in an AND as well. 4053 // TBZ has a smaller branch displacement than CBZ. If the offset is 4054 // out of bounds, a late MI-layer pass rewrites branches. 4055 // 403.gcc is an example that hits this case. 4056 if (LHS.getOpcode() == ISD::AND && 4057 isa<ConstantSDNode>(LHS.getOperand(1)) && 4058 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 4059 SDValue Test = LHS.getOperand(0); 4060 uint64_t Mask = LHS.getConstantOperandVal(1); 4061 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 4062 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 4063 Dest); 4064 } 4065 4066 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 4067 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 4068 // Don't combine AND since emitComparison converts the AND to an ANDS 4069 // (a.k.a. TST) and the test in the test bit and branch instruction 4070 // becomes redundant. This would also increase register pressure. 4071 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4072 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 4073 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4074 } 4075 } 4076 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 4077 LHS.getOpcode() != ISD::AND) { 4078 // Don't combine AND since emitComparison converts the AND to an ANDS 4079 // (a.k.a. TST) and the test in the test bit and branch instruction 4080 // becomes redundant. This would also increase register pressure. 4081 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4082 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 4083 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4084 } 4085 4086 SDValue CCVal; 4087 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4088 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 4089 Cmp); 4090 } 4091 4092 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4093 LHS.getValueType() == MVT::f64); 4094 4095 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4096 // clean. Some of them require two branches to implement. 4097 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4098 AArch64CC::CondCode CC1, CC2; 4099 changeFPCCToAArch64CC(CC, CC1, CC2); 4100 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4101 SDValue BR1 = 4102 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 4103 if (CC2 != AArch64CC::AL) { 4104 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4105 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 4106 Cmp); 4107 } 4108 4109 return BR1; 4110 } 4111 4112 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 4113 SelectionDAG &DAG) const { 4114 EVT VT = Op.getValueType(); 4115 SDLoc DL(Op); 4116 4117 SDValue In1 = Op.getOperand(0); 4118 SDValue In2 = Op.getOperand(1); 4119 EVT SrcVT = In2.getValueType(); 4120 4121 if (SrcVT.bitsLT(VT)) 4122 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 4123 else if (SrcVT.bitsGT(VT)) 4124 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 4125 4126 EVT VecVT; 4127 uint64_t EltMask; 4128 SDValue VecVal1, VecVal2; 4129 4130 auto setVecVal = [&] (int Idx) { 4131 if (!VT.isVector()) { 4132 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 4133 DAG.getUNDEF(VecVT), In1); 4134 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 4135 DAG.getUNDEF(VecVT), In2); 4136 } else { 4137 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 4138 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 4139 } 4140 }; 4141 4142 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 4143 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 4144 EltMask = 0x80000000ULL; 4145 setVecVal(AArch64::ssub); 4146 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 4147 VecVT = MVT::v2i64; 4148 4149 // We want to materialize a mask with the high bit set, but the AdvSIMD 4150 // immediate moves cannot materialize that in a single instruction for 4151 // 64-bit elements. Instead, materialize zero and then negate it. 4152 EltMask = 0; 4153 4154 setVecVal(AArch64::dsub); 4155 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 4156 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 4157 EltMask = 0x8000ULL; 4158 setVecVal(AArch64::hsub); 4159 } else { 4160 llvm_unreachable("Invalid type for copysign!"); 4161 } 4162 4163 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 4164 4165 // If we couldn't materialize the mask above, then the mask vector will be 4166 // the zero vector, and we need to negate it here. 4167 if (VT == MVT::f64 || VT == MVT::v2f64) { 4168 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 4169 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 4170 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 4171 } 4172 4173 SDValue Sel = 4174 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 4175 4176 if (VT == MVT::f16) 4177 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 4178 if (VT == MVT::f32) 4179 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 4180 else if (VT == MVT::f64) 4181 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 4182 else 4183 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 4184 } 4185 4186 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 4187 if (DAG.getMachineFunction().getFunction()->hasFnAttribute( 4188 Attribute::NoImplicitFloat)) 4189 return SDValue(); 4190 4191 if (!Subtarget->hasNEON()) 4192 return SDValue(); 4193 4194 // While there is no integer popcount instruction, it can 4195 // be more efficiently lowered to the following sequence that uses 4196 // AdvSIMD registers/instructions as long as the copies to/from 4197 // the AdvSIMD registers are cheap. 4198 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 4199 // CNT V0.8B, V0.8B // 8xbyte pop-counts 4200 // ADDV B0, V0.8B // sum 8xbyte pop-counts 4201 // UMOV X0, V0.B[0] // copy byte result back to integer reg 4202 SDValue Val = Op.getOperand(0); 4203 SDLoc DL(Op); 4204 EVT VT = Op.getValueType(); 4205 4206 if (VT == MVT::i32) 4207 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 4208 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 4209 4210 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 4211 SDValue UaddLV = DAG.getNode( 4212 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 4213 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 4214 4215 if (VT == MVT::i64) 4216 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 4217 return UaddLV; 4218 } 4219 4220 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 4221 4222 if (Op.getValueType().isVector()) 4223 return LowerVSETCC(Op, DAG); 4224 4225 SDValue LHS = Op.getOperand(0); 4226 SDValue RHS = Op.getOperand(1); 4227 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 4228 SDLoc dl(Op); 4229 4230 // We chose ZeroOrOneBooleanContents, so use zero and one. 4231 EVT VT = Op.getValueType(); 4232 SDValue TVal = DAG.getConstant(1, dl, VT); 4233 SDValue FVal = DAG.getConstant(0, dl, VT); 4234 4235 // Handle f128 first, since one possible outcome is a normal integer 4236 // comparison which gets picked up by the next if statement. 4237 if (LHS.getValueType() == MVT::f128) { 4238 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4239 4240 // If softenSetCCOperands returned a scalar, use it. 4241 if (!RHS.getNode()) { 4242 assert(LHS.getValueType() == Op.getValueType() && 4243 "Unexpected setcc expansion!"); 4244 return LHS; 4245 } 4246 } 4247 4248 if (LHS.getValueType().isInteger()) { 4249 SDValue CCVal; 4250 SDValue Cmp = 4251 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); 4252 4253 // Note that we inverted the condition above, so we reverse the order of 4254 // the true and false operands here. This will allow the setcc to be 4255 // matched to a single CSINC instruction. 4256 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 4257 } 4258 4259 // Now we know we're dealing with FP values. 4260 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4261 LHS.getValueType() == MVT::f64); 4262 4263 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 4264 // and do the comparison. 4265 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4266 4267 AArch64CC::CondCode CC1, CC2; 4268 changeFPCCToAArch64CC(CC, CC1, CC2); 4269 if (CC2 == AArch64CC::AL) { 4270 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); 4271 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4272 4273 // Note that we inverted the condition above, so we reverse the order of 4274 // the true and false operands here. This will allow the setcc to be 4275 // matched to a single CSINC instruction. 4276 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 4277 } else { 4278 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 4279 // totally clean. Some of them require two CSELs to implement. As is in 4280 // this case, we emit the first CSEL and then emit a second using the output 4281 // of the first as the RHS. We're effectively OR'ing the two CC's together. 4282 4283 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 4284 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4285 SDValue CS1 = 4286 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4287 4288 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4289 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4290 } 4291 } 4292 4293 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 4294 SDValue RHS, SDValue TVal, 4295 SDValue FVal, const SDLoc &dl, 4296 SelectionDAG &DAG) const { 4297 // Handle f128 first, because it will result in a comparison of some RTLIB 4298 // call result against zero. 4299 if (LHS.getValueType() == MVT::f128) { 4300 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4301 4302 // If softenSetCCOperands returned a scalar, we need to compare the result 4303 // against zero to select between true and false values. 4304 if (!RHS.getNode()) { 4305 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4306 CC = ISD::SETNE; 4307 } 4308 } 4309 4310 // Also handle f16, for which we need to do a f32 comparison. 4311 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 4312 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 4313 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 4314 } 4315 4316 // Next, handle integers. 4317 if (LHS.getValueType().isInteger()) { 4318 assert((LHS.getValueType() == RHS.getValueType()) && 4319 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 4320 4321 unsigned Opcode = AArch64ISD::CSEL; 4322 4323 // If both the TVal and the FVal are constants, see if we can swap them in 4324 // order to for a CSINV or CSINC out of them. 4325 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 4326 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 4327 4328 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 4329 std::swap(TVal, FVal); 4330 std::swap(CTVal, CFVal); 4331 CC = ISD::getSetCCInverse(CC, true); 4332 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 4333 std::swap(TVal, FVal); 4334 std::swap(CTVal, CFVal); 4335 CC = ISD::getSetCCInverse(CC, true); 4336 } else if (TVal.getOpcode() == ISD::XOR) { 4337 // If TVal is a NOT we want to swap TVal and FVal so that we can match 4338 // with a CSINV rather than a CSEL. 4339 if (isAllOnesConstant(TVal.getOperand(1))) { 4340 std::swap(TVal, FVal); 4341 std::swap(CTVal, CFVal); 4342 CC = ISD::getSetCCInverse(CC, true); 4343 } 4344 } else if (TVal.getOpcode() == ISD::SUB) { 4345 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 4346 // that we can match with a CSNEG rather than a CSEL. 4347 if (isNullConstant(TVal.getOperand(0))) { 4348 std::swap(TVal, FVal); 4349 std::swap(CTVal, CFVal); 4350 CC = ISD::getSetCCInverse(CC, true); 4351 } 4352 } else if (CTVal && CFVal) { 4353 const int64_t TrueVal = CTVal->getSExtValue(); 4354 const int64_t FalseVal = CFVal->getSExtValue(); 4355 bool Swap = false; 4356 4357 // If both TVal and FVal are constants, see if FVal is the 4358 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 4359 // instead of a CSEL in that case. 4360 if (TrueVal == ~FalseVal) { 4361 Opcode = AArch64ISD::CSINV; 4362 } else if (TrueVal == -FalseVal) { 4363 Opcode = AArch64ISD::CSNEG; 4364 } else if (TVal.getValueType() == MVT::i32) { 4365 // If our operands are only 32-bit wide, make sure we use 32-bit 4366 // arithmetic for the check whether we can use CSINC. This ensures that 4367 // the addition in the check will wrap around properly in case there is 4368 // an overflow (which would not be the case if we do the check with 4369 // 64-bit arithmetic). 4370 const uint32_t TrueVal32 = CTVal->getZExtValue(); 4371 const uint32_t FalseVal32 = CFVal->getZExtValue(); 4372 4373 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 4374 Opcode = AArch64ISD::CSINC; 4375 4376 if (TrueVal32 > FalseVal32) { 4377 Swap = true; 4378 } 4379 } 4380 // 64-bit check whether we can use CSINC. 4381 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 4382 Opcode = AArch64ISD::CSINC; 4383 4384 if (TrueVal > FalseVal) { 4385 Swap = true; 4386 } 4387 } 4388 4389 // Swap TVal and FVal if necessary. 4390 if (Swap) { 4391 std::swap(TVal, FVal); 4392 std::swap(CTVal, CFVal); 4393 CC = ISD::getSetCCInverse(CC, true); 4394 } 4395 4396 if (Opcode != AArch64ISD::CSEL) { 4397 // Drop FVal since we can get its value by simply inverting/negating 4398 // TVal. 4399 FVal = TVal; 4400 } 4401 } 4402 4403 // Avoid materializing a constant when possible by reusing a known value in 4404 // a register. However, don't perform this optimization if the known value 4405 // is one, zero or negative one in the case of a CSEL. We can always 4406 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 4407 // FVal, respectively. 4408 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 4409 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 4410 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 4411 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4412 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 4413 // "a != C ? x : a" to avoid materializing C. 4414 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 4415 TVal = LHS; 4416 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 4417 FVal = LHS; 4418 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 4419 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 4420 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 4421 // avoid materializing C. 4422 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4423 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 4424 Opcode = AArch64ISD::CSINV; 4425 TVal = LHS; 4426 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 4427 } 4428 } 4429 4430 SDValue CCVal; 4431 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4432 EVT VT = TVal.getValueType(); 4433 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 4434 } 4435 4436 // Now we know we're dealing with FP values. 4437 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4438 LHS.getValueType() == MVT::f64); 4439 assert(LHS.getValueType() == RHS.getValueType()); 4440 EVT VT = TVal.getValueType(); 4441 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4442 4443 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4444 // clean. Some of them require two CSELs to implement. 4445 AArch64CC::CondCode CC1, CC2; 4446 changeFPCCToAArch64CC(CC, CC1, CC2); 4447 4448 if (DAG.getTarget().Options.UnsafeFPMath) { 4449 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 4450 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 4451 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 4452 if (RHSVal && RHSVal->isZero()) { 4453 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 4454 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 4455 4456 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 4457 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 4458 TVal = LHS; 4459 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 4460 CFVal && CFVal->isZero() && 4461 FVal.getValueType() == LHS.getValueType()) 4462 FVal = LHS; 4463 } 4464 } 4465 4466 // Emit first, and possibly only, CSEL. 4467 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4468 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4469 4470 // If we need a second CSEL, emit it, using the output of the first as the 4471 // RHS. We're effectively OR'ing the two CC's together. 4472 if (CC2 != AArch64CC::AL) { 4473 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4474 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4475 } 4476 4477 // Otherwise, return the output of the first CSEL. 4478 return CS1; 4479 } 4480 4481 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 4482 SelectionDAG &DAG) const { 4483 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4484 SDValue LHS = Op.getOperand(0); 4485 SDValue RHS = Op.getOperand(1); 4486 SDValue TVal = Op.getOperand(2); 4487 SDValue FVal = Op.getOperand(3); 4488 SDLoc DL(Op); 4489 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4490 } 4491 4492 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 4493 SelectionDAG &DAG) const { 4494 SDValue CCVal = Op->getOperand(0); 4495 SDValue TVal = Op->getOperand(1); 4496 SDValue FVal = Op->getOperand(2); 4497 SDLoc DL(Op); 4498 4499 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 4500 // instruction. 4501 if (isOverflowIntrOpRes(CCVal)) { 4502 // Only lower legal XALUO ops. 4503 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 4504 return SDValue(); 4505 4506 AArch64CC::CondCode OFCC; 4507 SDValue Value, Overflow; 4508 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 4509 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 4510 4511 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 4512 CCVal, Overflow); 4513 } 4514 4515 // Lower it the same way as we would lower a SELECT_CC node. 4516 ISD::CondCode CC; 4517 SDValue LHS, RHS; 4518 if (CCVal.getOpcode() == ISD::SETCC) { 4519 LHS = CCVal.getOperand(0); 4520 RHS = CCVal.getOperand(1); 4521 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 4522 } else { 4523 LHS = CCVal; 4524 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 4525 CC = ISD::SETNE; 4526 } 4527 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4528 } 4529 4530 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 4531 SelectionDAG &DAG) const { 4532 // Jump table entries as PC relative offsets. No additional tweaking 4533 // is necessary here. Just get the address of the jump table. 4534 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 4535 4536 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4537 !Subtarget->isTargetMachO()) { 4538 return getAddrLarge(JT, DAG); 4539 } 4540 return getAddr(JT, DAG); 4541 } 4542 4543 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 4544 SelectionDAG &DAG) const { 4545 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 4546 4547 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4548 // Use the GOT for the large code model on iOS. 4549 if (Subtarget->isTargetMachO()) { 4550 return getGOT(CP, DAG); 4551 } 4552 return getAddrLarge(CP, DAG); 4553 } else { 4554 return getAddr(CP, DAG); 4555 } 4556 } 4557 4558 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 4559 SelectionDAG &DAG) const { 4560 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 4561 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4562 !Subtarget->isTargetMachO()) { 4563 return getAddrLarge(BA, DAG); 4564 } else { 4565 return getAddr(BA, DAG); 4566 } 4567 } 4568 4569 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 4570 SelectionDAG &DAG) const { 4571 AArch64FunctionInfo *FuncInfo = 4572 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4573 4574 SDLoc DL(Op); 4575 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 4576 getPointerTy(DAG.getDataLayout())); 4577 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4578 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4579 MachinePointerInfo(SV)); 4580 } 4581 4582 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 4583 SelectionDAG &DAG) const { 4584 AArch64FunctionInfo *FuncInfo = 4585 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4586 4587 SDLoc DL(Op); 4588 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 4589 ? FuncInfo->getVarArgsGPRIndex() 4590 : FuncInfo->getVarArgsStackIndex(), 4591 getPointerTy(DAG.getDataLayout())); 4592 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4593 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4594 MachinePointerInfo(SV)); 4595 } 4596 4597 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 4598 SelectionDAG &DAG) const { 4599 // The layout of the va_list struct is specified in the AArch64 Procedure Call 4600 // Standard, section B.3. 4601 MachineFunction &MF = DAG.getMachineFunction(); 4602 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4603 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4604 SDLoc DL(Op); 4605 4606 SDValue Chain = Op.getOperand(0); 4607 SDValue VAList = Op.getOperand(1); 4608 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4609 SmallVector<SDValue, 4> MemOps; 4610 4611 // void *__stack at offset 0 4612 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 4613 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 4614 MachinePointerInfo(SV), /* Alignment = */ 8)); 4615 4616 // void *__gr_top at offset 8 4617 int GPRSize = FuncInfo->getVarArgsGPRSize(); 4618 if (GPRSize > 0) { 4619 SDValue GRTop, GRTopAddr; 4620 4621 GRTopAddr = 4622 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 4623 4624 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 4625 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 4626 DAG.getConstant(GPRSize, DL, PtrVT)); 4627 4628 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 4629 MachinePointerInfo(SV, 8), 4630 /* Alignment = */ 8)); 4631 } 4632 4633 // void *__vr_top at offset 16 4634 int FPRSize = FuncInfo->getVarArgsFPRSize(); 4635 if (FPRSize > 0) { 4636 SDValue VRTop, VRTopAddr; 4637 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4638 DAG.getConstant(16, DL, PtrVT)); 4639 4640 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 4641 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 4642 DAG.getConstant(FPRSize, DL, PtrVT)); 4643 4644 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 4645 MachinePointerInfo(SV, 16), 4646 /* Alignment = */ 8)); 4647 } 4648 4649 // int __gr_offs at offset 24 4650 SDValue GROffsAddr = 4651 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 4652 MemOps.push_back(DAG.getStore( 4653 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, 4654 MachinePointerInfo(SV, 24), /* Alignment = */ 4)); 4655 4656 // int __vr_offs at offset 28 4657 SDValue VROffsAddr = 4658 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 4659 MemOps.push_back(DAG.getStore( 4660 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, 4661 MachinePointerInfo(SV, 28), /* Alignment = */ 4)); 4662 4663 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 4664 } 4665 4666 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 4667 SelectionDAG &DAG) const { 4668 MachineFunction &MF = DAG.getMachineFunction(); 4669 4670 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) 4671 return LowerWin64_VASTART(Op, DAG); 4672 else if (Subtarget->isTargetDarwin()) 4673 return LowerDarwin_VASTART(Op, DAG); 4674 else 4675 return LowerAAPCS_VASTART(Op, DAG); 4676 } 4677 4678 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 4679 SelectionDAG &DAG) const { 4680 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 4681 // pointer. 4682 SDLoc DL(Op); 4683 unsigned VaListSize = 4684 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32; 4685 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 4686 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 4687 4688 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), 4689 Op.getOperand(2), 4690 DAG.getConstant(VaListSize, DL, MVT::i32), 4691 8, false, false, false, MachinePointerInfo(DestSV), 4692 MachinePointerInfo(SrcSV)); 4693 } 4694 4695 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 4696 assert(Subtarget->isTargetDarwin() && 4697 "automatic va_arg instruction only works on Darwin"); 4698 4699 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4700 EVT VT = Op.getValueType(); 4701 SDLoc DL(Op); 4702 SDValue Chain = Op.getOperand(0); 4703 SDValue Addr = Op.getOperand(1); 4704 unsigned Align = Op.getConstantOperandVal(3); 4705 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4706 4707 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V)); 4708 Chain = VAList.getValue(1); 4709 4710 if (Align > 8) { 4711 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 4712 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4713 DAG.getConstant(Align - 1, DL, PtrVT)); 4714 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 4715 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 4716 } 4717 4718 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 4719 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 4720 4721 // Scalar integer and FP values smaller than 64 bits are implicitly extended 4722 // up to 64 bits. At the very least, we have to increase the striding of the 4723 // vaargs list to match this, and for FP values we need to introduce 4724 // FP_ROUND nodes as well. 4725 if (VT.isInteger() && !VT.isVector()) 4726 ArgSize = 8; 4727 bool NeedFPTrunc = false; 4728 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 4729 ArgSize = 8; 4730 NeedFPTrunc = true; 4731 } 4732 4733 // Increment the pointer, VAList, to the next vaarg 4734 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4735 DAG.getConstant(ArgSize, DL, PtrVT)); 4736 // Store the incremented VAList to the legalized pointer 4737 SDValue APStore = 4738 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 4739 4740 // Load the actual argument out of the pointer VAList 4741 if (NeedFPTrunc) { 4742 // Load the value as an f64. 4743 SDValue WideFP = 4744 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 4745 // Round the value down to an f32. 4746 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 4747 DAG.getIntPtrConstant(1, DL)); 4748 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 4749 // Merge the rounded value with the chain output of the load. 4750 return DAG.getMergeValues(Ops, DL); 4751 } 4752 4753 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 4754 } 4755 4756 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 4757 SelectionDAG &DAG) const { 4758 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4759 MFI.setFrameAddressIsTaken(true); 4760 4761 EVT VT = Op.getValueType(); 4762 SDLoc DL(Op); 4763 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4764 SDValue FrameAddr = 4765 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 4766 while (Depth--) 4767 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 4768 MachinePointerInfo()); 4769 return FrameAddr; 4770 } 4771 4772 // FIXME? Maybe this could be a TableGen attribute on some registers and 4773 // this table could be generated automatically from RegInfo. 4774 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, 4775 SelectionDAG &DAG) const { 4776 unsigned Reg = StringSwitch<unsigned>(RegName) 4777 .Case("sp", AArch64::SP) 4778 .Case("x18", AArch64::X18) 4779 .Case("w18", AArch64::W18) 4780 .Default(0); 4781 if ((Reg == AArch64::X18 || Reg == AArch64::W18) && 4782 !Subtarget->isX18Reserved()) 4783 Reg = 0; 4784 if (Reg) 4785 return Reg; 4786 report_fatal_error(Twine("Invalid register name \"" 4787 + StringRef(RegName) + "\".")); 4788 } 4789 4790 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 4791 SelectionDAG &DAG) const { 4792 MachineFunction &MF = DAG.getMachineFunction(); 4793 MachineFrameInfo &MFI = MF.getFrameInfo(); 4794 MFI.setReturnAddressIsTaken(true); 4795 4796 EVT VT = Op.getValueType(); 4797 SDLoc DL(Op); 4798 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4799 if (Depth) { 4800 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4801 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 4802 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4803 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4804 MachinePointerInfo()); 4805 } 4806 4807 // Return LR, which contains the return address. Mark it an implicit live-in. 4808 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 4809 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4810 } 4811 4812 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4813 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4814 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 4815 SelectionDAG &DAG) const { 4816 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4817 EVT VT = Op.getValueType(); 4818 unsigned VTBits = VT.getSizeInBits(); 4819 SDLoc dl(Op); 4820 SDValue ShOpLo = Op.getOperand(0); 4821 SDValue ShOpHi = Op.getOperand(1); 4822 SDValue ShAmt = Op.getOperand(2); 4823 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4824 4825 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4826 4827 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4828 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4829 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4830 4831 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 4832 // is "undef". We wanted 0, so CSEL it directly. 4833 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4834 ISD::SETEQ, dl, DAG); 4835 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4836 HiBitsForLo = 4837 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4838 HiBitsForLo, CCVal, Cmp); 4839 4840 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4841 DAG.getConstant(VTBits, dl, MVT::i64)); 4842 4843 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4844 SDValue LoForNormalShift = 4845 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 4846 4847 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4848 dl, DAG); 4849 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4850 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4851 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4852 LoForNormalShift, CCVal, Cmp); 4853 4854 // AArch64 shifts larger than the register width are wrapped rather than 4855 // clamped, so we can't just emit "hi >> x". 4856 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4857 SDValue HiForBigShift = 4858 Opc == ISD::SRA 4859 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4860 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 4861 : DAG.getConstant(0, dl, VT); 4862 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4863 HiForNormalShift, CCVal, Cmp); 4864 4865 SDValue Ops[2] = { Lo, Hi }; 4866 return DAG.getMergeValues(Ops, dl); 4867 } 4868 4869 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4870 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4871 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 4872 SelectionDAG &DAG) const { 4873 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4874 EVT VT = Op.getValueType(); 4875 unsigned VTBits = VT.getSizeInBits(); 4876 SDLoc dl(Op); 4877 SDValue ShOpLo = Op.getOperand(0); 4878 SDValue ShOpHi = Op.getOperand(1); 4879 SDValue ShAmt = Op.getOperand(2); 4880 4881 assert(Op.getOpcode() == ISD::SHL_PARTS); 4882 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4883 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4884 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4885 4886 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 4887 // is "undef". We wanted 0, so CSEL it directly. 4888 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4889 ISD::SETEQ, dl, DAG); 4890 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4891 LoBitsForHi = 4892 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4893 LoBitsForHi, CCVal, Cmp); 4894 4895 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4896 DAG.getConstant(VTBits, dl, MVT::i64)); 4897 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4898 SDValue HiForNormalShift = 4899 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 4900 4901 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4902 4903 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4904 dl, DAG); 4905 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4906 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4907 HiForNormalShift, CCVal, Cmp); 4908 4909 // AArch64 shifts of larger than register sizes are wrapped rather than 4910 // clamped, so we can't just emit "lo << a" if a is too big. 4911 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 4912 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4913 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4914 LoForNormalShift, CCVal, Cmp); 4915 4916 SDValue Ops[2] = { Lo, Hi }; 4917 return DAG.getMergeValues(Ops, dl); 4918 } 4919 4920 bool AArch64TargetLowering::isOffsetFoldingLegal( 4921 const GlobalAddressSDNode *GA) const { 4922 DEBUG(dbgs() << "Skipping offset folding global address: "); 4923 DEBUG(GA->dump()); 4924 DEBUG(dbgs() << "AArch64 doesn't support folding offsets into global " 4925 "addresses\n"); 4926 return false; 4927 } 4928 4929 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 4930 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases. 4931 // FIXME: We should be able to handle f128 as well with a clever lowering. 4932 if (Imm.isPosZero() && (VT == MVT::f16 || VT == MVT::f64 || VT == MVT::f32)) { 4933 DEBUG(dbgs() << "Legal fp imm: materialize 0 using the zero register\n"); 4934 return true; 4935 } 4936 4937 StringRef FPType; 4938 bool IsLegal = false; 4939 SmallString<128> ImmStrVal; 4940 Imm.toString(ImmStrVal); 4941 4942 if (VT == MVT::f64) { 4943 FPType = "f64"; 4944 IsLegal = AArch64_AM::getFP64Imm(Imm) != -1; 4945 } else if (VT == MVT::f32) { 4946 FPType = "f32"; 4947 IsLegal = AArch64_AM::getFP32Imm(Imm) != -1; 4948 } else if (VT == MVT::f16 && Subtarget->hasFullFP16()) { 4949 FPType = "f16"; 4950 IsLegal = AArch64_AM::getFP16Imm(Imm) != -1; 4951 } 4952 4953 if (IsLegal) { 4954 DEBUG(dbgs() << "Legal " << FPType << " imm value: " << ImmStrVal << "\n"); 4955 return true; 4956 } 4957 4958 if (!FPType.empty()) 4959 DEBUG(dbgs() << "Illegal " << FPType << " imm value: " << ImmStrVal << "\n"); 4960 else 4961 DEBUG(dbgs() << "Illegal fp imm " << ImmStrVal << ": unsupported fp type\n"); 4962 4963 return false; 4964 } 4965 4966 //===----------------------------------------------------------------------===// 4967 // AArch64 Optimization Hooks 4968 //===----------------------------------------------------------------------===// 4969 4970 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 4971 SDValue Operand, SelectionDAG &DAG, 4972 int &ExtraSteps) { 4973 EVT VT = Operand.getValueType(); 4974 if (ST->hasNEON() && 4975 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 4976 VT == MVT::f32 || VT == MVT::v1f32 || 4977 VT == MVT::v2f32 || VT == MVT::v4f32)) { 4978 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 4979 // For the reciprocal estimates, convergence is quadratic, so the number 4980 // of digits is doubled after each iteration. In ARMv8, the accuracy of 4981 // the initial estimate is 2^-8. Thus the number of extra steps to refine 4982 // the result for float (23 mantissa bits) is 2 and for double (52 4983 // mantissa bits) is 3. 4984 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; 4985 4986 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 4987 } 4988 4989 return SDValue(); 4990 } 4991 4992 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 4993 SelectionDAG &DAG, int Enabled, 4994 int &ExtraSteps, 4995 bool &UseOneConst, 4996 bool Reciprocal) const { 4997 if (Enabled == ReciprocalEstimate::Enabled || 4998 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 4999 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, 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 square root iteration: E * 0.5 * (3 - X * E^2) 5008 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 5009 for (int i = ExtraSteps; i > 0; --i) { 5010 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 5011 Flags); 5012 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 5013 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 5014 } 5015 5016 if (!Reciprocal) { 5017 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 5018 VT); 5019 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 5020 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); 5021 5022 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 5023 // Correct the result if the operand is 0.0. 5024 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, 5025 VT, Eq, Operand, Estimate); 5026 } 5027 5028 ExtraSteps = 0; 5029 return Estimate; 5030 } 5031 5032 return SDValue(); 5033 } 5034 5035 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 5036 SelectionDAG &DAG, int Enabled, 5037 int &ExtraSteps) const { 5038 if (Enabled == ReciprocalEstimate::Enabled) 5039 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 5040 DAG, ExtraSteps)) { 5041 SDLoc DL(Operand); 5042 EVT VT = Operand.getValueType(); 5043 5044 SDNodeFlags Flags; 5045 Flags.setUnsafeAlgebra(true); 5046 5047 // Newton reciprocal iteration: E * (2 - X * E) 5048 // AArch64 reciprocal iteration instruction: (2 - M * N) 5049 for (int i = ExtraSteps; i > 0; --i) { 5050 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 5051 Estimate, Flags); 5052 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 5053 } 5054 5055 ExtraSteps = 0; 5056 return Estimate; 5057 } 5058 5059 return SDValue(); 5060 } 5061 5062 //===----------------------------------------------------------------------===// 5063 // AArch64 Inline Assembly Support 5064 //===----------------------------------------------------------------------===// 5065 5066 // Table of Constraints 5067 // TODO: This is the current set of constraints supported by ARM for the 5068 // compiler, not all of them may make sense, e.g. S may be difficult to support. 5069 // 5070 // r - A general register 5071 // w - An FP/SIMD register of some size in the range v0-v31 5072 // x - An FP/SIMD register of some size in the range v0-v15 5073 // I - Constant that can be used with an ADD instruction 5074 // J - Constant that can be used with a SUB instruction 5075 // K - Constant that can be used with a 32-bit logical instruction 5076 // L - Constant that can be used with a 64-bit logical instruction 5077 // M - Constant that can be used as a 32-bit MOV immediate 5078 // N - Constant that can be used as a 64-bit MOV immediate 5079 // Q - A memory reference with base register and no offset 5080 // S - A symbolic address 5081 // Y - Floating point constant zero 5082 // Z - Integer constant zero 5083 // 5084 // Note that general register operands will be output using their 64-bit x 5085 // register name, whatever the size of the variable, unless the asm operand 5086 // is prefixed by the %w modifier. Floating-point and SIMD register operands 5087 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 5088 // %q modifier. 5089 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5090 // At this point, we have to lower this constraint to something else, so we 5091 // lower it to an "r" or "w". However, by doing this we will force the result 5092 // to be in register, while the X constraint is much more permissive. 5093 // 5094 // Although we are correct (we are free to emit anything, without 5095 // constraints), we might break use cases that would expect us to be more 5096 // efficient and emit something else. 5097 if (!Subtarget->hasFPARMv8()) 5098 return "r"; 5099 5100 if (ConstraintVT.isFloatingPoint()) 5101 return "w"; 5102 5103 if (ConstraintVT.isVector() && 5104 (ConstraintVT.getSizeInBits() == 64 || 5105 ConstraintVT.getSizeInBits() == 128)) 5106 return "w"; 5107 5108 return "r"; 5109 } 5110 5111 /// getConstraintType - Given a constraint letter, return the type of 5112 /// constraint it is for this target. 5113 AArch64TargetLowering::ConstraintType 5114 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 5115 if (Constraint.size() == 1) { 5116 switch (Constraint[0]) { 5117 default: 5118 break; 5119 case 'z': 5120 return C_Other; 5121 case 'x': 5122 case 'w': 5123 return C_RegisterClass; 5124 // An address with a single base register. Due to the way we 5125 // currently handle addresses it is the same as 'r'. 5126 case 'Q': 5127 return C_Memory; 5128 } 5129 } 5130 return TargetLowering::getConstraintType(Constraint); 5131 } 5132 5133 /// Examine constraint type and operand type and determine a weight value. 5134 /// This object must already have been set up with the operand type 5135 /// and the current alternative constraint selected. 5136 TargetLowering::ConstraintWeight 5137 AArch64TargetLowering::getSingleConstraintMatchWeight( 5138 AsmOperandInfo &info, const char *constraint) const { 5139 ConstraintWeight weight = CW_Invalid; 5140 Value *CallOperandVal = info.CallOperandVal; 5141 // If we don't have a value, we can't do a match, 5142 // but allow it at the lowest weight. 5143 if (!CallOperandVal) 5144 return CW_Default; 5145 Type *type = CallOperandVal->getType(); 5146 // Look at the constraint type. 5147 switch (*constraint) { 5148 default: 5149 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 5150 break; 5151 case 'x': 5152 case 'w': 5153 if (type->isFloatingPointTy() || type->isVectorTy()) 5154 weight = CW_Register; 5155 break; 5156 case 'z': 5157 weight = CW_Constant; 5158 break; 5159 } 5160 return weight; 5161 } 5162 5163 std::pair<unsigned, const TargetRegisterClass *> 5164 AArch64TargetLowering::getRegForInlineAsmConstraint( 5165 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 5166 if (Constraint.size() == 1) { 5167 switch (Constraint[0]) { 5168 case 'r': 5169 if (VT.getSizeInBits() == 64) 5170 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 5171 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 5172 case 'w': 5173 if (VT.getSizeInBits() == 16) 5174 return std::make_pair(0U, &AArch64::FPR16RegClass); 5175 if (VT.getSizeInBits() == 32) 5176 return std::make_pair(0U, &AArch64::FPR32RegClass); 5177 if (VT.getSizeInBits() == 64) 5178 return std::make_pair(0U, &AArch64::FPR64RegClass); 5179 if (VT.getSizeInBits() == 128) 5180 return std::make_pair(0U, &AArch64::FPR128RegClass); 5181 break; 5182 // The instructions that this constraint is designed for can 5183 // only take 128-bit registers so just use that regclass. 5184 case 'x': 5185 if (VT.getSizeInBits() == 128) 5186 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 5187 break; 5188 } 5189 } 5190 if (StringRef("{cc}").equals_lower(Constraint)) 5191 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 5192 5193 // Use the default implementation in TargetLowering to convert the register 5194 // constraint into a member of a register class. 5195 std::pair<unsigned, const TargetRegisterClass *> Res; 5196 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 5197 5198 // Not found as a standard register? 5199 if (!Res.second) { 5200 unsigned Size = Constraint.size(); 5201 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 5202 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 5203 int RegNo; 5204 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 5205 if (!Failed && RegNo >= 0 && RegNo <= 31) { 5206 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 5207 // By default we'll emit v0-v31 for this unless there's a modifier where 5208 // we'll emit the correct register as well. 5209 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 5210 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 5211 Res.second = &AArch64::FPR64RegClass; 5212 } else { 5213 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 5214 Res.second = &AArch64::FPR128RegClass; 5215 } 5216 } 5217 } 5218 } 5219 5220 return Res; 5221 } 5222 5223 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 5224 /// vector. If it is invalid, don't add anything to Ops. 5225 void AArch64TargetLowering::LowerAsmOperandForConstraint( 5226 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 5227 SelectionDAG &DAG) const { 5228 SDValue Result; 5229 5230 // Currently only support length 1 constraints. 5231 if (Constraint.length() != 1) 5232 return; 5233 5234 char ConstraintLetter = Constraint[0]; 5235 switch (ConstraintLetter) { 5236 default: 5237 break; 5238 5239 // This set of constraints deal with valid constants for various instructions. 5240 // Validate and return a target constant for them if we can. 5241 case 'z': { 5242 // 'z' maps to xzr or wzr so it needs an input of 0. 5243 if (!isNullConstant(Op)) 5244 return; 5245 5246 if (Op.getValueType() == MVT::i64) 5247 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 5248 else 5249 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 5250 break; 5251 } 5252 5253 case 'I': 5254 case 'J': 5255 case 'K': 5256 case 'L': 5257 case 'M': 5258 case 'N': 5259 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 5260 if (!C) 5261 return; 5262 5263 // Grab the value and do some validation. 5264 uint64_t CVal = C->getZExtValue(); 5265 switch (ConstraintLetter) { 5266 // The I constraint applies only to simple ADD or SUB immediate operands: 5267 // i.e. 0 to 4095 with optional shift by 12 5268 // The J constraint applies only to ADD or SUB immediates that would be 5269 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 5270 // instruction [or vice versa], in other words -1 to -4095 with optional 5271 // left shift by 12. 5272 case 'I': 5273 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 5274 break; 5275 return; 5276 case 'J': { 5277 uint64_t NVal = -C->getSExtValue(); 5278 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 5279 CVal = C->getSExtValue(); 5280 break; 5281 } 5282 return; 5283 } 5284 // The K and L constraints apply *only* to logical immediates, including 5285 // what used to be the MOVI alias for ORR (though the MOVI alias has now 5286 // been removed and MOV should be used). So these constraints have to 5287 // distinguish between bit patterns that are valid 32-bit or 64-bit 5288 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 5289 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 5290 // versa. 5291 case 'K': 5292 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 5293 break; 5294 return; 5295 case 'L': 5296 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 5297 break; 5298 return; 5299 // The M and N constraints are a superset of K and L respectively, for use 5300 // with the MOV (immediate) alias. As well as the logical immediates they 5301 // also match 32 or 64-bit immediates that can be loaded either using a 5302 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 5303 // (M) or 64-bit 0x1234000000000000 (N) etc. 5304 // As a note some of this code is liberally stolen from the asm parser. 5305 case 'M': { 5306 if (!isUInt<32>(CVal)) 5307 return; 5308 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 5309 break; 5310 if ((CVal & 0xFFFF) == CVal) 5311 break; 5312 if ((CVal & 0xFFFF0000ULL) == CVal) 5313 break; 5314 uint64_t NCVal = ~(uint32_t)CVal; 5315 if ((NCVal & 0xFFFFULL) == NCVal) 5316 break; 5317 if ((NCVal & 0xFFFF0000ULL) == NCVal) 5318 break; 5319 return; 5320 } 5321 case 'N': { 5322 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 5323 break; 5324 if ((CVal & 0xFFFFULL) == CVal) 5325 break; 5326 if ((CVal & 0xFFFF0000ULL) == CVal) 5327 break; 5328 if ((CVal & 0xFFFF00000000ULL) == CVal) 5329 break; 5330 if ((CVal & 0xFFFF000000000000ULL) == CVal) 5331 break; 5332 uint64_t NCVal = ~CVal; 5333 if ((NCVal & 0xFFFFULL) == NCVal) 5334 break; 5335 if ((NCVal & 0xFFFF0000ULL) == NCVal) 5336 break; 5337 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 5338 break; 5339 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 5340 break; 5341 return; 5342 } 5343 default: 5344 return; 5345 } 5346 5347 // All assembler immediates are 64-bit integers. 5348 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 5349 break; 5350 } 5351 5352 if (Result.getNode()) { 5353 Ops.push_back(Result); 5354 return; 5355 } 5356 5357 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 5358 } 5359 5360 //===----------------------------------------------------------------------===// 5361 // AArch64 Advanced SIMD Support 5362 //===----------------------------------------------------------------------===// 5363 5364 /// WidenVector - Given a value in the V64 register class, produce the 5365 /// equivalent value in the V128 register class. 5366 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 5367 EVT VT = V64Reg.getValueType(); 5368 unsigned NarrowSize = VT.getVectorNumElements(); 5369 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5370 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 5371 SDLoc DL(V64Reg); 5372 5373 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 5374 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 5375 } 5376 5377 /// getExtFactor - Determine the adjustment factor for the position when 5378 /// generating an "extract from vector registers" instruction. 5379 static unsigned getExtFactor(SDValue &V) { 5380 EVT EltType = V.getValueType().getVectorElementType(); 5381 return EltType.getSizeInBits() / 8; 5382 } 5383 5384 /// NarrowVector - Given a value in the V128 register class, produce the 5385 /// equivalent value in the V64 register class. 5386 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 5387 EVT VT = V128Reg.getValueType(); 5388 unsigned WideSize = VT.getVectorNumElements(); 5389 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5390 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 5391 SDLoc DL(V128Reg); 5392 5393 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 5394 } 5395 5396 // Gather data to see if the operation can be modelled as a 5397 // shuffle in combination with VEXTs. 5398 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 5399 SelectionDAG &DAG) const { 5400 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5401 DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 5402 SDLoc dl(Op); 5403 EVT VT = Op.getValueType(); 5404 unsigned NumElts = VT.getVectorNumElements(); 5405 5406 struct ShuffleSourceInfo { 5407 SDValue Vec; 5408 unsigned MinElt; 5409 unsigned MaxElt; 5410 5411 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5412 // be compatible with the shuffle we intend to construct. As a result 5413 // ShuffleVec will be some sliding window into the original Vec. 5414 SDValue ShuffleVec; 5415 5416 // Code should guarantee that element i in Vec starts at element "WindowBase 5417 // + i * WindowScale in ShuffleVec". 5418 int WindowBase; 5419 int WindowScale; 5420 5421 ShuffleSourceInfo(SDValue Vec) 5422 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 5423 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 5424 5425 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5426 }; 5427 5428 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5429 // node. 5430 SmallVector<ShuffleSourceInfo, 2> Sources; 5431 for (unsigned i = 0; i < NumElts; ++i) { 5432 SDValue V = Op.getOperand(i); 5433 if (V.isUndef()) 5434 continue; 5435 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5436 !isa<ConstantSDNode>(V.getOperand(1))) { 5437 DEBUG(dbgs() << "Reshuffle failed: " 5438 "a shuffle can only come from building a vector from " 5439 "various elements of other vectors, provided their " 5440 "indices are constant\n"); 5441 return SDValue(); 5442 } 5443 5444 // Add this element source to the list if it's not already there. 5445 SDValue SourceVec = V.getOperand(0); 5446 auto Source = find(Sources, SourceVec); 5447 if (Source == Sources.end()) 5448 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5449 5450 // Update the minimum and maximum lane number seen. 5451 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5452 Source->MinElt = std::min(Source->MinElt, EltNo); 5453 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5454 } 5455 5456 if (Sources.size() > 2) { 5457 DEBUG(dbgs() << "Reshuffle failed: currently only do something sane when at " 5458 "most two source vectors are involved\n"); 5459 return SDValue(); 5460 } 5461 5462 // Find out the smallest element size among result and two sources, and use 5463 // it as element size to build the shuffle_vector. 5464 EVT SmallestEltTy = VT.getVectorElementType(); 5465 for (auto &Source : Sources) { 5466 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5467 if (SrcEltTy.bitsLT(SmallestEltTy)) { 5468 SmallestEltTy = SrcEltTy; 5469 } 5470 } 5471 unsigned ResMultiplier = 5472 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 5473 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5474 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5475 5476 // If the source vector is too wide or too narrow, we may nevertheless be able 5477 // to construct a compatible shuffle either by concatenating it with UNDEF or 5478 // extracting a suitable range of elements. 5479 for (auto &Src : Sources) { 5480 EVT SrcVT = Src.ShuffleVec.getValueType(); 5481 5482 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5483 continue; 5484 5485 // This stage of the search produces a source with the same element type as 5486 // the original, but with a total width matching the BUILD_VECTOR output. 5487 EVT EltVT = SrcVT.getVectorElementType(); 5488 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5489 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5490 5491 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5492 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 5493 // We can pad out the smaller vector for free, so if it's part of a 5494 // shuffle... 5495 Src.ShuffleVec = 5496 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5497 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5498 continue; 5499 } 5500 5501 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 5502 5503 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5504 DEBUG(dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 5505 return SDValue(); 5506 } 5507 5508 if (Src.MinElt >= NumSrcElts) { 5509 // The extraction can just take the second half 5510 Src.ShuffleVec = 5511 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5512 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5513 Src.WindowBase = -NumSrcElts; 5514 } else if (Src.MaxElt < NumSrcElts) { 5515 // The extraction can just take the first half 5516 Src.ShuffleVec = 5517 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5518 DAG.getConstant(0, dl, MVT::i64)); 5519 } else { 5520 // An actual VEXT is needed 5521 SDValue VEXTSrc1 = 5522 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5523 DAG.getConstant(0, dl, MVT::i64)); 5524 SDValue VEXTSrc2 = 5525 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5526 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5527 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 5528 5529 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 5530 VEXTSrc2, 5531 DAG.getConstant(Imm, dl, MVT::i32)); 5532 Src.WindowBase = -Src.MinElt; 5533 } 5534 } 5535 5536 // Another possible incompatibility occurs from the vector element types. We 5537 // can fix this by bitcasting the source vectors to the same type we intend 5538 // for the shuffle. 5539 for (auto &Src : Sources) { 5540 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5541 if (SrcEltTy == SmallestEltTy) 5542 continue; 5543 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5544 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5545 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5546 Src.WindowBase *= Src.WindowScale; 5547 } 5548 5549 // Final sanity check before we try to actually produce a shuffle. 5550 DEBUG( 5551 for (auto Src : Sources) 5552 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5553 ); 5554 5555 // The stars all align, our next step is to produce the mask for the shuffle. 5556 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5557 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 5558 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5559 SDValue Entry = Op.getOperand(i); 5560 if (Entry.isUndef()) 5561 continue; 5562 5563 auto Src = find(Sources, Entry.getOperand(0)); 5564 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5565 5566 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5567 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5568 // segment. 5569 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5570 int BitsDefined = 5571 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); 5572 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5573 5574 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5575 // starting at the appropriate offset. 5576 int *LaneMask = &Mask[i * ResMultiplier]; 5577 5578 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5579 ExtractBase += NumElts * (Src - Sources.begin()); 5580 for (int j = 0; j < LanesDefined; ++j) 5581 LaneMask[j] = ExtractBase + j; 5582 } 5583 5584 // Final check before we try to produce nonsense... 5585 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 5586 DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 5587 return SDValue(); 5588 } 5589 5590 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5591 for (unsigned i = 0; i < Sources.size(); ++i) 5592 ShuffleOps[i] = Sources[i].ShuffleVec; 5593 5594 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5595 ShuffleOps[1], Mask); 5596 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5597 5598 DEBUG( 5599 dbgs() << "Reshuffle, creating node: "; 5600 Shuffle.dump(); 5601 dbgs() << "Reshuffle, creating node: "; 5602 V.dump(); 5603 ); 5604 5605 return V; 5606 } 5607 5608 // check if an EXT instruction can handle the shuffle mask when the 5609 // vector sources of the shuffle are the same. 5610 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5611 unsigned NumElts = VT.getVectorNumElements(); 5612 5613 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5614 if (M[0] < 0) 5615 return false; 5616 5617 Imm = M[0]; 5618 5619 // If this is a VEXT shuffle, the immediate value is the index of the first 5620 // element. The other shuffle indices must be the successive elements after 5621 // the first one. 5622 unsigned ExpectedElt = Imm; 5623 for (unsigned i = 1; i < NumElts; ++i) { 5624 // Increment the expected index. If it wraps around, just follow it 5625 // back to index zero and keep going. 5626 ++ExpectedElt; 5627 if (ExpectedElt == NumElts) 5628 ExpectedElt = 0; 5629 5630 if (M[i] < 0) 5631 continue; // ignore UNDEF indices 5632 if (ExpectedElt != static_cast<unsigned>(M[i])) 5633 return false; 5634 } 5635 5636 return true; 5637 } 5638 5639 // check if an EXT instruction can handle the shuffle mask when the 5640 // vector sources of the shuffle are different. 5641 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 5642 unsigned &Imm) { 5643 // Look for the first non-undef element. 5644 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 5645 5646 // Benefit form APInt to handle overflow when calculating expected element. 5647 unsigned NumElts = VT.getVectorNumElements(); 5648 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 5649 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 5650 // The following shuffle indices must be the successive elements after the 5651 // first real element. 5652 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 5653 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 5654 if (FirstWrongElt != M.end()) 5655 return false; 5656 5657 // The index of an EXT is the first element if it is not UNDEF. 5658 // Watch out for the beginning UNDEFs. The EXT index should be the expected 5659 // value of the first element. E.g. 5660 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 5661 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 5662 // ExpectedElt is the last mask index plus 1. 5663 Imm = ExpectedElt.getZExtValue(); 5664 5665 // There are two difference cases requiring to reverse input vectors. 5666 // For example, for vector <4 x i32> we have the following cases, 5667 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 5668 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 5669 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 5670 // to reverse two input vectors. 5671 if (Imm < NumElts) 5672 ReverseEXT = true; 5673 else 5674 Imm -= NumElts; 5675 5676 return true; 5677 } 5678 5679 /// isREVMask - Check if a vector shuffle corresponds to a REV 5680 /// instruction with the specified blocksize. (The order of the elements 5681 /// within each block of the vector is reversed.) 5682 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5683 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 5684 "Only possible block sizes for REV are: 16, 32, 64"); 5685 5686 unsigned EltSz = VT.getScalarSizeInBits(); 5687 if (EltSz == 64) 5688 return false; 5689 5690 unsigned NumElts = VT.getVectorNumElements(); 5691 unsigned BlockElts = M[0] + 1; 5692 // If the first shuffle index is UNDEF, be optimistic. 5693 if (M[0] < 0) 5694 BlockElts = BlockSize / EltSz; 5695 5696 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5697 return false; 5698 5699 for (unsigned i = 0; i < NumElts; ++i) { 5700 if (M[i] < 0) 5701 continue; // ignore UNDEF indices 5702 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 5703 return false; 5704 } 5705 5706 return true; 5707 } 5708 5709 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5710 unsigned NumElts = VT.getVectorNumElements(); 5711 WhichResult = (M[0] == 0 ? 0 : 1); 5712 unsigned Idx = WhichResult * NumElts / 2; 5713 for (unsigned i = 0; i != NumElts; i += 2) { 5714 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5715 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 5716 return false; 5717 Idx += 1; 5718 } 5719 5720 return true; 5721 } 5722 5723 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5724 unsigned NumElts = VT.getVectorNumElements(); 5725 WhichResult = (M[0] == 0 ? 0 : 1); 5726 for (unsigned i = 0; i != NumElts; ++i) { 5727 if (M[i] < 0) 5728 continue; // ignore UNDEF indices 5729 if ((unsigned)M[i] != 2 * i + WhichResult) 5730 return false; 5731 } 5732 5733 return true; 5734 } 5735 5736 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5737 unsigned NumElts = VT.getVectorNumElements(); 5738 WhichResult = (M[0] == 0 ? 0 : 1); 5739 for (unsigned i = 0; i < NumElts; i += 2) { 5740 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5741 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 5742 return false; 5743 } 5744 return true; 5745 } 5746 5747 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 5748 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5749 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5750 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5751 unsigned NumElts = VT.getVectorNumElements(); 5752 WhichResult = (M[0] == 0 ? 0 : 1); 5753 unsigned Idx = WhichResult * NumElts / 2; 5754 for (unsigned i = 0; i != NumElts; i += 2) { 5755 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5756 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 5757 return false; 5758 Idx += 1; 5759 } 5760 5761 return true; 5762 } 5763 5764 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 5765 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5766 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5767 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5768 unsigned Half = VT.getVectorNumElements() / 2; 5769 WhichResult = (M[0] == 0 ? 0 : 1); 5770 for (unsigned j = 0; j != 2; ++j) { 5771 unsigned Idx = WhichResult; 5772 for (unsigned i = 0; i != Half; ++i) { 5773 int MIdx = M[i + j * Half]; 5774 if (MIdx >= 0 && (unsigned)MIdx != Idx) 5775 return false; 5776 Idx += 2; 5777 } 5778 } 5779 5780 return true; 5781 } 5782 5783 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 5784 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5785 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5786 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5787 unsigned NumElts = VT.getVectorNumElements(); 5788 WhichResult = (M[0] == 0 ? 0 : 1); 5789 for (unsigned i = 0; i < NumElts; i += 2) { 5790 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5791 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 5792 return false; 5793 } 5794 return true; 5795 } 5796 5797 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 5798 bool &DstIsLeft, int &Anomaly) { 5799 if (M.size() != static_cast<size_t>(NumInputElements)) 5800 return false; 5801 5802 int NumLHSMatch = 0, NumRHSMatch = 0; 5803 int LastLHSMismatch = -1, LastRHSMismatch = -1; 5804 5805 for (int i = 0; i < NumInputElements; ++i) { 5806 if (M[i] == -1) { 5807 ++NumLHSMatch; 5808 ++NumRHSMatch; 5809 continue; 5810 } 5811 5812 if (M[i] == i) 5813 ++NumLHSMatch; 5814 else 5815 LastLHSMismatch = i; 5816 5817 if (M[i] == i + NumInputElements) 5818 ++NumRHSMatch; 5819 else 5820 LastRHSMismatch = i; 5821 } 5822 5823 if (NumLHSMatch == NumInputElements - 1) { 5824 DstIsLeft = true; 5825 Anomaly = LastLHSMismatch; 5826 return true; 5827 } else if (NumRHSMatch == NumInputElements - 1) { 5828 DstIsLeft = false; 5829 Anomaly = LastRHSMismatch; 5830 return true; 5831 } 5832 5833 return false; 5834 } 5835 5836 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 5837 if (VT.getSizeInBits() != 128) 5838 return false; 5839 5840 unsigned NumElts = VT.getVectorNumElements(); 5841 5842 for (int I = 0, E = NumElts / 2; I != E; I++) { 5843 if (Mask[I] != I) 5844 return false; 5845 } 5846 5847 int Offset = NumElts / 2; 5848 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 5849 if (Mask[I] != I + SplitLHS * Offset) 5850 return false; 5851 } 5852 5853 return true; 5854 } 5855 5856 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 5857 SDLoc DL(Op); 5858 EVT VT = Op.getValueType(); 5859 SDValue V0 = Op.getOperand(0); 5860 SDValue V1 = Op.getOperand(1); 5861 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 5862 5863 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 5864 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 5865 return SDValue(); 5866 5867 bool SplitV0 = V0.getValueSizeInBits() == 128; 5868 5869 if (!isConcatMask(Mask, VT, SplitV0)) 5870 return SDValue(); 5871 5872 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 5873 VT.getVectorNumElements() / 2); 5874 if (SplitV0) { 5875 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 5876 DAG.getConstant(0, DL, MVT::i64)); 5877 } 5878 if (V1.getValueSizeInBits() == 128) { 5879 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 5880 DAG.getConstant(0, DL, MVT::i64)); 5881 } 5882 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 5883 } 5884 5885 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5886 /// the specified operations to build the shuffle. 5887 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5888 SDValue RHS, SelectionDAG &DAG, 5889 const SDLoc &dl) { 5890 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5891 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 5892 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 5893 5894 enum { 5895 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5896 OP_VREV, 5897 OP_VDUP0, 5898 OP_VDUP1, 5899 OP_VDUP2, 5900 OP_VDUP3, 5901 OP_VEXT1, 5902 OP_VEXT2, 5903 OP_VEXT3, 5904 OP_VUZPL, // VUZP, left result 5905 OP_VUZPR, // VUZP, right result 5906 OP_VZIPL, // VZIP, left result 5907 OP_VZIPR, // VZIP, right result 5908 OP_VTRNL, // VTRN, left result 5909 OP_VTRNR // VTRN, right result 5910 }; 5911 5912 if (OpNum == OP_COPY) { 5913 if (LHSID == (1 * 9 + 2) * 9 + 3) 5914 return LHS; 5915 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 5916 return RHS; 5917 } 5918 5919 SDValue OpLHS, OpRHS; 5920 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5921 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5922 EVT VT = OpLHS.getValueType(); 5923 5924 switch (OpNum) { 5925 default: 5926 llvm_unreachable("Unknown shuffle opcode!"); 5927 case OP_VREV: 5928 // VREV divides the vector in half and swaps within the half. 5929 if (VT.getVectorElementType() == MVT::i32 || 5930 VT.getVectorElementType() == MVT::f32) 5931 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 5932 // vrev <4 x i16> -> REV32 5933 if (VT.getVectorElementType() == MVT::i16 || 5934 VT.getVectorElementType() == MVT::f16) 5935 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 5936 // vrev <4 x i8> -> REV16 5937 assert(VT.getVectorElementType() == MVT::i8); 5938 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 5939 case OP_VDUP0: 5940 case OP_VDUP1: 5941 case OP_VDUP2: 5942 case OP_VDUP3: { 5943 EVT EltTy = VT.getVectorElementType(); 5944 unsigned Opcode; 5945 if (EltTy == MVT::i8) 5946 Opcode = AArch64ISD::DUPLANE8; 5947 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 5948 Opcode = AArch64ISD::DUPLANE16; 5949 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 5950 Opcode = AArch64ISD::DUPLANE32; 5951 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 5952 Opcode = AArch64ISD::DUPLANE64; 5953 else 5954 llvm_unreachable("Invalid vector element type?"); 5955 5956 if (VT.getSizeInBits() == 64) 5957 OpLHS = WidenVector(OpLHS, DAG); 5958 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 5959 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 5960 } 5961 case OP_VEXT1: 5962 case OP_VEXT2: 5963 case OP_VEXT3: { 5964 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 5965 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 5966 DAG.getConstant(Imm, dl, MVT::i32)); 5967 } 5968 case OP_VUZPL: 5969 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 5970 OpRHS); 5971 case OP_VUZPR: 5972 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 5973 OpRHS); 5974 case OP_VZIPL: 5975 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 5976 OpRHS); 5977 case OP_VZIPR: 5978 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 5979 OpRHS); 5980 case OP_VTRNL: 5981 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 5982 OpRHS); 5983 case OP_VTRNR: 5984 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 5985 OpRHS); 5986 } 5987 } 5988 5989 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 5990 SelectionDAG &DAG) { 5991 // Check to see if we can use the TBL instruction. 5992 SDValue V1 = Op.getOperand(0); 5993 SDValue V2 = Op.getOperand(1); 5994 SDLoc DL(Op); 5995 5996 EVT EltVT = Op.getValueType().getVectorElementType(); 5997 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 5998 5999 SmallVector<SDValue, 8> TBLMask; 6000 for (int Val : ShuffleMask) { 6001 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 6002 unsigned Offset = Byte + Val * BytesPerElt; 6003 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 6004 } 6005 } 6006 6007 MVT IndexVT = MVT::v8i8; 6008 unsigned IndexLen = 8; 6009 if (Op.getValueSizeInBits() == 128) { 6010 IndexVT = MVT::v16i8; 6011 IndexLen = 16; 6012 } 6013 6014 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 6015 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 6016 6017 SDValue Shuffle; 6018 if (V2.getNode()->isUndef()) { 6019 if (IndexLen == 8) 6020 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 6021 Shuffle = DAG.getNode( 6022 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6023 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 6024 DAG.getBuildVector(IndexVT, DL, 6025 makeArrayRef(TBLMask.data(), IndexLen))); 6026 } else { 6027 if (IndexLen == 8) { 6028 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 6029 Shuffle = DAG.getNode( 6030 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6031 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 6032 DAG.getBuildVector(IndexVT, DL, 6033 makeArrayRef(TBLMask.data(), IndexLen))); 6034 } else { 6035 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 6036 // cannot currently represent the register constraints on the input 6037 // table registers. 6038 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 6039 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 6040 // IndexLen)); 6041 Shuffle = DAG.getNode( 6042 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6043 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 6044 V2Cst, DAG.getBuildVector(IndexVT, DL, 6045 makeArrayRef(TBLMask.data(), IndexLen))); 6046 } 6047 } 6048 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 6049 } 6050 6051 static unsigned getDUPLANEOp(EVT EltType) { 6052 if (EltType == MVT::i8) 6053 return AArch64ISD::DUPLANE8; 6054 if (EltType == MVT::i16 || EltType == MVT::f16) 6055 return AArch64ISD::DUPLANE16; 6056 if (EltType == MVT::i32 || EltType == MVT::f32) 6057 return AArch64ISD::DUPLANE32; 6058 if (EltType == MVT::i64 || EltType == MVT::f64) 6059 return AArch64ISD::DUPLANE64; 6060 6061 llvm_unreachable("Invalid vector element type?"); 6062 } 6063 6064 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 6065 SelectionDAG &DAG) const { 6066 SDLoc dl(Op); 6067 EVT VT = Op.getValueType(); 6068 6069 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6070 6071 // Convert shuffles that are directly supported on NEON to target-specific 6072 // DAG nodes, instead of keeping them as shuffles and matching them again 6073 // during code selection. This is more efficient and avoids the possibility 6074 // of inconsistencies between legalization and selection. 6075 ArrayRef<int> ShuffleMask = SVN->getMask(); 6076 6077 SDValue V1 = Op.getOperand(0); 6078 SDValue V2 = Op.getOperand(1); 6079 6080 if (SVN->isSplat()) { 6081 int Lane = SVN->getSplatIndex(); 6082 // If this is undef splat, generate it via "just" vdup, if possible. 6083 if (Lane == -1) 6084 Lane = 0; 6085 6086 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 6087 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 6088 V1.getOperand(0)); 6089 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 6090 // constant. If so, we can just reference the lane's definition directly. 6091 if (V1.getOpcode() == ISD::BUILD_VECTOR && 6092 !isa<ConstantSDNode>(V1.getOperand(Lane))) 6093 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 6094 6095 // Otherwise, duplicate from the lane of the input vector. 6096 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 6097 6098 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated 6099 // to make a vector of the same size as this SHUFFLE. We can ignore the 6100 // extract entirely, and canonicalise the concat using WidenVector. 6101 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 6102 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); 6103 V1 = V1.getOperand(0); 6104 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 6105 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 6106 Lane -= Idx * VT.getVectorNumElements() / 2; 6107 V1 = WidenVector(V1.getOperand(Idx), DAG); 6108 } else if (VT.getSizeInBits() == 64) 6109 V1 = WidenVector(V1, DAG); 6110 6111 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 6112 } 6113 6114 if (isREVMask(ShuffleMask, VT, 64)) 6115 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 6116 if (isREVMask(ShuffleMask, VT, 32)) 6117 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 6118 if (isREVMask(ShuffleMask, VT, 16)) 6119 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 6120 6121 bool ReverseEXT = false; 6122 unsigned Imm; 6123 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 6124 if (ReverseEXT) 6125 std::swap(V1, V2); 6126 Imm *= getExtFactor(V1); 6127 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 6128 DAG.getConstant(Imm, dl, MVT::i32)); 6129 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 6130 Imm *= getExtFactor(V1); 6131 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 6132 DAG.getConstant(Imm, dl, MVT::i32)); 6133 } 6134 6135 unsigned WhichResult; 6136 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 6137 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 6138 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6139 } 6140 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 6141 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 6142 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6143 } 6144 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 6145 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 6146 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6147 } 6148 6149 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6150 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 6151 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6152 } 6153 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6154 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 6155 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6156 } 6157 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6158 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 6159 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6160 } 6161 6162 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 6163 return Concat; 6164 6165 bool DstIsLeft; 6166 int Anomaly; 6167 int NumInputElements = V1.getValueType().getVectorNumElements(); 6168 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 6169 SDValue DstVec = DstIsLeft ? V1 : V2; 6170 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 6171 6172 SDValue SrcVec = V1; 6173 int SrcLane = ShuffleMask[Anomaly]; 6174 if (SrcLane >= NumInputElements) { 6175 SrcVec = V2; 6176 SrcLane -= VT.getVectorNumElements(); 6177 } 6178 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 6179 6180 EVT ScalarVT = VT.getVectorElementType(); 6181 6182 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 6183 ScalarVT = MVT::i32; 6184 6185 return DAG.getNode( 6186 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 6187 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 6188 DstLaneV); 6189 } 6190 6191 // If the shuffle is not directly supported and it has 4 elements, use 6192 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6193 unsigned NumElts = VT.getVectorNumElements(); 6194 if (NumElts == 4) { 6195 unsigned PFIndexes[4]; 6196 for (unsigned i = 0; i != 4; ++i) { 6197 if (ShuffleMask[i] < 0) 6198 PFIndexes[i] = 8; 6199 else 6200 PFIndexes[i] = ShuffleMask[i]; 6201 } 6202 6203 // Compute the index in the perfect shuffle table. 6204 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 6205 PFIndexes[2] * 9 + PFIndexes[3]; 6206 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6207 unsigned Cost = (PFEntry >> 30); 6208 6209 if (Cost <= 4) 6210 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6211 } 6212 6213 return GenerateTBL(Op, ShuffleMask, DAG); 6214 } 6215 6216 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 6217 APInt &UndefBits) { 6218 EVT VT = BVN->getValueType(0); 6219 APInt SplatBits, SplatUndef; 6220 unsigned SplatBitSize; 6221 bool HasAnyUndefs; 6222 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6223 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 6224 6225 for (unsigned i = 0; i < NumSplats; ++i) { 6226 CnstBits <<= SplatBitSize; 6227 UndefBits <<= SplatBitSize; 6228 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 6229 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 6230 } 6231 6232 return true; 6233 } 6234 6235 return false; 6236 } 6237 6238 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op, 6239 SelectionDAG &DAG) const { 6240 BuildVectorSDNode *BVN = 6241 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 6242 SDValue LHS = Op.getOperand(0); 6243 SDLoc dl(Op); 6244 EVT VT = Op.getValueType(); 6245 6246 if (!BVN) 6247 return Op; 6248 6249 APInt CnstBits(VT.getSizeInBits(), 0); 6250 APInt UndefBits(VT.getSizeInBits(), 0); 6251 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6252 // We only have BIC vector immediate instruction, which is and-not. 6253 CnstBits = ~CnstBits; 6254 6255 // We make use of a little bit of goto ickiness in order to avoid having to 6256 // duplicate the immediate matching logic for the undef toggled case. 6257 bool SecondTry = false; 6258 AttemptModImm: 6259 6260 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6261 CnstBits = CnstBits.zextOrTrunc(64); 6262 uint64_t CnstVal = CnstBits.getZExtValue(); 6263 6264 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6265 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6266 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6267 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6268 DAG.getConstant(CnstVal, dl, MVT::i32), 6269 DAG.getConstant(0, dl, MVT::i32)); 6270 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6271 } 6272 6273 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6274 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6275 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6276 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6277 DAG.getConstant(CnstVal, dl, MVT::i32), 6278 DAG.getConstant(8, dl, MVT::i32)); 6279 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6280 } 6281 6282 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6283 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6284 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6285 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6286 DAG.getConstant(CnstVal, dl, MVT::i32), 6287 DAG.getConstant(16, dl, MVT::i32)); 6288 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6289 } 6290 6291 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6292 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6293 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6294 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6295 DAG.getConstant(CnstVal, dl, MVT::i32), 6296 DAG.getConstant(24, dl, MVT::i32)); 6297 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6298 } 6299 6300 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6301 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6302 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6303 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6304 DAG.getConstant(CnstVal, dl, MVT::i32), 6305 DAG.getConstant(0, dl, MVT::i32)); 6306 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6307 } 6308 6309 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6310 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6311 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6312 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6313 DAG.getConstant(CnstVal, dl, MVT::i32), 6314 DAG.getConstant(8, dl, MVT::i32)); 6315 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6316 } 6317 } 6318 6319 if (SecondTry) 6320 goto FailedModImm; 6321 SecondTry = true; 6322 CnstBits = ~UndefBits; 6323 goto AttemptModImm; 6324 } 6325 6326 // We can always fall back to a non-immediate AND. 6327 FailedModImm: 6328 return Op; 6329 } 6330 6331 // Specialized code to quickly find if PotentialBVec is a BuildVector that 6332 // consists of only the same constant int value, returned in reference arg 6333 // ConstVal 6334 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 6335 uint64_t &ConstVal) { 6336 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 6337 if (!Bvec) 6338 return false; 6339 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 6340 if (!FirstElt) 6341 return false; 6342 EVT VT = Bvec->getValueType(0); 6343 unsigned NumElts = VT.getVectorNumElements(); 6344 for (unsigned i = 1; i < NumElts; ++i) 6345 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 6346 return false; 6347 ConstVal = FirstElt->getZExtValue(); 6348 return true; 6349 } 6350 6351 static unsigned getIntrinsicID(const SDNode *N) { 6352 unsigned Opcode = N->getOpcode(); 6353 switch (Opcode) { 6354 default: 6355 return Intrinsic::not_intrinsic; 6356 case ISD::INTRINSIC_WO_CHAIN: { 6357 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6358 if (IID < Intrinsic::num_intrinsics) 6359 return IID; 6360 return Intrinsic::not_intrinsic; 6361 } 6362 } 6363 } 6364 6365 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 6366 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 6367 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 6368 // Also, logical shift right -> sri, with the same structure. 6369 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 6370 EVT VT = N->getValueType(0); 6371 6372 if (!VT.isVector()) 6373 return SDValue(); 6374 6375 SDLoc DL(N); 6376 6377 // Is the first op an AND? 6378 const SDValue And = N->getOperand(0); 6379 if (And.getOpcode() != ISD::AND) 6380 return SDValue(); 6381 6382 // Is the second op an shl or lshr? 6383 SDValue Shift = N->getOperand(1); 6384 // This will have been turned into: AArch64ISD::VSHL vector, #shift 6385 // or AArch64ISD::VLSHR vector, #shift 6386 unsigned ShiftOpc = Shift.getOpcode(); 6387 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 6388 return SDValue(); 6389 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 6390 6391 // Is the shift amount constant? 6392 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 6393 if (!C2node) 6394 return SDValue(); 6395 6396 // Is the and mask vector all constant? 6397 uint64_t C1; 6398 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 6399 return SDValue(); 6400 6401 // Is C1 == ~C2, taking into account how much one can shift elements of a 6402 // particular size? 6403 uint64_t C2 = C2node->getZExtValue(); 6404 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 6405 if (C2 > ElemSizeInBits) 6406 return SDValue(); 6407 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 6408 if ((C1 & ElemMask) != (~C2 & ElemMask)) 6409 return SDValue(); 6410 6411 SDValue X = And.getOperand(0); 6412 SDValue Y = Shift.getOperand(0); 6413 6414 unsigned Intrin = 6415 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 6416 SDValue ResultSLI = 6417 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6418 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 6419 Shift.getOperand(1)); 6420 6421 DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 6422 DEBUG(N->dump(&DAG)); 6423 DEBUG(dbgs() << "into: \n"); 6424 DEBUG(ResultSLI->dump(&DAG)); 6425 6426 ++NumShiftInserts; 6427 return ResultSLI; 6428 } 6429 6430 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 6431 SelectionDAG &DAG) const { 6432 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 6433 if (EnableAArch64SlrGeneration) { 6434 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 6435 return Res; 6436 } 6437 6438 BuildVectorSDNode *BVN = 6439 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 6440 SDValue LHS = Op.getOperand(1); 6441 SDLoc dl(Op); 6442 EVT VT = Op.getValueType(); 6443 6444 // OR commutes, so try swapping the operands. 6445 if (!BVN) { 6446 LHS = Op.getOperand(0); 6447 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 6448 } 6449 if (!BVN) 6450 return Op; 6451 6452 APInt CnstBits(VT.getSizeInBits(), 0); 6453 APInt UndefBits(VT.getSizeInBits(), 0); 6454 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6455 // We make use of a little bit of goto ickiness in order to avoid having to 6456 // duplicate the immediate matching logic for the undef toggled case. 6457 bool SecondTry = false; 6458 AttemptModImm: 6459 6460 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6461 CnstBits = CnstBits.zextOrTrunc(64); 6462 uint64_t CnstVal = CnstBits.getZExtValue(); 6463 6464 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6465 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6466 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6467 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6468 DAG.getConstant(CnstVal, dl, MVT::i32), 6469 DAG.getConstant(0, dl, MVT::i32)); 6470 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6471 } 6472 6473 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6474 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6475 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6476 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6477 DAG.getConstant(CnstVal, dl, MVT::i32), 6478 DAG.getConstant(8, dl, MVT::i32)); 6479 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6480 } 6481 6482 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6483 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6484 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6485 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6486 DAG.getConstant(CnstVal, dl, MVT::i32), 6487 DAG.getConstant(16, dl, MVT::i32)); 6488 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6489 } 6490 6491 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6492 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6493 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6494 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6495 DAG.getConstant(CnstVal, dl, MVT::i32), 6496 DAG.getConstant(24, dl, MVT::i32)); 6497 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6498 } 6499 6500 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6501 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6502 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6503 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6504 DAG.getConstant(CnstVal, dl, MVT::i32), 6505 DAG.getConstant(0, dl, MVT::i32)); 6506 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6507 } 6508 6509 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6510 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6511 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6512 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6513 DAG.getConstant(CnstVal, dl, MVT::i32), 6514 DAG.getConstant(8, dl, MVT::i32)); 6515 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6516 } 6517 } 6518 6519 if (SecondTry) 6520 goto FailedModImm; 6521 SecondTry = true; 6522 CnstBits = UndefBits; 6523 goto AttemptModImm; 6524 } 6525 6526 // We can always fall back to a non-immediate OR. 6527 FailedModImm: 6528 return Op; 6529 } 6530 6531 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 6532 // be truncated to fit element width. 6533 static SDValue NormalizeBuildVector(SDValue Op, 6534 SelectionDAG &DAG) { 6535 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6536 SDLoc dl(Op); 6537 EVT VT = Op.getValueType(); 6538 EVT EltTy= VT.getVectorElementType(); 6539 6540 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 6541 return Op; 6542 6543 SmallVector<SDValue, 16> Ops; 6544 for (SDValue Lane : Op->ops()) { 6545 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 6546 APInt LowBits(EltTy.getSizeInBits(), 6547 CstLane->getZExtValue()); 6548 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 6549 } 6550 Ops.push_back(Lane); 6551 } 6552 return DAG.getBuildVector(VT, dl, Ops); 6553 } 6554 6555 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 6556 SelectionDAG &DAG) const { 6557 SDLoc dl(Op); 6558 EVT VT = Op.getValueType(); 6559 Op = NormalizeBuildVector(Op, DAG); 6560 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6561 6562 APInt CnstBits(VT.getSizeInBits(), 0); 6563 APInt UndefBits(VT.getSizeInBits(), 0); 6564 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6565 // We make use of a little bit of goto ickiness in order to avoid having to 6566 // duplicate the immediate matching logic for the undef toggled case. 6567 bool SecondTry = false; 6568 AttemptModImm: 6569 6570 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6571 CnstBits = CnstBits.zextOrTrunc(64); 6572 uint64_t CnstVal = CnstBits.getZExtValue(); 6573 6574 // Certain magic vector constants (used to express things like NOT 6575 // and NEG) are passed through unmodified. This allows codegen patterns 6576 // for these operations to match. Special-purpose patterns will lower 6577 // these immediates to MOVIs if it proves necessary. 6578 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL)) 6579 return Op; 6580 6581 // The many faces of MOVI... 6582 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) { 6583 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal); 6584 if (VT.getSizeInBits() == 128) { 6585 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64, 6586 DAG.getConstant(CnstVal, dl, MVT::i32)); 6587 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6588 } 6589 6590 // Support the V64 version via subregister insertion. 6591 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64, 6592 DAG.getConstant(CnstVal, dl, MVT::i32)); 6593 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6594 } 6595 6596 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6597 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6598 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6599 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6600 DAG.getConstant(CnstVal, dl, MVT::i32), 6601 DAG.getConstant(0, dl, MVT::i32)); 6602 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6603 } 6604 6605 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6606 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6607 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6608 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6609 DAG.getConstant(CnstVal, dl, MVT::i32), 6610 DAG.getConstant(8, dl, MVT::i32)); 6611 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6612 } 6613 6614 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6615 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6616 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6617 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6618 DAG.getConstant(CnstVal, dl, MVT::i32), 6619 DAG.getConstant(16, dl, MVT::i32)); 6620 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6621 } 6622 6623 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6624 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6625 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6626 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6627 DAG.getConstant(CnstVal, dl, MVT::i32), 6628 DAG.getConstant(24, dl, MVT::i32)); 6629 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6630 } 6631 6632 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6633 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6634 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6635 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6636 DAG.getConstant(CnstVal, dl, MVT::i32), 6637 DAG.getConstant(0, dl, MVT::i32)); 6638 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6639 } 6640 6641 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6642 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6643 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6644 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6645 DAG.getConstant(CnstVal, dl, MVT::i32), 6646 DAG.getConstant(8, dl, MVT::i32)); 6647 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6648 } 6649 6650 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6651 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6652 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6653 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6654 DAG.getConstant(CnstVal, dl, MVT::i32), 6655 DAG.getConstant(264, dl, MVT::i32)); 6656 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6657 } 6658 6659 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6660 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6661 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6662 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6663 DAG.getConstant(CnstVal, dl, MVT::i32), 6664 DAG.getConstant(272, dl, MVT::i32)); 6665 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6666 } 6667 6668 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) { 6669 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal); 6670 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 6671 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy, 6672 DAG.getConstant(CnstVal, dl, MVT::i32)); 6673 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6674 } 6675 6676 // The few faces of FMOV... 6677 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) { 6678 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal); 6679 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32; 6680 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy, 6681 DAG.getConstant(CnstVal, dl, MVT::i32)); 6682 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6683 } 6684 6685 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) && 6686 VT.getSizeInBits() == 128) { 6687 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal); 6688 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64, 6689 DAG.getConstant(CnstVal, dl, MVT::i32)); 6690 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6691 } 6692 6693 // The many faces of MVNI... 6694 CnstVal = ~CnstVal; 6695 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6696 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6697 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6698 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6699 DAG.getConstant(CnstVal, dl, MVT::i32), 6700 DAG.getConstant(0, dl, MVT::i32)); 6701 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6702 } 6703 6704 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6705 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6706 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6707 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6708 DAG.getConstant(CnstVal, dl, MVT::i32), 6709 DAG.getConstant(8, dl, MVT::i32)); 6710 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6711 } 6712 6713 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6714 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6715 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6716 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6717 DAG.getConstant(CnstVal, dl, MVT::i32), 6718 DAG.getConstant(16, dl, MVT::i32)); 6719 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6720 } 6721 6722 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6723 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6724 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6725 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6726 DAG.getConstant(CnstVal, dl, MVT::i32), 6727 DAG.getConstant(24, dl, MVT::i32)); 6728 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6729 } 6730 6731 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6732 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6733 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6734 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6735 DAG.getConstant(CnstVal, dl, MVT::i32), 6736 DAG.getConstant(0, dl, MVT::i32)); 6737 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6738 } 6739 6740 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6741 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6742 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6743 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6744 DAG.getConstant(CnstVal, dl, MVT::i32), 6745 DAG.getConstant(8, dl, MVT::i32)); 6746 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6747 } 6748 6749 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6750 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6751 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6752 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6753 DAG.getConstant(CnstVal, dl, MVT::i32), 6754 DAG.getConstant(264, dl, MVT::i32)); 6755 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6756 } 6757 6758 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6759 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6760 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6761 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6762 DAG.getConstant(CnstVal, dl, MVT::i32), 6763 DAG.getConstant(272, dl, MVT::i32)); 6764 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6765 } 6766 } 6767 6768 if (SecondTry) 6769 goto FailedModImm; 6770 SecondTry = true; 6771 CnstBits = UndefBits; 6772 goto AttemptModImm; 6773 } 6774 FailedModImm: 6775 6776 // Scan through the operands to find some interesting properties we can 6777 // exploit: 6778 // 1) If only one value is used, we can use a DUP, or 6779 // 2) if only the low element is not undef, we can just insert that, or 6780 // 3) if only one constant value is used (w/ some non-constant lanes), 6781 // we can splat the constant value into the whole vector then fill 6782 // in the non-constant lanes. 6783 // 4) FIXME: If different constant values are used, but we can intelligently 6784 // select the values we'll be overwriting for the non-constant 6785 // lanes such that we can directly materialize the vector 6786 // some other way (MOVI, e.g.), we can be sneaky. 6787 unsigned NumElts = VT.getVectorNumElements(); 6788 bool isOnlyLowElement = true; 6789 bool usesOnlyOneValue = true; 6790 bool usesOnlyOneConstantValue = true; 6791 bool isConstant = true; 6792 unsigned NumConstantLanes = 0; 6793 SDValue Value; 6794 SDValue ConstantValue; 6795 for (unsigned i = 0; i < NumElts; ++i) { 6796 SDValue V = Op.getOperand(i); 6797 if (V.isUndef()) 6798 continue; 6799 if (i > 0) 6800 isOnlyLowElement = false; 6801 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6802 isConstant = false; 6803 6804 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 6805 ++NumConstantLanes; 6806 if (!ConstantValue.getNode()) 6807 ConstantValue = V; 6808 else if (ConstantValue != V) 6809 usesOnlyOneConstantValue = false; 6810 } 6811 6812 if (!Value.getNode()) 6813 Value = V; 6814 else if (V != Value) 6815 usesOnlyOneValue = false; 6816 } 6817 6818 if (!Value.getNode()) { 6819 DEBUG(dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 6820 return DAG.getUNDEF(VT); 6821 } 6822 6823 if (isOnlyLowElement) { 6824 DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 6825 "SCALAR_TO_VECTOR node\n"); 6826 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6827 } 6828 6829 // Use DUP for non-constant splats. For f32 constant splats, reduce to 6830 // i32 and try again. 6831 if (usesOnlyOneValue) { 6832 if (!isConstant) { 6833 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6834 Value.getValueType() != VT) { 6835 DEBUG(dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 6836 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 6837 } 6838 6839 // This is actually a DUPLANExx operation, which keeps everything vectory. 6840 6841 SDValue Lane = Value.getOperand(1); 6842 Value = Value.getOperand(0); 6843 if (Value.getValueSizeInBits() == 64) { 6844 DEBUG(dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 6845 "widening it\n"); 6846 Value = WidenVector(Value, DAG); 6847 } 6848 6849 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 6850 return DAG.getNode(Opcode, dl, VT, Value, Lane); 6851 } 6852 6853 if (VT.getVectorElementType().isFloatingPoint()) { 6854 SmallVector<SDValue, 8> Ops; 6855 EVT EltTy = VT.getVectorElementType(); 6856 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 6857 "Unsupported floating-point vector type"); 6858 DEBUG(dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 6859 "BITCASTS, and try again\n"); 6860 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 6861 for (unsigned i = 0; i < NumElts; ++i) 6862 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 6863 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 6864 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6865 DEBUG( 6866 dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 6867 Val.dump(); 6868 ); 6869 Val = LowerBUILD_VECTOR(Val, DAG); 6870 if (Val.getNode()) 6871 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6872 } 6873 } 6874 6875 // If there was only one constant value used and for more than one lane, 6876 // start by splatting that value, then replace the non-constant lanes. This 6877 // is better than the default, which will perform a separate initialization 6878 // for each lane. 6879 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 6880 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 6881 // Now insert the non-constant lanes. 6882 for (unsigned i = 0; i < NumElts; ++i) { 6883 SDValue V = Op.getOperand(i); 6884 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6885 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) { 6886 // Note that type legalization likely mucked about with the VT of the 6887 // source operand, so we may have to convert it here before inserting. 6888 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 6889 } 6890 } 6891 return Val; 6892 } 6893 6894 // This will generate a load from the constant pool. 6895 if (isConstant) { 6896 DEBUG(dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 6897 "expansion\n"); 6898 return SDValue(); 6899 } 6900 6901 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6902 if (NumElts >= 4) { 6903 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 6904 return shuffle; 6905 } 6906 6907 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6908 // know the default expansion would otherwise fall back on something even 6909 // worse. For a vector with one or two non-undef values, that's 6910 // scalar_to_vector for the elements followed by a shuffle (provided the 6911 // shuffle is valid for the target) and materialization element by element 6912 // on the stack followed by a load for everything else. 6913 if (!isConstant && !usesOnlyOneValue) { 6914 DEBUG(dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 6915 "of INSERT_VECTOR_ELT\n"); 6916 6917 SDValue Vec = DAG.getUNDEF(VT); 6918 SDValue Op0 = Op.getOperand(0); 6919 unsigned i = 0; 6920 6921 // Use SCALAR_TO_VECTOR for lane zero to 6922 // a) Avoid a RMW dependency on the full vector register, and 6923 // b) Allow the register coalescer to fold away the copy if the 6924 // value is already in an S or D register, and we're forced to emit an 6925 // INSERT_SUBREG that we can't fold anywhere. 6926 // 6927 // We also allow types like i8 and i16 which are illegal scalar but legal 6928 // vector element types. After type-legalization the inserted value is 6929 // extended (i32) and it is safe to cast them to the vector type by ignoring 6930 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 6931 if (!Op0.isUndef()) { 6932 DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 6933 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 6934 ++i; 6935 } 6936 DEBUG( 6937 if (i < NumElts) 6938 dbgs() << "Creating nodes for the other vector elements:\n"; 6939 ); 6940 for (; i < NumElts; ++i) { 6941 SDValue V = Op.getOperand(i); 6942 if (V.isUndef()) 6943 continue; 6944 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6945 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6946 } 6947 return Vec; 6948 } 6949 6950 DEBUG(dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 6951 "better alternative\n"); 6952 return SDValue(); 6953 } 6954 6955 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 6956 SelectionDAG &DAG) const { 6957 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 6958 6959 // Check for non-constant or out of range lane. 6960 EVT VT = Op.getOperand(0).getValueType(); 6961 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 6962 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6963 return SDValue(); 6964 6965 6966 // Insertion/extraction are legal for V128 types. 6967 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6968 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6969 VT == MVT::v8f16) 6970 return Op; 6971 6972 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6973 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6974 return SDValue(); 6975 6976 // For V64 types, we perform insertion by expanding the value 6977 // to a V128 type and perform the insertion on that. 6978 SDLoc DL(Op); 6979 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6980 EVT WideTy = WideVec.getValueType(); 6981 6982 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 6983 Op.getOperand(1), Op.getOperand(2)); 6984 // Re-narrow the resultant vector. 6985 return NarrowVector(Node, DAG); 6986 } 6987 6988 SDValue 6989 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6990 SelectionDAG &DAG) const { 6991 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 6992 6993 // Check for non-constant or out of range lane. 6994 EVT VT = Op.getOperand(0).getValueType(); 6995 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6996 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6997 return SDValue(); 6998 6999 7000 // Insertion/extraction are legal for V128 types. 7001 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 7002 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 7003 VT == MVT::v8f16) 7004 return Op; 7005 7006 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 7007 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 7008 return SDValue(); 7009 7010 // For V64 types, we perform extraction by expanding the value 7011 // to a V128 type and perform the extraction on that. 7012 SDLoc DL(Op); 7013 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 7014 EVT WideTy = WideVec.getValueType(); 7015 7016 EVT ExtrTy = WideTy.getVectorElementType(); 7017 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 7018 ExtrTy = MVT::i32; 7019 7020 // For extractions, we just return the result directly. 7021 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 7022 Op.getOperand(1)); 7023 } 7024 7025 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 7026 SelectionDAG &DAG) const { 7027 EVT VT = Op.getOperand(0).getValueType(); 7028 SDLoc dl(Op); 7029 // Just in case... 7030 if (!VT.isVector()) 7031 return SDValue(); 7032 7033 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7034 if (!Cst) 7035 return SDValue(); 7036 unsigned Val = Cst->getZExtValue(); 7037 7038 unsigned Size = Op.getValueSizeInBits(); 7039 7040 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 7041 if (Val == 0) 7042 return Op; 7043 7044 // If this is extracting the upper 64-bits of a 128-bit vector, we match 7045 // that directly. 7046 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) 7047 return Op; 7048 7049 return SDValue(); 7050 } 7051 7052 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7053 if (VT.getVectorNumElements() == 4 && 7054 (VT.is128BitVector() || VT.is64BitVector())) { 7055 unsigned PFIndexes[4]; 7056 for (unsigned i = 0; i != 4; ++i) { 7057 if (M[i] < 0) 7058 PFIndexes[i] = 8; 7059 else 7060 PFIndexes[i] = M[i]; 7061 } 7062 7063 // Compute the index in the perfect shuffle table. 7064 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 7065 PFIndexes[2] * 9 + PFIndexes[3]; 7066 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7067 unsigned Cost = (PFEntry >> 30); 7068 7069 if (Cost <= 4) 7070 return true; 7071 } 7072 7073 bool DummyBool; 7074 int DummyInt; 7075 unsigned DummyUnsigned; 7076 7077 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 7078 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 7079 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 7080 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 7081 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 7082 isZIPMask(M, VT, DummyUnsigned) || 7083 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 7084 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 7085 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 7086 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 7087 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 7088 } 7089 7090 /// getVShiftImm - Check if this is a valid build_vector for the immediate 7091 /// operand of a vector shift operation, where all the elements of the 7092 /// build_vector must have the same constant integer value. 7093 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 7094 // Ignore bit_converts. 7095 while (Op.getOpcode() == ISD::BITCAST) 7096 Op = Op.getOperand(0); 7097 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7098 APInt SplatBits, SplatUndef; 7099 unsigned SplatBitSize; 7100 bool HasAnyUndefs; 7101 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 7102 HasAnyUndefs, ElementBits) || 7103 SplatBitSize > ElementBits) 7104 return false; 7105 Cnt = SplatBits.getSExtValue(); 7106 return true; 7107 } 7108 7109 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 7110 /// operand of a vector shift left operation. That value must be in the range: 7111 /// 0 <= Value < ElementBits for a left shift; or 7112 /// 0 <= Value <= ElementBits for a long left shift. 7113 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 7114 assert(VT.isVector() && "vector shift count is not a vector type"); 7115 int64_t ElementBits = VT.getScalarSizeInBits(); 7116 if (!getVShiftImm(Op, ElementBits, Cnt)) 7117 return false; 7118 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 7119 } 7120 7121 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 7122 /// operand of a vector shift right operation. The value must be in the range: 7123 /// 1 <= Value <= ElementBits for a right shift; or 7124 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 7125 assert(VT.isVector() && "vector shift count is not a vector type"); 7126 int64_t ElementBits = VT.getScalarSizeInBits(); 7127 if (!getVShiftImm(Op, ElementBits, Cnt)) 7128 return false; 7129 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 7130 } 7131 7132 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 7133 SelectionDAG &DAG) const { 7134 EVT VT = Op.getValueType(); 7135 SDLoc DL(Op); 7136 int64_t Cnt; 7137 7138 if (!Op.getOperand(1).getValueType().isVector()) 7139 return Op; 7140 unsigned EltSize = VT.getScalarSizeInBits(); 7141 7142 switch (Op.getOpcode()) { 7143 default: 7144 llvm_unreachable("unexpected shift opcode"); 7145 7146 case ISD::SHL: 7147 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 7148 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 7149 DAG.getConstant(Cnt, DL, MVT::i32)); 7150 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7151 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 7152 MVT::i32), 7153 Op.getOperand(0), Op.getOperand(1)); 7154 case ISD::SRA: 7155 case ISD::SRL: 7156 // Right shift immediate 7157 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 7158 unsigned Opc = 7159 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 7160 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 7161 DAG.getConstant(Cnt, DL, MVT::i32)); 7162 } 7163 7164 // Right shift register. Note, there is not a shift right register 7165 // instruction, but the shift left register instruction takes a signed 7166 // value, where negative numbers specify a right shift. 7167 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 7168 : Intrinsic::aarch64_neon_ushl; 7169 // negate the shift amount 7170 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 7171 SDValue NegShiftLeft = 7172 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7173 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 7174 NegShift); 7175 return NegShiftLeft; 7176 } 7177 7178 return SDValue(); 7179 } 7180 7181 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 7182 AArch64CC::CondCode CC, bool NoNans, EVT VT, 7183 const SDLoc &dl, SelectionDAG &DAG) { 7184 EVT SrcVT = LHS.getValueType(); 7185 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 7186 "function only supposed to emit natural comparisons"); 7187 7188 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 7189 APInt CnstBits(VT.getSizeInBits(), 0); 7190 APInt UndefBits(VT.getSizeInBits(), 0); 7191 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 7192 bool IsZero = IsCnst && (CnstBits == 0); 7193 7194 if (SrcVT.getVectorElementType().isFloatingPoint()) { 7195 switch (CC) { 7196 default: 7197 return SDValue(); 7198 case AArch64CC::NE: { 7199 SDValue Fcmeq; 7200 if (IsZero) 7201 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 7202 else 7203 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 7204 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 7205 } 7206 case AArch64CC::EQ: 7207 if (IsZero) 7208 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 7209 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 7210 case AArch64CC::GE: 7211 if (IsZero) 7212 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 7213 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 7214 case AArch64CC::GT: 7215 if (IsZero) 7216 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 7217 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 7218 case AArch64CC::LS: 7219 if (IsZero) 7220 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 7221 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 7222 case AArch64CC::LT: 7223 if (!NoNans) 7224 return SDValue(); 7225 // If we ignore NaNs then we can use to the MI implementation. 7226 LLVM_FALLTHROUGH; 7227 case AArch64CC::MI: 7228 if (IsZero) 7229 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 7230 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 7231 } 7232 } 7233 7234 switch (CC) { 7235 default: 7236 return SDValue(); 7237 case AArch64CC::NE: { 7238 SDValue Cmeq; 7239 if (IsZero) 7240 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 7241 else 7242 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 7243 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 7244 } 7245 case AArch64CC::EQ: 7246 if (IsZero) 7247 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 7248 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 7249 case AArch64CC::GE: 7250 if (IsZero) 7251 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 7252 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 7253 case AArch64CC::GT: 7254 if (IsZero) 7255 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 7256 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 7257 case AArch64CC::LE: 7258 if (IsZero) 7259 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 7260 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 7261 case AArch64CC::LS: 7262 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 7263 case AArch64CC::LO: 7264 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 7265 case AArch64CC::LT: 7266 if (IsZero) 7267 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 7268 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 7269 case AArch64CC::HI: 7270 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 7271 case AArch64CC::HS: 7272 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 7273 } 7274 } 7275 7276 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 7277 SelectionDAG &DAG) const { 7278 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7279 SDValue LHS = Op.getOperand(0); 7280 SDValue RHS = Op.getOperand(1); 7281 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 7282 SDLoc dl(Op); 7283 7284 if (LHS.getValueType().getVectorElementType().isInteger()) { 7285 assert(LHS.getValueType() == RHS.getValueType()); 7286 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 7287 SDValue Cmp = 7288 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 7289 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 7290 } 7291 7292 if (LHS.getValueType().getVectorElementType() == MVT::f16) 7293 return SDValue(); 7294 7295 assert(LHS.getValueType().getVectorElementType() == MVT::f32 || 7296 LHS.getValueType().getVectorElementType() == MVT::f64); 7297 7298 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 7299 // clean. Some of them require two branches to implement. 7300 AArch64CC::CondCode CC1, CC2; 7301 bool ShouldInvert; 7302 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 7303 7304 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 7305 SDValue Cmp = 7306 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 7307 if (!Cmp.getNode()) 7308 return SDValue(); 7309 7310 if (CC2 != AArch64CC::AL) { 7311 SDValue Cmp2 = 7312 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 7313 if (!Cmp2.getNode()) 7314 return SDValue(); 7315 7316 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 7317 } 7318 7319 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 7320 7321 if (ShouldInvert) 7322 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 7323 7324 return Cmp; 7325 } 7326 7327 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 7328 SelectionDAG &DAG) { 7329 SDValue VecOp = ScalarOp.getOperand(0); 7330 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 7331 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 7332 DAG.getConstant(0, DL, MVT::i64)); 7333 } 7334 7335 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 7336 SelectionDAG &DAG) const { 7337 SDLoc dl(Op); 7338 switch (Op.getOpcode()) { 7339 case ISD::VECREDUCE_ADD: 7340 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 7341 case ISD::VECREDUCE_SMAX: 7342 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 7343 case ISD::VECREDUCE_SMIN: 7344 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 7345 case ISD::VECREDUCE_UMAX: 7346 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 7347 case ISD::VECREDUCE_UMIN: 7348 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 7349 case ISD::VECREDUCE_FMAX: { 7350 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag"); 7351 return DAG.getNode( 7352 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 7353 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 7354 Op.getOperand(0)); 7355 } 7356 case ISD::VECREDUCE_FMIN: { 7357 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag"); 7358 return DAG.getNode( 7359 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 7360 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 7361 Op.getOperand(0)); 7362 } 7363 default: 7364 llvm_unreachable("Unhandled reduction"); 7365 } 7366 } 7367 7368 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 7369 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 7370 /// specified in the intrinsic calls. 7371 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 7372 const CallInst &I, 7373 unsigned Intrinsic) const { 7374 auto &DL = I.getModule()->getDataLayout(); 7375 switch (Intrinsic) { 7376 case Intrinsic::aarch64_neon_ld2: 7377 case Intrinsic::aarch64_neon_ld3: 7378 case Intrinsic::aarch64_neon_ld4: 7379 case Intrinsic::aarch64_neon_ld1x2: 7380 case Intrinsic::aarch64_neon_ld1x3: 7381 case Intrinsic::aarch64_neon_ld1x4: 7382 case Intrinsic::aarch64_neon_ld2lane: 7383 case Intrinsic::aarch64_neon_ld3lane: 7384 case Intrinsic::aarch64_neon_ld4lane: 7385 case Intrinsic::aarch64_neon_ld2r: 7386 case Intrinsic::aarch64_neon_ld3r: 7387 case Intrinsic::aarch64_neon_ld4r: { 7388 Info.opc = ISD::INTRINSIC_W_CHAIN; 7389 // Conservatively set memVT to the entire set of vectors loaded. 7390 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 7391 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 7392 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 7393 Info.offset = 0; 7394 Info.align = 0; 7395 Info.vol = false; // volatile loads with NEON intrinsics not supported 7396 Info.readMem = true; 7397 Info.writeMem = false; 7398 return true; 7399 } 7400 case Intrinsic::aarch64_neon_st2: 7401 case Intrinsic::aarch64_neon_st3: 7402 case Intrinsic::aarch64_neon_st4: 7403 case Intrinsic::aarch64_neon_st1x2: 7404 case Intrinsic::aarch64_neon_st1x3: 7405 case Intrinsic::aarch64_neon_st1x4: 7406 case Intrinsic::aarch64_neon_st2lane: 7407 case Intrinsic::aarch64_neon_st3lane: 7408 case Intrinsic::aarch64_neon_st4lane: { 7409 Info.opc = ISD::INTRINSIC_VOID; 7410 // Conservatively set memVT to the entire set of vectors stored. 7411 unsigned NumElts = 0; 7412 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 7413 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 7414 if (!ArgTy->isVectorTy()) 7415 break; 7416 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 7417 } 7418 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 7419 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 7420 Info.offset = 0; 7421 Info.align = 0; 7422 Info.vol = false; // volatile stores with NEON intrinsics not supported 7423 Info.readMem = false; 7424 Info.writeMem = true; 7425 return true; 7426 } 7427 case Intrinsic::aarch64_ldaxr: 7428 case Intrinsic::aarch64_ldxr: { 7429 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 7430 Info.opc = ISD::INTRINSIC_W_CHAIN; 7431 Info.memVT = MVT::getVT(PtrTy->getElementType()); 7432 Info.ptrVal = I.getArgOperand(0); 7433 Info.offset = 0; 7434 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 7435 Info.vol = true; 7436 Info.readMem = true; 7437 Info.writeMem = false; 7438 return true; 7439 } 7440 case Intrinsic::aarch64_stlxr: 7441 case Intrinsic::aarch64_stxr: { 7442 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 7443 Info.opc = ISD::INTRINSIC_W_CHAIN; 7444 Info.memVT = MVT::getVT(PtrTy->getElementType()); 7445 Info.ptrVal = I.getArgOperand(1); 7446 Info.offset = 0; 7447 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 7448 Info.vol = true; 7449 Info.readMem = false; 7450 Info.writeMem = true; 7451 return true; 7452 } 7453 case Intrinsic::aarch64_ldaxp: 7454 case Intrinsic::aarch64_ldxp: 7455 Info.opc = ISD::INTRINSIC_W_CHAIN; 7456 Info.memVT = MVT::i128; 7457 Info.ptrVal = I.getArgOperand(0); 7458 Info.offset = 0; 7459 Info.align = 16; 7460 Info.vol = true; 7461 Info.readMem = true; 7462 Info.writeMem = false; 7463 return true; 7464 case Intrinsic::aarch64_stlxp: 7465 case Intrinsic::aarch64_stxp: 7466 Info.opc = ISD::INTRINSIC_W_CHAIN; 7467 Info.memVT = MVT::i128; 7468 Info.ptrVal = I.getArgOperand(2); 7469 Info.offset = 0; 7470 Info.align = 16; 7471 Info.vol = true; 7472 Info.readMem = false; 7473 Info.writeMem = true; 7474 return true; 7475 default: 7476 break; 7477 } 7478 7479 return false; 7480 } 7481 7482 // Truncations from 64-bit GPR to 32-bit GPR is free. 7483 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 7484 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7485 return false; 7486 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7487 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7488 return NumBits1 > NumBits2; 7489 } 7490 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 7491 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7492 return false; 7493 unsigned NumBits1 = VT1.getSizeInBits(); 7494 unsigned NumBits2 = VT2.getSizeInBits(); 7495 return NumBits1 > NumBits2; 7496 } 7497 7498 /// Check if it is profitable to hoist instruction in then/else to if. 7499 /// Not profitable if I and it's user can form a FMA instruction 7500 /// because we prefer FMSUB/FMADD. 7501 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 7502 if (I->getOpcode() != Instruction::FMul) 7503 return true; 7504 7505 if (!I->hasOneUse()) 7506 return true; 7507 7508 Instruction *User = I->user_back(); 7509 7510 if (User && 7511 !(User->getOpcode() == Instruction::FSub || 7512 User->getOpcode() == Instruction::FAdd)) 7513 return true; 7514 7515 const TargetOptions &Options = getTargetMachine().Options; 7516 const DataLayout &DL = I->getModule()->getDataLayout(); 7517 EVT VT = getValueType(DL, User->getOperand(0)->getType()); 7518 7519 return !(isFMAFasterThanFMulAndFAdd(VT) && 7520 isOperationLegalOrCustom(ISD::FMA, VT) && 7521 (Options.AllowFPOpFusion == FPOpFusion::Fast || 7522 Options.UnsafeFPMath)); 7523 } 7524 7525 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 7526 // 64-bit GPR. 7527 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 7528 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7529 return false; 7530 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7531 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7532 return NumBits1 == 32 && NumBits2 == 64; 7533 } 7534 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 7535 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7536 return false; 7537 unsigned NumBits1 = VT1.getSizeInBits(); 7538 unsigned NumBits2 = VT2.getSizeInBits(); 7539 return NumBits1 == 32 && NumBits2 == 64; 7540 } 7541 7542 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 7543 EVT VT1 = Val.getValueType(); 7544 if (isZExtFree(VT1, VT2)) { 7545 return true; 7546 } 7547 7548 if (Val.getOpcode() != ISD::LOAD) 7549 return false; 7550 7551 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 7552 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 7553 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 7554 VT1.getSizeInBits() <= 32); 7555 } 7556 7557 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 7558 if (isa<FPExtInst>(Ext)) 7559 return false; 7560 7561 // Vector types are not free. 7562 if (Ext->getType()->isVectorTy()) 7563 return false; 7564 7565 for (const Use &U : Ext->uses()) { 7566 // The extension is free if we can fold it with a left shift in an 7567 // addressing mode or an arithmetic operation: add, sub, and cmp. 7568 7569 // Is there a shift? 7570 const Instruction *Instr = cast<Instruction>(U.getUser()); 7571 7572 // Is this a constant shift? 7573 switch (Instr->getOpcode()) { 7574 case Instruction::Shl: 7575 if (!isa<ConstantInt>(Instr->getOperand(1))) 7576 return false; 7577 break; 7578 case Instruction::GetElementPtr: { 7579 gep_type_iterator GTI = gep_type_begin(Instr); 7580 auto &DL = Ext->getModule()->getDataLayout(); 7581 std::advance(GTI, U.getOperandNo()-1); 7582 Type *IdxTy = GTI.getIndexedType(); 7583 // This extension will end up with a shift because of the scaling factor. 7584 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 7585 // Get the shift amount based on the scaling factor: 7586 // log2(sizeof(IdxTy)) - log2(8). 7587 uint64_t ShiftAmt = 7588 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3; 7589 // Is the constant foldable in the shift of the addressing mode? 7590 // I.e., shift amount is between 1 and 4 inclusive. 7591 if (ShiftAmt == 0 || ShiftAmt > 4) 7592 return false; 7593 break; 7594 } 7595 case Instruction::Trunc: 7596 // Check if this is a noop. 7597 // trunc(sext ty1 to ty2) to ty1. 7598 if (Instr->getType() == Ext->getOperand(0)->getType()) 7599 continue; 7600 LLVM_FALLTHROUGH; 7601 default: 7602 return false; 7603 } 7604 7605 // At this point we can use the bfm family, so this extension is free 7606 // for that use. 7607 } 7608 return true; 7609 } 7610 7611 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 7612 unsigned &RequiredAligment) const { 7613 if (!LoadedType.isSimple() || 7614 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 7615 return false; 7616 // Cyclone supports unaligned accesses. 7617 RequiredAligment = 0; 7618 unsigned NumBits = LoadedType.getSizeInBits(); 7619 return NumBits == 32 || NumBits == 64; 7620 } 7621 7622 /// A helper function for determining the number of interleaved accesses we 7623 /// will generate when lowering accesses of the given type. 7624 unsigned 7625 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 7626 const DataLayout &DL) const { 7627 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 7628 } 7629 7630 MachineMemOperand::Flags 7631 AArch64TargetLowering::getMMOFlags(const Instruction &I) const { 7632 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 7633 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 7634 return MOStridedAccess; 7635 return MachineMemOperand::MONone; 7636 } 7637 7638 bool AArch64TargetLowering::isLegalInterleavedAccessType( 7639 VectorType *VecTy, const DataLayout &DL) const { 7640 7641 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 7642 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 7643 7644 // Ensure the number of vector elements is greater than 1. 7645 if (VecTy->getNumElements() < 2) 7646 return false; 7647 7648 // Ensure the element type is legal. 7649 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 7650 return false; 7651 7652 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 7653 // 128 will be split into multiple interleaved accesses. 7654 return VecSize == 64 || VecSize % 128 == 0; 7655 } 7656 7657 /// \brief Lower an interleaved load into a ldN intrinsic. 7658 /// 7659 /// E.g. Lower an interleaved load (Factor = 2): 7660 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 7661 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 7662 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 7663 /// 7664 /// Into: 7665 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 7666 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 7667 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 7668 bool AArch64TargetLowering::lowerInterleavedLoad( 7669 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 7670 ArrayRef<unsigned> Indices, unsigned Factor) const { 7671 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7672 "Invalid interleave factor"); 7673 assert(!Shuffles.empty() && "Empty shufflevector input"); 7674 assert(Shuffles.size() == Indices.size() && 7675 "Unmatched number of shufflevectors and indices"); 7676 7677 const DataLayout &DL = LI->getModule()->getDataLayout(); 7678 7679 VectorType *VecTy = Shuffles[0]->getType(); 7680 7681 // Skip if we do not have NEON and skip illegal vector types. We can 7682 // "legalize" wide vector types into multiple interleaved accesses as long as 7683 // the vector types are divisible by 128. 7684 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 7685 return false; 7686 7687 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 7688 7689 // A pointer vector can not be the return type of the ldN intrinsics. Need to 7690 // load integer vectors first and then convert to pointer vectors. 7691 Type *EltTy = VecTy->getVectorElementType(); 7692 if (EltTy->isPointerTy()) 7693 VecTy = 7694 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 7695 7696 IRBuilder<> Builder(LI); 7697 7698 // The base address of the load. 7699 Value *BaseAddr = LI->getPointerOperand(); 7700 7701 if (NumLoads > 1) { 7702 // If we're going to generate more than one load, reset the sub-vector type 7703 // to something legal. 7704 VecTy = VectorType::get(VecTy->getVectorElementType(), 7705 VecTy->getVectorNumElements() / NumLoads); 7706 7707 // We will compute the pointer operand of each load from the original base 7708 // address using GEPs. Cast the base address to a pointer to the scalar 7709 // element type. 7710 BaseAddr = Builder.CreateBitCast( 7711 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 7712 LI->getPointerAddressSpace())); 7713 } 7714 7715 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 7716 Type *Tys[2] = {VecTy, PtrTy}; 7717 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 7718 Intrinsic::aarch64_neon_ld3, 7719 Intrinsic::aarch64_neon_ld4}; 7720 Function *LdNFunc = 7721 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 7722 7723 // Holds sub-vectors extracted from the load intrinsic return values. The 7724 // sub-vectors are associated with the shufflevector instructions they will 7725 // replace. 7726 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 7727 7728 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 7729 7730 // If we're generating more than one load, compute the base address of 7731 // subsequent loads as an offset from the previous. 7732 if (LoadCount > 0) 7733 BaseAddr = Builder.CreateConstGEP1_32( 7734 BaseAddr, VecTy->getVectorNumElements() * Factor); 7735 7736 CallInst *LdN = Builder.CreateCall( 7737 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 7738 7739 // Extract and store the sub-vectors returned by the load intrinsic. 7740 for (unsigned i = 0; i < Shuffles.size(); i++) { 7741 ShuffleVectorInst *SVI = Shuffles[i]; 7742 unsigned Index = Indices[i]; 7743 7744 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 7745 7746 // Convert the integer vector to pointer vector if the element is pointer. 7747 if (EltTy->isPointerTy()) 7748 SubVec = Builder.CreateIntToPtr( 7749 SubVec, VectorType::get(SVI->getType()->getVectorElementType(), 7750 VecTy->getVectorNumElements())); 7751 SubVecs[SVI].push_back(SubVec); 7752 } 7753 } 7754 7755 // Replace uses of the shufflevector instructions with the sub-vectors 7756 // returned by the load intrinsic. If a shufflevector instruction is 7757 // associated with more than one sub-vector, those sub-vectors will be 7758 // concatenated into a single wide vector. 7759 for (ShuffleVectorInst *SVI : Shuffles) { 7760 auto &SubVec = SubVecs[SVI]; 7761 auto *WideVec = 7762 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 7763 SVI->replaceAllUsesWith(WideVec); 7764 } 7765 7766 return true; 7767 } 7768 7769 /// \brief Lower an interleaved store into a stN intrinsic. 7770 /// 7771 /// E.g. Lower an interleaved store (Factor = 3): 7772 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 7773 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 7774 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7775 /// 7776 /// Into: 7777 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 7778 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 7779 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 7780 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7781 /// 7782 /// Note that the new shufflevectors will be removed and we'll only generate one 7783 /// st3 instruction in CodeGen. 7784 /// 7785 /// Example for a more general valid mask (Factor 3). Lower: 7786 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 7787 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 7788 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7789 /// 7790 /// Into: 7791 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 7792 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 7793 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 7794 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7795 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 7796 ShuffleVectorInst *SVI, 7797 unsigned Factor) const { 7798 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7799 "Invalid interleave factor"); 7800 7801 VectorType *VecTy = SVI->getType(); 7802 assert(VecTy->getVectorNumElements() % Factor == 0 && 7803 "Invalid interleaved store"); 7804 7805 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 7806 Type *EltTy = VecTy->getVectorElementType(); 7807 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 7808 7809 const DataLayout &DL = SI->getModule()->getDataLayout(); 7810 7811 // Skip if we do not have NEON and skip illegal vector types. We can 7812 // "legalize" wide vector types into multiple interleaved accesses as long as 7813 // the vector types are divisible by 128. 7814 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 7815 return false; 7816 7817 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 7818 7819 Value *Op0 = SVI->getOperand(0); 7820 Value *Op1 = SVI->getOperand(1); 7821 IRBuilder<> Builder(SI); 7822 7823 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 7824 // vectors to integer vectors. 7825 if (EltTy->isPointerTy()) { 7826 Type *IntTy = DL.getIntPtrType(EltTy); 7827 unsigned NumOpElts = 7828 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements(); 7829 7830 // Convert to the corresponding integer vector. 7831 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 7832 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 7833 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 7834 7835 SubVecTy = VectorType::get(IntTy, LaneLen); 7836 } 7837 7838 // The base address of the store. 7839 Value *BaseAddr = SI->getPointerOperand(); 7840 7841 if (NumStores > 1) { 7842 // If we're going to generate more than one store, reset the lane length 7843 // and sub-vector type to something legal. 7844 LaneLen /= NumStores; 7845 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 7846 7847 // We will compute the pointer operand of each store from the original base 7848 // address using GEPs. Cast the base address to a pointer to the scalar 7849 // element type. 7850 BaseAddr = Builder.CreateBitCast( 7851 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 7852 SI->getPointerAddressSpace())); 7853 } 7854 7855 auto Mask = SVI->getShuffleMask(); 7856 7857 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 7858 Type *Tys[2] = {SubVecTy, PtrTy}; 7859 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 7860 Intrinsic::aarch64_neon_st3, 7861 Intrinsic::aarch64_neon_st4}; 7862 Function *StNFunc = 7863 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 7864 7865 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 7866 7867 SmallVector<Value *, 5> Ops; 7868 7869 // Split the shufflevector operands into sub vectors for the new stN call. 7870 for (unsigned i = 0; i < Factor; i++) { 7871 unsigned IdxI = StoreCount * LaneLen * Factor + i; 7872 if (Mask[IdxI] >= 0) { 7873 Ops.push_back(Builder.CreateShuffleVector( 7874 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 7875 } else { 7876 unsigned StartMask = 0; 7877 for (unsigned j = 1; j < LaneLen; j++) { 7878 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 7879 if (Mask[IdxJ * Factor + IdxI] >= 0) { 7880 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 7881 break; 7882 } 7883 } 7884 // Note: Filling undef gaps with random elements is ok, since 7885 // those elements were being written anyway (with undefs). 7886 // In the case of all undefs we're defaulting to using elems from 0 7887 // Note: StartMask cannot be negative, it's checked in 7888 // isReInterleaveMask 7889 Ops.push_back(Builder.CreateShuffleVector( 7890 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 7891 } 7892 } 7893 7894 // If we generating more than one store, we compute the base address of 7895 // subsequent stores as an offset from the previous. 7896 if (StoreCount > 0) 7897 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 7898 7899 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 7900 Builder.CreateCall(StNFunc, Ops); 7901 } 7902 return true; 7903 } 7904 7905 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 7906 unsigned AlignCheck) { 7907 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 7908 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 7909 } 7910 7911 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 7912 unsigned SrcAlign, bool IsMemset, 7913 bool ZeroMemset, 7914 bool MemcpyStrSrc, 7915 MachineFunction &MF) const { 7916 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one 7917 // instruction to materialize the v2i64 zero and one store (with restrictive 7918 // addressing mode). Just do two i64 store of zero-registers. 7919 bool Fast; 7920 const Function *F = MF.getFunction(); 7921 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 && 7922 !F->hasFnAttribute(Attribute::NoImplicitFloat) && 7923 (memOpAlign(SrcAlign, DstAlign, 16) || 7924 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast))) 7925 return MVT::f128; 7926 7927 if (Size >= 8 && 7928 (memOpAlign(SrcAlign, DstAlign, 8) || 7929 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast))) 7930 return MVT::i64; 7931 7932 if (Size >= 4 && 7933 (memOpAlign(SrcAlign, DstAlign, 4) || 7934 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast))) 7935 return MVT::i32; 7936 7937 return MVT::Other; 7938 } 7939 7940 // 12-bit optionally shifted immediates are legal for adds. 7941 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 7942 if (Immed == std::numeric_limits<int64_t>::min()) { 7943 DEBUG(dbgs() << "Illegal add imm " << Immed << ": avoid UB for INT64_MIN\n"); 7944 return false; 7945 } 7946 // Same encoding for add/sub, just flip the sign. 7947 Immed = std::abs(Immed); 7948 bool IsLegal = ((Immed >> 12) == 0 || 7949 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 7950 DEBUG(dbgs() << "Is " << Immed << " legal add imm: " << 7951 (IsLegal ? "yes" : "no") << "\n"); 7952 return IsLegal; 7953 } 7954 7955 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 7956 // immediates is the same as for an add or a sub. 7957 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 7958 return isLegalAddImmediate(Immed); 7959 } 7960 7961 /// isLegalAddressingMode - Return true if the addressing mode represented 7962 /// by AM is legal for this target, for a load/store of the specified type. 7963 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 7964 const AddrMode &AM, Type *Ty, 7965 unsigned AS, Instruction *I) const { 7966 // AArch64 has five basic addressing modes: 7967 // reg 7968 // reg + 9-bit signed offset 7969 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 7970 // reg1 + reg2 7971 // reg + SIZE_IN_BYTES * reg 7972 7973 // No global is ever allowed as a base. 7974 if (AM.BaseGV) 7975 return false; 7976 7977 // No reg+reg+imm addressing. 7978 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 7979 return false; 7980 7981 // check reg + imm case: 7982 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 7983 uint64_t NumBytes = 0; 7984 if (Ty->isSized()) { 7985 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 7986 NumBytes = NumBits / 8; 7987 if (!isPowerOf2_64(NumBits)) 7988 NumBytes = 0; 7989 } 7990 7991 if (!AM.Scale) { 7992 int64_t Offset = AM.BaseOffs; 7993 7994 // 9-bit signed offset 7995 if (isInt<9>(Offset)) 7996 return true; 7997 7998 // 12-bit unsigned offset 7999 unsigned shift = Log2_64(NumBytes); 8000 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 8001 // Must be a multiple of NumBytes (NumBytes is a power of 2) 8002 (Offset >> shift) << shift == Offset) 8003 return true; 8004 return false; 8005 } 8006 8007 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 8008 8009 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 8010 } 8011 8012 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 8013 const AddrMode &AM, Type *Ty, 8014 unsigned AS) const { 8015 // Scaling factors are not free at all. 8016 // Operands | Rt Latency 8017 // ------------------------------------------- 8018 // Rt, [Xn, Xm] | 4 8019 // ------------------------------------------- 8020 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 8021 // Rt, [Xn, Wm, <extend> #imm] | 8022 if (isLegalAddressingMode(DL, AM, Ty, AS)) 8023 // Scale represents reg2 * scale, thus account for 1 if 8024 // it is not equal to 0 or 1. 8025 return AM.Scale != 0 && AM.Scale != 1; 8026 return -1; 8027 } 8028 8029 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 8030 VT = VT.getScalarType(); 8031 8032 if (!VT.isSimple()) 8033 return false; 8034 8035 switch (VT.getSimpleVT().SimpleTy) { 8036 case MVT::f32: 8037 case MVT::f64: 8038 return true; 8039 default: 8040 break; 8041 } 8042 8043 return false; 8044 } 8045 8046 const MCPhysReg * 8047 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 8048 // LR is a callee-save register, but we must treat it as clobbered by any call 8049 // site. Hence we include LR in the scratch registers, which are in turn added 8050 // as implicit-defs for stackmaps and patchpoints. 8051 static const MCPhysReg ScratchRegs[] = { 8052 AArch64::X16, AArch64::X17, AArch64::LR, 0 8053 }; 8054 return ScratchRegs; 8055 } 8056 8057 bool 8058 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const { 8059 EVT VT = N->getValueType(0); 8060 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 8061 // it with shift to let it be lowered to UBFX. 8062 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 8063 isa<ConstantSDNode>(N->getOperand(1))) { 8064 uint64_t TruncMask = N->getConstantOperandVal(1); 8065 if (isMask_64(TruncMask) && 8066 N->getOperand(0).getOpcode() == ISD::SRL && 8067 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 8068 return false; 8069 } 8070 return true; 8071 } 8072 8073 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 8074 Type *Ty) const { 8075 assert(Ty->isIntegerTy()); 8076 8077 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 8078 if (BitSize == 0) 8079 return false; 8080 8081 int64_t Val = Imm.getSExtValue(); 8082 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 8083 return true; 8084 8085 if ((int64_t)Val < 0) 8086 Val = ~Val; 8087 if (BitSize == 32) 8088 Val &= (1LL << 32) - 1; 8089 8090 unsigned LZ = countLeadingZeros((uint64_t)Val); 8091 unsigned Shift = (63 - LZ) / 16; 8092 // MOVZ is free so return true for one or fewer MOVK. 8093 return Shift < 3; 8094 } 8095 8096 /// Turn vector tests of the signbit in the form of: 8097 /// xor (sra X, elt_size(X)-1), -1 8098 /// into: 8099 /// cmge X, X, #0 8100 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 8101 const AArch64Subtarget *Subtarget) { 8102 EVT VT = N->getValueType(0); 8103 if (!Subtarget->hasNEON() || !VT.isVector()) 8104 return SDValue(); 8105 8106 // There must be a shift right algebraic before the xor, and the xor must be a 8107 // 'not' operation. 8108 SDValue Shift = N->getOperand(0); 8109 SDValue Ones = N->getOperand(1); 8110 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 8111 !ISD::isBuildVectorAllOnes(Ones.getNode())) 8112 return SDValue(); 8113 8114 // The shift should be smearing the sign bit across each vector element. 8115 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 8116 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 8117 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 8118 return SDValue(); 8119 8120 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 8121 } 8122 8123 // Generate SUBS and CSEL for integer abs. 8124 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 8125 EVT VT = N->getValueType(0); 8126 8127 SDValue N0 = N->getOperand(0); 8128 SDValue N1 = N->getOperand(1); 8129 SDLoc DL(N); 8130 8131 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 8132 // and change it to SUB and CSEL. 8133 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 8134 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 8135 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 8136 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 8137 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 8138 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 8139 N0.getOperand(0)); 8140 // Generate SUBS & CSEL. 8141 SDValue Cmp = 8142 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 8143 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 8144 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 8145 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 8146 SDValue(Cmp.getNode(), 1)); 8147 } 8148 return SDValue(); 8149 } 8150 8151 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 8152 TargetLowering::DAGCombinerInfo &DCI, 8153 const AArch64Subtarget *Subtarget) { 8154 if (DCI.isBeforeLegalizeOps()) 8155 return SDValue(); 8156 8157 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 8158 return Cmp; 8159 8160 return performIntegerAbsCombine(N, DAG); 8161 } 8162 8163 SDValue 8164 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8165 SelectionDAG &DAG, 8166 std::vector<SDNode *> *Created) const { 8167 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 8168 if (isIntDivCheap(N->getValueType(0), Attr)) 8169 return SDValue(N,0); // Lower SDIV as SDIV 8170 8171 // fold (sdiv X, pow2) 8172 EVT VT = N->getValueType(0); 8173 if ((VT != MVT::i32 && VT != MVT::i64) || 8174 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 8175 return SDValue(); 8176 8177 SDLoc DL(N); 8178 SDValue N0 = N->getOperand(0); 8179 unsigned Lg2 = Divisor.countTrailingZeros(); 8180 SDValue Zero = DAG.getConstant(0, DL, VT); 8181 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 8182 8183 // Add (N0 < 0) ? Pow2 - 1 : 0; 8184 SDValue CCVal; 8185 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 8186 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 8187 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 8188 8189 if (Created) { 8190 Created->push_back(Cmp.getNode()); 8191 Created->push_back(Add.getNode()); 8192 Created->push_back(CSel.getNode()); 8193 } 8194 8195 // Divide by pow2. 8196 SDValue SRA = 8197 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 8198 8199 // If we're dividing by a positive value, we're done. Otherwise, we must 8200 // negate the result. 8201 if (Divisor.isNonNegative()) 8202 return SRA; 8203 8204 if (Created) 8205 Created->push_back(SRA.getNode()); 8206 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 8207 } 8208 8209 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 8210 TargetLowering::DAGCombinerInfo &DCI, 8211 const AArch64Subtarget *Subtarget) { 8212 if (DCI.isBeforeLegalizeOps()) 8213 return SDValue(); 8214 8215 // The below optimizations require a constant RHS. 8216 if (!isa<ConstantSDNode>(N->getOperand(1))) 8217 return SDValue(); 8218 8219 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 8220 const APInt &ConstValue = C->getAPIntValue(); 8221 8222 // Multiplication of a power of two plus/minus one can be done more 8223 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 8224 // future CPUs have a cheaper MADD instruction, this may need to be 8225 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 8226 // 64-bit is 5 cycles, so this is always a win. 8227 // More aggressively, some multiplications N0 * C can be lowered to 8228 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 8229 // e.g. 6=3*2=(2+1)*2. 8230 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 8231 // which equals to (1+2)*16-(1+2). 8232 SDValue N0 = N->getOperand(0); 8233 // TrailingZeroes is used to test if the mul can be lowered to 8234 // shift+add+shift. 8235 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 8236 if (TrailingZeroes) { 8237 // Conservatively do not lower to shift+add+shift if the mul might be 8238 // folded into smul or umul. 8239 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 8240 isZeroExtended(N0.getNode(), DAG))) 8241 return SDValue(); 8242 // Conservatively do not lower to shift+add+shift if the mul might be 8243 // folded into madd or msub. 8244 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 8245 N->use_begin()->getOpcode() == ISD::SUB)) 8246 return SDValue(); 8247 } 8248 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 8249 // and shift+add+shift. 8250 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 8251 8252 unsigned ShiftAmt, AddSubOpc; 8253 // Is the shifted value the LHS operand of the add/sub? 8254 bool ShiftValUseIsN0 = true; 8255 // Do we need to negate the result? 8256 bool NegateResult = false; 8257 8258 if (ConstValue.isNonNegative()) { 8259 // (mul x, 2^N + 1) => (add (shl x, N), x) 8260 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8261 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 8262 APInt SCVMinus1 = ShiftedConstValue - 1; 8263 APInt CVPlus1 = ConstValue + 1; 8264 if (SCVMinus1.isPowerOf2()) { 8265 ShiftAmt = SCVMinus1.logBase2(); 8266 AddSubOpc = ISD::ADD; 8267 } else if (CVPlus1.isPowerOf2()) { 8268 ShiftAmt = CVPlus1.logBase2(); 8269 AddSubOpc = ISD::SUB; 8270 } else 8271 return SDValue(); 8272 } else { 8273 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8274 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8275 APInt CVNegPlus1 = -ConstValue + 1; 8276 APInt CVNegMinus1 = -ConstValue - 1; 8277 if (CVNegPlus1.isPowerOf2()) { 8278 ShiftAmt = CVNegPlus1.logBase2(); 8279 AddSubOpc = ISD::SUB; 8280 ShiftValUseIsN0 = false; 8281 } else if (CVNegMinus1.isPowerOf2()) { 8282 ShiftAmt = CVNegMinus1.logBase2(); 8283 AddSubOpc = ISD::ADD; 8284 NegateResult = true; 8285 } else 8286 return SDValue(); 8287 } 8288 8289 SDLoc DL(N); 8290 EVT VT = N->getValueType(0); 8291 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 8292 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 8293 8294 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 8295 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 8296 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 8297 assert(!(NegateResult && TrailingZeroes) && 8298 "NegateResult and TrailingZeroes cannot both be true for now."); 8299 // Negate the result. 8300 if (NegateResult) 8301 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 8302 // Shift the result. 8303 if (TrailingZeroes) 8304 return DAG.getNode(ISD::SHL, DL, VT, Res, 8305 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 8306 return Res; 8307 } 8308 8309 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 8310 SelectionDAG &DAG) { 8311 // Take advantage of vector comparisons producing 0 or -1 in each lane to 8312 // optimize away operation when it's from a constant. 8313 // 8314 // The general transformation is: 8315 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 8316 // AND(VECTOR_CMP(x,y), constant2) 8317 // constant2 = UNARYOP(constant) 8318 8319 // Early exit if this isn't a vector operation, the operand of the 8320 // unary operation isn't a bitwise AND, or if the sizes of the operations 8321 // aren't the same. 8322 EVT VT = N->getValueType(0); 8323 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 8324 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 8325 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 8326 return SDValue(); 8327 8328 // Now check that the other operand of the AND is a constant. We could 8329 // make the transformation for non-constant splats as well, but it's unclear 8330 // that would be a benefit as it would not eliminate any operations, just 8331 // perform one more step in scalar code before moving to the vector unit. 8332 if (BuildVectorSDNode *BV = 8333 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 8334 // Bail out if the vector isn't a constant. 8335 if (!BV->isConstant()) 8336 return SDValue(); 8337 8338 // Everything checks out. Build up the new and improved node. 8339 SDLoc DL(N); 8340 EVT IntVT = BV->getValueType(0); 8341 // Create a new constant of the appropriate type for the transformed 8342 // DAG. 8343 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 8344 // The AND node needs bitcasts to/from an integer vector type around it. 8345 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 8346 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 8347 N->getOperand(0)->getOperand(0), MaskConst); 8348 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 8349 return Res; 8350 } 8351 8352 return SDValue(); 8353 } 8354 8355 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 8356 const AArch64Subtarget *Subtarget) { 8357 // First try to optimize away the conversion when it's conditionally from 8358 // a constant. Vectors only. 8359 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 8360 return Res; 8361 8362 EVT VT = N->getValueType(0); 8363 if (VT != MVT::f32 && VT != MVT::f64) 8364 return SDValue(); 8365 8366 // Only optimize when the source and destination types have the same width. 8367 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 8368 return SDValue(); 8369 8370 // If the result of an integer load is only used by an integer-to-float 8371 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 8372 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 8373 SDValue N0 = N->getOperand(0); 8374 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8375 // Do not change the width of a volatile load. 8376 !cast<LoadSDNode>(N0)->isVolatile()) { 8377 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8378 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8379 LN0->getPointerInfo(), LN0->getAlignment(), 8380 LN0->getMemOperand()->getFlags()); 8381 8382 // Make sure successors of the original load stay after it by updating them 8383 // to use the new Chain. 8384 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 8385 8386 unsigned Opcode = 8387 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 8388 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 8389 } 8390 8391 return SDValue(); 8392 } 8393 8394 /// Fold a floating-point multiply by power of two into floating-point to 8395 /// fixed-point conversion. 8396 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 8397 TargetLowering::DAGCombinerInfo &DCI, 8398 const AArch64Subtarget *Subtarget) { 8399 if (!Subtarget->hasNEON()) 8400 return SDValue(); 8401 8402 SDValue Op = N->getOperand(0); 8403 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 8404 Op.getOpcode() != ISD::FMUL) 8405 return SDValue(); 8406 8407 SDValue ConstVec = Op->getOperand(1); 8408 if (!isa<BuildVectorSDNode>(ConstVec)) 8409 return SDValue(); 8410 8411 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 8412 uint32_t FloatBits = FloatTy.getSizeInBits(); 8413 if (FloatBits != 32 && FloatBits != 64) 8414 return SDValue(); 8415 8416 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 8417 uint32_t IntBits = IntTy.getSizeInBits(); 8418 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 8419 return SDValue(); 8420 8421 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 8422 if (IntBits > FloatBits) 8423 return SDValue(); 8424 8425 BitVector UndefElements; 8426 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 8427 int32_t Bits = IntBits == 64 ? 64 : 32; 8428 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 8429 if (C == -1 || C == 0 || C > Bits) 8430 return SDValue(); 8431 8432 MVT ResTy; 8433 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 8434 switch (NumLanes) { 8435 default: 8436 return SDValue(); 8437 case 2: 8438 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 8439 break; 8440 case 4: 8441 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 8442 break; 8443 } 8444 8445 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 8446 return SDValue(); 8447 8448 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 8449 "Illegal vector type after legalization"); 8450 8451 SDLoc DL(N); 8452 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8453 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 8454 : Intrinsic::aarch64_neon_vcvtfp2fxu; 8455 SDValue FixConv = 8456 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 8457 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 8458 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 8459 // We can handle smaller integers by generating an extra trunc. 8460 if (IntBits < FloatBits) 8461 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 8462 8463 return FixConv; 8464 } 8465 8466 /// Fold a floating-point divide by power of two into fixed-point to 8467 /// floating-point conversion. 8468 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 8469 TargetLowering::DAGCombinerInfo &DCI, 8470 const AArch64Subtarget *Subtarget) { 8471 if (!Subtarget->hasNEON()) 8472 return SDValue(); 8473 8474 SDValue Op = N->getOperand(0); 8475 unsigned Opc = Op->getOpcode(); 8476 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 8477 !Op.getOperand(0).getValueType().isSimple() || 8478 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 8479 return SDValue(); 8480 8481 SDValue ConstVec = N->getOperand(1); 8482 if (!isa<BuildVectorSDNode>(ConstVec)) 8483 return SDValue(); 8484 8485 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 8486 int32_t IntBits = IntTy.getSizeInBits(); 8487 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 8488 return SDValue(); 8489 8490 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 8491 int32_t FloatBits = FloatTy.getSizeInBits(); 8492 if (FloatBits != 32 && FloatBits != 64) 8493 return SDValue(); 8494 8495 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 8496 if (IntBits > FloatBits) 8497 return SDValue(); 8498 8499 BitVector UndefElements; 8500 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 8501 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 8502 if (C == -1 || C == 0 || C > FloatBits) 8503 return SDValue(); 8504 8505 MVT ResTy; 8506 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 8507 switch (NumLanes) { 8508 default: 8509 return SDValue(); 8510 case 2: 8511 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 8512 break; 8513 case 4: 8514 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 8515 break; 8516 } 8517 8518 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 8519 return SDValue(); 8520 8521 SDLoc DL(N); 8522 SDValue ConvInput = Op.getOperand(0); 8523 bool IsSigned = Opc == ISD::SINT_TO_FP; 8524 if (IntBits < FloatBits) 8525 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 8526 ResTy, ConvInput); 8527 8528 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 8529 : Intrinsic::aarch64_neon_vcvtfxu2fp; 8530 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 8531 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 8532 DAG.getConstant(C, DL, MVT::i32)); 8533 } 8534 8535 /// An EXTR instruction is made up of two shifts, ORed together. This helper 8536 /// searches for and classifies those shifts. 8537 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 8538 bool &FromHi) { 8539 if (N.getOpcode() == ISD::SHL) 8540 FromHi = false; 8541 else if (N.getOpcode() == ISD::SRL) 8542 FromHi = true; 8543 else 8544 return false; 8545 8546 if (!isa<ConstantSDNode>(N.getOperand(1))) 8547 return false; 8548 8549 ShiftAmount = N->getConstantOperandVal(1); 8550 Src = N->getOperand(0); 8551 return true; 8552 } 8553 8554 /// EXTR instruction extracts a contiguous chunk of bits from two existing 8555 /// registers viewed as a high/low pair. This function looks for the pattern: 8556 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 8557 /// with an EXTR. Can't quite be done in TableGen because the two immediates 8558 /// aren't independent. 8559 static SDValue tryCombineToEXTR(SDNode *N, 8560 TargetLowering::DAGCombinerInfo &DCI) { 8561 SelectionDAG &DAG = DCI.DAG; 8562 SDLoc DL(N); 8563 EVT VT = N->getValueType(0); 8564 8565 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 8566 8567 if (VT != MVT::i32 && VT != MVT::i64) 8568 return SDValue(); 8569 8570 SDValue LHS; 8571 uint32_t ShiftLHS = 0; 8572 bool LHSFromHi = false; 8573 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 8574 return SDValue(); 8575 8576 SDValue RHS; 8577 uint32_t ShiftRHS = 0; 8578 bool RHSFromHi = false; 8579 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 8580 return SDValue(); 8581 8582 // If they're both trying to come from the high part of the register, they're 8583 // not really an EXTR. 8584 if (LHSFromHi == RHSFromHi) 8585 return SDValue(); 8586 8587 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 8588 return SDValue(); 8589 8590 if (LHSFromHi) { 8591 std::swap(LHS, RHS); 8592 std::swap(ShiftLHS, ShiftRHS); 8593 } 8594 8595 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 8596 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 8597 } 8598 8599 static SDValue tryCombineToBSL(SDNode *N, 8600 TargetLowering::DAGCombinerInfo &DCI) { 8601 EVT VT = N->getValueType(0); 8602 SelectionDAG &DAG = DCI.DAG; 8603 SDLoc DL(N); 8604 8605 if (!VT.isVector()) 8606 return SDValue(); 8607 8608 SDValue N0 = N->getOperand(0); 8609 if (N0.getOpcode() != ISD::AND) 8610 return SDValue(); 8611 8612 SDValue N1 = N->getOperand(1); 8613 if (N1.getOpcode() != ISD::AND) 8614 return SDValue(); 8615 8616 // We only have to look for constant vectors here since the general, variable 8617 // case can be handled in TableGen. 8618 unsigned Bits = VT.getScalarSizeInBits(); 8619 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 8620 for (int i = 1; i >= 0; --i) 8621 for (int j = 1; j >= 0; --j) { 8622 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 8623 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 8624 if (!BVN0 || !BVN1) 8625 continue; 8626 8627 bool FoundMatch = true; 8628 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 8629 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 8630 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 8631 if (!CN0 || !CN1 || 8632 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 8633 FoundMatch = false; 8634 break; 8635 } 8636 } 8637 8638 if (FoundMatch) 8639 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), 8640 N0->getOperand(1 - i), N1->getOperand(1 - j)); 8641 } 8642 8643 return SDValue(); 8644 } 8645 8646 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 8647 const AArch64Subtarget *Subtarget) { 8648 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 8649 SelectionDAG &DAG = DCI.DAG; 8650 EVT VT = N->getValueType(0); 8651 8652 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8653 return SDValue(); 8654 8655 if (SDValue Res = tryCombineToEXTR(N, DCI)) 8656 return Res; 8657 8658 if (SDValue Res = tryCombineToBSL(N, DCI)) 8659 return Res; 8660 8661 return SDValue(); 8662 } 8663 8664 static SDValue performSRLCombine(SDNode *N, 8665 TargetLowering::DAGCombinerInfo &DCI) { 8666 SelectionDAG &DAG = DCI.DAG; 8667 EVT VT = N->getValueType(0); 8668 if (VT != MVT::i32 && VT != MVT::i64) 8669 return SDValue(); 8670 8671 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 8672 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 8673 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 8674 SDValue N0 = N->getOperand(0); 8675 if (N0.getOpcode() == ISD::BSWAP) { 8676 SDLoc DL(N); 8677 SDValue N1 = N->getOperand(1); 8678 SDValue N00 = N0.getOperand(0); 8679 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 8680 uint64_t ShiftAmt = C->getZExtValue(); 8681 if (VT == MVT::i32 && ShiftAmt == 16 && 8682 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 8683 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8684 if (VT == MVT::i64 && ShiftAmt == 32 && 8685 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 8686 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8687 } 8688 } 8689 return SDValue(); 8690 } 8691 8692 static SDValue performBitcastCombine(SDNode *N, 8693 TargetLowering::DAGCombinerInfo &DCI, 8694 SelectionDAG &DAG) { 8695 // Wait 'til after everything is legalized to try this. That way we have 8696 // legal vector types and such. 8697 if (DCI.isBeforeLegalizeOps()) 8698 return SDValue(); 8699 8700 // Remove extraneous bitcasts around an extract_subvector. 8701 // For example, 8702 // (v4i16 (bitconvert 8703 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) 8704 // becomes 8705 // (extract_subvector ((v8i16 ...), (i64 4))) 8706 8707 // Only interested in 64-bit vectors as the ultimate result. 8708 EVT VT = N->getValueType(0); 8709 if (!VT.isVector()) 8710 return SDValue(); 8711 if (VT.getSimpleVT().getSizeInBits() != 64) 8712 return SDValue(); 8713 // Is the operand an extract_subvector starting at the beginning or halfway 8714 // point of the vector? A low half may also come through as an 8715 // EXTRACT_SUBREG, so look for that, too. 8716 SDValue Op0 = N->getOperand(0); 8717 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && 8718 !(Op0->isMachineOpcode() && 8719 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) 8720 return SDValue(); 8721 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); 8722 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { 8723 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) 8724 return SDValue(); 8725 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { 8726 if (idx != AArch64::dsub) 8727 return SDValue(); 8728 // The dsub reference is equivalent to a lane zero subvector reference. 8729 idx = 0; 8730 } 8731 // Look through the bitcast of the input to the extract. 8732 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) 8733 return SDValue(); 8734 SDValue Source = Op0->getOperand(0)->getOperand(0); 8735 // If the source type has twice the number of elements as our destination 8736 // type, we know this is an extract of the high or low half of the vector. 8737 EVT SVT = Source->getValueType(0); 8738 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) 8739 return SDValue(); 8740 8741 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); 8742 8743 // Create the simplified form to just extract the low or high half of the 8744 // vector directly rather than bothering with the bitcasts. 8745 SDLoc dl(N); 8746 unsigned NumElements = VT.getVectorNumElements(); 8747 if (idx) { 8748 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); 8749 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); 8750 } else { 8751 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); 8752 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, 8753 Source, SubReg), 8754 0); 8755 } 8756 } 8757 8758 static SDValue performConcatVectorsCombine(SDNode *N, 8759 TargetLowering::DAGCombinerInfo &DCI, 8760 SelectionDAG &DAG) { 8761 SDLoc dl(N); 8762 EVT VT = N->getValueType(0); 8763 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 8764 8765 // Optimize concat_vectors of truncated vectors, where the intermediate 8766 // type is illegal, to avoid said illegality, e.g., 8767 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 8768 // (v2i16 (truncate (v2i64))))) 8769 // -> 8770 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 8771 // (v4i32 (bitcast (v2i64))), 8772 // <0, 2, 4, 6>))) 8773 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 8774 // on both input and result type, so we might generate worse code. 8775 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 8776 if (N->getNumOperands() == 2 && 8777 N0->getOpcode() == ISD::TRUNCATE && 8778 N1->getOpcode() == ISD::TRUNCATE) { 8779 SDValue N00 = N0->getOperand(0); 8780 SDValue N10 = N1->getOperand(0); 8781 EVT N00VT = N00.getValueType(); 8782 8783 if (N00VT == N10.getValueType() && 8784 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 8785 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 8786 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 8787 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 8788 for (size_t i = 0; i < Mask.size(); ++i) 8789 Mask[i] = i * 2; 8790 return DAG.getNode(ISD::TRUNCATE, dl, VT, 8791 DAG.getVectorShuffle( 8792 MidVT, dl, 8793 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 8794 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 8795 } 8796 } 8797 8798 // Wait 'til after everything is legalized to try this. That way we have 8799 // legal vector types and such. 8800 if (DCI.isBeforeLegalizeOps()) 8801 return SDValue(); 8802 8803 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 8804 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 8805 // canonicalise to that. 8806 if (N0 == N1 && VT.getVectorNumElements() == 2) { 8807 assert(VT.getScalarSizeInBits() == 64); 8808 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 8809 DAG.getConstant(0, dl, MVT::i64)); 8810 } 8811 8812 // Canonicalise concat_vectors so that the right-hand vector has as few 8813 // bit-casts as possible before its real operation. The primary matching 8814 // destination for these operations will be the narrowing "2" instructions, 8815 // which depend on the operation being performed on this right-hand vector. 8816 // For example, 8817 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 8818 // becomes 8819 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 8820 8821 if (N1->getOpcode() != ISD::BITCAST) 8822 return SDValue(); 8823 SDValue RHS = N1->getOperand(0); 8824 MVT RHSTy = RHS.getValueType().getSimpleVT(); 8825 // If the RHS is not a vector, this is not the pattern we're looking for. 8826 if (!RHSTy.isVector()) 8827 return SDValue(); 8828 8829 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 8830 8831 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 8832 RHSTy.getVectorNumElements() * 2); 8833 return DAG.getNode(ISD::BITCAST, dl, VT, 8834 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 8835 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 8836 RHS)); 8837 } 8838 8839 static SDValue tryCombineFixedPointConvert(SDNode *N, 8840 TargetLowering::DAGCombinerInfo &DCI, 8841 SelectionDAG &DAG) { 8842 // Wait 'til after everything is legalized to try this. That way we have 8843 // legal vector types and such. 8844 if (DCI.isBeforeLegalizeOps()) 8845 return SDValue(); 8846 // Transform a scalar conversion of a value from a lane extract into a 8847 // lane extract of a vector conversion. E.g., from foo1 to foo2: 8848 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 8849 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 8850 // 8851 // The second form interacts better with instruction selection and the 8852 // register allocator to avoid cross-class register copies that aren't 8853 // coalescable due to a lane reference. 8854 8855 // Check the operand and see if it originates from a lane extract. 8856 SDValue Op1 = N->getOperand(1); 8857 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8858 // Yep, no additional predication needed. Perform the transform. 8859 SDValue IID = N->getOperand(0); 8860 SDValue Shift = N->getOperand(2); 8861 SDValue Vec = Op1.getOperand(0); 8862 SDValue Lane = Op1.getOperand(1); 8863 EVT ResTy = N->getValueType(0); 8864 EVT VecResTy; 8865 SDLoc DL(N); 8866 8867 // The vector width should be 128 bits by the time we get here, even 8868 // if it started as 64 bits (the extract_vector handling will have 8869 // done so). 8870 assert(Vec.getValueSizeInBits() == 128 && 8871 "unexpected vector size on extract_vector_elt!"); 8872 if (Vec.getValueType() == MVT::v4i32) 8873 VecResTy = MVT::v4f32; 8874 else if (Vec.getValueType() == MVT::v2i64) 8875 VecResTy = MVT::v2f64; 8876 else 8877 llvm_unreachable("unexpected vector type!"); 8878 8879 SDValue Convert = 8880 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 8881 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 8882 } 8883 return SDValue(); 8884 } 8885 8886 // AArch64 high-vector "long" operations are formed by performing the non-high 8887 // version on an extract_subvector of each operand which gets the high half: 8888 // 8889 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 8890 // 8891 // However, there are cases which don't have an extract_high explicitly, but 8892 // have another operation that can be made compatible with one for free. For 8893 // example: 8894 // 8895 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 8896 // 8897 // This routine does the actual conversion of such DUPs, once outer routines 8898 // have determined that everything else is in order. 8899 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 8900 // similarly here. 8901 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 8902 switch (N.getOpcode()) { 8903 case AArch64ISD::DUP: 8904 case AArch64ISD::DUPLANE8: 8905 case AArch64ISD::DUPLANE16: 8906 case AArch64ISD::DUPLANE32: 8907 case AArch64ISD::DUPLANE64: 8908 case AArch64ISD::MOVI: 8909 case AArch64ISD::MOVIshift: 8910 case AArch64ISD::MOVIedit: 8911 case AArch64ISD::MOVImsl: 8912 case AArch64ISD::MVNIshift: 8913 case AArch64ISD::MVNImsl: 8914 break; 8915 default: 8916 // FMOV could be supported, but isn't very useful, as it would only occur 8917 // if you passed a bitcast' floating point immediate to an eligible long 8918 // integer op (addl, smull, ...). 8919 return SDValue(); 8920 } 8921 8922 MVT NarrowTy = N.getSimpleValueType(); 8923 if (!NarrowTy.is64BitVector()) 8924 return SDValue(); 8925 8926 MVT ElementTy = NarrowTy.getVectorElementType(); 8927 unsigned NumElems = NarrowTy.getVectorNumElements(); 8928 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 8929 8930 SDLoc dl(N); 8931 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 8932 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 8933 DAG.getConstant(NumElems, dl, MVT::i64)); 8934 } 8935 8936 static bool isEssentiallyExtractSubvector(SDValue N) { 8937 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR) 8938 return true; 8939 8940 return N.getOpcode() == ISD::BITCAST && 8941 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR; 8942 } 8943 8944 /// \brief Helper structure to keep track of ISD::SET_CC operands. 8945 struct GenericSetCCInfo { 8946 const SDValue *Opnd0; 8947 const SDValue *Opnd1; 8948 ISD::CondCode CC; 8949 }; 8950 8951 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code. 8952 struct AArch64SetCCInfo { 8953 const SDValue *Cmp; 8954 AArch64CC::CondCode CC; 8955 }; 8956 8957 /// \brief Helper structure to keep track of SetCC information. 8958 union SetCCInfo { 8959 GenericSetCCInfo Generic; 8960 AArch64SetCCInfo AArch64; 8961 }; 8962 8963 /// \brief Helper structure to be able to read SetCC information. If set to 8964 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 8965 /// GenericSetCCInfo. 8966 struct SetCCInfoAndKind { 8967 SetCCInfo Info; 8968 bool IsAArch64; 8969 }; 8970 8971 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or 8972 /// an 8973 /// AArch64 lowered one. 8974 /// \p SetCCInfo is filled accordingly. 8975 /// \post SetCCInfo is meanginfull only when this function returns true. 8976 /// \return True when Op is a kind of SET_CC operation. 8977 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 8978 // If this is a setcc, this is straight forward. 8979 if (Op.getOpcode() == ISD::SETCC) { 8980 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 8981 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 8982 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8983 SetCCInfo.IsAArch64 = false; 8984 return true; 8985 } 8986 // Otherwise, check if this is a matching csel instruction. 8987 // In other words: 8988 // - csel 1, 0, cc 8989 // - csel 0, 1, !cc 8990 if (Op.getOpcode() != AArch64ISD::CSEL) 8991 return false; 8992 // Set the information about the operands. 8993 // TODO: we want the operands of the Cmp not the csel 8994 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 8995 SetCCInfo.IsAArch64 = true; 8996 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 8997 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 8998 8999 // Check that the operands matches the constraints: 9000 // (1) Both operands must be constants. 9001 // (2) One must be 1 and the other must be 0. 9002 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 9003 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9004 9005 // Check (1). 9006 if (!TValue || !FValue) 9007 return false; 9008 9009 // Check (2). 9010 if (!TValue->isOne()) { 9011 // Update the comparison when we are interested in !cc. 9012 std::swap(TValue, FValue); 9013 SetCCInfo.Info.AArch64.CC = 9014 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 9015 } 9016 return TValue->isOne() && FValue->isNullValue(); 9017 } 9018 9019 // Returns true if Op is setcc or zext of setcc. 9020 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 9021 if (isSetCC(Op, Info)) 9022 return true; 9023 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 9024 isSetCC(Op->getOperand(0), Info)); 9025 } 9026 9027 // The folding we want to perform is: 9028 // (add x, [zext] (setcc cc ...) ) 9029 // --> 9030 // (csel x, (add x, 1), !cc ...) 9031 // 9032 // The latter will get matched to a CSINC instruction. 9033 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 9034 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 9035 SDValue LHS = Op->getOperand(0); 9036 SDValue RHS = Op->getOperand(1); 9037 SetCCInfoAndKind InfoAndKind; 9038 9039 // If neither operand is a SET_CC, give up. 9040 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 9041 std::swap(LHS, RHS); 9042 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 9043 return SDValue(); 9044 } 9045 9046 // FIXME: This could be generatized to work for FP comparisons. 9047 EVT CmpVT = InfoAndKind.IsAArch64 9048 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 9049 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 9050 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 9051 return SDValue(); 9052 9053 SDValue CCVal; 9054 SDValue Cmp; 9055 SDLoc dl(Op); 9056 if (InfoAndKind.IsAArch64) { 9057 CCVal = DAG.getConstant( 9058 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 9059 MVT::i32); 9060 Cmp = *InfoAndKind.Info.AArch64.Cmp; 9061 } else 9062 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, 9063 *InfoAndKind.Info.Generic.Opnd1, 9064 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), 9065 CCVal, DAG, dl); 9066 9067 EVT VT = Op->getValueType(0); 9068 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 9069 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 9070 } 9071 9072 // The basic add/sub long vector instructions have variants with "2" on the end 9073 // which act on the high-half of their inputs. They are normally matched by 9074 // patterns like: 9075 // 9076 // (add (zeroext (extract_high LHS)), 9077 // (zeroext (extract_high RHS))) 9078 // -> uaddl2 vD, vN, vM 9079 // 9080 // However, if one of the extracts is something like a duplicate, this 9081 // instruction can still be used profitably. This function puts the DAG into a 9082 // more appropriate form for those patterns to trigger. 9083 static SDValue performAddSubLongCombine(SDNode *N, 9084 TargetLowering::DAGCombinerInfo &DCI, 9085 SelectionDAG &DAG) { 9086 if (DCI.isBeforeLegalizeOps()) 9087 return SDValue(); 9088 9089 MVT VT = N->getSimpleValueType(0); 9090 if (!VT.is128BitVector()) { 9091 if (N->getOpcode() == ISD::ADD) 9092 return performSetccAddFolding(N, DAG); 9093 return SDValue(); 9094 } 9095 9096 // Make sure both branches are extended in the same way. 9097 SDValue LHS = N->getOperand(0); 9098 SDValue RHS = N->getOperand(1); 9099 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 9100 LHS.getOpcode() != ISD::SIGN_EXTEND) || 9101 LHS.getOpcode() != RHS.getOpcode()) 9102 return SDValue(); 9103 9104 unsigned ExtType = LHS.getOpcode(); 9105 9106 // It's not worth doing if at least one of the inputs isn't already an 9107 // extract, but we don't know which it'll be so we have to try both. 9108 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) { 9109 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 9110 if (!RHS.getNode()) 9111 return SDValue(); 9112 9113 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 9114 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) { 9115 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 9116 if (!LHS.getNode()) 9117 return SDValue(); 9118 9119 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 9120 } 9121 9122 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 9123 } 9124 9125 // Massage DAGs which we can use the high-half "long" operations on into 9126 // something isel will recognize better. E.g. 9127 // 9128 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 9129 // (aarch64_neon_umull (extract_high (v2i64 vec))) 9130 // (extract_high (v2i64 (dup128 scalar))))) 9131 // 9132 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 9133 TargetLowering::DAGCombinerInfo &DCI, 9134 SelectionDAG &DAG) { 9135 if (DCI.isBeforeLegalizeOps()) 9136 return SDValue(); 9137 9138 SDValue LHS = N->getOperand(1); 9139 SDValue RHS = N->getOperand(2); 9140 assert(LHS.getValueType().is64BitVector() && 9141 RHS.getValueType().is64BitVector() && 9142 "unexpected shape for long operation"); 9143 9144 // Either node could be a DUP, but it's not worth doing both of them (you'd 9145 // just as well use the non-high version) so look for a corresponding extract 9146 // operation on the other "wing". 9147 if (isEssentiallyExtractSubvector(LHS)) { 9148 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 9149 if (!RHS.getNode()) 9150 return SDValue(); 9151 } else if (isEssentiallyExtractSubvector(RHS)) { 9152 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 9153 if (!LHS.getNode()) 9154 return SDValue(); 9155 } 9156 9157 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 9158 N->getOperand(0), LHS, RHS); 9159 } 9160 9161 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 9162 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 9163 unsigned ElemBits = ElemTy.getSizeInBits(); 9164 9165 int64_t ShiftAmount; 9166 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 9167 APInt SplatValue, SplatUndef; 9168 unsigned SplatBitSize; 9169 bool HasAnyUndefs; 9170 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 9171 HasAnyUndefs, ElemBits) || 9172 SplatBitSize != ElemBits) 9173 return SDValue(); 9174 9175 ShiftAmount = SplatValue.getSExtValue(); 9176 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 9177 ShiftAmount = CVN->getSExtValue(); 9178 } else 9179 return SDValue(); 9180 9181 unsigned Opcode; 9182 bool IsRightShift; 9183 switch (IID) { 9184 default: 9185 llvm_unreachable("Unknown shift intrinsic"); 9186 case Intrinsic::aarch64_neon_sqshl: 9187 Opcode = AArch64ISD::SQSHL_I; 9188 IsRightShift = false; 9189 break; 9190 case Intrinsic::aarch64_neon_uqshl: 9191 Opcode = AArch64ISD::UQSHL_I; 9192 IsRightShift = false; 9193 break; 9194 case Intrinsic::aarch64_neon_srshl: 9195 Opcode = AArch64ISD::SRSHR_I; 9196 IsRightShift = true; 9197 break; 9198 case Intrinsic::aarch64_neon_urshl: 9199 Opcode = AArch64ISD::URSHR_I; 9200 IsRightShift = true; 9201 break; 9202 case Intrinsic::aarch64_neon_sqshlu: 9203 Opcode = AArch64ISD::SQSHLU_I; 9204 IsRightShift = false; 9205 break; 9206 } 9207 9208 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 9209 SDLoc dl(N); 9210 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 9211 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 9212 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 9213 SDLoc dl(N); 9214 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 9215 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 9216 } 9217 9218 return SDValue(); 9219 } 9220 9221 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 9222 // the intrinsics must be legal and take an i32, this means there's almost 9223 // certainly going to be a zext in the DAG which we can eliminate. 9224 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 9225 SDValue AndN = N->getOperand(2); 9226 if (AndN.getOpcode() != ISD::AND) 9227 return SDValue(); 9228 9229 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 9230 if (!CMask || CMask->getZExtValue() != Mask) 9231 return SDValue(); 9232 9233 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 9234 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 9235 } 9236 9237 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 9238 SelectionDAG &DAG) { 9239 SDLoc dl(N); 9240 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 9241 DAG.getNode(Opc, dl, 9242 N->getOperand(1).getSimpleValueType(), 9243 N->getOperand(1)), 9244 DAG.getConstant(0, dl, MVT::i64)); 9245 } 9246 9247 static SDValue performIntrinsicCombine(SDNode *N, 9248 TargetLowering::DAGCombinerInfo &DCI, 9249 const AArch64Subtarget *Subtarget) { 9250 SelectionDAG &DAG = DCI.DAG; 9251 unsigned IID = getIntrinsicID(N); 9252 switch (IID) { 9253 default: 9254 break; 9255 case Intrinsic::aarch64_neon_vcvtfxs2fp: 9256 case Intrinsic::aarch64_neon_vcvtfxu2fp: 9257 return tryCombineFixedPointConvert(N, DCI, DAG); 9258 case Intrinsic::aarch64_neon_saddv: 9259 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 9260 case Intrinsic::aarch64_neon_uaddv: 9261 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 9262 case Intrinsic::aarch64_neon_sminv: 9263 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 9264 case Intrinsic::aarch64_neon_uminv: 9265 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 9266 case Intrinsic::aarch64_neon_smaxv: 9267 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 9268 case Intrinsic::aarch64_neon_umaxv: 9269 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 9270 case Intrinsic::aarch64_neon_fmax: 9271 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0), 9272 N->getOperand(1), N->getOperand(2)); 9273 case Intrinsic::aarch64_neon_fmin: 9274 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0), 9275 N->getOperand(1), N->getOperand(2)); 9276 case Intrinsic::aarch64_neon_fmaxnm: 9277 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 9278 N->getOperand(1), N->getOperand(2)); 9279 case Intrinsic::aarch64_neon_fminnm: 9280 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 9281 N->getOperand(1), N->getOperand(2)); 9282 case Intrinsic::aarch64_neon_smull: 9283 case Intrinsic::aarch64_neon_umull: 9284 case Intrinsic::aarch64_neon_pmull: 9285 case Intrinsic::aarch64_neon_sqdmull: 9286 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 9287 case Intrinsic::aarch64_neon_sqshl: 9288 case Intrinsic::aarch64_neon_uqshl: 9289 case Intrinsic::aarch64_neon_sqshlu: 9290 case Intrinsic::aarch64_neon_srshl: 9291 case Intrinsic::aarch64_neon_urshl: 9292 return tryCombineShiftImm(IID, N, DAG); 9293 case Intrinsic::aarch64_crc32b: 9294 case Intrinsic::aarch64_crc32cb: 9295 return tryCombineCRC32(0xff, N, DAG); 9296 case Intrinsic::aarch64_crc32h: 9297 case Intrinsic::aarch64_crc32ch: 9298 return tryCombineCRC32(0xffff, N, DAG); 9299 } 9300 return SDValue(); 9301 } 9302 9303 static SDValue performExtendCombine(SDNode *N, 9304 TargetLowering::DAGCombinerInfo &DCI, 9305 SelectionDAG &DAG) { 9306 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 9307 // we can convert that DUP into another extract_high (of a bigger DUP), which 9308 // helps the backend to decide that an sabdl2 would be useful, saving a real 9309 // extract_high operation. 9310 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 9311 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 9312 SDNode *ABDNode = N->getOperand(0).getNode(); 9313 unsigned IID = getIntrinsicID(ABDNode); 9314 if (IID == Intrinsic::aarch64_neon_sabd || 9315 IID == Intrinsic::aarch64_neon_uabd) { 9316 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 9317 if (!NewABD.getNode()) 9318 return SDValue(); 9319 9320 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 9321 NewABD); 9322 } 9323 } 9324 9325 // This is effectively a custom type legalization for AArch64. 9326 // 9327 // Type legalization will split an extend of a small, legal, type to a larger 9328 // illegal type by first splitting the destination type, often creating 9329 // illegal source types, which then get legalized in isel-confusing ways, 9330 // leading to really terrible codegen. E.g., 9331 // %result = v8i32 sext v8i8 %value 9332 // becomes 9333 // %losrc = extract_subreg %value, ... 9334 // %hisrc = extract_subreg %value, ... 9335 // %lo = v4i32 sext v4i8 %losrc 9336 // %hi = v4i32 sext v4i8 %hisrc 9337 // Things go rapidly downhill from there. 9338 // 9339 // For AArch64, the [sz]ext vector instructions can only go up one element 9340 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 9341 // take two instructions. 9342 // 9343 // This implies that the most efficient way to do the extend from v8i8 9344 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 9345 // the normal splitting to happen for the v8i16->v8i32. 9346 9347 // This is pre-legalization to catch some cases where the default 9348 // type legalization will create ill-tempered code. 9349 if (!DCI.isBeforeLegalizeOps()) 9350 return SDValue(); 9351 9352 // We're only interested in cleaning things up for non-legal vector types 9353 // here. If both the source and destination are legal, things will just 9354 // work naturally without any fiddling. 9355 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9356 EVT ResVT = N->getValueType(0); 9357 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 9358 return SDValue(); 9359 // If the vector type isn't a simple VT, it's beyond the scope of what 9360 // we're worried about here. Let legalization do its thing and hope for 9361 // the best. 9362 SDValue Src = N->getOperand(0); 9363 EVT SrcVT = Src->getValueType(0); 9364 if (!ResVT.isSimple() || !SrcVT.isSimple()) 9365 return SDValue(); 9366 9367 // If the source VT is a 64-bit vector, we can play games and get the 9368 // better results we want. 9369 if (SrcVT.getSizeInBits() != 64) 9370 return SDValue(); 9371 9372 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 9373 unsigned ElementCount = SrcVT.getVectorNumElements(); 9374 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 9375 SDLoc DL(N); 9376 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 9377 9378 // Now split the rest of the operation into two halves, each with a 64 9379 // bit source. 9380 EVT LoVT, HiVT; 9381 SDValue Lo, Hi; 9382 unsigned NumElements = ResVT.getVectorNumElements(); 9383 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 9384 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 9385 ResVT.getVectorElementType(), NumElements / 2); 9386 9387 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 9388 LoVT.getVectorNumElements()); 9389 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 9390 DAG.getConstant(0, DL, MVT::i64)); 9391 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 9392 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 9393 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 9394 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 9395 9396 // Now combine the parts back together so we still have a single result 9397 // like the combiner expects. 9398 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 9399 } 9400 9401 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 9402 SDValue SplatVal, unsigned NumVecElts) { 9403 unsigned OrigAlignment = St.getAlignment(); 9404 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 9405 9406 // Create scalar stores. This is at least as good as the code sequence for a 9407 // split unaligned store which is a dup.s, ext.b, and two stores. 9408 // Most of the time the three stores should be replaced by store pair 9409 // instructions (stp). 9410 SDLoc DL(&St); 9411 SDValue BasePtr = St.getBasePtr(); 9412 uint64_t BaseOffset = 0; 9413 9414 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 9415 SDValue NewST1 = 9416 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 9417 OrigAlignment, St.getMemOperand()->getFlags()); 9418 9419 // As this in ISel, we will not merge this add which may degrade results. 9420 if (BasePtr->getOpcode() == ISD::ADD && 9421 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 9422 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 9423 BasePtr = BasePtr->getOperand(0); 9424 } 9425 9426 unsigned Offset = EltOffset; 9427 while (--NumVecElts) { 9428 unsigned Alignment = MinAlign(OrigAlignment, Offset); 9429 SDValue OffsetPtr = 9430 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 9431 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 9432 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 9433 PtrInfo.getWithOffset(Offset), Alignment, 9434 St.getMemOperand()->getFlags()); 9435 Offset += EltOffset; 9436 } 9437 return NewST1; 9438 } 9439 9440 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 9441 /// load store optimizer pass will merge them to store pair stores. This should 9442 /// be better than a movi to create the vector zero followed by a vector store 9443 /// if the zero constant is not re-used, since one instructions and one register 9444 /// live range will be removed. 9445 /// 9446 /// For example, the final generated code should be: 9447 /// 9448 /// stp xzr, xzr, [x0] 9449 /// 9450 /// instead of: 9451 /// 9452 /// movi v0.2d, #0 9453 /// str q0, [x0] 9454 /// 9455 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 9456 SDValue StVal = St.getValue(); 9457 EVT VT = StVal.getValueType(); 9458 9459 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 9460 // 2, 3 or 4 i32 elements. 9461 int NumVecElts = VT.getVectorNumElements(); 9462 if (!(((NumVecElts == 2 || NumVecElts == 3) && 9463 VT.getVectorElementType().getSizeInBits() == 64) || 9464 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 9465 VT.getVectorElementType().getSizeInBits() == 32))) 9466 return SDValue(); 9467 9468 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 9469 return SDValue(); 9470 9471 // If the zero constant has more than one use then the vector store could be 9472 // better since the constant mov will be amortized and stp q instructions 9473 // should be able to be formed. 9474 if (!StVal.hasOneUse()) 9475 return SDValue(); 9476 9477 // If the immediate offset of the address operand is too large for the stp 9478 // instruction, then bail out. 9479 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 9480 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 9481 if (Offset < -512 || Offset > 504) 9482 return SDValue(); 9483 } 9484 9485 for (int I = 0; I < NumVecElts; ++I) { 9486 SDValue EltVal = StVal.getOperand(I); 9487 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 9488 return SDValue(); 9489 } 9490 9491 // Use a CopyFromReg WZR/XZR here to prevent 9492 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 9493 SDLoc DL(&St); 9494 unsigned ZeroReg; 9495 EVT ZeroVT; 9496 if (VT.getVectorElementType().getSizeInBits() == 32) { 9497 ZeroReg = AArch64::WZR; 9498 ZeroVT = MVT::i32; 9499 } else { 9500 ZeroReg = AArch64::XZR; 9501 ZeroVT = MVT::i64; 9502 } 9503 SDValue SplatVal = 9504 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 9505 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 9506 } 9507 9508 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 9509 /// value. The load store optimizer pass will merge them to store pair stores. 9510 /// This has better performance than a splat of the scalar followed by a split 9511 /// vector store. Even if the stores are not merged it is four stores vs a dup, 9512 /// followed by an ext.b and two stores. 9513 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 9514 SDValue StVal = St.getValue(); 9515 EVT VT = StVal.getValueType(); 9516 9517 // Don't replace floating point stores, they possibly won't be transformed to 9518 // stp because of the store pair suppress pass. 9519 if (VT.isFloatingPoint()) 9520 return SDValue(); 9521 9522 // We can express a splat as store pair(s) for 2 or 4 elements. 9523 unsigned NumVecElts = VT.getVectorNumElements(); 9524 if (NumVecElts != 4 && NumVecElts != 2) 9525 return SDValue(); 9526 9527 // Check that this is a splat. 9528 // Make sure that each of the relevant vector element locations are inserted 9529 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 9530 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 9531 SDValue SplatVal; 9532 for (unsigned I = 0; I < NumVecElts; ++I) { 9533 // Check for insert vector elements. 9534 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 9535 return SDValue(); 9536 9537 // Check that same value is inserted at each vector element. 9538 if (I == 0) 9539 SplatVal = StVal.getOperand(1); 9540 else if (StVal.getOperand(1) != SplatVal) 9541 return SDValue(); 9542 9543 // Check insert element index. 9544 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 9545 if (!CIndex) 9546 return SDValue(); 9547 uint64_t IndexVal = CIndex->getZExtValue(); 9548 if (IndexVal >= NumVecElts) 9549 return SDValue(); 9550 IndexNotInserted.reset(IndexVal); 9551 9552 StVal = StVal.getOperand(0); 9553 } 9554 // Check that all vector element locations were inserted to. 9555 if (IndexNotInserted.any()) 9556 return SDValue(); 9557 9558 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 9559 } 9560 9561 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 9562 SelectionDAG &DAG, 9563 const AArch64Subtarget *Subtarget) { 9564 if (!DCI.isBeforeLegalize()) 9565 return SDValue(); 9566 9567 StoreSDNode *S = cast<StoreSDNode>(N); 9568 if (S->isVolatile() || S->isIndexed()) 9569 return SDValue(); 9570 9571 SDValue StVal = S->getValue(); 9572 EVT VT = StVal.getValueType(); 9573 if (!VT.isVector()) 9574 return SDValue(); 9575 9576 // If we get a splat of zeros, convert this vector store to a store of 9577 // scalars. They will be merged into store pairs of xzr thereby removing one 9578 // instruction and one register. 9579 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 9580 return ReplacedZeroSplat; 9581 9582 // FIXME: The logic for deciding if an unaligned store should be split should 9583 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 9584 // a call to that function here. 9585 9586 if (!Subtarget->isMisaligned128StoreSlow()) 9587 return SDValue(); 9588 9589 // Don't split at -Oz. 9590 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 9591 return SDValue(); 9592 9593 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 9594 // those up regresses performance on micro-benchmarks and olden/bh. 9595 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 9596 return SDValue(); 9597 9598 // Split unaligned 16B stores. They are terrible for performance. 9599 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 9600 // extensions can use this to mark that it does not want splitting to happen 9601 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 9602 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 9603 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 9604 S->getAlignment() <= 2) 9605 return SDValue(); 9606 9607 // If we get a splat of a scalar convert this vector store to a store of 9608 // scalars. They will be merged into store pairs thereby removing two 9609 // instructions. 9610 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 9611 return ReplacedSplat; 9612 9613 SDLoc DL(S); 9614 unsigned NumElts = VT.getVectorNumElements() / 2; 9615 // Split VT into two. 9616 EVT HalfVT = 9617 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts); 9618 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 9619 DAG.getConstant(0, DL, MVT::i64)); 9620 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 9621 DAG.getConstant(NumElts, DL, MVT::i64)); 9622 SDValue BasePtr = S->getBasePtr(); 9623 SDValue NewST1 = 9624 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 9625 S->getAlignment(), S->getMemOperand()->getFlags()); 9626 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 9627 DAG.getConstant(8, DL, MVT::i64)); 9628 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 9629 S->getPointerInfo(), S->getAlignment(), 9630 S->getMemOperand()->getFlags()); 9631 } 9632 9633 /// Target-specific DAG combine function for post-increment LD1 (lane) and 9634 /// post-increment LD1R. 9635 static SDValue performPostLD1Combine(SDNode *N, 9636 TargetLowering::DAGCombinerInfo &DCI, 9637 bool IsLaneOp) { 9638 if (DCI.isBeforeLegalizeOps()) 9639 return SDValue(); 9640 9641 SelectionDAG &DAG = DCI.DAG; 9642 EVT VT = N->getValueType(0); 9643 9644 unsigned LoadIdx = IsLaneOp ? 1 : 0; 9645 SDNode *LD = N->getOperand(LoadIdx).getNode(); 9646 // If it is not LOAD, can not do such combine. 9647 if (LD->getOpcode() != ISD::LOAD) 9648 return SDValue(); 9649 9650 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 9651 EVT MemVT = LoadSDN->getMemoryVT(); 9652 // Check if memory operand is the same type as the vector element. 9653 if (MemVT != VT.getVectorElementType()) 9654 return SDValue(); 9655 9656 // Check if there are other uses. If so, do not combine as it will introduce 9657 // an extra load. 9658 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 9659 ++UI) { 9660 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 9661 continue; 9662 if (*UI != N) 9663 return SDValue(); 9664 } 9665 9666 SDValue Addr = LD->getOperand(1); 9667 SDValue Vector = N->getOperand(0); 9668 // Search for a use of the address operand that is an increment. 9669 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 9670 Addr.getNode()->use_end(); UI != UE; ++UI) { 9671 SDNode *User = *UI; 9672 if (User->getOpcode() != ISD::ADD 9673 || UI.getUse().getResNo() != Addr.getResNo()) 9674 continue; 9675 9676 // Check that the add is independent of the load. Otherwise, folding it 9677 // would create a cycle. 9678 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User)) 9679 continue; 9680 // Also check that add is not used in the vector operand. This would also 9681 // create a cycle. 9682 if (User->isPredecessorOf(Vector.getNode())) 9683 continue; 9684 9685 // If the increment is a constant, it must match the memory ref size. 9686 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9687 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9688 uint32_t IncVal = CInc->getZExtValue(); 9689 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 9690 if (IncVal != NumBytes) 9691 continue; 9692 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9693 } 9694 9695 // Finally, check that the vector doesn't depend on the load. 9696 // Again, this would create a cycle. 9697 // The load depending on the vector is fine, as that's the case for the 9698 // LD1*post we'll eventually generate anyway. 9699 if (LoadSDN->isPredecessorOf(Vector.getNode())) 9700 continue; 9701 9702 SmallVector<SDValue, 8> Ops; 9703 Ops.push_back(LD->getOperand(0)); // Chain 9704 if (IsLaneOp) { 9705 Ops.push_back(Vector); // The vector to be inserted 9706 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector 9707 } 9708 Ops.push_back(Addr); 9709 Ops.push_back(Inc); 9710 9711 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 9712 SDVTList SDTys = DAG.getVTList(Tys); 9713 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 9714 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 9715 MemVT, 9716 LoadSDN->getMemOperand()); 9717 9718 // Update the uses. 9719 SDValue NewResults[] = { 9720 SDValue(LD, 0), // The result of load 9721 SDValue(UpdN.getNode(), 2) // Chain 9722 }; 9723 DCI.CombineTo(LD, NewResults); 9724 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 9725 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 9726 9727 break; 9728 } 9729 return SDValue(); 9730 } 9731 9732 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 9733 /// address translation. 9734 static bool performTBISimplification(SDValue Addr, 9735 TargetLowering::DAGCombinerInfo &DCI, 9736 SelectionDAG &DAG) { 9737 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 9738 KnownBits Known; 9739 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9740 !DCI.isBeforeLegalizeOps()); 9741 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9742 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 9743 DCI.CommitTargetLoweringOpt(TLO); 9744 return true; 9745 } 9746 return false; 9747 } 9748 9749 static SDValue performSTORECombine(SDNode *N, 9750 TargetLowering::DAGCombinerInfo &DCI, 9751 SelectionDAG &DAG, 9752 const AArch64Subtarget *Subtarget) { 9753 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 9754 return Split; 9755 9756 if (Subtarget->supportsAddressTopByteIgnored() && 9757 performTBISimplification(N->getOperand(2), DCI, DAG)) 9758 return SDValue(N, 0); 9759 9760 return SDValue(); 9761 } 9762 9763 9764 /// Target-specific DAG combine function for NEON load/store intrinsics 9765 /// to merge base address updates. 9766 static SDValue performNEONPostLDSTCombine(SDNode *N, 9767 TargetLowering::DAGCombinerInfo &DCI, 9768 SelectionDAG &DAG) { 9769 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9770 return SDValue(); 9771 9772 unsigned AddrOpIdx = N->getNumOperands() - 1; 9773 SDValue Addr = N->getOperand(AddrOpIdx); 9774 9775 // Search for a use of the address operand that is an increment. 9776 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9777 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9778 SDNode *User = *UI; 9779 if (User->getOpcode() != ISD::ADD || 9780 UI.getUse().getResNo() != Addr.getResNo()) 9781 continue; 9782 9783 // Check that the add is independent of the load/store. Otherwise, folding 9784 // it would create a cycle. 9785 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9786 continue; 9787 9788 // Find the new opcode for the updating load/store. 9789 bool IsStore = false; 9790 bool IsLaneOp = false; 9791 bool IsDupOp = false; 9792 unsigned NewOpc = 0; 9793 unsigned NumVecs = 0; 9794 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9795 switch (IntNo) { 9796 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9797 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 9798 NumVecs = 2; break; 9799 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 9800 NumVecs = 3; break; 9801 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 9802 NumVecs = 4; break; 9803 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 9804 NumVecs = 2; IsStore = true; break; 9805 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 9806 NumVecs = 3; IsStore = true; break; 9807 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 9808 NumVecs = 4; IsStore = true; break; 9809 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 9810 NumVecs = 2; break; 9811 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 9812 NumVecs = 3; break; 9813 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 9814 NumVecs = 4; break; 9815 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 9816 NumVecs = 2; IsStore = true; break; 9817 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 9818 NumVecs = 3; IsStore = true; break; 9819 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 9820 NumVecs = 4; IsStore = true; break; 9821 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 9822 NumVecs = 2; IsDupOp = true; break; 9823 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 9824 NumVecs = 3; IsDupOp = true; break; 9825 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 9826 NumVecs = 4; IsDupOp = true; break; 9827 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 9828 NumVecs = 2; IsLaneOp = true; break; 9829 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 9830 NumVecs = 3; IsLaneOp = true; break; 9831 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 9832 NumVecs = 4; IsLaneOp = true; break; 9833 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 9834 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 9835 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 9836 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 9837 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 9838 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 9839 } 9840 9841 EVT VecTy; 9842 if (IsStore) 9843 VecTy = N->getOperand(2).getValueType(); 9844 else 9845 VecTy = N->getValueType(0); 9846 9847 // If the increment is a constant, it must match the memory ref size. 9848 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9849 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9850 uint32_t IncVal = CInc->getZExtValue(); 9851 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9852 if (IsLaneOp || IsDupOp) 9853 NumBytes /= VecTy.getVectorNumElements(); 9854 if (IncVal != NumBytes) 9855 continue; 9856 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9857 } 9858 SmallVector<SDValue, 8> Ops; 9859 Ops.push_back(N->getOperand(0)); // Incoming chain 9860 // Load lane and store have vector list as input. 9861 if (IsLaneOp || IsStore) 9862 for (unsigned i = 2; i < AddrOpIdx; ++i) 9863 Ops.push_back(N->getOperand(i)); 9864 Ops.push_back(Addr); // Base register 9865 Ops.push_back(Inc); 9866 9867 // Return Types. 9868 EVT Tys[6]; 9869 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 9870 unsigned n; 9871 for (n = 0; n < NumResultVecs; ++n) 9872 Tys[n] = VecTy; 9873 Tys[n++] = MVT::i64; // Type of write back register 9874 Tys[n] = MVT::Other; // Type of the chain 9875 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 9876 9877 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 9878 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 9879 MemInt->getMemoryVT(), 9880 MemInt->getMemOperand()); 9881 9882 // Update the uses. 9883 std::vector<SDValue> NewResults; 9884 for (unsigned i = 0; i < NumResultVecs; ++i) { 9885 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9886 } 9887 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 9888 DCI.CombineTo(N, NewResults); 9889 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9890 9891 break; 9892 } 9893 return SDValue(); 9894 } 9895 9896 // Checks to see if the value is the prescribed width and returns information 9897 // about its extension mode. 9898 static 9899 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 9900 ExtType = ISD::NON_EXTLOAD; 9901 switch(V.getNode()->getOpcode()) { 9902 default: 9903 return false; 9904 case ISD::LOAD: { 9905 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 9906 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 9907 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 9908 ExtType = LoadNode->getExtensionType(); 9909 return true; 9910 } 9911 return false; 9912 } 9913 case ISD::AssertSext: { 9914 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9915 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9916 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9917 ExtType = ISD::SEXTLOAD; 9918 return true; 9919 } 9920 return false; 9921 } 9922 case ISD::AssertZext: { 9923 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9924 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9925 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9926 ExtType = ISD::ZEXTLOAD; 9927 return true; 9928 } 9929 return false; 9930 } 9931 case ISD::Constant: 9932 case ISD::TargetConstant: { 9933 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 9934 1LL << (width - 1); 9935 } 9936 } 9937 9938 return true; 9939 } 9940 9941 // This function does a whole lot of voodoo to determine if the tests are 9942 // equivalent without and with a mask. Essentially what happens is that given a 9943 // DAG resembling: 9944 // 9945 // +-------------+ +-------------+ +-------------+ +-------------+ 9946 // | Input | | AddConstant | | CompConstant| | CC | 9947 // +-------------+ +-------------+ +-------------+ +-------------+ 9948 // | | | | 9949 // V V | +----------+ 9950 // +-------------+ +----+ | | 9951 // | ADD | |0xff| | | 9952 // +-------------+ +----+ | | 9953 // | | | | 9954 // V V | | 9955 // +-------------+ | | 9956 // | AND | | | 9957 // +-------------+ | | 9958 // | | | 9959 // +-----+ | | 9960 // | | | 9961 // V V V 9962 // +-------------+ 9963 // | CMP | 9964 // +-------------+ 9965 // 9966 // The AND node may be safely removed for some combinations of inputs. In 9967 // particular we need to take into account the extension type of the Input, 9968 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 9969 // width of the input (this can work for any width inputs, the above graph is 9970 // specific to 8 bits. 9971 // 9972 // The specific equations were worked out by generating output tables for each 9973 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 9974 // problem was simplified by working with 4 bit inputs, which means we only 9975 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 9976 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 9977 // patterns present in both extensions (0,7). For every distinct set of 9978 // AddConstant and CompConstants bit patterns we can consider the masked and 9979 // unmasked versions to be equivalent if the result of this function is true for 9980 // all 16 distinct bit patterns of for the current extension type of Input (w0). 9981 // 9982 // sub w8, w0, w1 9983 // and w10, w8, #0x0f 9984 // cmp w8, w2 9985 // cset w9, AArch64CC 9986 // cmp w10, w2 9987 // cset w11, AArch64CC 9988 // cmp w9, w11 9989 // cset w0, eq 9990 // ret 9991 // 9992 // Since the above function shows when the outputs are equivalent it defines 9993 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 9994 // would be expensive to run during compiles. The equations below were written 9995 // in a test harness that confirmed they gave equivalent outputs to the above 9996 // for all inputs function, so they can be used determine if the removal is 9997 // legal instead. 9998 // 9999 // isEquivalentMaskless() is the code for testing if the AND can be removed 10000 // factored out of the DAG recognition as the DAG can take several forms. 10001 10002 static bool isEquivalentMaskless(unsigned CC, unsigned width, 10003 ISD::LoadExtType ExtType, int AddConstant, 10004 int CompConstant) { 10005 // By being careful about our equations and only writing the in term 10006 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 10007 // make them generally applicable to all bit widths. 10008 int MaxUInt = (1 << width); 10009 10010 // For the purposes of these comparisons sign extending the type is 10011 // equivalent to zero extending the add and displacing it by half the integer 10012 // width. Provided we are careful and make sure our equations are valid over 10013 // the whole range we can just adjust the input and avoid writing equations 10014 // for sign extended inputs. 10015 if (ExtType == ISD::SEXTLOAD) 10016 AddConstant -= (1 << (width-1)); 10017 10018 switch(CC) { 10019 case AArch64CC::LE: 10020 case AArch64CC::GT: 10021 if ((AddConstant == 0) || 10022 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 10023 (AddConstant >= 0 && CompConstant < 0) || 10024 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 10025 return true; 10026 break; 10027 case AArch64CC::LT: 10028 case AArch64CC::GE: 10029 if ((AddConstant == 0) || 10030 (AddConstant >= 0 && CompConstant <= 0) || 10031 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 10032 return true; 10033 break; 10034 case AArch64CC::HI: 10035 case AArch64CC::LS: 10036 if ((AddConstant >= 0 && CompConstant < 0) || 10037 (AddConstant <= 0 && CompConstant >= -1 && 10038 CompConstant < AddConstant + MaxUInt)) 10039 return true; 10040 break; 10041 case AArch64CC::PL: 10042 case AArch64CC::MI: 10043 if ((AddConstant == 0) || 10044 (AddConstant > 0 && CompConstant <= 0) || 10045 (AddConstant < 0 && CompConstant <= AddConstant)) 10046 return true; 10047 break; 10048 case AArch64CC::LO: 10049 case AArch64CC::HS: 10050 if ((AddConstant >= 0 && CompConstant <= 0) || 10051 (AddConstant <= 0 && CompConstant >= 0 && 10052 CompConstant <= AddConstant + MaxUInt)) 10053 return true; 10054 break; 10055 case AArch64CC::EQ: 10056 case AArch64CC::NE: 10057 if ((AddConstant > 0 && CompConstant < 0) || 10058 (AddConstant < 0 && CompConstant >= 0 && 10059 CompConstant < AddConstant + MaxUInt) || 10060 (AddConstant >= 0 && CompConstant >= 0 && 10061 CompConstant >= AddConstant) || 10062 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 10063 return true; 10064 break; 10065 case AArch64CC::VS: 10066 case AArch64CC::VC: 10067 case AArch64CC::AL: 10068 case AArch64CC::NV: 10069 return true; 10070 case AArch64CC::Invalid: 10071 break; 10072 } 10073 10074 return false; 10075 } 10076 10077 static 10078 SDValue performCONDCombine(SDNode *N, 10079 TargetLowering::DAGCombinerInfo &DCI, 10080 SelectionDAG &DAG, unsigned CCIndex, 10081 unsigned CmpIndex) { 10082 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 10083 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 10084 unsigned CondOpcode = SubsNode->getOpcode(); 10085 10086 if (CondOpcode != AArch64ISD::SUBS) 10087 return SDValue(); 10088 10089 // There is a SUBS feeding this condition. Is it fed by a mask we can 10090 // use? 10091 10092 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 10093 unsigned MaskBits = 0; 10094 10095 if (AndNode->getOpcode() != ISD::AND) 10096 return SDValue(); 10097 10098 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 10099 uint32_t CNV = CN->getZExtValue(); 10100 if (CNV == 255) 10101 MaskBits = 8; 10102 else if (CNV == 65535) 10103 MaskBits = 16; 10104 } 10105 10106 if (!MaskBits) 10107 return SDValue(); 10108 10109 SDValue AddValue = AndNode->getOperand(0); 10110 10111 if (AddValue.getOpcode() != ISD::ADD) 10112 return SDValue(); 10113 10114 // The basic dag structure is correct, grab the inputs and validate them. 10115 10116 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 10117 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 10118 SDValue SubsInputValue = SubsNode->getOperand(1); 10119 10120 // The mask is present and the provenance of all the values is a smaller type, 10121 // lets see if the mask is superfluous. 10122 10123 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 10124 !isa<ConstantSDNode>(SubsInputValue.getNode())) 10125 return SDValue(); 10126 10127 ISD::LoadExtType ExtType; 10128 10129 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 10130 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 10131 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 10132 return SDValue(); 10133 10134 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 10135 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 10136 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 10137 return SDValue(); 10138 10139 // The AND is not necessary, remove it. 10140 10141 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 10142 SubsNode->getValueType(1)); 10143 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 10144 10145 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 10146 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 10147 10148 return SDValue(N, 0); 10149 } 10150 10151 // Optimize compare with zero and branch. 10152 static SDValue performBRCONDCombine(SDNode *N, 10153 TargetLowering::DAGCombinerInfo &DCI, 10154 SelectionDAG &DAG) { 10155 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 10156 N = NV.getNode(); 10157 SDValue Chain = N->getOperand(0); 10158 SDValue Dest = N->getOperand(1); 10159 SDValue CCVal = N->getOperand(2); 10160 SDValue Cmp = N->getOperand(3); 10161 10162 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 10163 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 10164 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 10165 return SDValue(); 10166 10167 unsigned CmpOpc = Cmp.getOpcode(); 10168 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 10169 return SDValue(); 10170 10171 // Only attempt folding if there is only one use of the flag and no use of the 10172 // value. 10173 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 10174 return SDValue(); 10175 10176 SDValue LHS = Cmp.getOperand(0); 10177 SDValue RHS = Cmp.getOperand(1); 10178 10179 assert(LHS.getValueType() == RHS.getValueType() && 10180 "Expected the value type to be the same for both operands!"); 10181 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 10182 return SDValue(); 10183 10184 if (isNullConstant(LHS)) 10185 std::swap(LHS, RHS); 10186 10187 if (!isNullConstant(RHS)) 10188 return SDValue(); 10189 10190 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 10191 LHS.getOpcode() == ISD::SRL) 10192 return SDValue(); 10193 10194 // Fold the compare into the branch instruction. 10195 SDValue BR; 10196 if (CC == AArch64CC::EQ) 10197 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 10198 else 10199 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 10200 10201 // Do not add new nodes to DAG combiner worklist. 10202 DCI.CombineTo(N, BR, false); 10203 10204 return SDValue(); 10205 } 10206 10207 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 10208 // as well as whether the test should be inverted. This code is required to 10209 // catch these cases (as opposed to standard dag combines) because 10210 // AArch64ISD::TBZ is matched during legalization. 10211 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 10212 SelectionDAG &DAG) { 10213 10214 if (!Op->hasOneUse()) 10215 return Op; 10216 10217 // We don't handle undef/constant-fold cases below, as they should have 10218 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 10219 // etc.) 10220 10221 // (tbz (trunc x), b) -> (tbz x, b) 10222 // This case is just here to enable more of the below cases to be caught. 10223 if (Op->getOpcode() == ISD::TRUNCATE && 10224 Bit < Op->getValueType(0).getSizeInBits()) { 10225 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10226 } 10227 10228 if (Op->getNumOperands() != 2) 10229 return Op; 10230 10231 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 10232 if (!C) 10233 return Op; 10234 10235 switch (Op->getOpcode()) { 10236 default: 10237 return Op; 10238 10239 // (tbz (and x, m), b) -> (tbz x, b) 10240 case ISD::AND: 10241 if ((C->getZExtValue() >> Bit) & 1) 10242 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10243 return Op; 10244 10245 // (tbz (shl x, c), b) -> (tbz x, b-c) 10246 case ISD::SHL: 10247 if (C->getZExtValue() <= Bit && 10248 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 10249 Bit = Bit - C->getZExtValue(); 10250 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10251 } 10252 return Op; 10253 10254 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 10255 case ISD::SRA: 10256 Bit = Bit + C->getZExtValue(); 10257 if (Bit >= Op->getValueType(0).getSizeInBits()) 10258 Bit = Op->getValueType(0).getSizeInBits() - 1; 10259 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10260 10261 // (tbz (srl x, c), b) -> (tbz x, b+c) 10262 case ISD::SRL: 10263 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 10264 Bit = Bit + C->getZExtValue(); 10265 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10266 } 10267 return Op; 10268 10269 // (tbz (xor x, -1), b) -> (tbnz x, b) 10270 case ISD::XOR: 10271 if ((C->getZExtValue() >> Bit) & 1) 10272 Invert = !Invert; 10273 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10274 } 10275 } 10276 10277 // Optimize test single bit zero/non-zero and branch. 10278 static SDValue performTBZCombine(SDNode *N, 10279 TargetLowering::DAGCombinerInfo &DCI, 10280 SelectionDAG &DAG) { 10281 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10282 bool Invert = false; 10283 SDValue TestSrc = N->getOperand(1); 10284 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 10285 10286 if (TestSrc == NewTestSrc) 10287 return SDValue(); 10288 10289 unsigned NewOpc = N->getOpcode(); 10290 if (Invert) { 10291 if (NewOpc == AArch64ISD::TBZ) 10292 NewOpc = AArch64ISD::TBNZ; 10293 else { 10294 assert(NewOpc == AArch64ISD::TBNZ); 10295 NewOpc = AArch64ISD::TBZ; 10296 } 10297 } 10298 10299 SDLoc DL(N); 10300 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 10301 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 10302 } 10303 10304 // vselect (v1i1 setcc) -> 10305 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 10306 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 10307 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 10308 // such VSELECT. 10309 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 10310 SDValue N0 = N->getOperand(0); 10311 EVT CCVT = N0.getValueType(); 10312 10313 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 10314 CCVT.getVectorElementType() != MVT::i1) 10315 return SDValue(); 10316 10317 EVT ResVT = N->getValueType(0); 10318 EVT CmpVT = N0.getOperand(0).getValueType(); 10319 // Only combine when the result type is of the same size as the compared 10320 // operands. 10321 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 10322 return SDValue(); 10323 10324 SDValue IfTrue = N->getOperand(1); 10325 SDValue IfFalse = N->getOperand(2); 10326 SDValue SetCC = 10327 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 10328 N0.getOperand(0), N0.getOperand(1), 10329 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 10330 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 10331 IfTrue, IfFalse); 10332 } 10333 10334 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 10335 /// the compare-mask instructions rather than going via NZCV, even if LHS and 10336 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 10337 /// with a vector one followed by a DUP shuffle on the result. 10338 static SDValue performSelectCombine(SDNode *N, 10339 TargetLowering::DAGCombinerInfo &DCI) { 10340 SelectionDAG &DAG = DCI.DAG; 10341 SDValue N0 = N->getOperand(0); 10342 EVT ResVT = N->getValueType(0); 10343 10344 if (N0.getOpcode() != ISD::SETCC) 10345 return SDValue(); 10346 10347 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 10348 // scalar SetCCResultType. We also don't expect vectors, because we assume 10349 // that selects fed by vector SETCCs are canonicalized to VSELECT. 10350 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 10351 "Scalar-SETCC feeding SELECT has unexpected result type!"); 10352 10353 // If NumMaskElts == 0, the comparison is larger than select result. The 10354 // largest real NEON comparison is 64-bits per lane, which means the result is 10355 // at most 32-bits and an illegal vector. Just bail out for now. 10356 EVT SrcVT = N0.getOperand(0).getValueType(); 10357 10358 // Don't try to do this optimization when the setcc itself has i1 operands. 10359 // There are no legal vectors of i1, so this would be pointless. 10360 if (SrcVT == MVT::i1) 10361 return SDValue(); 10362 10363 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 10364 if (!ResVT.isVector() || NumMaskElts == 0) 10365 return SDValue(); 10366 10367 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 10368 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 10369 10370 // Also bail out if the vector CCVT isn't the same size as ResVT. 10371 // This can happen if the SETCC operand size doesn't divide the ResVT size 10372 // (e.g., f64 vs v3f32). 10373 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 10374 return SDValue(); 10375 10376 // Make sure we didn't create illegal types, if we're not supposed to. 10377 assert(DCI.isBeforeLegalize() || 10378 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 10379 10380 // First perform a vector comparison, where lane 0 is the one we're interested 10381 // in. 10382 SDLoc DL(N0); 10383 SDValue LHS = 10384 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 10385 SDValue RHS = 10386 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 10387 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 10388 10389 // Now duplicate the comparison mask we want across all other lanes. 10390 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 10391 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 10392 Mask = DAG.getNode(ISD::BITCAST, DL, 10393 ResVT.changeVectorElementTypeToInteger(), Mask); 10394 10395 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 10396 } 10397 10398 /// Get rid of unnecessary NVCASTs (that don't change the type). 10399 static SDValue performNVCASTCombine(SDNode *N) { 10400 if (N->getValueType(0) == N->getOperand(0).getValueType()) 10401 return N->getOperand(0); 10402 10403 return SDValue(); 10404 } 10405 10406 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 10407 DAGCombinerInfo &DCI) const { 10408 SelectionDAG &DAG = DCI.DAG; 10409 switch (N->getOpcode()) { 10410 default: 10411 DEBUG(dbgs() << "Custom combining: skipping\n"); 10412 break; 10413 case ISD::ADD: 10414 case ISD::SUB: 10415 return performAddSubLongCombine(N, DCI, DAG); 10416 case ISD::XOR: 10417 return performXorCombine(N, DAG, DCI, Subtarget); 10418 case ISD::MUL: 10419 return performMulCombine(N, DAG, DCI, Subtarget); 10420 case ISD::SINT_TO_FP: 10421 case ISD::UINT_TO_FP: 10422 return performIntToFpCombine(N, DAG, Subtarget); 10423 case ISD::FP_TO_SINT: 10424 case ISD::FP_TO_UINT: 10425 return performFpToIntCombine(N, DAG, DCI, Subtarget); 10426 case ISD::FDIV: 10427 return performFDivCombine(N, DAG, DCI, Subtarget); 10428 case ISD::OR: 10429 return performORCombine(N, DCI, Subtarget); 10430 case ISD::SRL: 10431 return performSRLCombine(N, DCI); 10432 case ISD::INTRINSIC_WO_CHAIN: 10433 return performIntrinsicCombine(N, DCI, Subtarget); 10434 case ISD::ANY_EXTEND: 10435 case ISD::ZERO_EXTEND: 10436 case ISD::SIGN_EXTEND: 10437 return performExtendCombine(N, DCI, DAG); 10438 case ISD::BITCAST: 10439 return performBitcastCombine(N, DCI, DAG); 10440 case ISD::CONCAT_VECTORS: 10441 return performConcatVectorsCombine(N, DCI, DAG); 10442 case ISD::SELECT: 10443 return performSelectCombine(N, DCI); 10444 case ISD::VSELECT: 10445 return performVSelectCombine(N, DCI.DAG); 10446 case ISD::LOAD: 10447 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 10448 return SDValue(N, 0); 10449 break; 10450 case ISD::STORE: 10451 return performSTORECombine(N, DCI, DAG, Subtarget); 10452 case AArch64ISD::BRCOND: 10453 return performBRCONDCombine(N, DCI, DAG); 10454 case AArch64ISD::TBNZ: 10455 case AArch64ISD::TBZ: 10456 return performTBZCombine(N, DCI, DAG); 10457 case AArch64ISD::CSEL: 10458 return performCONDCombine(N, DCI, DAG, 2, 3); 10459 case AArch64ISD::DUP: 10460 return performPostLD1Combine(N, DCI, false); 10461 case AArch64ISD::NVCAST: 10462 return performNVCASTCombine(N); 10463 case ISD::INSERT_VECTOR_ELT: 10464 return performPostLD1Combine(N, DCI, true); 10465 case ISD::INTRINSIC_VOID: 10466 case ISD::INTRINSIC_W_CHAIN: 10467 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10468 case Intrinsic::aarch64_neon_ld2: 10469 case Intrinsic::aarch64_neon_ld3: 10470 case Intrinsic::aarch64_neon_ld4: 10471 case Intrinsic::aarch64_neon_ld1x2: 10472 case Intrinsic::aarch64_neon_ld1x3: 10473 case Intrinsic::aarch64_neon_ld1x4: 10474 case Intrinsic::aarch64_neon_ld2lane: 10475 case Intrinsic::aarch64_neon_ld3lane: 10476 case Intrinsic::aarch64_neon_ld4lane: 10477 case Intrinsic::aarch64_neon_ld2r: 10478 case Intrinsic::aarch64_neon_ld3r: 10479 case Intrinsic::aarch64_neon_ld4r: 10480 case Intrinsic::aarch64_neon_st2: 10481 case Intrinsic::aarch64_neon_st3: 10482 case Intrinsic::aarch64_neon_st4: 10483 case Intrinsic::aarch64_neon_st1x2: 10484 case Intrinsic::aarch64_neon_st1x3: 10485 case Intrinsic::aarch64_neon_st1x4: 10486 case Intrinsic::aarch64_neon_st2lane: 10487 case Intrinsic::aarch64_neon_st3lane: 10488 case Intrinsic::aarch64_neon_st4lane: 10489 return performNEONPostLDSTCombine(N, DCI, DAG); 10490 default: 10491 break; 10492 } 10493 } 10494 return SDValue(); 10495 } 10496 10497 // Check if the return value is used as only a return value, as otherwise 10498 // we can't perform a tail-call. In particular, we need to check for 10499 // target ISD nodes that are returns and any other "odd" constructs 10500 // that the generic analysis code won't necessarily catch. 10501 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 10502 SDValue &Chain) const { 10503 if (N->getNumValues() != 1) 10504 return false; 10505 if (!N->hasNUsesOfValue(1, 0)) 10506 return false; 10507 10508 SDValue TCChain = Chain; 10509 SDNode *Copy = *N->use_begin(); 10510 if (Copy->getOpcode() == ISD::CopyToReg) { 10511 // If the copy has a glue operand, we conservatively assume it isn't safe to 10512 // perform a tail call. 10513 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 10514 MVT::Glue) 10515 return false; 10516 TCChain = Copy->getOperand(0); 10517 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 10518 return false; 10519 10520 bool HasRet = false; 10521 for (SDNode *Node : Copy->uses()) { 10522 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 10523 return false; 10524 HasRet = true; 10525 } 10526 10527 if (!HasRet) 10528 return false; 10529 10530 Chain = TCChain; 10531 return true; 10532 } 10533 10534 // Return whether the an instruction can potentially be optimized to a tail 10535 // call. This will cause the optimizers to attempt to move, or duplicate, 10536 // return instructions to help enable tail call optimizations for this 10537 // instruction. 10538 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10539 return CI->isTailCall(); 10540 } 10541 10542 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 10543 SDValue &Offset, 10544 ISD::MemIndexedMode &AM, 10545 bool &IsInc, 10546 SelectionDAG &DAG) const { 10547 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 10548 return false; 10549 10550 Base = Op->getOperand(0); 10551 // All of the indexed addressing mode instructions take a signed 10552 // 9 bit immediate offset. 10553 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 10554 int64_t RHSC = RHS->getSExtValue(); 10555 if (Op->getOpcode() == ISD::SUB) 10556 RHSC = -(uint64_t)RHSC; 10557 if (!isInt<9>(RHSC)) 10558 return false; 10559 IsInc = (Op->getOpcode() == ISD::ADD); 10560 Offset = Op->getOperand(1); 10561 return true; 10562 } 10563 return false; 10564 } 10565 10566 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 10567 SDValue &Offset, 10568 ISD::MemIndexedMode &AM, 10569 SelectionDAG &DAG) const { 10570 EVT VT; 10571 SDValue Ptr; 10572 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10573 VT = LD->getMemoryVT(); 10574 Ptr = LD->getBasePtr(); 10575 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10576 VT = ST->getMemoryVT(); 10577 Ptr = ST->getBasePtr(); 10578 } else 10579 return false; 10580 10581 bool IsInc; 10582 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 10583 return false; 10584 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 10585 return true; 10586 } 10587 10588 bool AArch64TargetLowering::getPostIndexedAddressParts( 10589 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 10590 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 10591 EVT VT; 10592 SDValue Ptr; 10593 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10594 VT = LD->getMemoryVT(); 10595 Ptr = LD->getBasePtr(); 10596 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10597 VT = ST->getMemoryVT(); 10598 Ptr = ST->getBasePtr(); 10599 } else 10600 return false; 10601 10602 bool IsInc; 10603 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 10604 return false; 10605 // Post-indexing updates the base, so it's not a valid transform 10606 // if that's not the same as the load's pointer. 10607 if (Ptr != Base) 10608 return false; 10609 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 10610 return true; 10611 } 10612 10613 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 10614 SelectionDAG &DAG) { 10615 SDLoc DL(N); 10616 SDValue Op = N->getOperand(0); 10617 10618 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 10619 return; 10620 10621 Op = SDValue( 10622 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 10623 DAG.getUNDEF(MVT::i32), Op, 10624 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 10625 0); 10626 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 10627 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 10628 } 10629 10630 static void ReplaceReductionResults(SDNode *N, 10631 SmallVectorImpl<SDValue> &Results, 10632 SelectionDAG &DAG, unsigned InterOp, 10633 unsigned AcrossOp) { 10634 EVT LoVT, HiVT; 10635 SDValue Lo, Hi; 10636 SDLoc dl(N); 10637 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 10638 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 10639 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 10640 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 10641 Results.push_back(SplitVal); 10642 } 10643 10644 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 10645 SDLoc DL(N); 10646 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 10647 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 10648 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 10649 DAG.getConstant(64, DL, MVT::i64))); 10650 return std::make_pair(Lo, Hi); 10651 } 10652 10653 static void ReplaceCMP_SWAP_128Results(SDNode *N, 10654 SmallVectorImpl<SDValue> & Results, 10655 SelectionDAG &DAG) { 10656 assert(N->getValueType(0) == MVT::i128 && 10657 "AtomicCmpSwap on types less than 128 should be legal"); 10658 auto Desired = splitInt128(N->getOperand(2), DAG); 10659 auto New = splitInt128(N->getOperand(3), DAG); 10660 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 10661 New.first, New.second, N->getOperand(0)}; 10662 SDNode *CmpSwap = DAG.getMachineNode( 10663 AArch64::CMP_SWAP_128, SDLoc(N), 10664 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 10665 10666 MachineFunction &MF = DAG.getMachineFunction(); 10667 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 10668 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 10669 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 10670 10671 Results.push_back(SDValue(CmpSwap, 0)); 10672 Results.push_back(SDValue(CmpSwap, 1)); 10673 Results.push_back(SDValue(CmpSwap, 3)); 10674 } 10675 10676 void AArch64TargetLowering::ReplaceNodeResults( 10677 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 10678 switch (N->getOpcode()) { 10679 default: 10680 llvm_unreachable("Don't know how to custom expand this"); 10681 case ISD::BITCAST: 10682 ReplaceBITCASTResults(N, Results, DAG); 10683 return; 10684 case ISD::VECREDUCE_ADD: 10685 case ISD::VECREDUCE_SMAX: 10686 case ISD::VECREDUCE_SMIN: 10687 case ISD::VECREDUCE_UMAX: 10688 case ISD::VECREDUCE_UMIN: 10689 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 10690 return; 10691 10692 case AArch64ISD::SADDV: 10693 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 10694 return; 10695 case AArch64ISD::UADDV: 10696 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 10697 return; 10698 case AArch64ISD::SMINV: 10699 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 10700 return; 10701 case AArch64ISD::UMINV: 10702 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 10703 return; 10704 case AArch64ISD::SMAXV: 10705 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 10706 return; 10707 case AArch64ISD::UMAXV: 10708 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 10709 return; 10710 case ISD::FP_TO_UINT: 10711 case ISD::FP_TO_SINT: 10712 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 10713 // Let normal code take care of it by not adding anything to Results. 10714 return; 10715 case ISD::ATOMIC_CMP_SWAP: 10716 ReplaceCMP_SWAP_128Results(N, Results, DAG); 10717 return; 10718 } 10719 } 10720 10721 bool AArch64TargetLowering::useLoadStackGuardNode() const { 10722 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 10723 return TargetLowering::useLoadStackGuardNode(); 10724 return true; 10725 } 10726 10727 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 10728 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10729 // reciprocal if there are three or more FDIVs. 10730 return 3; 10731 } 10732 10733 TargetLoweringBase::LegalizeTypeAction 10734 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const { 10735 MVT SVT = VT.getSimpleVT(); 10736 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 10737 // v4i16, v2i32 instead of to promote. 10738 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32 10739 || SVT == MVT::v1f32) 10740 return TypeWidenVector; 10741 10742 return TargetLoweringBase::getPreferredVectorAction(VT); 10743 } 10744 10745 // Loads and stores less than 128-bits are already atomic; ones above that 10746 // are doomed anyway, so defer to the default libcall and blame the OS when 10747 // things go wrong. 10748 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 10749 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 10750 return Size == 128; 10751 } 10752 10753 // Loads and stores less than 128-bits are already atomic; ones above that 10754 // are doomed anyway, so defer to the default libcall and blame the OS when 10755 // things go wrong. 10756 TargetLowering::AtomicExpansionKind 10757 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 10758 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 10759 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10760 } 10761 10762 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 10763 TargetLowering::AtomicExpansionKind 10764 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10765 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10766 if (Size > 128) return AtomicExpansionKind::None; 10767 // Nand not supported in LSE. 10768 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 10769 // Leave 128 bits to LLSC. 10770 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC; 10771 } 10772 10773 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 10774 AtomicCmpXchgInst *AI) const { 10775 // If subtarget has LSE, leave cmpxchg intact for codegen. 10776 if (Subtarget->hasLSE()) return false; 10777 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 10778 // implement cmpxchg without spilling. If the address being exchanged is also 10779 // on the stack and close enough to the spill slot, this can lead to a 10780 // situation where the monitor always gets cleared and the atomic operation 10781 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 10782 return getTargetMachine().getOptLevel() != 0; 10783 } 10784 10785 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 10786 AtomicOrdering Ord) const { 10787 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10788 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 10789 bool IsAcquire = isAcquireOrStronger(Ord); 10790 10791 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 10792 // intrinsic must return {i64, i64} and we have to recombine them into a 10793 // single i128 here. 10794 if (ValTy->getPrimitiveSizeInBits() == 128) { 10795 Intrinsic::ID Int = 10796 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 10797 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 10798 10799 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10800 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 10801 10802 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 10803 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 10804 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 10805 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 10806 return Builder.CreateOr( 10807 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 10808 } 10809 10810 Type *Tys[] = { Addr->getType() }; 10811 Intrinsic::ID Int = 10812 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 10813 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 10814 10815 return Builder.CreateTruncOrBitCast( 10816 Builder.CreateCall(Ldxr, Addr), 10817 cast<PointerType>(Addr->getType())->getElementType()); 10818 } 10819 10820 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 10821 IRBuilder<> &Builder) const { 10822 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10823 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 10824 } 10825 10826 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 10827 Value *Val, Value *Addr, 10828 AtomicOrdering Ord) const { 10829 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10830 bool IsRelease = isReleaseOrStronger(Ord); 10831 10832 // Since the intrinsics must have legal type, the i128 intrinsics take two 10833 // parameters: "i64, i64". We must marshal Val into the appropriate form 10834 // before the call. 10835 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 10836 Intrinsic::ID Int = 10837 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 10838 Function *Stxr = Intrinsic::getDeclaration(M, Int); 10839 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 10840 10841 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 10842 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 10843 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10844 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 10845 } 10846 10847 Intrinsic::ID Int = 10848 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 10849 Type *Tys[] = { Addr->getType() }; 10850 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 10851 10852 return Builder.CreateCall(Stxr, 10853 {Builder.CreateZExtOrBitCast( 10854 Val, Stxr->getFunctionType()->getParamType(0)), 10855 Addr}); 10856 } 10857 10858 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 10859 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 10860 return Ty->isArrayTy(); 10861 } 10862 10863 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 10864 EVT) const { 10865 return false; 10866 } 10867 10868 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 10869 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10870 Function *ThreadPointerFunc = 10871 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 10872 return IRB.CreatePointerCast( 10873 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset), 10874 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10875 } 10876 10877 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 10878 // Android provides a fixed TLS slot for the stack cookie. See the definition 10879 // of TLS_SLOT_STACK_GUARD in 10880 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10881 if (Subtarget->isTargetAndroid()) 10882 return UseTlsOffset(IRB, 0x28); 10883 10884 // Fuchsia is similar. 10885 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 10886 if (Subtarget->isTargetFuchsia()) 10887 return UseTlsOffset(IRB, -0x10); 10888 10889 return TargetLowering::getIRStackGuard(IRB); 10890 } 10891 10892 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 10893 // Android provides a fixed TLS slot for the SafeStack pointer. See the 10894 // definition of TLS_SLOT_SAFESTACK in 10895 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10896 if (Subtarget->isTargetAndroid()) 10897 return UseTlsOffset(IRB, 0x48); 10898 10899 // Fuchsia is similar. 10900 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 10901 if (Subtarget->isTargetFuchsia()) 10902 return UseTlsOffset(IRB, -0x8); 10903 10904 return TargetLowering::getSafeStackPointerLocation(IRB); 10905 } 10906 10907 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 10908 const Instruction &AndI) const { 10909 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 10910 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 10911 // may be beneficial to sink in other cases, but we would have to check that 10912 // the cmp would not get folded into the br to form a cbz for these to be 10913 // beneficial. 10914 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 10915 if (!Mask) 10916 return false; 10917 return Mask->getValue().isPowerOf2(); 10918 } 10919 10920 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 10921 // Update IsSplitCSR in AArch64unctionInfo. 10922 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 10923 AFI->setIsSplitCSR(true); 10924 } 10925 10926 void AArch64TargetLowering::insertCopiesSplitCSR( 10927 MachineBasicBlock *Entry, 10928 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 10929 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10930 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 10931 if (!IStart) 10932 return; 10933 10934 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10935 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 10936 MachineBasicBlock::iterator MBBI = Entry->begin(); 10937 for (const MCPhysReg *I = IStart; *I; ++I) { 10938 const TargetRegisterClass *RC = nullptr; 10939 if (AArch64::GPR64RegClass.contains(*I)) 10940 RC = &AArch64::GPR64RegClass; 10941 else if (AArch64::FPR64RegClass.contains(*I)) 10942 RC = &AArch64::FPR64RegClass; 10943 else 10944 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 10945 10946 unsigned NewVR = MRI->createVirtualRegister(RC); 10947 // Create copy from CSR to a virtual register. 10948 // FIXME: this currently does not emit CFI pseudo-instructions, it works 10949 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 10950 // nounwind. If we want to generalize this later, we may need to emit 10951 // CFI pseudo-instructions. 10952 assert(Entry->getParent()->getFunction()->hasFnAttribute( 10953 Attribute::NoUnwind) && 10954 "Function should be nounwind in insertCopiesSplitCSR!"); 10955 Entry->addLiveIn(*I); 10956 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 10957 .addReg(*I); 10958 10959 // Insert the copy-back instructions right before the terminator. 10960 for (auto *Exit : Exits) 10961 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 10962 TII->get(TargetOpcode::COPY), *I) 10963 .addReg(NewVR); 10964 } 10965 } 10966 10967 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 10968 // Integer division on AArch64 is expensive. However, when aggressively 10969 // optimizing for code size, we prefer to use a div instruction, as it is 10970 // usually smaller than the alternative sequence. 10971 // The exception to this is vector division. Since AArch64 doesn't have vector 10972 // integer division, leaving the division as-is is a loss even in terms of 10973 // size, because it will have to be scalarized, while the alternative code 10974 // sequence can be performed in vector form. 10975 bool OptSize = 10976 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize); 10977 return OptSize && !VT.isVector(); 10978 } 10979 10980 unsigned 10981 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 10982 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 10983 return getPointerTy(DL).getSizeInBits(); 10984 10985 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 10986 } 10987