1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that ARM uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "ARMISelLowering.h" 15 #include "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMCallingConv.h" 18 #include "ARMConstantPoolValue.h" 19 #include "ARMMachineFunctionInfo.h" 20 #include "ARMPerfectShuffle.h" 21 #include "ARMRegisterInfo.h" 22 #include "ARMSelectionDAGInfo.h" 23 #include "ARMSubtarget.h" 24 #include "ARMTargetTransformInfo.h" 25 #include "MCTargetDesc/ARMAddressingModes.h" 26 #include "MCTargetDesc/ARMBaseInfo.h" 27 #include "Utils/ARMBaseInfo.h" 28 #include "llvm/ADT/APFloat.h" 29 #include "llvm/ADT/APInt.h" 30 #include "llvm/ADT/ArrayRef.h" 31 #include "llvm/ADT/BitVector.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/Statistic.h" 37 #include "llvm/ADT/StringExtras.h" 38 #include "llvm/ADT/StringRef.h" 39 #include "llvm/ADT/StringSwitch.h" 40 #include "llvm/ADT/Triple.h" 41 #include "llvm/ADT/Twine.h" 42 #include "llvm/Analysis/VectorUtils.h" 43 #include "llvm/CodeGen/CallingConvLower.h" 44 #include "llvm/CodeGen/ISDOpcodes.h" 45 #include "llvm/CodeGen/IntrinsicLowering.h" 46 #include "llvm/CodeGen/MachineBasicBlock.h" 47 #include "llvm/CodeGen/MachineConstantPool.h" 48 #include "llvm/CodeGen/MachineFrameInfo.h" 49 #include "llvm/CodeGen/MachineFunction.h" 50 #include "llvm/CodeGen/MachineInstr.h" 51 #include "llvm/CodeGen/MachineInstrBuilder.h" 52 #include "llvm/CodeGen/MachineJumpTableInfo.h" 53 #include "llvm/CodeGen/MachineMemOperand.h" 54 #include "llvm/CodeGen/MachineOperand.h" 55 #include "llvm/CodeGen/MachineRegisterInfo.h" 56 #include "llvm/CodeGen/RuntimeLibcalls.h" 57 #include "llvm/CodeGen/SelectionDAG.h" 58 #include "llvm/CodeGen/SelectionDAGNodes.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/IR/Attributes.h" 66 #include "llvm/IR/CallingConv.h" 67 #include "llvm/IR/Constant.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugLoc.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GlobalAlias.h" 74 #include "llvm/IR/GlobalValue.h" 75 #include "llvm/IR/GlobalVariable.h" 76 #include "llvm/IR/IRBuilder.h" 77 #include "llvm/IR/InlineAsm.h" 78 #include "llvm/IR/Instruction.h" 79 #include "llvm/IR/Instructions.h" 80 #include "llvm/IR/IntrinsicInst.h" 81 #include "llvm/IR/Intrinsics.h" 82 #include "llvm/IR/IntrinsicsARM.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/PatternMatch.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCInstrDesc.h" 89 #include "llvm/MC/MCInstrItineraries.h" 90 #include "llvm/MC/MCRegisterInfo.h" 91 #include "llvm/MC/MCSchedule.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/BranchProbability.h" 94 #include "llvm/Support/Casting.h" 95 #include "llvm/Support/CodeGen.h" 96 #include "llvm/Support/CommandLine.h" 97 #include "llvm/Support/Compiler.h" 98 #include "llvm/Support/Debug.h" 99 #include "llvm/Support/ErrorHandling.h" 100 #include "llvm/Support/KnownBits.h" 101 #include "llvm/Support/MachineValueType.h" 102 #include "llvm/Support/MathExtras.h" 103 #include "llvm/Support/raw_ostream.h" 104 #include "llvm/Target/TargetMachine.h" 105 #include "llvm/Target/TargetOptions.h" 106 #include <algorithm> 107 #include <cassert> 108 #include <cstdint> 109 #include <cstdlib> 110 #include <iterator> 111 #include <limits> 112 #include <string> 113 #include <tuple> 114 #include <utility> 115 #include <vector> 116 117 using namespace llvm; 118 using namespace llvm::PatternMatch; 119 120 #define DEBUG_TYPE "arm-isel" 121 122 STATISTIC(NumTailCalls, "Number of tail calls"); 123 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 124 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 125 STATISTIC(NumConstpoolPromoted, 126 "Number of constants with their storage promoted into constant pools"); 127 128 static cl::opt<bool> 129 ARMInterworking("arm-interworking", cl::Hidden, 130 cl::desc("Enable / disable ARM interworking (for debugging only)"), 131 cl::init(true)); 132 133 static cl::opt<bool> EnableConstpoolPromotion( 134 "arm-promote-constant", cl::Hidden, 135 cl::desc("Enable / disable promotion of unnamed_addr constants into " 136 "constant pools"), 137 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 138 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 139 "arm-promote-constant-max-size", cl::Hidden, 140 cl::desc("Maximum size of constant to promote into a constant pool"), 141 cl::init(64)); 142 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 143 "arm-promote-constant-max-total", cl::Hidden, 144 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 145 cl::init(128)); 146 147 cl::opt<unsigned> 148 MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden, 149 cl::desc("Maximum interleave factor for MVE VLDn to generate."), 150 cl::init(2)); 151 152 // The APCS parameter registers. 153 static const MCPhysReg GPRArgRegs[] = { 154 ARM::R0, ARM::R1, ARM::R2, ARM::R3 155 }; 156 157 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 158 MVT PromotedBitwiseVT) { 159 if (VT != PromotedLdStVT) { 160 setOperationAction(ISD::LOAD, VT, Promote); 161 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 162 163 setOperationAction(ISD::STORE, VT, Promote); 164 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 165 } 166 167 MVT ElemTy = VT.getVectorElementType(); 168 if (ElemTy != MVT::f64) 169 setOperationAction(ISD::SETCC, VT, Custom); 170 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 171 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 172 if (ElemTy == MVT::i32) { 173 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 174 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 175 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 176 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 177 } else { 178 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 179 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 180 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 181 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 182 } 183 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 184 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 185 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 186 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 187 setOperationAction(ISD::SELECT, VT, Expand); 188 setOperationAction(ISD::SELECT_CC, VT, Expand); 189 setOperationAction(ISD::VSELECT, VT, Expand); 190 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 191 if (VT.isInteger()) { 192 setOperationAction(ISD::SHL, VT, Custom); 193 setOperationAction(ISD::SRA, VT, Custom); 194 setOperationAction(ISD::SRL, VT, Custom); 195 } 196 197 // Promote all bit-wise operations. 198 if (VT.isInteger() && VT != PromotedBitwiseVT) { 199 setOperationAction(ISD::AND, VT, Promote); 200 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 201 setOperationAction(ISD::OR, VT, Promote); 202 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 203 setOperationAction(ISD::XOR, VT, Promote); 204 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 205 } 206 207 // Neon does not support vector divide/remainder operations. 208 setOperationAction(ISD::SDIV, VT, Expand); 209 setOperationAction(ISD::UDIV, VT, Expand); 210 setOperationAction(ISD::FDIV, VT, Expand); 211 setOperationAction(ISD::SREM, VT, Expand); 212 setOperationAction(ISD::UREM, VT, Expand); 213 setOperationAction(ISD::FREM, VT, Expand); 214 setOperationAction(ISD::SDIVREM, VT, Expand); 215 setOperationAction(ISD::UDIVREM, VT, Expand); 216 217 if (!VT.isFloatingPoint() && 218 VT != MVT::v2i64 && VT != MVT::v1i64) 219 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 220 setOperationAction(Opcode, VT, Legal); 221 if (!VT.isFloatingPoint()) 222 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}) 223 setOperationAction(Opcode, VT, Legal); 224 } 225 226 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 227 addRegisterClass(VT, &ARM::DPRRegClass); 228 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 229 } 230 231 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 232 addRegisterClass(VT, &ARM::DPairRegClass); 233 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 234 } 235 236 void ARMTargetLowering::setAllExpand(MVT VT) { 237 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc) 238 setOperationAction(Opc, VT, Expand); 239 240 // We support these really simple operations even on types where all 241 // the actual arithmetic has to be broken down into simpler 242 // operations or turned into library calls. 243 setOperationAction(ISD::BITCAST, VT, Legal); 244 setOperationAction(ISD::LOAD, VT, Legal); 245 setOperationAction(ISD::STORE, VT, Legal); 246 setOperationAction(ISD::UNDEF, VT, Legal); 247 } 248 249 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To, 250 LegalizeAction Action) { 251 setLoadExtAction(ISD::EXTLOAD, From, To, Action); 252 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action); 253 setLoadExtAction(ISD::SEXTLOAD, From, To, Action); 254 } 255 256 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) { 257 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 }; 258 259 for (auto VT : IntTypes) { 260 addRegisterClass(VT, &ARM::MQPRRegClass); 261 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 262 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 263 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 264 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 265 setOperationAction(ISD::SHL, VT, Custom); 266 setOperationAction(ISD::SRA, VT, Custom); 267 setOperationAction(ISD::SRL, VT, Custom); 268 setOperationAction(ISD::SMIN, VT, Legal); 269 setOperationAction(ISD::SMAX, VT, Legal); 270 setOperationAction(ISD::UMIN, VT, Legal); 271 setOperationAction(ISD::UMAX, VT, Legal); 272 setOperationAction(ISD::ABS, VT, Legal); 273 setOperationAction(ISD::SETCC, VT, Custom); 274 setOperationAction(ISD::MLOAD, VT, Custom); 275 setOperationAction(ISD::MSTORE, VT, Legal); 276 setOperationAction(ISD::CTLZ, VT, Legal); 277 setOperationAction(ISD::CTTZ, VT, Custom); 278 setOperationAction(ISD::BITREVERSE, VT, Legal); 279 setOperationAction(ISD::BSWAP, VT, Legal); 280 setOperationAction(ISD::SADDSAT, VT, Legal); 281 setOperationAction(ISD::UADDSAT, VT, Legal); 282 setOperationAction(ISD::SSUBSAT, VT, Legal); 283 setOperationAction(ISD::USUBSAT, VT, Legal); 284 285 // No native support for these. 286 setOperationAction(ISD::UDIV, VT, Expand); 287 setOperationAction(ISD::SDIV, VT, Expand); 288 setOperationAction(ISD::UREM, VT, Expand); 289 setOperationAction(ISD::SREM, VT, Expand); 290 setOperationAction(ISD::UDIVREM, VT, Expand); 291 setOperationAction(ISD::SDIVREM, VT, Expand); 292 setOperationAction(ISD::CTPOP, VT, Expand); 293 setOperationAction(ISD::SELECT, VT, Expand); 294 setOperationAction(ISD::SELECT_CC, VT, Expand); 295 296 // Vector reductions 297 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal); 298 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal); 299 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal); 300 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal); 301 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal); 302 setOperationAction(ISD::VECREDUCE_MUL, VT, Custom); 303 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 304 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 305 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 306 307 if (!HasMVEFP) { 308 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 309 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 310 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 311 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 312 } 313 314 // Pre and Post inc are supported on loads and stores 315 for (unsigned im = (unsigned)ISD::PRE_INC; 316 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 317 setIndexedLoadAction(im, VT, Legal); 318 setIndexedStoreAction(im, VT, Legal); 319 setIndexedMaskedLoadAction(im, VT, Legal); 320 setIndexedMaskedStoreAction(im, VT, Legal); 321 } 322 } 323 324 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 325 for (auto VT : FloatTypes) { 326 addRegisterClass(VT, &ARM::MQPRRegClass); 327 if (!HasMVEFP) 328 setAllExpand(VT); 329 330 // These are legal or custom whether we have MVE.fp or not 331 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 332 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 333 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 334 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 335 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 336 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 337 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 338 setOperationAction(ISD::SETCC, VT, Custom); 339 setOperationAction(ISD::MLOAD, VT, Custom); 340 setOperationAction(ISD::MSTORE, VT, Legal); 341 setOperationAction(ISD::SELECT, VT, Expand); 342 setOperationAction(ISD::SELECT_CC, VT, Expand); 343 344 // Pre and Post inc are supported on loads and stores 345 for (unsigned im = (unsigned)ISD::PRE_INC; 346 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 347 setIndexedLoadAction(im, VT, Legal); 348 setIndexedStoreAction(im, VT, Legal); 349 setIndexedMaskedLoadAction(im, VT, Legal); 350 setIndexedMaskedStoreAction(im, VT, Legal); 351 } 352 353 if (HasMVEFP) { 354 setOperationAction(ISD::FMINNUM, VT, Legal); 355 setOperationAction(ISD::FMAXNUM, VT, Legal); 356 setOperationAction(ISD::FROUND, VT, Legal); 357 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 358 setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom); 359 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 360 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 361 362 // No native support for these. 363 setOperationAction(ISD::FDIV, VT, Expand); 364 setOperationAction(ISD::FREM, VT, Expand); 365 setOperationAction(ISD::FSQRT, VT, Expand); 366 setOperationAction(ISD::FSIN, VT, Expand); 367 setOperationAction(ISD::FCOS, VT, Expand); 368 setOperationAction(ISD::FPOW, VT, Expand); 369 setOperationAction(ISD::FLOG, VT, Expand); 370 setOperationAction(ISD::FLOG2, VT, Expand); 371 setOperationAction(ISD::FLOG10, VT, Expand); 372 setOperationAction(ISD::FEXP, VT, Expand); 373 setOperationAction(ISD::FEXP2, VT, Expand); 374 setOperationAction(ISD::FNEARBYINT, VT, Expand); 375 } 376 } 377 378 // Custom Expand smaller than legal vector reductions to prevent false zero 379 // items being added. 380 setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom); 381 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom); 382 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom); 383 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom); 384 setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom); 385 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom); 386 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom); 387 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom); 388 389 // We 'support' these types up to bitcast/load/store level, regardless of 390 // MVE integer-only / float support. Only doing FP data processing on the FP 391 // vector types is inhibited at integer-only level. 392 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 393 for (auto VT : LongTypes) { 394 addRegisterClass(VT, &ARM::MQPRRegClass); 395 setAllExpand(VT); 396 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 398 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 399 } 400 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 401 402 // We can do bitwise operations on v2i64 vectors 403 setOperationAction(ISD::AND, MVT::v2i64, Legal); 404 setOperationAction(ISD::OR, MVT::v2i64, Legal); 405 setOperationAction(ISD::XOR, MVT::v2i64, Legal); 406 407 // It is legal to extload from v4i8 to v4i16 or v4i32. 408 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 409 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 410 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 411 412 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16. 413 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 414 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 415 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 416 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Legal); 417 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal); 418 419 // Some truncating stores are legal too. 420 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 421 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 422 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 423 424 // Pre and Post inc on these are legal, given the correct extends 425 for (unsigned im = (unsigned)ISD::PRE_INC; 426 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 427 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) { 428 setIndexedLoadAction(im, VT, Legal); 429 setIndexedStoreAction(im, VT, Legal); 430 setIndexedMaskedLoadAction(im, VT, Legal); 431 setIndexedMaskedStoreAction(im, VT, Legal); 432 } 433 } 434 435 // Predicate types 436 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1}; 437 for (auto VT : pTypes) { 438 addRegisterClass(VT, &ARM::VCCRRegClass); 439 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 440 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 441 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 442 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 443 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 444 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 445 setOperationAction(ISD::SETCC, VT, Custom); 446 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 447 setOperationAction(ISD::LOAD, VT, Custom); 448 setOperationAction(ISD::STORE, VT, Custom); 449 setOperationAction(ISD::TRUNCATE, VT, Custom); 450 setOperationAction(ISD::VSELECT, VT, Expand); 451 setOperationAction(ISD::SELECT, VT, Expand); 452 } 453 } 454 455 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 456 const ARMSubtarget &STI) 457 : TargetLowering(TM), Subtarget(&STI) { 458 RegInfo = Subtarget->getRegisterInfo(); 459 Itins = Subtarget->getInstrItineraryData(); 460 461 setBooleanContents(ZeroOrOneBooleanContent); 462 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 463 464 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 465 !Subtarget->isTargetWatchOS()) { 466 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 467 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 468 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 469 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 470 : CallingConv::ARM_AAPCS); 471 } 472 473 if (Subtarget->isTargetMachO()) { 474 // Uses VFP for Thumb libfuncs if available. 475 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 476 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 477 static const struct { 478 const RTLIB::Libcall Op; 479 const char * const Name; 480 const ISD::CondCode Cond; 481 } LibraryCalls[] = { 482 // Single-precision floating-point arithmetic. 483 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 484 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 485 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 486 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 487 488 // Double-precision floating-point arithmetic. 489 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 490 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 491 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 492 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 493 494 // Single-precision comparisons. 495 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 496 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 497 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 498 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 499 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 500 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 501 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 502 503 // Double-precision comparisons. 504 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 505 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 506 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 507 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 508 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 509 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 510 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 511 512 // Floating-point to integer conversions. 513 // i64 conversions are done via library routines even when generating VFP 514 // instructions, so use the same ones. 515 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 516 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 517 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 518 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 519 520 // Conversions between floating types. 521 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 522 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 523 524 // Integer to floating-point conversions. 525 // i64 conversions are done via library routines even when generating VFP 526 // instructions, so use the same ones. 527 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 528 // e.g., __floatunsidf vs. __floatunssidfvfp. 529 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 530 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 531 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 532 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 533 }; 534 535 for (const auto &LC : LibraryCalls) { 536 setLibcallName(LC.Op, LC.Name); 537 if (LC.Cond != ISD::SETCC_INVALID) 538 setCmpLibcallCC(LC.Op, LC.Cond); 539 } 540 } 541 } 542 543 // These libcalls are not available in 32-bit. 544 setLibcallName(RTLIB::SHL_I128, nullptr); 545 setLibcallName(RTLIB::SRL_I128, nullptr); 546 setLibcallName(RTLIB::SRA_I128, nullptr); 547 548 // RTLIB 549 if (Subtarget->isAAPCS_ABI() && 550 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 551 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 552 static const struct { 553 const RTLIB::Libcall Op; 554 const char * const Name; 555 const CallingConv::ID CC; 556 const ISD::CondCode Cond; 557 } LibraryCalls[] = { 558 // Double-precision floating-point arithmetic helper functions 559 // RTABI chapter 4.1.2, Table 2 560 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 561 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 562 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 563 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 564 565 // Double-precision floating-point comparison helper functions 566 // RTABI chapter 4.1.2, Table 3 567 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 568 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 569 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 570 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 571 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 572 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 573 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 574 575 // Single-precision floating-point arithmetic helper functions 576 // RTABI chapter 4.1.2, Table 4 577 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 578 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 579 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 580 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 581 582 // Single-precision floating-point comparison helper functions 583 // RTABI chapter 4.1.2, Table 5 584 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 585 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 586 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 587 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 588 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 589 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 590 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 591 592 // Floating-point to integer conversions. 593 // RTABI chapter 4.1.2, Table 6 594 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 595 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 596 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 597 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 598 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 599 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 600 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 601 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 602 603 // Conversions between floating types. 604 // RTABI chapter 4.1.2, Table 7 605 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 606 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 607 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 608 609 // Integer to floating-point conversions. 610 // RTABI chapter 4.1.2, Table 8 611 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 612 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 613 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 614 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 615 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 616 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 617 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 618 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 619 620 // Long long helper functions 621 // RTABI chapter 4.2, Table 9 622 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 623 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 624 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 625 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 626 627 // Integer division functions 628 // RTABI chapter 4.3.1 629 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 630 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 631 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 632 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 633 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 634 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 635 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 636 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 637 }; 638 639 for (const auto &LC : LibraryCalls) { 640 setLibcallName(LC.Op, LC.Name); 641 setLibcallCallingConv(LC.Op, LC.CC); 642 if (LC.Cond != ISD::SETCC_INVALID) 643 setCmpLibcallCC(LC.Op, LC.Cond); 644 } 645 646 // EABI dependent RTLIB 647 if (TM.Options.EABIVersion == EABI::EABI4 || 648 TM.Options.EABIVersion == EABI::EABI5) { 649 static const struct { 650 const RTLIB::Libcall Op; 651 const char *const Name; 652 const CallingConv::ID CC; 653 const ISD::CondCode Cond; 654 } MemOpsLibraryCalls[] = { 655 // Memory operations 656 // RTABI chapter 4.3.4 657 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 658 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 659 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 660 }; 661 662 for (const auto &LC : MemOpsLibraryCalls) { 663 setLibcallName(LC.Op, LC.Name); 664 setLibcallCallingConv(LC.Op, LC.CC); 665 if (LC.Cond != ISD::SETCC_INVALID) 666 setCmpLibcallCC(LC.Op, LC.Cond); 667 } 668 } 669 } 670 671 if (Subtarget->isTargetWindows()) { 672 static const struct { 673 const RTLIB::Libcall Op; 674 const char * const Name; 675 const CallingConv::ID CC; 676 } LibraryCalls[] = { 677 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 678 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 679 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 680 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 681 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 682 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 683 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 684 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 685 }; 686 687 for (const auto &LC : LibraryCalls) { 688 setLibcallName(LC.Op, LC.Name); 689 setLibcallCallingConv(LC.Op, LC.CC); 690 } 691 } 692 693 // Use divmod compiler-rt calls for iOS 5.0 and later. 694 if (Subtarget->isTargetMachO() && 695 !(Subtarget->isTargetIOS() && 696 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 697 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 698 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 699 } 700 701 // The half <-> float conversion functions are always soft-float on 702 // non-watchos platforms, but are needed for some targets which use a 703 // hard-float calling convention by default. 704 if (!Subtarget->isTargetWatchABI()) { 705 if (Subtarget->isAAPCS_ABI()) { 706 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 707 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 708 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 709 } else { 710 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 711 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 712 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 713 } 714 } 715 716 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 717 // a __gnu_ prefix (which is the default). 718 if (Subtarget->isTargetAEABI()) { 719 static const struct { 720 const RTLIB::Libcall Op; 721 const char * const Name; 722 const CallingConv::ID CC; 723 } LibraryCalls[] = { 724 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 725 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 726 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 727 }; 728 729 for (const auto &LC : LibraryCalls) { 730 setLibcallName(LC.Op, LC.Name); 731 setLibcallCallingConv(LC.Op, LC.CC); 732 } 733 } 734 735 if (Subtarget->isThumb1Only()) 736 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 737 else 738 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 739 740 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 741 Subtarget->hasFPRegs()) { 742 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 743 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 744 if (!Subtarget->hasVFP2Base()) 745 setAllExpand(MVT::f32); 746 if (!Subtarget->hasFP64()) 747 setAllExpand(MVT::f64); 748 } 749 750 if (Subtarget->hasFullFP16()) { 751 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 752 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 753 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 754 755 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 756 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 757 } 758 759 if (Subtarget->hasBF16()) { 760 addRegisterClass(MVT::bf16, &ARM::HPRRegClass); 761 setAllExpand(MVT::bf16); 762 if (!Subtarget->hasFullFP16()) 763 setOperationAction(ISD::BITCAST, MVT::bf16, Custom); 764 } 765 766 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 767 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 768 setTruncStoreAction(VT, InnerVT, Expand); 769 addAllExtLoads(VT, InnerVT, Expand); 770 } 771 772 setOperationAction(ISD::MULHS, VT, Expand); 773 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 774 setOperationAction(ISD::MULHU, VT, Expand); 775 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 776 777 setOperationAction(ISD::BSWAP, VT, Expand); 778 } 779 780 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 781 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 782 783 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 784 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 785 786 if (Subtarget->hasMVEIntegerOps()) 787 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 788 789 // Combine low-overhead loop intrinsics so that we can lower i1 types. 790 if (Subtarget->hasLOB()) { 791 setTargetDAGCombine(ISD::BRCOND); 792 setTargetDAGCombine(ISD::BR_CC); 793 } 794 795 if (Subtarget->hasNEON()) { 796 addDRTypeForNEON(MVT::v2f32); 797 addDRTypeForNEON(MVT::v8i8); 798 addDRTypeForNEON(MVT::v4i16); 799 addDRTypeForNEON(MVT::v2i32); 800 addDRTypeForNEON(MVT::v1i64); 801 802 addQRTypeForNEON(MVT::v4f32); 803 addQRTypeForNEON(MVT::v2f64); 804 addQRTypeForNEON(MVT::v16i8); 805 addQRTypeForNEON(MVT::v8i16); 806 addQRTypeForNEON(MVT::v4i32); 807 addQRTypeForNEON(MVT::v2i64); 808 809 if (Subtarget->hasFullFP16()) { 810 addQRTypeForNEON(MVT::v8f16); 811 addDRTypeForNEON(MVT::v4f16); 812 } 813 814 if (Subtarget->hasBF16()) { 815 addQRTypeForNEON(MVT::v8bf16); 816 addDRTypeForNEON(MVT::v4bf16); 817 } 818 } 819 820 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 821 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 822 // none of Neon, MVE or VFP supports any arithmetic operations on it. 823 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 824 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 825 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 826 // FIXME: Code duplication: FDIV and FREM are expanded always, see 827 // ARMTargetLowering::addTypeForNEON method for details. 828 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 829 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 830 // FIXME: Create unittest. 831 // In another words, find a way when "copysign" appears in DAG with vector 832 // operands. 833 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 834 // FIXME: Code duplication: SETCC has custom operation action, see 835 // ARMTargetLowering::addTypeForNEON method for details. 836 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 837 // FIXME: Create unittest for FNEG and for FABS. 838 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 839 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 840 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 841 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 842 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 843 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 844 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 845 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 846 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 847 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 848 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 849 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 850 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 851 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 852 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 853 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 854 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 855 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 856 } 857 858 if (Subtarget->hasNEON()) { 859 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 860 // supported for v4f32. 861 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 862 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 863 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 864 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 865 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 866 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 867 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 868 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 869 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 870 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 871 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 872 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 873 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 874 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 875 876 // Mark v2f32 intrinsics. 877 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 878 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 879 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 880 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 881 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 882 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 883 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 884 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 885 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 886 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 887 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 888 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 889 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 890 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 891 892 // Neon does not support some operations on v1i64 and v2i64 types. 893 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 894 // Custom handling for some quad-vector types to detect VMULL. 895 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 896 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 897 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 898 // Custom handling for some vector types to avoid expensive expansions 899 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 900 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 901 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 902 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 903 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 904 // a destination type that is wider than the source, and nor does 905 // it have a FP_TO_[SU]INT instruction with a narrower destination than 906 // source. 907 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 908 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 909 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 910 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 911 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 912 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 913 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 914 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 915 916 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 917 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 918 919 // NEON does not have single instruction CTPOP for vectors with element 920 // types wider than 8-bits. However, custom lowering can leverage the 921 // v8i8/v16i8 vcnt instruction. 922 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 923 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 924 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 925 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 926 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 927 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 928 929 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 930 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 931 932 // NEON does not have single instruction CTTZ for vectors. 933 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 934 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 935 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 936 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 937 938 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 939 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 940 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 941 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 942 943 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 944 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 945 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 946 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 947 948 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 949 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 950 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 951 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 952 953 // NEON only has FMA instructions as of VFP4. 954 if (!Subtarget->hasVFP4Base()) { 955 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 956 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 957 } 958 959 setTargetDAGCombine(ISD::SHL); 960 setTargetDAGCombine(ISD::SRL); 961 setTargetDAGCombine(ISD::SRA); 962 setTargetDAGCombine(ISD::FP_TO_SINT); 963 setTargetDAGCombine(ISD::FP_TO_UINT); 964 setTargetDAGCombine(ISD::FDIV); 965 setTargetDAGCombine(ISD::LOAD); 966 967 // It is legal to extload from v4i8 to v4i16 or v4i32. 968 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 969 MVT::v2i32}) { 970 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 971 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 972 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 973 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 974 } 975 } 976 } 977 978 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 979 setTargetDAGCombine(ISD::BUILD_VECTOR); 980 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 981 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 982 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 983 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 984 setTargetDAGCombine(ISD::STORE); 985 setTargetDAGCombine(ISD::SIGN_EXTEND); 986 setTargetDAGCombine(ISD::ZERO_EXTEND); 987 setTargetDAGCombine(ISD::ANY_EXTEND); 988 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 989 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 990 setTargetDAGCombine(ISD::INTRINSIC_VOID); 991 setTargetDAGCombine(ISD::VECREDUCE_ADD); 992 setTargetDAGCombine(ISD::ADD); 993 setTargetDAGCombine(ISD::BITCAST); 994 } 995 if (Subtarget->hasMVEIntegerOps()) { 996 setTargetDAGCombine(ISD::SMIN); 997 setTargetDAGCombine(ISD::UMIN); 998 setTargetDAGCombine(ISD::SMAX); 999 setTargetDAGCombine(ISD::UMAX); 1000 setTargetDAGCombine(ISD::FP_EXTEND); 1001 setTargetDAGCombine(ISD::SELECT); 1002 setTargetDAGCombine(ISD::SELECT_CC); 1003 } 1004 1005 if (!Subtarget->hasFP64()) { 1006 // When targeting a floating-point unit with only single-precision 1007 // operations, f64 is legal for the few double-precision instructions which 1008 // are present However, no double-precision operations other than moves, 1009 // loads and stores are provided by the hardware. 1010 setOperationAction(ISD::FADD, MVT::f64, Expand); 1011 setOperationAction(ISD::FSUB, MVT::f64, Expand); 1012 setOperationAction(ISD::FMUL, MVT::f64, Expand); 1013 setOperationAction(ISD::FMA, MVT::f64, Expand); 1014 setOperationAction(ISD::FDIV, MVT::f64, Expand); 1015 setOperationAction(ISD::FREM, MVT::f64, Expand); 1016 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 1017 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 1018 setOperationAction(ISD::FNEG, MVT::f64, Expand); 1019 setOperationAction(ISD::FABS, MVT::f64, Expand); 1020 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 1021 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1022 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1023 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1024 setOperationAction(ISD::FLOG, MVT::f64, Expand); 1025 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 1026 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 1027 setOperationAction(ISD::FEXP, MVT::f64, Expand); 1028 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 1029 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 1030 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 1031 setOperationAction(ISD::FRINT, MVT::f64, Expand); 1032 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 1033 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 1034 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 1035 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 1036 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 1037 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 1038 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 1039 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 1040 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 1041 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 1042 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 1043 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom); 1044 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom); 1045 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 1046 } 1047 1048 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 1049 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 1050 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom); 1051 if (Subtarget->hasFullFP16()) { 1052 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 1053 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom); 1054 } 1055 } 1056 1057 if (!Subtarget->hasFP16()) { 1058 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 1059 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom); 1060 } 1061 1062 computeRegisterProperties(Subtarget->getRegisterInfo()); 1063 1064 // ARM does not have floating-point extending loads. 1065 for (MVT VT : MVT::fp_valuetypes()) { 1066 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 1067 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 1068 } 1069 1070 // ... or truncating stores 1071 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 1072 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 1073 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 1074 1075 // ARM does not have i1 sign extending load. 1076 for (MVT VT : MVT::integer_valuetypes()) 1077 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 1078 1079 // ARM supports all 4 flavors of integer indexed load / store. 1080 if (!Subtarget->isThumb1Only()) { 1081 for (unsigned im = (unsigned)ISD::PRE_INC; 1082 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1083 setIndexedLoadAction(im, MVT::i1, Legal); 1084 setIndexedLoadAction(im, MVT::i8, Legal); 1085 setIndexedLoadAction(im, MVT::i16, Legal); 1086 setIndexedLoadAction(im, MVT::i32, Legal); 1087 setIndexedStoreAction(im, MVT::i1, Legal); 1088 setIndexedStoreAction(im, MVT::i8, Legal); 1089 setIndexedStoreAction(im, MVT::i16, Legal); 1090 setIndexedStoreAction(im, MVT::i32, Legal); 1091 } 1092 } else { 1093 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 1094 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 1095 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 1096 } 1097 1098 setOperationAction(ISD::SADDO, MVT::i32, Custom); 1099 setOperationAction(ISD::UADDO, MVT::i32, Custom); 1100 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 1101 setOperationAction(ISD::USUBO, MVT::i32, Custom); 1102 1103 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 1104 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 1105 if (Subtarget->hasDSP()) { 1106 setOperationAction(ISD::SADDSAT, MVT::i8, Custom); 1107 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom); 1108 setOperationAction(ISD::SADDSAT, MVT::i16, Custom); 1109 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom); 1110 } 1111 if (Subtarget->hasBaseDSP()) { 1112 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 1113 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 1114 } 1115 1116 // i64 operation support. 1117 setOperationAction(ISD::MUL, MVT::i64, Expand); 1118 setOperationAction(ISD::MULHU, MVT::i32, Expand); 1119 if (Subtarget->isThumb1Only()) { 1120 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 1121 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 1122 } 1123 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 1124 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 1125 setOperationAction(ISD::MULHS, MVT::i32, Expand); 1126 1127 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 1128 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 1129 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 1130 setOperationAction(ISD::SRL, MVT::i64, Custom); 1131 setOperationAction(ISD::SRA, MVT::i64, Custom); 1132 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 1133 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 1134 setOperationAction(ISD::LOAD, MVT::i64, Custom); 1135 setOperationAction(ISD::STORE, MVT::i64, Custom); 1136 1137 // MVE lowers 64 bit shifts to lsll and lsrl 1138 // assuming that ISD::SRL and SRA of i64 are already marked custom 1139 if (Subtarget->hasMVEIntegerOps()) 1140 setOperationAction(ISD::SHL, MVT::i64, Custom); 1141 1142 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1143 if (Subtarget->isThumb1Only()) { 1144 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1145 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1146 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1147 } 1148 1149 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1150 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1151 1152 // ARM does not have ROTL. 1153 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1154 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1155 setOperationAction(ISD::ROTL, VT, Expand); 1156 setOperationAction(ISD::ROTR, VT, Expand); 1157 } 1158 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1159 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1160 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1161 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1162 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1163 } 1164 1165 // @llvm.readcyclecounter requires the Performance Monitors extension. 1166 // Default to the 0 expansion on unsupported platforms. 1167 // FIXME: Technically there are older ARM CPUs that have 1168 // implementation-specific ways of obtaining this information. 1169 if (Subtarget->hasPerfMon()) 1170 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1171 1172 // Only ARMv6 has BSWAP. 1173 if (!Subtarget->hasV6Ops()) 1174 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1175 1176 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1177 : Subtarget->hasDivideInARMMode(); 1178 if (!hasDivide) { 1179 // These are expanded into libcalls if the cpu doesn't have HW divider. 1180 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1181 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1182 } 1183 1184 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1185 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1186 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1187 1188 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1189 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1190 } 1191 1192 setOperationAction(ISD::SREM, MVT::i32, Expand); 1193 setOperationAction(ISD::UREM, MVT::i32, Expand); 1194 1195 // Register based DivRem for AEABI (RTABI 4.2) 1196 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1197 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1198 Subtarget->isTargetWindows()) { 1199 setOperationAction(ISD::SREM, MVT::i64, Custom); 1200 setOperationAction(ISD::UREM, MVT::i64, Custom); 1201 HasStandaloneRem = false; 1202 1203 if (Subtarget->isTargetWindows()) { 1204 const struct { 1205 const RTLIB::Libcall Op; 1206 const char * const Name; 1207 const CallingConv::ID CC; 1208 } LibraryCalls[] = { 1209 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1210 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1211 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1212 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1213 1214 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1215 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1216 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1217 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1218 }; 1219 1220 for (const auto &LC : LibraryCalls) { 1221 setLibcallName(LC.Op, LC.Name); 1222 setLibcallCallingConv(LC.Op, LC.CC); 1223 } 1224 } else { 1225 const struct { 1226 const RTLIB::Libcall Op; 1227 const char * const Name; 1228 const CallingConv::ID CC; 1229 } LibraryCalls[] = { 1230 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1231 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1232 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1233 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1234 1235 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1236 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1237 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1238 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1239 }; 1240 1241 for (const auto &LC : LibraryCalls) { 1242 setLibcallName(LC.Op, LC.Name); 1243 setLibcallCallingConv(LC.Op, LC.CC); 1244 } 1245 } 1246 1247 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1248 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1249 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1250 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1251 } else { 1252 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1253 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1254 } 1255 1256 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 1257 // MSVCRT doesn't have powi; fall back to pow 1258 setLibcallName(RTLIB::POWI_F32, nullptr); 1259 setLibcallName(RTLIB::POWI_F64, nullptr); 1260 } 1261 1262 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1263 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1264 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1265 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1266 1267 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1268 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1269 1270 // Use the default implementation. 1271 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1272 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1273 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1274 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1275 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1276 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1277 1278 if (Subtarget->isTargetWindows()) 1279 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1280 else 1281 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1282 1283 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1284 // the default expansion. 1285 InsertFencesForAtomic = false; 1286 if (Subtarget->hasAnyDataBarrier() && 1287 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1288 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1289 // to ldrex/strex loops already. 1290 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1291 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1292 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1293 1294 // On v8, we have particularly efficient implementations of atomic fences 1295 // if they can be combined with nearby atomic loads and stores. 1296 if (!Subtarget->hasAcquireRelease() || 1297 getTargetMachine().getOptLevel() == 0) { 1298 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1299 InsertFencesForAtomic = true; 1300 } 1301 } else { 1302 // If there's anything we can use as a barrier, go through custom lowering 1303 // for ATOMIC_FENCE. 1304 // If target has DMB in thumb, Fences can be inserted. 1305 if (Subtarget->hasDataBarrier()) 1306 InsertFencesForAtomic = true; 1307 1308 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1309 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1310 1311 // Set them all for expansion, which will force libcalls. 1312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1313 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1314 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1315 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1316 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1317 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1318 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1319 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1320 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1321 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1322 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1323 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1324 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1325 // Unordered/Monotonic case. 1326 if (!InsertFencesForAtomic) { 1327 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1328 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1329 } 1330 } 1331 1332 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1333 1334 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1335 if (!Subtarget->hasV6Ops()) { 1336 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1337 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1338 } 1339 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1340 1341 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1342 !Subtarget->isThumb1Only()) { 1343 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1344 // iff target supports vfp2. 1345 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1346 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1347 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 1348 } 1349 1350 // We want to custom lower some of our intrinsics. 1351 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1352 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1353 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1354 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1355 if (Subtarget->useSjLjEH()) 1356 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1357 1358 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1359 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1360 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1361 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1362 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1363 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1364 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1365 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1366 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1367 if (Subtarget->hasFullFP16()) { 1368 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1369 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1370 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1371 } 1372 1373 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1374 1375 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1376 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1377 if (Subtarget->hasFullFP16()) 1378 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1379 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1380 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1381 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1382 1383 // We don't support sin/cos/fmod/copysign/pow 1384 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1385 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1386 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1387 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1388 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1389 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1390 setOperationAction(ISD::FREM, MVT::f64, Expand); 1391 setOperationAction(ISD::FREM, MVT::f32, Expand); 1392 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1393 !Subtarget->isThumb1Only()) { 1394 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1395 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1396 } 1397 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1398 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1399 1400 if (!Subtarget->hasVFP4Base()) { 1401 setOperationAction(ISD::FMA, MVT::f64, Expand); 1402 setOperationAction(ISD::FMA, MVT::f32, Expand); 1403 } 1404 1405 // Various VFP goodness 1406 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1407 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1408 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1409 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1410 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1411 } 1412 1413 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1414 if (!Subtarget->hasFP16()) { 1415 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1416 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1417 } 1418 1419 // Strict floating-point comparisons need custom lowering. 1420 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 1421 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 1422 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 1423 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 1424 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 1425 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 1426 } 1427 1428 // Use __sincos_stret if available. 1429 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1430 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1431 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1432 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1433 } 1434 1435 // FP-ARMv8 implements a lot of rounding-like FP operations. 1436 if (Subtarget->hasFPARMv8Base()) { 1437 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1438 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1439 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1440 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1441 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1442 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1443 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1444 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1445 if (Subtarget->hasNEON()) { 1446 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1447 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1448 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1449 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1450 } 1451 1452 if (Subtarget->hasFP64()) { 1453 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1454 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1455 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1456 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1457 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1458 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1459 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1460 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1461 } 1462 } 1463 1464 // FP16 often need to be promoted to call lib functions 1465 if (Subtarget->hasFullFP16()) { 1466 setOperationAction(ISD::FREM, MVT::f16, Promote); 1467 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1468 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1469 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1470 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1471 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1472 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1473 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1474 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1475 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1476 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1477 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1478 1479 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1480 } 1481 1482 if (Subtarget->hasNEON()) { 1483 // vmin and vmax aren't available in a scalar form, so we can use 1484 // a NEON instruction with an undef lane instead. This has a performance 1485 // penalty on some cores, so we don't do this unless we have been 1486 // asked to by the core tuning model. 1487 if (Subtarget->useNEONForSinglePrecisionFP()) { 1488 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1489 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1490 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1491 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1492 } 1493 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1494 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1495 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1496 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1497 1498 if (Subtarget->hasFullFP16()) { 1499 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1500 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1501 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1502 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1503 1504 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1505 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1506 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1507 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1508 } 1509 } 1510 1511 // We have target-specific dag combine patterns for the following nodes: 1512 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1513 setTargetDAGCombine(ISD::ADD); 1514 setTargetDAGCombine(ISD::SUB); 1515 setTargetDAGCombine(ISD::MUL); 1516 setTargetDAGCombine(ISD::AND); 1517 setTargetDAGCombine(ISD::OR); 1518 setTargetDAGCombine(ISD::XOR); 1519 1520 if (Subtarget->hasMVEIntegerOps()) 1521 setTargetDAGCombine(ISD::VSELECT); 1522 1523 if (Subtarget->hasV6Ops()) 1524 setTargetDAGCombine(ISD::SRL); 1525 if (Subtarget->isThumb1Only()) 1526 setTargetDAGCombine(ISD::SHL); 1527 1528 setStackPointerRegisterToSaveRestore(ARM::SP); 1529 1530 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1531 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1532 setSchedulingPreference(Sched::RegPressure); 1533 else 1534 setSchedulingPreference(Sched::Hybrid); 1535 1536 //// temporary - rewrite interface to use type 1537 MaxStoresPerMemset = 8; 1538 MaxStoresPerMemsetOptSize = 4; 1539 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1540 MaxStoresPerMemcpyOptSize = 2; 1541 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1542 MaxStoresPerMemmoveOptSize = 2; 1543 1544 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1545 // are at least 4 bytes aligned. 1546 setMinStackArgumentAlignment(Align(4)); 1547 1548 // Prefer likely predicted branches to selects on out-of-order cores. 1549 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1550 1551 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment())); 1552 1553 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4)); 1554 1555 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1556 setTargetDAGCombine(ISD::ABS); 1557 } 1558 1559 bool ARMTargetLowering::useSoftFloat() const { 1560 return Subtarget->useSoftFloat(); 1561 } 1562 1563 // FIXME: It might make sense to define the representative register class as the 1564 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1565 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1566 // SPR's representative would be DPR_VFP2. This should work well if register 1567 // pressure tracking were modified such that a register use would increment the 1568 // pressure of the register class's representative and all of it's super 1569 // classes' representatives transitively. We have not implemented this because 1570 // of the difficulty prior to coalescing of modeling operand register classes 1571 // due to the common occurrence of cross class copies and subregister insertions 1572 // and extractions. 1573 std::pair<const TargetRegisterClass *, uint8_t> 1574 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1575 MVT VT) const { 1576 const TargetRegisterClass *RRC = nullptr; 1577 uint8_t Cost = 1; 1578 switch (VT.SimpleTy) { 1579 default: 1580 return TargetLowering::findRepresentativeClass(TRI, VT); 1581 // Use DPR as representative register class for all floating point 1582 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1583 // the cost is 1 for both f32 and f64. 1584 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1585 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1586 RRC = &ARM::DPRRegClass; 1587 // When NEON is used for SP, only half of the register file is available 1588 // because operations that define both SP and DP results will be constrained 1589 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1590 // coalescing by double-counting the SP regs. See the FIXME above. 1591 if (Subtarget->useNEONForSinglePrecisionFP()) 1592 Cost = 2; 1593 break; 1594 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1595 case MVT::v4f32: case MVT::v2f64: 1596 RRC = &ARM::DPRRegClass; 1597 Cost = 2; 1598 break; 1599 case MVT::v4i64: 1600 RRC = &ARM::DPRRegClass; 1601 Cost = 4; 1602 break; 1603 case MVT::v8i64: 1604 RRC = &ARM::DPRRegClass; 1605 Cost = 8; 1606 break; 1607 } 1608 return std::make_pair(RRC, Cost); 1609 } 1610 1611 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1612 #define MAKE_CASE(V) \ 1613 case V: \ 1614 return #V; 1615 switch ((ARMISD::NodeType)Opcode) { 1616 case ARMISD::FIRST_NUMBER: 1617 break; 1618 MAKE_CASE(ARMISD::Wrapper) 1619 MAKE_CASE(ARMISD::WrapperPIC) 1620 MAKE_CASE(ARMISD::WrapperJT) 1621 MAKE_CASE(ARMISD::COPY_STRUCT_BYVAL) 1622 MAKE_CASE(ARMISD::CALL) 1623 MAKE_CASE(ARMISD::CALL_PRED) 1624 MAKE_CASE(ARMISD::CALL_NOLINK) 1625 MAKE_CASE(ARMISD::tSECALL) 1626 MAKE_CASE(ARMISD::BRCOND) 1627 MAKE_CASE(ARMISD::BR_JT) 1628 MAKE_CASE(ARMISD::BR2_JT) 1629 MAKE_CASE(ARMISD::RET_FLAG) 1630 MAKE_CASE(ARMISD::SERET_FLAG) 1631 MAKE_CASE(ARMISD::INTRET_FLAG) 1632 MAKE_CASE(ARMISD::PIC_ADD) 1633 MAKE_CASE(ARMISD::CMP) 1634 MAKE_CASE(ARMISD::CMN) 1635 MAKE_CASE(ARMISD::CMPZ) 1636 MAKE_CASE(ARMISD::CMPFP) 1637 MAKE_CASE(ARMISD::CMPFPE) 1638 MAKE_CASE(ARMISD::CMPFPw0) 1639 MAKE_CASE(ARMISD::CMPFPEw0) 1640 MAKE_CASE(ARMISD::BCC_i64) 1641 MAKE_CASE(ARMISD::FMSTAT) 1642 MAKE_CASE(ARMISD::CMOV) 1643 MAKE_CASE(ARMISD::SUBS) 1644 MAKE_CASE(ARMISD::SSAT) 1645 MAKE_CASE(ARMISD::USAT) 1646 MAKE_CASE(ARMISD::ASRL) 1647 MAKE_CASE(ARMISD::LSRL) 1648 MAKE_CASE(ARMISD::LSLL) 1649 MAKE_CASE(ARMISD::SRL_FLAG) 1650 MAKE_CASE(ARMISD::SRA_FLAG) 1651 MAKE_CASE(ARMISD::RRX) 1652 MAKE_CASE(ARMISD::ADDC) 1653 MAKE_CASE(ARMISD::ADDE) 1654 MAKE_CASE(ARMISD::SUBC) 1655 MAKE_CASE(ARMISD::SUBE) 1656 MAKE_CASE(ARMISD::LSLS) 1657 MAKE_CASE(ARMISD::VMOVRRD) 1658 MAKE_CASE(ARMISD::VMOVDRR) 1659 MAKE_CASE(ARMISD::VMOVhr) 1660 MAKE_CASE(ARMISD::VMOVrh) 1661 MAKE_CASE(ARMISD::VMOVSR) 1662 MAKE_CASE(ARMISD::EH_SJLJ_SETJMP) 1663 MAKE_CASE(ARMISD::EH_SJLJ_LONGJMP) 1664 MAKE_CASE(ARMISD::EH_SJLJ_SETUP_DISPATCH) 1665 MAKE_CASE(ARMISD::TC_RETURN) 1666 MAKE_CASE(ARMISD::THREAD_POINTER) 1667 MAKE_CASE(ARMISD::DYN_ALLOC) 1668 MAKE_CASE(ARMISD::MEMBARRIER_MCR) 1669 MAKE_CASE(ARMISD::PRELOAD) 1670 MAKE_CASE(ARMISD::LDRD) 1671 MAKE_CASE(ARMISD::STRD) 1672 MAKE_CASE(ARMISD::WIN__CHKSTK) 1673 MAKE_CASE(ARMISD::WIN__DBZCHK) 1674 MAKE_CASE(ARMISD::PREDICATE_CAST) 1675 MAKE_CASE(ARMISD::VECTOR_REG_CAST) 1676 MAKE_CASE(ARMISD::VCMP) 1677 MAKE_CASE(ARMISD::VCMPZ) 1678 MAKE_CASE(ARMISD::VTST) 1679 MAKE_CASE(ARMISD::VSHLs) 1680 MAKE_CASE(ARMISD::VSHLu) 1681 MAKE_CASE(ARMISD::VSHLIMM) 1682 MAKE_CASE(ARMISD::VSHRsIMM) 1683 MAKE_CASE(ARMISD::VSHRuIMM) 1684 MAKE_CASE(ARMISD::VRSHRsIMM) 1685 MAKE_CASE(ARMISD::VRSHRuIMM) 1686 MAKE_CASE(ARMISD::VRSHRNIMM) 1687 MAKE_CASE(ARMISD::VQSHLsIMM) 1688 MAKE_CASE(ARMISD::VQSHLuIMM) 1689 MAKE_CASE(ARMISD::VQSHLsuIMM) 1690 MAKE_CASE(ARMISD::VQSHRNsIMM) 1691 MAKE_CASE(ARMISD::VQSHRNuIMM) 1692 MAKE_CASE(ARMISD::VQSHRNsuIMM) 1693 MAKE_CASE(ARMISD::VQRSHRNsIMM) 1694 MAKE_CASE(ARMISD::VQRSHRNuIMM) 1695 MAKE_CASE(ARMISD::VQRSHRNsuIMM) 1696 MAKE_CASE(ARMISD::VSLIIMM) 1697 MAKE_CASE(ARMISD::VSRIIMM) 1698 MAKE_CASE(ARMISD::VGETLANEu) 1699 MAKE_CASE(ARMISD::VGETLANEs) 1700 MAKE_CASE(ARMISD::VMOVIMM) 1701 MAKE_CASE(ARMISD::VMVNIMM) 1702 MAKE_CASE(ARMISD::VMOVFPIMM) 1703 MAKE_CASE(ARMISD::VDUP) 1704 MAKE_CASE(ARMISD::VDUPLANE) 1705 MAKE_CASE(ARMISD::VEXT) 1706 MAKE_CASE(ARMISD::VREV64) 1707 MAKE_CASE(ARMISD::VREV32) 1708 MAKE_CASE(ARMISD::VREV16) 1709 MAKE_CASE(ARMISD::VZIP) 1710 MAKE_CASE(ARMISD::VUZP) 1711 MAKE_CASE(ARMISD::VTRN) 1712 MAKE_CASE(ARMISD::VTBL1) 1713 MAKE_CASE(ARMISD::VTBL2) 1714 MAKE_CASE(ARMISD::VMOVN) 1715 MAKE_CASE(ARMISD::VQMOVNs) 1716 MAKE_CASE(ARMISD::VQMOVNu) 1717 MAKE_CASE(ARMISD::VCVTN) 1718 MAKE_CASE(ARMISD::VCVTL) 1719 MAKE_CASE(ARMISD::VMULLs) 1720 MAKE_CASE(ARMISD::VMULLu) 1721 MAKE_CASE(ARMISD::VQDMULH) 1722 MAKE_CASE(ARMISD::VADDVs) 1723 MAKE_CASE(ARMISD::VADDVu) 1724 MAKE_CASE(ARMISD::VADDVps) 1725 MAKE_CASE(ARMISD::VADDVpu) 1726 MAKE_CASE(ARMISD::VADDLVs) 1727 MAKE_CASE(ARMISD::VADDLVu) 1728 MAKE_CASE(ARMISD::VADDLVAs) 1729 MAKE_CASE(ARMISD::VADDLVAu) 1730 MAKE_CASE(ARMISD::VADDLVps) 1731 MAKE_CASE(ARMISD::VADDLVpu) 1732 MAKE_CASE(ARMISD::VADDLVAps) 1733 MAKE_CASE(ARMISD::VADDLVApu) 1734 MAKE_CASE(ARMISD::VMLAVs) 1735 MAKE_CASE(ARMISD::VMLAVu) 1736 MAKE_CASE(ARMISD::VMLAVps) 1737 MAKE_CASE(ARMISD::VMLAVpu) 1738 MAKE_CASE(ARMISD::VMLALVs) 1739 MAKE_CASE(ARMISD::VMLALVu) 1740 MAKE_CASE(ARMISD::VMLALVps) 1741 MAKE_CASE(ARMISD::VMLALVpu) 1742 MAKE_CASE(ARMISD::VMLALVAs) 1743 MAKE_CASE(ARMISD::VMLALVAu) 1744 MAKE_CASE(ARMISD::VMLALVAps) 1745 MAKE_CASE(ARMISD::VMLALVApu) 1746 MAKE_CASE(ARMISD::VMINVu) 1747 MAKE_CASE(ARMISD::VMINVs) 1748 MAKE_CASE(ARMISD::VMAXVu) 1749 MAKE_CASE(ARMISD::VMAXVs) 1750 MAKE_CASE(ARMISD::UMAAL) 1751 MAKE_CASE(ARMISD::UMLAL) 1752 MAKE_CASE(ARMISD::SMLAL) 1753 MAKE_CASE(ARMISD::SMLALBB) 1754 MAKE_CASE(ARMISD::SMLALBT) 1755 MAKE_CASE(ARMISD::SMLALTB) 1756 MAKE_CASE(ARMISD::SMLALTT) 1757 MAKE_CASE(ARMISD::SMULWB) 1758 MAKE_CASE(ARMISD::SMULWT) 1759 MAKE_CASE(ARMISD::SMLALD) 1760 MAKE_CASE(ARMISD::SMLALDX) 1761 MAKE_CASE(ARMISD::SMLSLD) 1762 MAKE_CASE(ARMISD::SMLSLDX) 1763 MAKE_CASE(ARMISD::SMMLAR) 1764 MAKE_CASE(ARMISD::SMMLSR) 1765 MAKE_CASE(ARMISD::QADD16b) 1766 MAKE_CASE(ARMISD::QSUB16b) 1767 MAKE_CASE(ARMISD::QADD8b) 1768 MAKE_CASE(ARMISD::QSUB8b) 1769 MAKE_CASE(ARMISD::BUILD_VECTOR) 1770 MAKE_CASE(ARMISD::BFI) 1771 MAKE_CASE(ARMISD::VORRIMM) 1772 MAKE_CASE(ARMISD::VBICIMM) 1773 MAKE_CASE(ARMISD::VBSP) 1774 MAKE_CASE(ARMISD::MEMCPY) 1775 MAKE_CASE(ARMISD::VLD1DUP) 1776 MAKE_CASE(ARMISD::VLD2DUP) 1777 MAKE_CASE(ARMISD::VLD3DUP) 1778 MAKE_CASE(ARMISD::VLD4DUP) 1779 MAKE_CASE(ARMISD::VLD1_UPD) 1780 MAKE_CASE(ARMISD::VLD2_UPD) 1781 MAKE_CASE(ARMISD::VLD3_UPD) 1782 MAKE_CASE(ARMISD::VLD4_UPD) 1783 MAKE_CASE(ARMISD::VLD2LN_UPD) 1784 MAKE_CASE(ARMISD::VLD3LN_UPD) 1785 MAKE_CASE(ARMISD::VLD4LN_UPD) 1786 MAKE_CASE(ARMISD::VLD1DUP_UPD) 1787 MAKE_CASE(ARMISD::VLD2DUP_UPD) 1788 MAKE_CASE(ARMISD::VLD3DUP_UPD) 1789 MAKE_CASE(ARMISD::VLD4DUP_UPD) 1790 MAKE_CASE(ARMISD::VST1_UPD) 1791 MAKE_CASE(ARMISD::VST2_UPD) 1792 MAKE_CASE(ARMISD::VST3_UPD) 1793 MAKE_CASE(ARMISD::VST4_UPD) 1794 MAKE_CASE(ARMISD::VST2LN_UPD) 1795 MAKE_CASE(ARMISD::VST3LN_UPD) 1796 MAKE_CASE(ARMISD::VST4LN_UPD) 1797 MAKE_CASE(ARMISD::WLS) 1798 MAKE_CASE(ARMISD::WLSSETUP) 1799 MAKE_CASE(ARMISD::LE) 1800 MAKE_CASE(ARMISD::LOOP_DEC) 1801 MAKE_CASE(ARMISD::CSINV) 1802 MAKE_CASE(ARMISD::CSNEG) 1803 MAKE_CASE(ARMISD::CSINC) 1804 #undef MAKE_CASE 1805 } 1806 return nullptr; 1807 } 1808 1809 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1810 EVT VT) const { 1811 if (!VT.isVector()) 1812 return getPointerTy(DL); 1813 1814 // MVE has a predicate register. 1815 if (Subtarget->hasMVEIntegerOps() && 1816 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1817 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1818 return VT.changeVectorElementTypeToInteger(); 1819 } 1820 1821 /// getRegClassFor - Return the register class that should be used for the 1822 /// specified value type. 1823 const TargetRegisterClass * 1824 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1825 (void)isDivergent; 1826 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1827 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1828 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1829 // MVE Q registers. 1830 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1831 if (VT == MVT::v4i64) 1832 return &ARM::QQPRRegClass; 1833 if (VT == MVT::v8i64) 1834 return &ARM::QQQQPRRegClass; 1835 } 1836 return TargetLowering::getRegClassFor(VT); 1837 } 1838 1839 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1840 // source/dest is aligned and the copy size is large enough. We therefore want 1841 // to align such objects passed to memory intrinsics. 1842 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1843 unsigned &PrefAlign) const { 1844 if (!isa<MemIntrinsic>(CI)) 1845 return false; 1846 MinSize = 8; 1847 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1848 // cycle faster than 4-byte aligned LDM. 1849 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1850 return true; 1851 } 1852 1853 // Create a fast isel object. 1854 FastISel * 1855 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1856 const TargetLibraryInfo *libInfo) const { 1857 return ARM::createFastISel(funcInfo, libInfo); 1858 } 1859 1860 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1861 unsigned NumVals = N->getNumValues(); 1862 if (!NumVals) 1863 return Sched::RegPressure; 1864 1865 for (unsigned i = 0; i != NumVals; ++i) { 1866 EVT VT = N->getValueType(i); 1867 if (VT == MVT::Glue || VT == MVT::Other) 1868 continue; 1869 if (VT.isFloatingPoint() || VT.isVector()) 1870 return Sched::ILP; 1871 } 1872 1873 if (!N->isMachineOpcode()) 1874 return Sched::RegPressure; 1875 1876 // Load are scheduled for latency even if there instruction itinerary 1877 // is not available. 1878 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1879 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1880 1881 if (MCID.getNumDefs() == 0) 1882 return Sched::RegPressure; 1883 if (!Itins->isEmpty() && 1884 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1885 return Sched::ILP; 1886 1887 return Sched::RegPressure; 1888 } 1889 1890 //===----------------------------------------------------------------------===// 1891 // Lowering Code 1892 //===----------------------------------------------------------------------===// 1893 1894 static bool isSRL16(const SDValue &Op) { 1895 if (Op.getOpcode() != ISD::SRL) 1896 return false; 1897 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1898 return Const->getZExtValue() == 16; 1899 return false; 1900 } 1901 1902 static bool isSRA16(const SDValue &Op) { 1903 if (Op.getOpcode() != ISD::SRA) 1904 return false; 1905 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1906 return Const->getZExtValue() == 16; 1907 return false; 1908 } 1909 1910 static bool isSHL16(const SDValue &Op) { 1911 if (Op.getOpcode() != ISD::SHL) 1912 return false; 1913 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1914 return Const->getZExtValue() == 16; 1915 return false; 1916 } 1917 1918 // Check for a signed 16-bit value. We special case SRA because it makes it 1919 // more simple when also looking for SRAs that aren't sign extending a 1920 // smaller value. Without the check, we'd need to take extra care with 1921 // checking order for some operations. 1922 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1923 if (isSRA16(Op)) 1924 return isSHL16(Op.getOperand(0)); 1925 return DAG.ComputeNumSignBits(Op) == 17; 1926 } 1927 1928 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1929 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1930 switch (CC) { 1931 default: llvm_unreachable("Unknown condition code!"); 1932 case ISD::SETNE: return ARMCC::NE; 1933 case ISD::SETEQ: return ARMCC::EQ; 1934 case ISD::SETGT: return ARMCC::GT; 1935 case ISD::SETGE: return ARMCC::GE; 1936 case ISD::SETLT: return ARMCC::LT; 1937 case ISD::SETLE: return ARMCC::LE; 1938 case ISD::SETUGT: return ARMCC::HI; 1939 case ISD::SETUGE: return ARMCC::HS; 1940 case ISD::SETULT: return ARMCC::LO; 1941 case ISD::SETULE: return ARMCC::LS; 1942 } 1943 } 1944 1945 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1946 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1947 ARMCC::CondCodes &CondCode2) { 1948 CondCode2 = ARMCC::AL; 1949 switch (CC) { 1950 default: llvm_unreachable("Unknown FP condition!"); 1951 case ISD::SETEQ: 1952 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1953 case ISD::SETGT: 1954 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1955 case ISD::SETGE: 1956 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1957 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1958 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1959 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1960 case ISD::SETO: CondCode = ARMCC::VC; break; 1961 case ISD::SETUO: CondCode = ARMCC::VS; break; 1962 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1963 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1964 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1965 case ISD::SETLT: 1966 case ISD::SETULT: CondCode = ARMCC::LT; break; 1967 case ISD::SETLE: 1968 case ISD::SETULE: CondCode = ARMCC::LE; break; 1969 case ISD::SETNE: 1970 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1971 } 1972 } 1973 1974 //===----------------------------------------------------------------------===// 1975 // Calling Convention Implementation 1976 //===----------------------------------------------------------------------===// 1977 1978 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1979 /// account presence of floating point hardware and calling convention 1980 /// limitations, such as support for variadic functions. 1981 CallingConv::ID 1982 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1983 bool isVarArg) const { 1984 switch (CC) { 1985 default: 1986 report_fatal_error("Unsupported calling convention"); 1987 case CallingConv::ARM_AAPCS: 1988 case CallingConv::ARM_APCS: 1989 case CallingConv::GHC: 1990 case CallingConv::CFGuard_Check: 1991 return CC; 1992 case CallingConv::PreserveMost: 1993 return CallingConv::PreserveMost; 1994 case CallingConv::ARM_AAPCS_VFP: 1995 case CallingConv::Swift: 1996 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1997 case CallingConv::C: 1998 if (!Subtarget->isAAPCS_ABI()) 1999 return CallingConv::ARM_APCS; 2000 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 2001 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 2002 !isVarArg) 2003 return CallingConv::ARM_AAPCS_VFP; 2004 else 2005 return CallingConv::ARM_AAPCS; 2006 case CallingConv::Fast: 2007 case CallingConv::CXX_FAST_TLS: 2008 if (!Subtarget->isAAPCS_ABI()) { 2009 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 2010 return CallingConv::Fast; 2011 return CallingConv::ARM_APCS; 2012 } else if (Subtarget->hasVFP2Base() && 2013 !Subtarget->isThumb1Only() && !isVarArg) 2014 return CallingConv::ARM_AAPCS_VFP; 2015 else 2016 return CallingConv::ARM_AAPCS; 2017 } 2018 } 2019 2020 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2021 bool isVarArg) const { 2022 return CCAssignFnForNode(CC, false, isVarArg); 2023 } 2024 2025 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 2026 bool isVarArg) const { 2027 return CCAssignFnForNode(CC, true, isVarArg); 2028 } 2029 2030 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 2031 /// CallingConvention. 2032 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 2033 bool Return, 2034 bool isVarArg) const { 2035 switch (getEffectiveCallingConv(CC, isVarArg)) { 2036 default: 2037 report_fatal_error("Unsupported calling convention"); 2038 case CallingConv::ARM_APCS: 2039 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 2040 case CallingConv::ARM_AAPCS: 2041 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2042 case CallingConv::ARM_AAPCS_VFP: 2043 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 2044 case CallingConv::Fast: 2045 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 2046 case CallingConv::GHC: 2047 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 2048 case CallingConv::PreserveMost: 2049 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2050 case CallingConv::CFGuard_Check: 2051 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check); 2052 } 2053 } 2054 2055 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG, 2056 MVT LocVT, MVT ValVT, SDValue Val) const { 2057 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()), 2058 Val); 2059 if (Subtarget->hasFullFP16()) { 2060 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val); 2061 } else { 2062 Val = DAG.getNode(ISD::TRUNCATE, dl, 2063 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2064 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val); 2065 } 2066 return Val; 2067 } 2068 2069 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG, 2070 MVT LocVT, MVT ValVT, 2071 SDValue Val) const { 2072 if (Subtarget->hasFullFP16()) { 2073 Val = DAG.getNode(ARMISD::VMOVrh, dl, 2074 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2075 } else { 2076 Val = DAG.getNode(ISD::BITCAST, dl, 2077 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2078 Val = DAG.getNode(ISD::ZERO_EXTEND, dl, 2079 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2080 } 2081 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val); 2082 } 2083 2084 /// LowerCallResult - Lower the result values of a call into the 2085 /// appropriate copies out of appropriate physical registers. 2086 SDValue ARMTargetLowering::LowerCallResult( 2087 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2088 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 2089 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2090 SDValue ThisVal) const { 2091 // Assign locations to each value returned by this call. 2092 SmallVector<CCValAssign, 16> RVLocs; 2093 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2094 *DAG.getContext()); 2095 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 2096 2097 // Copy all of the result registers out of their specified physreg. 2098 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2099 CCValAssign VA = RVLocs[i]; 2100 2101 // Pass 'this' value directly from the argument to return value, to avoid 2102 // reg unit interference 2103 if (i == 0 && isThisReturn) { 2104 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 2105 "unexpected return calling convention register assignment"); 2106 InVals.push_back(ThisVal); 2107 continue; 2108 } 2109 2110 SDValue Val; 2111 if (VA.needsCustom() && 2112 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) { 2113 // Handle f64 or half of a v2f64. 2114 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2115 InFlag); 2116 Chain = Lo.getValue(1); 2117 InFlag = Lo.getValue(2); 2118 VA = RVLocs[++i]; // skip ahead to next loc 2119 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2120 InFlag); 2121 Chain = Hi.getValue(1); 2122 InFlag = Hi.getValue(2); 2123 if (!Subtarget->isLittle()) 2124 std::swap (Lo, Hi); 2125 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2126 2127 if (VA.getLocVT() == MVT::v2f64) { 2128 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 2129 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2130 DAG.getConstant(0, dl, MVT::i32)); 2131 2132 VA = RVLocs[++i]; // skip ahead to next loc 2133 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2134 Chain = Lo.getValue(1); 2135 InFlag = Lo.getValue(2); 2136 VA = RVLocs[++i]; // skip ahead to next loc 2137 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2138 Chain = Hi.getValue(1); 2139 InFlag = Hi.getValue(2); 2140 if (!Subtarget->isLittle()) 2141 std::swap (Lo, Hi); 2142 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2143 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2144 DAG.getConstant(1, dl, MVT::i32)); 2145 } 2146 } else { 2147 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 2148 InFlag); 2149 Chain = Val.getValue(1); 2150 InFlag = Val.getValue(2); 2151 } 2152 2153 switch (VA.getLocInfo()) { 2154 default: llvm_unreachable("Unknown loc info!"); 2155 case CCValAssign::Full: break; 2156 case CCValAssign::BCvt: 2157 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 2158 break; 2159 } 2160 2161 // f16 arguments have their size extended to 4 bytes and passed as if they 2162 // had been copied to the LSBs of a 32-bit register. 2163 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2164 if (VA.needsCustom() && 2165 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 2166 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val); 2167 2168 InVals.push_back(Val); 2169 } 2170 2171 return Chain; 2172 } 2173 2174 /// LowerMemOpCallTo - Store the argument to the stack. 2175 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 2176 SDValue Arg, const SDLoc &dl, 2177 SelectionDAG &DAG, 2178 const CCValAssign &VA, 2179 ISD::ArgFlagsTy Flags) const { 2180 unsigned LocMemOffset = VA.getLocMemOffset(); 2181 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2182 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 2183 StackPtr, PtrOff); 2184 return DAG.getStore( 2185 Chain, dl, Arg, PtrOff, 2186 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 2187 } 2188 2189 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 2190 SDValue Chain, SDValue &Arg, 2191 RegsToPassVector &RegsToPass, 2192 CCValAssign &VA, CCValAssign &NextVA, 2193 SDValue &StackPtr, 2194 SmallVectorImpl<SDValue> &MemOpChains, 2195 ISD::ArgFlagsTy Flags) const { 2196 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2197 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2198 unsigned id = Subtarget->isLittle() ? 0 : 1; 2199 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2200 2201 if (NextVA.isRegLoc()) 2202 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2203 else { 2204 assert(NextVA.isMemLoc()); 2205 if (!StackPtr.getNode()) 2206 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2207 getPointerTy(DAG.getDataLayout())); 2208 2209 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2210 dl, DAG, NextVA, 2211 Flags)); 2212 } 2213 } 2214 2215 /// LowerCall - Lowering a call into a callseq_start <- 2216 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2217 /// nodes. 2218 SDValue 2219 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2220 SmallVectorImpl<SDValue> &InVals) const { 2221 SelectionDAG &DAG = CLI.DAG; 2222 SDLoc &dl = CLI.DL; 2223 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2224 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2225 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2226 SDValue Chain = CLI.Chain; 2227 SDValue Callee = CLI.Callee; 2228 bool &isTailCall = CLI.IsTailCall; 2229 CallingConv::ID CallConv = CLI.CallConv; 2230 bool doesNotRet = CLI.DoesNotReturn; 2231 bool isVarArg = CLI.IsVarArg; 2232 2233 MachineFunction &MF = DAG.getMachineFunction(); 2234 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2235 MachineFunction::CallSiteInfo CSInfo; 2236 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2237 bool isThisReturn = false; 2238 bool isCmseNSCall = false; 2239 bool PreferIndirect = false; 2240 2241 // Determine whether this is a non-secure function call. 2242 if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call")) 2243 isCmseNSCall = true; 2244 2245 // Disable tail calls if they're not supported. 2246 if (!Subtarget->supportsTailCall()) 2247 isTailCall = false; 2248 2249 // For both the non-secure calls and the returns from a CMSE entry function, 2250 // the function needs to do some extra work afte r the call, or before the 2251 // return, respectively, thus it cannot end with atail call 2252 if (isCmseNSCall || AFI->isCmseNSEntryFunction()) 2253 isTailCall = false; 2254 2255 if (isa<GlobalAddressSDNode>(Callee)) { 2256 // If we're optimizing for minimum size and the function is called three or 2257 // more times in this block, we can improve codesize by calling indirectly 2258 // as BLXr has a 16-bit encoding. 2259 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2260 if (CLI.CB) { 2261 auto *BB = CLI.CB->getParent(); 2262 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2263 count_if(GV->users(), [&BB](const User *U) { 2264 return isa<Instruction>(U) && 2265 cast<Instruction>(U)->getParent() == BB; 2266 }) > 2; 2267 } 2268 } 2269 if (isTailCall) { 2270 // Check if it's really possible to do a tail call. 2271 isTailCall = IsEligibleForTailCallOptimization( 2272 Callee, CallConv, isVarArg, isStructRet, 2273 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2274 PreferIndirect); 2275 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall()) 2276 report_fatal_error("failed to perform tail call elimination on a call " 2277 "site marked musttail"); 2278 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2279 // detected sibcalls. 2280 if (isTailCall) 2281 ++NumTailCalls; 2282 } 2283 2284 // Analyze operands of the call, assigning locations to each operand. 2285 SmallVector<CCValAssign, 16> ArgLocs; 2286 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2287 *DAG.getContext()); 2288 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2289 2290 // Get a count of how many bytes are to be pushed on the stack. 2291 unsigned NumBytes = CCInfo.getNextStackOffset(); 2292 2293 if (isTailCall) { 2294 // For tail calls, memory operands are available in our caller's stack. 2295 NumBytes = 0; 2296 } else { 2297 // Adjust the stack pointer for the new arguments... 2298 // These operations are automatically eliminated by the prolog/epilog pass 2299 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2300 } 2301 2302 SDValue StackPtr = 2303 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2304 2305 RegsToPassVector RegsToPass; 2306 SmallVector<SDValue, 8> MemOpChains; 2307 2308 // Walk the register/memloc assignments, inserting copies/loads. In the case 2309 // of tail call optimization, arguments are handled later. 2310 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2311 i != e; 2312 ++i, ++realArgIdx) { 2313 CCValAssign &VA = ArgLocs[i]; 2314 SDValue Arg = OutVals[realArgIdx]; 2315 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2316 bool isByVal = Flags.isByVal(); 2317 2318 // Promote the value if needed. 2319 switch (VA.getLocInfo()) { 2320 default: llvm_unreachable("Unknown loc info!"); 2321 case CCValAssign::Full: break; 2322 case CCValAssign::SExt: 2323 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2324 break; 2325 case CCValAssign::ZExt: 2326 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2327 break; 2328 case CCValAssign::AExt: 2329 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2330 break; 2331 case CCValAssign::BCvt: 2332 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2333 break; 2334 } 2335 2336 // f16 arguments have their size extended to 4 bytes and passed as if they 2337 // had been copied to the LSBs of a 32-bit register. 2338 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2339 if (VA.needsCustom() && 2340 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) { 2341 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 2342 } else { 2343 // f16 arguments could have been extended prior to argument lowering. 2344 // Mask them arguments if this is a CMSE nonsecure call. 2345 auto ArgVT = Outs[realArgIdx].ArgVT; 2346 if (isCmseNSCall && (ArgVT == MVT::f16)) { 2347 auto LocBits = VA.getLocVT().getSizeInBits(); 2348 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits()); 2349 SDValue Mask = 2350 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 2351 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 2352 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 2353 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2354 } 2355 } 2356 2357 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2358 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 2359 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2360 DAG.getConstant(0, dl, MVT::i32)); 2361 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2362 DAG.getConstant(1, dl, MVT::i32)); 2363 2364 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i], 2365 StackPtr, MemOpChains, Flags); 2366 2367 VA = ArgLocs[++i]; // skip ahead to next loc 2368 if (VA.isRegLoc()) { 2369 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i], 2370 StackPtr, MemOpChains, Flags); 2371 } else { 2372 assert(VA.isMemLoc()); 2373 2374 MemOpChains.push_back( 2375 LowerMemOpCallTo(Chain, StackPtr, Op1, dl, DAG, VA, Flags)); 2376 } 2377 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 2378 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2379 StackPtr, MemOpChains, Flags); 2380 } else if (VA.isRegLoc()) { 2381 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2382 Outs[0].VT == MVT::i32) { 2383 assert(VA.getLocVT() == MVT::i32 && 2384 "unexpected calling convention register assignment"); 2385 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2386 "unexpected use of 'returned'"); 2387 isThisReturn = true; 2388 } 2389 const TargetOptions &Options = DAG.getTarget().Options; 2390 if (Options.EmitCallSiteInfo) 2391 CSInfo.emplace_back(VA.getLocReg(), i); 2392 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2393 } else if (isByVal) { 2394 assert(VA.isMemLoc()); 2395 unsigned offset = 0; 2396 2397 // True if this byval aggregate will be split between registers 2398 // and memory. 2399 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2400 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2401 2402 if (CurByValIdx < ByValArgsCount) { 2403 2404 unsigned RegBegin, RegEnd; 2405 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2406 2407 EVT PtrVT = 2408 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2409 unsigned int i, j; 2410 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2411 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2412 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2413 SDValue Load = 2414 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(), 2415 DAG.InferPtrAlign(AddArg)); 2416 MemOpChains.push_back(Load.getValue(1)); 2417 RegsToPass.push_back(std::make_pair(j, Load)); 2418 } 2419 2420 // If parameter size outsides register area, "offset" value 2421 // helps us to calculate stack slot for remained part properly. 2422 offset = RegEnd - RegBegin; 2423 2424 CCInfo.nextInRegsParam(); 2425 } 2426 2427 if (Flags.getByValSize() > 4*offset) { 2428 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2429 unsigned LocMemOffset = VA.getLocMemOffset(); 2430 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2431 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2432 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2433 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2434 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2435 MVT::i32); 2436 SDValue AlignNode = 2437 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32); 2438 2439 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2440 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2441 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2442 Ops)); 2443 } 2444 } else if (!isTailCall) { 2445 assert(VA.isMemLoc()); 2446 2447 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2448 dl, DAG, VA, Flags)); 2449 } 2450 } 2451 2452 if (!MemOpChains.empty()) 2453 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2454 2455 // Build a sequence of copy-to-reg nodes chained together with token chain 2456 // and flag operands which copy the outgoing args into the appropriate regs. 2457 SDValue InFlag; 2458 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2459 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2460 RegsToPass[i].second, InFlag); 2461 InFlag = Chain.getValue(1); 2462 } 2463 2464 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2465 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2466 // node so that legalize doesn't hack it. 2467 bool isDirect = false; 2468 2469 const TargetMachine &TM = getTargetMachine(); 2470 const Module *Mod = MF.getFunction().getParent(); 2471 const GlobalValue *GV = nullptr; 2472 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2473 GV = G->getGlobal(); 2474 bool isStub = 2475 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2476 2477 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2478 bool isLocalARMFunc = false; 2479 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2480 2481 if (Subtarget->genLongCalls()) { 2482 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2483 "long-calls codegen is not position independent!"); 2484 // Handle a global address or an external symbol. If it's not one of 2485 // those, the target's already in a register, so we don't need to do 2486 // anything extra. 2487 if (isa<GlobalAddressSDNode>(Callee)) { 2488 // Create a constant pool entry for the callee address 2489 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2490 ARMConstantPoolValue *CPV = 2491 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2492 2493 // Get the address of the callee into a register 2494 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2495 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2496 Callee = DAG.getLoad( 2497 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2498 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2499 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2500 const char *Sym = S->getSymbol(); 2501 2502 // Create a constant pool entry for the callee address 2503 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2504 ARMConstantPoolValue *CPV = 2505 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2506 ARMPCLabelIndex, 0); 2507 // Get the address of the callee into a register 2508 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2509 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2510 Callee = DAG.getLoad( 2511 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2512 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2513 } 2514 } else if (isa<GlobalAddressSDNode>(Callee)) { 2515 if (!PreferIndirect) { 2516 isDirect = true; 2517 bool isDef = GV->isStrongDefinitionForLinker(); 2518 2519 // ARM call to a local ARM function is predicable. 2520 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2521 // tBX takes a register source operand. 2522 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2523 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2524 Callee = DAG.getNode( 2525 ARMISD::WrapperPIC, dl, PtrVt, 2526 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2527 Callee = DAG.getLoad( 2528 PtrVt, dl, DAG.getEntryNode(), Callee, 2529 MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(), 2530 MachineMemOperand::MODereferenceable | 2531 MachineMemOperand::MOInvariant); 2532 } else if (Subtarget->isTargetCOFF()) { 2533 assert(Subtarget->isTargetWindows() && 2534 "Windows is the only supported COFF target"); 2535 unsigned TargetFlags = ARMII::MO_NO_FLAG; 2536 if (GV->hasDLLImportStorageClass()) 2537 TargetFlags = ARMII::MO_DLLIMPORT; 2538 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 2539 TargetFlags = ARMII::MO_COFFSTUB; 2540 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2541 TargetFlags); 2542 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 2543 Callee = 2544 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2545 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2546 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2547 } else { 2548 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2549 } 2550 } 2551 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2552 isDirect = true; 2553 // tBX takes a register source operand. 2554 const char *Sym = S->getSymbol(); 2555 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2556 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2557 ARMConstantPoolValue *CPV = 2558 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2559 ARMPCLabelIndex, 4); 2560 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2561 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2562 Callee = DAG.getLoad( 2563 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2564 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2565 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2566 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2567 } else { 2568 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2569 } 2570 } 2571 2572 if (isCmseNSCall) { 2573 assert(!isARMFunc && !isDirect && 2574 "Cannot handle call to ARM function or direct call"); 2575 if (NumBytes > 0) { 2576 DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(), 2577 "call to non-secure function would " 2578 "require passing arguments on stack", 2579 dl.getDebugLoc()); 2580 DAG.getContext()->diagnose(Diag); 2581 } 2582 if (isStructRet) { 2583 DiagnosticInfoUnsupported Diag( 2584 DAG.getMachineFunction().getFunction(), 2585 "call to non-secure function would return value through pointer", 2586 dl.getDebugLoc()); 2587 DAG.getContext()->diagnose(Diag); 2588 } 2589 } 2590 2591 // FIXME: handle tail calls differently. 2592 unsigned CallOpc; 2593 if (Subtarget->isThumb()) { 2594 if (isCmseNSCall) 2595 CallOpc = ARMISD::tSECALL; 2596 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2597 CallOpc = ARMISD::CALL_NOLINK; 2598 else 2599 CallOpc = ARMISD::CALL; 2600 } else { 2601 if (!isDirect && !Subtarget->hasV5TOps()) 2602 CallOpc = ARMISD::CALL_NOLINK; 2603 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2604 // Emit regular call when code size is the priority 2605 !Subtarget->hasMinSize()) 2606 // "mov lr, pc; b _foo" to avoid confusing the RSP 2607 CallOpc = ARMISD::CALL_NOLINK; 2608 else 2609 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2610 } 2611 2612 std::vector<SDValue> Ops; 2613 Ops.push_back(Chain); 2614 Ops.push_back(Callee); 2615 2616 // Add argument registers to the end of the list so that they are known live 2617 // into the call. 2618 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2619 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2620 RegsToPass[i].second.getValueType())); 2621 2622 // Add a register mask operand representing the call-preserved registers. 2623 if (!isTailCall) { 2624 const uint32_t *Mask; 2625 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2626 if (isThisReturn) { 2627 // For 'this' returns, use the R0-preserving mask if applicable 2628 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2629 if (!Mask) { 2630 // Set isThisReturn to false if the calling convention is not one that 2631 // allows 'returned' to be modeled in this way, so LowerCallResult does 2632 // not try to pass 'this' straight through 2633 isThisReturn = false; 2634 Mask = ARI->getCallPreservedMask(MF, CallConv); 2635 } 2636 } else 2637 Mask = ARI->getCallPreservedMask(MF, CallConv); 2638 2639 assert(Mask && "Missing call preserved mask for calling convention"); 2640 Ops.push_back(DAG.getRegisterMask(Mask)); 2641 } 2642 2643 if (InFlag.getNode()) 2644 Ops.push_back(InFlag); 2645 2646 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2647 if (isTailCall) { 2648 MF.getFrameInfo().setHasTailCall(); 2649 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2650 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 2651 return Ret; 2652 } 2653 2654 // Returns a chain and a flag for retval copy to use. 2655 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2656 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 2657 InFlag = Chain.getValue(1); 2658 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 2659 2660 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2661 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2662 if (!Ins.empty()) 2663 InFlag = Chain.getValue(1); 2664 2665 // Handle result values, copying them out of physregs into vregs that we 2666 // return. 2667 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2668 InVals, isThisReturn, 2669 isThisReturn ? OutVals[0] : SDValue()); 2670 } 2671 2672 /// HandleByVal - Every parameter *after* a byval parameter is passed 2673 /// on the stack. Remember the next parameter register to allocate, 2674 /// and then confiscate the rest of the parameter registers to insure 2675 /// this. 2676 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2677 Align Alignment) const { 2678 // Byval (as with any stack) slots are always at least 4 byte aligned. 2679 Alignment = std::max(Alignment, Align(4)); 2680 2681 unsigned Reg = State->AllocateReg(GPRArgRegs); 2682 if (!Reg) 2683 return; 2684 2685 unsigned AlignInRegs = Alignment.value() / 4; 2686 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2687 for (unsigned i = 0; i < Waste; ++i) 2688 Reg = State->AllocateReg(GPRArgRegs); 2689 2690 if (!Reg) 2691 return; 2692 2693 unsigned Excess = 4 * (ARM::R4 - Reg); 2694 2695 // Special case when NSAA != SP and parameter size greater than size of 2696 // all remained GPR regs. In that case we can't split parameter, we must 2697 // send it to stack. We also must set NCRN to R4, so waste all 2698 // remained registers. 2699 const unsigned NSAAOffset = State->getNextStackOffset(); 2700 if (NSAAOffset != 0 && Size > Excess) { 2701 while (State->AllocateReg(GPRArgRegs)) 2702 ; 2703 return; 2704 } 2705 2706 // First register for byval parameter is the first register that wasn't 2707 // allocated before this method call, so it would be "reg". 2708 // If parameter is small enough to be saved in range [reg, r4), then 2709 // the end (first after last) register would be reg + param-size-in-regs, 2710 // else parameter would be splitted between registers and stack, 2711 // end register would be r4 in this case. 2712 unsigned ByValRegBegin = Reg; 2713 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2714 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2715 // Note, first register is allocated in the beginning of function already, 2716 // allocate remained amount of registers we need. 2717 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2718 State->AllocateReg(GPRArgRegs); 2719 // A byval parameter that is split between registers and memory needs its 2720 // size truncated here. 2721 // In the case where the entire structure fits in registers, we set the 2722 // size in memory to zero. 2723 Size = std::max<int>(Size - Excess, 0); 2724 } 2725 2726 /// MatchingStackOffset - Return true if the given stack call argument is 2727 /// already available in the same position (relatively) of the caller's 2728 /// incoming argument stack. 2729 static 2730 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2731 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2732 const TargetInstrInfo *TII) { 2733 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2734 int FI = std::numeric_limits<int>::max(); 2735 if (Arg.getOpcode() == ISD::CopyFromReg) { 2736 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2737 if (!Register::isVirtualRegister(VR)) 2738 return false; 2739 MachineInstr *Def = MRI->getVRegDef(VR); 2740 if (!Def) 2741 return false; 2742 if (!Flags.isByVal()) { 2743 if (!TII->isLoadFromStackSlot(*Def, FI)) 2744 return false; 2745 } else { 2746 return false; 2747 } 2748 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2749 if (Flags.isByVal()) 2750 // ByVal argument is passed in as a pointer but it's now being 2751 // dereferenced. e.g. 2752 // define @foo(%struct.X* %A) { 2753 // tail call @bar(%struct.X* byval %A) 2754 // } 2755 return false; 2756 SDValue Ptr = Ld->getBasePtr(); 2757 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2758 if (!FINode) 2759 return false; 2760 FI = FINode->getIndex(); 2761 } else 2762 return false; 2763 2764 assert(FI != std::numeric_limits<int>::max()); 2765 if (!MFI.isFixedObjectIndex(FI)) 2766 return false; 2767 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2768 } 2769 2770 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2771 /// for tail call optimization. Targets which want to do tail call 2772 /// optimization should implement this function. 2773 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2774 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2775 bool isCalleeStructRet, bool isCallerStructRet, 2776 const SmallVectorImpl<ISD::OutputArg> &Outs, 2777 const SmallVectorImpl<SDValue> &OutVals, 2778 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2779 const bool isIndirect) const { 2780 MachineFunction &MF = DAG.getMachineFunction(); 2781 const Function &CallerF = MF.getFunction(); 2782 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2783 2784 assert(Subtarget->supportsTailCall()); 2785 2786 // Indirect tail calls cannot be optimized for Thumb1 if the args 2787 // to the call take up r0-r3. The reason is that there are no legal registers 2788 // left to hold the pointer to the function to be called. 2789 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2790 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2791 return false; 2792 2793 // Look for obvious safe cases to perform tail call optimization that do not 2794 // require ABI changes. This is what gcc calls sibcall. 2795 2796 // Exception-handling functions need a special set of instructions to indicate 2797 // a return to the hardware. Tail-calling another function would probably 2798 // break this. 2799 if (CallerF.hasFnAttribute("interrupt")) 2800 return false; 2801 2802 // Also avoid sibcall optimization if either caller or callee uses struct 2803 // return semantics. 2804 if (isCalleeStructRet || isCallerStructRet) 2805 return false; 2806 2807 // Externally-defined functions with weak linkage should not be 2808 // tail-called on ARM when the OS does not support dynamic 2809 // pre-emption of symbols, as the AAELF spec requires normal calls 2810 // to undefined weak functions to be replaced with a NOP or jump to the 2811 // next instruction. The behaviour of branch instructions in this 2812 // situation (as used for tail calls) is implementation-defined, so we 2813 // cannot rely on the linker replacing the tail call with a return. 2814 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2815 const GlobalValue *GV = G->getGlobal(); 2816 const Triple &TT = getTargetMachine().getTargetTriple(); 2817 if (GV->hasExternalWeakLinkage() && 2818 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2819 return false; 2820 } 2821 2822 // Check that the call results are passed in the same way. 2823 LLVMContext &C = *DAG.getContext(); 2824 if (!CCState::resultsCompatible( 2825 getEffectiveCallingConv(CalleeCC, isVarArg), 2826 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins, 2827 CCAssignFnForReturn(CalleeCC, isVarArg), 2828 CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) 2829 return false; 2830 // The callee has to preserve all registers the caller needs to preserve. 2831 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2832 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2833 if (CalleeCC != CallerCC) { 2834 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2835 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2836 return false; 2837 } 2838 2839 // If Caller's vararg or byval argument has been split between registers and 2840 // stack, do not perform tail call, since part of the argument is in caller's 2841 // local frame. 2842 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2843 if (AFI_Caller->getArgRegsSaveSize()) 2844 return false; 2845 2846 // If the callee takes no arguments then go on to check the results of the 2847 // call. 2848 if (!Outs.empty()) { 2849 // Check if stack adjustment is needed. For now, do not do this if any 2850 // argument is passed on the stack. 2851 SmallVector<CCValAssign, 16> ArgLocs; 2852 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2853 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2854 if (CCInfo.getNextStackOffset()) { 2855 // Check if the arguments are already laid out in the right way as 2856 // the caller's fixed stack objects. 2857 MachineFrameInfo &MFI = MF.getFrameInfo(); 2858 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2859 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2860 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2861 i != e; 2862 ++i, ++realArgIdx) { 2863 CCValAssign &VA = ArgLocs[i]; 2864 EVT RegVT = VA.getLocVT(); 2865 SDValue Arg = OutVals[realArgIdx]; 2866 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2867 if (VA.getLocInfo() == CCValAssign::Indirect) 2868 return false; 2869 if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) { 2870 // f64 and vector types are split into multiple registers or 2871 // register/stack-slot combinations. The types will not match 2872 // the registers; give up on memory f64 refs until we figure 2873 // out what to do about this. 2874 if (!VA.isRegLoc()) 2875 return false; 2876 if (!ArgLocs[++i].isRegLoc()) 2877 return false; 2878 if (RegVT == MVT::v2f64) { 2879 if (!ArgLocs[++i].isRegLoc()) 2880 return false; 2881 if (!ArgLocs[++i].isRegLoc()) 2882 return false; 2883 } 2884 } else if (!VA.isRegLoc()) { 2885 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2886 MFI, MRI, TII)) 2887 return false; 2888 } 2889 } 2890 } 2891 2892 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2893 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2894 return false; 2895 } 2896 2897 return true; 2898 } 2899 2900 bool 2901 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2902 MachineFunction &MF, bool isVarArg, 2903 const SmallVectorImpl<ISD::OutputArg> &Outs, 2904 LLVMContext &Context) const { 2905 SmallVector<CCValAssign, 16> RVLocs; 2906 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2907 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2908 } 2909 2910 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2911 const SDLoc &DL, SelectionDAG &DAG) { 2912 const MachineFunction &MF = DAG.getMachineFunction(); 2913 const Function &F = MF.getFunction(); 2914 2915 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2916 2917 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2918 // version of the "preferred return address". These offsets affect the return 2919 // instruction if this is a return from PL1 without hypervisor extensions. 2920 // IRQ/FIQ: +4 "subs pc, lr, #4" 2921 // SWI: 0 "subs pc, lr, #0" 2922 // ABORT: +4 "subs pc, lr, #4" 2923 // UNDEF: +4/+2 "subs pc, lr, #0" 2924 // UNDEF varies depending on where the exception came from ARM or Thumb 2925 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2926 2927 int64_t LROffset; 2928 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2929 IntKind == "ABORT") 2930 LROffset = 4; 2931 else if (IntKind == "SWI" || IntKind == "UNDEF") 2932 LROffset = 0; 2933 else 2934 report_fatal_error("Unsupported interrupt attribute. If present, value " 2935 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2936 2937 RetOps.insert(RetOps.begin() + 1, 2938 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2939 2940 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2941 } 2942 2943 SDValue 2944 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2945 bool isVarArg, 2946 const SmallVectorImpl<ISD::OutputArg> &Outs, 2947 const SmallVectorImpl<SDValue> &OutVals, 2948 const SDLoc &dl, SelectionDAG &DAG) const { 2949 // CCValAssign - represent the assignment of the return value to a location. 2950 SmallVector<CCValAssign, 16> RVLocs; 2951 2952 // CCState - Info about the registers and stack slots. 2953 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2954 *DAG.getContext()); 2955 2956 // Analyze outgoing return values. 2957 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2958 2959 SDValue Flag; 2960 SmallVector<SDValue, 4> RetOps; 2961 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2962 bool isLittleEndian = Subtarget->isLittle(); 2963 2964 MachineFunction &MF = DAG.getMachineFunction(); 2965 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2966 AFI->setReturnRegsCount(RVLocs.size()); 2967 2968 // Report error if cmse entry function returns structure through first ptr arg. 2969 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) { 2970 // Note: using an empty SDLoc(), as the first line of the function is a 2971 // better place to report than the last line. 2972 DiagnosticInfoUnsupported Diag( 2973 DAG.getMachineFunction().getFunction(), 2974 "secure entry function would return value through pointer", 2975 SDLoc().getDebugLoc()); 2976 DAG.getContext()->diagnose(Diag); 2977 } 2978 2979 // Copy the result values into the output registers. 2980 for (unsigned i = 0, realRVLocIdx = 0; 2981 i != RVLocs.size(); 2982 ++i, ++realRVLocIdx) { 2983 CCValAssign &VA = RVLocs[i]; 2984 assert(VA.isRegLoc() && "Can only return in registers!"); 2985 2986 SDValue Arg = OutVals[realRVLocIdx]; 2987 bool ReturnF16 = false; 2988 2989 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2990 // Half-precision return values can be returned like this: 2991 // 2992 // t11 f16 = fadd ... 2993 // t12: i16 = bitcast t11 2994 // t13: i32 = zero_extend t12 2995 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2996 // 2997 // to avoid code generation for bitcasts, we simply set Arg to the node 2998 // that produces the f16 value, t11 in this case. 2999 // 3000 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 3001 SDValue ZE = Arg.getOperand(0); 3002 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 3003 SDValue BC = ZE.getOperand(0); 3004 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 3005 Arg = BC.getOperand(0); 3006 ReturnF16 = true; 3007 } 3008 } 3009 } 3010 } 3011 3012 switch (VA.getLocInfo()) { 3013 default: llvm_unreachable("Unknown loc info!"); 3014 case CCValAssign::Full: break; 3015 case CCValAssign::BCvt: 3016 if (!ReturnF16) 3017 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3018 break; 3019 } 3020 3021 // Mask f16 arguments if this is a CMSE nonsecure entry. 3022 auto RetVT = Outs[realRVLocIdx].ArgVT; 3023 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) { 3024 if (VA.needsCustom() && VA.getValVT() == MVT::f16) { 3025 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 3026 } else { 3027 auto LocBits = VA.getLocVT().getSizeInBits(); 3028 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits()); 3029 SDValue Mask = 3030 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 3031 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 3032 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 3033 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3034 } 3035 } 3036 3037 if (VA.needsCustom() && 3038 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) { 3039 if (VA.getLocVT() == MVT::v2f64) { 3040 // Extract the first half and return it in two registers. 3041 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3042 DAG.getConstant(0, dl, MVT::i32)); 3043 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 3044 DAG.getVTList(MVT::i32, MVT::i32), Half); 3045 3046 Chain = 3047 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3048 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag); 3049 Flag = Chain.getValue(1); 3050 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3051 VA = RVLocs[++i]; // skip ahead to next loc 3052 Chain = 3053 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3054 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag); 3055 Flag = Chain.getValue(1); 3056 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3057 VA = RVLocs[++i]; // skip ahead to next loc 3058 3059 // Extract the 2nd half and fall through to handle it as an f64 value. 3060 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3061 DAG.getConstant(1, dl, MVT::i32)); 3062 } 3063 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 3064 // available. 3065 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 3066 DAG.getVTList(MVT::i32, MVT::i32), Arg); 3067 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3068 fmrrd.getValue(isLittleEndian ? 0 : 1), Flag); 3069 Flag = Chain.getValue(1); 3070 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3071 VA = RVLocs[++i]; // skip ahead to next loc 3072 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3073 fmrrd.getValue(isLittleEndian ? 1 : 0), Flag); 3074 } else 3075 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 3076 3077 // Guarantee that all emitted copies are 3078 // stuck together, avoiding something bad. 3079 Flag = Chain.getValue(1); 3080 RetOps.push_back(DAG.getRegister( 3081 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT())); 3082 } 3083 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 3084 const MCPhysReg *I = 3085 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3086 if (I) { 3087 for (; *I; ++I) { 3088 if (ARM::GPRRegClass.contains(*I)) 3089 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 3090 else if (ARM::DPRRegClass.contains(*I)) 3091 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3092 else 3093 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3094 } 3095 } 3096 3097 // Update chain and glue. 3098 RetOps[0] = Chain; 3099 if (Flag.getNode()) 3100 RetOps.push_back(Flag); 3101 3102 // CPUs which aren't M-class use a special sequence to return from 3103 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 3104 // though we use "subs pc, lr, #N"). 3105 // 3106 // M-class CPUs actually use a normal return sequence with a special 3107 // (hardware-provided) value in LR, so the normal code path works. 3108 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 3109 !Subtarget->isMClass()) { 3110 if (Subtarget->isThumb1Only()) 3111 report_fatal_error("interrupt attribute is not supported in Thumb1"); 3112 return LowerInterruptReturn(RetOps, dl, DAG); 3113 } 3114 3115 ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG : 3116 ARMISD::RET_FLAG; 3117 return DAG.getNode(RetNode, dl, MVT::Other, RetOps); 3118 } 3119 3120 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 3121 if (N->getNumValues() != 1) 3122 return false; 3123 if (!N->hasNUsesOfValue(1, 0)) 3124 return false; 3125 3126 SDValue TCChain = Chain; 3127 SDNode *Copy = *N->use_begin(); 3128 if (Copy->getOpcode() == ISD::CopyToReg) { 3129 // If the copy has a glue operand, we conservatively assume it isn't safe to 3130 // perform a tail call. 3131 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3132 return false; 3133 TCChain = Copy->getOperand(0); 3134 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 3135 SDNode *VMov = Copy; 3136 // f64 returned in a pair of GPRs. 3137 SmallPtrSet<SDNode*, 2> Copies; 3138 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3139 UI != UE; ++UI) { 3140 if (UI->getOpcode() != ISD::CopyToReg) 3141 return false; 3142 Copies.insert(*UI); 3143 } 3144 if (Copies.size() > 2) 3145 return false; 3146 3147 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3148 UI != UE; ++UI) { 3149 SDValue UseChain = UI->getOperand(0); 3150 if (Copies.count(UseChain.getNode())) 3151 // Second CopyToReg 3152 Copy = *UI; 3153 else { 3154 // We are at the top of this chain. 3155 // If the copy has a glue operand, we conservatively assume it 3156 // isn't safe to perform a tail call. 3157 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 3158 return false; 3159 // First CopyToReg 3160 TCChain = UseChain; 3161 } 3162 } 3163 } else if (Copy->getOpcode() == ISD::BITCAST) { 3164 // f32 returned in a single GPR. 3165 if (!Copy->hasOneUse()) 3166 return false; 3167 Copy = *Copy->use_begin(); 3168 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 3169 return false; 3170 // If the copy has a glue operand, we conservatively assume it isn't safe to 3171 // perform a tail call. 3172 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3173 return false; 3174 TCChain = Copy->getOperand(0); 3175 } else { 3176 return false; 3177 } 3178 3179 bool HasRet = false; 3180 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 3181 UI != UE; ++UI) { 3182 if (UI->getOpcode() != ARMISD::RET_FLAG && 3183 UI->getOpcode() != ARMISD::INTRET_FLAG) 3184 return false; 3185 HasRet = true; 3186 } 3187 3188 if (!HasRet) 3189 return false; 3190 3191 Chain = TCChain; 3192 return true; 3193 } 3194 3195 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3196 if (!Subtarget->supportsTailCall()) 3197 return false; 3198 3199 if (!CI->isTailCall()) 3200 return false; 3201 3202 return true; 3203 } 3204 3205 // Trying to write a 64 bit value so need to split into two 32 bit values first, 3206 // and pass the lower and high parts through. 3207 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 3208 SDLoc DL(Op); 3209 SDValue WriteValue = Op->getOperand(2); 3210 3211 // This function is only supposed to be called for i64 type argument. 3212 assert(WriteValue.getValueType() == MVT::i64 3213 && "LowerWRITE_REGISTER called for non-i64 type argument."); 3214 3215 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3216 DAG.getConstant(0, DL, MVT::i32)); 3217 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3218 DAG.getConstant(1, DL, MVT::i32)); 3219 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 3220 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 3221 } 3222 3223 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 3224 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 3225 // one of the above mentioned nodes. It has to be wrapped because otherwise 3226 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 3227 // be used to form addressing mode. These wrapped nodes will be selected 3228 // into MOVi. 3229 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 3230 SelectionDAG &DAG) const { 3231 EVT PtrVT = Op.getValueType(); 3232 // FIXME there is no actual debug info here 3233 SDLoc dl(Op); 3234 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3235 SDValue Res; 3236 3237 // When generating execute-only code Constant Pools must be promoted to the 3238 // global data section. It's a bit ugly that we can't share them across basic 3239 // blocks, but this way we guarantee that execute-only behaves correct with 3240 // position-independent addressing modes. 3241 if (Subtarget->genExecuteOnly()) { 3242 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3243 auto T = const_cast<Type*>(CP->getType()); 3244 auto C = const_cast<Constant*>(CP->getConstVal()); 3245 auto M = const_cast<Module*>(DAG.getMachineFunction(). 3246 getFunction().getParent()); 3247 auto GV = new GlobalVariable( 3248 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 3249 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 3250 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 3251 Twine(AFI->createPICLabelUId()) 3252 ); 3253 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 3254 dl, PtrVT); 3255 return LowerGlobalAddress(GA, DAG); 3256 } 3257 3258 if (CP->isMachineConstantPoolEntry()) 3259 Res = 3260 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign()); 3261 else 3262 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign()); 3263 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 3264 } 3265 3266 unsigned ARMTargetLowering::getJumpTableEncoding() const { 3267 return MachineJumpTableInfo::EK_Inline; 3268 } 3269 3270 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 3271 SelectionDAG &DAG) const { 3272 MachineFunction &MF = DAG.getMachineFunction(); 3273 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3274 unsigned ARMPCLabelIndex = 0; 3275 SDLoc DL(Op); 3276 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3277 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 3278 SDValue CPAddr; 3279 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 3280 if (!IsPositionIndependent) { 3281 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4)); 3282 } else { 3283 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3284 ARMPCLabelIndex = AFI->createPICLabelUId(); 3285 ARMConstantPoolValue *CPV = 3286 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3287 ARMCP::CPBlockAddress, PCAdj); 3288 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3289 } 3290 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3291 SDValue Result = DAG.getLoad( 3292 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3293 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3294 if (!IsPositionIndependent) 3295 return Result; 3296 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3297 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3298 } 3299 3300 /// Convert a TLS address reference into the correct sequence of loads 3301 /// and calls to compute the variable's address for Darwin, and return an 3302 /// SDValue containing the final node. 3303 3304 /// Darwin only has one TLS scheme which must be capable of dealing with the 3305 /// fully general situation, in the worst case. This means: 3306 /// + "extern __thread" declaration. 3307 /// + Defined in a possibly unknown dynamic library. 3308 /// 3309 /// The general system is that each __thread variable has a [3 x i32] descriptor 3310 /// which contains information used by the runtime to calculate the address. The 3311 /// only part of this the compiler needs to know about is the first word, which 3312 /// contains a function pointer that must be called with the address of the 3313 /// entire descriptor in "r0". 3314 /// 3315 /// Since this descriptor may be in a different unit, in general access must 3316 /// proceed along the usual ARM rules. A common sequence to produce is: 3317 /// 3318 /// movw rT1, :lower16:_var$non_lazy_ptr 3319 /// movt rT1, :upper16:_var$non_lazy_ptr 3320 /// ldr r0, [rT1] 3321 /// ldr rT2, [r0] 3322 /// blx rT2 3323 /// [...address now in r0...] 3324 SDValue 3325 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3326 SelectionDAG &DAG) const { 3327 assert(Subtarget->isTargetDarwin() && 3328 "This function expects a Darwin target"); 3329 SDLoc DL(Op); 3330 3331 // First step is to get the address of the actua global symbol. This is where 3332 // the TLS descriptor lives. 3333 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3334 3335 // The first entry in the descriptor is a function pointer that we must call 3336 // to obtain the address of the variable. 3337 SDValue Chain = DAG.getEntryNode(); 3338 SDValue FuncTLVGet = DAG.getLoad( 3339 MVT::i32, DL, Chain, DescAddr, 3340 MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4), 3341 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3342 MachineMemOperand::MOInvariant); 3343 Chain = FuncTLVGet.getValue(1); 3344 3345 MachineFunction &F = DAG.getMachineFunction(); 3346 MachineFrameInfo &MFI = F.getFrameInfo(); 3347 MFI.setAdjustsStack(true); 3348 3349 // TLS calls preserve all registers except those that absolutely must be 3350 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3351 // silly). 3352 auto TRI = 3353 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3354 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3355 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3356 3357 // Finally, we can make the call. This is just a degenerate version of a 3358 // normal AArch64 call node: r0 takes the address of the descriptor, and 3359 // returns the address of the variable in this thread. 3360 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3361 Chain = 3362 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3363 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3364 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3365 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3366 } 3367 3368 SDValue 3369 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3370 SelectionDAG &DAG) const { 3371 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3372 3373 SDValue Chain = DAG.getEntryNode(); 3374 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3375 SDLoc DL(Op); 3376 3377 // Load the current TEB (thread environment block) 3378 SDValue Ops[] = {Chain, 3379 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3380 DAG.getTargetConstant(15, DL, MVT::i32), 3381 DAG.getTargetConstant(0, DL, MVT::i32), 3382 DAG.getTargetConstant(13, DL, MVT::i32), 3383 DAG.getTargetConstant(0, DL, MVT::i32), 3384 DAG.getTargetConstant(2, DL, MVT::i32)}; 3385 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3386 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3387 3388 SDValue TEB = CurrentTEB.getValue(0); 3389 Chain = CurrentTEB.getValue(1); 3390 3391 // Load the ThreadLocalStoragePointer from the TEB 3392 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3393 SDValue TLSArray = 3394 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3395 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3396 3397 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3398 // offset into the TLSArray. 3399 3400 // Load the TLS index from the C runtime 3401 SDValue TLSIndex = 3402 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3403 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3404 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3405 3406 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3407 DAG.getConstant(2, DL, MVT::i32)); 3408 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3409 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3410 MachinePointerInfo()); 3411 3412 // Get the offset of the start of the .tls section (section base) 3413 const auto *GA = cast<GlobalAddressSDNode>(Op); 3414 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3415 SDValue Offset = DAG.getLoad( 3416 PtrVT, DL, Chain, 3417 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3418 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))), 3419 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3420 3421 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3422 } 3423 3424 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3425 SDValue 3426 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3427 SelectionDAG &DAG) const { 3428 SDLoc dl(GA); 3429 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3430 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3431 MachineFunction &MF = DAG.getMachineFunction(); 3432 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3433 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3434 ARMConstantPoolValue *CPV = 3435 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3436 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3437 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3438 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3439 Argument = DAG.getLoad( 3440 PtrVT, dl, DAG.getEntryNode(), Argument, 3441 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3442 SDValue Chain = Argument.getValue(1); 3443 3444 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3445 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3446 3447 // call __tls_get_addr. 3448 ArgListTy Args; 3449 ArgListEntry Entry; 3450 Entry.Node = Argument; 3451 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3452 Args.push_back(Entry); 3453 3454 // FIXME: is there useful debug info available here? 3455 TargetLowering::CallLoweringInfo CLI(DAG); 3456 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3457 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3458 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3459 3460 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3461 return CallResult.first; 3462 } 3463 3464 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3465 // "local exec" model. 3466 SDValue 3467 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3468 SelectionDAG &DAG, 3469 TLSModel::Model model) const { 3470 const GlobalValue *GV = GA->getGlobal(); 3471 SDLoc dl(GA); 3472 SDValue Offset; 3473 SDValue Chain = DAG.getEntryNode(); 3474 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3475 // Get the Thread Pointer 3476 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3477 3478 if (model == TLSModel::InitialExec) { 3479 MachineFunction &MF = DAG.getMachineFunction(); 3480 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3481 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3482 // Initial exec model. 3483 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3484 ARMConstantPoolValue *CPV = 3485 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3486 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3487 true); 3488 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3489 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3490 Offset = DAG.getLoad( 3491 PtrVT, dl, Chain, Offset, 3492 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3493 Chain = Offset.getValue(1); 3494 3495 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3496 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3497 3498 Offset = DAG.getLoad( 3499 PtrVT, dl, Chain, Offset, 3500 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3501 } else { 3502 // local exec model 3503 assert(model == TLSModel::LocalExec); 3504 ARMConstantPoolValue *CPV = 3505 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3506 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3507 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3508 Offset = DAG.getLoad( 3509 PtrVT, dl, Chain, Offset, 3510 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3511 } 3512 3513 // The address of the thread local variable is the add of the thread 3514 // pointer with the offset of the variable. 3515 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3516 } 3517 3518 SDValue 3519 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3520 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3521 if (DAG.getTarget().useEmulatedTLS()) 3522 return LowerToTLSEmulatedModel(GA, DAG); 3523 3524 if (Subtarget->isTargetDarwin()) 3525 return LowerGlobalTLSAddressDarwin(Op, DAG); 3526 3527 if (Subtarget->isTargetWindows()) 3528 return LowerGlobalTLSAddressWindows(Op, DAG); 3529 3530 // TODO: implement the "local dynamic" model 3531 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3532 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3533 3534 switch (model) { 3535 case TLSModel::GeneralDynamic: 3536 case TLSModel::LocalDynamic: 3537 return LowerToTLSGeneralDynamicModel(GA, DAG); 3538 case TLSModel::InitialExec: 3539 case TLSModel::LocalExec: 3540 return LowerToTLSExecModels(GA, DAG, model); 3541 } 3542 llvm_unreachable("bogus TLS model"); 3543 } 3544 3545 /// Return true if all users of V are within function F, looking through 3546 /// ConstantExprs. 3547 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3548 SmallVector<const User*,4> Worklist(V->users()); 3549 while (!Worklist.empty()) { 3550 auto *U = Worklist.pop_back_val(); 3551 if (isa<ConstantExpr>(U)) { 3552 append_range(Worklist, U->users()); 3553 continue; 3554 } 3555 3556 auto *I = dyn_cast<Instruction>(U); 3557 if (!I || I->getParent()->getParent() != F) 3558 return false; 3559 } 3560 return true; 3561 } 3562 3563 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3564 const GlobalValue *GV, SelectionDAG &DAG, 3565 EVT PtrVT, const SDLoc &dl) { 3566 // If we're creating a pool entry for a constant global with unnamed address, 3567 // and the global is small enough, we can emit it inline into the constant pool 3568 // to save ourselves an indirection. 3569 // 3570 // This is a win if the constant is only used in one function (so it doesn't 3571 // need to be duplicated) or duplicating the constant wouldn't increase code 3572 // size (implying the constant is no larger than 4 bytes). 3573 const Function &F = DAG.getMachineFunction().getFunction(); 3574 3575 // We rely on this decision to inline being idemopotent and unrelated to the 3576 // use-site. We know that if we inline a variable at one use site, we'll 3577 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3578 // doesn't know about this optimization, so bail out if it's enabled else 3579 // we could decide to inline here (and thus never emit the GV) but require 3580 // the GV from fast-isel generated code. 3581 if (!EnableConstpoolPromotion || 3582 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3583 return SDValue(); 3584 3585 auto *GVar = dyn_cast<GlobalVariable>(GV); 3586 if (!GVar || !GVar->hasInitializer() || 3587 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3588 !GVar->hasLocalLinkage()) 3589 return SDValue(); 3590 3591 // If we inline a value that contains relocations, we move the relocations 3592 // from .data to .text. This is not allowed in position-independent code. 3593 auto *Init = GVar->getInitializer(); 3594 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3595 Init->needsDynamicRelocation()) 3596 return SDValue(); 3597 3598 // The constant islands pass can only really deal with alignment requests 3599 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3600 // any type wanting greater alignment requirements than 4 bytes. We also 3601 // can only promote constants that are multiples of 4 bytes in size or 3602 // are paddable to a multiple of 4. Currently we only try and pad constants 3603 // that are strings for simplicity. 3604 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3605 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3606 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar); 3607 unsigned RequiredPadding = 4 - (Size % 4); 3608 bool PaddingPossible = 3609 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3610 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize || 3611 Size == 0) 3612 return SDValue(); 3613 3614 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3615 MachineFunction &MF = DAG.getMachineFunction(); 3616 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3617 3618 // We can't bloat the constant pool too much, else the ConstantIslands pass 3619 // may fail to converge. If we haven't promoted this global yet (it may have 3620 // multiple uses), and promoting it would increase the constant pool size (Sz 3621 // > 4), ensure we have space to do so up to MaxTotal. 3622 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3623 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3624 ConstpoolPromotionMaxTotal) 3625 return SDValue(); 3626 3627 // This is only valid if all users are in a single function; we can't clone 3628 // the constant in general. The LLVM IR unnamed_addr allows merging 3629 // constants, but not cloning them. 3630 // 3631 // We could potentially allow cloning if we could prove all uses of the 3632 // constant in the current function don't care about the address, like 3633 // printf format strings. But that isn't implemented for now. 3634 if (!allUsersAreInFunction(GVar, &F)) 3635 return SDValue(); 3636 3637 // We're going to inline this global. Pad it out if needed. 3638 if (RequiredPadding != 4) { 3639 StringRef S = CDAInit->getAsString(); 3640 3641 SmallVector<uint8_t,16> V(S.size()); 3642 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3643 while (RequiredPadding--) 3644 V.push_back(0); 3645 Init = ConstantDataArray::get(*DAG.getContext(), V); 3646 } 3647 3648 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3649 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4)); 3650 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3651 AFI->markGlobalAsPromotedToConstantPool(GVar); 3652 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3653 PaddedSize - 4); 3654 } 3655 ++NumConstpoolPromoted; 3656 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3657 } 3658 3659 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3660 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3661 if (!(GV = GA->getBaseObject())) 3662 return false; 3663 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3664 return V->isConstant(); 3665 return isa<Function>(GV); 3666 } 3667 3668 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3669 SelectionDAG &DAG) const { 3670 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3671 default: llvm_unreachable("unknown object format"); 3672 case Triple::COFF: 3673 return LowerGlobalAddressWindows(Op, DAG); 3674 case Triple::ELF: 3675 return LowerGlobalAddressELF(Op, DAG); 3676 case Triple::MachO: 3677 return LowerGlobalAddressDarwin(Op, DAG); 3678 } 3679 } 3680 3681 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3682 SelectionDAG &DAG) const { 3683 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3684 SDLoc dl(Op); 3685 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3686 const TargetMachine &TM = getTargetMachine(); 3687 bool IsRO = isReadOnly(GV); 3688 3689 // promoteToConstantPool only if not generating XO text section 3690 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3691 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3692 return V; 3693 3694 if (isPositionIndependent()) { 3695 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3696 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3697 UseGOT_PREL ? ARMII::MO_GOT : 0); 3698 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3699 if (UseGOT_PREL) 3700 Result = 3701 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3702 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3703 return Result; 3704 } else if (Subtarget->isROPI() && IsRO) { 3705 // PC-relative. 3706 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3707 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3708 return Result; 3709 } else if (Subtarget->isRWPI() && !IsRO) { 3710 // SB-relative. 3711 SDValue RelAddr; 3712 if (Subtarget->useMovt()) { 3713 ++NumMovwMovt; 3714 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3715 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3716 } else { // use literal pool for address constant 3717 ARMConstantPoolValue *CPV = 3718 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3719 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3720 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3721 RelAddr = DAG.getLoad( 3722 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3723 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3724 } 3725 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3726 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3727 return Result; 3728 } 3729 3730 // If we have T2 ops, we can materialize the address directly via movt/movw 3731 // pair. This is always cheaper. 3732 if (Subtarget->useMovt()) { 3733 ++NumMovwMovt; 3734 // FIXME: Once remat is capable of dealing with instructions with register 3735 // operands, expand this into two nodes. 3736 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3737 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3738 } else { 3739 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4)); 3740 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3741 return DAG.getLoad( 3742 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3743 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3744 } 3745 } 3746 3747 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3748 SelectionDAG &DAG) const { 3749 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3750 "ROPI/RWPI not currently supported for Darwin"); 3751 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3752 SDLoc dl(Op); 3753 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3754 3755 if (Subtarget->useMovt()) 3756 ++NumMovwMovt; 3757 3758 // FIXME: Once remat is capable of dealing with instructions with register 3759 // operands, expand this into multiple nodes 3760 unsigned Wrapper = 3761 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3762 3763 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3764 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3765 3766 if (Subtarget->isGVIndirectSymbol(GV)) 3767 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3768 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3769 return Result; 3770 } 3771 3772 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3773 SelectionDAG &DAG) const { 3774 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3775 assert(Subtarget->useMovt() && 3776 "Windows on ARM expects to use movw/movt"); 3777 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3778 "ROPI/RWPI not currently supported for Windows"); 3779 3780 const TargetMachine &TM = getTargetMachine(); 3781 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3782 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3783 if (GV->hasDLLImportStorageClass()) 3784 TargetFlags = ARMII::MO_DLLIMPORT; 3785 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3786 TargetFlags = ARMII::MO_COFFSTUB; 3787 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3788 SDValue Result; 3789 SDLoc DL(Op); 3790 3791 ++NumMovwMovt; 3792 3793 // FIXME: Once remat is capable of dealing with instructions with register 3794 // operands, expand this into two nodes. 3795 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3796 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3797 TargetFlags)); 3798 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3799 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3800 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3801 return Result; 3802 } 3803 3804 SDValue 3805 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3806 SDLoc dl(Op); 3807 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3808 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3809 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3810 Op.getOperand(1), Val); 3811 } 3812 3813 SDValue 3814 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3815 SDLoc dl(Op); 3816 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3817 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3818 } 3819 3820 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3821 SelectionDAG &DAG) const { 3822 SDLoc dl(Op); 3823 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3824 Op.getOperand(0)); 3825 } 3826 3827 SDValue ARMTargetLowering::LowerINTRINSIC_VOID( 3828 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const { 3829 unsigned IntNo = 3830 cast<ConstantSDNode>( 3831 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other)) 3832 ->getZExtValue(); 3833 switch (IntNo) { 3834 default: 3835 return SDValue(); // Don't custom lower most intrinsics. 3836 case Intrinsic::arm_gnu_eabi_mcount: { 3837 MachineFunction &MF = DAG.getMachineFunction(); 3838 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3839 SDLoc dl(Op); 3840 SDValue Chain = Op.getOperand(0); 3841 // call "\01__gnu_mcount_nc" 3842 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 3843 const uint32_t *Mask = 3844 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3845 assert(Mask && "Missing call preserved mask for calling convention"); 3846 // Mark LR an implicit live-in. 3847 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3848 SDValue ReturnAddress = 3849 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT); 3850 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue}; 3851 SDValue Callee = 3852 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0); 3853 SDValue RegisterMask = DAG.getRegisterMask(Mask); 3854 if (Subtarget->isThumb()) 3855 return SDValue( 3856 DAG.getMachineNode( 3857 ARM::tBL_PUSHLR, dl, ResultTys, 3858 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT), 3859 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}), 3860 0); 3861 return SDValue( 3862 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys, 3863 {ReturnAddress, Callee, RegisterMask, Chain}), 3864 0); 3865 } 3866 } 3867 } 3868 3869 SDValue 3870 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3871 const ARMSubtarget *Subtarget) const { 3872 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3873 SDLoc dl(Op); 3874 switch (IntNo) { 3875 default: return SDValue(); // Don't custom lower most intrinsics. 3876 case Intrinsic::thread_pointer: { 3877 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3878 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3879 } 3880 case Intrinsic::arm_cls: { 3881 const SDValue &Operand = Op.getOperand(1); 3882 const EVT VTy = Op.getValueType(); 3883 SDValue SRA = 3884 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy)); 3885 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand); 3886 SDValue SHL = 3887 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy)); 3888 SDValue OR = 3889 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy)); 3890 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR); 3891 return Result; 3892 } 3893 case Intrinsic::arm_cls64: { 3894 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x)) 3895 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x))) 3896 const SDValue &Operand = Op.getOperand(1); 3897 const EVT VTy = Op.getValueType(); 3898 3899 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3900 DAG.getConstant(1, dl, VTy)); 3901 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3902 DAG.getConstant(0, dl, VTy)); 3903 SDValue Constant0 = DAG.getConstant(0, dl, VTy); 3904 SDValue Constant1 = DAG.getConstant(1, dl, VTy); 3905 SDValue Constant31 = DAG.getConstant(31, dl, VTy); 3906 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31); 3907 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi); 3908 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1); 3909 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1); 3910 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi); 3911 SDValue CheckLo = 3912 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ); 3913 SDValue HiIsZero = 3914 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ); 3915 SDValue AdjustedLo = 3916 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy)); 3917 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo); 3918 SDValue Result = 3919 DAG.getSelect(dl, VTy, CheckLo, 3920 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi); 3921 return Result; 3922 } 3923 case Intrinsic::eh_sjlj_lsda: { 3924 MachineFunction &MF = DAG.getMachineFunction(); 3925 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3926 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3927 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3928 SDValue CPAddr; 3929 bool IsPositionIndependent = isPositionIndependent(); 3930 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3931 ARMConstantPoolValue *CPV = 3932 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3933 ARMCP::CPLSDA, PCAdj); 3934 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3935 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3936 SDValue Result = DAG.getLoad( 3937 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3938 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3939 3940 if (IsPositionIndependent) { 3941 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3942 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3943 } 3944 return Result; 3945 } 3946 case Intrinsic::arm_neon_vabs: 3947 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3948 Op.getOperand(1)); 3949 case Intrinsic::arm_neon_vmulls: 3950 case Intrinsic::arm_neon_vmullu: { 3951 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3952 ? ARMISD::VMULLs : ARMISD::VMULLu; 3953 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3954 Op.getOperand(1), Op.getOperand(2)); 3955 } 3956 case Intrinsic::arm_neon_vminnm: 3957 case Intrinsic::arm_neon_vmaxnm: { 3958 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3959 ? ISD::FMINNUM : ISD::FMAXNUM; 3960 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3961 Op.getOperand(1), Op.getOperand(2)); 3962 } 3963 case Intrinsic::arm_neon_vminu: 3964 case Intrinsic::arm_neon_vmaxu: { 3965 if (Op.getValueType().isFloatingPoint()) 3966 return SDValue(); 3967 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3968 ? ISD::UMIN : ISD::UMAX; 3969 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3970 Op.getOperand(1), Op.getOperand(2)); 3971 } 3972 case Intrinsic::arm_neon_vmins: 3973 case Intrinsic::arm_neon_vmaxs: { 3974 // v{min,max}s is overloaded between signed integers and floats. 3975 if (!Op.getValueType().isFloatingPoint()) { 3976 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3977 ? ISD::SMIN : ISD::SMAX; 3978 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3979 Op.getOperand(1), Op.getOperand(2)); 3980 } 3981 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3982 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3983 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3984 Op.getOperand(1), Op.getOperand(2)); 3985 } 3986 case Intrinsic::arm_neon_vtbl1: 3987 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3988 Op.getOperand(1), Op.getOperand(2)); 3989 case Intrinsic::arm_neon_vtbl2: 3990 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3991 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3992 case Intrinsic::arm_mve_pred_i2v: 3993 case Intrinsic::arm_mve_pred_v2i: 3994 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(), 3995 Op.getOperand(1)); 3996 case Intrinsic::arm_mve_vreinterpretq: 3997 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(), 3998 Op.getOperand(1)); 3999 case Intrinsic::arm_mve_lsll: 4000 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(), 4001 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4002 case Intrinsic::arm_mve_asrl: 4003 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(), 4004 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4005 } 4006 } 4007 4008 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 4009 const ARMSubtarget *Subtarget) { 4010 SDLoc dl(Op); 4011 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 4012 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 4013 if (SSID == SyncScope::SingleThread) 4014 return Op; 4015 4016 if (!Subtarget->hasDataBarrier()) { 4017 // Some ARMv6 cpus can support data barriers with an mcr instruction. 4018 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 4019 // here. 4020 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 4021 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 4022 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 4023 DAG.getConstant(0, dl, MVT::i32)); 4024 } 4025 4026 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 4027 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 4028 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 4029 if (Subtarget->isMClass()) { 4030 // Only a full system barrier exists in the M-class architectures. 4031 Domain = ARM_MB::SY; 4032 } else if (Subtarget->preferISHSTBarriers() && 4033 Ord == AtomicOrdering::Release) { 4034 // Swift happens to implement ISHST barriers in a way that's compatible with 4035 // Release semantics but weaker than ISH so we'd be fools not to use 4036 // it. Beware: other processors probably don't! 4037 Domain = ARM_MB::ISHST; 4038 } 4039 4040 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 4041 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 4042 DAG.getConstant(Domain, dl, MVT::i32)); 4043 } 4044 4045 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 4046 const ARMSubtarget *Subtarget) { 4047 // ARM pre v5TE and Thumb1 does not have preload instructions. 4048 if (!(Subtarget->isThumb2() || 4049 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 4050 // Just preserve the chain. 4051 return Op.getOperand(0); 4052 4053 SDLoc dl(Op); 4054 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 4055 if (!isRead && 4056 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 4057 // ARMv7 with MP extension has PLDW. 4058 return Op.getOperand(0); 4059 4060 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 4061 if (Subtarget->isThumb()) { 4062 // Invert the bits. 4063 isRead = ~isRead & 1; 4064 isData = ~isData & 1; 4065 } 4066 4067 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 4068 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 4069 DAG.getConstant(isData, dl, MVT::i32)); 4070 } 4071 4072 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 4073 MachineFunction &MF = DAG.getMachineFunction(); 4074 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 4075 4076 // vastart just stores the address of the VarArgsFrameIndex slot into the 4077 // memory location argument. 4078 SDLoc dl(Op); 4079 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4080 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4081 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4082 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 4083 MachinePointerInfo(SV)); 4084 } 4085 4086 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 4087 CCValAssign &NextVA, 4088 SDValue &Root, 4089 SelectionDAG &DAG, 4090 const SDLoc &dl) const { 4091 MachineFunction &MF = DAG.getMachineFunction(); 4092 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4093 4094 const TargetRegisterClass *RC; 4095 if (AFI->isThumb1OnlyFunction()) 4096 RC = &ARM::tGPRRegClass; 4097 else 4098 RC = &ARM::GPRRegClass; 4099 4100 // Transform the arguments stored in physical registers into virtual ones. 4101 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4102 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4103 4104 SDValue ArgValue2; 4105 if (NextVA.isMemLoc()) { 4106 MachineFrameInfo &MFI = MF.getFrameInfo(); 4107 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 4108 4109 // Create load node to retrieve arguments from the stack. 4110 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4111 ArgValue2 = DAG.getLoad( 4112 MVT::i32, dl, Root, FIN, 4113 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4114 } else { 4115 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 4116 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4117 } 4118 if (!Subtarget->isLittle()) 4119 std::swap (ArgValue, ArgValue2); 4120 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 4121 } 4122 4123 // The remaining GPRs hold either the beginning of variable-argument 4124 // data, or the beginning of an aggregate passed by value (usually 4125 // byval). Either way, we allocate stack slots adjacent to the data 4126 // provided by our caller, and store the unallocated registers there. 4127 // If this is a variadic function, the va_list pointer will begin with 4128 // these values; otherwise, this reassembles a (byval) structure that 4129 // was split between registers and memory. 4130 // Return: The frame index registers were stored into. 4131 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 4132 const SDLoc &dl, SDValue &Chain, 4133 const Value *OrigArg, 4134 unsigned InRegsParamRecordIdx, 4135 int ArgOffset, unsigned ArgSize) const { 4136 // Currently, two use-cases possible: 4137 // Case #1. Non-var-args function, and we meet first byval parameter. 4138 // Setup first unallocated register as first byval register; 4139 // eat all remained registers 4140 // (these two actions are performed by HandleByVal method). 4141 // Then, here, we initialize stack frame with 4142 // "store-reg" instructions. 4143 // Case #2. Var-args function, that doesn't contain byval parameters. 4144 // The same: eat all remained unallocated registers, 4145 // initialize stack frame. 4146 4147 MachineFunction &MF = DAG.getMachineFunction(); 4148 MachineFrameInfo &MFI = MF.getFrameInfo(); 4149 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4150 unsigned RBegin, REnd; 4151 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 4152 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 4153 } else { 4154 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4155 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 4156 REnd = ARM::R4; 4157 } 4158 4159 if (REnd != RBegin) 4160 ArgOffset = -4 * (ARM::R4 - RBegin); 4161 4162 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4163 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 4164 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 4165 4166 SmallVector<SDValue, 4> MemOps; 4167 const TargetRegisterClass *RC = 4168 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 4169 4170 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 4171 unsigned VReg = MF.addLiveIn(Reg, RC); 4172 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4173 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4174 MachinePointerInfo(OrigArg, 4 * i)); 4175 MemOps.push_back(Store); 4176 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 4177 } 4178 4179 if (!MemOps.empty()) 4180 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4181 return FrameIndex; 4182 } 4183 4184 // Setup stack frame, the va_list pointer will start from. 4185 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 4186 const SDLoc &dl, SDValue &Chain, 4187 unsigned ArgOffset, 4188 unsigned TotalArgRegsSaveSize, 4189 bool ForceMutable) const { 4190 MachineFunction &MF = DAG.getMachineFunction(); 4191 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4192 4193 // Try to store any remaining integer argument regs 4194 // to their spots on the stack so that they may be loaded by dereferencing 4195 // the result of va_next. 4196 // If there is no regs to be stored, just point address after last 4197 // argument passed via stack. 4198 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 4199 CCInfo.getInRegsParamsCount(), 4200 CCInfo.getNextStackOffset(), 4201 std::max(4U, TotalArgRegsSaveSize)); 4202 AFI->setVarArgsFrameIndex(FrameIndex); 4203 } 4204 4205 bool ARMTargetLowering::splitValueIntoRegisterParts( 4206 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 4207 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 4208 bool IsABIRegCopy = CC.hasValue(); 4209 EVT ValueVT = Val.getValueType(); 4210 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4211 PartVT == MVT::f32) { 4212 unsigned ValueBits = ValueVT.getSizeInBits(); 4213 unsigned PartBits = PartVT.getSizeInBits(); 4214 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val); 4215 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val); 4216 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 4217 Parts[0] = Val; 4218 return true; 4219 } 4220 return false; 4221 } 4222 4223 SDValue ARMTargetLowering::joinRegisterPartsIntoValue( 4224 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 4225 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 4226 bool IsABIRegCopy = CC.hasValue(); 4227 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4228 PartVT == MVT::f32) { 4229 unsigned ValueBits = ValueVT.getSizeInBits(); 4230 unsigned PartBits = PartVT.getSizeInBits(); 4231 SDValue Val = Parts[0]; 4232 4233 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val); 4234 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val); 4235 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 4236 return Val; 4237 } 4238 return SDValue(); 4239 } 4240 4241 SDValue ARMTargetLowering::LowerFormalArguments( 4242 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4243 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4244 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4245 MachineFunction &MF = DAG.getMachineFunction(); 4246 MachineFrameInfo &MFI = MF.getFrameInfo(); 4247 4248 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4249 4250 // Assign locations to all of the incoming arguments. 4251 SmallVector<CCValAssign, 16> ArgLocs; 4252 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4253 *DAG.getContext()); 4254 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 4255 4256 SmallVector<SDValue, 16> ArgValues; 4257 SDValue ArgValue; 4258 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4259 unsigned CurArgIdx = 0; 4260 4261 // Initially ArgRegsSaveSize is zero. 4262 // Then we increase this value each time we meet byval parameter. 4263 // We also increase this value in case of varargs function. 4264 AFI->setArgRegsSaveSize(0); 4265 4266 // Calculate the amount of stack space that we need to allocate to store 4267 // byval and variadic arguments that are passed in registers. 4268 // We need to know this before we allocate the first byval or variadic 4269 // argument, as they will be allocated a stack slot below the CFA (Canonical 4270 // Frame Address, the stack pointer at entry to the function). 4271 unsigned ArgRegBegin = ARM::R4; 4272 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4273 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 4274 break; 4275 4276 CCValAssign &VA = ArgLocs[i]; 4277 unsigned Index = VA.getValNo(); 4278 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 4279 if (!Flags.isByVal()) 4280 continue; 4281 4282 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 4283 unsigned RBegin, REnd; 4284 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 4285 ArgRegBegin = std::min(ArgRegBegin, RBegin); 4286 4287 CCInfo.nextInRegsParam(); 4288 } 4289 CCInfo.rewindByValRegsInfo(); 4290 4291 int lastInsIndex = -1; 4292 if (isVarArg && MFI.hasVAStart()) { 4293 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4294 if (RegIdx != array_lengthof(GPRArgRegs)) 4295 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 4296 } 4297 4298 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 4299 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 4300 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4301 4302 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4303 CCValAssign &VA = ArgLocs[i]; 4304 if (Ins[VA.getValNo()].isOrigArg()) { 4305 std::advance(CurOrigArg, 4306 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 4307 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 4308 } 4309 // Arguments stored in registers. 4310 if (VA.isRegLoc()) { 4311 EVT RegVT = VA.getLocVT(); 4312 4313 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 4314 // f64 and vector types are split up into multiple registers or 4315 // combinations of registers and stack slots. 4316 SDValue ArgValue1 = 4317 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4318 VA = ArgLocs[++i]; // skip ahead to next loc 4319 SDValue ArgValue2; 4320 if (VA.isMemLoc()) { 4321 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 4322 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4323 ArgValue2 = DAG.getLoad( 4324 MVT::f64, dl, Chain, FIN, 4325 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4326 } else { 4327 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4328 } 4329 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 4330 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4331 ArgValue1, DAG.getIntPtrConstant(0, dl)); 4332 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4333 ArgValue2, DAG.getIntPtrConstant(1, dl)); 4334 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 4335 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4336 } else { 4337 const TargetRegisterClass *RC; 4338 4339 if (RegVT == MVT::f16 || RegVT == MVT::bf16) 4340 RC = &ARM::HPRRegClass; 4341 else if (RegVT == MVT::f32) 4342 RC = &ARM::SPRRegClass; 4343 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 || 4344 RegVT == MVT::v4bf16) 4345 RC = &ARM::DPRRegClass; 4346 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 || 4347 RegVT == MVT::v8bf16) 4348 RC = &ARM::QPRRegClass; 4349 else if (RegVT == MVT::i32) 4350 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 4351 : &ARM::GPRRegClass; 4352 else 4353 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4354 4355 // Transform the arguments in physical registers into virtual ones. 4356 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4357 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 4358 4359 // If this value is passed in r0 and has the returned attribute (e.g. 4360 // C++ 'structors), record this fact for later use. 4361 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 4362 AFI->setPreservesR0(); 4363 } 4364 } 4365 4366 // If this is an 8 or 16-bit value, it is really passed promoted 4367 // to 32 bits. Insert an assert[sz]ext to capture this, then 4368 // truncate to the right size. 4369 switch (VA.getLocInfo()) { 4370 default: llvm_unreachable("Unknown loc info!"); 4371 case CCValAssign::Full: break; 4372 case CCValAssign::BCvt: 4373 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 4374 break; 4375 case CCValAssign::SExt: 4376 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 4377 DAG.getValueType(VA.getValVT())); 4378 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4379 break; 4380 case CCValAssign::ZExt: 4381 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 4382 DAG.getValueType(VA.getValVT())); 4383 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4384 break; 4385 } 4386 4387 // f16 arguments have their size extended to 4 bytes and passed as if they 4388 // had been copied to the LSBs of a 32-bit register. 4389 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 4390 if (VA.needsCustom() && 4391 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 4392 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue); 4393 4394 InVals.push_back(ArgValue); 4395 } else { // VA.isRegLoc() 4396 // sanity check 4397 assert(VA.isMemLoc()); 4398 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 4399 4400 int index = VA.getValNo(); 4401 4402 // Some Ins[] entries become multiple ArgLoc[] entries. 4403 // Process them only once. 4404 if (index != lastInsIndex) 4405 { 4406 ISD::ArgFlagsTy Flags = Ins[index].Flags; 4407 // FIXME: For now, all byval parameter objects are marked mutable. 4408 // This can be changed with more analysis. 4409 // In case of tail call optimization mark all arguments mutable. 4410 // Since they could be overwritten by lowering of arguments in case of 4411 // a tail call. 4412 if (Flags.isByVal()) { 4413 assert(Ins[index].isOrigArg() && 4414 "Byval arguments cannot be implicit"); 4415 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 4416 4417 int FrameIndex = StoreByValRegs( 4418 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4419 VA.getLocMemOffset(), Flags.getByValSize()); 4420 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4421 CCInfo.nextInRegsParam(); 4422 } else { 4423 unsigned FIOffset = VA.getLocMemOffset(); 4424 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4425 FIOffset, true); 4426 4427 // Create load nodes to retrieve arguments from the stack. 4428 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4429 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4430 MachinePointerInfo::getFixedStack( 4431 DAG.getMachineFunction(), FI))); 4432 } 4433 lastInsIndex = index; 4434 } 4435 } 4436 } 4437 4438 // varargs 4439 if (isVarArg && MFI.hasVAStart()) { 4440 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(), 4441 TotalArgRegsSaveSize); 4442 if (AFI->isCmseNSEntryFunction()) { 4443 DiagnosticInfoUnsupported Diag( 4444 DAG.getMachineFunction().getFunction(), 4445 "secure entry function must not be variadic", dl.getDebugLoc()); 4446 DAG.getContext()->diagnose(Diag); 4447 } 4448 } 4449 4450 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4451 4452 if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) { 4453 DiagnosticInfoUnsupported Diag( 4454 DAG.getMachineFunction().getFunction(), 4455 "secure entry function requires arguments on stack", dl.getDebugLoc()); 4456 DAG.getContext()->diagnose(Diag); 4457 } 4458 4459 return Chain; 4460 } 4461 4462 /// isFloatingPointZero - Return true if this is +0.0. 4463 static bool isFloatingPointZero(SDValue Op) { 4464 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4465 return CFP->getValueAPF().isPosZero(); 4466 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4467 // Maybe this has already been legalized into the constant pool? 4468 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4469 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4470 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4471 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4472 return CFP->getValueAPF().isPosZero(); 4473 } 4474 } else if (Op->getOpcode() == ISD::BITCAST && 4475 Op->getValueType(0) == MVT::f64) { 4476 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4477 // created by LowerConstantFP(). 4478 SDValue BitcastOp = Op->getOperand(0); 4479 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4480 isNullConstant(BitcastOp->getOperand(0))) 4481 return true; 4482 } 4483 return false; 4484 } 4485 4486 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4487 /// the given operands. 4488 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4489 SDValue &ARMcc, SelectionDAG &DAG, 4490 const SDLoc &dl) const { 4491 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4492 unsigned C = RHSC->getZExtValue(); 4493 if (!isLegalICmpImmediate((int32_t)C)) { 4494 // Constant does not fit, try adjusting it by one. 4495 switch (CC) { 4496 default: break; 4497 case ISD::SETLT: 4498 case ISD::SETGE: 4499 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4500 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4501 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4502 } 4503 break; 4504 case ISD::SETULT: 4505 case ISD::SETUGE: 4506 if (C != 0 && isLegalICmpImmediate(C-1)) { 4507 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4508 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4509 } 4510 break; 4511 case ISD::SETLE: 4512 case ISD::SETGT: 4513 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4514 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4515 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4516 } 4517 break; 4518 case ISD::SETULE: 4519 case ISD::SETUGT: 4520 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4521 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4522 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4523 } 4524 break; 4525 } 4526 } 4527 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4528 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4529 // In ARM and Thumb-2, the compare instructions can shift their second 4530 // operand. 4531 CC = ISD::getSetCCSwappedOperands(CC); 4532 std::swap(LHS, RHS); 4533 } 4534 4535 // Thumb1 has very limited immediate modes, so turning an "and" into a 4536 // shift can save multiple instructions. 4537 // 4538 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4539 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4540 // own. If it's the operand to an unsigned comparison with an immediate, 4541 // we can eliminate one of the shifts: we transform 4542 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4543 // 4544 // We avoid transforming cases which aren't profitable due to encoding 4545 // details: 4546 // 4547 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4548 // would not; in that case, we're essentially trading one immediate load for 4549 // another. 4550 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4551 // 3. C2 is zero; we have other code for this special case. 4552 // 4553 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4554 // instruction, since the AND is always one instruction anyway, but we could 4555 // use narrow instructions in some cases. 4556 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4557 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4558 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4559 !isSignedIntSetCC(CC)) { 4560 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4561 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4562 uint64_t RHSV = RHSC->getZExtValue(); 4563 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4564 unsigned ShiftBits = countLeadingZeros(Mask); 4565 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4566 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4567 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4568 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4569 } 4570 } 4571 } 4572 4573 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4574 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4575 // way a cmp would. 4576 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4577 // some tweaks to the heuristics for the previous and->shift transform. 4578 // FIXME: Optimize cases where the LHS isn't a shift. 4579 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4580 isa<ConstantSDNode>(RHS) && 4581 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4582 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4583 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4584 unsigned ShiftAmt = 4585 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4586 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4587 DAG.getVTList(MVT::i32, MVT::i32), 4588 LHS.getOperand(0), 4589 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4590 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4591 Shift.getValue(1), SDValue()); 4592 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4593 return Chain.getValue(1); 4594 } 4595 4596 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4597 4598 // If the RHS is a constant zero then the V (overflow) flag will never be 4599 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4600 // simpler for other passes (like the peephole optimiser) to deal with. 4601 if (isNullConstant(RHS)) { 4602 switch (CondCode) { 4603 default: break; 4604 case ARMCC::GE: 4605 CondCode = ARMCC::PL; 4606 break; 4607 case ARMCC::LT: 4608 CondCode = ARMCC::MI; 4609 break; 4610 } 4611 } 4612 4613 ARMISD::NodeType CompareType; 4614 switch (CondCode) { 4615 default: 4616 CompareType = ARMISD::CMP; 4617 break; 4618 case ARMCC::EQ: 4619 case ARMCC::NE: 4620 // Uses only Z Flag 4621 CompareType = ARMISD::CMPZ; 4622 break; 4623 } 4624 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4625 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4626 } 4627 4628 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4629 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4630 SelectionDAG &DAG, const SDLoc &dl, 4631 bool Signaling) const { 4632 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4633 SDValue Cmp; 4634 if (!isFloatingPointZero(RHS)) 4635 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, 4636 dl, MVT::Glue, LHS, RHS); 4637 else 4638 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, 4639 dl, MVT::Glue, LHS); 4640 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4641 } 4642 4643 /// duplicateCmp - Glue values can have only one use, so this function 4644 /// duplicates a comparison node. 4645 SDValue 4646 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4647 unsigned Opc = Cmp.getOpcode(); 4648 SDLoc DL(Cmp); 4649 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4650 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4651 4652 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4653 Cmp = Cmp.getOperand(0); 4654 Opc = Cmp.getOpcode(); 4655 if (Opc == ARMISD::CMPFP) 4656 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4657 else { 4658 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4659 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 4660 } 4661 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4662 } 4663 4664 // This function returns three things: the arithmetic computation itself 4665 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4666 // comparison and the condition code define the case in which the arithmetic 4667 // computation *does not* overflow. 4668 std::pair<SDValue, SDValue> 4669 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4670 SDValue &ARMcc) const { 4671 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4672 4673 SDValue Value, OverflowCmp; 4674 SDValue LHS = Op.getOperand(0); 4675 SDValue RHS = Op.getOperand(1); 4676 SDLoc dl(Op); 4677 4678 // FIXME: We are currently always generating CMPs because we don't support 4679 // generating CMN through the backend. This is not as good as the natural 4680 // CMP case because it causes a register dependency and cannot be folded 4681 // later. 4682 4683 switch (Op.getOpcode()) { 4684 default: 4685 llvm_unreachable("Unknown overflow instruction!"); 4686 case ISD::SADDO: 4687 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4688 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4689 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4690 break; 4691 case ISD::UADDO: 4692 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4693 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4694 // We do not use it in the USUBO case as Value may not be used. 4695 Value = DAG.getNode(ARMISD::ADDC, dl, 4696 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4697 .getValue(0); 4698 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4699 break; 4700 case ISD::SSUBO: 4701 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4702 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4703 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4704 break; 4705 case ISD::USUBO: 4706 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4707 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4708 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4709 break; 4710 case ISD::UMULO: 4711 // We generate a UMUL_LOHI and then check if the high word is 0. 4712 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4713 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4714 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4715 LHS, RHS); 4716 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4717 DAG.getConstant(0, dl, MVT::i32)); 4718 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4719 break; 4720 case ISD::SMULO: 4721 // We generate a SMUL_LOHI and then check if all the bits of the high word 4722 // are the same as the sign bit of the low word. 4723 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4724 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4725 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4726 LHS, RHS); 4727 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4728 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4729 Value.getValue(0), 4730 DAG.getConstant(31, dl, MVT::i32))); 4731 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4732 break; 4733 } // switch (...) 4734 4735 return std::make_pair(Value, OverflowCmp); 4736 } 4737 4738 SDValue 4739 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4740 // Let legalize expand this if it isn't a legal type yet. 4741 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4742 return SDValue(); 4743 4744 SDValue Value, OverflowCmp; 4745 SDValue ARMcc; 4746 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4747 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4748 SDLoc dl(Op); 4749 // We use 0 and 1 as false and true values. 4750 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4751 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4752 EVT VT = Op.getValueType(); 4753 4754 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4755 ARMcc, CCR, OverflowCmp); 4756 4757 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4758 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4759 } 4760 4761 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4762 SelectionDAG &DAG) { 4763 SDLoc DL(BoolCarry); 4764 EVT CarryVT = BoolCarry.getValueType(); 4765 4766 // This converts the boolean value carry into the carry flag by doing 4767 // ARMISD::SUBC Carry, 1 4768 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4769 DAG.getVTList(CarryVT, MVT::i32), 4770 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4771 return Carry.getValue(1); 4772 } 4773 4774 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4775 SelectionDAG &DAG) { 4776 SDLoc DL(Flags); 4777 4778 // Now convert the carry flag into a boolean carry. We do this 4779 // using ARMISD:ADDE 0, 0, Carry 4780 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4781 DAG.getConstant(0, DL, MVT::i32), 4782 DAG.getConstant(0, DL, MVT::i32), Flags); 4783 } 4784 4785 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4786 SelectionDAG &DAG) const { 4787 // Let legalize expand this if it isn't a legal type yet. 4788 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4789 return SDValue(); 4790 4791 SDValue LHS = Op.getOperand(0); 4792 SDValue RHS = Op.getOperand(1); 4793 SDLoc dl(Op); 4794 4795 EVT VT = Op.getValueType(); 4796 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4797 SDValue Value; 4798 SDValue Overflow; 4799 switch (Op.getOpcode()) { 4800 default: 4801 llvm_unreachable("Unknown overflow instruction!"); 4802 case ISD::UADDO: 4803 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4804 // Convert the carry flag into a boolean value. 4805 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4806 break; 4807 case ISD::USUBO: { 4808 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4809 // Convert the carry flag into a boolean value. 4810 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4811 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4812 // value. So compute 1 - C. 4813 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4814 DAG.getConstant(1, dl, MVT::i32), Overflow); 4815 break; 4816 } 4817 } 4818 4819 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4820 } 4821 4822 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG, 4823 const ARMSubtarget *Subtarget) { 4824 EVT VT = Op.getValueType(); 4825 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 4826 return SDValue(); 4827 if (!VT.isSimple()) 4828 return SDValue(); 4829 4830 unsigned NewOpcode; 4831 bool IsAdd = Op->getOpcode() == ISD::SADDSAT; 4832 switch (VT.getSimpleVT().SimpleTy) { 4833 default: 4834 return SDValue(); 4835 case MVT::i8: 4836 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b; 4837 break; 4838 case MVT::i16: 4839 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b; 4840 break; 4841 } 4842 4843 SDLoc dl(Op); 4844 SDValue Add = 4845 DAG.getNode(NewOpcode, dl, MVT::i32, 4846 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32), 4847 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32)); 4848 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add); 4849 } 4850 4851 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4852 SDValue Cond = Op.getOperand(0); 4853 SDValue SelectTrue = Op.getOperand(1); 4854 SDValue SelectFalse = Op.getOperand(2); 4855 SDLoc dl(Op); 4856 unsigned Opc = Cond.getOpcode(); 4857 4858 if (Cond.getResNo() == 1 && 4859 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4860 Opc == ISD::USUBO)) { 4861 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4862 return SDValue(); 4863 4864 SDValue Value, OverflowCmp; 4865 SDValue ARMcc; 4866 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4867 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4868 EVT VT = Op.getValueType(); 4869 4870 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4871 OverflowCmp, DAG); 4872 } 4873 4874 // Convert: 4875 // 4876 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4877 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4878 // 4879 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4880 const ConstantSDNode *CMOVTrue = 4881 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4882 const ConstantSDNode *CMOVFalse = 4883 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4884 4885 if (CMOVTrue && CMOVFalse) { 4886 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4887 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4888 4889 SDValue True; 4890 SDValue False; 4891 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4892 True = SelectTrue; 4893 False = SelectFalse; 4894 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4895 True = SelectFalse; 4896 False = SelectTrue; 4897 } 4898 4899 if (True.getNode() && False.getNode()) { 4900 EVT VT = Op.getValueType(); 4901 SDValue ARMcc = Cond.getOperand(2); 4902 SDValue CCR = Cond.getOperand(3); 4903 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4904 assert(True.getValueType() == VT); 4905 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4906 } 4907 } 4908 } 4909 4910 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4911 // undefined bits before doing a full-word comparison with zero. 4912 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4913 DAG.getConstant(1, dl, Cond.getValueType())); 4914 4915 return DAG.getSelectCC(dl, Cond, 4916 DAG.getConstant(0, dl, Cond.getValueType()), 4917 SelectTrue, SelectFalse, ISD::SETNE); 4918 } 4919 4920 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4921 bool &swpCmpOps, bool &swpVselOps) { 4922 // Start by selecting the GE condition code for opcodes that return true for 4923 // 'equality' 4924 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4925 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4926 CondCode = ARMCC::GE; 4927 4928 // and GT for opcodes that return false for 'equality'. 4929 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4930 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4931 CondCode = ARMCC::GT; 4932 4933 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4934 // to swap the compare operands. 4935 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4936 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4937 swpCmpOps = true; 4938 4939 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4940 // If we have an unordered opcode, we need to swap the operands to the VSEL 4941 // instruction (effectively negating the condition). 4942 // 4943 // This also has the effect of swapping which one of 'less' or 'greater' 4944 // returns true, so we also swap the compare operands. It also switches 4945 // whether we return true for 'equality', so we compensate by picking the 4946 // opposite condition code to our original choice. 4947 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4948 CC == ISD::SETUGT) { 4949 swpCmpOps = !swpCmpOps; 4950 swpVselOps = !swpVselOps; 4951 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4952 } 4953 4954 // 'ordered' is 'anything but unordered', so use the VS condition code and 4955 // swap the VSEL operands. 4956 if (CC == ISD::SETO) { 4957 CondCode = ARMCC::VS; 4958 swpVselOps = true; 4959 } 4960 4961 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4962 // code and swap the VSEL operands. Also do this if we don't care about the 4963 // unordered case. 4964 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4965 CondCode = ARMCC::EQ; 4966 swpVselOps = true; 4967 } 4968 } 4969 4970 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4971 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4972 SDValue Cmp, SelectionDAG &DAG) const { 4973 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4974 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4975 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4976 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4977 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4978 4979 SDValue TrueLow = TrueVal.getValue(0); 4980 SDValue TrueHigh = TrueVal.getValue(1); 4981 SDValue FalseLow = FalseVal.getValue(0); 4982 SDValue FalseHigh = FalseVal.getValue(1); 4983 4984 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4985 ARMcc, CCR, Cmp); 4986 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4987 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4988 4989 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4990 } else { 4991 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4992 Cmp); 4993 } 4994 } 4995 4996 static bool isGTorGE(ISD::CondCode CC) { 4997 return CC == ISD::SETGT || CC == ISD::SETGE; 4998 } 4999 5000 static bool isLTorLE(ISD::CondCode CC) { 5001 return CC == ISD::SETLT || CC == ISD::SETLE; 5002 } 5003 5004 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 5005 // All of these conditions (and their <= and >= counterparts) will do: 5006 // x < k ? k : x 5007 // x > k ? x : k 5008 // k < x ? x : k 5009 // k > x ? k : x 5010 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 5011 const SDValue TrueVal, const SDValue FalseVal, 5012 const ISD::CondCode CC, const SDValue K) { 5013 return (isGTorGE(CC) && 5014 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 5015 (isLTorLE(CC) && 5016 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 5017 } 5018 5019 // Check if two chained conditionals could be converted into SSAT or USAT. 5020 // 5021 // SSAT can replace a set of two conditional selectors that bound a number to an 5022 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 5023 // 5024 // x < -k ? -k : (x > k ? k : x) 5025 // x < -k ? -k : (x < k ? x : k) 5026 // x > -k ? (x > k ? k : x) : -k 5027 // x < k ? (x < -k ? -k : x) : k 5028 // etc. 5029 // 5030 // LLVM canonicalizes these to either a min(max()) or a max(min()) 5031 // pattern. This function tries to match one of these and will return a SSAT 5032 // node if successful. 5033 // 5034 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 5035 // is a power of 2. 5036 static SDValue LowerSaturatingConditional(SDValue Op, SelectionDAG &DAG) { 5037 EVT VT = Op.getValueType(); 5038 SDValue V1 = Op.getOperand(0); 5039 SDValue K1 = Op.getOperand(1); 5040 SDValue TrueVal1 = Op.getOperand(2); 5041 SDValue FalseVal1 = Op.getOperand(3); 5042 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5043 5044 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 5045 if (Op2.getOpcode() != ISD::SELECT_CC) 5046 return SDValue(); 5047 5048 SDValue V2 = Op2.getOperand(0); 5049 SDValue K2 = Op2.getOperand(1); 5050 SDValue TrueVal2 = Op2.getOperand(2); 5051 SDValue FalseVal2 = Op2.getOperand(3); 5052 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 5053 5054 SDValue V1Tmp = V1; 5055 SDValue V2Tmp = V2; 5056 5057 // Check that the registers and the constants match a max(min()) or min(max()) 5058 // pattern 5059 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 || 5060 K2 != FalseVal2 || 5061 !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2)))) 5062 return SDValue(); 5063 5064 // Check that the constant in the lower-bound check is 5065 // the opposite of the constant in the upper-bound check 5066 // in 1's complement. 5067 if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2)) 5068 return SDValue(); 5069 5070 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue(); 5071 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue(); 5072 int64_t PosVal = std::max(Val1, Val2); 5073 int64_t NegVal = std::min(Val1, Val2); 5074 5075 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) || 5076 !isPowerOf2_64(PosVal + 1)) 5077 return SDValue(); 5078 5079 // Handle the difference between USAT (unsigned) and SSAT (signed) 5080 // saturation 5081 // At this point, PosVal is guaranteed to be positive 5082 uint64_t K = PosVal; 5083 SDLoc dl(Op); 5084 if (Val1 == ~Val2) 5085 return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp, 5086 DAG.getConstant(countTrailingOnes(K), dl, VT)); 5087 if (NegVal == 0) 5088 return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp, 5089 DAG.getConstant(countTrailingOnes(K), dl, VT)); 5090 5091 return SDValue(); 5092 } 5093 5094 // Check if a condition of the type x < k ? k : x can be converted into a 5095 // bit operation instead of conditional moves. 5096 // Currently this is allowed given: 5097 // - The conditions and values match up 5098 // - k is 0 or -1 (all ones) 5099 // This function will not check the last condition, thats up to the caller 5100 // It returns true if the transformation can be made, and in such case 5101 // returns x in V, and k in SatK. 5102 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 5103 SDValue &SatK) 5104 { 5105 SDValue LHS = Op.getOperand(0); 5106 SDValue RHS = Op.getOperand(1); 5107 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5108 SDValue TrueVal = Op.getOperand(2); 5109 SDValue FalseVal = Op.getOperand(3); 5110 5111 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 5112 ? &RHS 5113 : nullptr; 5114 5115 // No constant operation in comparison, early out 5116 if (!K) 5117 return false; 5118 5119 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 5120 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 5121 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 5122 5123 // If the constant on left and right side, or variable on left and right, 5124 // does not match, early out 5125 if (*K != KTmp || V != VTmp) 5126 return false; 5127 5128 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 5129 SatK = *K; 5130 return true; 5131 } 5132 5133 return false; 5134 } 5135 5136 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 5137 if (VT == MVT::f32) 5138 return !Subtarget->hasVFP2Base(); 5139 if (VT == MVT::f64) 5140 return !Subtarget->hasFP64(); 5141 if (VT == MVT::f16) 5142 return !Subtarget->hasFullFP16(); 5143 return false; 5144 } 5145 5146 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 5147 EVT VT = Op.getValueType(); 5148 SDLoc dl(Op); 5149 5150 // Try to convert two saturating conditional selects into a single SSAT 5151 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) 5152 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG)) 5153 return SatValue; 5154 5155 // Try to convert expressions of the form x < k ? k : x (and similar forms) 5156 // into more efficient bit operations, which is possible when k is 0 or -1 5157 // On ARM and Thumb-2 which have flexible operand 2 this will result in 5158 // single instructions. On Thumb the shift and the bit operation will be two 5159 // instructions. 5160 // Only allow this transformation on full-width (32-bit) operations 5161 SDValue LowerSatConstant; 5162 SDValue SatValue; 5163 if (VT == MVT::i32 && 5164 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 5165 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 5166 DAG.getConstant(31, dl, VT)); 5167 if (isNullConstant(LowerSatConstant)) { 5168 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 5169 DAG.getAllOnesConstant(dl, VT)); 5170 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 5171 } else if (isAllOnesConstant(LowerSatConstant)) 5172 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 5173 } 5174 5175 SDValue LHS = Op.getOperand(0); 5176 SDValue RHS = Op.getOperand(1); 5177 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5178 SDValue TrueVal = Op.getOperand(2); 5179 SDValue FalseVal = Op.getOperand(3); 5180 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal); 5181 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal); 5182 5183 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal && 5184 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) { 5185 unsigned TVal = CTVal->getZExtValue(); 5186 unsigned FVal = CFVal->getZExtValue(); 5187 unsigned Opcode = 0; 5188 5189 if (TVal == ~FVal) { 5190 Opcode = ARMISD::CSINV; 5191 } else if (TVal == ~FVal + 1) { 5192 Opcode = ARMISD::CSNEG; 5193 } else if (TVal + 1 == FVal) { 5194 Opcode = ARMISD::CSINC; 5195 } else if (TVal == FVal + 1) { 5196 Opcode = ARMISD::CSINC; 5197 std::swap(TrueVal, FalseVal); 5198 std::swap(TVal, FVal); 5199 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5200 } 5201 5202 if (Opcode) { 5203 // If one of the constants is cheaper than another, materialise the 5204 // cheaper one and let the csel generate the other. 5205 if (Opcode != ARMISD::CSINC && 5206 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) { 5207 std::swap(TrueVal, FalseVal); 5208 std::swap(TVal, FVal); 5209 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5210 } 5211 5212 // Attempt to use ZR checking TVal is 0, possibly inverting the condition 5213 // to get there. CSINC not is invertable like the other two (~(~a) == a, 5214 // -(-a) == a, but (a+1)+1 != a). 5215 if (FVal == 0 && Opcode != ARMISD::CSINC) { 5216 std::swap(TrueVal, FalseVal); 5217 std::swap(TVal, FVal); 5218 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5219 } 5220 5221 // Drops F's value because we can get it by inverting/negating TVal. 5222 FalseVal = TrueVal; 5223 5224 SDValue ARMcc; 5225 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5226 EVT VT = TrueVal.getValueType(); 5227 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp); 5228 } 5229 } 5230 5231 if (isUnsupportedFloatingType(LHS.getValueType())) { 5232 DAG.getTargetLoweringInfo().softenSetCCOperands( 5233 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5234 5235 // If softenSetCCOperands only returned one value, we should compare it to 5236 // zero. 5237 if (!RHS.getNode()) { 5238 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5239 CC = ISD::SETNE; 5240 } 5241 } 5242 5243 if (LHS.getValueType() == MVT::i32) { 5244 // Try to generate VSEL on ARMv8. 5245 // The VSEL instruction can't use all the usual ARM condition 5246 // codes: it only has two bits to select the condition code, so it's 5247 // constrained to use only GE, GT, VS and EQ. 5248 // 5249 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 5250 // swap the operands of the previous compare instruction (effectively 5251 // inverting the compare condition, swapping 'less' and 'greater') and 5252 // sometimes need to swap the operands to the VSEL (which inverts the 5253 // condition in the sense of firing whenever the previous condition didn't) 5254 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 5255 TrueVal.getValueType() == MVT::f32 || 5256 TrueVal.getValueType() == MVT::f64)) { 5257 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5258 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 5259 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 5260 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5261 std::swap(TrueVal, FalseVal); 5262 } 5263 } 5264 5265 SDValue ARMcc; 5266 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5267 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5268 // Choose GE over PL, which vsel does now support 5269 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 5270 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 5271 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5272 } 5273 5274 ARMCC::CondCodes CondCode, CondCode2; 5275 FPCCToARMCC(CC, CondCode, CondCode2); 5276 5277 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 5278 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 5279 // must use VSEL (limited condition codes), due to not having conditional f16 5280 // moves. 5281 if (Subtarget->hasFPARMv8Base() && 5282 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 5283 (TrueVal.getValueType() == MVT::f16 || 5284 TrueVal.getValueType() == MVT::f32 || 5285 TrueVal.getValueType() == MVT::f64)) { 5286 bool swpCmpOps = false; 5287 bool swpVselOps = false; 5288 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 5289 5290 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 5291 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 5292 if (swpCmpOps) 5293 std::swap(LHS, RHS); 5294 if (swpVselOps) 5295 std::swap(TrueVal, FalseVal); 5296 } 5297 } 5298 5299 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5300 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5301 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5302 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5303 if (CondCode2 != ARMCC::AL) { 5304 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 5305 // FIXME: Needs another CMP because flag can have but one use. 5306 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 5307 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 5308 } 5309 return Result; 5310 } 5311 5312 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 5313 /// to morph to an integer compare sequence. 5314 static bool canChangeToInt(SDValue Op, bool &SeenZero, 5315 const ARMSubtarget *Subtarget) { 5316 SDNode *N = Op.getNode(); 5317 if (!N->hasOneUse()) 5318 // Otherwise it requires moving the value from fp to integer registers. 5319 return false; 5320 if (!N->getNumValues()) 5321 return false; 5322 EVT VT = Op.getValueType(); 5323 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 5324 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 5325 // vmrs are very slow, e.g. cortex-a8. 5326 return false; 5327 5328 if (isFloatingPointZero(Op)) { 5329 SeenZero = true; 5330 return true; 5331 } 5332 return ISD::isNormalLoad(N); 5333 } 5334 5335 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 5336 if (isFloatingPointZero(Op)) 5337 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 5338 5339 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 5340 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 5341 Ld->getPointerInfo(), Ld->getAlignment(), 5342 Ld->getMemOperand()->getFlags()); 5343 5344 llvm_unreachable("Unknown VFP cmp argument!"); 5345 } 5346 5347 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 5348 SDValue &RetVal1, SDValue &RetVal2) { 5349 SDLoc dl(Op); 5350 5351 if (isFloatingPointZero(Op)) { 5352 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 5353 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 5354 return; 5355 } 5356 5357 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 5358 SDValue Ptr = Ld->getBasePtr(); 5359 RetVal1 = 5360 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 5361 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 5362 5363 EVT PtrType = Ptr.getValueType(); 5364 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 5365 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 5366 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 5367 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 5368 Ld->getPointerInfo().getWithOffset(4), NewAlign, 5369 Ld->getMemOperand()->getFlags()); 5370 return; 5371 } 5372 5373 llvm_unreachable("Unknown VFP cmp argument!"); 5374 } 5375 5376 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 5377 /// f32 and even f64 comparisons to integer ones. 5378 SDValue 5379 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 5380 SDValue Chain = Op.getOperand(0); 5381 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5382 SDValue LHS = Op.getOperand(2); 5383 SDValue RHS = Op.getOperand(3); 5384 SDValue Dest = Op.getOperand(4); 5385 SDLoc dl(Op); 5386 5387 bool LHSSeenZero = false; 5388 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 5389 bool RHSSeenZero = false; 5390 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 5391 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 5392 // If unsafe fp math optimization is enabled and there are no other uses of 5393 // the CMP operands, and the condition code is EQ or NE, we can optimize it 5394 // to an integer comparison. 5395 if (CC == ISD::SETOEQ) 5396 CC = ISD::SETEQ; 5397 else if (CC == ISD::SETUNE) 5398 CC = ISD::SETNE; 5399 5400 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5401 SDValue ARMcc; 5402 if (LHS.getValueType() == MVT::f32) { 5403 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5404 bitcastf32Toi32(LHS, DAG), Mask); 5405 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5406 bitcastf32Toi32(RHS, DAG), Mask); 5407 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5408 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5409 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5410 Chain, Dest, ARMcc, CCR, Cmp); 5411 } 5412 5413 SDValue LHS1, LHS2; 5414 SDValue RHS1, RHS2; 5415 expandf64Toi32(LHS, DAG, LHS1, LHS2); 5416 expandf64Toi32(RHS, DAG, RHS1, RHS2); 5417 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 5418 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 5419 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5420 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5421 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5422 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 5423 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 5424 } 5425 5426 return SDValue(); 5427 } 5428 5429 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 5430 SDValue Chain = Op.getOperand(0); 5431 SDValue Cond = Op.getOperand(1); 5432 SDValue Dest = Op.getOperand(2); 5433 SDLoc dl(Op); 5434 5435 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5436 // instruction. 5437 unsigned Opc = Cond.getOpcode(); 5438 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5439 !Subtarget->isThumb1Only(); 5440 if (Cond.getResNo() == 1 && 5441 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5442 Opc == ISD::USUBO || OptimizeMul)) { 5443 // Only lower legal XALUO ops. 5444 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 5445 return SDValue(); 5446 5447 // The actual operation with overflow check. 5448 SDValue Value, OverflowCmp; 5449 SDValue ARMcc; 5450 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 5451 5452 // Reverse the condition code. 5453 ARMCC::CondCodes CondCode = 5454 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5455 CondCode = ARMCC::getOppositeCondition(CondCode); 5456 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5457 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5458 5459 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5460 OverflowCmp); 5461 } 5462 5463 return SDValue(); 5464 } 5465 5466 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5467 SDValue Chain = Op.getOperand(0); 5468 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5469 SDValue LHS = Op.getOperand(2); 5470 SDValue RHS = Op.getOperand(3); 5471 SDValue Dest = Op.getOperand(4); 5472 SDLoc dl(Op); 5473 5474 if (isUnsupportedFloatingType(LHS.getValueType())) { 5475 DAG.getTargetLoweringInfo().softenSetCCOperands( 5476 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5477 5478 // If softenSetCCOperands only returned one value, we should compare it to 5479 // zero. 5480 if (!RHS.getNode()) { 5481 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5482 CC = ISD::SETNE; 5483 } 5484 } 5485 5486 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5487 // instruction. 5488 unsigned Opc = LHS.getOpcode(); 5489 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5490 !Subtarget->isThumb1Only(); 5491 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5492 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5493 Opc == ISD::USUBO || OptimizeMul) && 5494 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5495 // Only lower legal XALUO ops. 5496 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5497 return SDValue(); 5498 5499 // The actual operation with overflow check. 5500 SDValue Value, OverflowCmp; 5501 SDValue ARMcc; 5502 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5503 5504 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5505 // Reverse the condition code. 5506 ARMCC::CondCodes CondCode = 5507 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5508 CondCode = ARMCC::getOppositeCondition(CondCode); 5509 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5510 } 5511 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5512 5513 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5514 OverflowCmp); 5515 } 5516 5517 if (LHS.getValueType() == MVT::i32) { 5518 SDValue ARMcc; 5519 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5520 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5521 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5522 Chain, Dest, ARMcc, CCR, Cmp); 5523 } 5524 5525 if (getTargetMachine().Options.UnsafeFPMath && 5526 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5527 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5528 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5529 return Result; 5530 } 5531 5532 ARMCC::CondCodes CondCode, CondCode2; 5533 FPCCToARMCC(CC, CondCode, CondCode2); 5534 5535 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5536 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5537 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5538 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5539 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5540 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5541 if (CondCode2 != ARMCC::AL) { 5542 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5543 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5544 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5545 } 5546 return Res; 5547 } 5548 5549 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5550 SDValue Chain = Op.getOperand(0); 5551 SDValue Table = Op.getOperand(1); 5552 SDValue Index = Op.getOperand(2); 5553 SDLoc dl(Op); 5554 5555 EVT PTy = getPointerTy(DAG.getDataLayout()); 5556 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5557 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5558 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5559 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5560 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5561 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5562 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5563 // which does another jump to the destination. This also makes it easier 5564 // to translate it to TBB / TBH later (Thumb2 only). 5565 // FIXME: This might not work if the function is extremely large. 5566 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5567 Addr, Op.getOperand(2), JTI); 5568 } 5569 if (isPositionIndependent() || Subtarget->isROPI()) { 5570 Addr = 5571 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5572 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5573 Chain = Addr.getValue(1); 5574 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5575 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5576 } else { 5577 Addr = 5578 DAG.getLoad(PTy, dl, Chain, Addr, 5579 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5580 Chain = Addr.getValue(1); 5581 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5582 } 5583 } 5584 5585 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5586 EVT VT = Op.getValueType(); 5587 SDLoc dl(Op); 5588 5589 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5590 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5591 return Op; 5592 return DAG.UnrollVectorOp(Op.getNode()); 5593 } 5594 5595 const bool HasFullFP16 = 5596 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5597 5598 EVT NewTy; 5599 const EVT OpTy = Op.getOperand(0).getValueType(); 5600 if (OpTy == MVT::v4f32) 5601 NewTy = MVT::v4i32; 5602 else if (OpTy == MVT::v4f16 && HasFullFP16) 5603 NewTy = MVT::v4i16; 5604 else if (OpTy == MVT::v8f16 && HasFullFP16) 5605 NewTy = MVT::v8i16; 5606 else 5607 llvm_unreachable("Invalid type for custom lowering!"); 5608 5609 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5610 return DAG.UnrollVectorOp(Op.getNode()); 5611 5612 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5613 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5614 } 5615 5616 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5617 EVT VT = Op.getValueType(); 5618 if (VT.isVector()) 5619 return LowerVectorFP_TO_INT(Op, DAG); 5620 5621 bool IsStrict = Op->isStrictFPOpcode(); 5622 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 5623 5624 if (isUnsupportedFloatingType(SrcVal.getValueType())) { 5625 RTLIB::Libcall LC; 5626 if (Op.getOpcode() == ISD::FP_TO_SINT || 5627 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 5628 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), 5629 Op.getValueType()); 5630 else 5631 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), 5632 Op.getValueType()); 5633 SDLoc Loc(Op); 5634 MakeLibCallOptions CallOptions; 5635 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 5636 SDValue Result; 5637 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 5638 CallOptions, Loc, Chain); 5639 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 5640 } 5641 5642 // FIXME: Remove this when we have strict fp instruction selection patterns 5643 if (IsStrict) { 5644 SDLoc Loc(Op); 5645 SDValue Result = 5646 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT 5647 : ISD::FP_TO_UINT, 5648 Loc, Op.getValueType(), SrcVal); 5649 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 5650 } 5651 5652 return Op; 5653 } 5654 5655 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5656 EVT VT = Op.getValueType(); 5657 SDLoc dl(Op); 5658 5659 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5660 if (VT.getVectorElementType() == MVT::f32) 5661 return Op; 5662 return DAG.UnrollVectorOp(Op.getNode()); 5663 } 5664 5665 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5666 Op.getOperand(0).getValueType() == MVT::v8i16) && 5667 "Invalid type for custom lowering!"); 5668 5669 const bool HasFullFP16 = 5670 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5671 5672 EVT DestVecType; 5673 if (VT == MVT::v4f32) 5674 DestVecType = MVT::v4i32; 5675 else if (VT == MVT::v4f16 && HasFullFP16) 5676 DestVecType = MVT::v4i16; 5677 else if (VT == MVT::v8f16 && HasFullFP16) 5678 DestVecType = MVT::v8i16; 5679 else 5680 return DAG.UnrollVectorOp(Op.getNode()); 5681 5682 unsigned CastOpc; 5683 unsigned Opc; 5684 switch (Op.getOpcode()) { 5685 default: llvm_unreachable("Invalid opcode!"); 5686 case ISD::SINT_TO_FP: 5687 CastOpc = ISD::SIGN_EXTEND; 5688 Opc = ISD::SINT_TO_FP; 5689 break; 5690 case ISD::UINT_TO_FP: 5691 CastOpc = ISD::ZERO_EXTEND; 5692 Opc = ISD::UINT_TO_FP; 5693 break; 5694 } 5695 5696 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5697 return DAG.getNode(Opc, dl, VT, Op); 5698 } 5699 5700 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5701 EVT VT = Op.getValueType(); 5702 if (VT.isVector()) 5703 return LowerVectorINT_TO_FP(Op, DAG); 5704 if (isUnsupportedFloatingType(VT)) { 5705 RTLIB::Libcall LC; 5706 if (Op.getOpcode() == ISD::SINT_TO_FP) 5707 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5708 Op.getValueType()); 5709 else 5710 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5711 Op.getValueType()); 5712 MakeLibCallOptions CallOptions; 5713 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5714 CallOptions, SDLoc(Op)).first; 5715 } 5716 5717 return Op; 5718 } 5719 5720 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5721 // Implement fcopysign with a fabs and a conditional fneg. 5722 SDValue Tmp0 = Op.getOperand(0); 5723 SDValue Tmp1 = Op.getOperand(1); 5724 SDLoc dl(Op); 5725 EVT VT = Op.getValueType(); 5726 EVT SrcVT = Tmp1.getValueType(); 5727 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5728 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5729 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5730 5731 if (UseNEON) { 5732 // Use VBSL to copy the sign bit. 5733 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5734 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5735 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5736 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5737 if (VT == MVT::f64) 5738 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5739 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5740 DAG.getConstant(32, dl, MVT::i32)); 5741 else /*if (VT == MVT::f32)*/ 5742 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5743 if (SrcVT == MVT::f32) { 5744 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5745 if (VT == MVT::f64) 5746 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5747 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5748 DAG.getConstant(32, dl, MVT::i32)); 5749 } else if (VT == MVT::f32) 5750 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5751 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5752 DAG.getConstant(32, dl, MVT::i32)); 5753 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5754 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5755 5756 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5757 dl, MVT::i32); 5758 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5759 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5760 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5761 5762 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5763 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5764 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5765 if (VT == MVT::f32) { 5766 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5767 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5768 DAG.getConstant(0, dl, MVT::i32)); 5769 } else { 5770 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5771 } 5772 5773 return Res; 5774 } 5775 5776 // Bitcast operand 1 to i32. 5777 if (SrcVT == MVT::f64) 5778 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5779 Tmp1).getValue(1); 5780 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5781 5782 // Or in the signbit with integer operations. 5783 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5784 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5785 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5786 if (VT == MVT::f32) { 5787 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5788 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5789 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5790 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5791 } 5792 5793 // f64: Or the high part with signbit and then combine two parts. 5794 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5795 Tmp0); 5796 SDValue Lo = Tmp0.getValue(0); 5797 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5798 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5799 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5800 } 5801 5802 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5803 MachineFunction &MF = DAG.getMachineFunction(); 5804 MachineFrameInfo &MFI = MF.getFrameInfo(); 5805 MFI.setReturnAddressIsTaken(true); 5806 5807 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5808 return SDValue(); 5809 5810 EVT VT = Op.getValueType(); 5811 SDLoc dl(Op); 5812 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5813 if (Depth) { 5814 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5815 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5816 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5817 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5818 MachinePointerInfo()); 5819 } 5820 5821 // Return LR, which contains the return address. Mark it an implicit live-in. 5822 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5823 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5824 } 5825 5826 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5827 const ARMBaseRegisterInfo &ARI = 5828 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5829 MachineFunction &MF = DAG.getMachineFunction(); 5830 MachineFrameInfo &MFI = MF.getFrameInfo(); 5831 MFI.setFrameAddressIsTaken(true); 5832 5833 EVT VT = Op.getValueType(); 5834 SDLoc dl(Op); // FIXME probably not meaningful 5835 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5836 Register FrameReg = ARI.getFrameRegister(MF); 5837 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5838 while (Depth--) 5839 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5840 MachinePointerInfo()); 5841 return FrameAddr; 5842 } 5843 5844 // FIXME? Maybe this could be a TableGen attribute on some registers and 5845 // this table could be generated automatically from RegInfo. 5846 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT, 5847 const MachineFunction &MF) const { 5848 Register Reg = StringSwitch<unsigned>(RegName) 5849 .Case("sp", ARM::SP) 5850 .Default(0); 5851 if (Reg) 5852 return Reg; 5853 report_fatal_error(Twine("Invalid register name \"" 5854 + StringRef(RegName) + "\".")); 5855 } 5856 5857 // Result is 64 bit value so split into two 32 bit values and return as a 5858 // pair of values. 5859 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5860 SelectionDAG &DAG) { 5861 SDLoc DL(N); 5862 5863 // This function is only supposed to be called for i64 type destination. 5864 assert(N->getValueType(0) == MVT::i64 5865 && "ExpandREAD_REGISTER called for non-i64 type result."); 5866 5867 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5868 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5869 N->getOperand(0), 5870 N->getOperand(1)); 5871 5872 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5873 Read.getValue(1))); 5874 Results.push_back(Read.getOperand(0)); 5875 } 5876 5877 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5878 /// When \p DstVT, the destination type of \p BC, is on the vector 5879 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5880 /// it might be possible to combine them, such that everything stays on the 5881 /// vector register bank. 5882 /// \p return The node that would replace \p BT, if the combine 5883 /// is possible. 5884 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5885 SelectionDAG &DAG) { 5886 SDValue Op = BC->getOperand(0); 5887 EVT DstVT = BC->getValueType(0); 5888 5889 // The only vector instruction that can produce a scalar (remember, 5890 // since the bitcast was about to be turned into VMOVDRR, the source 5891 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5892 // Moreover, we can do this combine only if there is one use. 5893 // Finally, if the destination type is not a vector, there is not 5894 // much point on forcing everything on the vector bank. 5895 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5896 !Op.hasOneUse()) 5897 return SDValue(); 5898 5899 // If the index is not constant, we will introduce an additional 5900 // multiply that will stick. 5901 // Give up in that case. 5902 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5903 if (!Index) 5904 return SDValue(); 5905 unsigned DstNumElt = DstVT.getVectorNumElements(); 5906 5907 // Compute the new index. 5908 const APInt &APIntIndex = Index->getAPIntValue(); 5909 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5910 NewIndex *= APIntIndex; 5911 // Check if the new constant index fits into i32. 5912 if (NewIndex.getBitWidth() > 32) 5913 return SDValue(); 5914 5915 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5916 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5917 SDLoc dl(Op); 5918 SDValue ExtractSrc = Op.getOperand(0); 5919 EVT VecVT = EVT::getVectorVT( 5920 *DAG.getContext(), DstVT.getScalarType(), 5921 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5922 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5923 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5924 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5925 } 5926 5927 /// ExpandBITCAST - If the target supports VFP, this function is called to 5928 /// expand a bit convert where either the source or destination type is i64 to 5929 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5930 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5931 /// vectors), since the legalizer won't know what to do with that. 5932 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5933 const ARMSubtarget *Subtarget) const { 5934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5935 SDLoc dl(N); 5936 SDValue Op = N->getOperand(0); 5937 5938 // This function is only supposed to be called for i16 and i64 types, either 5939 // as the source or destination of the bit convert. 5940 EVT SrcVT = Op.getValueType(); 5941 EVT DstVT = N->getValueType(0); 5942 5943 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) && 5944 (DstVT == MVT::f16 || DstVT == MVT::bf16)) 5945 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(), 5946 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op)); 5947 5948 if ((DstVT == MVT::i16 || DstVT == MVT::i32) && 5949 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) 5950 return DAG.getNode( 5951 ISD::TRUNCATE, SDLoc(N), DstVT, 5952 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op)); 5953 5954 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5955 return SDValue(); 5956 5957 // Turn i64->f64 into VMOVDRR. 5958 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5959 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5960 // if we can combine the bitcast with its source. 5961 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5962 return Val; 5963 5964 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5965 DAG.getConstant(0, dl, MVT::i32)); 5966 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5967 DAG.getConstant(1, dl, MVT::i32)); 5968 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5969 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5970 } 5971 5972 // Turn f64->i64 into VMOVRRD. 5973 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5974 SDValue Cvt; 5975 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5976 SrcVT.getVectorNumElements() > 1) 5977 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5978 DAG.getVTList(MVT::i32, MVT::i32), 5979 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5980 else 5981 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5982 DAG.getVTList(MVT::i32, MVT::i32), Op); 5983 // Merge the pieces into a single i64 value. 5984 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5985 } 5986 5987 return SDValue(); 5988 } 5989 5990 /// getZeroVector - Returns a vector of specified type with all zero elements. 5991 /// Zero vectors are used to represent vector negation and in those cases 5992 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5993 /// not support i64 elements, so sometimes the zero vectors will need to be 5994 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5995 /// zero vector. 5996 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5997 assert(VT.isVector() && "Expected a vector type"); 5998 // The canonical modified immediate encoding of a zero vector is....0! 5999 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 6000 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 6001 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 6002 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6003 } 6004 6005 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 6006 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6007 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 6008 SelectionDAG &DAG) const { 6009 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6010 EVT VT = Op.getValueType(); 6011 unsigned VTBits = VT.getSizeInBits(); 6012 SDLoc dl(Op); 6013 SDValue ShOpLo = Op.getOperand(0); 6014 SDValue ShOpHi = Op.getOperand(1); 6015 SDValue ShAmt = Op.getOperand(2); 6016 SDValue ARMcc; 6017 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6018 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 6019 6020 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 6021 6022 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6023 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6024 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 6025 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6026 DAG.getConstant(VTBits, dl, MVT::i32)); 6027 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 6028 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6029 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 6030 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6031 ISD::SETGE, ARMcc, DAG, dl); 6032 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 6033 ARMcc, CCR, CmpLo); 6034 6035 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 6036 SDValue HiBigShift = Opc == ISD::SRA 6037 ? DAG.getNode(Opc, dl, VT, ShOpHi, 6038 DAG.getConstant(VTBits - 1, dl, VT)) 6039 : DAG.getConstant(0, dl, VT); 6040 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6041 ISD::SETGE, ARMcc, DAG, dl); 6042 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6043 ARMcc, CCR, CmpHi); 6044 6045 SDValue Ops[2] = { Lo, Hi }; 6046 return DAG.getMergeValues(Ops, dl); 6047 } 6048 6049 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 6050 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6051 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 6052 SelectionDAG &DAG) const { 6053 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6054 EVT VT = Op.getValueType(); 6055 unsigned VTBits = VT.getSizeInBits(); 6056 SDLoc dl(Op); 6057 SDValue ShOpLo = Op.getOperand(0); 6058 SDValue ShOpHi = Op.getOperand(1); 6059 SDValue ShAmt = Op.getOperand(2); 6060 SDValue ARMcc; 6061 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6062 6063 assert(Op.getOpcode() == ISD::SHL_PARTS); 6064 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6065 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6066 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 6067 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 6068 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6069 6070 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6071 DAG.getConstant(VTBits, dl, MVT::i32)); 6072 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 6073 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6074 ISD::SETGE, ARMcc, DAG, dl); 6075 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6076 ARMcc, CCR, CmpHi); 6077 6078 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6079 ISD::SETGE, ARMcc, DAG, dl); 6080 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6081 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 6082 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 6083 6084 SDValue Ops[2] = { Lo, Hi }; 6085 return DAG.getMergeValues(Ops, dl); 6086 } 6087 6088 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 6089 SelectionDAG &DAG) const { 6090 // The rounding mode is in bits 23:22 of the FPSCR. 6091 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 6092 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 6093 // so that the shift + and get folded into a bitfield extract. 6094 SDLoc dl(Op); 6095 SDValue Chain = Op.getOperand(0); 6096 SDValue Ops[] = {Chain, 6097 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)}; 6098 6099 SDValue FPSCR = 6100 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops); 6101 Chain = FPSCR.getValue(1); 6102 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 6103 DAG.getConstant(1U << 22, dl, MVT::i32)); 6104 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 6105 DAG.getConstant(22, dl, MVT::i32)); 6106 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 6107 DAG.getConstant(3, dl, MVT::i32)); 6108 return DAG.getMergeValues({And, Chain}, dl); 6109 } 6110 6111 SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op, 6112 SelectionDAG &DAG) const { 6113 SDLoc DL(Op); 6114 SDValue Chain = Op->getOperand(0); 6115 SDValue RMValue = Op->getOperand(1); 6116 6117 // The rounding mode is in bits 23:22 of the FPSCR. 6118 // The llvm.set.rounding argument value to ARM rounding mode value mapping 6119 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is 6120 // ((arg - 1) & 3) << 22). 6121 // 6122 // It is expected that the argument of llvm.set.rounding is within the 6123 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is 6124 // responsibility of the code generated llvm.set.rounding to ensure this 6125 // condition. 6126 6127 // Calculate new value of FPSCR[23:22]. 6128 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue, 6129 DAG.getConstant(1, DL, MVT::i32)); 6130 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue, 6131 DAG.getConstant(0x3, DL, MVT::i32)); 6132 RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue, 6133 DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32)); 6134 6135 // Get current value of FPSCR. 6136 SDValue Ops[] = {Chain, 6137 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)}; 6138 SDValue FPSCR = 6139 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops); 6140 Chain = FPSCR.getValue(1); 6141 FPSCR = FPSCR.getValue(0); 6142 6143 // Put new rounding mode into FPSCR[23:22]. 6144 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos); 6145 FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR, 6146 DAG.getConstant(RMMask, DL, MVT::i32)); 6147 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue); 6148 SDValue Ops2[] = { 6149 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR}; 6150 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2); 6151 } 6152 6153 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 6154 const ARMSubtarget *ST) { 6155 SDLoc dl(N); 6156 EVT VT = N->getValueType(0); 6157 if (VT.isVector() && ST->hasNEON()) { 6158 6159 // Compute the least significant set bit: LSB = X & -X 6160 SDValue X = N->getOperand(0); 6161 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 6162 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 6163 6164 EVT ElemTy = VT.getVectorElementType(); 6165 6166 if (ElemTy == MVT::i8) { 6167 // Compute with: cttz(x) = ctpop(lsb - 1) 6168 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6169 DAG.getTargetConstant(1, dl, ElemTy)); 6170 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6171 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6172 } 6173 6174 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 6175 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 6176 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 6177 unsigned NumBits = ElemTy.getSizeInBits(); 6178 SDValue WidthMinus1 = 6179 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6180 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 6181 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 6182 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 6183 } 6184 6185 // Compute with: cttz(x) = ctpop(lsb - 1) 6186 6187 // Compute LSB - 1. 6188 SDValue Bits; 6189 if (ElemTy == MVT::i64) { 6190 // Load constant 0xffff'ffff'ffff'ffff to register. 6191 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6192 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 6193 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 6194 } else { 6195 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6196 DAG.getTargetConstant(1, dl, ElemTy)); 6197 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6198 } 6199 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6200 } 6201 6202 if (!ST->hasV6T2Ops()) 6203 return SDValue(); 6204 6205 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 6206 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 6207 } 6208 6209 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 6210 const ARMSubtarget *ST) { 6211 EVT VT = N->getValueType(0); 6212 SDLoc DL(N); 6213 6214 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 6215 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6216 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6217 "Unexpected type for custom ctpop lowering"); 6218 6219 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6220 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6221 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 6222 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 6223 6224 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6225 unsigned EltSize = 8; 6226 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6227 while (EltSize != VT.getScalarSizeInBits()) { 6228 SmallVector<SDValue, 8> Ops; 6229 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 6230 TLI.getPointerTy(DAG.getDataLayout()))); 6231 Ops.push_back(Res); 6232 6233 EltSize *= 2; 6234 NumElts /= 2; 6235 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6236 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 6237 } 6238 6239 return Res; 6240 } 6241 6242 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 6243 /// operand of a vector shift operation, where all the elements of the 6244 /// build_vector must have the same constant integer value. 6245 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6246 // Ignore bit_converts. 6247 while (Op.getOpcode() == ISD::BITCAST) 6248 Op = Op.getOperand(0); 6249 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6250 APInt SplatBits, SplatUndef; 6251 unsigned SplatBitSize; 6252 bool HasAnyUndefs; 6253 if (!BVN || 6254 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 6255 ElementBits) || 6256 SplatBitSize > ElementBits) 6257 return false; 6258 Cnt = SplatBits.getSExtValue(); 6259 return true; 6260 } 6261 6262 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6263 /// operand of a vector shift left operation. That value must be in the range: 6264 /// 0 <= Value < ElementBits for a left shift; or 6265 /// 0 <= Value <= ElementBits for a long left shift. 6266 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6267 assert(VT.isVector() && "vector shift count is not a vector type"); 6268 int64_t ElementBits = VT.getScalarSizeInBits(); 6269 if (!getVShiftImm(Op, ElementBits, Cnt)) 6270 return false; 6271 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6272 } 6273 6274 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6275 /// operand of a vector shift right operation. For a shift opcode, the value 6276 /// is positive, but for an intrinsic the value count must be negative. The 6277 /// absolute value must be in the range: 6278 /// 1 <= |Value| <= ElementBits for a right shift; or 6279 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 6280 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 6281 int64_t &Cnt) { 6282 assert(VT.isVector() && "vector shift count is not a vector type"); 6283 int64_t ElementBits = VT.getScalarSizeInBits(); 6284 if (!getVShiftImm(Op, ElementBits, Cnt)) 6285 return false; 6286 if (!isIntrinsic) 6287 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6288 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 6289 Cnt = -Cnt; 6290 return true; 6291 } 6292 return false; 6293 } 6294 6295 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 6296 const ARMSubtarget *ST) { 6297 EVT VT = N->getValueType(0); 6298 SDLoc dl(N); 6299 int64_t Cnt; 6300 6301 if (!VT.isVector()) 6302 return SDValue(); 6303 6304 // We essentially have two forms here. Shift by an immediate and shift by a 6305 // vector register (there are also shift by a gpr, but that is just handled 6306 // with a tablegen pattern). We cannot easily match shift by an immediate in 6307 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 6308 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 6309 // signed or unsigned, and a negative shift indicates a shift right). 6310 if (N->getOpcode() == ISD::SHL) { 6311 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 6312 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 6313 DAG.getConstant(Cnt, dl, MVT::i32)); 6314 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 6315 N->getOperand(1)); 6316 } 6317 6318 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 6319 "unexpected vector shift opcode"); 6320 6321 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 6322 unsigned VShiftOpc = 6323 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 6324 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 6325 DAG.getConstant(Cnt, dl, MVT::i32)); 6326 } 6327 6328 // Other right shifts we don't have operations for (we use a shift left by a 6329 // negative number). 6330 EVT ShiftVT = N->getOperand(1).getValueType(); 6331 SDValue NegatedCount = DAG.getNode( 6332 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 6333 unsigned VShiftOpc = 6334 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 6335 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 6336 } 6337 6338 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 6339 const ARMSubtarget *ST) { 6340 EVT VT = N->getValueType(0); 6341 SDLoc dl(N); 6342 6343 // We can get here for a node like i32 = ISD::SHL i32, i64 6344 if (VT != MVT::i64) 6345 return SDValue(); 6346 6347 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 6348 N->getOpcode() == ISD::SHL) && 6349 "Unknown shift to lower!"); 6350 6351 unsigned ShOpc = N->getOpcode(); 6352 if (ST->hasMVEIntegerOps()) { 6353 SDValue ShAmt = N->getOperand(1); 6354 unsigned ShPartsOpc = ARMISD::LSLL; 6355 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 6356 6357 // If the shift amount is greater than 32 or has a greater bitwidth than 64 6358 // then do the default optimisation 6359 if (ShAmt->getValueType(0).getSizeInBits() > 64 || 6360 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32))) 6361 return SDValue(); 6362 6363 // Extract the lower 32 bits of the shift amount if it's not an i32 6364 if (ShAmt->getValueType(0) != MVT::i32) 6365 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32); 6366 6367 if (ShOpc == ISD::SRL) { 6368 if (!Con) 6369 // There is no t2LSRLr instruction so negate and perform an lsll if the 6370 // shift amount is in a register, emulating a right shift. 6371 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6372 DAG.getConstant(0, dl, MVT::i32), ShAmt); 6373 else 6374 // Else generate an lsrl on the immediate shift amount 6375 ShPartsOpc = ARMISD::LSRL; 6376 } else if (ShOpc == ISD::SRA) 6377 ShPartsOpc = ARMISD::ASRL; 6378 6379 // Lower 32 bits of the destination/source 6380 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6381 DAG.getConstant(0, dl, MVT::i32)); 6382 // Upper 32 bits of the destination/source 6383 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6384 DAG.getConstant(1, dl, MVT::i32)); 6385 6386 // Generate the shift operation as computed above 6387 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 6388 ShAmt); 6389 // The upper 32 bits come from the second return value of lsll 6390 Hi = SDValue(Lo.getNode(), 1); 6391 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6392 } 6393 6394 // We only lower SRA, SRL of 1 here, all others use generic lowering. 6395 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 6396 return SDValue(); 6397 6398 // If we are in thumb mode, we don't have RRX. 6399 if (ST->isThumb1Only()) 6400 return SDValue(); 6401 6402 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 6403 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6404 DAG.getConstant(0, dl, MVT::i32)); 6405 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6406 DAG.getConstant(1, dl, MVT::i32)); 6407 6408 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 6409 // captures the result into a carry flag. 6410 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 6411 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 6412 6413 // The low part is an ARMISD::RRX operand, which shifts the carry in. 6414 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 6415 6416 // Merge the pieces into a single i64 value. 6417 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6418 } 6419 6420 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 6421 const ARMSubtarget *ST) { 6422 bool Invert = false; 6423 bool Swap = false; 6424 unsigned Opc = ARMCC::AL; 6425 6426 SDValue Op0 = Op.getOperand(0); 6427 SDValue Op1 = Op.getOperand(1); 6428 SDValue CC = Op.getOperand(2); 6429 EVT VT = Op.getValueType(); 6430 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 6431 SDLoc dl(Op); 6432 6433 EVT CmpVT; 6434 if (ST->hasNEON()) 6435 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 6436 else { 6437 assert(ST->hasMVEIntegerOps() && 6438 "No hardware support for integer vector comparison!"); 6439 6440 if (Op.getValueType().getVectorElementType() != MVT::i1) 6441 return SDValue(); 6442 6443 // Make sure we expand floating point setcc to scalar if we do not have 6444 // mve.fp, so that we can handle them from there. 6445 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 6446 return SDValue(); 6447 6448 CmpVT = VT; 6449 } 6450 6451 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 6452 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 6453 // Special-case integer 64-bit equality comparisons. They aren't legal, 6454 // but they can be lowered with a few vector instructions. 6455 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 6456 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 6457 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 6458 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 6459 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 6460 DAG.getCondCode(ISD::SETEQ)); 6461 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 6462 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 6463 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 6464 if (SetCCOpcode == ISD::SETNE) 6465 Merged = DAG.getNOT(dl, Merged, CmpVT); 6466 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6467 return Merged; 6468 } 6469 6470 if (CmpVT.getVectorElementType() == MVT::i64) 6471 // 64-bit comparisons are not legal in general. 6472 return SDValue(); 6473 6474 if (Op1.getValueType().isFloatingPoint()) { 6475 switch (SetCCOpcode) { 6476 default: llvm_unreachable("Illegal FP comparison"); 6477 case ISD::SETUNE: 6478 case ISD::SETNE: 6479 if (ST->hasMVEFloatOps()) { 6480 Opc = ARMCC::NE; break; 6481 } else { 6482 Invert = true; LLVM_FALLTHROUGH; 6483 } 6484 case ISD::SETOEQ: 6485 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6486 case ISD::SETOLT: 6487 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6488 case ISD::SETOGT: 6489 case ISD::SETGT: Opc = ARMCC::GT; break; 6490 case ISD::SETOLE: 6491 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6492 case ISD::SETOGE: 6493 case ISD::SETGE: Opc = ARMCC::GE; break; 6494 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6495 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6496 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6497 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6498 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6499 case ISD::SETONE: { 6500 // Expand this to (OLT | OGT). 6501 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6502 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6503 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6504 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6505 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6506 if (Invert) 6507 Result = DAG.getNOT(dl, Result, VT); 6508 return Result; 6509 } 6510 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6511 case ISD::SETO: { 6512 // Expand this to (OLT | OGE). 6513 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6514 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6515 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6516 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6517 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6518 if (Invert) 6519 Result = DAG.getNOT(dl, Result, VT); 6520 return Result; 6521 } 6522 } 6523 } else { 6524 // Integer comparisons. 6525 switch (SetCCOpcode) { 6526 default: llvm_unreachable("Illegal integer comparison"); 6527 case ISD::SETNE: 6528 if (ST->hasMVEIntegerOps()) { 6529 Opc = ARMCC::NE; break; 6530 } else { 6531 Invert = true; LLVM_FALLTHROUGH; 6532 } 6533 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6534 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6535 case ISD::SETGT: Opc = ARMCC::GT; break; 6536 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6537 case ISD::SETGE: Opc = ARMCC::GE; break; 6538 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6539 case ISD::SETUGT: Opc = ARMCC::HI; break; 6540 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6541 case ISD::SETUGE: Opc = ARMCC::HS; break; 6542 } 6543 6544 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6545 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6546 SDValue AndOp; 6547 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6548 AndOp = Op0; 6549 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6550 AndOp = Op1; 6551 6552 // Ignore bitconvert. 6553 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6554 AndOp = AndOp.getOperand(0); 6555 6556 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6557 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6558 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6559 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6560 if (!Invert) 6561 Result = DAG.getNOT(dl, Result, VT); 6562 return Result; 6563 } 6564 } 6565 } 6566 6567 if (Swap) 6568 std::swap(Op0, Op1); 6569 6570 // If one of the operands is a constant vector zero, attempt to fold the 6571 // comparison to a specialized compare-against-zero form. 6572 SDValue SingleOp; 6573 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6574 SingleOp = Op0; 6575 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6576 if (Opc == ARMCC::GE) 6577 Opc = ARMCC::LE; 6578 else if (Opc == ARMCC::GT) 6579 Opc = ARMCC::LT; 6580 SingleOp = Op1; 6581 } 6582 6583 SDValue Result; 6584 if (SingleOp.getNode()) { 6585 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6586 DAG.getConstant(Opc, dl, MVT::i32)); 6587 } else { 6588 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6589 DAG.getConstant(Opc, dl, MVT::i32)); 6590 } 6591 6592 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6593 6594 if (Invert) 6595 Result = DAG.getNOT(dl, Result, VT); 6596 6597 return Result; 6598 } 6599 6600 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6601 SDValue LHS = Op.getOperand(0); 6602 SDValue RHS = Op.getOperand(1); 6603 SDValue Carry = Op.getOperand(2); 6604 SDValue Cond = Op.getOperand(3); 6605 SDLoc DL(Op); 6606 6607 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6608 6609 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6610 // have to invert the carry first. 6611 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6612 DAG.getConstant(1, DL, MVT::i32), Carry); 6613 // This converts the boolean value carry into the carry flag. 6614 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6615 6616 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6617 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6618 6619 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6620 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6621 SDValue ARMcc = DAG.getConstant( 6622 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6623 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6624 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6625 Cmp.getValue(1), SDValue()); 6626 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6627 CCR, Chain.getValue(1)); 6628 } 6629 6630 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6631 /// valid vector constant for a NEON or MVE instruction with a "modified 6632 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6633 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6634 unsigned SplatBitSize, SelectionDAG &DAG, 6635 const SDLoc &dl, EVT &VT, EVT VectorVT, 6636 VMOVModImmType type) { 6637 unsigned OpCmode, Imm; 6638 bool is128Bits = VectorVT.is128BitVector(); 6639 6640 // SplatBitSize is set to the smallest size that splats the vector, so a 6641 // zero vector will always have SplatBitSize == 8. However, NEON modified 6642 // immediate instructions others than VMOV do not support the 8-bit encoding 6643 // of a zero vector, and the default encoding of zero is supposed to be the 6644 // 32-bit version. 6645 if (SplatBits == 0) 6646 SplatBitSize = 32; 6647 6648 switch (SplatBitSize) { 6649 case 8: 6650 if (type != VMOVModImm) 6651 return SDValue(); 6652 // Any 1-byte value is OK. Op=0, Cmode=1110. 6653 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6654 OpCmode = 0xe; 6655 Imm = SplatBits; 6656 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6657 break; 6658 6659 case 16: 6660 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6661 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6662 if ((SplatBits & ~0xff) == 0) { 6663 // Value = 0x00nn: Op=x, Cmode=100x. 6664 OpCmode = 0x8; 6665 Imm = SplatBits; 6666 break; 6667 } 6668 if ((SplatBits & ~0xff00) == 0) { 6669 // Value = 0xnn00: Op=x, Cmode=101x. 6670 OpCmode = 0xa; 6671 Imm = SplatBits >> 8; 6672 break; 6673 } 6674 return SDValue(); 6675 6676 case 32: 6677 // NEON's 32-bit VMOV supports splat values where: 6678 // * only one byte is nonzero, or 6679 // * the least significant byte is 0xff and the second byte is nonzero, or 6680 // * the least significant 2 bytes are 0xff and the third is nonzero. 6681 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6682 if ((SplatBits & ~0xff) == 0) { 6683 // Value = 0x000000nn: Op=x, Cmode=000x. 6684 OpCmode = 0; 6685 Imm = SplatBits; 6686 break; 6687 } 6688 if ((SplatBits & ~0xff00) == 0) { 6689 // Value = 0x0000nn00: Op=x, Cmode=001x. 6690 OpCmode = 0x2; 6691 Imm = SplatBits >> 8; 6692 break; 6693 } 6694 if ((SplatBits & ~0xff0000) == 0) { 6695 // Value = 0x00nn0000: Op=x, Cmode=010x. 6696 OpCmode = 0x4; 6697 Imm = SplatBits >> 16; 6698 break; 6699 } 6700 if ((SplatBits & ~0xff000000) == 0) { 6701 // Value = 0xnn000000: Op=x, Cmode=011x. 6702 OpCmode = 0x6; 6703 Imm = SplatBits >> 24; 6704 break; 6705 } 6706 6707 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6708 if (type == OtherModImm) return SDValue(); 6709 6710 if ((SplatBits & ~0xffff) == 0 && 6711 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6712 // Value = 0x0000nnff: Op=x, Cmode=1100. 6713 OpCmode = 0xc; 6714 Imm = SplatBits >> 8; 6715 break; 6716 } 6717 6718 // cmode == 0b1101 is not supported for MVE VMVN 6719 if (type == MVEVMVNModImm) 6720 return SDValue(); 6721 6722 if ((SplatBits & ~0xffffff) == 0 && 6723 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6724 // Value = 0x00nnffff: Op=x, Cmode=1101. 6725 OpCmode = 0xd; 6726 Imm = SplatBits >> 16; 6727 break; 6728 } 6729 6730 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6731 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6732 // VMOV.I32. A (very) minor optimization would be to replicate the value 6733 // and fall through here to test for a valid 64-bit splat. But, then the 6734 // caller would also need to check and handle the change in size. 6735 return SDValue(); 6736 6737 case 64: { 6738 if (type != VMOVModImm) 6739 return SDValue(); 6740 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6741 uint64_t BitMask = 0xff; 6742 uint64_t Val = 0; 6743 unsigned ImmMask = 1; 6744 Imm = 0; 6745 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6746 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6747 Val |= BitMask; 6748 Imm |= ImmMask; 6749 } else if ((SplatBits & BitMask) != 0) { 6750 return SDValue(); 6751 } 6752 BitMask <<= 8; 6753 ImmMask <<= 1; 6754 } 6755 6756 if (DAG.getDataLayout().isBigEndian()) { 6757 // Reverse the order of elements within the vector. 6758 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8; 6759 unsigned Mask = (1 << BytesPerElem) - 1; 6760 unsigned NumElems = 8 / BytesPerElem; 6761 unsigned NewImm = 0; 6762 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) { 6763 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask); 6764 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem; 6765 } 6766 Imm = NewImm; 6767 } 6768 6769 // Op=1, Cmode=1110. 6770 OpCmode = 0x1e; 6771 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6772 break; 6773 } 6774 6775 default: 6776 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6777 } 6778 6779 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6780 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6781 } 6782 6783 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6784 const ARMSubtarget *ST) const { 6785 EVT VT = Op.getValueType(); 6786 bool IsDouble = (VT == MVT::f64); 6787 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6788 const APFloat &FPVal = CFP->getValueAPF(); 6789 6790 // Prevent floating-point constants from using literal loads 6791 // when execute-only is enabled. 6792 if (ST->genExecuteOnly()) { 6793 // If we can represent the constant as an immediate, don't lower it 6794 if (isFPImmLegal(FPVal, VT)) 6795 return Op; 6796 // Otherwise, construct as integer, and move to float register 6797 APInt INTVal = FPVal.bitcastToAPInt(); 6798 SDLoc DL(CFP); 6799 switch (VT.getSimpleVT().SimpleTy) { 6800 default: 6801 llvm_unreachable("Unknown floating point type!"); 6802 break; 6803 case MVT::f64: { 6804 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6805 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6806 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6807 } 6808 case MVT::f32: 6809 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6810 DAG.getConstant(INTVal, DL, MVT::i32)); 6811 } 6812 } 6813 6814 if (!ST->hasVFP3Base()) 6815 return SDValue(); 6816 6817 // Use the default (constant pool) lowering for double constants when we have 6818 // an SP-only FPU 6819 if (IsDouble && !Subtarget->hasFP64()) 6820 return SDValue(); 6821 6822 // Try splatting with a VMOV.f32... 6823 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6824 6825 if (ImmVal != -1) { 6826 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6827 // We have code in place to select a valid ConstantFP already, no need to 6828 // do any mangling. 6829 return Op; 6830 } 6831 6832 // It's a float and we are trying to use NEON operations where 6833 // possible. Lower it to a splat followed by an extract. 6834 SDLoc DL(Op); 6835 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6836 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6837 NewVal); 6838 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6839 DAG.getConstant(0, DL, MVT::i32)); 6840 } 6841 6842 // The rest of our options are NEON only, make sure that's allowed before 6843 // proceeding.. 6844 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6845 return SDValue(); 6846 6847 EVT VMovVT; 6848 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6849 6850 // It wouldn't really be worth bothering for doubles except for one very 6851 // important value, which does happen to match: 0.0. So make sure we don't do 6852 // anything stupid. 6853 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6854 return SDValue(); 6855 6856 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6857 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6858 VMovVT, VT, VMOVModImm); 6859 if (NewVal != SDValue()) { 6860 SDLoc DL(Op); 6861 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6862 NewVal); 6863 if (IsDouble) 6864 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6865 6866 // It's a float: cast and extract a vector element. 6867 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6868 VecConstant); 6869 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6870 DAG.getConstant(0, DL, MVT::i32)); 6871 } 6872 6873 // Finally, try a VMVN.i32 6874 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6875 VT, VMVNModImm); 6876 if (NewVal != SDValue()) { 6877 SDLoc DL(Op); 6878 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6879 6880 if (IsDouble) 6881 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6882 6883 // It's a float: cast and extract a vector element. 6884 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6885 VecConstant); 6886 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6887 DAG.getConstant(0, DL, MVT::i32)); 6888 } 6889 6890 return SDValue(); 6891 } 6892 6893 // check if an VEXT instruction can handle the shuffle mask when the 6894 // vector sources of the shuffle are the same. 6895 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6896 unsigned NumElts = VT.getVectorNumElements(); 6897 6898 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6899 if (M[0] < 0) 6900 return false; 6901 6902 Imm = M[0]; 6903 6904 // If this is a VEXT shuffle, the immediate value is the index of the first 6905 // element. The other shuffle indices must be the successive elements after 6906 // the first one. 6907 unsigned ExpectedElt = Imm; 6908 for (unsigned i = 1; i < NumElts; ++i) { 6909 // Increment the expected index. If it wraps around, just follow it 6910 // back to index zero and keep going. 6911 ++ExpectedElt; 6912 if (ExpectedElt == NumElts) 6913 ExpectedElt = 0; 6914 6915 if (M[i] < 0) continue; // ignore UNDEF indices 6916 if (ExpectedElt != static_cast<unsigned>(M[i])) 6917 return false; 6918 } 6919 6920 return true; 6921 } 6922 6923 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6924 bool &ReverseVEXT, unsigned &Imm) { 6925 unsigned NumElts = VT.getVectorNumElements(); 6926 ReverseVEXT = false; 6927 6928 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6929 if (M[0] < 0) 6930 return false; 6931 6932 Imm = M[0]; 6933 6934 // If this is a VEXT shuffle, the immediate value is the index of the first 6935 // element. The other shuffle indices must be the successive elements after 6936 // the first one. 6937 unsigned ExpectedElt = Imm; 6938 for (unsigned i = 1; i < NumElts; ++i) { 6939 // Increment the expected index. If it wraps around, it may still be 6940 // a VEXT but the source vectors must be swapped. 6941 ExpectedElt += 1; 6942 if (ExpectedElt == NumElts * 2) { 6943 ExpectedElt = 0; 6944 ReverseVEXT = true; 6945 } 6946 6947 if (M[i] < 0) continue; // ignore UNDEF indices 6948 if (ExpectedElt != static_cast<unsigned>(M[i])) 6949 return false; 6950 } 6951 6952 // Adjust the index value if the source operands will be swapped. 6953 if (ReverseVEXT) 6954 Imm -= NumElts; 6955 6956 return true; 6957 } 6958 6959 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6960 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6961 // range, then 0 is placed into the resulting vector. So pretty much any mask 6962 // of 8 elements can work here. 6963 return VT == MVT::v8i8 && M.size() == 8; 6964 } 6965 6966 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6967 unsigned Index) { 6968 if (Mask.size() == Elements * 2) 6969 return Index / Elements; 6970 return Mask[Index] == 0 ? 0 : 1; 6971 } 6972 6973 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6974 // checking that pairs of elements in the shuffle mask represent the same index 6975 // in each vector, incrementing the expected index by 2 at each step. 6976 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6977 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6978 // v2={e,f,g,h} 6979 // WhichResult gives the offset for each element in the mask based on which 6980 // of the two results it belongs to. 6981 // 6982 // The transpose can be represented either as: 6983 // result1 = shufflevector v1, v2, result1_shuffle_mask 6984 // result2 = shufflevector v1, v2, result2_shuffle_mask 6985 // where v1/v2 and the shuffle masks have the same number of elements 6986 // (here WhichResult (see below) indicates which result is being checked) 6987 // 6988 // or as: 6989 // results = shufflevector v1, v2, shuffle_mask 6990 // where both results are returned in one vector and the shuffle mask has twice 6991 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6992 // want to check the low half and high half of the shuffle mask as if it were 6993 // the other case 6994 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6995 unsigned EltSz = VT.getScalarSizeInBits(); 6996 if (EltSz == 64) 6997 return false; 6998 6999 unsigned NumElts = VT.getVectorNumElements(); 7000 if (M.size() != NumElts && M.size() != NumElts*2) 7001 return false; 7002 7003 // If the mask is twice as long as the input vector then we need to check the 7004 // upper and lower parts of the mask with a matching value for WhichResult 7005 // FIXME: A mask with only even values will be rejected in case the first 7006 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 7007 // M[0] is used to determine WhichResult 7008 for (unsigned i = 0; i < M.size(); i += NumElts) { 7009 WhichResult = SelectPairHalf(NumElts, M, i); 7010 for (unsigned j = 0; j < NumElts; j += 2) { 7011 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7012 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 7013 return false; 7014 } 7015 } 7016 7017 if (M.size() == NumElts*2) 7018 WhichResult = 0; 7019 7020 return true; 7021 } 7022 7023 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 7024 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7025 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 7026 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7027 unsigned EltSz = VT.getScalarSizeInBits(); 7028 if (EltSz == 64) 7029 return false; 7030 7031 unsigned NumElts = VT.getVectorNumElements(); 7032 if (M.size() != NumElts && M.size() != NumElts*2) 7033 return false; 7034 7035 for (unsigned i = 0; i < M.size(); i += NumElts) { 7036 WhichResult = SelectPairHalf(NumElts, M, i); 7037 for (unsigned j = 0; j < NumElts; j += 2) { 7038 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7039 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 7040 return false; 7041 } 7042 } 7043 7044 if (M.size() == NumElts*2) 7045 WhichResult = 0; 7046 7047 return true; 7048 } 7049 7050 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 7051 // that the mask elements are either all even and in steps of size 2 or all odd 7052 // and in steps of size 2. 7053 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 7054 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 7055 // v2={e,f,g,h} 7056 // Requires similar checks to that of isVTRNMask with 7057 // respect the how results are returned. 7058 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7059 unsigned EltSz = VT.getScalarSizeInBits(); 7060 if (EltSz == 64) 7061 return false; 7062 7063 unsigned NumElts = VT.getVectorNumElements(); 7064 if (M.size() != NumElts && M.size() != NumElts*2) 7065 return false; 7066 7067 for (unsigned i = 0; i < M.size(); i += NumElts) { 7068 WhichResult = SelectPairHalf(NumElts, M, i); 7069 for (unsigned j = 0; j < NumElts; ++j) { 7070 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 7071 return false; 7072 } 7073 } 7074 7075 if (M.size() == NumElts*2) 7076 WhichResult = 0; 7077 7078 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7079 if (VT.is64BitVector() && EltSz == 32) 7080 return false; 7081 7082 return true; 7083 } 7084 7085 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 7086 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7087 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 7088 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7089 unsigned EltSz = VT.getScalarSizeInBits(); 7090 if (EltSz == 64) 7091 return false; 7092 7093 unsigned NumElts = VT.getVectorNumElements(); 7094 if (M.size() != NumElts && M.size() != NumElts*2) 7095 return false; 7096 7097 unsigned Half = NumElts / 2; 7098 for (unsigned i = 0; i < M.size(); i += NumElts) { 7099 WhichResult = SelectPairHalf(NumElts, M, i); 7100 for (unsigned j = 0; j < NumElts; j += Half) { 7101 unsigned Idx = WhichResult; 7102 for (unsigned k = 0; k < Half; ++k) { 7103 int MIdx = M[i + j + k]; 7104 if (MIdx >= 0 && (unsigned) MIdx != Idx) 7105 return false; 7106 Idx += 2; 7107 } 7108 } 7109 } 7110 7111 if (M.size() == NumElts*2) 7112 WhichResult = 0; 7113 7114 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7115 if (VT.is64BitVector() && EltSz == 32) 7116 return false; 7117 7118 return true; 7119 } 7120 7121 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 7122 // that pairs of elements of the shufflemask represent the same index in each 7123 // vector incrementing sequentially through the vectors. 7124 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 7125 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 7126 // v2={e,f,g,h} 7127 // Requires similar checks to that of isVTRNMask with respect the how results 7128 // are returned. 7129 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7130 unsigned EltSz = VT.getScalarSizeInBits(); 7131 if (EltSz == 64) 7132 return false; 7133 7134 unsigned NumElts = VT.getVectorNumElements(); 7135 if (M.size() != NumElts && M.size() != NumElts*2) 7136 return false; 7137 7138 for (unsigned i = 0; i < M.size(); i += NumElts) { 7139 WhichResult = SelectPairHalf(NumElts, M, i); 7140 unsigned Idx = WhichResult * NumElts / 2; 7141 for (unsigned j = 0; j < NumElts; j += 2) { 7142 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7143 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 7144 return false; 7145 Idx += 1; 7146 } 7147 } 7148 7149 if (M.size() == NumElts*2) 7150 WhichResult = 0; 7151 7152 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7153 if (VT.is64BitVector() && EltSz == 32) 7154 return false; 7155 7156 return true; 7157 } 7158 7159 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 7160 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7161 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 7162 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7163 unsigned EltSz = VT.getScalarSizeInBits(); 7164 if (EltSz == 64) 7165 return false; 7166 7167 unsigned NumElts = VT.getVectorNumElements(); 7168 if (M.size() != NumElts && M.size() != NumElts*2) 7169 return false; 7170 7171 for (unsigned i = 0; i < M.size(); i += NumElts) { 7172 WhichResult = SelectPairHalf(NumElts, M, i); 7173 unsigned Idx = WhichResult * NumElts / 2; 7174 for (unsigned j = 0; j < NumElts; j += 2) { 7175 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7176 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 7177 return false; 7178 Idx += 1; 7179 } 7180 } 7181 7182 if (M.size() == NumElts*2) 7183 WhichResult = 0; 7184 7185 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7186 if (VT.is64BitVector() && EltSz == 32) 7187 return false; 7188 7189 return true; 7190 } 7191 7192 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 7193 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 7194 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 7195 unsigned &WhichResult, 7196 bool &isV_UNDEF) { 7197 isV_UNDEF = false; 7198 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 7199 return ARMISD::VTRN; 7200 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 7201 return ARMISD::VUZP; 7202 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 7203 return ARMISD::VZIP; 7204 7205 isV_UNDEF = true; 7206 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7207 return ARMISD::VTRN; 7208 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7209 return ARMISD::VUZP; 7210 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7211 return ARMISD::VZIP; 7212 7213 return 0; 7214 } 7215 7216 /// \return true if this is a reverse operation on an vector. 7217 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 7218 unsigned NumElts = VT.getVectorNumElements(); 7219 // Make sure the mask has the right size. 7220 if (NumElts != M.size()) 7221 return false; 7222 7223 // Look for <15, ..., 3, -1, 1, 0>. 7224 for (unsigned i = 0; i != NumElts; ++i) 7225 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 7226 return false; 7227 7228 return true; 7229 } 7230 7231 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) { 7232 unsigned NumElts = VT.getVectorNumElements(); 7233 // Make sure the mask has the right size. 7234 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8)) 7235 return false; 7236 7237 // If Top 7238 // Look for <0, N, 2, N+2, 4, N+4, ..>. 7239 // This inserts Input2 into Input1 7240 // else if not Top 7241 // Look for <0, N+1, 2, N+3, 4, N+5, ..> 7242 // This inserts Input1 into Input2 7243 unsigned Offset = Top ? 0 : 1; 7244 unsigned N = SingleSource ? 0 : NumElts; 7245 for (unsigned i = 0; i < NumElts; i += 2) { 7246 if (M[i] >= 0 && M[i] != (int)i) 7247 return false; 7248 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset)) 7249 return false; 7250 } 7251 7252 return true; 7253 } 7254 7255 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted 7256 // from a pair of inputs. For example: 7257 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7258 // FP_ROUND(EXTRACT_ELT(Y, 0), 7259 // FP_ROUND(EXTRACT_ELT(X, 1), 7260 // FP_ROUND(EXTRACT_ELT(Y, 1), ...) 7261 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG, 7262 const ARMSubtarget *ST) { 7263 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7264 if (!ST->hasMVEFloatOps()) 7265 return SDValue(); 7266 7267 SDLoc dl(BV); 7268 EVT VT = BV.getValueType(); 7269 if (VT != MVT::v8f16) 7270 return SDValue(); 7271 7272 // We are looking for a buildvector of fptrunc elements, where all the 7273 // elements are interleavingly extracted from two sources. Check the first two 7274 // items are valid enough and extract some info from them (they are checked 7275 // properly in the loop below). 7276 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND || 7277 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7278 BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0) 7279 return SDValue(); 7280 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND || 7281 BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7282 BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0) 7283 return SDValue(); 7284 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7285 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0); 7286 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32) 7287 return SDValue(); 7288 7289 // Check all the values in the BuildVector line up with our expectations. 7290 for (unsigned i = 1; i < 4; i++) { 7291 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7292 return Trunc.getOpcode() == ISD::FP_ROUND && 7293 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7294 Trunc.getOperand(0).getOperand(0) == Op && 7295 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7296 }; 7297 if (!Check(BV.getOperand(i * 2 + 0), Op0, i)) 7298 return SDValue(); 7299 if (!Check(BV.getOperand(i * 2 + 1), Op1, i)) 7300 return SDValue(); 7301 } 7302 7303 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0, 7304 DAG.getConstant(0, dl, MVT::i32)); 7305 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1, 7306 DAG.getConstant(1, dl, MVT::i32)); 7307 } 7308 7309 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted 7310 // from a single input on alternating lanes. For example: 7311 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7312 // FP_ROUND(EXTRACT_ELT(X, 2), 7313 // FP_ROUND(EXTRACT_ELT(X, 4), ...) 7314 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG, 7315 const ARMSubtarget *ST) { 7316 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7317 if (!ST->hasMVEFloatOps()) 7318 return SDValue(); 7319 7320 SDLoc dl(BV); 7321 EVT VT = BV.getValueType(); 7322 if (VT != MVT::v4f32) 7323 return SDValue(); 7324 7325 // We are looking for a buildvector of fptext elements, where all the 7326 // elements are alternating lanes from a single source. For example <0,2,4,6> 7327 // or <1,3,5,7>. Check the first two items are valid enough and extract some 7328 // info from them (they are checked properly in the loop below). 7329 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND || 7330 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7331 return SDValue(); 7332 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7333 int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1); 7334 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1)) 7335 return SDValue(); 7336 7337 // Check all the values in the BuildVector line up with our expectations. 7338 for (unsigned i = 1; i < 4; i++) { 7339 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7340 return Trunc.getOpcode() == ISD::FP_EXTEND && 7341 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7342 Trunc.getOperand(0).getOperand(0) == Op && 7343 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7344 }; 7345 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset)) 7346 return SDValue(); 7347 } 7348 7349 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0, 7350 DAG.getConstant(Offset, dl, MVT::i32)); 7351 } 7352 7353 // If N is an integer constant that can be moved into a register in one 7354 // instruction, return an SDValue of such a constant (will become a MOV 7355 // instruction). Otherwise return null. 7356 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 7357 const ARMSubtarget *ST, const SDLoc &dl) { 7358 uint64_t Val; 7359 if (!isa<ConstantSDNode>(N)) 7360 return SDValue(); 7361 Val = cast<ConstantSDNode>(N)->getZExtValue(); 7362 7363 if (ST->isThumb1Only()) { 7364 if (Val <= 255 || ~Val <= 255) 7365 return DAG.getConstant(Val, dl, MVT::i32); 7366 } else { 7367 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 7368 return DAG.getConstant(Val, dl, MVT::i32); 7369 } 7370 return SDValue(); 7371 } 7372 7373 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 7374 const ARMSubtarget *ST) { 7375 SDLoc dl(Op); 7376 EVT VT = Op.getValueType(); 7377 7378 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 7379 7380 unsigned NumElts = VT.getVectorNumElements(); 7381 unsigned BoolMask; 7382 unsigned BitsPerBool; 7383 if (NumElts == 4) { 7384 BitsPerBool = 4; 7385 BoolMask = 0xf; 7386 } else if (NumElts == 8) { 7387 BitsPerBool = 2; 7388 BoolMask = 0x3; 7389 } else if (NumElts == 16) { 7390 BitsPerBool = 1; 7391 BoolMask = 0x1; 7392 } else 7393 return SDValue(); 7394 7395 // If this is a single value copied into all lanes (a splat), we can just sign 7396 // extend that single value 7397 SDValue FirstOp = Op.getOperand(0); 7398 if (!isa<ConstantSDNode>(FirstOp) && 7399 std::all_of(std::next(Op->op_begin()), Op->op_end(), 7400 [&FirstOp](SDUse &U) { 7401 return U.get().isUndef() || U.get() == FirstOp; 7402 })) { 7403 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp, 7404 DAG.getValueType(MVT::i1)); 7405 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext); 7406 } 7407 7408 // First create base with bits set where known 7409 unsigned Bits32 = 0; 7410 for (unsigned i = 0; i < NumElts; ++i) { 7411 SDValue V = Op.getOperand(i); 7412 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 7413 continue; 7414 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 7415 if (BitSet) 7416 Bits32 |= BoolMask << (i * BitsPerBool); 7417 } 7418 7419 // Add in unknown nodes 7420 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 7421 DAG.getConstant(Bits32, dl, MVT::i32)); 7422 for (unsigned i = 0; i < NumElts; ++i) { 7423 SDValue V = Op.getOperand(i); 7424 if (isa<ConstantSDNode>(V) || V.isUndef()) 7425 continue; 7426 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 7427 DAG.getConstant(i, dl, MVT::i32)); 7428 } 7429 7430 return Base; 7431 } 7432 7433 // If this is a case we can't handle, return null and let the default 7434 // expansion code take care of it. 7435 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 7436 const ARMSubtarget *ST) const { 7437 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7438 SDLoc dl(Op); 7439 EVT VT = Op.getValueType(); 7440 7441 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7442 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 7443 7444 APInt SplatBits, SplatUndef; 7445 unsigned SplatBitSize; 7446 bool HasAnyUndefs; 7447 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7448 if (SplatUndef.isAllOnesValue()) 7449 return DAG.getUNDEF(VT); 7450 7451 if ((ST->hasNEON() && SplatBitSize <= 64) || 7452 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) { 7453 // Check if an immediate VMOV works. 7454 EVT VmovVT; 7455 SDValue Val = 7456 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 7457 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm); 7458 7459 if (Val.getNode()) { 7460 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 7461 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7462 } 7463 7464 // Try an immediate VMVN. 7465 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 7466 Val = isVMOVModifiedImm( 7467 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT, 7468 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 7469 if (Val.getNode()) { 7470 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 7471 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7472 } 7473 7474 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 7475 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 7476 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 7477 if (ImmVal != -1) { 7478 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 7479 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 7480 } 7481 } 7482 } 7483 } 7484 7485 // Scan through the operands to see if only one value is used. 7486 // 7487 // As an optimisation, even if more than one value is used it may be more 7488 // profitable to splat with one value then change some lanes. 7489 // 7490 // Heuristically we decide to do this if the vector has a "dominant" value, 7491 // defined as splatted to more than half of the lanes. 7492 unsigned NumElts = VT.getVectorNumElements(); 7493 bool isOnlyLowElement = true; 7494 bool usesOnlyOneValue = true; 7495 bool hasDominantValue = false; 7496 bool isConstant = true; 7497 7498 // Map of the number of times a particular SDValue appears in the 7499 // element list. 7500 DenseMap<SDValue, unsigned> ValueCounts; 7501 SDValue Value; 7502 for (unsigned i = 0; i < NumElts; ++i) { 7503 SDValue V = Op.getOperand(i); 7504 if (V.isUndef()) 7505 continue; 7506 if (i > 0) 7507 isOnlyLowElement = false; 7508 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7509 isConstant = false; 7510 7511 ValueCounts.insert(std::make_pair(V, 0)); 7512 unsigned &Count = ValueCounts[V]; 7513 7514 // Is this value dominant? (takes up more than half of the lanes) 7515 if (++Count > (NumElts / 2)) { 7516 hasDominantValue = true; 7517 Value = V; 7518 } 7519 } 7520 if (ValueCounts.size() != 1) 7521 usesOnlyOneValue = false; 7522 if (!Value.getNode() && !ValueCounts.empty()) 7523 Value = ValueCounts.begin()->first; 7524 7525 if (ValueCounts.empty()) 7526 return DAG.getUNDEF(VT); 7527 7528 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 7529 // Keep going if we are hitting this case. 7530 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 7531 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7532 7533 unsigned EltSize = VT.getScalarSizeInBits(); 7534 7535 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 7536 // i32 and try again. 7537 if (hasDominantValue && EltSize <= 32) { 7538 if (!isConstant) { 7539 SDValue N; 7540 7541 // If we are VDUPing a value that comes directly from a vector, that will 7542 // cause an unnecessary move to and from a GPR, where instead we could 7543 // just use VDUPLANE. We can only do this if the lane being extracted 7544 // is at a constant index, as the VDUP from lane instructions only have 7545 // constant-index forms. 7546 ConstantSDNode *constIndex; 7547 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7548 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 7549 // We need to create a new undef vector to use for the VDUPLANE if the 7550 // size of the vector from which we get the value is different than the 7551 // size of the vector that we need to create. We will insert the element 7552 // such that the register coalescer will remove unnecessary copies. 7553 if (VT != Value->getOperand(0).getValueType()) { 7554 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 7555 VT.getVectorNumElements(); 7556 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7557 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 7558 Value, DAG.getConstant(index, dl, MVT::i32)), 7559 DAG.getConstant(index, dl, MVT::i32)); 7560 } else 7561 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7562 Value->getOperand(0), Value->getOperand(1)); 7563 } else 7564 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 7565 7566 if (!usesOnlyOneValue) { 7567 // The dominant value was splatted as 'N', but we now have to insert 7568 // all differing elements. 7569 for (unsigned I = 0; I < NumElts; ++I) { 7570 if (Op.getOperand(I) == Value) 7571 continue; 7572 SmallVector<SDValue, 3> Ops; 7573 Ops.push_back(N); 7574 Ops.push_back(Op.getOperand(I)); 7575 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7576 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7577 } 7578 } 7579 return N; 7580 } 7581 if (VT.getVectorElementType().isFloatingPoint()) { 7582 SmallVector<SDValue, 8> Ops; 7583 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7584 assert(FVT == MVT::f32 || FVT == MVT::f16); 7585 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7586 for (unsigned i = 0; i < NumElts; ++i) 7587 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7588 Op.getOperand(i))); 7589 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7590 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7591 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7592 if (Val.getNode()) 7593 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7594 } 7595 if (usesOnlyOneValue) { 7596 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7597 if (isConstant && Val.getNode()) 7598 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7599 } 7600 } 7601 7602 // If all elements are constants and the case above didn't get hit, fall back 7603 // to the default expansion, which will generate a load from the constant 7604 // pool. 7605 if (isConstant) 7606 return SDValue(); 7607 7608 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and 7609 // vmovn). Empirical tests suggest this is rarely worth it for vectors of 7610 // length <= 2. 7611 if (NumElts >= 4) 7612 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 7613 return shuffle; 7614 7615 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into 7616 // VCVT's 7617 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget)) 7618 return VCVT; 7619 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget)) 7620 return VCVT; 7621 7622 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7623 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7624 // into two 64-bit vectors; we might discover a better way to lower it. 7625 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7626 EVT ExtVT = VT.getVectorElementType(); 7627 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7628 SDValue Lower = 7629 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7630 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7631 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7632 SDValue Upper = DAG.getBuildVector( 7633 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7634 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7635 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7636 if (Lower && Upper) 7637 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7638 } 7639 7640 // Vectors with 32- or 64-bit elements can be built by directly assigning 7641 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7642 // will be legalized. 7643 if (EltSize >= 32) { 7644 // Do the expansion with floating-point types, since that is what the VFP 7645 // registers are defined to use, and since i64 is not legal. 7646 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7647 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7648 SmallVector<SDValue, 8> Ops; 7649 for (unsigned i = 0; i < NumElts; ++i) 7650 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7651 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7652 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7653 } 7654 7655 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7656 // know the default expansion would otherwise fall back on something even 7657 // worse. For a vector with one or two non-undef values, that's 7658 // scalar_to_vector for the elements followed by a shuffle (provided the 7659 // shuffle is valid for the target) and materialization element by element 7660 // on the stack followed by a load for everything else. 7661 if (!isConstant && !usesOnlyOneValue) { 7662 SDValue Vec = DAG.getUNDEF(VT); 7663 for (unsigned i = 0 ; i < NumElts; ++i) { 7664 SDValue V = Op.getOperand(i); 7665 if (V.isUndef()) 7666 continue; 7667 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7668 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7669 } 7670 return Vec; 7671 } 7672 7673 return SDValue(); 7674 } 7675 7676 // Gather data to see if the operation can be modelled as a 7677 // shuffle in combination with VEXTs. 7678 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7679 SelectionDAG &DAG) const { 7680 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7681 SDLoc dl(Op); 7682 EVT VT = Op.getValueType(); 7683 unsigned NumElts = VT.getVectorNumElements(); 7684 7685 struct ShuffleSourceInfo { 7686 SDValue Vec; 7687 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7688 unsigned MaxElt = 0; 7689 7690 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7691 // be compatible with the shuffle we intend to construct. As a result 7692 // ShuffleVec will be some sliding window into the original Vec. 7693 SDValue ShuffleVec; 7694 7695 // Code should guarantee that element i in Vec starts at element "WindowBase 7696 // + i * WindowScale in ShuffleVec". 7697 int WindowBase = 0; 7698 int WindowScale = 1; 7699 7700 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7701 7702 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7703 }; 7704 7705 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7706 // node. 7707 SmallVector<ShuffleSourceInfo, 2> Sources; 7708 for (unsigned i = 0; i < NumElts; ++i) { 7709 SDValue V = Op.getOperand(i); 7710 if (V.isUndef()) 7711 continue; 7712 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7713 // A shuffle can only come from building a vector from various 7714 // elements of other vectors. 7715 return SDValue(); 7716 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7717 // Furthermore, shuffles require a constant mask, whereas extractelts 7718 // accept variable indices. 7719 return SDValue(); 7720 } 7721 7722 // Add this element source to the list if it's not already there. 7723 SDValue SourceVec = V.getOperand(0); 7724 auto Source = llvm::find(Sources, SourceVec); 7725 if (Source == Sources.end()) 7726 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7727 7728 // Update the minimum and maximum lane number seen. 7729 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7730 Source->MinElt = std::min(Source->MinElt, EltNo); 7731 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7732 } 7733 7734 // Currently only do something sane when at most two source vectors 7735 // are involved. 7736 if (Sources.size() > 2) 7737 return SDValue(); 7738 7739 // Find out the smallest element size among result and two sources, and use 7740 // it as element size to build the shuffle_vector. 7741 EVT SmallestEltTy = VT.getVectorElementType(); 7742 for (auto &Source : Sources) { 7743 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7744 if (SrcEltTy.bitsLT(SmallestEltTy)) 7745 SmallestEltTy = SrcEltTy; 7746 } 7747 unsigned ResMultiplier = 7748 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7749 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7750 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7751 7752 // If the source vector is too wide or too narrow, we may nevertheless be able 7753 // to construct a compatible shuffle either by concatenating it with UNDEF or 7754 // extracting a suitable range of elements. 7755 for (auto &Src : Sources) { 7756 EVT SrcVT = Src.ShuffleVec.getValueType(); 7757 7758 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits(); 7759 uint64_t VTSize = VT.getFixedSizeInBits(); 7760 if (SrcVTSize == VTSize) 7761 continue; 7762 7763 // This stage of the search produces a source with the same element type as 7764 // the original, but with a total width matching the BUILD_VECTOR output. 7765 EVT EltVT = SrcVT.getVectorElementType(); 7766 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits(); 7767 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7768 7769 if (SrcVTSize < VTSize) { 7770 if (2 * SrcVTSize != VTSize) 7771 return SDValue(); 7772 // We can pad out the smaller vector for free, so if it's part of a 7773 // shuffle... 7774 Src.ShuffleVec = 7775 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7776 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7777 continue; 7778 } 7779 7780 if (SrcVTSize != 2 * VTSize) 7781 return SDValue(); 7782 7783 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7784 // Span too large for a VEXT to cope 7785 return SDValue(); 7786 } 7787 7788 if (Src.MinElt >= NumSrcElts) { 7789 // The extraction can just take the second half 7790 Src.ShuffleVec = 7791 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7792 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7793 Src.WindowBase = -NumSrcElts; 7794 } else if (Src.MaxElt < NumSrcElts) { 7795 // The extraction can just take the first half 7796 Src.ShuffleVec = 7797 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7798 DAG.getConstant(0, dl, MVT::i32)); 7799 } else { 7800 // An actual VEXT is needed 7801 SDValue VEXTSrc1 = 7802 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7803 DAG.getConstant(0, dl, MVT::i32)); 7804 SDValue VEXTSrc2 = 7805 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7806 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7807 7808 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7809 VEXTSrc2, 7810 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7811 Src.WindowBase = -Src.MinElt; 7812 } 7813 } 7814 7815 // Another possible incompatibility occurs from the vector element types. We 7816 // can fix this by bitcasting the source vectors to the same type we intend 7817 // for the shuffle. 7818 for (auto &Src : Sources) { 7819 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7820 if (SrcEltTy == SmallestEltTy) 7821 continue; 7822 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7823 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec); 7824 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7825 Src.WindowBase *= Src.WindowScale; 7826 } 7827 7828 // Final sanity check before we try to actually produce a shuffle. 7829 LLVM_DEBUG(for (auto Src 7830 : Sources) 7831 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7832 7833 // The stars all align, our next step is to produce the mask for the shuffle. 7834 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7835 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7836 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7837 SDValue Entry = Op.getOperand(i); 7838 if (Entry.isUndef()) 7839 continue; 7840 7841 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7842 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7843 7844 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7845 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7846 // segment. 7847 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7848 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(), 7849 VT.getScalarSizeInBits()); 7850 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7851 7852 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7853 // starting at the appropriate offset. 7854 int *LaneMask = &Mask[i * ResMultiplier]; 7855 7856 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7857 ExtractBase += NumElts * (Src - Sources.begin()); 7858 for (int j = 0; j < LanesDefined; ++j) 7859 LaneMask[j] = ExtractBase + j; 7860 } 7861 7862 7863 // We can't handle more than two sources. This should have already 7864 // been checked before this point. 7865 assert(Sources.size() <= 2 && "Too many sources!"); 7866 7867 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7868 for (unsigned i = 0; i < Sources.size(); ++i) 7869 ShuffleOps[i] = Sources[i].ShuffleVec; 7870 7871 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7872 ShuffleOps[1], Mask, DAG); 7873 if (!Shuffle) 7874 return SDValue(); 7875 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle); 7876 } 7877 7878 enum ShuffleOpCodes { 7879 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7880 OP_VREV, 7881 OP_VDUP0, 7882 OP_VDUP1, 7883 OP_VDUP2, 7884 OP_VDUP3, 7885 OP_VEXT1, 7886 OP_VEXT2, 7887 OP_VEXT3, 7888 OP_VUZPL, // VUZP, left result 7889 OP_VUZPR, // VUZP, right result 7890 OP_VZIPL, // VZIP, left result 7891 OP_VZIPR, // VZIP, right result 7892 OP_VTRNL, // VTRN, left result 7893 OP_VTRNR // VTRN, right result 7894 }; 7895 7896 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7897 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7898 switch (OpNum) { 7899 case OP_COPY: 7900 case OP_VREV: 7901 case OP_VDUP0: 7902 case OP_VDUP1: 7903 case OP_VDUP2: 7904 case OP_VDUP3: 7905 return true; 7906 } 7907 return false; 7908 } 7909 7910 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7911 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7912 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7913 /// are assumed to be legal. 7914 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7915 if (VT.getVectorNumElements() == 4 && 7916 (VT.is128BitVector() || VT.is64BitVector())) { 7917 unsigned PFIndexes[4]; 7918 for (unsigned i = 0; i != 4; ++i) { 7919 if (M[i] < 0) 7920 PFIndexes[i] = 8; 7921 else 7922 PFIndexes[i] = M[i]; 7923 } 7924 7925 // Compute the index in the perfect shuffle table. 7926 unsigned PFTableIndex = 7927 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7928 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7929 unsigned Cost = (PFEntry >> 30); 7930 7931 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7932 return true; 7933 } 7934 7935 bool ReverseVEXT, isV_UNDEF; 7936 unsigned Imm, WhichResult; 7937 7938 unsigned EltSize = VT.getScalarSizeInBits(); 7939 if (EltSize >= 32 || 7940 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7941 ShuffleVectorInst::isIdentityMask(M) || 7942 isVREVMask(M, VT, 64) || 7943 isVREVMask(M, VT, 32) || 7944 isVREVMask(M, VT, 16)) 7945 return true; 7946 else if (Subtarget->hasNEON() && 7947 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7948 isVTBLMask(M, VT) || 7949 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7950 return true; 7951 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7952 isReverseMask(M, VT)) 7953 return true; 7954 else if (Subtarget->hasMVEIntegerOps() && 7955 (isVMOVNMask(M, VT, true, false) || 7956 isVMOVNMask(M, VT, false, false) || isVMOVNMask(M, VT, true, true))) 7957 return true; 7958 else 7959 return false; 7960 } 7961 7962 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7963 /// the specified operations to build the shuffle. 7964 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7965 SDValue RHS, SelectionDAG &DAG, 7966 const SDLoc &dl) { 7967 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7968 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7969 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7970 7971 if (OpNum == OP_COPY) { 7972 if (LHSID == (1*9+2)*9+3) return LHS; 7973 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7974 return RHS; 7975 } 7976 7977 SDValue OpLHS, OpRHS; 7978 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7979 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7980 EVT VT = OpLHS.getValueType(); 7981 7982 switch (OpNum) { 7983 default: llvm_unreachable("Unknown shuffle opcode!"); 7984 case OP_VREV: 7985 // VREV divides the vector in half and swaps within the half. 7986 if (VT.getVectorElementType() == MVT::i32 || 7987 VT.getVectorElementType() == MVT::f32) 7988 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7989 // vrev <4 x i16> -> VREV32 7990 if (VT.getVectorElementType() == MVT::i16 || 7991 VT.getVectorElementType() == MVT::f16) 7992 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7993 // vrev <4 x i8> -> VREV16 7994 assert(VT.getVectorElementType() == MVT::i8); 7995 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 7996 case OP_VDUP0: 7997 case OP_VDUP1: 7998 case OP_VDUP2: 7999 case OP_VDUP3: 8000 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 8001 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 8002 case OP_VEXT1: 8003 case OP_VEXT2: 8004 case OP_VEXT3: 8005 return DAG.getNode(ARMISD::VEXT, dl, VT, 8006 OpLHS, OpRHS, 8007 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 8008 case OP_VUZPL: 8009 case OP_VUZPR: 8010 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 8011 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 8012 case OP_VZIPL: 8013 case OP_VZIPR: 8014 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 8015 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 8016 case OP_VTRNL: 8017 case OP_VTRNR: 8018 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 8019 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 8020 } 8021 } 8022 8023 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 8024 ArrayRef<int> ShuffleMask, 8025 SelectionDAG &DAG) { 8026 // Check to see if we can use the VTBL instruction. 8027 SDValue V1 = Op.getOperand(0); 8028 SDValue V2 = Op.getOperand(1); 8029 SDLoc DL(Op); 8030 8031 SmallVector<SDValue, 8> VTBLMask; 8032 for (ArrayRef<int>::iterator 8033 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 8034 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 8035 8036 if (V2.getNode()->isUndef()) 8037 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 8038 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8039 8040 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 8041 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8042 } 8043 8044 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 8045 SelectionDAG &DAG) { 8046 SDLoc DL(Op); 8047 SDValue OpLHS = Op.getOperand(0); 8048 EVT VT = OpLHS.getValueType(); 8049 8050 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 8051 "Expect an v8i16/v16i8 type"); 8052 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 8053 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 8054 // extract the first 8 bytes into the top double word and the last 8 bytes 8055 // into the bottom double word. The v8i16 case is similar. 8056 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 8057 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 8058 DAG.getConstant(ExtractNum, DL, MVT::i32)); 8059 } 8060 8061 static EVT getVectorTyFromPredicateVector(EVT VT) { 8062 switch (VT.getSimpleVT().SimpleTy) { 8063 case MVT::v4i1: 8064 return MVT::v4i32; 8065 case MVT::v8i1: 8066 return MVT::v8i16; 8067 case MVT::v16i1: 8068 return MVT::v16i8; 8069 default: 8070 llvm_unreachable("Unexpected vector predicate type"); 8071 } 8072 } 8073 8074 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 8075 SelectionDAG &DAG) { 8076 // Converting from boolean predicates to integers involves creating a vector 8077 // of all ones or all zeroes and selecting the lanes based upon the real 8078 // predicate. 8079 SDValue AllOnes = 8080 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 8081 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 8082 8083 SDValue AllZeroes = 8084 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 8085 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 8086 8087 // Get full vector type from predicate type 8088 EVT NewVT = getVectorTyFromPredicateVector(VT); 8089 8090 SDValue RecastV1; 8091 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 8092 // this to a v16i1. This cannot be done with an ordinary bitcast because the 8093 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 8094 // since we know in hardware the sizes are really the same. 8095 if (VT != MVT::v16i1) 8096 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 8097 else 8098 RecastV1 = Pred; 8099 8100 // Select either all ones or zeroes depending upon the real predicate bits. 8101 SDValue PredAsVector = 8102 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 8103 8104 // Recast our new predicate-as-integer v16i8 vector into something 8105 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 8106 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 8107 } 8108 8109 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 8110 const ARMSubtarget *ST) { 8111 EVT VT = Op.getValueType(); 8112 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8113 ArrayRef<int> ShuffleMask = SVN->getMask(); 8114 8115 assert(ST->hasMVEIntegerOps() && 8116 "No support for vector shuffle of boolean predicates"); 8117 8118 SDValue V1 = Op.getOperand(0); 8119 SDLoc dl(Op); 8120 if (isReverseMask(ShuffleMask, VT)) { 8121 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 8122 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 8123 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 8124 DAG.getConstant(16, dl, MVT::i32)); 8125 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 8126 } 8127 8128 // Until we can come up with optimised cases for every single vector 8129 // shuffle in existence we have chosen the least painful strategy. This is 8130 // to essentially promote the boolean predicate to a 8-bit integer, where 8131 // each predicate represents a byte. Then we fall back on a normal integer 8132 // vector shuffle and convert the result back into a predicate vector. In 8133 // many cases the generated code might be even better than scalar code 8134 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 8135 // fields in a register into 8 other arbitrary 2-bit fields! 8136 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 8137 EVT NewVT = PredAsVector.getValueType(); 8138 8139 // Do the shuffle! 8140 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 8141 DAG.getUNDEF(NewVT), ShuffleMask); 8142 8143 // Now return the result of comparing the shuffled vector with zero, 8144 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8145 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 8146 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8147 } 8148 8149 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op, 8150 ArrayRef<int> ShuffleMask, 8151 SelectionDAG &DAG) { 8152 // Attempt to lower the vector shuffle using as many whole register movs as 8153 // possible. This is useful for types smaller than 32bits, which would 8154 // often otherwise become a series for grp movs. 8155 SDLoc dl(Op); 8156 EVT VT = Op.getValueType(); 8157 if (VT.getScalarSizeInBits() >= 32) 8158 return SDValue(); 8159 8160 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && 8161 "Unexpected vector type"); 8162 int NumElts = VT.getVectorNumElements(); 8163 int QuarterSize = NumElts / 4; 8164 // The four final parts of the vector, as i32's 8165 SDValue Parts[4]; 8166 8167 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not 8168 // <u,u,u,u>), returning the vmov lane index 8169 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) { 8170 // Detect which mov lane this would be from the first non-undef element. 8171 int MovIdx = -1; 8172 for (int i = 0; i < Length; i++) { 8173 if (ShuffleMask[Start + i] >= 0) { 8174 if (ShuffleMask[Start + i] % Length != i) 8175 return -1; 8176 MovIdx = ShuffleMask[Start + i] / Length; 8177 break; 8178 } 8179 } 8180 // If all items are undef, leave this for other combines 8181 if (MovIdx == -1) 8182 return -1; 8183 // Check the remaining values are the correct part of the same mov 8184 for (int i = 1; i < Length; i++) { 8185 if (ShuffleMask[Start + i] >= 0 && 8186 (ShuffleMask[Start + i] / Length != MovIdx || 8187 ShuffleMask[Start + i] % Length != i)) 8188 return -1; 8189 } 8190 return MovIdx; 8191 }; 8192 8193 for (int Part = 0; Part < 4; ++Part) { 8194 // Does this part look like a mov 8195 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize); 8196 if (Elt != -1) { 8197 SDValue Input = Op->getOperand(0); 8198 if (Elt >= 4) { 8199 Input = Op->getOperand(1); 8200 Elt -= 4; 8201 } 8202 SDValue BitCast = DAG.getBitcast(MVT::v4f32, Input); 8203 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, BitCast, 8204 DAG.getConstant(Elt, dl, MVT::i32)); 8205 } 8206 } 8207 8208 // Nothing interesting found, just return 8209 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3]) 8210 return SDValue(); 8211 8212 // The other parts need to be built with the old shuffle vector, cast to a 8213 // v4i32 and extract_vector_elts 8214 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) { 8215 SmallVector<int, 16> NewShuffleMask; 8216 for (int Part = 0; Part < 4; ++Part) 8217 for (int i = 0; i < QuarterSize; i++) 8218 NewShuffleMask.push_back( 8219 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]); 8220 SDValue NewShuffle = DAG.getVectorShuffle( 8221 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask); 8222 SDValue BitCast = DAG.getBitcast(MVT::v4f32, NewShuffle); 8223 8224 for (int Part = 0; Part < 4; ++Part) 8225 if (!Parts[Part]) 8226 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, 8227 BitCast, DAG.getConstant(Part, dl, MVT::i32)); 8228 } 8229 // Build a vector out of the various parts and bitcast it back to the original 8230 // type. 8231 SDValue NewVec = DAG.getNode(ARMISD::BUILD_VECTOR, dl, MVT::v4f32, Parts); 8232 return DAG.getBitcast(VT, NewVec); 8233 } 8234 8235 static SDValue LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op, 8236 ArrayRef<int> ShuffleMask, 8237 SelectionDAG &DAG) { 8238 SDValue V1 = Op.getOperand(0); 8239 SDValue V2 = Op.getOperand(1); 8240 EVT VT = Op.getValueType(); 8241 unsigned NumElts = VT.getVectorNumElements(); 8242 8243 // An One-Off Identity mask is one that is mostly an identity mask from as 8244 // single source but contains a single element out-of-place, either from a 8245 // different vector or from another position in the same vector. As opposed to 8246 // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert 8247 // pair directly. 8248 auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset, 8249 int &OffElement) { 8250 OffElement = -1; 8251 int NonUndef = 0; 8252 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) { 8253 if (Mask[i] == -1) 8254 continue; 8255 NonUndef++; 8256 if (Mask[i] != i + BaseOffset) { 8257 if (OffElement == -1) 8258 OffElement = i; 8259 else 8260 return false; 8261 } 8262 } 8263 return NonUndef > 2 && OffElement != -1; 8264 }; 8265 int OffElement; 8266 SDValue VInput; 8267 if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement)) 8268 VInput = V1; 8269 else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement)) 8270 VInput = V2; 8271 else 8272 return SDValue(); 8273 8274 SDLoc dl(Op); 8275 EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16 8276 ? MVT::i32 8277 : VT.getScalarType(); 8278 SDValue Elt = DAG.getNode( 8279 ISD::EXTRACT_VECTOR_ELT, dl, SVT, 8280 ShuffleMask[OffElement] < (int)NumElts ? V1 : V2, 8281 DAG.getVectorIdxConstant(ShuffleMask[OffElement] % NumElts, dl)); 8282 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, VInput, Elt, 8283 DAG.getVectorIdxConstant(OffElement % NumElts, dl)); 8284 } 8285 8286 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 8287 const ARMSubtarget *ST) { 8288 SDValue V1 = Op.getOperand(0); 8289 SDValue V2 = Op.getOperand(1); 8290 SDLoc dl(Op); 8291 EVT VT = Op.getValueType(); 8292 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8293 unsigned EltSize = VT.getScalarSizeInBits(); 8294 8295 if (ST->hasMVEIntegerOps() && EltSize == 1) 8296 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 8297 8298 // Convert shuffles that are directly supported on NEON to target-specific 8299 // DAG nodes, instead of keeping them as shuffles and matching them again 8300 // during code selection. This is more efficient and avoids the possibility 8301 // of inconsistencies between legalization and selection. 8302 // FIXME: floating-point vectors should be canonicalized to integer vectors 8303 // of the same time so that they get CSEd properly. 8304 ArrayRef<int> ShuffleMask = SVN->getMask(); 8305 8306 if (EltSize <= 32) { 8307 if (SVN->isSplat()) { 8308 int Lane = SVN->getSplatIndex(); 8309 // If this is undef splat, generate it via "just" vdup, if possible. 8310 if (Lane == -1) Lane = 0; 8311 8312 // Test if V1 is a SCALAR_TO_VECTOR. 8313 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 8314 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8315 } 8316 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 8317 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 8318 // reaches it). 8319 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 8320 !isa<ConstantSDNode>(V1.getOperand(0))) { 8321 bool IsScalarToVector = true; 8322 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 8323 if (!V1.getOperand(i).isUndef()) { 8324 IsScalarToVector = false; 8325 break; 8326 } 8327 if (IsScalarToVector) 8328 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8329 } 8330 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 8331 DAG.getConstant(Lane, dl, MVT::i32)); 8332 } 8333 8334 bool ReverseVEXT = false; 8335 unsigned Imm = 0; 8336 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 8337 if (ReverseVEXT) 8338 std::swap(V1, V2); 8339 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 8340 DAG.getConstant(Imm, dl, MVT::i32)); 8341 } 8342 8343 if (isVREVMask(ShuffleMask, VT, 64)) 8344 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 8345 if (isVREVMask(ShuffleMask, VT, 32)) 8346 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 8347 if (isVREVMask(ShuffleMask, VT, 16)) 8348 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 8349 8350 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 8351 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 8352 DAG.getConstant(Imm, dl, MVT::i32)); 8353 } 8354 8355 // Check for Neon shuffles that modify both input vectors in place. 8356 // If both results are used, i.e., if there are two shuffles with the same 8357 // source operands and with masks corresponding to both results of one of 8358 // these operations, DAG memoization will ensure that a single node is 8359 // used for both shuffles. 8360 unsigned WhichResult = 0; 8361 bool isV_UNDEF = false; 8362 if (ST->hasNEON()) { 8363 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8364 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 8365 if (isV_UNDEF) 8366 V2 = V1; 8367 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 8368 .getValue(WhichResult); 8369 } 8370 } 8371 if (ST->hasMVEIntegerOps()) { 8372 if (isVMOVNMask(ShuffleMask, VT, false, false)) 8373 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1, 8374 DAG.getConstant(0, dl, MVT::i32)); 8375 if (isVMOVNMask(ShuffleMask, VT, true, false)) 8376 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2, 8377 DAG.getConstant(1, dl, MVT::i32)); 8378 if (isVMOVNMask(ShuffleMask, VT, true, true)) 8379 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V1, 8380 DAG.getConstant(1, dl, MVT::i32)); 8381 } 8382 8383 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 8384 // shuffles that produce a result larger than their operands with: 8385 // shuffle(concat(v1, undef), concat(v2, undef)) 8386 // -> 8387 // shuffle(concat(v1, v2), undef) 8388 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 8389 // 8390 // This is useful in the general case, but there are special cases where 8391 // native shuffles produce larger results: the two-result ops. 8392 // 8393 // Look through the concat when lowering them: 8394 // shuffle(concat(v1, v2), undef) 8395 // -> 8396 // concat(VZIP(v1, v2):0, :1) 8397 // 8398 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 8399 SDValue SubV1 = V1->getOperand(0); 8400 SDValue SubV2 = V1->getOperand(1); 8401 EVT SubVT = SubV1.getValueType(); 8402 8403 // We expect these to have been canonicalized to -1. 8404 assert(llvm::all_of(ShuffleMask, [&](int i) { 8405 return i < (int)VT.getVectorNumElements(); 8406 }) && "Unexpected shuffle index into UNDEF operand!"); 8407 8408 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8409 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 8410 if (isV_UNDEF) 8411 SubV2 = SubV1; 8412 assert((WhichResult == 0) && 8413 "In-place shuffle of concat can only have one result!"); 8414 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 8415 SubV1, SubV2); 8416 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 8417 Res.getValue(1)); 8418 } 8419 } 8420 } 8421 8422 if (ST->hasMVEIntegerOps() && EltSize <= 32) 8423 if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG)) 8424 return V; 8425 8426 // If the shuffle is not directly supported and it has 4 elements, use 8427 // the PerfectShuffle-generated table to synthesize it from other shuffles. 8428 unsigned NumElts = VT.getVectorNumElements(); 8429 if (NumElts == 4) { 8430 unsigned PFIndexes[4]; 8431 for (unsigned i = 0; i != 4; ++i) { 8432 if (ShuffleMask[i] < 0) 8433 PFIndexes[i] = 8; 8434 else 8435 PFIndexes[i] = ShuffleMask[i]; 8436 } 8437 8438 // Compute the index in the perfect shuffle table. 8439 unsigned PFTableIndex = 8440 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8441 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8442 unsigned Cost = (PFEntry >> 30); 8443 8444 if (Cost <= 4) { 8445 if (ST->hasNEON()) 8446 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8447 else if (isLegalMVEShuffleOp(PFEntry)) { 8448 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8449 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8450 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 8451 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 8452 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 8453 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8454 } 8455 } 8456 } 8457 8458 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 8459 if (EltSize >= 32) { 8460 // Do the expansion with floating-point types, since that is what the VFP 8461 // registers are defined to use, and since i64 is not legal. 8462 EVT EltVT = EVT::getFloatingPointVT(EltSize); 8463 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 8464 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 8465 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 8466 SmallVector<SDValue, 8> Ops; 8467 for (unsigned i = 0; i < NumElts; ++i) { 8468 if (ShuffleMask[i] < 0) 8469 Ops.push_back(DAG.getUNDEF(EltVT)); 8470 else 8471 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 8472 ShuffleMask[i] < (int)NumElts ? V1 : V2, 8473 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 8474 dl, MVT::i32))); 8475 } 8476 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 8477 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8478 } 8479 8480 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 8481 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 8482 8483 if (ST->hasNEON() && VT == MVT::v8i8) 8484 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 8485 return NewOp; 8486 8487 if (ST->hasMVEIntegerOps()) 8488 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG)) 8489 return NewOp; 8490 8491 return SDValue(); 8492 } 8493 8494 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8495 const ARMSubtarget *ST) { 8496 EVT VecVT = Op.getOperand(0).getValueType(); 8497 SDLoc dl(Op); 8498 8499 assert(ST->hasMVEIntegerOps() && 8500 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8501 8502 SDValue Conv = 8503 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8504 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8505 unsigned LaneWidth = 8506 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8507 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 8508 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 8509 Op.getOperand(1), DAG.getValueType(MVT::i1)); 8510 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 8511 DAG.getConstant(~Mask, dl, MVT::i32)); 8512 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 8513 } 8514 8515 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8516 SelectionDAG &DAG) const { 8517 // INSERT_VECTOR_ELT is legal only for immediate indexes. 8518 SDValue Lane = Op.getOperand(2); 8519 if (!isa<ConstantSDNode>(Lane)) 8520 return SDValue(); 8521 8522 SDValue Elt = Op.getOperand(1); 8523 EVT EltVT = Elt.getValueType(); 8524 8525 if (Subtarget->hasMVEIntegerOps() && 8526 Op.getValueType().getScalarSizeInBits() == 1) 8527 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 8528 8529 if (getTypeAction(*DAG.getContext(), EltVT) == 8530 TargetLowering::TypePromoteFloat) { 8531 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 8532 // but the type system will try to do that if we don't intervene. 8533 // Reinterpret any such vector-element insertion as one with the 8534 // corresponding integer types. 8535 8536 SDLoc dl(Op); 8537 8538 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 8539 assert(getTypeAction(*DAG.getContext(), IEltVT) != 8540 TargetLowering::TypePromoteFloat); 8541 8542 SDValue VecIn = Op.getOperand(0); 8543 EVT VecVT = VecIn.getValueType(); 8544 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 8545 VecVT.getVectorNumElements()); 8546 8547 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 8548 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 8549 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 8550 IVecIn, IElt, Lane); 8551 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 8552 } 8553 8554 return Op; 8555 } 8556 8557 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8558 const ARMSubtarget *ST) { 8559 EVT VecVT = Op.getOperand(0).getValueType(); 8560 SDLoc dl(Op); 8561 8562 assert(ST->hasMVEIntegerOps() && 8563 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8564 8565 SDValue Conv = 8566 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8567 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8568 unsigned LaneWidth = 8569 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8570 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 8571 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 8572 return Shift; 8573 } 8574 8575 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 8576 const ARMSubtarget *ST) { 8577 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 8578 SDValue Lane = Op.getOperand(1); 8579 if (!isa<ConstantSDNode>(Lane)) 8580 return SDValue(); 8581 8582 SDValue Vec = Op.getOperand(0); 8583 EVT VT = Vec.getValueType(); 8584 8585 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8586 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 8587 8588 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 8589 SDLoc dl(Op); 8590 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 8591 } 8592 8593 return Op; 8594 } 8595 8596 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 8597 const ARMSubtarget *ST) { 8598 SDValue V1 = Op.getOperand(0); 8599 SDValue V2 = Op.getOperand(1); 8600 SDLoc dl(Op); 8601 EVT VT = Op.getValueType(); 8602 EVT Op1VT = V1.getValueType(); 8603 EVT Op2VT = V2.getValueType(); 8604 unsigned NumElts = VT.getVectorNumElements(); 8605 8606 assert(Op1VT == Op2VT && "Operand types don't match!"); 8607 assert(VT.getScalarSizeInBits() == 1 && 8608 "Unexpected custom CONCAT_VECTORS lowering"); 8609 assert(ST->hasMVEIntegerOps() && 8610 "CONCAT_VECTORS lowering only supported for MVE"); 8611 8612 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8613 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 8614 8615 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 8616 // promoted to v8i16, etc. 8617 8618 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8619 8620 // Extract the vector elements from Op1 and Op2 one by one and truncate them 8621 // to be the right size for the destination. For example, if Op1 is v4i1 then 8622 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 8623 // which when promoted is v8i16. That means each i32 element from Op1 needs 8624 // truncating to i16 and inserting in the result. 8625 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 8626 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 8627 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 8628 EVT NewVT = NewV.getValueType(); 8629 EVT ConcatVT = ConVec.getValueType(); 8630 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 8631 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 8632 DAG.getIntPtrConstant(i, dl)); 8633 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 8634 DAG.getConstant(j, dl, MVT::i32)); 8635 } 8636 return ConVec; 8637 }; 8638 unsigned j = 0; 8639 ConVec = ExractInto(NewV1, ConVec, j); 8640 ConVec = ExractInto(NewV2, ConVec, j); 8641 8642 // Now return the result of comparing the subvector with zero, 8643 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8644 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 8645 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8646 } 8647 8648 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 8649 const ARMSubtarget *ST) { 8650 EVT VT = Op->getValueType(0); 8651 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8652 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 8653 8654 // The only time a CONCAT_VECTORS operation can have legal types is when 8655 // two 64-bit vectors are concatenated to a 128-bit vector. 8656 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 8657 "unexpected CONCAT_VECTORS"); 8658 SDLoc dl(Op); 8659 SDValue Val = DAG.getUNDEF(MVT::v2f64); 8660 SDValue Op0 = Op.getOperand(0); 8661 SDValue Op1 = Op.getOperand(1); 8662 if (!Op0.isUndef()) 8663 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8664 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 8665 DAG.getIntPtrConstant(0, dl)); 8666 if (!Op1.isUndef()) 8667 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8668 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 8669 DAG.getIntPtrConstant(1, dl)); 8670 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 8671 } 8672 8673 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 8674 const ARMSubtarget *ST) { 8675 SDValue V1 = Op.getOperand(0); 8676 SDValue V2 = Op.getOperand(1); 8677 SDLoc dl(Op); 8678 EVT VT = Op.getValueType(); 8679 EVT Op1VT = V1.getValueType(); 8680 unsigned NumElts = VT.getVectorNumElements(); 8681 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 8682 8683 assert(VT.getScalarSizeInBits() == 1 && 8684 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 8685 assert(ST->hasMVEIntegerOps() && 8686 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 8687 8688 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8689 8690 // We now have Op1 promoted to a vector of integers, where v8i1 gets 8691 // promoted to v8i16, etc. 8692 8693 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8694 8695 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 8696 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 8697 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 8698 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 8699 DAG.getIntPtrConstant(i, dl)); 8700 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 8701 DAG.getConstant(j, dl, MVT::i32)); 8702 } 8703 8704 // Now return the result of comparing the subvector with zero, 8705 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8706 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 8707 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8708 } 8709 8710 // Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0). 8711 static SDValue LowerTruncatei1(SDValue N, SelectionDAG &DAG, 8712 const ARMSubtarget *ST) { 8713 assert(ST->hasMVEIntegerOps() && "Expected MVE!"); 8714 EVT VT = N.getValueType(); 8715 assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) && 8716 "Expected a vector i1 type!"); 8717 SDValue Op = N.getOperand(0); 8718 EVT FromVT = Op.getValueType(); 8719 SDLoc DL(N); 8720 8721 SDValue And = 8722 DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT)); 8723 return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT), 8724 DAG.getCondCode(ISD::SETNE)); 8725 } 8726 8727 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 8728 /// element has been zero/sign-extended, depending on the isSigned parameter, 8729 /// from an integer type half its size. 8730 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 8731 bool isSigned) { 8732 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 8733 EVT VT = N->getValueType(0); 8734 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 8735 SDNode *BVN = N->getOperand(0).getNode(); 8736 if (BVN->getValueType(0) != MVT::v4i32 || 8737 BVN->getOpcode() != ISD::BUILD_VECTOR) 8738 return false; 8739 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8740 unsigned HiElt = 1 - LoElt; 8741 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 8742 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 8743 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 8744 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 8745 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 8746 return false; 8747 if (isSigned) { 8748 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 8749 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 8750 return true; 8751 } else { 8752 if (Hi0->isNullValue() && Hi1->isNullValue()) 8753 return true; 8754 } 8755 return false; 8756 } 8757 8758 if (N->getOpcode() != ISD::BUILD_VECTOR) 8759 return false; 8760 8761 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8762 SDNode *Elt = N->getOperand(i).getNode(); 8763 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8764 unsigned EltSize = VT.getScalarSizeInBits(); 8765 unsigned HalfSize = EltSize / 2; 8766 if (isSigned) { 8767 if (!isIntN(HalfSize, C->getSExtValue())) 8768 return false; 8769 } else { 8770 if (!isUIntN(HalfSize, C->getZExtValue())) 8771 return false; 8772 } 8773 continue; 8774 } 8775 return false; 8776 } 8777 8778 return true; 8779 } 8780 8781 /// isSignExtended - Check if a node is a vector value that is sign-extended 8782 /// or a constant BUILD_VECTOR with sign-extended elements. 8783 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8784 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8785 return true; 8786 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8787 return true; 8788 return false; 8789 } 8790 8791 /// isZeroExtended - Check if a node is a vector value that is zero-extended (or 8792 /// any-extended) or a constant BUILD_VECTOR with zero-extended elements. 8793 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8794 if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND || 8795 ISD::isZEXTLoad(N)) 8796 return true; 8797 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8798 return true; 8799 return false; 8800 } 8801 8802 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8803 if (OrigVT.getSizeInBits() >= 64) 8804 return OrigVT; 8805 8806 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8807 8808 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8809 switch (OrigSimpleTy) { 8810 default: llvm_unreachable("Unexpected Vector Type"); 8811 case MVT::v2i8: 8812 case MVT::v2i16: 8813 return MVT::v2i32; 8814 case MVT::v4i8: 8815 return MVT::v4i16; 8816 } 8817 } 8818 8819 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8820 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8821 /// We insert the required extension here to get the vector to fill a D register. 8822 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8823 const EVT &OrigTy, 8824 const EVT &ExtTy, 8825 unsigned ExtOpcode) { 8826 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8827 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8828 // 64-bits we need to insert a new extension so that it will be 64-bits. 8829 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8830 if (OrigTy.getSizeInBits() >= 64) 8831 return N; 8832 8833 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8834 EVT NewVT = getExtensionTo64Bits(OrigTy); 8835 8836 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8837 } 8838 8839 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8840 /// does not do any sign/zero extension. If the original vector is less 8841 /// than 64 bits, an appropriate extension will be added after the load to 8842 /// reach a total size of 64 bits. We have to add the extension separately 8843 /// because ARM does not have a sign/zero extending load for vectors. 8844 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8845 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8846 8847 // The load already has the right type. 8848 if (ExtendedTy == LD->getMemoryVT()) 8849 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8850 LD->getBasePtr(), LD->getPointerInfo(), 8851 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8852 8853 // We need to create a zextload/sextload. We cannot just create a load 8854 // followed by a zext/zext node because LowerMUL is also run during normal 8855 // operation legalization where we can't create illegal types. 8856 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8857 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8858 LD->getMemoryVT(), LD->getAlignment(), 8859 LD->getMemOperand()->getFlags()); 8860 } 8861 8862 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8863 /// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return 8864 /// the unextended value. The unextended vector should be 64 bits so that it can 8865 /// be used as an operand to a VMULL instruction. If the original vector size 8866 /// before extension is less than 64 bits we add a an extension to resize 8867 /// the vector to 64 bits. 8868 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8869 if (N->getOpcode() == ISD::SIGN_EXTEND || 8870 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND) 8871 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8872 N->getOperand(0)->getValueType(0), 8873 N->getValueType(0), 8874 N->getOpcode()); 8875 8876 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8877 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8878 "Expected extending load"); 8879 8880 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8881 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8882 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8883 SDValue extLoad = 8884 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8885 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8886 8887 return newLoad; 8888 } 8889 8890 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8891 // have been legalized as a BITCAST from v4i32. 8892 if (N->getOpcode() == ISD::BITCAST) { 8893 SDNode *BVN = N->getOperand(0).getNode(); 8894 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8895 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8896 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8897 return DAG.getBuildVector( 8898 MVT::v2i32, SDLoc(N), 8899 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8900 } 8901 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8902 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8903 EVT VT = N->getValueType(0); 8904 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8905 unsigned NumElts = VT.getVectorNumElements(); 8906 MVT TruncVT = MVT::getIntegerVT(EltSize); 8907 SmallVector<SDValue, 8> Ops; 8908 SDLoc dl(N); 8909 for (unsigned i = 0; i != NumElts; ++i) { 8910 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8911 const APInt &CInt = C->getAPIntValue(); 8912 // Element types smaller than 32 bits are not legal, so use i32 elements. 8913 // The values are implicitly truncated so sext vs. zext doesn't matter. 8914 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8915 } 8916 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8917 } 8918 8919 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8920 unsigned Opcode = N->getOpcode(); 8921 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8922 SDNode *N0 = N->getOperand(0).getNode(); 8923 SDNode *N1 = N->getOperand(1).getNode(); 8924 return N0->hasOneUse() && N1->hasOneUse() && 8925 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8926 } 8927 return false; 8928 } 8929 8930 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8931 unsigned Opcode = N->getOpcode(); 8932 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8933 SDNode *N0 = N->getOperand(0).getNode(); 8934 SDNode *N1 = N->getOperand(1).getNode(); 8935 return N0->hasOneUse() && N1->hasOneUse() && 8936 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8937 } 8938 return false; 8939 } 8940 8941 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8942 // Multiplications are only custom-lowered for 128-bit vectors so that 8943 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8944 EVT VT = Op.getValueType(); 8945 assert(VT.is128BitVector() && VT.isInteger() && 8946 "unexpected type for custom-lowering ISD::MUL"); 8947 SDNode *N0 = Op.getOperand(0).getNode(); 8948 SDNode *N1 = Op.getOperand(1).getNode(); 8949 unsigned NewOpc = 0; 8950 bool isMLA = false; 8951 bool isN0SExt = isSignExtended(N0, DAG); 8952 bool isN1SExt = isSignExtended(N1, DAG); 8953 if (isN0SExt && isN1SExt) 8954 NewOpc = ARMISD::VMULLs; 8955 else { 8956 bool isN0ZExt = isZeroExtended(N0, DAG); 8957 bool isN1ZExt = isZeroExtended(N1, DAG); 8958 if (isN0ZExt && isN1ZExt) 8959 NewOpc = ARMISD::VMULLu; 8960 else if (isN1SExt || isN1ZExt) { 8961 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8962 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8963 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8964 NewOpc = ARMISD::VMULLs; 8965 isMLA = true; 8966 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8967 NewOpc = ARMISD::VMULLu; 8968 isMLA = true; 8969 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8970 std::swap(N0, N1); 8971 NewOpc = ARMISD::VMULLu; 8972 isMLA = true; 8973 } 8974 } 8975 8976 if (!NewOpc) { 8977 if (VT == MVT::v2i64) 8978 // Fall through to expand this. It is not legal. 8979 return SDValue(); 8980 else 8981 // Other vector multiplications are legal. 8982 return Op; 8983 } 8984 } 8985 8986 // Legalize to a VMULL instruction. 8987 SDLoc DL(Op); 8988 SDValue Op0; 8989 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8990 if (!isMLA) { 8991 Op0 = SkipExtensionForVMULL(N0, DAG); 8992 assert(Op0.getValueType().is64BitVector() && 8993 Op1.getValueType().is64BitVector() && 8994 "unexpected types for extended operands to VMULL"); 8995 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8996 } 8997 8998 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8999 // isel lowering to take advantage of no-stall back to back vmul + vmla. 9000 // vmull q0, d4, d6 9001 // vmlal q0, d5, d6 9002 // is faster than 9003 // vaddl q0, d4, d5 9004 // vmovl q1, d6 9005 // vmul q0, q0, q1 9006 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 9007 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 9008 EVT Op1VT = Op1.getValueType(); 9009 return DAG.getNode(N0->getOpcode(), DL, VT, 9010 DAG.getNode(NewOpc, DL, VT, 9011 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 9012 DAG.getNode(NewOpc, DL, VT, 9013 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 9014 } 9015 9016 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 9017 SelectionDAG &DAG) { 9018 // TODO: Should this propagate fast-math-flags? 9019 9020 // Convert to float 9021 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 9022 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 9023 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 9024 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 9025 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 9026 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 9027 // Get reciprocal estimate. 9028 // float4 recip = vrecpeq_f32(yf); 9029 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9030 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 9031 Y); 9032 // Because char has a smaller range than uchar, we can actually get away 9033 // without any newton steps. This requires that we use a weird bias 9034 // of 0xb000, however (again, this has been exhaustively tested). 9035 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 9036 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 9037 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 9038 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 9039 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 9040 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 9041 // Convert back to short. 9042 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 9043 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 9044 return X; 9045 } 9046 9047 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 9048 SelectionDAG &DAG) { 9049 // TODO: Should this propagate fast-math-flags? 9050 9051 SDValue N2; 9052 // Convert to float. 9053 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 9054 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 9055 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 9056 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 9057 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 9058 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 9059 9060 // Use reciprocal estimate and one refinement step. 9061 // float4 recip = vrecpeq_f32(yf); 9062 // recip *= vrecpsq_f32(yf, recip); 9063 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9064 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 9065 N1); 9066 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9067 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9068 N1, N2); 9069 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9070 // Because short has a smaller range than ushort, we can actually get away 9071 // with only a single newton step. This requires that we use a weird bias 9072 // of 89, however (again, this has been exhaustively tested). 9073 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 9074 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9075 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9076 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 9077 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9078 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9079 // Convert back to integer and return. 9080 // return vmovn_s32(vcvt_s32_f32(result)); 9081 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9082 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9083 return N0; 9084 } 9085 9086 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 9087 const ARMSubtarget *ST) { 9088 EVT VT = Op.getValueType(); 9089 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9090 "unexpected type for custom-lowering ISD::SDIV"); 9091 9092 SDLoc dl(Op); 9093 SDValue N0 = Op.getOperand(0); 9094 SDValue N1 = Op.getOperand(1); 9095 SDValue N2, N3; 9096 9097 if (VT == MVT::v8i8) { 9098 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 9099 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 9100 9101 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9102 DAG.getIntPtrConstant(4, dl)); 9103 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9104 DAG.getIntPtrConstant(4, dl)); 9105 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9106 DAG.getIntPtrConstant(0, dl)); 9107 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9108 DAG.getIntPtrConstant(0, dl)); 9109 9110 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 9111 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 9112 9113 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9114 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9115 9116 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 9117 return N0; 9118 } 9119 return LowerSDIV_v4i16(N0, N1, dl, DAG); 9120 } 9121 9122 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 9123 const ARMSubtarget *ST) { 9124 // TODO: Should this propagate fast-math-flags? 9125 EVT VT = Op.getValueType(); 9126 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9127 "unexpected type for custom-lowering ISD::UDIV"); 9128 9129 SDLoc dl(Op); 9130 SDValue N0 = Op.getOperand(0); 9131 SDValue N1 = Op.getOperand(1); 9132 SDValue N2, N3; 9133 9134 if (VT == MVT::v8i8) { 9135 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 9136 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 9137 9138 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9139 DAG.getIntPtrConstant(4, dl)); 9140 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9141 DAG.getIntPtrConstant(4, dl)); 9142 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9143 DAG.getIntPtrConstant(0, dl)); 9144 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9145 DAG.getIntPtrConstant(0, dl)); 9146 9147 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 9148 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 9149 9150 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9151 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9152 9153 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 9154 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 9155 MVT::i32), 9156 N0); 9157 return N0; 9158 } 9159 9160 // v4i16 sdiv ... Convert to float. 9161 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 9162 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 9163 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 9164 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 9165 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 9166 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 9167 9168 // Use reciprocal estimate and two refinement steps. 9169 // float4 recip = vrecpeq_f32(yf); 9170 // recip *= vrecpsq_f32(yf, recip); 9171 // recip *= vrecpsq_f32(yf, recip); 9172 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9173 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 9174 BN1); 9175 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9176 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9177 BN1, N2); 9178 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9179 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9180 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9181 BN1, N2); 9182 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9183 // Simply multiplying by the reciprocal estimate can leave us a few ulps 9184 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 9185 // and that it will never cause us to return an answer too large). 9186 // float4 result = as_float4(as_int4(xf*recip) + 2); 9187 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9188 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9189 N1 = DAG.getConstant(2, dl, MVT::v4i32); 9190 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9191 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9192 // Convert back to integer and return. 9193 // return vmovn_u32(vcvt_s32_f32(result)); 9194 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9195 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9196 return N0; 9197 } 9198 9199 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 9200 SDNode *N = Op.getNode(); 9201 EVT VT = N->getValueType(0); 9202 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 9203 9204 SDValue Carry = Op.getOperand(2); 9205 9206 SDLoc DL(Op); 9207 9208 SDValue Result; 9209 if (Op.getOpcode() == ISD::ADDCARRY) { 9210 // This converts the boolean value carry into the carry flag. 9211 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9212 9213 // Do the addition proper using the carry flag we wanted. 9214 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 9215 Op.getOperand(1), Carry); 9216 9217 // Now convert the carry flag into a boolean value. 9218 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9219 } else { 9220 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 9221 // have to invert the carry first. 9222 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9223 DAG.getConstant(1, DL, MVT::i32), Carry); 9224 // This converts the boolean value carry into the carry flag. 9225 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9226 9227 // Do the subtraction proper using the carry flag we wanted. 9228 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 9229 Op.getOperand(1), Carry); 9230 9231 // Now convert the carry flag into a boolean value. 9232 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9233 // But the carry returned by ARMISD::SUBE is not a borrow as expected 9234 // by ISD::SUBCARRY, so compute 1 - C. 9235 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9236 DAG.getConstant(1, DL, MVT::i32), Carry); 9237 } 9238 9239 // Return both values. 9240 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 9241 } 9242 9243 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 9244 assert(Subtarget->isTargetDarwin()); 9245 9246 // For iOS, we want to call an alternative entry point: __sincos_stret, 9247 // return values are passed via sret. 9248 SDLoc dl(Op); 9249 SDValue Arg = Op.getOperand(0); 9250 EVT ArgVT = Arg.getValueType(); 9251 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 9252 auto PtrVT = getPointerTy(DAG.getDataLayout()); 9253 9254 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9255 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9256 9257 // Pair of floats / doubles used to pass the result. 9258 Type *RetTy = StructType::get(ArgTy, ArgTy); 9259 auto &DL = DAG.getDataLayout(); 9260 9261 ArgListTy Args; 9262 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 9263 SDValue SRet; 9264 if (ShouldUseSRet) { 9265 // Create stack object for sret. 9266 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 9267 const Align StackAlign = DL.getPrefTypeAlign(RetTy); 9268 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 9269 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 9270 9271 ArgListEntry Entry; 9272 Entry.Node = SRet; 9273 Entry.Ty = RetTy->getPointerTo(); 9274 Entry.IsSExt = false; 9275 Entry.IsZExt = false; 9276 Entry.IsSRet = true; 9277 Args.push_back(Entry); 9278 RetTy = Type::getVoidTy(*DAG.getContext()); 9279 } 9280 9281 ArgListEntry Entry; 9282 Entry.Node = Arg; 9283 Entry.Ty = ArgTy; 9284 Entry.IsSExt = false; 9285 Entry.IsZExt = false; 9286 Args.push_back(Entry); 9287 9288 RTLIB::Libcall LC = 9289 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 9290 const char *LibcallName = getLibcallName(LC); 9291 CallingConv::ID CC = getLibcallCallingConv(LC); 9292 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 9293 9294 TargetLowering::CallLoweringInfo CLI(DAG); 9295 CLI.setDebugLoc(dl) 9296 .setChain(DAG.getEntryNode()) 9297 .setCallee(CC, RetTy, Callee, std::move(Args)) 9298 .setDiscardResult(ShouldUseSRet); 9299 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 9300 9301 if (!ShouldUseSRet) 9302 return CallResult.first; 9303 9304 SDValue LoadSin = 9305 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 9306 9307 // Address of cos field. 9308 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 9309 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 9310 SDValue LoadCos = 9311 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 9312 9313 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 9314 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 9315 LoadSin.getValue(0), LoadCos.getValue(0)); 9316 } 9317 9318 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 9319 bool Signed, 9320 SDValue &Chain) const { 9321 EVT VT = Op.getValueType(); 9322 assert((VT == MVT::i32 || VT == MVT::i64) && 9323 "unexpected type for custom lowering DIV"); 9324 SDLoc dl(Op); 9325 9326 const auto &DL = DAG.getDataLayout(); 9327 const auto &TLI = DAG.getTargetLoweringInfo(); 9328 9329 const char *Name = nullptr; 9330 if (Signed) 9331 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 9332 else 9333 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 9334 9335 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 9336 9337 ARMTargetLowering::ArgListTy Args; 9338 9339 for (auto AI : {1, 0}) { 9340 ArgListEntry Arg; 9341 Arg.Node = Op.getOperand(AI); 9342 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 9343 Args.push_back(Arg); 9344 } 9345 9346 CallLoweringInfo CLI(DAG); 9347 CLI.setDebugLoc(dl) 9348 .setChain(Chain) 9349 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 9350 ES, std::move(Args)); 9351 9352 return LowerCallTo(CLI).first; 9353 } 9354 9355 // This is a code size optimisation: return the original SDIV node to 9356 // DAGCombiner when we don't want to expand SDIV into a sequence of 9357 // instructions, and an empty node otherwise which will cause the 9358 // SDIV to be expanded in DAGCombine. 9359 SDValue 9360 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 9361 SelectionDAG &DAG, 9362 SmallVectorImpl<SDNode *> &Created) const { 9363 // TODO: Support SREM 9364 if (N->getOpcode() != ISD::SDIV) 9365 return SDValue(); 9366 9367 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 9368 const bool MinSize = ST.hasMinSize(); 9369 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 9370 : ST.hasDivideInARMMode(); 9371 9372 // Don't touch vector types; rewriting this may lead to scalarizing 9373 // the int divs. 9374 if (N->getOperand(0).getValueType().isVector()) 9375 return SDValue(); 9376 9377 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 9378 // hwdiv support for this to be really profitable. 9379 if (!(MinSize && HasDivide)) 9380 return SDValue(); 9381 9382 // ARM mode is a bit simpler than Thumb: we can handle large power 9383 // of 2 immediates with 1 mov instruction; no further checks required, 9384 // just return the sdiv node. 9385 if (!ST.isThumb()) 9386 return SDValue(N, 0); 9387 9388 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 9389 // and thus lose the code size benefits of a MOVS that requires only 2. 9390 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 9391 // but as it's doing exactly this, it's not worth the trouble to get TTI. 9392 if (Divisor.sgt(128)) 9393 return SDValue(); 9394 9395 return SDValue(N, 0); 9396 } 9397 9398 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 9399 bool Signed) const { 9400 assert(Op.getValueType() == MVT::i32 && 9401 "unexpected type for custom lowering DIV"); 9402 SDLoc dl(Op); 9403 9404 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 9405 DAG.getEntryNode(), Op.getOperand(1)); 9406 9407 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9408 } 9409 9410 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 9411 SDLoc DL(N); 9412 SDValue Op = N->getOperand(1); 9413 if (N->getValueType(0) == MVT::i32) 9414 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 9415 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9416 DAG.getConstant(0, DL, MVT::i32)); 9417 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9418 DAG.getConstant(1, DL, MVT::i32)); 9419 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 9420 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 9421 } 9422 9423 void ARMTargetLowering::ExpandDIV_Windows( 9424 SDValue Op, SelectionDAG &DAG, bool Signed, 9425 SmallVectorImpl<SDValue> &Results) const { 9426 const auto &DL = DAG.getDataLayout(); 9427 const auto &TLI = DAG.getTargetLoweringInfo(); 9428 9429 assert(Op.getValueType() == MVT::i64 && 9430 "unexpected type for custom lowering DIV"); 9431 SDLoc dl(Op); 9432 9433 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 9434 9435 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9436 9437 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 9438 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 9439 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 9440 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 9441 9442 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper)); 9443 } 9444 9445 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) { 9446 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode()); 9447 EVT MemVT = LD->getMemoryVT(); 9448 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9449 "Expected a predicate type!"); 9450 assert(MemVT == Op.getValueType()); 9451 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && 9452 "Expected a non-extending load"); 9453 assert(LD->isUnindexed() && "Expected a unindexed load"); 9454 9455 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit 9456 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We 9457 // need to make sure that 8/4 bits are actually loaded into the correct 9458 // place, which means loading the value and then shuffling the values into 9459 // the bottom bits of the predicate. 9460 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect 9461 // for BE). 9462 // Speaking of BE, apparently the rest of llvm will assume a reverse order to 9463 // a natural VMSR(load), so needs to be reversed. 9464 9465 SDLoc dl(Op); 9466 SDValue Load = DAG.getExtLoad( 9467 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(), 9468 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9469 LD->getMemOperand()); 9470 SDValue Val = Load; 9471 if (DAG.getDataLayout().isBigEndian()) 9472 Val = DAG.getNode(ISD::SRL, dl, MVT::i32, 9473 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Load), 9474 DAG.getConstant(32 - MemVT.getSizeInBits(), dl, MVT::i32)); 9475 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Val); 9476 if (MemVT != MVT::v16i1) 9477 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred, 9478 DAG.getConstant(0, dl, MVT::i32)); 9479 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl); 9480 } 9481 9482 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results, 9483 SelectionDAG &DAG) const { 9484 LoadSDNode *LD = cast<LoadSDNode>(N); 9485 EVT MemVT = LD->getMemoryVT(); 9486 assert(LD->isUnindexed() && "Loads should be unindexed at this point."); 9487 9488 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9489 !Subtarget->isThumb1Only() && LD->isVolatile()) { 9490 SDLoc dl(N); 9491 SDValue Result = DAG.getMemIntrinsicNode( 9492 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}), 9493 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand()); 9494 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1); 9495 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0); 9496 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 9497 Results.append({Pair, Result.getValue(2)}); 9498 } 9499 } 9500 9501 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) { 9502 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9503 EVT MemVT = ST->getMemoryVT(); 9504 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9505 "Expected a predicate type!"); 9506 assert(MemVT == ST->getValue().getValueType()); 9507 assert(!ST->isTruncatingStore() && "Expected a non-extending store"); 9508 assert(ST->isUnindexed() && "Expected a unindexed store"); 9509 9510 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits 9511 // unset and a scalar store. 9512 SDLoc dl(Op); 9513 SDValue Build = ST->getValue(); 9514 if (MemVT != MVT::v16i1) { 9515 SmallVector<SDValue, 16> Ops; 9516 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) { 9517 unsigned Elt = DAG.getDataLayout().isBigEndian() 9518 ? MemVT.getVectorNumElements() - I - 1 9519 : I; 9520 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build, 9521 DAG.getConstant(Elt, dl, MVT::i32))); 9522 } 9523 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++) 9524 Ops.push_back(DAG.getUNDEF(MVT::i32)); 9525 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops); 9526 } 9527 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build); 9528 if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian()) 9529 GRP = DAG.getNode(ISD::SRL, dl, MVT::i32, 9530 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, GRP), 9531 DAG.getConstant(16, dl, MVT::i32)); 9532 return DAG.getTruncStore( 9533 ST->getChain(), dl, GRP, ST->getBasePtr(), 9534 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9535 ST->getMemOperand()); 9536 } 9537 9538 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG, 9539 const ARMSubtarget *Subtarget) { 9540 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9541 EVT MemVT = ST->getMemoryVT(); 9542 assert(ST->isUnindexed() && "Stores should be unindexed at this point."); 9543 9544 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9545 !Subtarget->isThumb1Only() && ST->isVolatile()) { 9546 SDNode *N = Op.getNode(); 9547 SDLoc dl(N); 9548 9549 SDValue Lo = DAG.getNode( 9550 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9551 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl, 9552 MVT::i32)); 9553 SDValue Hi = DAG.getNode( 9554 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9555 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl, 9556 MVT::i32)); 9557 9558 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other), 9559 {ST->getChain(), Lo, Hi, ST->getBasePtr()}, 9560 MemVT, ST->getMemOperand()); 9561 } else if (Subtarget->hasMVEIntegerOps() && 9562 ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || 9563 MemVT == MVT::v16i1))) { 9564 return LowerPredicateStore(Op, DAG); 9565 } 9566 9567 return SDValue(); 9568 } 9569 9570 static bool isZeroVector(SDValue N) { 9571 return (ISD::isBuildVectorAllZeros(N.getNode()) || 9572 (N->getOpcode() == ARMISD::VMOVIMM && 9573 isNullConstant(N->getOperand(0)))); 9574 } 9575 9576 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) { 9577 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode()); 9578 MVT VT = Op.getSimpleValueType(); 9579 SDValue Mask = N->getMask(); 9580 SDValue PassThru = N->getPassThru(); 9581 SDLoc dl(Op); 9582 9583 if (isZeroVector(PassThru)) 9584 return Op; 9585 9586 // MVE Masked loads use zero as the passthru value. Here we convert undef to 9587 // zero too, and other values are lowered to a select. 9588 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 9589 DAG.getTargetConstant(0, dl, MVT::i32)); 9590 SDValue NewLoad = DAG.getMaskedLoad( 9591 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec, 9592 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(), 9593 N->getExtensionType(), N->isExpandingLoad()); 9594 SDValue Combo = NewLoad; 9595 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST || 9596 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) && 9597 isZeroVector(PassThru->getOperand(0)); 9598 if (!PassThru.isUndef() && !PassThruIsCastZero) 9599 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru); 9600 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl); 9601 } 9602 9603 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG, 9604 const ARMSubtarget *ST) { 9605 if (!ST->hasMVEIntegerOps()) 9606 return SDValue(); 9607 9608 SDLoc dl(Op); 9609 unsigned BaseOpcode = 0; 9610 switch (Op->getOpcode()) { 9611 default: llvm_unreachable("Expected VECREDUCE opcode"); 9612 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break; 9613 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break; 9614 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break; 9615 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break; 9616 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break; 9617 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break; 9618 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break; 9619 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break; 9620 } 9621 9622 SDValue Op0 = Op->getOperand(0); 9623 EVT VT = Op0.getValueType(); 9624 EVT EltVT = VT.getVectorElementType(); 9625 unsigned NumElts = VT.getVectorNumElements(); 9626 unsigned NumActiveLanes = NumElts; 9627 9628 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || 9629 NumActiveLanes == 2) && 9630 "Only expected a power 2 vector size"); 9631 9632 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements 9633 // allows us to easily extract vector elements from the lanes. 9634 while (NumActiveLanes > 4) { 9635 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32; 9636 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0); 9637 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev); 9638 NumActiveLanes /= 2; 9639 } 9640 9641 SDValue Res; 9642 if (NumActiveLanes == 4) { 9643 // The remaining 4 elements are summed sequentially 9644 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9645 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32)); 9646 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9647 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32)); 9648 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9649 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32)); 9650 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9651 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32)); 9652 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9653 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags()); 9654 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags()); 9655 } else { 9656 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9657 DAG.getConstant(0, dl, MVT::i32)); 9658 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9659 DAG.getConstant(1, dl, MVT::i32)); 9660 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9661 } 9662 9663 // Result type may be wider than element type. 9664 if (EltVT != Op->getValueType(0)) 9665 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res); 9666 return Res; 9667 } 9668 9669 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG, 9670 const ARMSubtarget *ST) { 9671 if (!ST->hasMVEFloatOps()) 9672 return SDValue(); 9673 return LowerVecReduce(Op, DAG, ST); 9674 } 9675 9676 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 9677 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 9678 // Acquire/Release load/store is not legal for targets without a dmb or 9679 // equivalent available. 9680 return SDValue(); 9681 9682 // Monotonic load/store is legal for all targets. 9683 return Op; 9684 } 9685 9686 static void ReplaceREADCYCLECOUNTER(SDNode *N, 9687 SmallVectorImpl<SDValue> &Results, 9688 SelectionDAG &DAG, 9689 const ARMSubtarget *Subtarget) { 9690 SDLoc DL(N); 9691 // Under Power Management extensions, the cycle-count is: 9692 // mrc p15, #0, <Rt>, c9, c13, #0 9693 SDValue Ops[] = { N->getOperand(0), // Chain 9694 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 9695 DAG.getTargetConstant(15, DL, MVT::i32), 9696 DAG.getTargetConstant(0, DL, MVT::i32), 9697 DAG.getTargetConstant(9, DL, MVT::i32), 9698 DAG.getTargetConstant(13, DL, MVT::i32), 9699 DAG.getTargetConstant(0, DL, MVT::i32) 9700 }; 9701 9702 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 9703 DAG.getVTList(MVT::i32, MVT::Other), Ops); 9704 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 9705 DAG.getConstant(0, DL, MVT::i32))); 9706 Results.push_back(Cycles32.getValue(1)); 9707 } 9708 9709 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 9710 SDLoc dl(V.getNode()); 9711 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 9712 SDValue VHi = DAG.getAnyExtOrTrunc( 9713 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 9714 dl, MVT::i32); 9715 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9716 if (isBigEndian) 9717 std::swap (VLo, VHi); 9718 SDValue RegClass = 9719 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 9720 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 9721 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 9722 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 9723 return SDValue( 9724 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 9725 } 9726 9727 static void ReplaceCMP_SWAP_64Results(SDNode *N, 9728 SmallVectorImpl<SDValue> & Results, 9729 SelectionDAG &DAG) { 9730 assert(N->getValueType(0) == MVT::i64 && 9731 "AtomicCmpSwap on types less than 64 should be legal"); 9732 SDValue Ops[] = {N->getOperand(1), 9733 createGPRPairNode(DAG, N->getOperand(2)), 9734 createGPRPairNode(DAG, N->getOperand(3)), 9735 N->getOperand(0)}; 9736 SDNode *CmpSwap = DAG.getMachineNode( 9737 ARM::CMP_SWAP_64, SDLoc(N), 9738 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 9739 9740 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 9741 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 9742 9743 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9744 9745 SDValue Lo = 9746 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 9747 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9748 SDValue Hi = 9749 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 9750 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9751 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi)); 9752 Results.push_back(SDValue(CmpSwap, 2)); 9753 } 9754 9755 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const { 9756 SDLoc dl(Op); 9757 EVT VT = Op.getValueType(); 9758 SDValue Chain = Op.getOperand(0); 9759 SDValue LHS = Op.getOperand(1); 9760 SDValue RHS = Op.getOperand(2); 9761 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get(); 9762 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 9763 9764 // If we don't have instructions of this float type then soften to a libcall 9765 // and use SETCC instead. 9766 if (isUnsupportedFloatingType(LHS.getValueType())) { 9767 DAG.getTargetLoweringInfo().softenSetCCOperands( 9768 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling); 9769 if (!RHS.getNode()) { 9770 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 9771 CC = ISD::SETNE; 9772 } 9773 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS, 9774 DAG.getCondCode(CC)); 9775 return DAG.getMergeValues({Result, Chain}, dl); 9776 } 9777 9778 ARMCC::CondCodes CondCode, CondCode2; 9779 FPCCToARMCC(CC, CondCode, CondCode2); 9780 9781 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit 9782 // in CMPFP and CMPFPE, but instead it should be made explicit by these 9783 // instructions using a chain instead of glue. This would also fix the problem 9784 // here (and also in LowerSELECT_CC) where we generate two comparisons when 9785 // CondCode2 != AL. 9786 SDValue True = DAG.getConstant(1, dl, VT); 9787 SDValue False = DAG.getConstant(0, dl, VT); 9788 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 9789 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 9790 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9791 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG); 9792 if (CondCode2 != ARMCC::AL) { 9793 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 9794 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9795 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG); 9796 } 9797 return DAG.getMergeValues({Result, Chain}, dl); 9798 } 9799 9800 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9801 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 9802 switch (Op.getOpcode()) { 9803 default: llvm_unreachable("Don't know how to custom lower this!"); 9804 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 9805 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9806 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9807 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9808 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9809 case ISD::SELECT: return LowerSELECT(Op, DAG); 9810 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9811 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9812 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 9813 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 9814 case ISD::VASTART: return LowerVASTART(Op, DAG); 9815 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 9816 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 9817 case ISD::SINT_TO_FP: 9818 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9819 case ISD::STRICT_FP_TO_SINT: 9820 case ISD::STRICT_FP_TO_UINT: 9821 case ISD::FP_TO_SINT: 9822 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 9823 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9824 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9825 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9826 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 9827 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 9828 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 9829 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget); 9830 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 9831 Subtarget); 9832 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 9833 case ISD::SHL: 9834 case ISD::SRL: 9835 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 9836 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 9837 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 9838 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 9839 case ISD::SRL_PARTS: 9840 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 9841 case ISD::CTTZ: 9842 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 9843 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 9844 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 9845 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 9846 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 9847 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 9848 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 9849 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 9850 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9851 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 9852 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 9853 case ISD::TRUNCATE: return LowerTruncatei1(Op, DAG, Subtarget); 9854 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9855 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG); 9856 case ISD::MUL: return LowerMUL(Op, DAG); 9857 case ISD::SDIV: 9858 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9859 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 9860 return LowerSDIV(Op, DAG, Subtarget); 9861 case ISD::UDIV: 9862 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9863 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 9864 return LowerUDIV(Op, DAG, Subtarget); 9865 case ISD::ADDCARRY: 9866 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 9867 case ISD::SADDO: 9868 case ISD::SSUBO: 9869 return LowerSignedALUO(Op, DAG); 9870 case ISD::UADDO: 9871 case ISD::USUBO: 9872 return LowerUnsignedALUO(Op, DAG); 9873 case ISD::SADDSAT: 9874 case ISD::SSUBSAT: 9875 return LowerSADDSUBSAT(Op, DAG, Subtarget); 9876 case ISD::LOAD: 9877 return LowerPredicateLoad(Op, DAG); 9878 case ISD::STORE: 9879 return LowerSTORE(Op, DAG, Subtarget); 9880 case ISD::MLOAD: 9881 return LowerMLOAD(Op, DAG); 9882 case ISD::VECREDUCE_MUL: 9883 case ISD::VECREDUCE_AND: 9884 case ISD::VECREDUCE_OR: 9885 case ISD::VECREDUCE_XOR: 9886 return LowerVecReduce(Op, DAG, Subtarget); 9887 case ISD::VECREDUCE_FADD: 9888 case ISD::VECREDUCE_FMUL: 9889 case ISD::VECREDUCE_FMIN: 9890 case ISD::VECREDUCE_FMAX: 9891 return LowerVecReduceF(Op, DAG, Subtarget); 9892 case ISD::ATOMIC_LOAD: 9893 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 9894 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 9895 case ISD::SDIVREM: 9896 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 9897 case ISD::DYNAMIC_STACKALLOC: 9898 if (Subtarget->isTargetWindows()) 9899 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9900 llvm_unreachable("Don't know how to custom lower this!"); 9901 case ISD::STRICT_FP_ROUND: 9902 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 9903 case ISD::STRICT_FP_EXTEND: 9904 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9905 case ISD::STRICT_FSETCC: 9906 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG); 9907 case ARMISD::WIN__DBZCHK: return SDValue(); 9908 } 9909 } 9910 9911 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 9912 SelectionDAG &DAG) { 9913 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9914 unsigned Opc = 0; 9915 if (IntNo == Intrinsic::arm_smlald) 9916 Opc = ARMISD::SMLALD; 9917 else if (IntNo == Intrinsic::arm_smlaldx) 9918 Opc = ARMISD::SMLALDX; 9919 else if (IntNo == Intrinsic::arm_smlsld) 9920 Opc = ARMISD::SMLSLD; 9921 else if (IntNo == Intrinsic::arm_smlsldx) 9922 Opc = ARMISD::SMLSLDX; 9923 else 9924 return; 9925 9926 SDLoc dl(N); 9927 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9928 N->getOperand(3), 9929 DAG.getConstant(0, dl, MVT::i32)); 9930 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9931 N->getOperand(3), 9932 DAG.getConstant(1, dl, MVT::i32)); 9933 9934 SDValue LongMul = DAG.getNode(Opc, dl, 9935 DAG.getVTList(MVT::i32, MVT::i32), 9936 N->getOperand(1), N->getOperand(2), 9937 Lo, Hi); 9938 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, 9939 LongMul.getValue(0), LongMul.getValue(1))); 9940 } 9941 9942 /// ReplaceNodeResults - Replace the results of node with an illegal result 9943 /// type with new values built out of custom code. 9944 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 9945 SmallVectorImpl<SDValue> &Results, 9946 SelectionDAG &DAG) const { 9947 SDValue Res; 9948 switch (N->getOpcode()) { 9949 default: 9950 llvm_unreachable("Don't know how to custom expand this!"); 9951 case ISD::READ_REGISTER: 9952 ExpandREAD_REGISTER(N, Results, DAG); 9953 break; 9954 case ISD::BITCAST: 9955 Res = ExpandBITCAST(N, DAG, Subtarget); 9956 break; 9957 case ISD::SRL: 9958 case ISD::SRA: 9959 case ISD::SHL: 9960 Res = Expand64BitShift(N, DAG, Subtarget); 9961 break; 9962 case ISD::SREM: 9963 case ISD::UREM: 9964 Res = LowerREM(N, DAG); 9965 break; 9966 case ISD::SDIVREM: 9967 case ISD::UDIVREM: 9968 Res = LowerDivRem(SDValue(N, 0), DAG); 9969 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 9970 Results.push_back(Res.getValue(0)); 9971 Results.push_back(Res.getValue(1)); 9972 return; 9973 case ISD::SADDSAT: 9974 case ISD::SSUBSAT: 9975 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget); 9976 break; 9977 case ISD::READCYCLECOUNTER: 9978 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 9979 return; 9980 case ISD::UDIV: 9981 case ISD::SDIV: 9982 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 9983 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 9984 Results); 9985 case ISD::ATOMIC_CMP_SWAP: 9986 ReplaceCMP_SWAP_64Results(N, Results, DAG); 9987 return; 9988 case ISD::INTRINSIC_WO_CHAIN: 9989 return ReplaceLongIntrinsic(N, Results, DAG); 9990 case ISD::ABS: 9991 lowerABS(N, Results, DAG); 9992 return ; 9993 case ISD::LOAD: 9994 LowerLOAD(N, Results, DAG); 9995 break; 9996 } 9997 if (Res.getNode()) 9998 Results.push_back(Res); 9999 } 10000 10001 //===----------------------------------------------------------------------===// 10002 // ARM Scheduler Hooks 10003 //===----------------------------------------------------------------------===// 10004 10005 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 10006 /// registers the function context. 10007 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 10008 MachineBasicBlock *MBB, 10009 MachineBasicBlock *DispatchBB, 10010 int FI) const { 10011 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 10012 "ROPI/RWPI not currently supported with SjLj"); 10013 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10014 DebugLoc dl = MI.getDebugLoc(); 10015 MachineFunction *MF = MBB->getParent(); 10016 MachineRegisterInfo *MRI = &MF->getRegInfo(); 10017 MachineConstantPool *MCP = MF->getConstantPool(); 10018 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 10019 const Function &F = MF->getFunction(); 10020 10021 bool isThumb = Subtarget->isThumb(); 10022 bool isThumb2 = Subtarget->isThumb2(); 10023 10024 unsigned PCLabelId = AFI->createPICLabelUId(); 10025 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 10026 ARMConstantPoolValue *CPV = 10027 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 10028 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4)); 10029 10030 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 10031 : &ARM::GPRRegClass; 10032 10033 // Grab constant pool and fixed stack memory operands. 10034 MachineMemOperand *CPMMO = 10035 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 10036 MachineMemOperand::MOLoad, 4, Align(4)); 10037 10038 MachineMemOperand *FIMMOSt = 10039 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 10040 MachineMemOperand::MOStore, 4, Align(4)); 10041 10042 // Load the address of the dispatch MBB into the jump buffer. 10043 if (isThumb2) { 10044 // Incoming value: jbuf 10045 // ldr.n r5, LCPI1_1 10046 // orr r5, r5, #1 10047 // add r5, pc 10048 // str r5, [$jbuf, #+4] ; &jbuf[1] 10049 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10050 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 10051 .addConstantPoolIndex(CPI) 10052 .addMemOperand(CPMMO) 10053 .add(predOps(ARMCC::AL)); 10054 // Set the low bit because of thumb mode. 10055 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10056 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 10057 .addReg(NewVReg1, RegState::Kill) 10058 .addImm(0x01) 10059 .add(predOps(ARMCC::AL)) 10060 .add(condCodeOp()); 10061 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10062 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 10063 .addReg(NewVReg2, RegState::Kill) 10064 .addImm(PCLabelId); 10065 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 10066 .addReg(NewVReg3, RegState::Kill) 10067 .addFrameIndex(FI) 10068 .addImm(36) // &jbuf[1] :: pc 10069 .addMemOperand(FIMMOSt) 10070 .add(predOps(ARMCC::AL)); 10071 } else if (isThumb) { 10072 // Incoming value: jbuf 10073 // ldr.n r1, LCPI1_4 10074 // add r1, pc 10075 // mov r2, #1 10076 // orrs r1, r2 10077 // add r2, $jbuf, #+4 ; &jbuf[1] 10078 // str r1, [r2] 10079 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10080 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 10081 .addConstantPoolIndex(CPI) 10082 .addMemOperand(CPMMO) 10083 .add(predOps(ARMCC::AL)); 10084 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10085 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 10086 .addReg(NewVReg1, RegState::Kill) 10087 .addImm(PCLabelId); 10088 // Set the low bit because of thumb mode. 10089 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10090 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 10091 .addReg(ARM::CPSR, RegState::Define) 10092 .addImm(1) 10093 .add(predOps(ARMCC::AL)); 10094 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10095 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 10096 .addReg(ARM::CPSR, RegState::Define) 10097 .addReg(NewVReg2, RegState::Kill) 10098 .addReg(NewVReg3, RegState::Kill) 10099 .add(predOps(ARMCC::AL)); 10100 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10101 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 10102 .addFrameIndex(FI) 10103 .addImm(36); // &jbuf[1] :: pc 10104 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 10105 .addReg(NewVReg4, RegState::Kill) 10106 .addReg(NewVReg5, RegState::Kill) 10107 .addImm(0) 10108 .addMemOperand(FIMMOSt) 10109 .add(predOps(ARMCC::AL)); 10110 } else { 10111 // Incoming value: jbuf 10112 // ldr r1, LCPI1_1 10113 // add r1, pc, r1 10114 // str r1, [$jbuf, #+4] ; &jbuf[1] 10115 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10116 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 10117 .addConstantPoolIndex(CPI) 10118 .addImm(0) 10119 .addMemOperand(CPMMO) 10120 .add(predOps(ARMCC::AL)); 10121 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10122 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 10123 .addReg(NewVReg1, RegState::Kill) 10124 .addImm(PCLabelId) 10125 .add(predOps(ARMCC::AL)); 10126 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 10127 .addReg(NewVReg2, RegState::Kill) 10128 .addFrameIndex(FI) 10129 .addImm(36) // &jbuf[1] :: pc 10130 .addMemOperand(FIMMOSt) 10131 .add(predOps(ARMCC::AL)); 10132 } 10133 } 10134 10135 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 10136 MachineBasicBlock *MBB) const { 10137 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10138 DebugLoc dl = MI.getDebugLoc(); 10139 MachineFunction *MF = MBB->getParent(); 10140 MachineRegisterInfo *MRI = &MF->getRegInfo(); 10141 MachineFrameInfo &MFI = MF->getFrameInfo(); 10142 int FI = MFI.getFunctionContextIndex(); 10143 10144 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 10145 : &ARM::GPRnopcRegClass; 10146 10147 // Get a mapping of the call site numbers to all of the landing pads they're 10148 // associated with. 10149 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 10150 unsigned MaxCSNum = 0; 10151 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 10152 ++BB) { 10153 if (!BB->isEHPad()) continue; 10154 10155 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 10156 // pad. 10157 for (MachineBasicBlock::iterator 10158 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 10159 if (!II->isEHLabel()) continue; 10160 10161 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 10162 if (!MF->hasCallSiteLandingPad(Sym)) continue; 10163 10164 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 10165 for (SmallVectorImpl<unsigned>::iterator 10166 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 10167 CSI != CSE; ++CSI) { 10168 CallSiteNumToLPad[*CSI].push_back(&*BB); 10169 MaxCSNum = std::max(MaxCSNum, *CSI); 10170 } 10171 break; 10172 } 10173 } 10174 10175 // Get an ordered list of the machine basic blocks for the jump table. 10176 std::vector<MachineBasicBlock*> LPadList; 10177 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 10178 LPadList.reserve(CallSiteNumToLPad.size()); 10179 for (unsigned I = 1; I <= MaxCSNum; ++I) { 10180 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 10181 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10182 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 10183 LPadList.push_back(*II); 10184 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 10185 } 10186 } 10187 10188 assert(!LPadList.empty() && 10189 "No landing pad destinations for the dispatch jump table!"); 10190 10191 // Create the jump table and associated information. 10192 MachineJumpTableInfo *JTI = 10193 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 10194 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 10195 10196 // Create the MBBs for the dispatch code. 10197 10198 // Shove the dispatch's address into the return slot in the function context. 10199 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 10200 DispatchBB->setIsEHPad(); 10201 10202 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10203 unsigned trap_opcode; 10204 if (Subtarget->isThumb()) 10205 trap_opcode = ARM::tTRAP; 10206 else 10207 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 10208 10209 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 10210 DispatchBB->addSuccessor(TrapBB); 10211 10212 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 10213 DispatchBB->addSuccessor(DispContBB); 10214 10215 // Insert and MBBs. 10216 MF->insert(MF->end(), DispatchBB); 10217 MF->insert(MF->end(), DispContBB); 10218 MF->insert(MF->end(), TrapBB); 10219 10220 // Insert code into the entry block that creates and registers the function 10221 // context. 10222 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 10223 10224 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 10225 MachinePointerInfo::getFixedStack(*MF, FI), 10226 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4)); 10227 10228 MachineInstrBuilder MIB; 10229 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 10230 10231 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 10232 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 10233 10234 // Add a register mask with no preserved registers. This results in all 10235 // registers being marked as clobbered. This can't work if the dispatch block 10236 // is in a Thumb1 function and is linked with ARM code which uses the FP 10237 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 10238 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 10239 10240 bool IsPositionIndependent = isPositionIndependent(); 10241 unsigned NumLPads = LPadList.size(); 10242 if (Subtarget->isThumb2()) { 10243 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10244 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 10245 .addFrameIndex(FI) 10246 .addImm(4) 10247 .addMemOperand(FIMMOLd) 10248 .add(predOps(ARMCC::AL)); 10249 10250 if (NumLPads < 256) { 10251 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 10252 .addReg(NewVReg1) 10253 .addImm(LPadList.size()) 10254 .add(predOps(ARMCC::AL)); 10255 } else { 10256 Register VReg1 = MRI->createVirtualRegister(TRC); 10257 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 10258 .addImm(NumLPads & 0xFFFF) 10259 .add(predOps(ARMCC::AL)); 10260 10261 unsigned VReg2 = VReg1; 10262 if ((NumLPads & 0xFFFF0000) != 0) { 10263 VReg2 = MRI->createVirtualRegister(TRC); 10264 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 10265 .addReg(VReg1) 10266 .addImm(NumLPads >> 16) 10267 .add(predOps(ARMCC::AL)); 10268 } 10269 10270 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 10271 .addReg(NewVReg1) 10272 .addReg(VReg2) 10273 .add(predOps(ARMCC::AL)); 10274 } 10275 10276 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 10277 .addMBB(TrapBB) 10278 .addImm(ARMCC::HI) 10279 .addReg(ARM::CPSR); 10280 10281 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10282 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 10283 .addJumpTableIndex(MJTI) 10284 .add(predOps(ARMCC::AL)); 10285 10286 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10287 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 10288 .addReg(NewVReg3, RegState::Kill) 10289 .addReg(NewVReg1) 10290 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10291 .add(predOps(ARMCC::AL)) 10292 .add(condCodeOp()); 10293 10294 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 10295 .addReg(NewVReg4, RegState::Kill) 10296 .addReg(NewVReg1) 10297 .addJumpTableIndex(MJTI); 10298 } else if (Subtarget->isThumb()) { 10299 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10300 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 10301 .addFrameIndex(FI) 10302 .addImm(1) 10303 .addMemOperand(FIMMOLd) 10304 .add(predOps(ARMCC::AL)); 10305 10306 if (NumLPads < 256) { 10307 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 10308 .addReg(NewVReg1) 10309 .addImm(NumLPads) 10310 .add(predOps(ARMCC::AL)); 10311 } else { 10312 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10313 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10314 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10315 10316 // MachineConstantPool wants an explicit alignment. 10317 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10318 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10319 10320 Register VReg1 = MRI->createVirtualRegister(TRC); 10321 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 10322 .addReg(VReg1, RegState::Define) 10323 .addConstantPoolIndex(Idx) 10324 .add(predOps(ARMCC::AL)); 10325 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 10326 .addReg(NewVReg1) 10327 .addReg(VReg1) 10328 .add(predOps(ARMCC::AL)); 10329 } 10330 10331 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 10332 .addMBB(TrapBB) 10333 .addImm(ARMCC::HI) 10334 .addReg(ARM::CPSR); 10335 10336 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10337 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 10338 .addReg(ARM::CPSR, RegState::Define) 10339 .addReg(NewVReg1) 10340 .addImm(2) 10341 .add(predOps(ARMCC::AL)); 10342 10343 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10344 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 10345 .addJumpTableIndex(MJTI) 10346 .add(predOps(ARMCC::AL)); 10347 10348 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10349 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 10350 .addReg(ARM::CPSR, RegState::Define) 10351 .addReg(NewVReg2, RegState::Kill) 10352 .addReg(NewVReg3) 10353 .add(predOps(ARMCC::AL)); 10354 10355 MachineMemOperand *JTMMOLd = 10356 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10357 MachineMemOperand::MOLoad, 4, Align(4)); 10358 10359 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10360 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 10361 .addReg(NewVReg4, RegState::Kill) 10362 .addImm(0) 10363 .addMemOperand(JTMMOLd) 10364 .add(predOps(ARMCC::AL)); 10365 10366 unsigned NewVReg6 = NewVReg5; 10367 if (IsPositionIndependent) { 10368 NewVReg6 = MRI->createVirtualRegister(TRC); 10369 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 10370 .addReg(ARM::CPSR, RegState::Define) 10371 .addReg(NewVReg5, RegState::Kill) 10372 .addReg(NewVReg3) 10373 .add(predOps(ARMCC::AL)); 10374 } 10375 10376 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 10377 .addReg(NewVReg6, RegState::Kill) 10378 .addJumpTableIndex(MJTI); 10379 } else { 10380 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10381 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 10382 .addFrameIndex(FI) 10383 .addImm(4) 10384 .addMemOperand(FIMMOLd) 10385 .add(predOps(ARMCC::AL)); 10386 10387 if (NumLPads < 256) { 10388 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 10389 .addReg(NewVReg1) 10390 .addImm(NumLPads) 10391 .add(predOps(ARMCC::AL)); 10392 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 10393 Register VReg1 = MRI->createVirtualRegister(TRC); 10394 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 10395 .addImm(NumLPads & 0xFFFF) 10396 .add(predOps(ARMCC::AL)); 10397 10398 unsigned VReg2 = VReg1; 10399 if ((NumLPads & 0xFFFF0000) != 0) { 10400 VReg2 = MRI->createVirtualRegister(TRC); 10401 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 10402 .addReg(VReg1) 10403 .addImm(NumLPads >> 16) 10404 .add(predOps(ARMCC::AL)); 10405 } 10406 10407 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10408 .addReg(NewVReg1) 10409 .addReg(VReg2) 10410 .add(predOps(ARMCC::AL)); 10411 } else { 10412 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10413 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10414 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10415 10416 // MachineConstantPool wants an explicit alignment. 10417 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10418 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10419 10420 Register VReg1 = MRI->createVirtualRegister(TRC); 10421 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 10422 .addReg(VReg1, RegState::Define) 10423 .addConstantPoolIndex(Idx) 10424 .addImm(0) 10425 .add(predOps(ARMCC::AL)); 10426 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10427 .addReg(NewVReg1) 10428 .addReg(VReg1, RegState::Kill) 10429 .add(predOps(ARMCC::AL)); 10430 } 10431 10432 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 10433 .addMBB(TrapBB) 10434 .addImm(ARMCC::HI) 10435 .addReg(ARM::CPSR); 10436 10437 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10438 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 10439 .addReg(NewVReg1) 10440 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10441 .add(predOps(ARMCC::AL)) 10442 .add(condCodeOp()); 10443 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10444 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 10445 .addJumpTableIndex(MJTI) 10446 .add(predOps(ARMCC::AL)); 10447 10448 MachineMemOperand *JTMMOLd = 10449 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10450 MachineMemOperand::MOLoad, 4, Align(4)); 10451 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10452 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 10453 .addReg(NewVReg3, RegState::Kill) 10454 .addReg(NewVReg4) 10455 .addImm(0) 10456 .addMemOperand(JTMMOLd) 10457 .add(predOps(ARMCC::AL)); 10458 10459 if (IsPositionIndependent) { 10460 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 10461 .addReg(NewVReg5, RegState::Kill) 10462 .addReg(NewVReg4) 10463 .addJumpTableIndex(MJTI); 10464 } else { 10465 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 10466 .addReg(NewVReg5, RegState::Kill) 10467 .addJumpTableIndex(MJTI); 10468 } 10469 } 10470 10471 // Add the jump table entries as successors to the MBB. 10472 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 10473 for (std::vector<MachineBasicBlock*>::iterator 10474 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 10475 MachineBasicBlock *CurMBB = *I; 10476 if (SeenMBBs.insert(CurMBB).second) 10477 DispContBB->addSuccessor(CurMBB); 10478 } 10479 10480 // N.B. the order the invoke BBs are processed in doesn't matter here. 10481 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 10482 SmallVector<MachineBasicBlock*, 64> MBBLPads; 10483 for (MachineBasicBlock *BB : InvokeBBs) { 10484 10485 // Remove the landing pad successor from the invoke block and replace it 10486 // with the new dispatch block. 10487 SmallVector<MachineBasicBlock*, 4> Successors(BB->successors()); 10488 while (!Successors.empty()) { 10489 MachineBasicBlock *SMBB = Successors.pop_back_val(); 10490 if (SMBB->isEHPad()) { 10491 BB->removeSuccessor(SMBB); 10492 MBBLPads.push_back(SMBB); 10493 } 10494 } 10495 10496 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 10497 BB->normalizeSuccProbs(); 10498 10499 // Find the invoke call and mark all of the callee-saved registers as 10500 // 'implicit defined' so that they're spilled. This prevents code from 10501 // moving instructions to before the EH block, where they will never be 10502 // executed. 10503 for (MachineBasicBlock::reverse_iterator 10504 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 10505 if (!II->isCall()) continue; 10506 10507 DenseMap<unsigned, bool> DefRegs; 10508 for (MachineInstr::mop_iterator 10509 OI = II->operands_begin(), OE = II->operands_end(); 10510 OI != OE; ++OI) { 10511 if (!OI->isReg()) continue; 10512 DefRegs[OI->getReg()] = true; 10513 } 10514 10515 MachineInstrBuilder MIB(*MF, &*II); 10516 10517 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 10518 unsigned Reg = SavedRegs[i]; 10519 if (Subtarget->isThumb2() && 10520 !ARM::tGPRRegClass.contains(Reg) && 10521 !ARM::hGPRRegClass.contains(Reg)) 10522 continue; 10523 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 10524 continue; 10525 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 10526 continue; 10527 if (!DefRegs[Reg]) 10528 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 10529 } 10530 10531 break; 10532 } 10533 } 10534 10535 // Mark all former landing pads as non-landing pads. The dispatch is the only 10536 // landing pad now. 10537 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10538 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 10539 (*I)->setIsEHPad(false); 10540 10541 // The instruction is gone now. 10542 MI.eraseFromParent(); 10543 } 10544 10545 static 10546 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 10547 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 10548 E = MBB->succ_end(); I != E; ++I) 10549 if (*I != Succ) 10550 return *I; 10551 llvm_unreachable("Expecting a BB with two successors!"); 10552 } 10553 10554 /// Return the load opcode for a given load size. If load size >= 8, 10555 /// neon opcode will be returned. 10556 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 10557 if (LdSize >= 8) 10558 return LdSize == 16 ? ARM::VLD1q32wb_fixed 10559 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 10560 if (IsThumb1) 10561 return LdSize == 4 ? ARM::tLDRi 10562 : LdSize == 2 ? ARM::tLDRHi 10563 : LdSize == 1 ? ARM::tLDRBi : 0; 10564 if (IsThumb2) 10565 return LdSize == 4 ? ARM::t2LDR_POST 10566 : LdSize == 2 ? ARM::t2LDRH_POST 10567 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 10568 return LdSize == 4 ? ARM::LDR_POST_IMM 10569 : LdSize == 2 ? ARM::LDRH_POST 10570 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 10571 } 10572 10573 /// Return the store opcode for a given store size. If store size >= 8, 10574 /// neon opcode will be returned. 10575 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 10576 if (StSize >= 8) 10577 return StSize == 16 ? ARM::VST1q32wb_fixed 10578 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 10579 if (IsThumb1) 10580 return StSize == 4 ? ARM::tSTRi 10581 : StSize == 2 ? ARM::tSTRHi 10582 : StSize == 1 ? ARM::tSTRBi : 0; 10583 if (IsThumb2) 10584 return StSize == 4 ? ARM::t2STR_POST 10585 : StSize == 2 ? ARM::t2STRH_POST 10586 : StSize == 1 ? ARM::t2STRB_POST : 0; 10587 return StSize == 4 ? ARM::STR_POST_IMM 10588 : StSize == 2 ? ARM::STRH_POST 10589 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 10590 } 10591 10592 /// Emit a post-increment load operation with given size. The instructions 10593 /// will be added to BB at Pos. 10594 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10595 const TargetInstrInfo *TII, const DebugLoc &dl, 10596 unsigned LdSize, unsigned Data, unsigned AddrIn, 10597 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10598 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 10599 assert(LdOpc != 0 && "Should have a load opcode"); 10600 if (LdSize >= 8) { 10601 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10602 .addReg(AddrOut, RegState::Define) 10603 .addReg(AddrIn) 10604 .addImm(0) 10605 .add(predOps(ARMCC::AL)); 10606 } else if (IsThumb1) { 10607 // load + update AddrIn 10608 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10609 .addReg(AddrIn) 10610 .addImm(0) 10611 .add(predOps(ARMCC::AL)); 10612 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10613 .add(t1CondCodeOp()) 10614 .addReg(AddrIn) 10615 .addImm(LdSize) 10616 .add(predOps(ARMCC::AL)); 10617 } else if (IsThumb2) { 10618 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10619 .addReg(AddrOut, RegState::Define) 10620 .addReg(AddrIn) 10621 .addImm(LdSize) 10622 .add(predOps(ARMCC::AL)); 10623 } else { // arm 10624 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10625 .addReg(AddrOut, RegState::Define) 10626 .addReg(AddrIn) 10627 .addReg(0) 10628 .addImm(LdSize) 10629 .add(predOps(ARMCC::AL)); 10630 } 10631 } 10632 10633 /// Emit a post-increment store operation with given size. The instructions 10634 /// will be added to BB at Pos. 10635 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10636 const TargetInstrInfo *TII, const DebugLoc &dl, 10637 unsigned StSize, unsigned Data, unsigned AddrIn, 10638 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10639 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 10640 assert(StOpc != 0 && "Should have a store opcode"); 10641 if (StSize >= 8) { 10642 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10643 .addReg(AddrIn) 10644 .addImm(0) 10645 .addReg(Data) 10646 .add(predOps(ARMCC::AL)); 10647 } else if (IsThumb1) { 10648 // store + update AddrIn 10649 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 10650 .addReg(Data) 10651 .addReg(AddrIn) 10652 .addImm(0) 10653 .add(predOps(ARMCC::AL)); 10654 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10655 .add(t1CondCodeOp()) 10656 .addReg(AddrIn) 10657 .addImm(StSize) 10658 .add(predOps(ARMCC::AL)); 10659 } else if (IsThumb2) { 10660 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10661 .addReg(Data) 10662 .addReg(AddrIn) 10663 .addImm(StSize) 10664 .add(predOps(ARMCC::AL)); 10665 } else { // arm 10666 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10667 .addReg(Data) 10668 .addReg(AddrIn) 10669 .addReg(0) 10670 .addImm(StSize) 10671 .add(predOps(ARMCC::AL)); 10672 } 10673 } 10674 10675 MachineBasicBlock * 10676 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 10677 MachineBasicBlock *BB) const { 10678 // This pseudo instruction has 3 operands: dst, src, size 10679 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 10680 // Otherwise, we will generate unrolled scalar copies. 10681 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10682 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10683 MachineFunction::iterator It = ++BB->getIterator(); 10684 10685 Register dest = MI.getOperand(0).getReg(); 10686 Register src = MI.getOperand(1).getReg(); 10687 unsigned SizeVal = MI.getOperand(2).getImm(); 10688 unsigned Alignment = MI.getOperand(3).getImm(); 10689 DebugLoc dl = MI.getDebugLoc(); 10690 10691 MachineFunction *MF = BB->getParent(); 10692 MachineRegisterInfo &MRI = MF->getRegInfo(); 10693 unsigned UnitSize = 0; 10694 const TargetRegisterClass *TRC = nullptr; 10695 const TargetRegisterClass *VecTRC = nullptr; 10696 10697 bool IsThumb1 = Subtarget->isThumb1Only(); 10698 bool IsThumb2 = Subtarget->isThumb2(); 10699 bool IsThumb = Subtarget->isThumb(); 10700 10701 if (Alignment & 1) { 10702 UnitSize = 1; 10703 } else if (Alignment & 2) { 10704 UnitSize = 2; 10705 } else { 10706 // Check whether we can use NEON instructions. 10707 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 10708 Subtarget->hasNEON()) { 10709 if ((Alignment % 16 == 0) && SizeVal >= 16) 10710 UnitSize = 16; 10711 else if ((Alignment % 8 == 0) && SizeVal >= 8) 10712 UnitSize = 8; 10713 } 10714 // Can't use NEON instructions. 10715 if (UnitSize == 0) 10716 UnitSize = 4; 10717 } 10718 10719 // Select the correct opcode and register class for unit size load/store 10720 bool IsNeon = UnitSize >= 8; 10721 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 10722 if (IsNeon) 10723 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 10724 : UnitSize == 8 ? &ARM::DPRRegClass 10725 : nullptr; 10726 10727 unsigned BytesLeft = SizeVal % UnitSize; 10728 unsigned LoopSize = SizeVal - BytesLeft; 10729 10730 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 10731 // Use LDR and STR to copy. 10732 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 10733 // [destOut] = STR_POST(scratch, destIn, UnitSize) 10734 unsigned srcIn = src; 10735 unsigned destIn = dest; 10736 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 10737 Register srcOut = MRI.createVirtualRegister(TRC); 10738 Register destOut = MRI.createVirtualRegister(TRC); 10739 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10740 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 10741 IsThumb1, IsThumb2); 10742 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 10743 IsThumb1, IsThumb2); 10744 srcIn = srcOut; 10745 destIn = destOut; 10746 } 10747 10748 // Handle the leftover bytes with LDRB and STRB. 10749 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 10750 // [destOut] = STRB_POST(scratch, destIn, 1) 10751 for (unsigned i = 0; i < BytesLeft; i++) { 10752 Register srcOut = MRI.createVirtualRegister(TRC); 10753 Register destOut = MRI.createVirtualRegister(TRC); 10754 Register scratch = MRI.createVirtualRegister(TRC); 10755 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 10756 IsThumb1, IsThumb2); 10757 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 10758 IsThumb1, IsThumb2); 10759 srcIn = srcOut; 10760 destIn = destOut; 10761 } 10762 MI.eraseFromParent(); // The instruction is gone now. 10763 return BB; 10764 } 10765 10766 // Expand the pseudo op to a loop. 10767 // thisMBB: 10768 // ... 10769 // movw varEnd, # --> with thumb2 10770 // movt varEnd, # 10771 // ldrcp varEnd, idx --> without thumb2 10772 // fallthrough --> loopMBB 10773 // loopMBB: 10774 // PHI varPhi, varEnd, varLoop 10775 // PHI srcPhi, src, srcLoop 10776 // PHI destPhi, dst, destLoop 10777 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10778 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 10779 // subs varLoop, varPhi, #UnitSize 10780 // bne loopMBB 10781 // fallthrough --> exitMBB 10782 // exitMBB: 10783 // epilogue to handle left-over bytes 10784 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10785 // [destOut] = STRB_POST(scratch, destLoop, 1) 10786 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10787 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10788 MF->insert(It, loopMBB); 10789 MF->insert(It, exitMBB); 10790 10791 // Transfer the remainder of BB and its successor edges to exitMBB. 10792 exitMBB->splice(exitMBB->begin(), BB, 10793 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10794 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10795 10796 // Load an immediate to varEnd. 10797 Register varEnd = MRI.createVirtualRegister(TRC); 10798 if (Subtarget->useMovt()) { 10799 unsigned Vtmp = varEnd; 10800 if ((LoopSize & 0xFFFF0000) != 0) 10801 Vtmp = MRI.createVirtualRegister(TRC); 10802 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 10803 .addImm(LoopSize & 0xFFFF) 10804 .add(predOps(ARMCC::AL)); 10805 10806 if ((LoopSize & 0xFFFF0000) != 0) 10807 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 10808 .addReg(Vtmp) 10809 .addImm(LoopSize >> 16) 10810 .add(predOps(ARMCC::AL)); 10811 } else { 10812 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10813 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10814 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 10815 10816 // MachineConstantPool wants an explicit alignment. 10817 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10818 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10819 MachineMemOperand *CPMMO = 10820 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 10821 MachineMemOperand::MOLoad, 4, Align(4)); 10822 10823 if (IsThumb) 10824 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 10825 .addReg(varEnd, RegState::Define) 10826 .addConstantPoolIndex(Idx) 10827 .add(predOps(ARMCC::AL)) 10828 .addMemOperand(CPMMO); 10829 else 10830 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 10831 .addReg(varEnd, RegState::Define) 10832 .addConstantPoolIndex(Idx) 10833 .addImm(0) 10834 .add(predOps(ARMCC::AL)) 10835 .addMemOperand(CPMMO); 10836 } 10837 BB->addSuccessor(loopMBB); 10838 10839 // Generate the loop body: 10840 // varPhi = PHI(varLoop, varEnd) 10841 // srcPhi = PHI(srcLoop, src) 10842 // destPhi = PHI(destLoop, dst) 10843 MachineBasicBlock *entryBB = BB; 10844 BB = loopMBB; 10845 Register varLoop = MRI.createVirtualRegister(TRC); 10846 Register varPhi = MRI.createVirtualRegister(TRC); 10847 Register srcLoop = MRI.createVirtualRegister(TRC); 10848 Register srcPhi = MRI.createVirtualRegister(TRC); 10849 Register destLoop = MRI.createVirtualRegister(TRC); 10850 Register destPhi = MRI.createVirtualRegister(TRC); 10851 10852 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 10853 .addReg(varLoop).addMBB(loopMBB) 10854 .addReg(varEnd).addMBB(entryBB); 10855 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 10856 .addReg(srcLoop).addMBB(loopMBB) 10857 .addReg(src).addMBB(entryBB); 10858 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 10859 .addReg(destLoop).addMBB(loopMBB) 10860 .addReg(dest).addMBB(entryBB); 10861 10862 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10863 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 10864 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10865 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 10866 IsThumb1, IsThumb2); 10867 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 10868 IsThumb1, IsThumb2); 10869 10870 // Decrement loop variable by UnitSize. 10871 if (IsThumb1) { 10872 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 10873 .add(t1CondCodeOp()) 10874 .addReg(varPhi) 10875 .addImm(UnitSize) 10876 .add(predOps(ARMCC::AL)); 10877 } else { 10878 MachineInstrBuilder MIB = 10879 BuildMI(*BB, BB->end(), dl, 10880 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 10881 MIB.addReg(varPhi) 10882 .addImm(UnitSize) 10883 .add(predOps(ARMCC::AL)) 10884 .add(condCodeOp()); 10885 MIB->getOperand(5).setReg(ARM::CPSR); 10886 MIB->getOperand(5).setIsDef(true); 10887 } 10888 BuildMI(*BB, BB->end(), dl, 10889 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10890 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 10891 10892 // loopMBB can loop back to loopMBB or fall through to exitMBB. 10893 BB->addSuccessor(loopMBB); 10894 BB->addSuccessor(exitMBB); 10895 10896 // Add epilogue to handle BytesLeft. 10897 BB = exitMBB; 10898 auto StartOfExit = exitMBB->begin(); 10899 10900 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10901 // [destOut] = STRB_POST(scratch, destLoop, 1) 10902 unsigned srcIn = srcLoop; 10903 unsigned destIn = destLoop; 10904 for (unsigned i = 0; i < BytesLeft; i++) { 10905 Register srcOut = MRI.createVirtualRegister(TRC); 10906 Register destOut = MRI.createVirtualRegister(TRC); 10907 Register scratch = MRI.createVirtualRegister(TRC); 10908 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 10909 IsThumb1, IsThumb2); 10910 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 10911 IsThumb1, IsThumb2); 10912 srcIn = srcOut; 10913 destIn = destOut; 10914 } 10915 10916 MI.eraseFromParent(); // The instruction is gone now. 10917 return BB; 10918 } 10919 10920 MachineBasicBlock * 10921 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 10922 MachineBasicBlock *MBB) const { 10923 const TargetMachine &TM = getTargetMachine(); 10924 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 10925 DebugLoc DL = MI.getDebugLoc(); 10926 10927 assert(Subtarget->isTargetWindows() && 10928 "__chkstk is only supported on Windows"); 10929 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 10930 10931 // __chkstk takes the number of words to allocate on the stack in R4, and 10932 // returns the stack adjustment in number of bytes in R4. This will not 10933 // clober any other registers (other than the obvious lr). 10934 // 10935 // Although, technically, IP should be considered a register which may be 10936 // clobbered, the call itself will not touch it. Windows on ARM is a pure 10937 // thumb-2 environment, so there is no interworking required. As a result, we 10938 // do not expect a veneer to be emitted by the linker, clobbering IP. 10939 // 10940 // Each module receives its own copy of __chkstk, so no import thunk is 10941 // required, again, ensuring that IP is not clobbered. 10942 // 10943 // Finally, although some linkers may theoretically provide a trampoline for 10944 // out of range calls (which is quite common due to a 32M range limitation of 10945 // branches for Thumb), we can generate the long-call version via 10946 // -mcmodel=large, alleviating the need for the trampoline which may clobber 10947 // IP. 10948 10949 switch (TM.getCodeModel()) { 10950 case CodeModel::Tiny: 10951 llvm_unreachable("Tiny code model not available on ARM."); 10952 case CodeModel::Small: 10953 case CodeModel::Medium: 10954 case CodeModel::Kernel: 10955 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 10956 .add(predOps(ARMCC::AL)) 10957 .addExternalSymbol("__chkstk") 10958 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10959 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10960 .addReg(ARM::R12, 10961 RegState::Implicit | RegState::Define | RegState::Dead) 10962 .addReg(ARM::CPSR, 10963 RegState::Implicit | RegState::Define | RegState::Dead); 10964 break; 10965 case CodeModel::Large: { 10966 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10967 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 10968 10969 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 10970 .addExternalSymbol("__chkstk"); 10971 BuildMI(*MBB, MI, DL, TII.get(gettBLXrOpcode(*MBB->getParent()))) 10972 .add(predOps(ARMCC::AL)) 10973 .addReg(Reg, RegState::Kill) 10974 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10975 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10976 .addReg(ARM::R12, 10977 RegState::Implicit | RegState::Define | RegState::Dead) 10978 .addReg(ARM::CPSR, 10979 RegState::Implicit | RegState::Define | RegState::Dead); 10980 break; 10981 } 10982 } 10983 10984 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 10985 .addReg(ARM::SP, RegState::Kill) 10986 .addReg(ARM::R4, RegState::Kill) 10987 .setMIFlags(MachineInstr::FrameSetup) 10988 .add(predOps(ARMCC::AL)) 10989 .add(condCodeOp()); 10990 10991 MI.eraseFromParent(); 10992 return MBB; 10993 } 10994 10995 MachineBasicBlock * 10996 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 10997 MachineBasicBlock *MBB) const { 10998 DebugLoc DL = MI.getDebugLoc(); 10999 MachineFunction *MF = MBB->getParent(); 11000 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 11001 11002 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 11003 MF->insert(++MBB->getIterator(), ContBB); 11004 ContBB->splice(ContBB->begin(), MBB, 11005 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11006 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 11007 MBB->addSuccessor(ContBB); 11008 11009 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 11010 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 11011 MF->push_back(TrapBB); 11012 MBB->addSuccessor(TrapBB); 11013 11014 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 11015 .addReg(MI.getOperand(0).getReg()) 11016 .addImm(0) 11017 .add(predOps(ARMCC::AL)); 11018 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 11019 .addMBB(TrapBB) 11020 .addImm(ARMCC::EQ) 11021 .addReg(ARM::CPSR); 11022 11023 MI.eraseFromParent(); 11024 return ContBB; 11025 } 11026 11027 // The CPSR operand of SelectItr might be missing a kill marker 11028 // because there were multiple uses of CPSR, and ISel didn't know 11029 // which to mark. Figure out whether SelectItr should have had a 11030 // kill marker, and set it if it should. Returns the correct kill 11031 // marker value. 11032 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 11033 MachineBasicBlock* BB, 11034 const TargetRegisterInfo* TRI) { 11035 // Scan forward through BB for a use/def of CPSR. 11036 MachineBasicBlock::iterator miI(std::next(SelectItr)); 11037 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 11038 const MachineInstr& mi = *miI; 11039 if (mi.readsRegister(ARM::CPSR)) 11040 return false; 11041 if (mi.definesRegister(ARM::CPSR)) 11042 break; // Should have kill-flag - update below. 11043 } 11044 11045 // If we hit the end of the block, check whether CPSR is live into a 11046 // successor. 11047 if (miI == BB->end()) { 11048 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 11049 sEnd = BB->succ_end(); 11050 sItr != sEnd; ++sItr) { 11051 MachineBasicBlock* succ = *sItr; 11052 if (succ->isLiveIn(ARM::CPSR)) 11053 return false; 11054 } 11055 } 11056 11057 // We found a def, or hit the end of the basic block and CPSR wasn't live 11058 // out. SelectMI should have a kill flag on CPSR. 11059 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 11060 return true; 11061 } 11062 11063 MachineBasicBlock * 11064 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11065 MachineBasicBlock *BB) const { 11066 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 11067 DebugLoc dl = MI.getDebugLoc(); 11068 bool isThumb2 = Subtarget->isThumb2(); 11069 switch (MI.getOpcode()) { 11070 default: { 11071 MI.print(errs()); 11072 llvm_unreachable("Unexpected instr type to insert"); 11073 } 11074 11075 // Thumb1 post-indexed loads are really just single-register LDMs. 11076 case ARM::tLDR_postidx: { 11077 MachineOperand Def(MI.getOperand(1)); 11078 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 11079 .add(Def) // Rn_wb 11080 .add(MI.getOperand(2)) // Rn 11081 .add(MI.getOperand(3)) // PredImm 11082 .add(MI.getOperand(4)) // PredReg 11083 .add(MI.getOperand(0)) // Rt 11084 .cloneMemRefs(MI); 11085 MI.eraseFromParent(); 11086 return BB; 11087 } 11088 11089 // The Thumb2 pre-indexed stores have the same MI operands, they just 11090 // define them differently in the .td files from the isel patterns, so 11091 // they need pseudos. 11092 case ARM::t2STR_preidx: 11093 MI.setDesc(TII->get(ARM::t2STR_PRE)); 11094 return BB; 11095 case ARM::t2STRB_preidx: 11096 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 11097 return BB; 11098 case ARM::t2STRH_preidx: 11099 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 11100 return BB; 11101 11102 case ARM::STRi_preidx: 11103 case ARM::STRBi_preidx: { 11104 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 11105 : ARM::STRB_PRE_IMM; 11106 // Decode the offset. 11107 unsigned Offset = MI.getOperand(4).getImm(); 11108 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 11109 Offset = ARM_AM::getAM2Offset(Offset); 11110 if (isSub) 11111 Offset = -Offset; 11112 11113 MachineMemOperand *MMO = *MI.memoperands_begin(); 11114 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 11115 .add(MI.getOperand(0)) // Rn_wb 11116 .add(MI.getOperand(1)) // Rt 11117 .add(MI.getOperand(2)) // Rn 11118 .addImm(Offset) // offset (skip GPR==zero_reg) 11119 .add(MI.getOperand(5)) // pred 11120 .add(MI.getOperand(6)) 11121 .addMemOperand(MMO); 11122 MI.eraseFromParent(); 11123 return BB; 11124 } 11125 case ARM::STRr_preidx: 11126 case ARM::STRBr_preidx: 11127 case ARM::STRH_preidx: { 11128 unsigned NewOpc; 11129 switch (MI.getOpcode()) { 11130 default: llvm_unreachable("unexpected opcode!"); 11131 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 11132 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 11133 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 11134 } 11135 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 11136 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 11137 MIB.add(MI.getOperand(i)); 11138 MI.eraseFromParent(); 11139 return BB; 11140 } 11141 11142 case ARM::tMOVCCr_pseudo: { 11143 // To "insert" a SELECT_CC instruction, we actually have to insert the 11144 // diamond control-flow pattern. The incoming instruction knows the 11145 // destination vreg to set, the condition code register to branch on, the 11146 // true/false values to select between, and a branch opcode to use. 11147 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11148 MachineFunction::iterator It = ++BB->getIterator(); 11149 11150 // thisMBB: 11151 // ... 11152 // TrueVal = ... 11153 // cmpTY ccX, r1, r2 11154 // bCC copy1MBB 11155 // fallthrough --> copy0MBB 11156 MachineBasicBlock *thisMBB = BB; 11157 MachineFunction *F = BB->getParent(); 11158 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11159 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11160 F->insert(It, copy0MBB); 11161 F->insert(It, sinkMBB); 11162 11163 // Check whether CPSR is live past the tMOVCCr_pseudo. 11164 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11165 if (!MI.killsRegister(ARM::CPSR) && 11166 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 11167 copy0MBB->addLiveIn(ARM::CPSR); 11168 sinkMBB->addLiveIn(ARM::CPSR); 11169 } 11170 11171 // Transfer the remainder of BB and its successor edges to sinkMBB. 11172 sinkMBB->splice(sinkMBB->begin(), BB, 11173 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11174 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11175 11176 BB->addSuccessor(copy0MBB); 11177 BB->addSuccessor(sinkMBB); 11178 11179 BuildMI(BB, dl, TII->get(ARM::tBcc)) 11180 .addMBB(sinkMBB) 11181 .addImm(MI.getOperand(3).getImm()) 11182 .addReg(MI.getOperand(4).getReg()); 11183 11184 // copy0MBB: 11185 // %FalseValue = ... 11186 // # fallthrough to sinkMBB 11187 BB = copy0MBB; 11188 11189 // Update machine-CFG edges 11190 BB->addSuccessor(sinkMBB); 11191 11192 // sinkMBB: 11193 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11194 // ... 11195 BB = sinkMBB; 11196 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 11197 .addReg(MI.getOperand(1).getReg()) 11198 .addMBB(copy0MBB) 11199 .addReg(MI.getOperand(2).getReg()) 11200 .addMBB(thisMBB); 11201 11202 MI.eraseFromParent(); // The pseudo instruction is gone now. 11203 return BB; 11204 } 11205 11206 case ARM::BCCi64: 11207 case ARM::BCCZi64: { 11208 // If there is an unconditional branch to the other successor, remove it. 11209 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11210 11211 // Compare both parts that make up the double comparison separately for 11212 // equality. 11213 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 11214 11215 Register LHS1 = MI.getOperand(1).getReg(); 11216 Register LHS2 = MI.getOperand(2).getReg(); 11217 if (RHSisZero) { 11218 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11219 .addReg(LHS1) 11220 .addImm(0) 11221 .add(predOps(ARMCC::AL)); 11222 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11223 .addReg(LHS2).addImm(0) 11224 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11225 } else { 11226 Register RHS1 = MI.getOperand(3).getReg(); 11227 Register RHS2 = MI.getOperand(4).getReg(); 11228 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11229 .addReg(LHS1) 11230 .addReg(RHS1) 11231 .add(predOps(ARMCC::AL)); 11232 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11233 .addReg(LHS2).addReg(RHS2) 11234 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11235 } 11236 11237 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 11238 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 11239 if (MI.getOperand(0).getImm() == ARMCC::NE) 11240 std::swap(destMBB, exitMBB); 11241 11242 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 11243 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 11244 if (isThumb2) 11245 BuildMI(BB, dl, TII->get(ARM::t2B)) 11246 .addMBB(exitMBB) 11247 .add(predOps(ARMCC::AL)); 11248 else 11249 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 11250 11251 MI.eraseFromParent(); // The pseudo instruction is gone now. 11252 return BB; 11253 } 11254 11255 case ARM::Int_eh_sjlj_setjmp: 11256 case ARM::Int_eh_sjlj_setjmp_nofp: 11257 case ARM::tInt_eh_sjlj_setjmp: 11258 case ARM::t2Int_eh_sjlj_setjmp: 11259 case ARM::t2Int_eh_sjlj_setjmp_nofp: 11260 return BB; 11261 11262 case ARM::Int_eh_sjlj_setup_dispatch: 11263 EmitSjLjDispatchBlock(MI, BB); 11264 return BB; 11265 11266 case ARM::ABS: 11267 case ARM::t2ABS: { 11268 // To insert an ABS instruction, we have to insert the 11269 // diamond control-flow pattern. The incoming instruction knows the 11270 // source vreg to test against 0, the destination vreg to set, 11271 // the condition code register to branch on, the 11272 // true/false values to select between, and a branch opcode to use. 11273 // It transforms 11274 // V1 = ABS V0 11275 // into 11276 // V2 = MOVS V0 11277 // BCC (branch to SinkBB if V0 >= 0) 11278 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 11279 // SinkBB: V1 = PHI(V2, V3) 11280 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11281 MachineFunction::iterator BBI = ++BB->getIterator(); 11282 MachineFunction *Fn = BB->getParent(); 11283 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11284 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11285 Fn->insert(BBI, RSBBB); 11286 Fn->insert(BBI, SinkBB); 11287 11288 Register ABSSrcReg = MI.getOperand(1).getReg(); 11289 Register ABSDstReg = MI.getOperand(0).getReg(); 11290 bool ABSSrcKIll = MI.getOperand(1).isKill(); 11291 bool isThumb2 = Subtarget->isThumb2(); 11292 MachineRegisterInfo &MRI = Fn->getRegInfo(); 11293 // In Thumb mode S must not be specified if source register is the SP or 11294 // PC and if destination register is the SP, so restrict register class 11295 Register NewRsbDstReg = MRI.createVirtualRegister( 11296 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 11297 11298 // Transfer the remainder of BB and its successor edges to sinkMBB. 11299 SinkBB->splice(SinkBB->begin(), BB, 11300 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11301 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 11302 11303 BB->addSuccessor(RSBBB); 11304 BB->addSuccessor(SinkBB); 11305 11306 // fall through to SinkMBB 11307 RSBBB->addSuccessor(SinkBB); 11308 11309 // insert a cmp at the end of BB 11310 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11311 .addReg(ABSSrcReg) 11312 .addImm(0) 11313 .add(predOps(ARMCC::AL)); 11314 11315 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 11316 BuildMI(BB, dl, 11317 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 11318 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 11319 11320 // insert rsbri in RSBBB 11321 // Note: BCC and rsbri will be converted into predicated rsbmi 11322 // by if-conversion pass 11323 BuildMI(*RSBBB, RSBBB->begin(), dl, 11324 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 11325 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 11326 .addImm(0) 11327 .add(predOps(ARMCC::AL)) 11328 .add(condCodeOp()); 11329 11330 // insert PHI in SinkBB, 11331 // reuse ABSDstReg to not change uses of ABS instruction 11332 BuildMI(*SinkBB, SinkBB->begin(), dl, 11333 TII->get(ARM::PHI), ABSDstReg) 11334 .addReg(NewRsbDstReg).addMBB(RSBBB) 11335 .addReg(ABSSrcReg).addMBB(BB); 11336 11337 // remove ABS instruction 11338 MI.eraseFromParent(); 11339 11340 // return last added BB 11341 return SinkBB; 11342 } 11343 case ARM::COPY_STRUCT_BYVAL_I32: 11344 ++NumLoopByVals; 11345 return EmitStructByval(MI, BB); 11346 case ARM::WIN__CHKSTK: 11347 return EmitLowered__chkstk(MI, BB); 11348 case ARM::WIN__DBZCHK: 11349 return EmitLowered__dbzchk(MI, BB); 11350 } 11351 } 11352 11353 /// Attaches vregs to MEMCPY that it will use as scratch registers 11354 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 11355 /// instead of as a custom inserter because we need the use list from the SDNode. 11356 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 11357 MachineInstr &MI, const SDNode *Node) { 11358 bool isThumb1 = Subtarget->isThumb1Only(); 11359 11360 DebugLoc DL = MI.getDebugLoc(); 11361 MachineFunction *MF = MI.getParent()->getParent(); 11362 MachineRegisterInfo &MRI = MF->getRegInfo(); 11363 MachineInstrBuilder MIB(*MF, MI); 11364 11365 // If the new dst/src is unused mark it as dead. 11366 if (!Node->hasAnyUseOfValue(0)) { 11367 MI.getOperand(0).setIsDead(true); 11368 } 11369 if (!Node->hasAnyUseOfValue(1)) { 11370 MI.getOperand(1).setIsDead(true); 11371 } 11372 11373 // The MEMCPY both defines and kills the scratch registers. 11374 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 11375 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 11376 : &ARM::GPRRegClass); 11377 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 11378 } 11379 } 11380 11381 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11382 SDNode *Node) const { 11383 if (MI.getOpcode() == ARM::MEMCPY) { 11384 attachMEMCPYScratchRegs(Subtarget, MI, Node); 11385 return; 11386 } 11387 11388 const MCInstrDesc *MCID = &MI.getDesc(); 11389 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 11390 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 11391 // operand is still set to noreg. If needed, set the optional operand's 11392 // register to CPSR, and remove the redundant implicit def. 11393 // 11394 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 11395 11396 // Rename pseudo opcodes. 11397 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 11398 unsigned ccOutIdx; 11399 if (NewOpc) { 11400 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 11401 MCID = &TII->get(NewOpc); 11402 11403 assert(MCID->getNumOperands() == 11404 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 11405 && "converted opcode should be the same except for cc_out" 11406 " (and, on Thumb1, pred)"); 11407 11408 MI.setDesc(*MCID); 11409 11410 // Add the optional cc_out operand 11411 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 11412 11413 // On Thumb1, move all input operands to the end, then add the predicate 11414 if (Subtarget->isThumb1Only()) { 11415 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 11416 MI.addOperand(MI.getOperand(1)); 11417 MI.RemoveOperand(1); 11418 } 11419 11420 // Restore the ties 11421 for (unsigned i = MI.getNumOperands(); i--;) { 11422 const MachineOperand& op = MI.getOperand(i); 11423 if (op.isReg() && op.isUse()) { 11424 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 11425 if (DefIdx != -1) 11426 MI.tieOperands(DefIdx, i); 11427 } 11428 } 11429 11430 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 11431 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 11432 ccOutIdx = 1; 11433 } else 11434 ccOutIdx = MCID->getNumOperands() - 1; 11435 } else 11436 ccOutIdx = MCID->getNumOperands() - 1; 11437 11438 // Any ARM instruction that sets the 's' bit should specify an optional 11439 // "cc_out" operand in the last operand position. 11440 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 11441 assert(!NewOpc && "Optional cc_out operand required"); 11442 return; 11443 } 11444 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 11445 // since we already have an optional CPSR def. 11446 bool definesCPSR = false; 11447 bool deadCPSR = false; 11448 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 11449 ++i) { 11450 const MachineOperand &MO = MI.getOperand(i); 11451 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 11452 definesCPSR = true; 11453 if (MO.isDead()) 11454 deadCPSR = true; 11455 MI.RemoveOperand(i); 11456 break; 11457 } 11458 } 11459 if (!definesCPSR) { 11460 assert(!NewOpc && "Optional cc_out operand required"); 11461 return; 11462 } 11463 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 11464 if (deadCPSR) { 11465 assert(!MI.getOperand(ccOutIdx).getReg() && 11466 "expect uninitialized optional cc_out operand"); 11467 // Thumb1 instructions must have the S bit even if the CPSR is dead. 11468 if (!Subtarget->isThumb1Only()) 11469 return; 11470 } 11471 11472 // If this instruction was defined with an optional CPSR def and its dag node 11473 // had a live implicit CPSR def, then activate the optional CPSR def. 11474 MachineOperand &MO = MI.getOperand(ccOutIdx); 11475 MO.setReg(ARM::CPSR); 11476 MO.setIsDef(true); 11477 } 11478 11479 //===----------------------------------------------------------------------===// 11480 // ARM Optimization Hooks 11481 //===----------------------------------------------------------------------===// 11482 11483 // Helper function that checks if N is a null or all ones constant. 11484 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 11485 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 11486 } 11487 11488 // Return true if N is conditionally 0 or all ones. 11489 // Detects these expressions where cc is an i1 value: 11490 // 11491 // (select cc 0, y) [AllOnes=0] 11492 // (select cc y, 0) [AllOnes=0] 11493 // (zext cc) [AllOnes=0] 11494 // (sext cc) [AllOnes=0/1] 11495 // (select cc -1, y) [AllOnes=1] 11496 // (select cc y, -1) [AllOnes=1] 11497 // 11498 // Invert is set when N is the null/all ones constant when CC is false. 11499 // OtherOp is set to the alternative value of N. 11500 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 11501 SDValue &CC, bool &Invert, 11502 SDValue &OtherOp, 11503 SelectionDAG &DAG) { 11504 switch (N->getOpcode()) { 11505 default: return false; 11506 case ISD::SELECT: { 11507 CC = N->getOperand(0); 11508 SDValue N1 = N->getOperand(1); 11509 SDValue N2 = N->getOperand(2); 11510 if (isZeroOrAllOnes(N1, AllOnes)) { 11511 Invert = false; 11512 OtherOp = N2; 11513 return true; 11514 } 11515 if (isZeroOrAllOnes(N2, AllOnes)) { 11516 Invert = true; 11517 OtherOp = N1; 11518 return true; 11519 } 11520 return false; 11521 } 11522 case ISD::ZERO_EXTEND: 11523 // (zext cc) can never be the all ones value. 11524 if (AllOnes) 11525 return false; 11526 LLVM_FALLTHROUGH; 11527 case ISD::SIGN_EXTEND: { 11528 SDLoc dl(N); 11529 EVT VT = N->getValueType(0); 11530 CC = N->getOperand(0); 11531 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 11532 return false; 11533 Invert = !AllOnes; 11534 if (AllOnes) 11535 // When looking for an AllOnes constant, N is an sext, and the 'other' 11536 // value is 0. 11537 OtherOp = DAG.getConstant(0, dl, VT); 11538 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11539 // When looking for a 0 constant, N can be zext or sext. 11540 OtherOp = DAG.getConstant(1, dl, VT); 11541 else 11542 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 11543 VT); 11544 return true; 11545 } 11546 } 11547 } 11548 11549 // Combine a constant select operand into its use: 11550 // 11551 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11552 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11553 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 11554 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11555 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11556 // 11557 // The transform is rejected if the select doesn't have a constant operand that 11558 // is null, or all ones when AllOnes is set. 11559 // 11560 // Also recognize sext/zext from i1: 11561 // 11562 // (add (zext cc), x) -> (select cc (add x, 1), x) 11563 // (add (sext cc), x) -> (select cc (add x, -1), x) 11564 // 11565 // These transformations eventually create predicated instructions. 11566 // 11567 // @param N The node to transform. 11568 // @param Slct The N operand that is a select. 11569 // @param OtherOp The other N operand (x above). 11570 // @param DCI Context. 11571 // @param AllOnes Require the select constant to be all ones instead of null. 11572 // @returns The new node, or SDValue() on failure. 11573 static 11574 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 11575 TargetLowering::DAGCombinerInfo &DCI, 11576 bool AllOnes = false) { 11577 SelectionDAG &DAG = DCI.DAG; 11578 EVT VT = N->getValueType(0); 11579 SDValue NonConstantVal; 11580 SDValue CCOp; 11581 bool SwapSelectOps; 11582 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 11583 NonConstantVal, DAG)) 11584 return SDValue(); 11585 11586 // Slct is now know to be the desired identity constant when CC is true. 11587 SDValue TrueVal = OtherOp; 11588 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 11589 OtherOp, NonConstantVal); 11590 // Unless SwapSelectOps says CC should be false. 11591 if (SwapSelectOps) 11592 std::swap(TrueVal, FalseVal); 11593 11594 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 11595 CCOp, TrueVal, FalseVal); 11596 } 11597 11598 // Attempt combineSelectAndUse on each operand of a commutative operator N. 11599 static 11600 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 11601 TargetLowering::DAGCombinerInfo &DCI) { 11602 SDValue N0 = N->getOperand(0); 11603 SDValue N1 = N->getOperand(1); 11604 if (N0.getNode()->hasOneUse()) 11605 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 11606 return Result; 11607 if (N1.getNode()->hasOneUse()) 11608 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 11609 return Result; 11610 return SDValue(); 11611 } 11612 11613 static bool IsVUZPShuffleNode(SDNode *N) { 11614 // VUZP shuffle node. 11615 if (N->getOpcode() == ARMISD::VUZP) 11616 return true; 11617 11618 // "VUZP" on i32 is an alias for VTRN. 11619 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 11620 return true; 11621 11622 return false; 11623 } 11624 11625 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 11626 TargetLowering::DAGCombinerInfo &DCI, 11627 const ARMSubtarget *Subtarget) { 11628 // Look for ADD(VUZP.0, VUZP.1). 11629 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 11630 N0 == N1) 11631 return SDValue(); 11632 11633 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 11634 if (!N->getValueType(0).is64BitVector()) 11635 return SDValue(); 11636 11637 // Generate vpadd. 11638 SelectionDAG &DAG = DCI.DAG; 11639 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11640 SDLoc dl(N); 11641 SDNode *Unzip = N0.getNode(); 11642 EVT VT = N->getValueType(0); 11643 11644 SmallVector<SDValue, 8> Ops; 11645 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 11646 TLI.getPointerTy(DAG.getDataLayout()))); 11647 Ops.push_back(Unzip->getOperand(0)); 11648 Ops.push_back(Unzip->getOperand(1)); 11649 11650 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11651 } 11652 11653 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11654 TargetLowering::DAGCombinerInfo &DCI, 11655 const ARMSubtarget *Subtarget) { 11656 // Check for two extended operands. 11657 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 11658 N1.getOpcode() == ISD::SIGN_EXTEND) && 11659 !(N0.getOpcode() == ISD::ZERO_EXTEND && 11660 N1.getOpcode() == ISD::ZERO_EXTEND)) 11661 return SDValue(); 11662 11663 SDValue N00 = N0.getOperand(0); 11664 SDValue N10 = N1.getOperand(0); 11665 11666 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 11667 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 11668 N00 == N10) 11669 return SDValue(); 11670 11671 // We only recognize Q register paddl here; this can't be reached until 11672 // after type legalization. 11673 if (!N00.getValueType().is64BitVector() || 11674 !N0.getValueType().is128BitVector()) 11675 return SDValue(); 11676 11677 // Generate vpaddl. 11678 SelectionDAG &DAG = DCI.DAG; 11679 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11680 SDLoc dl(N); 11681 EVT VT = N->getValueType(0); 11682 11683 SmallVector<SDValue, 8> Ops; 11684 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 11685 unsigned Opcode; 11686 if (N0.getOpcode() == ISD::SIGN_EXTEND) 11687 Opcode = Intrinsic::arm_neon_vpaddls; 11688 else 11689 Opcode = Intrinsic::arm_neon_vpaddlu; 11690 Ops.push_back(DAG.getConstant(Opcode, dl, 11691 TLI.getPointerTy(DAG.getDataLayout()))); 11692 EVT ElemTy = N00.getValueType().getVectorElementType(); 11693 unsigned NumElts = VT.getVectorNumElements(); 11694 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 11695 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 11696 N00.getOperand(0), N00.getOperand(1)); 11697 Ops.push_back(Concat); 11698 11699 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11700 } 11701 11702 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 11703 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 11704 // much easier to match. 11705 static SDValue 11706 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11707 TargetLowering::DAGCombinerInfo &DCI, 11708 const ARMSubtarget *Subtarget) { 11709 // Only perform optimization if after legalize, and if NEON is available. We 11710 // also expected both operands to be BUILD_VECTORs. 11711 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 11712 || N0.getOpcode() != ISD::BUILD_VECTOR 11713 || N1.getOpcode() != ISD::BUILD_VECTOR) 11714 return SDValue(); 11715 11716 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 11717 EVT VT = N->getValueType(0); 11718 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 11719 return SDValue(); 11720 11721 // Check that the vector operands are of the right form. 11722 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 11723 // operands, where N is the size of the formed vector. 11724 // Each EXTRACT_VECTOR should have the same input vector and odd or even 11725 // index such that we have a pair wise add pattern. 11726 11727 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 11728 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11729 return SDValue(); 11730 SDValue Vec = N0->getOperand(0)->getOperand(0); 11731 SDNode *V = Vec.getNode(); 11732 unsigned nextIndex = 0; 11733 11734 // For each operands to the ADD which are BUILD_VECTORs, 11735 // check to see if each of their operands are an EXTRACT_VECTOR with 11736 // the same vector and appropriate index. 11737 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 11738 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 11739 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11740 11741 SDValue ExtVec0 = N0->getOperand(i); 11742 SDValue ExtVec1 = N1->getOperand(i); 11743 11744 // First operand is the vector, verify its the same. 11745 if (V != ExtVec0->getOperand(0).getNode() || 11746 V != ExtVec1->getOperand(0).getNode()) 11747 return SDValue(); 11748 11749 // Second is the constant, verify its correct. 11750 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 11751 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 11752 11753 // For the constant, we want to see all the even or all the odd. 11754 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 11755 || C1->getZExtValue() != nextIndex+1) 11756 return SDValue(); 11757 11758 // Increment index. 11759 nextIndex+=2; 11760 } else 11761 return SDValue(); 11762 } 11763 11764 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 11765 // we're using the entire input vector, otherwise there's a size/legality 11766 // mismatch somewhere. 11767 if (nextIndex != Vec.getValueType().getVectorNumElements() || 11768 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 11769 return SDValue(); 11770 11771 // Create VPADDL node. 11772 SelectionDAG &DAG = DCI.DAG; 11773 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11774 11775 SDLoc dl(N); 11776 11777 // Build operand list. 11778 SmallVector<SDValue, 8> Ops; 11779 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 11780 TLI.getPointerTy(DAG.getDataLayout()))); 11781 11782 // Input is the vector. 11783 Ops.push_back(Vec); 11784 11785 // Get widened type and narrowed type. 11786 MVT widenType; 11787 unsigned numElem = VT.getVectorNumElements(); 11788 11789 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 11790 switch (inputLaneType.getSimpleVT().SimpleTy) { 11791 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 11792 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 11793 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 11794 default: 11795 llvm_unreachable("Invalid vector element type for padd optimization."); 11796 } 11797 11798 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 11799 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 11800 return DAG.getNode(ExtOp, dl, VT, tmp); 11801 } 11802 11803 static SDValue findMUL_LOHI(SDValue V) { 11804 if (V->getOpcode() == ISD::UMUL_LOHI || 11805 V->getOpcode() == ISD::SMUL_LOHI) 11806 return V; 11807 return SDValue(); 11808 } 11809 11810 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 11811 TargetLowering::DAGCombinerInfo &DCI, 11812 const ARMSubtarget *Subtarget) { 11813 if (!Subtarget->hasBaseDSP()) 11814 return SDValue(); 11815 11816 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 11817 // accumulates the product into a 64-bit value. The 16-bit values will 11818 // be sign extended somehow or SRA'd into 32-bit values 11819 // (addc (adde (mul 16bit, 16bit), lo), hi) 11820 SDValue Mul = AddcNode->getOperand(0); 11821 SDValue Lo = AddcNode->getOperand(1); 11822 if (Mul.getOpcode() != ISD::MUL) { 11823 Lo = AddcNode->getOperand(0); 11824 Mul = AddcNode->getOperand(1); 11825 if (Mul.getOpcode() != ISD::MUL) 11826 return SDValue(); 11827 } 11828 11829 SDValue SRA = AddeNode->getOperand(0); 11830 SDValue Hi = AddeNode->getOperand(1); 11831 if (SRA.getOpcode() != ISD::SRA) { 11832 SRA = AddeNode->getOperand(1); 11833 Hi = AddeNode->getOperand(0); 11834 if (SRA.getOpcode() != ISD::SRA) 11835 return SDValue(); 11836 } 11837 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 11838 if (Const->getZExtValue() != 31) 11839 return SDValue(); 11840 } else 11841 return SDValue(); 11842 11843 if (SRA.getOperand(0) != Mul) 11844 return SDValue(); 11845 11846 SelectionDAG &DAG = DCI.DAG; 11847 SDLoc dl(AddcNode); 11848 unsigned Opcode = 0; 11849 SDValue Op0; 11850 SDValue Op1; 11851 11852 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 11853 Opcode = ARMISD::SMLALBB; 11854 Op0 = Mul.getOperand(0); 11855 Op1 = Mul.getOperand(1); 11856 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 11857 Opcode = ARMISD::SMLALBT; 11858 Op0 = Mul.getOperand(0); 11859 Op1 = Mul.getOperand(1).getOperand(0); 11860 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 11861 Opcode = ARMISD::SMLALTB; 11862 Op0 = Mul.getOperand(0).getOperand(0); 11863 Op1 = Mul.getOperand(1); 11864 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 11865 Opcode = ARMISD::SMLALTT; 11866 Op0 = Mul->getOperand(0).getOperand(0); 11867 Op1 = Mul->getOperand(1).getOperand(0); 11868 } 11869 11870 if (!Op0 || !Op1) 11871 return SDValue(); 11872 11873 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 11874 Op0, Op1, Lo, Hi); 11875 // Replace the ADDs' nodes uses by the MLA node's values. 11876 SDValue HiMLALResult(SMLAL.getNode(), 1); 11877 SDValue LoMLALResult(SMLAL.getNode(), 0); 11878 11879 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 11880 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 11881 11882 // Return original node to notify the driver to stop replacing. 11883 SDValue resNode(AddcNode, 0); 11884 return resNode; 11885 } 11886 11887 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 11888 TargetLowering::DAGCombinerInfo &DCI, 11889 const ARMSubtarget *Subtarget) { 11890 // Look for multiply add opportunities. 11891 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 11892 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 11893 // a glue link from the first add to the second add. 11894 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 11895 // a S/UMLAL instruction. 11896 // UMUL_LOHI 11897 // / :lo \ :hi 11898 // V \ [no multiline comment] 11899 // loAdd -> ADDC | 11900 // \ :carry / 11901 // V V 11902 // ADDE <- hiAdd 11903 // 11904 // In the special case where only the higher part of a signed result is used 11905 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 11906 // a constant with the exact value of 0x80000000, we recognize we are dealing 11907 // with a "rounded multiply and add" (or subtract) and transform it into 11908 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 11909 11910 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 11911 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 11912 "Expect an ADDE or SUBE"); 11913 11914 assert(AddeSubeNode->getNumOperands() == 3 && 11915 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 11916 "ADDE node has the wrong inputs"); 11917 11918 // Check that we are chained to the right ADDC or SUBC node. 11919 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 11920 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 11921 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 11922 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 11923 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 11924 return SDValue(); 11925 11926 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 11927 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 11928 11929 // Check if the two operands are from the same mul_lohi node. 11930 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 11931 return SDValue(); 11932 11933 assert(AddcSubcNode->getNumValues() == 2 && 11934 AddcSubcNode->getValueType(0) == MVT::i32 && 11935 "Expect ADDC with two result values. First: i32"); 11936 11937 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 11938 // maybe a SMLAL which multiplies two 16-bit values. 11939 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 11940 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 11941 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 11942 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 11943 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 11944 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 11945 11946 // Check for the triangle shape. 11947 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 11948 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 11949 11950 // Make sure that the ADDE/SUBE operands are not coming from the same node. 11951 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 11952 return SDValue(); 11953 11954 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 11955 bool IsLeftOperandMUL = false; 11956 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 11957 if (MULOp == SDValue()) 11958 MULOp = findMUL_LOHI(AddeSubeOp1); 11959 else 11960 IsLeftOperandMUL = true; 11961 if (MULOp == SDValue()) 11962 return SDValue(); 11963 11964 // Figure out the right opcode. 11965 unsigned Opc = MULOp->getOpcode(); 11966 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 11967 11968 // Figure out the high and low input values to the MLAL node. 11969 SDValue *HiAddSub = nullptr; 11970 SDValue *LoMul = nullptr; 11971 SDValue *LowAddSub = nullptr; 11972 11973 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 11974 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 11975 return SDValue(); 11976 11977 if (IsLeftOperandMUL) 11978 HiAddSub = &AddeSubeOp1; 11979 else 11980 HiAddSub = &AddeSubeOp0; 11981 11982 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 11983 // whose low result is fed to the ADDC/SUBC we are checking. 11984 11985 if (AddcSubcOp0 == MULOp.getValue(0)) { 11986 LoMul = &AddcSubcOp0; 11987 LowAddSub = &AddcSubcOp1; 11988 } 11989 if (AddcSubcOp1 == MULOp.getValue(0)) { 11990 LoMul = &AddcSubcOp1; 11991 LowAddSub = &AddcSubcOp0; 11992 } 11993 11994 if (!LoMul) 11995 return SDValue(); 11996 11997 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 11998 // the replacement below will create a cycle. 11999 if (AddcSubcNode == HiAddSub->getNode() || 12000 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 12001 return SDValue(); 12002 12003 // Create the merged node. 12004 SelectionDAG &DAG = DCI.DAG; 12005 12006 // Start building operand list. 12007 SmallVector<SDValue, 8> Ops; 12008 Ops.push_back(LoMul->getOperand(0)); 12009 Ops.push_back(LoMul->getOperand(1)); 12010 12011 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 12012 // the case, we must be doing signed multiplication and only use the higher 12013 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 12014 // addition or subtraction with the value of 0x800000. 12015 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 12016 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 12017 LowAddSub->getNode()->getOpcode() == ISD::Constant && 12018 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 12019 0x80000000) { 12020 Ops.push_back(*HiAddSub); 12021 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 12022 FinalOpc = ARMISD::SMMLSR; 12023 } else { 12024 FinalOpc = ARMISD::SMMLAR; 12025 } 12026 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 12027 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 12028 12029 return SDValue(AddeSubeNode, 0); 12030 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 12031 // SMMLS is generated during instruction selection and the rest of this 12032 // function can not handle the case where AddcSubcNode is a SUBC. 12033 return SDValue(); 12034 12035 // Finish building the operand list for {U/S}MLAL 12036 Ops.push_back(*LowAddSub); 12037 Ops.push_back(*HiAddSub); 12038 12039 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 12040 DAG.getVTList(MVT::i32, MVT::i32), Ops); 12041 12042 // Replace the ADDs' nodes uses by the MLA node's values. 12043 SDValue HiMLALResult(MLALNode.getNode(), 1); 12044 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 12045 12046 SDValue LoMLALResult(MLALNode.getNode(), 0); 12047 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 12048 12049 // Return original node to notify the driver to stop replacing. 12050 return SDValue(AddeSubeNode, 0); 12051 } 12052 12053 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 12054 TargetLowering::DAGCombinerInfo &DCI, 12055 const ARMSubtarget *Subtarget) { 12056 // UMAAL is similar to UMLAL except that it adds two unsigned values. 12057 // While trying to combine for the other MLAL nodes, first search for the 12058 // chance to use UMAAL. Check if Addc uses a node which has already 12059 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 12060 // as the addend, and it's handled in PerformUMLALCombine. 12061 12062 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 12063 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 12064 12065 // Check that we have a glued ADDC node. 12066 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 12067 if (AddcNode->getOpcode() != ARMISD::ADDC) 12068 return SDValue(); 12069 12070 // Find the converted UMAAL or quit if it doesn't exist. 12071 SDNode *UmlalNode = nullptr; 12072 SDValue AddHi; 12073 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 12074 UmlalNode = AddcNode->getOperand(0).getNode(); 12075 AddHi = AddcNode->getOperand(1); 12076 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 12077 UmlalNode = AddcNode->getOperand(1).getNode(); 12078 AddHi = AddcNode->getOperand(0); 12079 } else { 12080 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 12081 } 12082 12083 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 12084 // the ADDC as well as Zero. 12085 if (!isNullConstant(UmlalNode->getOperand(3))) 12086 return SDValue(); 12087 12088 if ((isNullConstant(AddeNode->getOperand(0)) && 12089 AddeNode->getOperand(1).getNode() == UmlalNode) || 12090 (AddeNode->getOperand(0).getNode() == UmlalNode && 12091 isNullConstant(AddeNode->getOperand(1)))) { 12092 SelectionDAG &DAG = DCI.DAG; 12093 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 12094 UmlalNode->getOperand(2), AddHi }; 12095 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 12096 DAG.getVTList(MVT::i32, MVT::i32), Ops); 12097 12098 // Replace the ADDs' nodes uses by the UMAAL node's values. 12099 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 12100 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 12101 12102 // Return original node to notify the driver to stop replacing. 12103 return SDValue(AddeNode, 0); 12104 } 12105 return SDValue(); 12106 } 12107 12108 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 12109 const ARMSubtarget *Subtarget) { 12110 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 12111 return SDValue(); 12112 12113 // Check that we have a pair of ADDC and ADDE as operands. 12114 // Both addends of the ADDE must be zero. 12115 SDNode* AddcNode = N->getOperand(2).getNode(); 12116 SDNode* AddeNode = N->getOperand(3).getNode(); 12117 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 12118 (AddeNode->getOpcode() == ARMISD::ADDE) && 12119 isNullConstant(AddeNode->getOperand(0)) && 12120 isNullConstant(AddeNode->getOperand(1)) && 12121 (AddeNode->getOperand(2).getNode() == AddcNode)) 12122 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 12123 DAG.getVTList(MVT::i32, MVT::i32), 12124 {N->getOperand(0), N->getOperand(1), 12125 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 12126 else 12127 return SDValue(); 12128 } 12129 12130 static SDValue PerformAddcSubcCombine(SDNode *N, 12131 TargetLowering::DAGCombinerInfo &DCI, 12132 const ARMSubtarget *Subtarget) { 12133 SelectionDAG &DAG(DCI.DAG); 12134 12135 if (N->getOpcode() == ARMISD::SUBC) { 12136 // (SUBC (ADDE 0, 0, C), 1) -> C 12137 SDValue LHS = N->getOperand(0); 12138 SDValue RHS = N->getOperand(1); 12139 if (LHS->getOpcode() == ARMISD::ADDE && 12140 isNullConstant(LHS->getOperand(0)) && 12141 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 12142 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 12143 } 12144 } 12145 12146 if (Subtarget->isThumb1Only()) { 12147 SDValue RHS = N->getOperand(1); 12148 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12149 int32_t imm = C->getSExtValue(); 12150 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 12151 SDLoc DL(N); 12152 RHS = DAG.getConstant(-imm, DL, MVT::i32); 12153 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 12154 : ARMISD::ADDC; 12155 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 12156 } 12157 } 12158 } 12159 12160 return SDValue(); 12161 } 12162 12163 static SDValue PerformAddeSubeCombine(SDNode *N, 12164 TargetLowering::DAGCombinerInfo &DCI, 12165 const ARMSubtarget *Subtarget) { 12166 if (Subtarget->isThumb1Only()) { 12167 SelectionDAG &DAG = DCI.DAG; 12168 SDValue RHS = N->getOperand(1); 12169 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12170 int64_t imm = C->getSExtValue(); 12171 if (imm < 0) { 12172 SDLoc DL(N); 12173 12174 // The with-carry-in form matches bitwise not instead of the negation. 12175 // Effectively, the inverse interpretation of the carry flag already 12176 // accounts for part of the negation. 12177 RHS = DAG.getConstant(~imm, DL, MVT::i32); 12178 12179 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 12180 : ARMISD::ADDE; 12181 return DAG.getNode(Opcode, DL, N->getVTList(), 12182 N->getOperand(0), RHS, N->getOperand(2)); 12183 } 12184 } 12185 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 12186 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 12187 } 12188 return SDValue(); 12189 } 12190 12191 static SDValue PerformSELECTCombine(SDNode *N, 12192 TargetLowering::DAGCombinerInfo &DCI, 12193 const ARMSubtarget *Subtarget) { 12194 if (!Subtarget->hasMVEIntegerOps()) 12195 return SDValue(); 12196 12197 SDLoc dl(N); 12198 SDValue SetCC; 12199 SDValue LHS; 12200 SDValue RHS; 12201 ISD::CondCode CC; 12202 SDValue TrueVal; 12203 SDValue FalseVal; 12204 12205 if (N->getOpcode() == ISD::SELECT && 12206 N->getOperand(0)->getOpcode() == ISD::SETCC) { 12207 SetCC = N->getOperand(0); 12208 LHS = SetCC->getOperand(0); 12209 RHS = SetCC->getOperand(1); 12210 CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 12211 TrueVal = N->getOperand(1); 12212 FalseVal = N->getOperand(2); 12213 } else if (N->getOpcode() == ISD::SELECT_CC) { 12214 LHS = N->getOperand(0); 12215 RHS = N->getOperand(1); 12216 CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 12217 TrueVal = N->getOperand(2); 12218 FalseVal = N->getOperand(3); 12219 } else { 12220 return SDValue(); 12221 } 12222 12223 unsigned int Opcode = 0; 12224 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN || 12225 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) && 12226 (CC == ISD::SETULT || CC == ISD::SETUGT)) { 12227 Opcode = ARMISD::VMINVu; 12228 if (CC == ISD::SETUGT) 12229 std::swap(TrueVal, FalseVal); 12230 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN || 12231 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) && 12232 (CC == ISD::SETLT || CC == ISD::SETGT)) { 12233 Opcode = ARMISD::VMINVs; 12234 if (CC == ISD::SETGT) 12235 std::swap(TrueVal, FalseVal); 12236 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX || 12237 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) && 12238 (CC == ISD::SETUGT || CC == ISD::SETULT)) { 12239 Opcode = ARMISD::VMAXVu; 12240 if (CC == ISD::SETULT) 12241 std::swap(TrueVal, FalseVal); 12242 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX || 12243 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) && 12244 (CC == ISD::SETGT || CC == ISD::SETLT)) { 12245 Opcode = ARMISD::VMAXVs; 12246 if (CC == ISD::SETLT) 12247 std::swap(TrueVal, FalseVal); 12248 } else 12249 return SDValue(); 12250 12251 // Normalise to the right hand side being the vector reduction 12252 switch (TrueVal->getOpcode()) { 12253 case ISD::VECREDUCE_UMIN: 12254 case ISD::VECREDUCE_SMIN: 12255 case ISD::VECREDUCE_UMAX: 12256 case ISD::VECREDUCE_SMAX: 12257 std::swap(LHS, RHS); 12258 std::swap(TrueVal, FalseVal); 12259 break; 12260 } 12261 12262 EVT VectorType = FalseVal->getOperand(0).getValueType(); 12263 12264 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 && 12265 VectorType != MVT::v4i32) 12266 return SDValue(); 12267 12268 EVT VectorScalarType = VectorType.getVectorElementType(); 12269 12270 // The values being selected must also be the ones being compared 12271 if (TrueVal != LHS || FalseVal != RHS) 12272 return SDValue(); 12273 12274 EVT LeftType = LHS->getValueType(0); 12275 EVT RightType = RHS->getValueType(0); 12276 12277 // The types must match the reduced type too 12278 if (LeftType != VectorScalarType || RightType != VectorScalarType) 12279 return SDValue(); 12280 12281 // Legalise the scalar to an i32 12282 if (VectorScalarType != MVT::i32) 12283 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 12284 12285 // Generate the reduction as an i32 for legalisation purposes 12286 auto Reduction = 12287 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0)); 12288 12289 // The result isn't actually an i32 so truncate it back to its original type 12290 if (VectorScalarType != MVT::i32) 12291 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction); 12292 12293 return Reduction; 12294 } 12295 12296 // A special combine for the vqdmulh family of instructions. This is one of the 12297 // potential set of patterns that could patch this instruction. The base pattern 12298 // you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))). 12299 // This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))), 12300 // which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as 12301 // the max is unnecessary. 12302 static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) { 12303 EVT VT = N->getValueType(0); 12304 SDValue Shft; 12305 ConstantSDNode *Clamp; 12306 12307 if (N->getOpcode() == ISD::SMIN) { 12308 Shft = N->getOperand(0); 12309 Clamp = isConstOrConstSplat(N->getOperand(1)); 12310 } else if (N->getOpcode() == ISD::VSELECT) { 12311 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin. 12312 SDValue Cmp = N->getOperand(0); 12313 if (Cmp.getOpcode() != ISD::SETCC || 12314 cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT || 12315 Cmp.getOperand(0) != N->getOperand(1) || 12316 Cmp.getOperand(1) != N->getOperand(2)) 12317 return SDValue(); 12318 Shft = N->getOperand(1); 12319 Clamp = isConstOrConstSplat(N->getOperand(2)); 12320 } else 12321 return SDValue(); 12322 12323 if (!Clamp) 12324 return SDValue(); 12325 12326 MVT ScalarType; 12327 int ShftAmt = 0; 12328 switch (Clamp->getSExtValue()) { 12329 case (1 << 7) - 1: 12330 ScalarType = MVT::i8; 12331 ShftAmt = 7; 12332 break; 12333 case (1 << 15) - 1: 12334 ScalarType = MVT::i16; 12335 ShftAmt = 15; 12336 break; 12337 case (1ULL << 31) - 1: 12338 ScalarType = MVT::i32; 12339 ShftAmt = 31; 12340 break; 12341 default: 12342 return SDValue(); 12343 } 12344 12345 if (Shft.getOpcode() != ISD::SRA) 12346 return SDValue(); 12347 ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1)); 12348 if (!N1 || N1->getSExtValue() != ShftAmt) 12349 return SDValue(); 12350 12351 SDValue Mul = Shft.getOperand(0); 12352 if (Mul.getOpcode() != ISD::MUL) 12353 return SDValue(); 12354 12355 SDValue Ext0 = Mul.getOperand(0); 12356 SDValue Ext1 = Mul.getOperand(1); 12357 if (Ext0.getOpcode() != ISD::SIGN_EXTEND || 12358 Ext1.getOpcode() != ISD::SIGN_EXTEND) 12359 return SDValue(); 12360 EVT VecVT = Ext0.getOperand(0).getValueType(); 12361 if (VecVT != MVT::v4i32 && VecVT != MVT::v8i16 && VecVT != MVT::v16i8) 12362 return SDValue(); 12363 if (Ext1.getOperand(0).getValueType() != VecVT || 12364 VecVT.getScalarType() != ScalarType || 12365 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2) 12366 return SDValue(); 12367 12368 SDLoc DL(Mul); 12369 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, VecVT, Ext0.getOperand(0), 12370 Ext1.getOperand(0)); 12371 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, VQDMULH); 12372 } 12373 12374 static SDValue PerformVSELECTCombine(SDNode *N, 12375 TargetLowering::DAGCombinerInfo &DCI, 12376 const ARMSubtarget *Subtarget) { 12377 if (!Subtarget->hasMVEIntegerOps()) 12378 return SDValue(); 12379 12380 if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG)) 12381 return V; 12382 12383 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs). 12384 // 12385 // We need to re-implement this optimization here as the implementation in the 12386 // Target-Independent DAGCombiner does not handle the kind of constant we make 12387 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for 12388 // good reason, allowing truncation there would break other targets). 12389 // 12390 // Currently, this is only done for MVE, as it's the only target that benefits 12391 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL). 12392 if (N->getOperand(0).getOpcode() != ISD::XOR) 12393 return SDValue(); 12394 SDValue XOR = N->getOperand(0); 12395 12396 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s. 12397 // It is important to check with truncation allowed as the BUILD_VECTORs we 12398 // generate in those situations will truncate their operands. 12399 ConstantSDNode *Const = 12400 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false, 12401 /*AllowTruncation*/ true); 12402 if (!Const || !Const->isOne()) 12403 return SDValue(); 12404 12405 // Rewrite into vselect(cond, rhs, lhs). 12406 SDValue Cond = XOR->getOperand(0); 12407 SDValue LHS = N->getOperand(1); 12408 SDValue RHS = N->getOperand(2); 12409 EVT Type = N->getValueType(0); 12410 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS); 12411 } 12412 12413 static SDValue PerformABSCombine(SDNode *N, 12414 TargetLowering::DAGCombinerInfo &DCI, 12415 const ARMSubtarget *Subtarget) { 12416 SDValue res; 12417 SelectionDAG &DAG = DCI.DAG; 12418 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12419 12420 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 12421 return SDValue(); 12422 12423 if (!TLI.expandABS(N, res, DAG)) 12424 return SDValue(); 12425 12426 return res; 12427 } 12428 12429 /// PerformADDECombine - Target-specific dag combine transform from 12430 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 12431 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 12432 static SDValue PerformADDECombine(SDNode *N, 12433 TargetLowering::DAGCombinerInfo &DCI, 12434 const ARMSubtarget *Subtarget) { 12435 // Only ARM and Thumb2 support UMLAL/SMLAL. 12436 if (Subtarget->isThumb1Only()) 12437 return PerformAddeSubeCombine(N, DCI, Subtarget); 12438 12439 // Only perform the checks after legalize when the pattern is available. 12440 if (DCI.isBeforeLegalize()) return SDValue(); 12441 12442 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 12443 } 12444 12445 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 12446 /// operands N0 and N1. This is a helper for PerformADDCombine that is 12447 /// called with the default operands, and if that fails, with commuted 12448 /// operands. 12449 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 12450 TargetLowering::DAGCombinerInfo &DCI, 12451 const ARMSubtarget *Subtarget){ 12452 // Attempt to create vpadd for this add. 12453 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 12454 return Result; 12455 12456 // Attempt to create vpaddl for this add. 12457 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 12458 return Result; 12459 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 12460 Subtarget)) 12461 return Result; 12462 12463 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 12464 if (N0.getNode()->hasOneUse()) 12465 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 12466 return Result; 12467 return SDValue(); 12468 } 12469 12470 static SDValue PerformADDVecReduce(SDNode *N, 12471 TargetLowering::DAGCombinerInfo &DCI, 12472 const ARMSubtarget *Subtarget) { 12473 if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64) 12474 return SDValue(); 12475 12476 SDValue N0 = N->getOperand(0); 12477 SDValue N1 = N->getOperand(1); 12478 12479 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this 12480 // will look like: 12481 // t1: i32,i32 = ARMISD::VADDLVs x 12482 // t2: i64 = build_pair t1, t1:1 12483 // t3: i64 = add t2, y 12484 // We also need to check for sext / zext and commutitive adds. 12485 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA, 12486 SDValue NB) { 12487 if (NB->getOpcode() != ISD::BUILD_PAIR) 12488 return SDValue(); 12489 SDValue VecRed = NB->getOperand(0); 12490 if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 || 12491 NB->getOperand(1) != SDValue(VecRed.getNode(), 1)) 12492 return SDValue(); 12493 12494 SDLoc dl(N); 12495 SmallVector<SDValue, 4> Ops; 12496 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12497 DCI.DAG.getConstant(0, dl, MVT::i32))); 12498 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12499 DCI.DAG.getConstant(1, dl, MVT::i32))); 12500 for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++) 12501 Ops.push_back(VecRed->getOperand(i)); 12502 SDValue Red = DCI.DAG.getNode(OpcodeA, dl, 12503 DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops); 12504 return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red, 12505 SDValue(Red.getNode(), 1)); 12506 }; 12507 12508 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1)) 12509 return M; 12510 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1)) 12511 return M; 12512 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0)) 12513 return M; 12514 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0)) 12515 return M; 12516 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1)) 12517 return M; 12518 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1)) 12519 return M; 12520 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0)) 12521 return M; 12522 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0)) 12523 return M; 12524 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1)) 12525 return M; 12526 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1)) 12527 return M; 12528 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0)) 12529 return M; 12530 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0)) 12531 return M; 12532 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1)) 12533 return M; 12534 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1)) 12535 return M; 12536 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0)) 12537 return M; 12538 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0)) 12539 return M; 12540 return SDValue(); 12541 } 12542 12543 bool 12544 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 12545 CombineLevel Level) const { 12546 if (Level == BeforeLegalizeTypes) 12547 return true; 12548 12549 if (N->getOpcode() != ISD::SHL) 12550 return true; 12551 12552 if (Subtarget->isThumb1Only()) { 12553 // Avoid making expensive immediates by commuting shifts. (This logic 12554 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 12555 // for free.) 12556 if (N->getOpcode() != ISD::SHL) 12557 return true; 12558 SDValue N1 = N->getOperand(0); 12559 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 12560 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 12561 return true; 12562 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 12563 if (Const->getAPIntValue().ult(256)) 12564 return false; 12565 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 12566 Const->getAPIntValue().sgt(-256)) 12567 return false; 12568 } 12569 return true; 12570 } 12571 12572 // Turn off commute-with-shift transform after legalization, so it doesn't 12573 // conflict with PerformSHLSimplify. (We could try to detect when 12574 // PerformSHLSimplify would trigger more precisely, but it isn't 12575 // really necessary.) 12576 return false; 12577 } 12578 12579 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 12580 const SDNode *N, CombineLevel Level) const { 12581 if (!Subtarget->isThumb1Only()) 12582 return true; 12583 12584 if (Level == BeforeLegalizeTypes) 12585 return true; 12586 12587 return false; 12588 } 12589 12590 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 12591 if (!Subtarget->hasNEON()) { 12592 if (Subtarget->isThumb1Only()) 12593 return VT.getScalarSizeInBits() <= 32; 12594 return true; 12595 } 12596 return VT.isScalarInteger(); 12597 } 12598 12599 static SDValue PerformSHLSimplify(SDNode *N, 12600 TargetLowering::DAGCombinerInfo &DCI, 12601 const ARMSubtarget *ST) { 12602 // Allow the generic combiner to identify potential bswaps. 12603 if (DCI.isBeforeLegalize()) 12604 return SDValue(); 12605 12606 // DAG combiner will fold: 12607 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 12608 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 12609 // Other code patterns that can be also be modified have the following form: 12610 // b + ((a << 1) | 510) 12611 // b + ((a << 1) & 510) 12612 // b + ((a << 1) ^ 510) 12613 // b + ((a << 1) + 510) 12614 12615 // Many instructions can perform the shift for free, but it requires both 12616 // the operands to be registers. If c1 << c2 is too large, a mov immediate 12617 // instruction will needed. So, unfold back to the original pattern if: 12618 // - if c1 and c2 are small enough that they don't require mov imms. 12619 // - the user(s) of the node can perform an shl 12620 12621 // No shifted operands for 16-bit instructions. 12622 if (ST->isThumb() && ST->isThumb1Only()) 12623 return SDValue(); 12624 12625 // Check that all the users could perform the shl themselves. 12626 for (auto U : N->uses()) { 12627 switch(U->getOpcode()) { 12628 default: 12629 return SDValue(); 12630 case ISD::SUB: 12631 case ISD::ADD: 12632 case ISD::AND: 12633 case ISD::OR: 12634 case ISD::XOR: 12635 case ISD::SETCC: 12636 case ARMISD::CMP: 12637 // Check that the user isn't already using a constant because there 12638 // aren't any instructions that support an immediate operand and a 12639 // shifted operand. 12640 if (isa<ConstantSDNode>(U->getOperand(0)) || 12641 isa<ConstantSDNode>(U->getOperand(1))) 12642 return SDValue(); 12643 12644 // Check that it's not already using a shift. 12645 if (U->getOperand(0).getOpcode() == ISD::SHL || 12646 U->getOperand(1).getOpcode() == ISD::SHL) 12647 return SDValue(); 12648 break; 12649 } 12650 } 12651 12652 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 12653 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 12654 return SDValue(); 12655 12656 if (N->getOperand(0).getOpcode() != ISD::SHL) 12657 return SDValue(); 12658 12659 SDValue SHL = N->getOperand(0); 12660 12661 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12662 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 12663 if (!C1ShlC2 || !C2) 12664 return SDValue(); 12665 12666 APInt C2Int = C2->getAPIntValue(); 12667 APInt C1Int = C1ShlC2->getAPIntValue(); 12668 12669 // Check that performing a lshr will not lose any information. 12670 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 12671 C2Int.getBitWidth() - C2->getZExtValue()); 12672 if ((C1Int & Mask) != C1Int) 12673 return SDValue(); 12674 12675 // Shift the first constant. 12676 C1Int.lshrInPlace(C2Int); 12677 12678 // The immediates are encoded as an 8-bit value that can be rotated. 12679 auto LargeImm = [](const APInt &Imm) { 12680 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 12681 return Imm.getBitWidth() - Zeros > 8; 12682 }; 12683 12684 if (LargeImm(C1Int) || LargeImm(C2Int)) 12685 return SDValue(); 12686 12687 SelectionDAG &DAG = DCI.DAG; 12688 SDLoc dl(N); 12689 SDValue X = SHL.getOperand(0); 12690 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 12691 DAG.getConstant(C1Int, dl, MVT::i32)); 12692 // Shift left to compensate for the lshr of C1Int. 12693 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 12694 12695 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 12696 SHL.dump(); N->dump()); 12697 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 12698 return Res; 12699 } 12700 12701 12702 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 12703 /// 12704 static SDValue PerformADDCombine(SDNode *N, 12705 TargetLowering::DAGCombinerInfo &DCI, 12706 const ARMSubtarget *Subtarget) { 12707 SDValue N0 = N->getOperand(0); 12708 SDValue N1 = N->getOperand(1); 12709 12710 // Only works one way, because it needs an immediate operand. 12711 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12712 return Result; 12713 12714 if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget)) 12715 return Result; 12716 12717 // First try with the default operand order. 12718 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 12719 return Result; 12720 12721 // If that didn't work, try again with the operands commuted. 12722 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 12723 } 12724 12725 // Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC) 12726 // providing -X is as cheap as X (currently, just a constant). 12727 static SDValue PerformSubCSINCCombine(SDNode *N, 12728 TargetLowering::DAGCombinerInfo &DCI) { 12729 if (N->getValueType(0) != MVT::i32 || !isNullConstant(N->getOperand(0))) 12730 return SDValue(); 12731 SDValue CSINC = N->getOperand(1); 12732 if (CSINC.getOpcode() != ARMISD::CSINC) 12733 return SDValue(); 12734 12735 ConstantSDNode *X = dyn_cast<ConstantSDNode>(CSINC.getOperand(0)); 12736 if (!X) 12737 return SDValue(); 12738 12739 return DCI.DAG.getNode(ARMISD::CSINV, SDLoc(N), MVT::i32, 12740 DCI.DAG.getNode(ISD::SUB, SDLoc(N), MVT::i32, 12741 N->getOperand(0), CSINC.getOperand(0)), 12742 CSINC.getOperand(1), CSINC.getOperand(2), 12743 CSINC.getOperand(3)); 12744 } 12745 12746 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 12747 /// 12748 static SDValue PerformSUBCombine(SDNode *N, 12749 TargetLowering::DAGCombinerInfo &DCI, 12750 const ARMSubtarget *Subtarget) { 12751 SDValue N0 = N->getOperand(0); 12752 SDValue N1 = N->getOperand(1); 12753 12754 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 12755 if (N1.getNode()->hasOneUse()) 12756 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 12757 return Result; 12758 12759 if (SDValue R = PerformSubCSINCCombine(N, DCI)) 12760 return R; 12761 12762 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector()) 12763 return SDValue(); 12764 12765 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x)) 12766 // so that we can readily pattern match more mve instructions which can use 12767 // a scalar operand. 12768 SDValue VDup = N->getOperand(1); 12769 if (VDup->getOpcode() != ARMISD::VDUP) 12770 return SDValue(); 12771 12772 SDValue VMov = N->getOperand(0); 12773 if (VMov->getOpcode() == ISD::BITCAST) 12774 VMov = VMov->getOperand(0); 12775 12776 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov)) 12777 return SDValue(); 12778 12779 SDLoc dl(N); 12780 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32, 12781 DCI.DAG.getConstant(0, dl, MVT::i32), 12782 VDup->getOperand(0)); 12783 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate); 12784 } 12785 12786 /// PerformVMULCombine 12787 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 12788 /// special multiplier accumulator forwarding. 12789 /// vmul d3, d0, d2 12790 /// vmla d3, d1, d2 12791 /// is faster than 12792 /// vadd d3, d0, d1 12793 /// vmul d3, d3, d2 12794 // However, for (A + B) * (A + B), 12795 // vadd d2, d0, d1 12796 // vmul d3, d0, d2 12797 // vmla d3, d1, d2 12798 // is slower than 12799 // vadd d2, d0, d1 12800 // vmul d3, d2, d2 12801 static SDValue PerformVMULCombine(SDNode *N, 12802 TargetLowering::DAGCombinerInfo &DCI, 12803 const ARMSubtarget *Subtarget) { 12804 if (!Subtarget->hasVMLxForwarding()) 12805 return SDValue(); 12806 12807 SelectionDAG &DAG = DCI.DAG; 12808 SDValue N0 = N->getOperand(0); 12809 SDValue N1 = N->getOperand(1); 12810 unsigned Opcode = N0.getOpcode(); 12811 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12812 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 12813 Opcode = N1.getOpcode(); 12814 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12815 Opcode != ISD::FADD && Opcode != ISD::FSUB) 12816 return SDValue(); 12817 std::swap(N0, N1); 12818 } 12819 12820 if (N0 == N1) 12821 return SDValue(); 12822 12823 EVT VT = N->getValueType(0); 12824 SDLoc DL(N); 12825 SDValue N00 = N0->getOperand(0); 12826 SDValue N01 = N0->getOperand(1); 12827 return DAG.getNode(Opcode, DL, VT, 12828 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 12829 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 12830 } 12831 12832 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG, 12833 const ARMSubtarget *Subtarget) { 12834 EVT VT = N->getValueType(0); 12835 if (VT != MVT::v2i64) 12836 return SDValue(); 12837 12838 SDValue N0 = N->getOperand(0); 12839 SDValue N1 = N->getOperand(1); 12840 12841 auto IsSignExt = [&](SDValue Op) { 12842 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG) 12843 return SDValue(); 12844 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT(); 12845 if (VT.getScalarSizeInBits() == 32) 12846 return Op->getOperand(0); 12847 return SDValue(); 12848 }; 12849 auto IsZeroExt = [&](SDValue Op) { 12850 // Zero extends are a little more awkward. At the point we are matching 12851 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask. 12852 // That might be before of after a bitcast depending on how the and is 12853 // placed. Because this has to look through bitcasts, it is currently only 12854 // supported on LE. 12855 if (!Subtarget->isLittle()) 12856 return SDValue(); 12857 12858 SDValue And = Op; 12859 if (And->getOpcode() == ISD::BITCAST) 12860 And = And->getOperand(0); 12861 if (And->getOpcode() != ISD::AND) 12862 return SDValue(); 12863 SDValue Mask = And->getOperand(1); 12864 if (Mask->getOpcode() == ISD::BITCAST) 12865 Mask = Mask->getOperand(0); 12866 12867 if (Mask->getOpcode() != ISD::BUILD_VECTOR || 12868 Mask.getValueType() != MVT::v4i32) 12869 return SDValue(); 12870 if (isAllOnesConstant(Mask->getOperand(0)) && 12871 isNullConstant(Mask->getOperand(1)) && 12872 isAllOnesConstant(Mask->getOperand(2)) && 12873 isNullConstant(Mask->getOperand(3))) 12874 return And->getOperand(0); 12875 return SDValue(); 12876 }; 12877 12878 SDLoc dl(N); 12879 if (SDValue Op0 = IsSignExt(N0)) { 12880 if (SDValue Op1 = IsSignExt(N1)) { 12881 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12882 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12883 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a); 12884 } 12885 } 12886 if (SDValue Op0 = IsZeroExt(N0)) { 12887 if (SDValue Op1 = IsZeroExt(N1)) { 12888 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12889 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12890 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a); 12891 } 12892 } 12893 12894 return SDValue(); 12895 } 12896 12897 static SDValue PerformMULCombine(SDNode *N, 12898 TargetLowering::DAGCombinerInfo &DCI, 12899 const ARMSubtarget *Subtarget) { 12900 SelectionDAG &DAG = DCI.DAG; 12901 12902 EVT VT = N->getValueType(0); 12903 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64) 12904 return PerformMVEVMULLCombine(N, DAG, Subtarget); 12905 12906 if (Subtarget->isThumb1Only()) 12907 return SDValue(); 12908 12909 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12910 return SDValue(); 12911 12912 if (VT.is64BitVector() || VT.is128BitVector()) 12913 return PerformVMULCombine(N, DCI, Subtarget); 12914 if (VT != MVT::i32) 12915 return SDValue(); 12916 12917 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12918 if (!C) 12919 return SDValue(); 12920 12921 int64_t MulAmt = C->getSExtValue(); 12922 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 12923 12924 ShiftAmt = ShiftAmt & (32 - 1); 12925 SDValue V = N->getOperand(0); 12926 SDLoc DL(N); 12927 12928 SDValue Res; 12929 MulAmt >>= ShiftAmt; 12930 12931 if (MulAmt >= 0) { 12932 if (isPowerOf2_32(MulAmt - 1)) { 12933 // (mul x, 2^N + 1) => (add (shl x, N), x) 12934 Res = DAG.getNode(ISD::ADD, DL, VT, 12935 V, 12936 DAG.getNode(ISD::SHL, DL, VT, 12937 V, 12938 DAG.getConstant(Log2_32(MulAmt - 1), DL, 12939 MVT::i32))); 12940 } else if (isPowerOf2_32(MulAmt + 1)) { 12941 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12942 Res = DAG.getNode(ISD::SUB, DL, VT, 12943 DAG.getNode(ISD::SHL, DL, VT, 12944 V, 12945 DAG.getConstant(Log2_32(MulAmt + 1), DL, 12946 MVT::i32)), 12947 V); 12948 } else 12949 return SDValue(); 12950 } else { 12951 uint64_t MulAmtAbs = -MulAmt; 12952 if (isPowerOf2_32(MulAmtAbs + 1)) { 12953 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12954 Res = DAG.getNode(ISD::SUB, DL, VT, 12955 V, 12956 DAG.getNode(ISD::SHL, DL, VT, 12957 V, 12958 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 12959 MVT::i32))); 12960 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 12961 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12962 Res = DAG.getNode(ISD::ADD, DL, VT, 12963 V, 12964 DAG.getNode(ISD::SHL, DL, VT, 12965 V, 12966 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 12967 MVT::i32))); 12968 Res = DAG.getNode(ISD::SUB, DL, VT, 12969 DAG.getConstant(0, DL, MVT::i32), Res); 12970 } else 12971 return SDValue(); 12972 } 12973 12974 if (ShiftAmt != 0) 12975 Res = DAG.getNode(ISD::SHL, DL, VT, 12976 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 12977 12978 // Do not add new nodes to DAG combiner worklist. 12979 DCI.CombineTo(N, Res, false); 12980 return SDValue(); 12981 } 12982 12983 static SDValue CombineANDShift(SDNode *N, 12984 TargetLowering::DAGCombinerInfo &DCI, 12985 const ARMSubtarget *Subtarget) { 12986 // Allow DAGCombine to pattern-match before we touch the canonical form. 12987 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12988 return SDValue(); 12989 12990 if (N->getValueType(0) != MVT::i32) 12991 return SDValue(); 12992 12993 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12994 if (!N1C) 12995 return SDValue(); 12996 12997 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 12998 // Don't transform uxtb/uxth. 12999 if (C1 == 255 || C1 == 65535) 13000 return SDValue(); 13001 13002 SDNode *N0 = N->getOperand(0).getNode(); 13003 if (!N0->hasOneUse()) 13004 return SDValue(); 13005 13006 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 13007 return SDValue(); 13008 13009 bool LeftShift = N0->getOpcode() == ISD::SHL; 13010 13011 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13012 if (!N01C) 13013 return SDValue(); 13014 13015 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 13016 if (!C2 || C2 >= 32) 13017 return SDValue(); 13018 13019 // Clear irrelevant bits in the mask. 13020 if (LeftShift) 13021 C1 &= (-1U << C2); 13022 else 13023 C1 &= (-1U >> C2); 13024 13025 SelectionDAG &DAG = DCI.DAG; 13026 SDLoc DL(N); 13027 13028 // We have a pattern of the form "(and (shl x, c2) c1)" or 13029 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 13030 // transform to a pair of shifts, to save materializing c1. 13031 13032 // First pattern: right shift, then mask off leading bits. 13033 // FIXME: Use demanded bits? 13034 if (!LeftShift && isMask_32(C1)) { 13035 uint32_t C3 = countLeadingZeros(C1); 13036 if (C2 < C3) { 13037 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 13038 DAG.getConstant(C3 - C2, DL, MVT::i32)); 13039 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 13040 DAG.getConstant(C3, DL, MVT::i32)); 13041 } 13042 } 13043 13044 // First pattern, reversed: left shift, then mask off trailing bits. 13045 if (LeftShift && isMask_32(~C1)) { 13046 uint32_t C3 = countTrailingZeros(C1); 13047 if (C2 < C3) { 13048 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 13049 DAG.getConstant(C3 - C2, DL, MVT::i32)); 13050 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 13051 DAG.getConstant(C3, DL, MVT::i32)); 13052 } 13053 } 13054 13055 // Second pattern: left shift, then mask off leading bits. 13056 // FIXME: Use demanded bits? 13057 if (LeftShift && isShiftedMask_32(C1)) { 13058 uint32_t Trailing = countTrailingZeros(C1); 13059 uint32_t C3 = countLeadingZeros(C1); 13060 if (Trailing == C2 && C2 + C3 < 32) { 13061 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 13062 DAG.getConstant(C2 + C3, DL, MVT::i32)); 13063 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 13064 DAG.getConstant(C3, DL, MVT::i32)); 13065 } 13066 } 13067 13068 // Second pattern, reversed: right shift, then mask off trailing bits. 13069 // FIXME: Handle other patterns of known/demanded bits. 13070 if (!LeftShift && isShiftedMask_32(C1)) { 13071 uint32_t Leading = countLeadingZeros(C1); 13072 uint32_t C3 = countTrailingZeros(C1); 13073 if (Leading == C2 && C2 + C3 < 32) { 13074 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 13075 DAG.getConstant(C2 + C3, DL, MVT::i32)); 13076 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 13077 DAG.getConstant(C3, DL, MVT::i32)); 13078 } 13079 } 13080 13081 // FIXME: Transform "(and (shl x, c2) c1)" -> 13082 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 13083 // c1. 13084 return SDValue(); 13085 } 13086 13087 static SDValue PerformANDCombine(SDNode *N, 13088 TargetLowering::DAGCombinerInfo &DCI, 13089 const ARMSubtarget *Subtarget) { 13090 // Attempt to use immediate-form VBIC 13091 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 13092 SDLoc dl(N); 13093 EVT VT = N->getValueType(0); 13094 SelectionDAG &DAG = DCI.DAG; 13095 13096 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 || 13097 VT == MVT::v8i1 || VT == MVT::v16i1) 13098 return SDValue(); 13099 13100 APInt SplatBits, SplatUndef; 13101 unsigned SplatBitSize; 13102 bool HasAnyUndefs; 13103 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 13104 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 13105 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 13106 SplatBitSize == 64) { 13107 EVT VbicVT; 13108 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 13109 SplatUndef.getZExtValue(), SplatBitSize, 13110 DAG, dl, VbicVT, VT, OtherModImm); 13111 if (Val.getNode()) { 13112 SDValue Input = 13113 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 13114 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 13115 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 13116 } 13117 } 13118 } 13119 13120 if (!Subtarget->isThumb1Only()) { 13121 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 13122 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 13123 return Result; 13124 13125 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13126 return Result; 13127 } 13128 13129 if (Subtarget->isThumb1Only()) 13130 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 13131 return Result; 13132 13133 return SDValue(); 13134 } 13135 13136 // Try combining OR nodes to SMULWB, SMULWT. 13137 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 13138 TargetLowering::DAGCombinerInfo &DCI, 13139 const ARMSubtarget *Subtarget) { 13140 if (!Subtarget->hasV6Ops() || 13141 (Subtarget->isThumb() && 13142 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 13143 return SDValue(); 13144 13145 SDValue SRL = OR->getOperand(0); 13146 SDValue SHL = OR->getOperand(1); 13147 13148 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 13149 SRL = OR->getOperand(1); 13150 SHL = OR->getOperand(0); 13151 } 13152 if (!isSRL16(SRL) || !isSHL16(SHL)) 13153 return SDValue(); 13154 13155 // The first operands to the shifts need to be the two results from the 13156 // same smul_lohi node. 13157 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 13158 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 13159 return SDValue(); 13160 13161 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 13162 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 13163 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 13164 return SDValue(); 13165 13166 // Now we have: 13167 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 13168 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 13169 // For SMUWB the 16-bit value will signed extended somehow. 13170 // For SMULWT only the SRA is required. 13171 // Check both sides of SMUL_LOHI 13172 SDValue OpS16 = SMULLOHI->getOperand(0); 13173 SDValue OpS32 = SMULLOHI->getOperand(1); 13174 13175 SelectionDAG &DAG = DCI.DAG; 13176 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 13177 OpS16 = OpS32; 13178 OpS32 = SMULLOHI->getOperand(0); 13179 } 13180 13181 SDLoc dl(OR); 13182 unsigned Opcode = 0; 13183 if (isS16(OpS16, DAG)) 13184 Opcode = ARMISD::SMULWB; 13185 else if (isSRA16(OpS16)) { 13186 Opcode = ARMISD::SMULWT; 13187 OpS16 = OpS16->getOperand(0); 13188 } 13189 else 13190 return SDValue(); 13191 13192 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 13193 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 13194 return SDValue(OR, 0); 13195 } 13196 13197 static SDValue PerformORCombineToBFI(SDNode *N, 13198 TargetLowering::DAGCombinerInfo &DCI, 13199 const ARMSubtarget *Subtarget) { 13200 // BFI is only available on V6T2+ 13201 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 13202 return SDValue(); 13203 13204 EVT VT = N->getValueType(0); 13205 SDValue N0 = N->getOperand(0); 13206 SDValue N1 = N->getOperand(1); 13207 SelectionDAG &DAG = DCI.DAG; 13208 SDLoc DL(N); 13209 // 1) or (and A, mask), val => ARMbfi A, val, mask 13210 // iff (val & mask) == val 13211 // 13212 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 13213 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 13214 // && mask == ~mask2 13215 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 13216 // && ~mask == mask2 13217 // (i.e., copy a bitfield value into another bitfield of the same width) 13218 13219 if (VT != MVT::i32) 13220 return SDValue(); 13221 13222 SDValue N00 = N0.getOperand(0); 13223 13224 // The value and the mask need to be constants so we can verify this is 13225 // actually a bitfield set. If the mask is 0xffff, we can do better 13226 // via a movt instruction, so don't use BFI in that case. 13227 SDValue MaskOp = N0.getOperand(1); 13228 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 13229 if (!MaskC) 13230 return SDValue(); 13231 unsigned Mask = MaskC->getZExtValue(); 13232 if (Mask == 0xffff) 13233 return SDValue(); 13234 SDValue Res; 13235 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 13236 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 13237 if (N1C) { 13238 unsigned Val = N1C->getZExtValue(); 13239 if ((Val & ~Mask) != Val) 13240 return SDValue(); 13241 13242 if (ARM::isBitFieldInvertedMask(Mask)) { 13243 Val >>= countTrailingZeros(~Mask); 13244 13245 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 13246 DAG.getConstant(Val, DL, MVT::i32), 13247 DAG.getConstant(Mask, DL, MVT::i32)); 13248 13249 DCI.CombineTo(N, Res, false); 13250 // Return value from the original node to inform the combiner than N is 13251 // now dead. 13252 return SDValue(N, 0); 13253 } 13254 } else if (N1.getOpcode() == ISD::AND) { 13255 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 13256 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 13257 if (!N11C) 13258 return SDValue(); 13259 unsigned Mask2 = N11C->getZExtValue(); 13260 13261 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 13262 // as is to match. 13263 if (ARM::isBitFieldInvertedMask(Mask) && 13264 (Mask == ~Mask2)) { 13265 // The pack halfword instruction works better for masks that fit it, 13266 // so use that when it's available. 13267 if (Subtarget->hasDSP() && 13268 (Mask == 0xffff || Mask == 0xffff0000)) 13269 return SDValue(); 13270 // 2a 13271 unsigned amt = countTrailingZeros(Mask2); 13272 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 13273 DAG.getConstant(amt, DL, MVT::i32)); 13274 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 13275 DAG.getConstant(Mask, DL, MVT::i32)); 13276 DCI.CombineTo(N, Res, false); 13277 // Return value from the original node to inform the combiner than N is 13278 // now dead. 13279 return SDValue(N, 0); 13280 } else if (ARM::isBitFieldInvertedMask(~Mask) && 13281 (~Mask == Mask2)) { 13282 // The pack halfword instruction works better for masks that fit it, 13283 // so use that when it's available. 13284 if (Subtarget->hasDSP() && 13285 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 13286 return SDValue(); 13287 // 2b 13288 unsigned lsb = countTrailingZeros(Mask); 13289 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 13290 DAG.getConstant(lsb, DL, MVT::i32)); 13291 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 13292 DAG.getConstant(Mask2, DL, MVT::i32)); 13293 DCI.CombineTo(N, Res, false); 13294 // Return value from the original node to inform the combiner than N is 13295 // now dead. 13296 return SDValue(N, 0); 13297 } 13298 } 13299 13300 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 13301 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 13302 ARM::isBitFieldInvertedMask(~Mask)) { 13303 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 13304 // where lsb(mask) == #shamt and masked bits of B are known zero. 13305 SDValue ShAmt = N00.getOperand(1); 13306 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 13307 unsigned LSB = countTrailingZeros(Mask); 13308 if (ShAmtC != LSB) 13309 return SDValue(); 13310 13311 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 13312 DAG.getConstant(~Mask, DL, MVT::i32)); 13313 13314 DCI.CombineTo(N, Res, false); 13315 // Return value from the original node to inform the combiner than N is 13316 // now dead. 13317 return SDValue(N, 0); 13318 } 13319 13320 return SDValue(); 13321 } 13322 13323 static bool isValidMVECond(unsigned CC, bool IsFloat) { 13324 switch (CC) { 13325 case ARMCC::EQ: 13326 case ARMCC::NE: 13327 case ARMCC::LE: 13328 case ARMCC::GT: 13329 case ARMCC::GE: 13330 case ARMCC::LT: 13331 return true; 13332 case ARMCC::HS: 13333 case ARMCC::HI: 13334 return !IsFloat; 13335 default: 13336 return false; 13337 }; 13338 } 13339 13340 static ARMCC::CondCodes getVCMPCondCode(SDValue N) { 13341 if (N->getOpcode() == ARMISD::VCMP) 13342 return (ARMCC::CondCodes)N->getConstantOperandVal(2); 13343 else if (N->getOpcode() == ARMISD::VCMPZ) 13344 return (ARMCC::CondCodes)N->getConstantOperandVal(1); 13345 else 13346 llvm_unreachable("Not a VCMP/VCMPZ!"); 13347 } 13348 13349 static bool CanInvertMVEVCMP(SDValue N) { 13350 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N)); 13351 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint()); 13352 } 13353 13354 static SDValue PerformORCombine_i1(SDNode *N, 13355 TargetLowering::DAGCombinerInfo &DCI, 13356 const ARMSubtarget *Subtarget) { 13357 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 13358 // together with predicates 13359 EVT VT = N->getValueType(0); 13360 SDLoc DL(N); 13361 SDValue N0 = N->getOperand(0); 13362 SDValue N1 = N->getOperand(1); 13363 13364 auto IsFreelyInvertable = [&](SDValue V) { 13365 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ) 13366 return CanInvertMVEVCMP(V); 13367 return false; 13368 }; 13369 13370 // At least one operand must be freely invertable. 13371 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1))) 13372 return SDValue(); 13373 13374 SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT); 13375 SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT); 13376 SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1); 13377 return DCI.DAG.getLogicalNOT(DL, And, VT); 13378 } 13379 13380 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 13381 static SDValue PerformORCombine(SDNode *N, 13382 TargetLowering::DAGCombinerInfo &DCI, 13383 const ARMSubtarget *Subtarget) { 13384 // Attempt to use immediate-form VORR 13385 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 13386 SDLoc dl(N); 13387 EVT VT = N->getValueType(0); 13388 SelectionDAG &DAG = DCI.DAG; 13389 13390 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13391 return SDValue(); 13392 13393 if (Subtarget->hasMVEIntegerOps() && 13394 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 13395 return PerformORCombine_i1(N, DCI, Subtarget); 13396 13397 APInt SplatBits, SplatUndef; 13398 unsigned SplatBitSize; 13399 bool HasAnyUndefs; 13400 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 13401 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 13402 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 13403 SplatBitSize == 64) { 13404 EVT VorrVT; 13405 SDValue Val = 13406 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 13407 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm); 13408 if (Val.getNode()) { 13409 SDValue Input = 13410 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 13411 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 13412 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 13413 } 13414 } 13415 } 13416 13417 if (!Subtarget->isThumb1Only()) { 13418 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 13419 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13420 return Result; 13421 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 13422 return Result; 13423 } 13424 13425 SDValue N0 = N->getOperand(0); 13426 SDValue N1 = N->getOperand(1); 13427 13428 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 13429 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 13430 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 13431 13432 // The code below optimizes (or (and X, Y), Z). 13433 // The AND operand needs to have a single user to make these optimizations 13434 // profitable. 13435 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 13436 return SDValue(); 13437 13438 APInt SplatUndef; 13439 unsigned SplatBitSize; 13440 bool HasAnyUndefs; 13441 13442 APInt SplatBits0, SplatBits1; 13443 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 13444 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 13445 // Ensure that the second operand of both ands are constants 13446 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 13447 HasAnyUndefs) && !HasAnyUndefs) { 13448 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 13449 HasAnyUndefs) && !HasAnyUndefs) { 13450 // Ensure that the bit width of the constants are the same and that 13451 // the splat arguments are logical inverses as per the pattern we 13452 // are trying to simplify. 13453 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 13454 SplatBits0 == ~SplatBits1) { 13455 // Canonicalize the vector type to make instruction selection 13456 // simpler. 13457 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 13458 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT, 13459 N0->getOperand(1), 13460 N0->getOperand(0), 13461 N1->getOperand(0)); 13462 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 13463 } 13464 } 13465 } 13466 } 13467 13468 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 13469 // reasonable. 13470 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 13471 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 13472 return Res; 13473 } 13474 13475 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13476 return Result; 13477 13478 return SDValue(); 13479 } 13480 13481 static SDValue PerformXORCombine(SDNode *N, 13482 TargetLowering::DAGCombinerInfo &DCI, 13483 const ARMSubtarget *Subtarget) { 13484 EVT VT = N->getValueType(0); 13485 SelectionDAG &DAG = DCI.DAG; 13486 13487 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13488 return SDValue(); 13489 13490 if (!Subtarget->isThumb1Only()) { 13491 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 13492 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13493 return Result; 13494 13495 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13496 return Result; 13497 } 13498 13499 if (Subtarget->hasMVEIntegerOps()) { 13500 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition. 13501 SDValue N0 = N->getOperand(0); 13502 SDValue N1 = N->getOperand(1); 13503 const TargetLowering *TLI = Subtarget->getTargetLowering(); 13504 if (TLI->isConstTrueVal(N1.getNode()) && 13505 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) { 13506 if (CanInvertMVEVCMP(N0)) { 13507 SDLoc DL(N0); 13508 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0)); 13509 13510 SmallVector<SDValue, 4> Ops; 13511 Ops.push_back(N0->getOperand(0)); 13512 if (N0->getOpcode() == ARMISD::VCMP) 13513 Ops.push_back(N0->getOperand(1)); 13514 Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32)); 13515 return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops); 13516 } 13517 } 13518 } 13519 13520 return SDValue(); 13521 } 13522 13523 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 13524 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 13525 // their position in "to" (Rd). 13526 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 13527 assert(N->getOpcode() == ARMISD::BFI); 13528 13529 SDValue From = N->getOperand(1); 13530 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 13531 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 13532 13533 // If the Base came from a SHR #C, we can deduce that it is really testing bit 13534 // #C in the base of the SHR. 13535 if (From->getOpcode() == ISD::SRL && 13536 isa<ConstantSDNode>(From->getOperand(1))) { 13537 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 13538 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 13539 FromMask <<= Shift.getLimitedValue(31); 13540 From = From->getOperand(0); 13541 } 13542 13543 return From; 13544 } 13545 13546 // If A and B contain one contiguous set of bits, does A | B == A . B? 13547 // 13548 // Neither A nor B must be zero. 13549 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 13550 unsigned LastActiveBitInA = A.countTrailingZeros(); 13551 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 13552 return LastActiveBitInA - 1 == FirstActiveBitInB; 13553 } 13554 13555 static SDValue FindBFIToCombineWith(SDNode *N) { 13556 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 13557 // if one exists. 13558 APInt ToMask, FromMask; 13559 SDValue From = ParseBFI(N, ToMask, FromMask); 13560 SDValue To = N->getOperand(0); 13561 13562 // Now check for a compatible BFI to merge with. We can pass through BFIs that 13563 // aren't compatible, but not if they set the same bit in their destination as 13564 // we do (or that of any BFI we're going to combine with). 13565 SDValue V = To; 13566 APInt CombinedToMask = ToMask; 13567 while (V.getOpcode() == ARMISD::BFI) { 13568 APInt NewToMask, NewFromMask; 13569 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 13570 if (NewFrom != From) { 13571 // This BFI has a different base. Keep going. 13572 CombinedToMask |= NewToMask; 13573 V = V.getOperand(0); 13574 continue; 13575 } 13576 13577 // Do the written bits conflict with any we've seen so far? 13578 if ((NewToMask & CombinedToMask).getBoolValue()) 13579 // Conflicting bits - bail out because going further is unsafe. 13580 return SDValue(); 13581 13582 // Are the new bits contiguous when combined with the old bits? 13583 if (BitsProperlyConcatenate(ToMask, NewToMask) && 13584 BitsProperlyConcatenate(FromMask, NewFromMask)) 13585 return V; 13586 if (BitsProperlyConcatenate(NewToMask, ToMask) && 13587 BitsProperlyConcatenate(NewFromMask, FromMask)) 13588 return V; 13589 13590 // We've seen a write to some bits, so track it. 13591 CombinedToMask |= NewToMask; 13592 // Keep going... 13593 V = V.getOperand(0); 13594 } 13595 13596 return SDValue(); 13597 } 13598 13599 static SDValue PerformBFICombine(SDNode *N, 13600 TargetLowering::DAGCombinerInfo &DCI) { 13601 SDValue N1 = N->getOperand(1); 13602 if (N1.getOpcode() == ISD::AND) { 13603 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 13604 // the bits being cleared by the AND are not demanded by the BFI. 13605 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 13606 if (!N11C) 13607 return SDValue(); 13608 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13609 unsigned LSB = countTrailingZeros(~InvMask); 13610 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 13611 assert(Width < 13612 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 13613 "undefined behavior"); 13614 unsigned Mask = (1u << Width) - 1; 13615 unsigned Mask2 = N11C->getZExtValue(); 13616 if ((Mask & (~Mask2)) == 0) 13617 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 13618 N->getOperand(0), N1.getOperand(0), 13619 N->getOperand(2)); 13620 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 13621 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 13622 // Keep track of any consecutive bits set that all come from the same base 13623 // value. We can combine these together into a single BFI. 13624 SDValue CombineBFI = FindBFIToCombineWith(N); 13625 if (CombineBFI == SDValue()) 13626 return SDValue(); 13627 13628 // We've found a BFI. 13629 APInt ToMask1, FromMask1; 13630 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 13631 13632 APInt ToMask2, FromMask2; 13633 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 13634 assert(From1 == From2); 13635 (void)From2; 13636 13637 // First, unlink CombineBFI. 13638 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 13639 // Then create a new BFI, combining the two together. 13640 APInt NewFromMask = FromMask1 | FromMask2; 13641 APInt NewToMask = ToMask1 | ToMask2; 13642 13643 EVT VT = N->getValueType(0); 13644 SDLoc dl(N); 13645 13646 if (NewFromMask[0] == 0) 13647 From1 = DCI.DAG.getNode( 13648 ISD::SRL, dl, VT, From1, 13649 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 13650 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 13651 DCI.DAG.getConstant(~NewToMask, dl, VT)); 13652 } 13653 return SDValue(); 13654 } 13655 13656 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 13657 /// ARMISD::VMOVRRD. 13658 static SDValue PerformVMOVRRDCombine(SDNode *N, 13659 TargetLowering::DAGCombinerInfo &DCI, 13660 const ARMSubtarget *Subtarget) { 13661 // vmovrrd(vmovdrr x, y) -> x,y 13662 SDValue InDouble = N->getOperand(0); 13663 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 13664 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 13665 13666 // vmovrrd(load f64) -> (load i32), (load i32) 13667 SDNode *InNode = InDouble.getNode(); 13668 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 13669 InNode->getValueType(0) == MVT::f64 && 13670 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 13671 !cast<LoadSDNode>(InNode)->isVolatile()) { 13672 // TODO: Should this be done for non-FrameIndex operands? 13673 LoadSDNode *LD = cast<LoadSDNode>(InNode); 13674 13675 SelectionDAG &DAG = DCI.DAG; 13676 SDLoc DL(LD); 13677 SDValue BasePtr = LD->getBasePtr(); 13678 SDValue NewLD1 = 13679 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 13680 LD->getAlignment(), LD->getMemOperand()->getFlags()); 13681 13682 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 13683 DAG.getConstant(4, DL, MVT::i32)); 13684 13685 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 13686 LD->getPointerInfo().getWithOffset(4), 13687 std::min(4U, LD->getAlignment()), 13688 LD->getMemOperand()->getFlags()); 13689 13690 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 13691 if (DCI.DAG.getDataLayout().isBigEndian()) 13692 std::swap (NewLD1, NewLD2); 13693 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 13694 return Result; 13695 } 13696 13697 // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d 13698 if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 13699 isa<ConstantSDNode>(InDouble.getOperand(1))) { 13700 SDValue BV = InDouble.getOperand(0); 13701 // Look up through any nop bitcasts 13702 while (BV.getOpcode() == ISD::BITCAST && 13703 (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) 13704 BV = BV.getOperand(0); 13705 if (BV.getValueType() != MVT::v4i32 || BV.getOpcode() != ISD::BUILD_VECTOR) 13706 return SDValue(); 13707 unsigned Offset = InDouble.getConstantOperandVal(1) == 1 ? 2 : 0; 13708 if (Subtarget->isLittle()) 13709 return DCI.DAG.getMergeValues( 13710 {BV.getOperand(Offset), BV.getOperand(Offset + 1)}, SDLoc(N)); 13711 else 13712 return DCI.DAG.getMergeValues( 13713 {BV.getOperand(Offset + 1), BV.getOperand(Offset)}, SDLoc(N)); 13714 } 13715 13716 return SDValue(); 13717 } 13718 13719 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 13720 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 13721 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 13722 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 13723 SDValue Op0 = N->getOperand(0); 13724 SDValue Op1 = N->getOperand(1); 13725 if (Op0.getOpcode() == ISD::BITCAST) 13726 Op0 = Op0.getOperand(0); 13727 if (Op1.getOpcode() == ISD::BITCAST) 13728 Op1 = Op1.getOperand(0); 13729 if (Op0.getOpcode() == ARMISD::VMOVRRD && 13730 Op0.getNode() == Op1.getNode() && 13731 Op0.getResNo() == 0 && Op1.getResNo() == 1) 13732 return DAG.getNode(ISD::BITCAST, SDLoc(N), 13733 N->getValueType(0), Op0.getOperand(0)); 13734 return SDValue(); 13735 } 13736 13737 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13738 SDValue Op0 = N->getOperand(0); 13739 13740 // VMOVhr (VMOVrh (X)) -> X 13741 if (Op0->getOpcode() == ARMISD::VMOVrh) 13742 return Op0->getOperand(0); 13743 13744 // FullFP16: half values are passed in S-registers, and we don't 13745 // need any of the bitcast and moves: 13746 // 13747 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 13748 // t5: i32 = bitcast t2 13749 // t18: f16 = ARMISD::VMOVhr t5 13750 if (Op0->getOpcode() == ISD::BITCAST) { 13751 SDValue Copy = Op0->getOperand(0); 13752 if (Copy.getValueType() == MVT::f32 && 13753 Copy->getOpcode() == ISD::CopyFromReg) { 13754 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)}; 13755 SDValue NewCopy = 13756 DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops); 13757 return NewCopy; 13758 } 13759 } 13760 13761 // fold (VMOVhr (load x)) -> (load (f16*)x) 13762 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) { 13763 if (LN0->hasOneUse() && LN0->isUnindexed() && 13764 LN0->getMemoryVT() == MVT::i16) { 13765 SDValue Load = 13766 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(), 13767 LN0->getBasePtr(), LN0->getMemOperand()); 13768 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13769 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1)); 13770 return Load; 13771 } 13772 } 13773 13774 // Only the bottom 16 bits of the source register are used. 13775 APInt DemandedMask = APInt::getLowBitsSet(32, 16); 13776 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 13777 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI)) 13778 return SDValue(N, 0); 13779 13780 return SDValue(); 13781 } 13782 13783 static SDValue PerformVMOVrhCombine(SDNode *N, 13784 TargetLowering::DAGCombinerInfo &DCI) { 13785 SDValue N0 = N->getOperand(0); 13786 EVT VT = N->getValueType(0); 13787 13788 // fold (VMOVrh (fpconst x)) -> const x 13789 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) { 13790 APFloat V = C->getValueAPF(); 13791 return DCI.DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT); 13792 } 13793 13794 // fold (VMOVrh (load x)) -> (zextload (i16*)x) 13795 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) { 13796 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 13797 13798 SDValue Load = 13799 DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(), 13800 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand()); 13801 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13802 DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 13803 return Load; 13804 } 13805 13806 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n) 13807 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 13808 isa<ConstantSDNode>(N0->getOperand(1))) 13809 return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0), 13810 N0->getOperand(1)); 13811 13812 return SDValue(); 13813 } 13814 13815 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 13816 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 13817 /// i64 vector to have f64 elements, since the value can then be loaded 13818 /// directly into a VFP register. 13819 static bool hasNormalLoadOperand(SDNode *N) { 13820 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 13821 for (unsigned i = 0; i < NumElts; ++i) { 13822 SDNode *Elt = N->getOperand(i).getNode(); 13823 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 13824 return true; 13825 } 13826 return false; 13827 } 13828 13829 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 13830 /// ISD::BUILD_VECTOR. 13831 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 13832 TargetLowering::DAGCombinerInfo &DCI, 13833 const ARMSubtarget *Subtarget) { 13834 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 13835 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 13836 // into a pair of GPRs, which is fine when the value is used as a scalar, 13837 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 13838 SelectionDAG &DAG = DCI.DAG; 13839 if (N->getNumOperands() == 2) 13840 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 13841 return RV; 13842 13843 // Load i64 elements as f64 values so that type legalization does not split 13844 // them up into i32 values. 13845 EVT VT = N->getValueType(0); 13846 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 13847 return SDValue(); 13848 SDLoc dl(N); 13849 SmallVector<SDValue, 8> Ops; 13850 unsigned NumElts = VT.getVectorNumElements(); 13851 for (unsigned i = 0; i < NumElts; ++i) { 13852 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 13853 Ops.push_back(V); 13854 // Make the DAGCombiner fold the bitcast. 13855 DCI.AddToWorklist(V.getNode()); 13856 } 13857 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 13858 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 13859 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 13860 } 13861 13862 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 13863 static SDValue 13864 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13865 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 13866 // At that time, we may have inserted bitcasts from integer to float. 13867 // If these bitcasts have survived DAGCombine, change the lowering of this 13868 // BUILD_VECTOR in something more vector friendly, i.e., that does not 13869 // force to use floating point types. 13870 13871 // Make sure we can change the type of the vector. 13872 // This is possible iff: 13873 // 1. The vector is only used in a bitcast to a integer type. I.e., 13874 // 1.1. Vector is used only once. 13875 // 1.2. Use is a bit convert to an integer type. 13876 // 2. The size of its operands are 32-bits (64-bits are not legal). 13877 EVT VT = N->getValueType(0); 13878 EVT EltVT = VT.getVectorElementType(); 13879 13880 // Check 1.1. and 2. 13881 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 13882 return SDValue(); 13883 13884 // By construction, the input type must be float. 13885 assert(EltVT == MVT::f32 && "Unexpected type!"); 13886 13887 // Check 1.2. 13888 SDNode *Use = *N->use_begin(); 13889 if (Use->getOpcode() != ISD::BITCAST || 13890 Use->getValueType(0).isFloatingPoint()) 13891 return SDValue(); 13892 13893 // Check profitability. 13894 // Model is, if more than half of the relevant operands are bitcast from 13895 // i32, turn the build_vector into a sequence of insert_vector_elt. 13896 // Relevant operands are everything that is not statically 13897 // (i.e., at compile time) bitcasted. 13898 unsigned NumOfBitCastedElts = 0; 13899 unsigned NumElts = VT.getVectorNumElements(); 13900 unsigned NumOfRelevantElts = NumElts; 13901 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 13902 SDValue Elt = N->getOperand(Idx); 13903 if (Elt->getOpcode() == ISD::BITCAST) { 13904 // Assume only bit cast to i32 will go away. 13905 if (Elt->getOperand(0).getValueType() == MVT::i32) 13906 ++NumOfBitCastedElts; 13907 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 13908 // Constants are statically casted, thus do not count them as 13909 // relevant operands. 13910 --NumOfRelevantElts; 13911 } 13912 13913 // Check if more than half of the elements require a non-free bitcast. 13914 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 13915 return SDValue(); 13916 13917 SelectionDAG &DAG = DCI.DAG; 13918 // Create the new vector type. 13919 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 13920 // Check if the type is legal. 13921 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13922 if (!TLI.isTypeLegal(VecVT)) 13923 return SDValue(); 13924 13925 // Combine: 13926 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 13927 // => BITCAST INSERT_VECTOR_ELT 13928 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 13929 // (BITCAST EN), N. 13930 SDValue Vec = DAG.getUNDEF(VecVT); 13931 SDLoc dl(N); 13932 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 13933 SDValue V = N->getOperand(Idx); 13934 if (V.isUndef()) 13935 continue; 13936 if (V.getOpcode() == ISD::BITCAST && 13937 V->getOperand(0).getValueType() == MVT::i32) 13938 // Fold obvious case. 13939 V = V.getOperand(0); 13940 else { 13941 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 13942 // Make the DAGCombiner fold the bitcasts. 13943 DCI.AddToWorklist(V.getNode()); 13944 } 13945 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 13946 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 13947 } 13948 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 13949 // Make the DAGCombiner fold the bitcasts. 13950 DCI.AddToWorklist(Vec.getNode()); 13951 return Vec; 13952 } 13953 13954 static SDValue 13955 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13956 EVT VT = N->getValueType(0); 13957 SDValue Op = N->getOperand(0); 13958 SDLoc dl(N); 13959 13960 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x) 13961 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) { 13962 // If the valuetypes are the same, we can remove the cast entirely. 13963 if (Op->getOperand(0).getValueType() == VT) 13964 return Op->getOperand(0); 13965 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0)); 13966 } 13967 13968 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce 13969 // more VPNOT which might get folded as else predicates. 13970 if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) { 13971 SDValue X = 13972 DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0)); 13973 SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 13974 DCI.DAG.getConstant(65535, dl, MVT::i32)); 13975 return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C); 13976 } 13977 13978 // Only the bottom 16 bits of the source register are used. 13979 if (Op.getValueType() == MVT::i32) { 13980 APInt DemandedMask = APInt::getLowBitsSet(32, 16); 13981 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 13982 if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI)) 13983 return SDValue(N, 0); 13984 } 13985 return SDValue(); 13986 } 13987 13988 static SDValue 13989 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 13990 const ARMSubtarget *ST) { 13991 EVT VT = N->getValueType(0); 13992 SDValue Op = N->getOperand(0); 13993 SDLoc dl(N); 13994 13995 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST 13996 if (ST->isLittle()) 13997 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op); 13998 13999 // VECTOR_REG_CAST undef -> undef 14000 if (Op.isUndef()) 14001 return DCI.DAG.getUNDEF(VT); 14002 14003 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x) 14004 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) { 14005 // If the valuetypes are the same, we can remove the cast entirely. 14006 if (Op->getOperand(0).getValueType() == VT) 14007 return Op->getOperand(0); 14008 return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0)); 14009 } 14010 14011 return SDValue(); 14012 } 14013 14014 static SDValue PerformVCMPCombine(SDNode *N, 14015 TargetLowering::DAGCombinerInfo &DCI, 14016 const ARMSubtarget *Subtarget) { 14017 if (!Subtarget->hasMVEIntegerOps()) 14018 return SDValue(); 14019 14020 EVT VT = N->getValueType(0); 14021 SDValue Op0 = N->getOperand(0); 14022 SDValue Op1 = N->getOperand(1); 14023 ARMCC::CondCodes Cond = 14024 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 14025 SDLoc dl(N); 14026 14027 // vcmp X, 0, cc -> vcmpz X, cc 14028 if (isZeroVector(Op1)) 14029 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, 14030 N->getOperand(2)); 14031 14032 unsigned SwappedCond = getSwappedCondition(Cond); 14033 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) { 14034 // vcmp 0, X, cc -> vcmpz X, reversed(cc) 14035 if (isZeroVector(Op0)) 14036 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1, 14037 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 14038 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc) 14039 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP) 14040 return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0, 14041 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 14042 } 14043 14044 return SDValue(); 14045 } 14046 14047 /// PerformInsertEltCombine - Target-specific dag combine xforms for 14048 /// ISD::INSERT_VECTOR_ELT. 14049 static SDValue PerformInsertEltCombine(SDNode *N, 14050 TargetLowering::DAGCombinerInfo &DCI) { 14051 // Bitcast an i64 load inserted into a vector to f64. 14052 // Otherwise, the i64 value will be legalized to a pair of i32 values. 14053 EVT VT = N->getValueType(0); 14054 SDNode *Elt = N->getOperand(1).getNode(); 14055 if (VT.getVectorElementType() != MVT::i64 || 14056 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 14057 return SDValue(); 14058 14059 SelectionDAG &DAG = DCI.DAG; 14060 SDLoc dl(N); 14061 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 14062 VT.getVectorNumElements()); 14063 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 14064 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 14065 // Make the DAGCombiner fold the bitcasts. 14066 DCI.AddToWorklist(Vec.getNode()); 14067 DCI.AddToWorklist(V.getNode()); 14068 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 14069 Vec, V, N->getOperand(2)); 14070 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 14071 } 14072 14073 // Convert a pair of extracts from the same base vector to a VMOVRRD. Either 14074 // directly or bitcast to an integer if the original is a float vector. 14075 // extract(x, n); extract(x, n+1) -> VMOVRRD(extract v2f64 x, n/2) 14076 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD(extract x, n/2) 14077 static SDValue 14078 PerformExtractEltToVMOVRRD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 14079 EVT VT = N->getValueType(0); 14080 SDLoc dl(N); 14081 14082 if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 || 14083 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(MVT::f64)) 14084 return SDValue(); 14085 14086 SDValue Ext = SDValue(N, 0); 14087 if (Ext.getOpcode() == ISD::BITCAST && 14088 Ext.getOperand(0).getValueType() == MVT::f32) 14089 Ext = Ext.getOperand(0); 14090 if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14091 !isa<ConstantSDNode>(Ext.getOperand(1)) || 14092 Ext.getConstantOperandVal(1) % 2 != 0) 14093 return SDValue(); 14094 if (Ext->use_size() == 1 && 14095 (Ext->use_begin()->getOpcode() == ISD::SINT_TO_FP || 14096 Ext->use_begin()->getOpcode() == ISD::UINT_TO_FP)) 14097 return SDValue(); 14098 14099 SDValue Op0 = Ext.getOperand(0); 14100 EVT VecVT = Op0.getValueType(); 14101 unsigned Lane = Ext.getConstantOperandVal(1); 14102 if (VecVT.getVectorNumElements() != 4) 14103 return SDValue(); 14104 14105 // Find another extract, of Lane + 1 14106 auto OtherIt = find_if(Op0->uses(), [&](SDNode *V) { 14107 return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 14108 isa<ConstantSDNode>(V->getOperand(1)) && 14109 V->getConstantOperandVal(1) == Lane + 1; 14110 }); 14111 if (OtherIt == Op0->uses().end()) 14112 return SDValue(); 14113 14114 // For float extracts, we need to be converting to a i32 for both vector 14115 // lanes. 14116 SDValue OtherExt(*OtherIt, 0); 14117 if (OtherExt.getValueType() != MVT::i32) { 14118 if (OtherExt->use_size() != 1 || 14119 OtherExt->use_begin()->getOpcode() != ISD::BITCAST || 14120 OtherExt->use_begin()->getValueType(0) != MVT::i32) 14121 return SDValue(); 14122 OtherExt = SDValue(*OtherExt->use_begin(), 0); 14123 } 14124 14125 // Convert the type to a f64 and extract with a VMOVRRD. 14126 SDValue F64 = DCI.DAG.getNode( 14127 ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 14128 DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v2f64, Op0), 14129 DCI.DAG.getConstant(Ext.getConstantOperandVal(1) / 2, dl, MVT::i32)); 14130 SDValue VMOVRRD = 14131 DCI.DAG.getNode(ARMISD::VMOVRRD, dl, {MVT::i32, MVT::i32}, F64); 14132 14133 DCI.CombineTo(OtherExt.getNode(), SDValue(VMOVRRD.getNode(), 1)); 14134 return VMOVRRD; 14135 } 14136 14137 static SDValue PerformExtractEltCombine(SDNode *N, 14138 TargetLowering::DAGCombinerInfo &DCI, 14139 const ARMSubtarget *ST) { 14140 SDValue Op0 = N->getOperand(0); 14141 EVT VT = N->getValueType(0); 14142 SDLoc dl(N); 14143 14144 // extract (vdup x) -> x 14145 if (Op0->getOpcode() == ARMISD::VDUP) { 14146 SDValue X = Op0->getOperand(0); 14147 if (VT == MVT::f16 && X.getValueType() == MVT::i32) 14148 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X); 14149 if (VT == MVT::i32 && X.getValueType() == MVT::f16) 14150 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X); 14151 14152 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST) 14153 X = X->getOperand(0); 14154 if (X.getValueType() == VT) 14155 return X; 14156 } 14157 14158 // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b 14159 if (Op0.getValueType() == MVT::v4i32 && 14160 isa<ConstantSDNode>(N->getOperand(1)) && 14161 Op0.getOpcode() == ISD::BITCAST && 14162 Op0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 14163 Op0.getOperand(0).getValueType() == MVT::v2f64) { 14164 SDValue BV = Op0.getOperand(0); 14165 unsigned Offset = N->getConstantOperandVal(1); 14166 SDValue MOV = BV.getOperand(Offset < 2 ? 0 : 1); 14167 if (MOV.getOpcode() == ARMISD::VMOVDRR) 14168 return MOV.getOperand(ST->isLittle() ? Offset % 2 : 1 - Offset % 2); 14169 } 14170 14171 // extract x, n; extract x, n+1 -> VMOVRRD x 14172 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI)) 14173 return R; 14174 14175 return SDValue(); 14176 } 14177 14178 static SDValue PerformSignExtendInregCombine(SDNode *N, SelectionDAG &DAG) { 14179 SDValue Op = N->getOperand(0); 14180 EVT VT = N->getValueType(0); 14181 14182 // sext_inreg(VGETLANEu) -> VGETLANEs 14183 if (Op.getOpcode() == ARMISD::VGETLANEu && 14184 cast<VTSDNode>(N->getOperand(1))->getVT() == 14185 Op.getOperand(0).getValueType().getScalarType()) 14186 return DAG.getNode(ARMISD::VGETLANEs, SDLoc(N), VT, Op.getOperand(0), 14187 Op.getOperand(1)); 14188 14189 return SDValue(); 14190 } 14191 14192 // When lowering complex nodes that we recognize, like VQDMULH and MULH, we 14193 // can end up with shuffle(binop(shuffle, shuffle)), that can be simplified to 14194 // binop as the shuffles cancel out. 14195 static SDValue FlattenVectorShuffle(ShuffleVectorSDNode *N, SelectionDAG &DAG) { 14196 EVT VT = N->getValueType(0); 14197 if (!N->getOperand(1).isUndef() || N->getOperand(0).getValueType() != VT) 14198 return SDValue(); 14199 SDValue Op = N->getOperand(0); 14200 14201 // Looking for binary operators that will have been folded from 14202 // truncates/extends. 14203 switch (Op.getOpcode()) { 14204 case ARMISD::VQDMULH: 14205 case ISD::MULHS: 14206 case ISD::MULHU: 14207 break; 14208 default: 14209 return SDValue(); 14210 } 14211 14212 ShuffleVectorSDNode *Op0 = dyn_cast<ShuffleVectorSDNode>(Op.getOperand(0)); 14213 ShuffleVectorSDNode *Op1 = dyn_cast<ShuffleVectorSDNode>(Op.getOperand(1)); 14214 if (!Op0 || !Op1 || !Op0->getOperand(1).isUndef() || 14215 !Op1->getOperand(1).isUndef() || Op0->getMask() != Op1->getMask() || 14216 Op0->getOperand(0).getValueType() != VT) 14217 return SDValue(); 14218 14219 // Check the mask turns into an identity shuffle. 14220 ArrayRef<int> NMask = N->getMask(); 14221 ArrayRef<int> OpMask = Op0->getMask(); 14222 for (int i = 0, e = NMask.size(); i != e; i++) { 14223 if (NMask[i] > 0 && OpMask[NMask[i]] > 0 && OpMask[NMask[i]] != i) 14224 return SDValue(); 14225 } 14226 14227 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 14228 Op0->getOperand(0), Op1->getOperand(0)); 14229 } 14230 14231 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 14232 /// ISD::VECTOR_SHUFFLE. 14233 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 14234 if (SDValue R = FlattenVectorShuffle(cast<ShuffleVectorSDNode>(N), DAG)) 14235 return R; 14236 14237 // The LLVM shufflevector instruction does not require the shuffle mask 14238 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 14239 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 14240 // operands do not match the mask length, they are extended by concatenating 14241 // them with undef vectors. That is probably the right thing for other 14242 // targets, but for NEON it is better to concatenate two double-register 14243 // size vector operands into a single quad-register size vector. Do that 14244 // transformation here: 14245 // shuffle(concat(v1, undef), concat(v2, undef)) -> 14246 // shuffle(concat(v1, v2), undef) 14247 SDValue Op0 = N->getOperand(0); 14248 SDValue Op1 = N->getOperand(1); 14249 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 14250 Op1.getOpcode() != ISD::CONCAT_VECTORS || 14251 Op0.getNumOperands() != 2 || 14252 Op1.getNumOperands() != 2) 14253 return SDValue(); 14254 SDValue Concat0Op1 = Op0.getOperand(1); 14255 SDValue Concat1Op1 = Op1.getOperand(1); 14256 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 14257 return SDValue(); 14258 // Skip the transformation if any of the types are illegal. 14259 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14260 EVT VT = N->getValueType(0); 14261 if (!TLI.isTypeLegal(VT) || 14262 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 14263 !TLI.isTypeLegal(Concat1Op1.getValueType())) 14264 return SDValue(); 14265 14266 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 14267 Op0.getOperand(0), Op1.getOperand(0)); 14268 // Translate the shuffle mask. 14269 SmallVector<int, 16> NewMask; 14270 unsigned NumElts = VT.getVectorNumElements(); 14271 unsigned HalfElts = NumElts/2; 14272 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14273 for (unsigned n = 0; n < NumElts; ++n) { 14274 int MaskElt = SVN->getMaskElt(n); 14275 int NewElt = -1; 14276 if (MaskElt < (int)HalfElts) 14277 NewElt = MaskElt; 14278 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 14279 NewElt = HalfElts + MaskElt - NumElts; 14280 NewMask.push_back(NewElt); 14281 } 14282 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 14283 DAG.getUNDEF(VT), NewMask); 14284 } 14285 14286 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 14287 /// NEON load/store intrinsics, and generic vector load/stores, to merge 14288 /// base address updates. 14289 /// For generic load/stores, the memory type is assumed to be a vector. 14290 /// The caller is assumed to have checked legality. 14291 static SDValue CombineBaseUpdate(SDNode *N, 14292 TargetLowering::DAGCombinerInfo &DCI) { 14293 SelectionDAG &DAG = DCI.DAG; 14294 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 14295 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 14296 const bool isStore = N->getOpcode() == ISD::STORE; 14297 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 14298 SDValue Addr = N->getOperand(AddrOpIdx); 14299 MemSDNode *MemN = cast<MemSDNode>(N); 14300 SDLoc dl(N); 14301 14302 // Search for a use of the address operand that is an increment. 14303 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14304 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 14305 SDNode *User = *UI; 14306 if (User->getOpcode() != ISD::ADD || 14307 UI.getUse().getResNo() != Addr.getResNo()) 14308 continue; 14309 14310 // Check that the add is independent of the load/store. Otherwise, folding 14311 // it would create a cycle. We can avoid searching through Addr as it's a 14312 // predecessor to both. 14313 SmallPtrSet<const SDNode *, 32> Visited; 14314 SmallVector<const SDNode *, 16> Worklist; 14315 Visited.insert(Addr.getNode()); 14316 Worklist.push_back(N); 14317 Worklist.push_back(User); 14318 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14319 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14320 continue; 14321 14322 // Find the new opcode for the updating load/store. 14323 bool isLoadOp = true; 14324 bool isLaneOp = false; 14325 unsigned NewOpc = 0; 14326 unsigned NumVecs = 0; 14327 if (isIntrinsic) { 14328 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14329 switch (IntNo) { 14330 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 14331 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 14332 NumVecs = 1; break; 14333 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 14334 NumVecs = 2; break; 14335 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 14336 NumVecs = 3; break; 14337 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 14338 NumVecs = 4; break; 14339 case Intrinsic::arm_neon_vld1x2: 14340 case Intrinsic::arm_neon_vld1x3: 14341 case Intrinsic::arm_neon_vld1x4: 14342 case Intrinsic::arm_neon_vld2dup: 14343 case Intrinsic::arm_neon_vld3dup: 14344 case Intrinsic::arm_neon_vld4dup: 14345 // TODO: Support updating VLD1x and VLDxDUP nodes. For now, we just skip 14346 // combining base updates for such intrinsics. 14347 continue; 14348 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 14349 NumVecs = 2; isLaneOp = true; break; 14350 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 14351 NumVecs = 3; isLaneOp = true; break; 14352 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 14353 NumVecs = 4; isLaneOp = true; break; 14354 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 14355 NumVecs = 1; isLoadOp = false; break; 14356 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 14357 NumVecs = 2; isLoadOp = false; break; 14358 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 14359 NumVecs = 3; isLoadOp = false; break; 14360 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 14361 NumVecs = 4; isLoadOp = false; break; 14362 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 14363 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 14364 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 14365 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 14366 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 14367 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 14368 } 14369 } else { 14370 isLaneOp = true; 14371 switch (N->getOpcode()) { 14372 default: llvm_unreachable("unexpected opcode for Neon base update"); 14373 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 14374 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 14375 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 14376 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 14377 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 14378 NumVecs = 1; isLaneOp = false; break; 14379 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 14380 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 14381 } 14382 } 14383 14384 // Find the size of memory referenced by the load/store. 14385 EVT VecTy; 14386 if (isLoadOp) { 14387 VecTy = N->getValueType(0); 14388 } else if (isIntrinsic) { 14389 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 14390 } else { 14391 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 14392 VecTy = N->getOperand(1).getValueType(); 14393 } 14394 14395 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14396 if (isLaneOp) 14397 NumBytes /= VecTy.getVectorNumElements(); 14398 14399 // If the increment is a constant, it must match the memory ref size. 14400 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14401 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 14402 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 14403 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 14404 // separate instructions that make it harder to use a non-constant update. 14405 continue; 14406 } 14407 14408 // OK, we found an ADD we can fold into the base update. 14409 // Now, create a _UPD node, taking care of not breaking alignment. 14410 14411 EVT AlignedVecTy = VecTy; 14412 unsigned Alignment = MemN->getAlignment(); 14413 14414 // If this is a less-than-standard-aligned load/store, change the type to 14415 // match the standard alignment. 14416 // The alignment is overlooked when selecting _UPD variants; and it's 14417 // easier to introduce bitcasts here than fix that. 14418 // There are 3 ways to get to this base-update combine: 14419 // - intrinsics: they are assumed to be properly aligned (to the standard 14420 // alignment of the memory type), so we don't need to do anything. 14421 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 14422 // intrinsics, so, likewise, there's nothing to do. 14423 // - generic load/store instructions: the alignment is specified as an 14424 // explicit operand, rather than implicitly as the standard alignment 14425 // of the memory type (like the intrisics). We need to change the 14426 // memory type to match the explicit alignment. That way, we don't 14427 // generate non-standard-aligned ARMISD::VLDx nodes. 14428 if (isa<LSBaseSDNode>(N)) { 14429 if (Alignment == 0) 14430 Alignment = 1; 14431 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 14432 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 14433 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 14434 assert(!isLaneOp && "Unexpected generic load/store lane."); 14435 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 14436 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 14437 } 14438 // Don't set an explicit alignment on regular load/stores that we want 14439 // to transform to VLD/VST 1_UPD nodes. 14440 // This matches the behavior of regular load/stores, which only get an 14441 // explicit alignment if the MMO alignment is larger than the standard 14442 // alignment of the memory type. 14443 // Intrinsics, however, always get an explicit alignment, set to the 14444 // alignment of the MMO. 14445 Alignment = 1; 14446 } 14447 14448 // Create the new updating load/store node. 14449 // First, create an SDVTList for the new updating node's results. 14450 EVT Tys[6]; 14451 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 14452 unsigned n; 14453 for (n = 0; n < NumResultVecs; ++n) 14454 Tys[n] = AlignedVecTy; 14455 Tys[n++] = MVT::i32; 14456 Tys[n] = MVT::Other; 14457 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 14458 14459 // Then, gather the new node's operands. 14460 SmallVector<SDValue, 8> Ops; 14461 Ops.push_back(N->getOperand(0)); // incoming chain 14462 Ops.push_back(N->getOperand(AddrOpIdx)); 14463 Ops.push_back(Inc); 14464 14465 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 14466 // Try to match the intrinsic's signature 14467 Ops.push_back(StN->getValue()); 14468 } else { 14469 // Loads (and of course intrinsics) match the intrinsics' signature, 14470 // so just add all but the alignment operand. 14471 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 14472 Ops.push_back(N->getOperand(i)); 14473 } 14474 14475 // For all node types, the alignment operand is always the last one. 14476 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 14477 14478 // If this is a non-standard-aligned STORE, the penultimate operand is the 14479 // stored value. Bitcast it to the aligned type. 14480 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 14481 SDValue &StVal = Ops[Ops.size()-2]; 14482 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 14483 } 14484 14485 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 14486 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 14487 MemN->getMemOperand()); 14488 14489 // Update the uses. 14490 SmallVector<SDValue, 5> NewResults; 14491 for (unsigned i = 0; i < NumResultVecs; ++i) 14492 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14493 14494 // If this is an non-standard-aligned LOAD, the first result is the loaded 14495 // value. Bitcast it to the expected result type. 14496 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 14497 SDValue &LdVal = NewResults[0]; 14498 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 14499 } 14500 14501 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 14502 DCI.CombineTo(N, NewResults); 14503 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14504 14505 break; 14506 } 14507 return SDValue(); 14508 } 14509 14510 static SDValue PerformVLDCombine(SDNode *N, 14511 TargetLowering::DAGCombinerInfo &DCI) { 14512 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14513 return SDValue(); 14514 14515 return CombineBaseUpdate(N, DCI); 14516 } 14517 14518 static SDValue PerformMVEVLDCombine(SDNode *N, 14519 TargetLowering::DAGCombinerInfo &DCI) { 14520 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14521 return SDValue(); 14522 14523 SelectionDAG &DAG = DCI.DAG; 14524 SDValue Addr = N->getOperand(2); 14525 MemSDNode *MemN = cast<MemSDNode>(N); 14526 SDLoc dl(N); 14527 14528 // For the stores, where there are multiple intrinsics we only actually want 14529 // to post-inc the last of the them. 14530 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14531 if (IntNo == Intrinsic::arm_mve_vst2q && 14532 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1) 14533 return SDValue(); 14534 if (IntNo == Intrinsic::arm_mve_vst4q && 14535 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3) 14536 return SDValue(); 14537 14538 // Search for a use of the address operand that is an increment. 14539 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14540 UE = Addr.getNode()->use_end(); 14541 UI != UE; ++UI) { 14542 SDNode *User = *UI; 14543 if (User->getOpcode() != ISD::ADD || 14544 UI.getUse().getResNo() != Addr.getResNo()) 14545 continue; 14546 14547 // Check that the add is independent of the load/store. Otherwise, folding 14548 // it would create a cycle. We can avoid searching through Addr as it's a 14549 // predecessor to both. 14550 SmallPtrSet<const SDNode *, 32> Visited; 14551 SmallVector<const SDNode *, 16> Worklist; 14552 Visited.insert(Addr.getNode()); 14553 Worklist.push_back(N); 14554 Worklist.push_back(User); 14555 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14556 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14557 continue; 14558 14559 // Find the new opcode for the updating load/store. 14560 bool isLoadOp = true; 14561 unsigned NewOpc = 0; 14562 unsigned NumVecs = 0; 14563 switch (IntNo) { 14564 default: 14565 llvm_unreachable("unexpected intrinsic for MVE VLDn combine"); 14566 case Intrinsic::arm_mve_vld2q: 14567 NewOpc = ARMISD::VLD2_UPD; 14568 NumVecs = 2; 14569 break; 14570 case Intrinsic::arm_mve_vld4q: 14571 NewOpc = ARMISD::VLD4_UPD; 14572 NumVecs = 4; 14573 break; 14574 case Intrinsic::arm_mve_vst2q: 14575 NewOpc = ARMISD::VST2_UPD; 14576 NumVecs = 2; 14577 isLoadOp = false; 14578 break; 14579 case Intrinsic::arm_mve_vst4q: 14580 NewOpc = ARMISD::VST4_UPD; 14581 NumVecs = 4; 14582 isLoadOp = false; 14583 break; 14584 } 14585 14586 // Find the size of memory referenced by the load/store. 14587 EVT VecTy; 14588 if (isLoadOp) { 14589 VecTy = N->getValueType(0); 14590 } else { 14591 VecTy = N->getOperand(3).getValueType(); 14592 } 14593 14594 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14595 14596 // If the increment is a constant, it must match the memory ref size. 14597 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14598 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 14599 if (!CInc || CInc->getZExtValue() != NumBytes) 14600 continue; 14601 14602 // Create the new updating load/store node. 14603 // First, create an SDVTList for the new updating node's results. 14604 EVT Tys[6]; 14605 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 14606 unsigned n; 14607 for (n = 0; n < NumResultVecs; ++n) 14608 Tys[n] = VecTy; 14609 Tys[n++] = MVT::i32; 14610 Tys[n] = MVT::Other; 14611 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 14612 14613 // Then, gather the new node's operands. 14614 SmallVector<SDValue, 8> Ops; 14615 Ops.push_back(N->getOperand(0)); // incoming chain 14616 Ops.push_back(N->getOperand(2)); // ptr 14617 Ops.push_back(Inc); 14618 14619 for (unsigned i = 3; i < N->getNumOperands(); ++i) 14620 Ops.push_back(N->getOperand(i)); 14621 14622 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy, 14623 MemN->getMemOperand()); 14624 14625 // Update the uses. 14626 SmallVector<SDValue, 5> NewResults; 14627 for (unsigned i = 0; i < NumResultVecs; ++i) 14628 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14629 14630 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain 14631 DCI.CombineTo(N, NewResults); 14632 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14633 14634 break; 14635 } 14636 14637 return SDValue(); 14638 } 14639 14640 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 14641 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 14642 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 14643 /// return true. 14644 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 14645 SelectionDAG &DAG = DCI.DAG; 14646 EVT VT = N->getValueType(0); 14647 // vldN-dup instructions only support 64-bit vectors for N > 1. 14648 if (!VT.is64BitVector()) 14649 return false; 14650 14651 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 14652 SDNode *VLD = N->getOperand(0).getNode(); 14653 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 14654 return false; 14655 unsigned NumVecs = 0; 14656 unsigned NewOpc = 0; 14657 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 14658 if (IntNo == Intrinsic::arm_neon_vld2lane) { 14659 NumVecs = 2; 14660 NewOpc = ARMISD::VLD2DUP; 14661 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 14662 NumVecs = 3; 14663 NewOpc = ARMISD::VLD3DUP; 14664 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 14665 NumVecs = 4; 14666 NewOpc = ARMISD::VLD4DUP; 14667 } else { 14668 return false; 14669 } 14670 14671 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 14672 // numbers match the load. 14673 unsigned VLDLaneNo = 14674 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 14675 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14676 UI != UE; ++UI) { 14677 // Ignore uses of the chain result. 14678 if (UI.getUse().getResNo() == NumVecs) 14679 continue; 14680 SDNode *User = *UI; 14681 if (User->getOpcode() != ARMISD::VDUPLANE || 14682 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 14683 return false; 14684 } 14685 14686 // Create the vldN-dup node. 14687 EVT Tys[5]; 14688 unsigned n; 14689 for (n = 0; n < NumVecs; ++n) 14690 Tys[n] = VT; 14691 Tys[n] = MVT::Other; 14692 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 14693 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 14694 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 14695 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 14696 Ops, VLDMemInt->getMemoryVT(), 14697 VLDMemInt->getMemOperand()); 14698 14699 // Update the uses. 14700 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14701 UI != UE; ++UI) { 14702 unsigned ResNo = UI.getUse().getResNo(); 14703 // Ignore uses of the chain result. 14704 if (ResNo == NumVecs) 14705 continue; 14706 SDNode *User = *UI; 14707 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 14708 } 14709 14710 // Now the vldN-lane intrinsic is dead except for its chain result. 14711 // Update uses of the chain. 14712 std::vector<SDValue> VLDDupResults; 14713 for (unsigned n = 0; n < NumVecs; ++n) 14714 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 14715 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 14716 DCI.CombineTo(VLD, VLDDupResults); 14717 14718 return true; 14719 } 14720 14721 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 14722 /// ARMISD::VDUPLANE. 14723 static SDValue PerformVDUPLANECombine(SDNode *N, 14724 TargetLowering::DAGCombinerInfo &DCI, 14725 const ARMSubtarget *Subtarget) { 14726 SDValue Op = N->getOperand(0); 14727 EVT VT = N->getValueType(0); 14728 14729 // On MVE, we just convert the VDUPLANE to a VDUP with an extract. 14730 if (Subtarget->hasMVEIntegerOps()) { 14731 EVT ExtractVT = VT.getVectorElementType(); 14732 // We need to ensure we are creating a legal type. 14733 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT)) 14734 ExtractVT = MVT::i32; 14735 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT, 14736 N->getOperand(0), N->getOperand(1)); 14737 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract); 14738 } 14739 14740 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 14741 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 14742 if (CombineVLDDUP(N, DCI)) 14743 return SDValue(N, 0); 14744 14745 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 14746 // redundant. Ignore bit_converts for now; element sizes are checked below. 14747 while (Op.getOpcode() == ISD::BITCAST) 14748 Op = Op.getOperand(0); 14749 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 14750 return SDValue(); 14751 14752 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 14753 unsigned EltSize = Op.getScalarValueSizeInBits(); 14754 // The canonical VMOV for a zero vector uses a 32-bit element size. 14755 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14756 unsigned EltBits; 14757 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 14758 EltSize = 8; 14759 if (EltSize > VT.getScalarSizeInBits()) 14760 return SDValue(); 14761 14762 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 14763 } 14764 14765 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 14766 static SDValue PerformVDUPCombine(SDNode *N, 14767 TargetLowering::DAGCombinerInfo &DCI, 14768 const ARMSubtarget *Subtarget) { 14769 SelectionDAG &DAG = DCI.DAG; 14770 SDValue Op = N->getOperand(0); 14771 SDLoc dl(N); 14772 14773 if (Subtarget->hasMVEIntegerOps()) { 14774 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will 14775 // need to come from a GPR. 14776 if (Op.getValueType() == MVT::f32) 14777 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14778 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op)); 14779 else if (Op.getValueType() == MVT::f16) 14780 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14781 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op)); 14782 } 14783 14784 if (!Subtarget->hasNEON()) 14785 return SDValue(); 14786 14787 // Match VDUP(LOAD) -> VLD1DUP. 14788 // We match this pattern here rather than waiting for isel because the 14789 // transform is only legal for unindexed loads. 14790 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 14791 if (LD && Op.hasOneUse() && LD->isUnindexed() && 14792 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 14793 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 14794 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 14795 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 14796 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 14797 Ops, LD->getMemoryVT(), 14798 LD->getMemOperand()); 14799 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 14800 return VLDDup; 14801 } 14802 14803 return SDValue(); 14804 } 14805 14806 static SDValue PerformLOADCombine(SDNode *N, 14807 TargetLowering::DAGCombinerInfo &DCI) { 14808 EVT VT = N->getValueType(0); 14809 14810 // If this is a legal vector load, try to combine it into a VLD1_UPD. 14811 if (ISD::isNormalLoad(N) && VT.isVector() && 14812 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14813 return CombineBaseUpdate(N, DCI); 14814 14815 return SDValue(); 14816 } 14817 14818 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 14819 // pack all of the elements in one place. Next, store to memory in fewer 14820 // chunks. 14821 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St, 14822 SelectionDAG &DAG) { 14823 SDValue StVal = St->getValue(); 14824 EVT VT = StVal.getValueType(); 14825 if (!St->isTruncatingStore() || !VT.isVector()) 14826 return SDValue(); 14827 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14828 EVT StVT = St->getMemoryVT(); 14829 unsigned NumElems = VT.getVectorNumElements(); 14830 assert(StVT != VT && "Cannot truncate to the same type"); 14831 unsigned FromEltSz = VT.getScalarSizeInBits(); 14832 unsigned ToEltSz = StVT.getScalarSizeInBits(); 14833 14834 // From, To sizes and ElemCount must be pow of two 14835 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) 14836 return SDValue(); 14837 14838 // We are going to use the original vector elt for storing. 14839 // Accumulated smaller vector elements must be a multiple of the store size. 14840 if (0 != (NumElems * FromEltSz) % ToEltSz) 14841 return SDValue(); 14842 14843 unsigned SizeRatio = FromEltSz / ToEltSz; 14844 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 14845 14846 // Create a type on which we perform the shuffle. 14847 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 14848 NumElems * SizeRatio); 14849 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 14850 14851 SDLoc DL(St); 14852 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 14853 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14854 for (unsigned i = 0; i < NumElems; ++i) 14855 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1 14856 : i * SizeRatio; 14857 14858 // Can't shuffle using an illegal type. 14859 if (!TLI.isTypeLegal(WideVecVT)) 14860 return SDValue(); 14861 14862 SDValue Shuff = DAG.getVectorShuffle( 14863 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec); 14864 // At this point all of the data is stored at the bottom of the 14865 // register. We now need to save it to mem. 14866 14867 // Find the largest store unit 14868 MVT StoreType = MVT::i8; 14869 for (MVT Tp : MVT::integer_valuetypes()) { 14870 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 14871 StoreType = Tp; 14872 } 14873 // Didn't find a legal store type. 14874 if (!TLI.isTypeLegal(StoreType)) 14875 return SDValue(); 14876 14877 // Bitcast the original vector into a vector of store-size units 14878 EVT StoreVecVT = 14879 EVT::getVectorVT(*DAG.getContext(), StoreType, 14880 VT.getSizeInBits() / EVT(StoreType).getSizeInBits()); 14881 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 14882 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 14883 SmallVector<SDValue, 8> Chains; 14884 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 14885 TLI.getPointerTy(DAG.getDataLayout())); 14886 SDValue BasePtr = St->getBasePtr(); 14887 14888 // Perform one or more big stores into memory. 14889 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits(); 14890 for (unsigned I = 0; I < E; I++) { 14891 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType, 14892 ShuffWide, DAG.getIntPtrConstant(I, DL)); 14893 SDValue Ch = 14894 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(), 14895 St->getAlignment(), St->getMemOperand()->getFlags()); 14896 BasePtr = 14897 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment); 14898 Chains.push_back(Ch); 14899 } 14900 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 14901 } 14902 14903 // Try taking a single vector store from an truncate (which would otherwise turn 14904 // into an expensive buildvector) and splitting it into a series of narrowing 14905 // stores. 14906 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, 14907 SelectionDAG &DAG) { 14908 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed()) 14909 return SDValue(); 14910 SDValue Trunc = St->getValue(); 14911 if (Trunc->getOpcode() != ISD::TRUNCATE && Trunc->getOpcode() != ISD::FP_ROUND) 14912 return SDValue(); 14913 EVT FromVT = Trunc->getOperand(0).getValueType(); 14914 EVT ToVT = Trunc.getValueType(); 14915 if (!ToVT.isVector()) 14916 return SDValue(); 14917 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 14918 EVT ToEltVT = ToVT.getVectorElementType(); 14919 EVT FromEltVT = FromVT.getVectorElementType(); 14920 14921 unsigned NumElements = 0; 14922 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8)) 14923 NumElements = 4; 14924 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8) 14925 NumElements = 8; 14926 if (FromEltVT == MVT::f32 && ToEltVT == MVT::f16) 14927 NumElements = 4; 14928 if (NumElements == 0 || 14929 (FromEltVT != MVT::f32 && FromVT.getVectorNumElements() == NumElements) || 14930 FromVT.getVectorNumElements() % NumElements != 0) 14931 return SDValue(); 14932 14933 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so 14934 // use the VMOVN over splitting the store. We are looking for patterns of: 14935 // !rev: 0 N 1 N+1 2 N+2 ... 14936 // rev: N 0 N+1 1 N+2 2 ... 14937 // The shuffle may either be a single source (in which case N = NumElts/2) or 14938 // two inputs extended with concat to the same size (in which case N = 14939 // NumElts). 14940 auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) { 14941 ArrayRef<int> M = SVN->getMask(); 14942 unsigned NumElts = ToVT.getVectorNumElements(); 14943 if (SVN->getOperand(1).isUndef()) 14944 NumElts /= 2; 14945 14946 unsigned Off0 = Rev ? NumElts : 0; 14947 unsigned Off1 = Rev ? 0 : NumElts; 14948 14949 for (unsigned I = 0; I < NumElts; I += 2) { 14950 if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2)) 14951 return false; 14952 if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2)) 14953 return false; 14954 } 14955 14956 return true; 14957 }; 14958 14959 // It may be preferable to keep the store unsplit as the trunc may end up 14960 // being removed. Check that here. 14961 if (Trunc.getOperand(0).getOpcode() == ISD::SMIN) { 14962 if (SDValue U = PerformVQDMULHCombine(Trunc.getOperand(0).getNode(), DAG)) { 14963 DAG.ReplaceAllUsesWith(Trunc.getOperand(0), U); 14964 return SDValue(); 14965 } 14966 } 14967 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0))) 14968 if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true)) 14969 return SDValue(); 14970 14971 LLVMContext &C = *DAG.getContext(); 14972 SDLoc DL(St); 14973 // Details about the old store 14974 SDValue Ch = St->getChain(); 14975 SDValue BasePtr = St->getBasePtr(); 14976 Align Alignment = St->getOriginalAlign(); 14977 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags(); 14978 AAMDNodes AAInfo = St->getAAInfo(); 14979 14980 // We split the store into slices of NumElements. fp16 trunc stores are vcvt 14981 // and then stored as truncating integer stores. 14982 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements); 14983 EVT NewToVT = EVT::getVectorVT( 14984 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements); 14985 14986 SmallVector<SDValue, 4> Stores; 14987 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 14988 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8; 14989 SDValue NewPtr = 14990 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 14991 14992 SDValue Extract = 14993 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0), 14994 DAG.getConstant(i * NumElements, DL, MVT::i32)); 14995 14996 if (ToEltVT == MVT::f16) { 14997 SDValue FPTrunc = 14998 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16), 14999 Extract, DAG.getConstant(0, DL, MVT::i32)); 15000 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc); 15001 } 15002 15003 SDValue Store = DAG.getTruncStore( 15004 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset), 15005 NewToVT, Alignment.value(), MMOFlags, AAInfo); 15006 Stores.push_back(Store); 15007 } 15008 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores); 15009 } 15010 15011 // Given a floating point store from an extracted vector, with an integer 15012 // VGETLANE that already exists, store the existing VGETLANEu directly. This can 15013 // help reduce fp register pressure, doesn't require the fp extract and allows 15014 // use of more integer post-inc stores not available with vstr. 15015 static SDValue PerformExtractFpToIntStores(StoreSDNode *St, SelectionDAG &DAG) { 15016 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed()) 15017 return SDValue(); 15018 SDValue Extract = St->getValue(); 15019 EVT VT = Extract.getValueType(); 15020 // For now only uses f16. This may be useful for f32 too, but that will 15021 // be bitcast(extract), not the VGETLANEu we currently check here. 15022 if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 15023 return SDValue(); 15024 15025 SDNode *GetLane = 15026 DAG.getNodeIfExists(ARMISD::VGETLANEu, DAG.getVTList(MVT::i32), 15027 {Extract.getOperand(0), Extract.getOperand(1)}); 15028 if (!GetLane) 15029 return SDValue(); 15030 15031 LLVMContext &C = *DAG.getContext(); 15032 SDLoc DL(St); 15033 // Create a new integer store to replace the existing floating point version. 15034 SDValue Ch = St->getChain(); 15035 SDValue BasePtr = St->getBasePtr(); 15036 Align Alignment = St->getOriginalAlign(); 15037 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags(); 15038 AAMDNodes AAInfo = St->getAAInfo(); 15039 EVT NewToVT = EVT::getIntegerVT(C, VT.getSizeInBits()); 15040 SDValue Store = DAG.getTruncStore(Ch, DL, SDValue(GetLane, 0), BasePtr, 15041 St->getPointerInfo(), NewToVT, 15042 Alignment.value(), MMOFlags, AAInfo); 15043 15044 return Store; 15045 } 15046 15047 /// PerformSTORECombine - Target-specific dag combine xforms for 15048 /// ISD::STORE. 15049 static SDValue PerformSTORECombine(SDNode *N, 15050 TargetLowering::DAGCombinerInfo &DCI, 15051 const ARMSubtarget *Subtarget) { 15052 StoreSDNode *St = cast<StoreSDNode>(N); 15053 if (St->isVolatile()) 15054 return SDValue(); 15055 SDValue StVal = St->getValue(); 15056 EVT VT = StVal.getValueType(); 15057 15058 if (Subtarget->hasNEON()) 15059 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG)) 15060 return Store; 15061 15062 if (Subtarget->hasMVEIntegerOps()) { 15063 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG)) 15064 return NewToken; 15065 if (SDValue NewChain = PerformExtractFpToIntStores(St, DCI.DAG)) 15066 return NewChain; 15067 } 15068 15069 if (!ISD::isNormalStore(St)) 15070 return SDValue(); 15071 15072 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 15073 // ARM stores of arguments in the same cache line. 15074 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 15075 StVal.getNode()->hasOneUse()) { 15076 SelectionDAG &DAG = DCI.DAG; 15077 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 15078 SDLoc DL(St); 15079 SDValue BasePtr = St->getBasePtr(); 15080 SDValue NewST1 = DAG.getStore( 15081 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 15082 BasePtr, St->getPointerInfo(), St->getOriginalAlign(), 15083 St->getMemOperand()->getFlags()); 15084 15085 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 15086 DAG.getConstant(4, DL, MVT::i32)); 15087 return DAG.getStore(NewST1.getValue(0), DL, 15088 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 15089 OffsetPtr, St->getPointerInfo().getWithOffset(4), 15090 St->getOriginalAlign(), 15091 St->getMemOperand()->getFlags()); 15092 } 15093 15094 if (StVal.getValueType() == MVT::i64 && 15095 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15096 15097 // Bitcast an i64 store extracted from a vector to f64. 15098 // Otherwise, the i64 value will be legalized to a pair of i32 values. 15099 SelectionDAG &DAG = DCI.DAG; 15100 SDLoc dl(StVal); 15101 SDValue IntVec = StVal.getOperand(0); 15102 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 15103 IntVec.getValueType().getVectorNumElements()); 15104 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 15105 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 15106 Vec, StVal.getOperand(1)); 15107 dl = SDLoc(N); 15108 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 15109 // Make the DAGCombiner fold the bitcasts. 15110 DCI.AddToWorklist(Vec.getNode()); 15111 DCI.AddToWorklist(ExtElt.getNode()); 15112 DCI.AddToWorklist(V.getNode()); 15113 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 15114 St->getPointerInfo(), St->getAlignment(), 15115 St->getMemOperand()->getFlags(), St->getAAInfo()); 15116 } 15117 15118 // If this is a legal vector store, try to combine it into a VST1_UPD. 15119 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() && 15120 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 15121 return CombineBaseUpdate(N, DCI); 15122 15123 return SDValue(); 15124 } 15125 15126 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 15127 /// can replace combinations of VMUL and VCVT (floating-point to integer) 15128 /// when the VMUL has a constant operand that is a power of 2. 15129 /// 15130 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 15131 /// vmul.f32 d16, d17, d16 15132 /// vcvt.s32.f32 d16, d16 15133 /// becomes: 15134 /// vcvt.s32.f32 d16, d16, #3 15135 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 15136 const ARMSubtarget *Subtarget) { 15137 if (!Subtarget->hasNEON()) 15138 return SDValue(); 15139 15140 SDValue Op = N->getOperand(0); 15141 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 15142 Op.getOpcode() != ISD::FMUL) 15143 return SDValue(); 15144 15145 SDValue ConstVec = Op->getOperand(1); 15146 if (!isa<BuildVectorSDNode>(ConstVec)) 15147 return SDValue(); 15148 15149 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 15150 uint32_t FloatBits = FloatTy.getSizeInBits(); 15151 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 15152 uint32_t IntBits = IntTy.getSizeInBits(); 15153 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 15154 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 15155 // These instructions only exist converting from f32 to i32. We can handle 15156 // smaller integers by generating an extra truncate, but larger ones would 15157 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 15158 // these intructions only support v2i32/v4i32 types. 15159 return SDValue(); 15160 } 15161 15162 BitVector UndefElements; 15163 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 15164 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 15165 if (C == -1 || C == 0 || C > 32) 15166 return SDValue(); 15167 15168 SDLoc dl(N); 15169 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 15170 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 15171 Intrinsic::arm_neon_vcvtfp2fxu; 15172 SDValue FixConv = DAG.getNode( 15173 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 15174 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 15175 DAG.getConstant(C, dl, MVT::i32)); 15176 15177 if (IntBits < FloatBits) 15178 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 15179 15180 return FixConv; 15181 } 15182 15183 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 15184 /// can replace combinations of VCVT (integer to floating-point) and VDIV 15185 /// when the VDIV has a constant operand that is a power of 2. 15186 /// 15187 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 15188 /// vcvt.f32.s32 d16, d16 15189 /// vdiv.f32 d16, d17, d16 15190 /// becomes: 15191 /// vcvt.f32.s32 d16, d16, #3 15192 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 15193 const ARMSubtarget *Subtarget) { 15194 if (!Subtarget->hasNEON()) 15195 return SDValue(); 15196 15197 SDValue Op = N->getOperand(0); 15198 unsigned OpOpcode = Op.getNode()->getOpcode(); 15199 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 15200 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 15201 return SDValue(); 15202 15203 SDValue ConstVec = N->getOperand(1); 15204 if (!isa<BuildVectorSDNode>(ConstVec)) 15205 return SDValue(); 15206 15207 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 15208 uint32_t FloatBits = FloatTy.getSizeInBits(); 15209 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 15210 uint32_t IntBits = IntTy.getSizeInBits(); 15211 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 15212 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 15213 // These instructions only exist converting from i32 to f32. We can handle 15214 // smaller integers by generating an extra extend, but larger ones would 15215 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 15216 // these intructions only support v2i32/v4i32 types. 15217 return SDValue(); 15218 } 15219 15220 BitVector UndefElements; 15221 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 15222 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 15223 if (C == -1 || C == 0 || C > 32) 15224 return SDValue(); 15225 15226 SDLoc dl(N); 15227 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 15228 SDValue ConvInput = Op.getOperand(0); 15229 if (IntBits < FloatBits) 15230 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 15231 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 15232 ConvInput); 15233 15234 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 15235 Intrinsic::arm_neon_vcvtfxu2fp; 15236 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 15237 Op.getValueType(), 15238 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 15239 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 15240 } 15241 15242 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG, 15243 const ARMSubtarget *ST) { 15244 if (!ST->hasMVEIntegerOps()) 15245 return SDValue(); 15246 15247 assert(N->getOpcode() == ISD::VECREDUCE_ADD); 15248 EVT ResVT = N->getValueType(0); 15249 SDValue N0 = N->getOperand(0); 15250 SDLoc dl(N); 15251 15252 // We are looking for something that will have illegal types if left alone, 15253 // but that we can convert to a single instruction undef MVE. For example 15254 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A 15255 // or 15256 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B 15257 15258 // Cases: 15259 // VADDV u/s 8/16/32 15260 // VMLAV u/s 8/16/32 15261 // VADDLV u/s 32 15262 // VMLALV u/s 16/32 15263 15264 // If the input vector is smaller than legal (v4i8/v4i16 for example) we can 15265 // extend it and use v4i32 instead. 15266 auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) { 15267 EVT AVT = A.getValueType(); 15268 if (!AVT.is128BitVector()) 15269 A = DAG.getNode(ExtendCode, dl, 15270 AVT.changeVectorElementType(MVT::getIntegerVT( 15271 128 / AVT.getVectorMinNumElements())), 15272 A); 15273 return A; 15274 }; 15275 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) { 15276 if (ResVT != RetTy || N0->getOpcode() != ExtendCode) 15277 return SDValue(); 15278 SDValue A = N0->getOperand(0); 15279 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 15280 return ExtendIfNeeded(A, ExtendCode); 15281 return SDValue(); 15282 }; 15283 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode, 15284 ArrayRef<MVT> ExtTypes, SDValue &Mask) { 15285 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 15286 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 15287 return SDValue(); 15288 Mask = N0->getOperand(0); 15289 SDValue Ext = N0->getOperand(1); 15290 if (Ext->getOpcode() != ExtendCode) 15291 return SDValue(); 15292 SDValue A = Ext->getOperand(0); 15293 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 15294 return ExtendIfNeeded(A, ExtendCode); 15295 return SDValue(); 15296 }; 15297 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 15298 SDValue &A, SDValue &B) { 15299 // For a vmla we are trying to match a larger pattern: 15300 // ExtA = sext/zext A 15301 // ExtB = sext/zext B 15302 // Mul = mul ExtA, ExtB 15303 // vecreduce.add Mul 15304 // There might also be en extra extend between the mul and the addreduce, so 15305 // long as the bitwidth is high enough to make them equivalent (for example 15306 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64). 15307 if (ResVT != RetTy) 15308 return false; 15309 SDValue Mul = N0; 15310 if (Mul->getOpcode() == ExtendCode && 15311 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >= 15312 ResVT.getScalarSizeInBits()) 15313 Mul = Mul->getOperand(0); 15314 if (Mul->getOpcode() != ISD::MUL) 15315 return false; 15316 SDValue ExtA = Mul->getOperand(0); 15317 SDValue ExtB = Mul->getOperand(1); 15318 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 15319 return false; 15320 A = ExtA->getOperand(0); 15321 B = ExtB->getOperand(0); 15322 if (A.getValueType() == B.getValueType() && 15323 llvm::any_of(ExtTypes, 15324 [&A](MVT Ty) { return A.getValueType() == Ty; })) { 15325 A = ExtendIfNeeded(A, ExtendCode); 15326 B = ExtendIfNeeded(B, ExtendCode); 15327 return true; 15328 } 15329 return false; 15330 }; 15331 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 15332 SDValue &A, SDValue &B, SDValue &Mask) { 15333 // Same as the pattern above with a select for the zero predicated lanes 15334 // ExtA = sext/zext A 15335 // ExtB = sext/zext B 15336 // Mul = mul ExtA, ExtB 15337 // N0 = select Mask, Mul, 0 15338 // vecreduce.add N0 15339 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 15340 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 15341 return false; 15342 Mask = N0->getOperand(0); 15343 SDValue Mul = N0->getOperand(1); 15344 if (Mul->getOpcode() == ExtendCode && 15345 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >= 15346 ResVT.getScalarSizeInBits()) 15347 Mul = Mul->getOperand(0); 15348 if (Mul->getOpcode() != ISD::MUL) 15349 return false; 15350 SDValue ExtA = Mul->getOperand(0); 15351 SDValue ExtB = Mul->getOperand(1); 15352 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 15353 return false; 15354 A = ExtA->getOperand(0); 15355 B = ExtB->getOperand(0); 15356 if (A.getValueType() == B.getValueType() && 15357 llvm::any_of(ExtTypes, 15358 [&A](MVT Ty) { return A.getValueType() == Ty; })) { 15359 A = ExtendIfNeeded(A, ExtendCode); 15360 B = ExtendIfNeeded(B, ExtendCode); 15361 return true; 15362 } 15363 return false; 15364 }; 15365 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) { 15366 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops); 15367 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node, 15368 SDValue(Node.getNode(), 1)); 15369 }; 15370 15371 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8})) 15372 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A); 15373 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8})) 15374 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A); 15375 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, 15376 {MVT::v4i8, MVT::v4i16, MVT::v4i32})) 15377 return Create64bitNode(ARMISD::VADDLVs, {A}); 15378 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, 15379 {MVT::v4i8, MVT::v4i16, MVT::v4i32})) 15380 return Create64bitNode(ARMISD::VADDLVu, {A}); 15381 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8})) 15382 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15383 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A)); 15384 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8})) 15385 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15386 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A)); 15387 15388 SDValue Mask; 15389 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 15390 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask); 15391 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 15392 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask); 15393 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, 15394 {MVT::v4i8, MVT::v4i16, MVT::v4i32}, Mask)) 15395 return Create64bitNode(ARMISD::VADDLVps, {A, Mask}); 15396 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, 15397 {MVT::v4i8, MVT::v4i16, MVT::v4i32}, Mask)) 15398 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask}); 15399 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask)) 15400 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15401 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask)); 15402 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask)) 15403 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15404 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask)); 15405 15406 SDValue A, B; 15407 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 15408 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B); 15409 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 15410 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B); 15411 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, 15412 {MVT::v8i8, MVT::v8i16, MVT::v4i8, MVT::v4i16, MVT::v4i32}, A, B)) 15413 return Create64bitNode(ARMISD::VMLALVs, {A, B}); 15414 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, 15415 {MVT::v8i8, MVT::v8i16, MVT::v4i8, MVT::v4i16, MVT::v4i32}, A, B)) 15416 return Create64bitNode(ARMISD::VMLALVu, {A, B}); 15417 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B)) 15418 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15419 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B)); 15420 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B)) 15421 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15422 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B)); 15423 15424 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 15425 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask); 15426 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 15427 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask); 15428 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, 15429 {MVT::v8i8, MVT::v8i16, MVT::v4i8, MVT::v4i16, MVT::v4i32}, A, 15430 B, Mask)) 15431 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask}); 15432 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, 15433 {MVT::v8i8, MVT::v8i16, MVT::v4i8, MVT::v4i16, MVT::v4i32}, A, 15434 B, Mask)) 15435 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask}); 15436 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask)) 15437 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15438 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask)); 15439 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask)) 15440 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 15441 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask)); 15442 15443 // Some complications. We can get a case where the two inputs of the mul are 15444 // the same, then the output sext will have been helpfully converted to a 15445 // zext. Turn it back. 15446 SDValue Op = N0; 15447 if (Op->getOpcode() == ISD::VSELECT) 15448 Op = Op->getOperand(1); 15449 if (Op->getOpcode() == ISD::ZERO_EXTEND && 15450 Op->getOperand(0)->getOpcode() == ISD::MUL) { 15451 SDValue Mul = Op->getOperand(0); 15452 if (Mul->getOperand(0) == Mul->getOperand(1) && 15453 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) { 15454 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul); 15455 if (Op != N0) 15456 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0), 15457 N0->getOperand(0), Ext, N0->getOperand(2)); 15458 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext); 15459 } 15460 } 15461 15462 return SDValue(); 15463 } 15464 15465 static SDValue PerformVMOVNCombine(SDNode *N, 15466 TargetLowering::DAGCombinerInfo &DCI) { 15467 SDValue Op0 = N->getOperand(0); 15468 SDValue Op1 = N->getOperand(1); 15469 unsigned IsTop = N->getConstantOperandVal(2); 15470 15471 // VMOVNT a undef -> a 15472 // VMOVNB a undef -> a 15473 // VMOVNB undef a -> a 15474 if (Op1->isUndef()) 15475 return Op0; 15476 if (Op0->isUndef() && !IsTop) 15477 return Op1; 15478 15479 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b) 15480 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b) 15481 if ((Op1->getOpcode() == ARMISD::VQMOVNs || 15482 Op1->getOpcode() == ARMISD::VQMOVNu) && 15483 Op1->getConstantOperandVal(2) == 0) 15484 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0), 15485 Op0, Op1->getOperand(1), N->getOperand(2)); 15486 15487 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from 15488 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting 15489 // into the top or bottom lanes. 15490 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 15491 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1)); 15492 APInt Op0DemandedElts = 15493 IsTop ? Op1DemandedElts 15494 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1)); 15495 15496 APInt KnownUndef, KnownZero; 15497 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 15498 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 15499 KnownZero, DCI)) 15500 return SDValue(N, 0); 15501 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef, 15502 KnownZero, DCI)) 15503 return SDValue(N, 0); 15504 15505 return SDValue(); 15506 } 15507 15508 static SDValue PerformVQMOVNCombine(SDNode *N, 15509 TargetLowering::DAGCombinerInfo &DCI) { 15510 SDValue Op0 = N->getOperand(0); 15511 unsigned IsTop = N->getConstantOperandVal(2); 15512 15513 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 15514 APInt Op0DemandedElts = 15515 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1) 15516 : APInt::getHighBitsSet(2, 1)); 15517 15518 APInt KnownUndef, KnownZero; 15519 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 15520 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 15521 KnownZero, DCI)) 15522 return SDValue(N, 0); 15523 return SDValue(); 15524 } 15525 15526 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) { 15527 SDLoc DL(N); 15528 SDValue Op0 = N->getOperand(0); 15529 SDValue Op1 = N->getOperand(1); 15530 15531 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from 15532 // uses of the intrinsics. 15533 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 15534 int ShiftAmt = C->getSExtValue(); 15535 if (ShiftAmt == 0) { 15536 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL); 15537 DAG.ReplaceAllUsesWith(N, Merge.getNode()); 15538 return SDValue(); 15539 } 15540 15541 if (ShiftAmt >= -32 && ShiftAmt < 0) { 15542 unsigned NewOpcode = 15543 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL; 15544 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1, 15545 DAG.getConstant(-ShiftAmt, DL, MVT::i32)); 15546 DAG.ReplaceAllUsesWith(N, NewShift.getNode()); 15547 return NewShift; 15548 } 15549 } 15550 15551 return SDValue(); 15552 } 15553 15554 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 15555 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N, 15556 DAGCombinerInfo &DCI) const { 15557 SelectionDAG &DAG = DCI.DAG; 15558 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15559 switch (IntNo) { 15560 default: 15561 // Don't do anything for most intrinsics. 15562 break; 15563 15564 // Vector shifts: check for immediate versions and lower them. 15565 // Note: This is done during DAG combining instead of DAG legalizing because 15566 // the build_vectors for 64-bit vector element shift counts are generally 15567 // not legal, and it is hard to see their values after they get legalized to 15568 // loads from a constant pool. 15569 case Intrinsic::arm_neon_vshifts: 15570 case Intrinsic::arm_neon_vshiftu: 15571 case Intrinsic::arm_neon_vrshifts: 15572 case Intrinsic::arm_neon_vrshiftu: 15573 case Intrinsic::arm_neon_vrshiftn: 15574 case Intrinsic::arm_neon_vqshifts: 15575 case Intrinsic::arm_neon_vqshiftu: 15576 case Intrinsic::arm_neon_vqshiftsu: 15577 case Intrinsic::arm_neon_vqshiftns: 15578 case Intrinsic::arm_neon_vqshiftnu: 15579 case Intrinsic::arm_neon_vqshiftnsu: 15580 case Intrinsic::arm_neon_vqrshiftns: 15581 case Intrinsic::arm_neon_vqrshiftnu: 15582 case Intrinsic::arm_neon_vqrshiftnsu: { 15583 EVT VT = N->getOperand(1).getValueType(); 15584 int64_t Cnt; 15585 unsigned VShiftOpc = 0; 15586 15587 switch (IntNo) { 15588 case Intrinsic::arm_neon_vshifts: 15589 case Intrinsic::arm_neon_vshiftu: 15590 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 15591 VShiftOpc = ARMISD::VSHLIMM; 15592 break; 15593 } 15594 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 15595 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 15596 : ARMISD::VSHRuIMM); 15597 break; 15598 } 15599 return SDValue(); 15600 15601 case Intrinsic::arm_neon_vrshifts: 15602 case Intrinsic::arm_neon_vrshiftu: 15603 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 15604 break; 15605 return SDValue(); 15606 15607 case Intrinsic::arm_neon_vqshifts: 15608 case Intrinsic::arm_neon_vqshiftu: 15609 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15610 break; 15611 return SDValue(); 15612 15613 case Intrinsic::arm_neon_vqshiftsu: 15614 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15615 break; 15616 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 15617 15618 case Intrinsic::arm_neon_vrshiftn: 15619 case Intrinsic::arm_neon_vqshiftns: 15620 case Intrinsic::arm_neon_vqshiftnu: 15621 case Intrinsic::arm_neon_vqshiftnsu: 15622 case Intrinsic::arm_neon_vqrshiftns: 15623 case Intrinsic::arm_neon_vqrshiftnu: 15624 case Intrinsic::arm_neon_vqrshiftnsu: 15625 // Narrowing shifts require an immediate right shift. 15626 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 15627 break; 15628 llvm_unreachable("invalid shift count for narrowing vector shift " 15629 "intrinsic"); 15630 15631 default: 15632 llvm_unreachable("unhandled vector shift"); 15633 } 15634 15635 switch (IntNo) { 15636 case Intrinsic::arm_neon_vshifts: 15637 case Intrinsic::arm_neon_vshiftu: 15638 // Opcode already set above. 15639 break; 15640 case Intrinsic::arm_neon_vrshifts: 15641 VShiftOpc = ARMISD::VRSHRsIMM; 15642 break; 15643 case Intrinsic::arm_neon_vrshiftu: 15644 VShiftOpc = ARMISD::VRSHRuIMM; 15645 break; 15646 case Intrinsic::arm_neon_vrshiftn: 15647 VShiftOpc = ARMISD::VRSHRNIMM; 15648 break; 15649 case Intrinsic::arm_neon_vqshifts: 15650 VShiftOpc = ARMISD::VQSHLsIMM; 15651 break; 15652 case Intrinsic::arm_neon_vqshiftu: 15653 VShiftOpc = ARMISD::VQSHLuIMM; 15654 break; 15655 case Intrinsic::arm_neon_vqshiftsu: 15656 VShiftOpc = ARMISD::VQSHLsuIMM; 15657 break; 15658 case Intrinsic::arm_neon_vqshiftns: 15659 VShiftOpc = ARMISD::VQSHRNsIMM; 15660 break; 15661 case Intrinsic::arm_neon_vqshiftnu: 15662 VShiftOpc = ARMISD::VQSHRNuIMM; 15663 break; 15664 case Intrinsic::arm_neon_vqshiftnsu: 15665 VShiftOpc = ARMISD::VQSHRNsuIMM; 15666 break; 15667 case Intrinsic::arm_neon_vqrshiftns: 15668 VShiftOpc = ARMISD::VQRSHRNsIMM; 15669 break; 15670 case Intrinsic::arm_neon_vqrshiftnu: 15671 VShiftOpc = ARMISD::VQRSHRNuIMM; 15672 break; 15673 case Intrinsic::arm_neon_vqrshiftnsu: 15674 VShiftOpc = ARMISD::VQRSHRNsuIMM; 15675 break; 15676 } 15677 15678 SDLoc dl(N); 15679 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15680 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 15681 } 15682 15683 case Intrinsic::arm_neon_vshiftins: { 15684 EVT VT = N->getOperand(1).getValueType(); 15685 int64_t Cnt; 15686 unsigned VShiftOpc = 0; 15687 15688 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 15689 VShiftOpc = ARMISD::VSLIIMM; 15690 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 15691 VShiftOpc = ARMISD::VSRIIMM; 15692 else { 15693 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 15694 } 15695 15696 SDLoc dl(N); 15697 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15698 N->getOperand(1), N->getOperand(2), 15699 DAG.getConstant(Cnt, dl, MVT::i32)); 15700 } 15701 15702 case Intrinsic::arm_neon_vqrshifts: 15703 case Intrinsic::arm_neon_vqrshiftu: 15704 // No immediate versions of these to check for. 15705 break; 15706 15707 case Intrinsic::arm_mve_vqdmlah: 15708 case Intrinsic::arm_mve_vqdmlash: 15709 case Intrinsic::arm_mve_vqrdmlah: 15710 case Intrinsic::arm_mve_vqrdmlash: 15711 case Intrinsic::arm_mve_vmla_n_predicated: 15712 case Intrinsic::arm_mve_vmlas_n_predicated: 15713 case Intrinsic::arm_mve_vqdmlah_predicated: 15714 case Intrinsic::arm_mve_vqdmlash_predicated: 15715 case Intrinsic::arm_mve_vqrdmlah_predicated: 15716 case Intrinsic::arm_mve_vqrdmlash_predicated: { 15717 // These intrinsics all take an i32 scalar operand which is narrowed to the 15718 // size of a single lane of the vector type they return. So we don't need 15719 // any bits of that operand above that point, which allows us to eliminate 15720 // uxth/sxth. 15721 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits(); 15722 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15723 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI)) 15724 return SDValue(); 15725 break; 15726 } 15727 15728 case Intrinsic::arm_mve_minv: 15729 case Intrinsic::arm_mve_maxv: 15730 case Intrinsic::arm_mve_minav: 15731 case Intrinsic::arm_mve_maxav: 15732 case Intrinsic::arm_mve_minv_predicated: 15733 case Intrinsic::arm_mve_maxv_predicated: 15734 case Intrinsic::arm_mve_minav_predicated: 15735 case Intrinsic::arm_mve_maxav_predicated: { 15736 // These intrinsics all take an i32 scalar operand which is narrowed to the 15737 // size of a single lane of the vector type they take as the other input. 15738 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits(); 15739 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15740 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 15741 return SDValue(); 15742 break; 15743 } 15744 15745 case Intrinsic::arm_mve_addv: { 15746 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node, 15747 // which allow PerformADDVecReduce to turn it into VADDLV when possible. 15748 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15749 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs; 15750 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1)); 15751 } 15752 15753 case Intrinsic::arm_mve_addlv: 15754 case Intrinsic::arm_mve_addlv_predicated: { 15755 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR 15756 // which recombines the two outputs into an i64 15757 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15758 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ? 15759 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) : 15760 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps); 15761 15762 SmallVector<SDValue, 4> Ops; 15763 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++) 15764 if (i != 2) // skip the unsigned flag 15765 Ops.push_back(N->getOperand(i)); 15766 15767 SDLoc dl(N); 15768 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops); 15769 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0), 15770 val.getValue(1)); 15771 } 15772 } 15773 15774 return SDValue(); 15775 } 15776 15777 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 15778 /// lowers them. As with the vector shift intrinsics, this is done during DAG 15779 /// combining instead of DAG legalizing because the build_vectors for 64-bit 15780 /// vector element shift counts are generally not legal, and it is hard to see 15781 /// their values after they get legalized to loads from a constant pool. 15782 static SDValue PerformShiftCombine(SDNode *N, 15783 TargetLowering::DAGCombinerInfo &DCI, 15784 const ARMSubtarget *ST) { 15785 SelectionDAG &DAG = DCI.DAG; 15786 EVT VT = N->getValueType(0); 15787 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 15788 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 15789 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 15790 SDValue N1 = N->getOperand(1); 15791 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 15792 SDValue N0 = N->getOperand(0); 15793 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 15794 DAG.MaskedValueIsZero(N0.getOperand(0), 15795 APInt::getHighBitsSet(32, 16))) 15796 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 15797 } 15798 } 15799 15800 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 15801 N->getOperand(0)->getOpcode() == ISD::AND && 15802 N->getOperand(0)->hasOneUse()) { 15803 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 15804 return SDValue(); 15805 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 15806 // usually show up because instcombine prefers to canonicalize it to 15807 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 15808 // out of GEP lowering in some cases. 15809 SDValue N0 = N->getOperand(0); 15810 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15811 if (!ShiftAmtNode) 15812 return SDValue(); 15813 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 15814 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15815 if (!AndMaskNode) 15816 return SDValue(); 15817 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 15818 // Don't transform uxtb/uxth. 15819 if (AndMask == 255 || AndMask == 65535) 15820 return SDValue(); 15821 if (isMask_32(AndMask)) { 15822 uint32_t MaskedBits = countLeadingZeros(AndMask); 15823 if (MaskedBits > ShiftAmt) { 15824 SDLoc DL(N); 15825 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 15826 DAG.getConstant(MaskedBits, DL, MVT::i32)); 15827 return DAG.getNode( 15828 ISD::SRL, DL, MVT::i32, SHL, 15829 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 15830 } 15831 } 15832 } 15833 15834 // Nothing to be done for scalar shifts. 15835 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15836 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 15837 return SDValue(); 15838 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 15839 return SDValue(); 15840 15841 int64_t Cnt; 15842 15843 switch (N->getOpcode()) { 15844 default: llvm_unreachable("unexpected shift opcode"); 15845 15846 case ISD::SHL: 15847 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 15848 SDLoc dl(N); 15849 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 15850 DAG.getConstant(Cnt, dl, MVT::i32)); 15851 } 15852 break; 15853 15854 case ISD::SRA: 15855 case ISD::SRL: 15856 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 15857 unsigned VShiftOpc = 15858 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 15859 SDLoc dl(N); 15860 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 15861 DAG.getConstant(Cnt, dl, MVT::i32)); 15862 } 15863 } 15864 return SDValue(); 15865 } 15866 15867 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be 15868 // split into multiple extending loads, which are simpler to deal with than an 15869 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL 15870 // to convert the type to an f32. 15871 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) { 15872 SDValue N0 = N->getOperand(0); 15873 if (N0.getOpcode() != ISD::LOAD) 15874 return SDValue(); 15875 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode()); 15876 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() || 15877 LD->getExtensionType() != ISD::NON_EXTLOAD) 15878 return SDValue(); 15879 EVT FromVT = LD->getValueType(0); 15880 EVT ToVT = N->getValueType(0); 15881 if (!ToVT.isVector()) 15882 return SDValue(); 15883 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 15884 EVT ToEltVT = ToVT.getVectorElementType(); 15885 EVT FromEltVT = FromVT.getVectorElementType(); 15886 15887 unsigned NumElements = 0; 15888 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8)) 15889 NumElements = 4; 15890 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8) 15891 NumElements = 8; 15892 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16) 15893 NumElements = 4; 15894 if (NumElements == 0 || 15895 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) || 15896 FromVT.getVectorNumElements() % NumElements != 0 || 15897 !isPowerOf2_32(NumElements)) 15898 return SDValue(); 15899 15900 LLVMContext &C = *DAG.getContext(); 15901 SDLoc DL(LD); 15902 // Details about the old load 15903 SDValue Ch = LD->getChain(); 15904 SDValue BasePtr = LD->getBasePtr(); 15905 Align Alignment = LD->getOriginalAlign(); 15906 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 15907 AAMDNodes AAInfo = LD->getAAInfo(); 15908 15909 ISD::LoadExtType NewExtType = 15910 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 15911 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType()); 15912 EVT NewFromVT = EVT::getVectorVT( 15913 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements); 15914 EVT NewToVT = EVT::getVectorVT( 15915 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements); 15916 15917 SmallVector<SDValue, 4> Loads; 15918 SmallVector<SDValue, 4> Chains; 15919 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 15920 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8; 15921 SDValue NewPtr = 15922 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 15923 15924 SDValue NewLoad = 15925 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset, 15926 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT, 15927 Alignment, MMOFlags, AAInfo); 15928 Loads.push_back(NewLoad); 15929 Chains.push_back(SDValue(NewLoad.getNode(), 1)); 15930 } 15931 15932 // Float truncs need to extended with VCVTB's into their floating point types. 15933 if (FromEltVT == MVT::f16) { 15934 SmallVector<SDValue, 4> Extends; 15935 15936 for (unsigned i = 0; i < Loads.size(); i++) { 15937 SDValue LoadBC = 15938 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]); 15939 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC, 15940 DAG.getConstant(0, DL, MVT::i32)); 15941 Extends.push_back(FPExt); 15942 } 15943 15944 Loads = Extends; 15945 } 15946 15947 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 15948 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain); 15949 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads); 15950 } 15951 15952 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 15953 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 15954 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 15955 const ARMSubtarget *ST) { 15956 SDValue N0 = N->getOperand(0); 15957 15958 // Check for sign- and zero-extensions of vector extract operations of 8- and 15959 // 16-bit vector elements. NEON and MVE support these directly. They are 15960 // handled during DAG combining because type legalization will promote them 15961 // to 32-bit types and it is messy to recognize the operations after that. 15962 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) && 15963 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15964 SDValue Vec = N0.getOperand(0); 15965 SDValue Lane = N0.getOperand(1); 15966 EVT VT = N->getValueType(0); 15967 EVT EltVT = N0.getValueType(); 15968 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15969 15970 if (VT == MVT::i32 && 15971 (EltVT == MVT::i8 || EltVT == MVT::i16) && 15972 TLI.isTypeLegal(Vec.getValueType()) && 15973 isa<ConstantSDNode>(Lane)) { 15974 15975 unsigned Opc = 0; 15976 switch (N->getOpcode()) { 15977 default: llvm_unreachable("unexpected opcode"); 15978 case ISD::SIGN_EXTEND: 15979 Opc = ARMISD::VGETLANEs; 15980 break; 15981 case ISD::ZERO_EXTEND: 15982 case ISD::ANY_EXTEND: 15983 Opc = ARMISD::VGETLANEu; 15984 break; 15985 } 15986 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 15987 } 15988 } 15989 15990 if (ST->hasMVEIntegerOps()) 15991 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 15992 return NewLoad; 15993 15994 return SDValue(); 15995 } 15996 15997 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG, 15998 const ARMSubtarget *ST) { 15999 if (ST->hasMVEFloatOps()) 16000 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 16001 return NewLoad; 16002 16003 return SDValue(); 16004 } 16005 16006 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating 16007 /// saturates. 16008 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG, 16009 const ARMSubtarget *ST) { 16010 EVT VT = N->getValueType(0); 16011 SDValue N0 = N->getOperand(0); 16012 if (!ST->hasMVEIntegerOps()) 16013 return SDValue(); 16014 16015 if (SDValue V = PerformVQDMULHCombine(N, DAG)) 16016 return V; 16017 16018 if (VT != MVT::v4i32 && VT != MVT::v8i16) 16019 return SDValue(); 16020 16021 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) { 16022 // Check one is a smin and the other is a smax 16023 if (Min->getOpcode() != ISD::SMIN) 16024 std::swap(Min, Max); 16025 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX) 16026 return false; 16027 16028 APInt SaturateC; 16029 if (VT == MVT::v4i32) 16030 SaturateC = APInt(32, (1 << 15) - 1, true); 16031 else //if (VT == MVT::v8i16) 16032 SaturateC = APInt(16, (1 << 7) - 1, true); 16033 16034 APInt MinC, MaxC; 16035 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 16036 MinC != SaturateC) 16037 return false; 16038 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) || 16039 MaxC != ~SaturateC) 16040 return false; 16041 return true; 16042 }; 16043 16044 if (IsSignedSaturate(N, N0.getNode())) { 16045 SDLoc DL(N); 16046 MVT ExtVT, HalfVT; 16047 if (VT == MVT::v4i32) { 16048 HalfVT = MVT::v8i16; 16049 ExtVT = MVT::v4i16; 16050 } else { // if (VT == MVT::v8i16) 16051 HalfVT = MVT::v16i8; 16052 ExtVT = MVT::v8i8; 16053 } 16054 16055 // Create a VQMOVNB with undef top lanes, then signed extended into the top 16056 // half. That extend will hopefully be removed if only the bottom bits are 16057 // demanded (though a truncating store, for example). 16058 SDValue VQMOVN = 16059 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT), 16060 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32)); 16061 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 16062 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast, 16063 DAG.getValueType(ExtVT)); 16064 } 16065 16066 auto IsUnsignedSaturate = [&](SDNode *Min) { 16067 // For unsigned, we just need to check for <= 0xffff 16068 if (Min->getOpcode() != ISD::UMIN) 16069 return false; 16070 16071 APInt SaturateC; 16072 if (VT == MVT::v4i32) 16073 SaturateC = APInt(32, (1 << 16) - 1, true); 16074 else //if (VT == MVT::v8i16) 16075 SaturateC = APInt(16, (1 << 8) - 1, true); 16076 16077 APInt MinC; 16078 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 16079 MinC != SaturateC) 16080 return false; 16081 return true; 16082 }; 16083 16084 if (IsUnsignedSaturate(N)) { 16085 SDLoc DL(N); 16086 MVT HalfVT; 16087 unsigned ExtConst; 16088 if (VT == MVT::v4i32) { 16089 HalfVT = MVT::v8i16; 16090 ExtConst = 0x0000FFFF; 16091 } else { //if (VT == MVT::v8i16) 16092 HalfVT = MVT::v16i8; 16093 ExtConst = 0x00FF; 16094 } 16095 16096 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with 16097 // an AND. That extend will hopefully be removed if only the bottom bits are 16098 // demanded (though a truncating store, for example). 16099 SDValue VQMOVN = 16100 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0, 16101 DAG.getConstant(0, DL, MVT::i32)); 16102 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 16103 return DAG.getNode(ISD::AND, DL, VT, Bitcast, 16104 DAG.getConstant(ExtConst, DL, VT)); 16105 } 16106 16107 return SDValue(); 16108 } 16109 16110 static const APInt *isPowerOf2Constant(SDValue V) { 16111 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 16112 if (!C) 16113 return nullptr; 16114 const APInt *CV = &C->getAPIntValue(); 16115 return CV->isPowerOf2() ? CV : nullptr; 16116 } 16117 16118 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 16119 // If we have a CMOV, OR and AND combination such as: 16120 // if (x & CN) 16121 // y |= CM; 16122 // 16123 // And: 16124 // * CN is a single bit; 16125 // * All bits covered by CM are known zero in y 16126 // 16127 // Then we can convert this into a sequence of BFI instructions. This will 16128 // always be a win if CM is a single bit, will always be no worse than the 16129 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 16130 // three bits (due to the extra IT instruction). 16131 16132 SDValue Op0 = CMOV->getOperand(0); 16133 SDValue Op1 = CMOV->getOperand(1); 16134 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 16135 auto CC = CCNode->getAPIntValue().getLimitedValue(); 16136 SDValue CmpZ = CMOV->getOperand(4); 16137 16138 // The compare must be against zero. 16139 if (!isNullConstant(CmpZ->getOperand(1))) 16140 return SDValue(); 16141 16142 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 16143 SDValue And = CmpZ->getOperand(0); 16144 if (And->getOpcode() != ISD::AND) 16145 return SDValue(); 16146 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 16147 if (!AndC) 16148 return SDValue(); 16149 SDValue X = And->getOperand(0); 16150 16151 if (CC == ARMCC::EQ) { 16152 // We're performing an "equal to zero" compare. Swap the operands so we 16153 // canonicalize on a "not equal to zero" compare. 16154 std::swap(Op0, Op1); 16155 } else { 16156 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 16157 } 16158 16159 if (Op1->getOpcode() != ISD::OR) 16160 return SDValue(); 16161 16162 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 16163 if (!OrC) 16164 return SDValue(); 16165 SDValue Y = Op1->getOperand(0); 16166 16167 if (Op0 != Y) 16168 return SDValue(); 16169 16170 // Now, is it profitable to continue? 16171 APInt OrCI = OrC->getAPIntValue(); 16172 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 16173 if (OrCI.countPopulation() > Heuristic) 16174 return SDValue(); 16175 16176 // Lastly, can we determine that the bits defined by OrCI 16177 // are zero in Y? 16178 KnownBits Known = DAG.computeKnownBits(Y); 16179 if ((OrCI & Known.Zero) != OrCI) 16180 return SDValue(); 16181 16182 // OK, we can do the combine. 16183 SDValue V = Y; 16184 SDLoc dl(X); 16185 EVT VT = X.getValueType(); 16186 unsigned BitInX = AndC->logBase2(); 16187 16188 if (BitInX != 0) { 16189 // We must shift X first. 16190 X = DAG.getNode(ISD::SRL, dl, VT, X, 16191 DAG.getConstant(BitInX, dl, VT)); 16192 } 16193 16194 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 16195 BitInY < NumActiveBits; ++BitInY) { 16196 if (OrCI[BitInY] == 0) 16197 continue; 16198 APInt Mask(VT.getSizeInBits(), 0); 16199 Mask.setBit(BitInY); 16200 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 16201 // Confusingly, the operand is an *inverted* mask. 16202 DAG.getConstant(~Mask, dl, VT)); 16203 } 16204 16205 return V; 16206 } 16207 16208 // Given N, the value controlling the conditional branch, search for the loop 16209 // intrinsic, returning it, along with how the value is used. We need to handle 16210 // patterns such as the following: 16211 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 16212 // (brcond (setcc (loop.decrement), 0, eq), exit) 16213 // (brcond (setcc (loop.decrement), 0, ne), header) 16214 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 16215 bool &Negate) { 16216 switch (N->getOpcode()) { 16217 default: 16218 break; 16219 case ISD::XOR: { 16220 if (!isa<ConstantSDNode>(N.getOperand(1))) 16221 return SDValue(); 16222 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 16223 return SDValue(); 16224 Negate = !Negate; 16225 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 16226 } 16227 case ISD::SETCC: { 16228 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 16229 if (!Const) 16230 return SDValue(); 16231 if (Const->isNullValue()) 16232 Imm = 0; 16233 else if (Const->isOne()) 16234 Imm = 1; 16235 else 16236 return SDValue(); 16237 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 16238 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 16239 } 16240 case ISD::INTRINSIC_W_CHAIN: { 16241 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 16242 if (IntOp != Intrinsic::test_start_loop_iterations && 16243 IntOp != Intrinsic::loop_decrement_reg) 16244 return SDValue(); 16245 return N; 16246 } 16247 } 16248 return SDValue(); 16249 } 16250 16251 static SDValue PerformHWLoopCombine(SDNode *N, 16252 TargetLowering::DAGCombinerInfo &DCI, 16253 const ARMSubtarget *ST) { 16254 16255 // The hwloop intrinsics that we're interested are used for control-flow, 16256 // either for entering or exiting the loop: 16257 // - test.start.loop.iterations will test whether its operand is zero. If it 16258 // is zero, the proceeding branch should not enter the loop. 16259 // - loop.decrement.reg also tests whether its operand is zero. If it is 16260 // zero, the proceeding branch should not branch back to the beginning of 16261 // the loop. 16262 // So here, we need to check that how the brcond is using the result of each 16263 // of the intrinsics to ensure that we're branching to the right place at the 16264 // right time. 16265 16266 ISD::CondCode CC; 16267 SDValue Cond; 16268 int Imm = 1; 16269 bool Negate = false; 16270 SDValue Chain = N->getOperand(0); 16271 SDValue Dest; 16272 16273 if (N->getOpcode() == ISD::BRCOND) { 16274 CC = ISD::SETEQ; 16275 Cond = N->getOperand(1); 16276 Dest = N->getOperand(2); 16277 } else { 16278 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 16279 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 16280 Cond = N->getOperand(2); 16281 Dest = N->getOperand(4); 16282 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 16283 if (!Const->isOne() && !Const->isNullValue()) 16284 return SDValue(); 16285 Imm = Const->getZExtValue(); 16286 } else 16287 return SDValue(); 16288 } 16289 16290 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 16291 if (!Int) 16292 return SDValue(); 16293 16294 if (Negate) 16295 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32); 16296 16297 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 16298 return (CC == ISD::SETEQ && Imm == 0) || 16299 (CC == ISD::SETNE && Imm == 1) || 16300 (CC == ISD::SETLT && Imm == 1) || 16301 (CC == ISD::SETULT && Imm == 1); 16302 }; 16303 16304 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 16305 return (CC == ISD::SETEQ && Imm == 1) || 16306 (CC == ISD::SETNE && Imm == 0) || 16307 (CC == ISD::SETGT && Imm == 0) || 16308 (CC == ISD::SETUGT && Imm == 0) || 16309 (CC == ISD::SETGE && Imm == 1) || 16310 (CC == ISD::SETUGE && Imm == 1); 16311 }; 16312 16313 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 16314 "unsupported condition"); 16315 16316 SDLoc dl(Int); 16317 SelectionDAG &DAG = DCI.DAG; 16318 SDValue Elements = Int.getOperand(2); 16319 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 16320 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 16321 && "expected single br user"); 16322 SDNode *Br = *N->use_begin(); 16323 SDValue OtherTarget = Br->getOperand(1); 16324 16325 // Update the unconditional branch to branch to the given Dest. 16326 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 16327 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 16328 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 16329 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 16330 }; 16331 16332 if (IntOp == Intrinsic::test_start_loop_iterations) { 16333 SDValue Res; 16334 SDValue Setup = DAG.getNode(ARMISD::WLSSETUP, dl, MVT::i32, Elements); 16335 // We expect this 'instruction' to branch when the counter is zero. 16336 if (IsTrueIfZero(CC, Imm)) { 16337 SDValue Ops[] = {Chain, Setup, Dest}; 16338 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 16339 } else { 16340 // The logic is the reverse of what we need for WLS, so find the other 16341 // basic block target: the target of the proceeding br. 16342 UpdateUncondBr(Br, Dest, DAG); 16343 16344 SDValue Ops[] = {Chain, Setup, OtherTarget}; 16345 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 16346 } 16347 // Update LR count to the new value 16348 DAG.ReplaceAllUsesOfValueWith(Int.getValue(0), Setup); 16349 // Update chain 16350 DAG.ReplaceAllUsesOfValueWith(Int.getValue(2), Int.getOperand(0)); 16351 return Res; 16352 } else { 16353 SDValue Size = DAG.getTargetConstant( 16354 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 16355 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 16356 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 16357 DAG.getVTList(MVT::i32, MVT::Other), Args); 16358 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 16359 16360 // We expect this instruction to branch when the count is not zero. 16361 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 16362 16363 // Update the unconditional branch to target the loop preheader if we've 16364 // found the condition has been reversed. 16365 if (Target == OtherTarget) 16366 UpdateUncondBr(Br, Dest, DAG); 16367 16368 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 16369 SDValue(LoopDec.getNode(), 1), Chain); 16370 16371 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 16372 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 16373 } 16374 return SDValue(); 16375 } 16376 16377 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 16378 SDValue 16379 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 16380 SDValue Cmp = N->getOperand(4); 16381 if (Cmp.getOpcode() != ARMISD::CMPZ) 16382 // Only looking at NE cases. 16383 return SDValue(); 16384 16385 EVT VT = N->getValueType(0); 16386 SDLoc dl(N); 16387 SDValue LHS = Cmp.getOperand(0); 16388 SDValue RHS = Cmp.getOperand(1); 16389 SDValue Chain = N->getOperand(0); 16390 SDValue BB = N->getOperand(1); 16391 SDValue ARMcc = N->getOperand(2); 16392 ARMCC::CondCodes CC = 16393 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 16394 16395 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 16396 // -> (brcond Chain BB CC CPSR Cmp) 16397 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 16398 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 16399 LHS->getOperand(0)->hasOneUse()) { 16400 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 16401 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 16402 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 16403 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 16404 if ((LHS00C && LHS00C->getZExtValue() == 0) && 16405 (LHS01C && LHS01C->getZExtValue() == 1) && 16406 (LHS1C && LHS1C->getZExtValue() == 1) && 16407 (RHSC && RHSC->getZExtValue() == 0)) { 16408 return DAG.getNode( 16409 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 16410 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 16411 } 16412 } 16413 16414 return SDValue(); 16415 } 16416 16417 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 16418 SDValue 16419 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 16420 SDValue Cmp = N->getOperand(4); 16421 if (Cmp.getOpcode() != ARMISD::CMPZ) 16422 // Only looking at EQ and NE cases. 16423 return SDValue(); 16424 16425 EVT VT = N->getValueType(0); 16426 SDLoc dl(N); 16427 SDValue LHS = Cmp.getOperand(0); 16428 SDValue RHS = Cmp.getOperand(1); 16429 SDValue FalseVal = N->getOperand(0); 16430 SDValue TrueVal = N->getOperand(1); 16431 SDValue ARMcc = N->getOperand(2); 16432 ARMCC::CondCodes CC = 16433 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 16434 16435 // BFI is only available on V6T2+. 16436 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 16437 SDValue R = PerformCMOVToBFICombine(N, DAG); 16438 if (R) 16439 return R; 16440 } 16441 16442 // Simplify 16443 // mov r1, r0 16444 // cmp r1, x 16445 // mov r0, y 16446 // moveq r0, x 16447 // to 16448 // cmp r0, x 16449 // movne r0, y 16450 // 16451 // mov r1, r0 16452 // cmp r1, x 16453 // mov r0, x 16454 // movne r0, y 16455 // to 16456 // cmp r0, x 16457 // movne r0, y 16458 /// FIXME: Turn this into a target neutral optimization? 16459 SDValue Res; 16460 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 16461 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 16462 N->getOperand(3), Cmp); 16463 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 16464 SDValue ARMcc; 16465 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 16466 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 16467 N->getOperand(3), NewCmp); 16468 } 16469 16470 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 16471 // -> (cmov F T CC CPSR Cmp) 16472 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 16473 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 16474 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 16475 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 16476 if ((LHS0C && LHS0C->getZExtValue() == 0) && 16477 (LHS1C && LHS1C->getZExtValue() == 1) && 16478 (RHSC && RHSC->getZExtValue() == 0)) { 16479 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 16480 LHS->getOperand(2), LHS->getOperand(3), 16481 LHS->getOperand(4)); 16482 } 16483 } 16484 16485 if (!VT.isInteger()) 16486 return SDValue(); 16487 16488 // Materialize a boolean comparison for integers so we can avoid branching. 16489 if (isNullConstant(FalseVal)) { 16490 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 16491 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 16492 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 16493 // right 5 bits will make that 32 be 1, otherwise it will be 0. 16494 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 16495 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 16496 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 16497 DAG.getConstant(5, dl, MVT::i32)); 16498 } else { 16499 // CMOV 0, 1, ==, (CMPZ x, y) -> 16500 // (ADDCARRY (SUB x, y), t:0, t:1) 16501 // where t = (SUBCARRY 0, (SUB x, y), 0) 16502 // 16503 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 16504 // x != y. In other words, a carry C == 1 when x == y, C == 0 16505 // otherwise. 16506 // The final ADDCARRY computes 16507 // x - y + (0 - (x - y)) + C == C 16508 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 16509 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 16510 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 16511 // ISD::SUBCARRY returns a borrow but we want the carry here 16512 // actually. 16513 SDValue Carry = 16514 DAG.getNode(ISD::SUB, dl, MVT::i32, 16515 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 16516 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 16517 } 16518 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 16519 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 16520 // This seems pointless but will allow us to combine it further below. 16521 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 16522 SDValue Sub = 16523 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 16524 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 16525 Sub.getValue(1), SDValue()); 16526 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 16527 N->getOperand(3), CPSRGlue.getValue(1)); 16528 FalseVal = Sub; 16529 } 16530 } else if (isNullConstant(TrueVal)) { 16531 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 16532 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 16533 // This seems pointless but will allow us to combine it further below 16534 // Note that we change == for != as this is the dual for the case above. 16535 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 16536 SDValue Sub = 16537 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 16538 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 16539 Sub.getValue(1), SDValue()); 16540 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 16541 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 16542 N->getOperand(3), CPSRGlue.getValue(1)); 16543 FalseVal = Sub; 16544 } 16545 } 16546 16547 // On Thumb1, the DAG above may be further combined if z is a power of 2 16548 // (z == 2 ^ K). 16549 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 16550 // t1 = (USUBO (SUB x, y), 1) 16551 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 16552 // Result = if K != 0 then (SHL t2:0, K) else t2:0 16553 // 16554 // This also handles the special case of comparing against zero; it's 16555 // essentially, the same pattern, except there's no SUBS: 16556 // CMOV x, z, !=, (CMPZ x, 0) -> 16557 // t1 = (USUBO x, 1) 16558 // t2 = (SUBCARRY x, t1:0, t1:1) 16559 // Result = if K != 0 then (SHL t2:0, K) else t2:0 16560 const APInt *TrueConst; 16561 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 16562 ((FalseVal.getOpcode() == ARMISD::SUBS && 16563 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 16564 (FalseVal == LHS && isNullConstant(RHS))) && 16565 (TrueConst = isPowerOf2Constant(TrueVal))) { 16566 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 16567 unsigned ShiftAmount = TrueConst->logBase2(); 16568 if (ShiftAmount) 16569 TrueVal = DAG.getConstant(1, dl, VT); 16570 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 16571 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 16572 16573 if (ShiftAmount) 16574 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 16575 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 16576 } 16577 16578 if (Res.getNode()) { 16579 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 16580 // Capture demanded bits information that would be otherwise lost. 16581 if (Known.Zero == 0xfffffffe) 16582 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16583 DAG.getValueType(MVT::i1)); 16584 else if (Known.Zero == 0xffffff00) 16585 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16586 DAG.getValueType(MVT::i8)); 16587 else if (Known.Zero == 0xffff0000) 16588 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16589 DAG.getValueType(MVT::i16)); 16590 } 16591 16592 return Res; 16593 } 16594 16595 static SDValue PerformBITCASTCombine(SDNode *N, 16596 TargetLowering::DAGCombinerInfo &DCI, 16597 const ARMSubtarget *ST) { 16598 SelectionDAG &DAG = DCI.DAG; 16599 SDValue Src = N->getOperand(0); 16600 EVT DstVT = N->getValueType(0); 16601 16602 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE. 16603 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) { 16604 EVT SrcVT = Src.getValueType(); 16605 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits()) 16606 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0)); 16607 } 16608 16609 // We may have a bitcast of something that has already had this bitcast 16610 // combine performed on it, so skip past any VECTOR_REG_CASTs. 16611 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST) 16612 Src = Src.getOperand(0); 16613 16614 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that 16615 // would be generated is at least the width of the element type. 16616 EVT SrcVT = Src.getValueType(); 16617 if ((Src.getOpcode() == ARMISD::VMOVIMM || 16618 Src.getOpcode() == ARMISD::VMVNIMM || 16619 Src.getOpcode() == ARMISD::VMOVFPIMM) && 16620 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() && 16621 DAG.getDataLayout().isBigEndian()) 16622 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src); 16623 16624 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD x 16625 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI)) 16626 return R; 16627 16628 return SDValue(); 16629 } 16630 16631 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 16632 DAGCombinerInfo &DCI) const { 16633 switch (N->getOpcode()) { 16634 default: break; 16635 case ISD::SELECT_CC: 16636 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget); 16637 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget); 16638 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 16639 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 16640 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 16641 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 16642 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget); 16643 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 16644 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 16645 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 16646 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 16647 case ISD::BRCOND: 16648 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 16649 case ARMISD::ADDC: 16650 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 16651 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 16652 case ARMISD::BFI: return PerformBFICombine(N, DCI); 16653 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 16654 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 16655 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI); 16656 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI); 16657 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget); 16658 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 16659 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 16660 case ISD::EXTRACT_VECTOR_ELT: 16661 return PerformExtractEltCombine(N, DCI, Subtarget); 16662 case ISD::SIGN_EXTEND_INREG: return PerformSignExtendInregCombine(N, DCI.DAG); 16663 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 16664 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget); 16665 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 16666 case ISD::FP_TO_SINT: 16667 case ISD::FP_TO_UINT: 16668 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 16669 case ISD::FDIV: 16670 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 16671 case ISD::INTRINSIC_WO_CHAIN: 16672 return PerformIntrinsicCombine(N, DCI); 16673 case ISD::SHL: 16674 case ISD::SRA: 16675 case ISD::SRL: 16676 return PerformShiftCombine(N, DCI, Subtarget); 16677 case ISD::SIGN_EXTEND: 16678 case ISD::ZERO_EXTEND: 16679 case ISD::ANY_EXTEND: 16680 return PerformExtendCombine(N, DCI.DAG, Subtarget); 16681 case ISD::FP_EXTEND: 16682 return PerformFPExtendCombine(N, DCI.DAG, Subtarget); 16683 case ISD::SMIN: 16684 case ISD::UMIN: 16685 case ISD::SMAX: 16686 case ISD::UMAX: 16687 return PerformMinMaxCombine(N, DCI.DAG, Subtarget); 16688 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 16689 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 16690 case ISD::LOAD: return PerformLOADCombine(N, DCI); 16691 case ARMISD::VLD1DUP: 16692 case ARMISD::VLD2DUP: 16693 case ARMISD::VLD3DUP: 16694 case ARMISD::VLD4DUP: 16695 return PerformVLDCombine(N, DCI); 16696 case ARMISD::BUILD_VECTOR: 16697 return PerformARMBUILD_VECTORCombine(N, DCI); 16698 case ISD::BITCAST: 16699 return PerformBITCASTCombine(N, DCI, Subtarget); 16700 case ARMISD::PREDICATE_CAST: 16701 return PerformPREDICATE_CASTCombine(N, DCI); 16702 case ARMISD::VECTOR_REG_CAST: 16703 return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget); 16704 case ARMISD::VCMP: 16705 return PerformVCMPCombine(N, DCI, Subtarget); 16706 case ISD::VECREDUCE_ADD: 16707 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget); 16708 case ARMISD::VMOVN: 16709 return PerformVMOVNCombine(N, DCI); 16710 case ARMISD::VQMOVNs: 16711 case ARMISD::VQMOVNu: 16712 return PerformVQMOVNCombine(N, DCI); 16713 case ARMISD::ASRL: 16714 case ARMISD::LSRL: 16715 case ARMISD::LSLL: 16716 return PerformLongShiftCombine(N, DCI.DAG); 16717 case ARMISD::SMULWB: { 16718 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16719 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16720 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16721 return SDValue(); 16722 break; 16723 } 16724 case ARMISD::SMULWT: { 16725 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16726 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16727 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16728 return SDValue(); 16729 break; 16730 } 16731 case ARMISD::SMLALBB: 16732 case ARMISD::QADD16b: 16733 case ARMISD::QSUB16b: { 16734 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16735 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16736 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16737 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16738 return SDValue(); 16739 break; 16740 } 16741 case ARMISD::SMLALBT: { 16742 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 16743 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16744 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 16745 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16746 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 16747 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 16748 return SDValue(); 16749 break; 16750 } 16751 case ARMISD::SMLALTB: { 16752 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 16753 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16754 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 16755 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16756 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 16757 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 16758 return SDValue(); 16759 break; 16760 } 16761 case ARMISD::SMLALTT: { 16762 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16763 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16764 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16765 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16766 return SDValue(); 16767 break; 16768 } 16769 case ARMISD::QADD8b: 16770 case ARMISD::QSUB8b: { 16771 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16772 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8); 16773 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16774 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16775 return SDValue(); 16776 break; 16777 } 16778 case ISD::INTRINSIC_VOID: 16779 case ISD::INTRINSIC_W_CHAIN: 16780 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 16781 case Intrinsic::arm_neon_vld1: 16782 case Intrinsic::arm_neon_vld1x2: 16783 case Intrinsic::arm_neon_vld1x3: 16784 case Intrinsic::arm_neon_vld1x4: 16785 case Intrinsic::arm_neon_vld2: 16786 case Intrinsic::arm_neon_vld3: 16787 case Intrinsic::arm_neon_vld4: 16788 case Intrinsic::arm_neon_vld2lane: 16789 case Intrinsic::arm_neon_vld3lane: 16790 case Intrinsic::arm_neon_vld4lane: 16791 case Intrinsic::arm_neon_vld2dup: 16792 case Intrinsic::arm_neon_vld3dup: 16793 case Intrinsic::arm_neon_vld4dup: 16794 case Intrinsic::arm_neon_vst1: 16795 case Intrinsic::arm_neon_vst1x2: 16796 case Intrinsic::arm_neon_vst1x3: 16797 case Intrinsic::arm_neon_vst1x4: 16798 case Intrinsic::arm_neon_vst2: 16799 case Intrinsic::arm_neon_vst3: 16800 case Intrinsic::arm_neon_vst4: 16801 case Intrinsic::arm_neon_vst2lane: 16802 case Intrinsic::arm_neon_vst3lane: 16803 case Intrinsic::arm_neon_vst4lane: 16804 return PerformVLDCombine(N, DCI); 16805 case Intrinsic::arm_mve_vld2q: 16806 case Intrinsic::arm_mve_vld4q: 16807 case Intrinsic::arm_mve_vst2q: 16808 case Intrinsic::arm_mve_vst4q: 16809 return PerformMVEVLDCombine(N, DCI); 16810 default: break; 16811 } 16812 break; 16813 } 16814 return SDValue(); 16815 } 16816 16817 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 16818 EVT VT) const { 16819 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 16820 } 16821 16822 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 16823 Align Alignment, 16824 MachineMemOperand::Flags, 16825 bool *Fast) const { 16826 // Depends what it gets converted into if the type is weird. 16827 if (!VT.isSimple()) 16828 return false; 16829 16830 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus 16831 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 16832 auto Ty = VT.getSimpleVT().SimpleTy; 16833 16834 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 16835 // Unaligned access can use (for example) LRDB, LRDH, LDR 16836 if (AllowsUnaligned) { 16837 if (Fast) 16838 *Fast = Subtarget->hasV7Ops(); 16839 return true; 16840 } 16841 } 16842 16843 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 16844 // For any little-endian targets with neon, we can support unaligned ld/st 16845 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 16846 // A big-endian target may also explicitly support unaligned accesses 16847 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 16848 if (Fast) 16849 *Fast = true; 16850 return true; 16851 } 16852 } 16853 16854 if (!Subtarget->hasMVEIntegerOps()) 16855 return false; 16856 16857 // These are for predicates 16858 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 16859 if (Fast) 16860 *Fast = true; 16861 return true; 16862 } 16863 16864 // These are for truncated stores/narrowing loads. They are fine so long as 16865 // the alignment is at least the size of the item being loaded 16866 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 16867 Alignment >= VT.getScalarSizeInBits() / 8) { 16868 if (Fast) 16869 *Fast = true; 16870 return true; 16871 } 16872 16873 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 16874 // VSTRW.U32 all store the vector register in exactly the same format, and 16875 // differ only in the range of their immediate offset field and the required 16876 // alignment. So there is always a store that can be used, regardless of 16877 // actual type. 16878 // 16879 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 16880 // VREV64.8) pair and get the same effect. This will likely be better than 16881 // aligning the vector through the stack. 16882 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 16883 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 16884 Ty == MVT::v2f64) { 16885 if (Fast) 16886 *Fast = true; 16887 return true; 16888 } 16889 16890 return false; 16891 } 16892 16893 16894 EVT ARMTargetLowering::getOptimalMemOpType( 16895 const MemOp &Op, const AttributeList &FuncAttributes) const { 16896 // See if we can use NEON instructions for this... 16897 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() && 16898 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 16899 bool Fast; 16900 if (Op.size() >= 16 && 16901 (Op.isAligned(Align(16)) || 16902 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, Align(1), 16903 MachineMemOperand::MONone, &Fast) && 16904 Fast))) { 16905 return MVT::v2f64; 16906 } else if (Op.size() >= 8 && 16907 (Op.isAligned(Align(8)) || 16908 (allowsMisalignedMemoryAccesses( 16909 MVT::f64, 0, Align(1), MachineMemOperand::MONone, &Fast) && 16910 Fast))) { 16911 return MVT::f64; 16912 } 16913 } 16914 16915 // Let the target-independent logic figure it out. 16916 return MVT::Other; 16917 } 16918 16919 // 64-bit integers are split into their high and low parts and held in two 16920 // different registers, so the trunc is free since the low register can just 16921 // be used. 16922 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 16923 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 16924 return false; 16925 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 16926 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 16927 return (SrcBits == 64 && DestBits == 32); 16928 } 16929 16930 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 16931 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 16932 !DstVT.isInteger()) 16933 return false; 16934 unsigned SrcBits = SrcVT.getSizeInBits(); 16935 unsigned DestBits = DstVT.getSizeInBits(); 16936 return (SrcBits == 64 && DestBits == 32); 16937 } 16938 16939 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16940 if (Val.getOpcode() != ISD::LOAD) 16941 return false; 16942 16943 EVT VT1 = Val.getValueType(); 16944 if (!VT1.isSimple() || !VT1.isInteger() || 16945 !VT2.isSimple() || !VT2.isInteger()) 16946 return false; 16947 16948 switch (VT1.getSimpleVT().SimpleTy) { 16949 default: break; 16950 case MVT::i1: 16951 case MVT::i8: 16952 case MVT::i16: 16953 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 16954 return true; 16955 } 16956 16957 return false; 16958 } 16959 16960 bool ARMTargetLowering::isFNegFree(EVT VT) const { 16961 if (!VT.isSimple()) 16962 return false; 16963 16964 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 16965 // negate values directly (fneg is free). So, we don't want to let the DAG 16966 // combiner rewrite fneg into xors and some other instructions. For f16 and 16967 // FullFP16 argument passing, some bitcast nodes may be introduced, 16968 // triggering this DAG combine rewrite, so we are avoiding that with this. 16969 switch (VT.getSimpleVT().SimpleTy) { 16970 default: break; 16971 case MVT::f16: 16972 return Subtarget->hasFullFP16(); 16973 } 16974 16975 return false; 16976 } 16977 16978 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 16979 /// of the vector elements. 16980 static bool areExtractExts(Value *Ext1, Value *Ext2) { 16981 auto areExtDoubled = [](Instruction *Ext) { 16982 return Ext->getType()->getScalarSizeInBits() == 16983 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 16984 }; 16985 16986 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 16987 !match(Ext2, m_ZExtOrSExt(m_Value())) || 16988 !areExtDoubled(cast<Instruction>(Ext1)) || 16989 !areExtDoubled(cast<Instruction>(Ext2))) 16990 return false; 16991 16992 return true; 16993 } 16994 16995 /// Check if sinking \p I's operands to I's basic block is profitable, because 16996 /// the operands can be folded into a target instruction, e.g. 16997 /// sext/zext can be folded into vsubl. 16998 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 16999 SmallVectorImpl<Use *> &Ops) const { 17000 if (!I->getType()->isVectorTy()) 17001 return false; 17002 17003 if (Subtarget->hasNEON()) { 17004 switch (I->getOpcode()) { 17005 case Instruction::Sub: 17006 case Instruction::Add: { 17007 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 17008 return false; 17009 Ops.push_back(&I->getOperandUse(0)); 17010 Ops.push_back(&I->getOperandUse(1)); 17011 return true; 17012 } 17013 default: 17014 return false; 17015 } 17016 } 17017 17018 if (!Subtarget->hasMVEIntegerOps()) 17019 return false; 17020 17021 auto IsFMSMul = [&](Instruction *I) { 17022 if (!I->hasOneUse()) 17023 return false; 17024 auto *Sub = cast<Instruction>(*I->users().begin()); 17025 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I; 17026 }; 17027 auto IsFMS = [&](Instruction *I) { 17028 if (match(I->getOperand(0), m_FNeg(m_Value())) || 17029 match(I->getOperand(1), m_FNeg(m_Value()))) 17030 return true; 17031 return false; 17032 }; 17033 17034 auto IsSinker = [&](Instruction *I, int Operand) { 17035 switch (I->getOpcode()) { 17036 case Instruction::Add: 17037 case Instruction::Mul: 17038 case Instruction::FAdd: 17039 case Instruction::ICmp: 17040 case Instruction::FCmp: 17041 return true; 17042 case Instruction::FMul: 17043 return !IsFMSMul(I); 17044 case Instruction::Sub: 17045 case Instruction::FSub: 17046 case Instruction::Shl: 17047 case Instruction::LShr: 17048 case Instruction::AShr: 17049 return Operand == 1; 17050 case Instruction::Call: 17051 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 17052 switch (II->getIntrinsicID()) { 17053 case Intrinsic::fma: 17054 return !IsFMS(I); 17055 case Intrinsic::arm_mve_add_predicated: 17056 case Intrinsic::arm_mve_mul_predicated: 17057 case Intrinsic::arm_mve_qadd_predicated: 17058 case Intrinsic::arm_mve_hadd_predicated: 17059 case Intrinsic::arm_mve_vqdmull_predicated: 17060 case Intrinsic::arm_mve_qdmulh_predicated: 17061 case Intrinsic::arm_mve_qrdmulh_predicated: 17062 case Intrinsic::arm_mve_fma_predicated: 17063 return true; 17064 case Intrinsic::arm_mve_sub_predicated: 17065 case Intrinsic::arm_mve_qsub_predicated: 17066 case Intrinsic::arm_mve_hsub_predicated: 17067 return Operand == 1; 17068 default: 17069 return false; 17070 } 17071 } 17072 return false; 17073 default: 17074 return false; 17075 } 17076 }; 17077 17078 for (auto OpIdx : enumerate(I->operands())) { 17079 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 17080 // Make sure we are not already sinking this operand 17081 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 17082 continue; 17083 17084 Instruction *Shuffle = Op; 17085 if (Shuffle->getOpcode() == Instruction::BitCast) 17086 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0)); 17087 // We are looking for a splat that can be sunk. 17088 if (!Shuffle || 17089 !match(Shuffle, m_Shuffle( 17090 m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 17091 m_Undef(), m_ZeroMask()))) 17092 continue; 17093 if (!IsSinker(I, OpIdx.index())) 17094 continue; 17095 17096 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 17097 // and vector registers 17098 for (Use &U : Op->uses()) { 17099 Instruction *Insn = cast<Instruction>(U.getUser()); 17100 if (!IsSinker(Insn, U.getOperandNo())) 17101 return false; 17102 } 17103 17104 Ops.push_back(&Shuffle->getOperandUse(0)); 17105 if (Shuffle != Op) 17106 Ops.push_back(&Op->getOperandUse(0)); 17107 Ops.push_back(&OpIdx.value()); 17108 } 17109 return true; 17110 } 17111 17112 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const { 17113 if (!Subtarget->hasMVEIntegerOps()) 17114 return nullptr; 17115 Type *SVIType = SVI->getType(); 17116 Type *ScalarType = SVIType->getScalarType(); 17117 17118 if (ScalarType->isFloatTy()) 17119 return Type::getInt32Ty(SVIType->getContext()); 17120 if (ScalarType->isHalfTy()) 17121 return Type::getInt16Ty(SVIType->getContext()); 17122 return nullptr; 17123 } 17124 17125 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 17126 EVT VT = ExtVal.getValueType(); 17127 17128 if (!isTypeLegal(VT)) 17129 return false; 17130 17131 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) { 17132 if (Ld->isExpandingLoad()) 17133 return false; 17134 } 17135 17136 if (Subtarget->hasMVEIntegerOps()) 17137 return true; 17138 17139 // Don't create a loadext if we can fold the extension into a wide/long 17140 // instruction. 17141 // If there's more than one user instruction, the loadext is desirable no 17142 // matter what. There can be two uses by the same instruction. 17143 if (ExtVal->use_empty() || 17144 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 17145 return true; 17146 17147 SDNode *U = *ExtVal->use_begin(); 17148 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 17149 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 17150 return false; 17151 17152 return true; 17153 } 17154 17155 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 17156 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 17157 return false; 17158 17159 if (!isTypeLegal(EVT::getEVT(Ty1))) 17160 return false; 17161 17162 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 17163 17164 // Assuming the caller doesn't have a zeroext or signext return parameter, 17165 // truncation all the way down to i1 is valid. 17166 return true; 17167 } 17168 17169 InstructionCost ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 17170 const AddrMode &AM, 17171 Type *Ty, 17172 unsigned AS) const { 17173 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 17174 if (Subtarget->hasFPAO()) 17175 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 17176 return 0; 17177 } 17178 return -1; 17179 } 17180 17181 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster 17182 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be 17183 /// expanded to FMAs when this method returns true, otherwise fmuladd is 17184 /// expanded to fmul + fadd. 17185 /// 17186 /// ARM supports both fused and unfused multiply-add operations; we already 17187 /// lower a pair of fmul and fadd to the latter so it's not clear that there 17188 /// would be a gain or that the gain would be worthwhile enough to risk 17189 /// correctness bugs. 17190 /// 17191 /// For MVE, we set this to true as it helps simplify the need for some 17192 /// patterns (and we don't have the non-fused floating point instruction). 17193 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 17194 EVT VT) const { 17195 if (!VT.isSimple()) 17196 return false; 17197 17198 switch (VT.getSimpleVT().SimpleTy) { 17199 case MVT::v4f32: 17200 case MVT::v8f16: 17201 return Subtarget->hasMVEFloatOps(); 17202 case MVT::f16: 17203 return Subtarget->useFPVFMx16(); 17204 case MVT::f32: 17205 return Subtarget->useFPVFMx(); 17206 case MVT::f64: 17207 return Subtarget->useFPVFMx64(); 17208 default: 17209 break; 17210 } 17211 17212 return false; 17213 } 17214 17215 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 17216 if (V < 0) 17217 return false; 17218 17219 unsigned Scale = 1; 17220 switch (VT.getSimpleVT().SimpleTy) { 17221 case MVT::i1: 17222 case MVT::i8: 17223 // Scale == 1; 17224 break; 17225 case MVT::i16: 17226 // Scale == 2; 17227 Scale = 2; 17228 break; 17229 default: 17230 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 17231 // Scale == 4; 17232 Scale = 4; 17233 break; 17234 } 17235 17236 if ((V & (Scale - 1)) != 0) 17237 return false; 17238 return isUInt<5>(V / Scale); 17239 } 17240 17241 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 17242 const ARMSubtarget *Subtarget) { 17243 if (!VT.isInteger() && !VT.isFloatingPoint()) 17244 return false; 17245 if (VT.isVector() && Subtarget->hasNEON()) 17246 return false; 17247 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 17248 !Subtarget->hasMVEFloatOps()) 17249 return false; 17250 17251 bool IsNeg = false; 17252 if (V < 0) { 17253 IsNeg = true; 17254 V = -V; 17255 } 17256 17257 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U); 17258 17259 // MVE: size * imm7 17260 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 17261 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 17262 case MVT::i32: 17263 case MVT::f32: 17264 return isShiftedUInt<7,2>(V); 17265 case MVT::i16: 17266 case MVT::f16: 17267 return isShiftedUInt<7,1>(V); 17268 case MVT::i8: 17269 return isUInt<7>(V); 17270 default: 17271 return false; 17272 } 17273 } 17274 17275 // half VLDR: 2 * imm8 17276 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 17277 return isShiftedUInt<8, 1>(V); 17278 // VLDR and LDRD: 4 * imm8 17279 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 17280 return isShiftedUInt<8, 2>(V); 17281 17282 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 17283 // + imm12 or - imm8 17284 if (IsNeg) 17285 return isUInt<8>(V); 17286 return isUInt<12>(V); 17287 } 17288 17289 return false; 17290 } 17291 17292 /// isLegalAddressImmediate - Return true if the integer value can be used 17293 /// as the offset of the target addressing mode for load / store of the 17294 /// given type. 17295 static bool isLegalAddressImmediate(int64_t V, EVT VT, 17296 const ARMSubtarget *Subtarget) { 17297 if (V == 0) 17298 return true; 17299 17300 if (!VT.isSimple()) 17301 return false; 17302 17303 if (Subtarget->isThumb1Only()) 17304 return isLegalT1AddressImmediate(V, VT); 17305 else if (Subtarget->isThumb2()) 17306 return isLegalT2AddressImmediate(V, VT, Subtarget); 17307 17308 // ARM mode. 17309 if (V < 0) 17310 V = - V; 17311 switch (VT.getSimpleVT().SimpleTy) { 17312 default: return false; 17313 case MVT::i1: 17314 case MVT::i8: 17315 case MVT::i32: 17316 // +- imm12 17317 return isUInt<12>(V); 17318 case MVT::i16: 17319 // +- imm8 17320 return isUInt<8>(V); 17321 case MVT::f32: 17322 case MVT::f64: 17323 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 17324 return false; 17325 return isShiftedUInt<8, 2>(V); 17326 } 17327 } 17328 17329 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 17330 EVT VT) const { 17331 int Scale = AM.Scale; 17332 if (Scale < 0) 17333 return false; 17334 17335 switch (VT.getSimpleVT().SimpleTy) { 17336 default: return false; 17337 case MVT::i1: 17338 case MVT::i8: 17339 case MVT::i16: 17340 case MVT::i32: 17341 if (Scale == 1) 17342 return true; 17343 // r + r << imm 17344 Scale = Scale & ~1; 17345 return Scale == 2 || Scale == 4 || Scale == 8; 17346 case MVT::i64: 17347 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 17348 // version in Thumb mode. 17349 // r + r 17350 if (Scale == 1) 17351 return true; 17352 // r * 2 (this can be lowered to r + r). 17353 if (!AM.HasBaseReg && Scale == 2) 17354 return true; 17355 return false; 17356 case MVT::isVoid: 17357 // Note, we allow "void" uses (basically, uses that aren't loads or 17358 // stores), because arm allows folding a scale into many arithmetic 17359 // operations. This should be made more precise and revisited later. 17360 17361 // Allow r << imm, but the imm has to be a multiple of two. 17362 if (Scale & 1) return false; 17363 return isPowerOf2_32(Scale); 17364 } 17365 } 17366 17367 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 17368 EVT VT) const { 17369 const int Scale = AM.Scale; 17370 17371 // Negative scales are not supported in Thumb1. 17372 if (Scale < 0) 17373 return false; 17374 17375 // Thumb1 addressing modes do not support register scaling excepting the 17376 // following cases: 17377 // 1. Scale == 1 means no scaling. 17378 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 17379 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 17380 } 17381 17382 /// isLegalAddressingMode - Return true if the addressing mode represented 17383 /// by AM is legal for this target, for a load/store of the specified type. 17384 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 17385 const AddrMode &AM, Type *Ty, 17386 unsigned AS, Instruction *I) const { 17387 EVT VT = getValueType(DL, Ty, true); 17388 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 17389 return false; 17390 17391 // Can never fold addr of global into load/store. 17392 if (AM.BaseGV) 17393 return false; 17394 17395 switch (AM.Scale) { 17396 case 0: // no scale reg, must be "r+i" or "r", or "i". 17397 break; 17398 default: 17399 // ARM doesn't support any R+R*scale+imm addr modes. 17400 if (AM.BaseOffs) 17401 return false; 17402 17403 if (!VT.isSimple()) 17404 return false; 17405 17406 if (Subtarget->isThumb1Only()) 17407 return isLegalT1ScaledAddressingMode(AM, VT); 17408 17409 if (Subtarget->isThumb2()) 17410 return isLegalT2ScaledAddressingMode(AM, VT); 17411 17412 int Scale = AM.Scale; 17413 switch (VT.getSimpleVT().SimpleTy) { 17414 default: return false; 17415 case MVT::i1: 17416 case MVT::i8: 17417 case MVT::i32: 17418 if (Scale < 0) Scale = -Scale; 17419 if (Scale == 1) 17420 return true; 17421 // r + r << imm 17422 return isPowerOf2_32(Scale & ~1); 17423 case MVT::i16: 17424 case MVT::i64: 17425 // r +/- r 17426 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 17427 return true; 17428 // r * 2 (this can be lowered to r + r). 17429 if (!AM.HasBaseReg && Scale == 2) 17430 return true; 17431 return false; 17432 17433 case MVT::isVoid: 17434 // Note, we allow "void" uses (basically, uses that aren't loads or 17435 // stores), because arm allows folding a scale into many arithmetic 17436 // operations. This should be made more precise and revisited later. 17437 17438 // Allow r << imm, but the imm has to be a multiple of two. 17439 if (Scale & 1) return false; 17440 return isPowerOf2_32(Scale); 17441 } 17442 } 17443 return true; 17444 } 17445 17446 /// isLegalICmpImmediate - Return true if the specified immediate is legal 17447 /// icmp immediate, that is the target has icmp instructions which can compare 17448 /// a register against the immediate without having to materialize the 17449 /// immediate into a register. 17450 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 17451 // Thumb2 and ARM modes can use cmn for negative immediates. 17452 if (!Subtarget->isThumb()) 17453 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 17454 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 17455 if (Subtarget->isThumb2()) 17456 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 17457 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 17458 // Thumb1 doesn't have cmn, and only 8-bit immediates. 17459 return Imm >= 0 && Imm <= 255; 17460 } 17461 17462 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 17463 /// *or sub* immediate, that is the target has add or sub instructions which can 17464 /// add a register with the immediate without having to materialize the 17465 /// immediate into a register. 17466 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 17467 // Same encoding for add/sub, just flip the sign. 17468 int64_t AbsImm = std::abs(Imm); 17469 if (!Subtarget->isThumb()) 17470 return ARM_AM::getSOImmVal(AbsImm) != -1; 17471 if (Subtarget->isThumb2()) 17472 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 17473 // Thumb1 only has 8-bit unsigned immediate. 17474 return AbsImm >= 0 && AbsImm <= 255; 17475 } 17476 17477 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 17478 bool isSEXTLoad, SDValue &Base, 17479 SDValue &Offset, bool &isInc, 17480 SelectionDAG &DAG) { 17481 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17482 return false; 17483 17484 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 17485 // AddressingMode 3 17486 Base = Ptr->getOperand(0); 17487 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17488 int RHSC = (int)RHS->getZExtValue(); 17489 if (RHSC < 0 && RHSC > -256) { 17490 assert(Ptr->getOpcode() == ISD::ADD); 17491 isInc = false; 17492 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17493 return true; 17494 } 17495 } 17496 isInc = (Ptr->getOpcode() == ISD::ADD); 17497 Offset = Ptr->getOperand(1); 17498 return true; 17499 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 17500 // AddressingMode 2 17501 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17502 int RHSC = (int)RHS->getZExtValue(); 17503 if (RHSC < 0 && RHSC > -0x1000) { 17504 assert(Ptr->getOpcode() == ISD::ADD); 17505 isInc = false; 17506 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17507 Base = Ptr->getOperand(0); 17508 return true; 17509 } 17510 } 17511 17512 if (Ptr->getOpcode() == ISD::ADD) { 17513 isInc = true; 17514 ARM_AM::ShiftOpc ShOpcVal= 17515 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 17516 if (ShOpcVal != ARM_AM::no_shift) { 17517 Base = Ptr->getOperand(1); 17518 Offset = Ptr->getOperand(0); 17519 } else { 17520 Base = Ptr->getOperand(0); 17521 Offset = Ptr->getOperand(1); 17522 } 17523 return true; 17524 } 17525 17526 isInc = (Ptr->getOpcode() == ISD::ADD); 17527 Base = Ptr->getOperand(0); 17528 Offset = Ptr->getOperand(1); 17529 return true; 17530 } 17531 17532 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 17533 return false; 17534 } 17535 17536 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 17537 bool isSEXTLoad, SDValue &Base, 17538 SDValue &Offset, bool &isInc, 17539 SelectionDAG &DAG) { 17540 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17541 return false; 17542 17543 Base = Ptr->getOperand(0); 17544 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17545 int RHSC = (int)RHS->getZExtValue(); 17546 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 17547 assert(Ptr->getOpcode() == ISD::ADD); 17548 isInc = false; 17549 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17550 return true; 17551 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 17552 isInc = Ptr->getOpcode() == ISD::ADD; 17553 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17554 return true; 17555 } 17556 } 17557 17558 return false; 17559 } 17560 17561 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment, 17562 bool isSEXTLoad, bool IsMasked, bool isLE, 17563 SDValue &Base, SDValue &Offset, 17564 bool &isInc, SelectionDAG &DAG) { 17565 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17566 return false; 17567 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 17568 return false; 17569 17570 // We allow LE non-masked loads to change the type (for example use a vldrb.8 17571 // as opposed to a vldrw.32). This can allow extra addressing modes or 17572 // alignments for what is otherwise an equivalent instruction. 17573 bool CanChangeType = isLE && !IsMasked; 17574 17575 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 17576 int RHSC = (int)RHS->getZExtValue(); 17577 17578 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 17579 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 17580 assert(Ptr->getOpcode() == ISD::ADD); 17581 isInc = false; 17582 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17583 return true; 17584 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 17585 isInc = Ptr->getOpcode() == ISD::ADD; 17586 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17587 return true; 17588 } 17589 return false; 17590 }; 17591 17592 // Try to find a matching instruction based on s/zext, Alignment, Offset and 17593 // (in BE/masked) type. 17594 Base = Ptr->getOperand(0); 17595 if (VT == MVT::v4i16) { 17596 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2)) 17597 return true; 17598 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 17599 if (IsInRange(RHSC, 0x80, 1)) 17600 return true; 17601 } else if (Alignment >= 4 && 17602 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) && 17603 IsInRange(RHSC, 0x80, 4)) 17604 return true; 17605 else if (Alignment >= 2 && 17606 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) && 17607 IsInRange(RHSC, 0x80, 2)) 17608 return true; 17609 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 17610 return true; 17611 return false; 17612 } 17613 17614 /// getPreIndexedAddressParts - returns true by value, base pointer and 17615 /// offset pointer and addressing mode by reference if the node's address 17616 /// can be legally represented as pre-indexed load / store address. 17617 bool 17618 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 17619 SDValue &Offset, 17620 ISD::MemIndexedMode &AM, 17621 SelectionDAG &DAG) const { 17622 if (Subtarget->isThumb1Only()) 17623 return false; 17624 17625 EVT VT; 17626 SDValue Ptr; 17627 Align Alignment; 17628 bool isSEXTLoad = false; 17629 bool IsMasked = false; 17630 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 17631 Ptr = LD->getBasePtr(); 17632 VT = LD->getMemoryVT(); 17633 Alignment = LD->getAlign(); 17634 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17635 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17636 Ptr = ST->getBasePtr(); 17637 VT = ST->getMemoryVT(); 17638 Alignment = ST->getAlign(); 17639 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17640 Ptr = LD->getBasePtr(); 17641 VT = LD->getMemoryVT(); 17642 Alignment = LD->getAlign(); 17643 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17644 IsMasked = true; 17645 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17646 Ptr = ST->getBasePtr(); 17647 VT = ST->getMemoryVT(); 17648 Alignment = ST->getAlign(); 17649 IsMasked = true; 17650 } else 17651 return false; 17652 17653 bool isInc; 17654 bool isLegal = false; 17655 if (VT.isVector()) 17656 isLegal = Subtarget->hasMVEIntegerOps() && 17657 getMVEIndexedAddressParts( 17658 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked, 17659 Subtarget->isLittle(), Base, Offset, isInc, DAG); 17660 else { 17661 if (Subtarget->isThumb2()) 17662 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17663 Offset, isInc, DAG); 17664 else 17665 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17666 Offset, isInc, DAG); 17667 } 17668 if (!isLegal) 17669 return false; 17670 17671 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 17672 return true; 17673 } 17674 17675 /// getPostIndexedAddressParts - returns true by value, base pointer and 17676 /// offset pointer and addressing mode by reference if this node can be 17677 /// combined with a load / store to form a post-indexed load / store. 17678 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 17679 SDValue &Base, 17680 SDValue &Offset, 17681 ISD::MemIndexedMode &AM, 17682 SelectionDAG &DAG) const { 17683 EVT VT; 17684 SDValue Ptr; 17685 Align Alignment; 17686 bool isSEXTLoad = false, isNonExt; 17687 bool IsMasked = false; 17688 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 17689 VT = LD->getMemoryVT(); 17690 Ptr = LD->getBasePtr(); 17691 Alignment = LD->getAlign(); 17692 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17693 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17694 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17695 VT = ST->getMemoryVT(); 17696 Ptr = ST->getBasePtr(); 17697 Alignment = ST->getAlign(); 17698 isNonExt = !ST->isTruncatingStore(); 17699 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17700 VT = LD->getMemoryVT(); 17701 Ptr = LD->getBasePtr(); 17702 Alignment = LD->getAlign(); 17703 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17704 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17705 IsMasked = true; 17706 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17707 VT = ST->getMemoryVT(); 17708 Ptr = ST->getBasePtr(); 17709 Alignment = ST->getAlign(); 17710 isNonExt = !ST->isTruncatingStore(); 17711 IsMasked = true; 17712 } else 17713 return false; 17714 17715 if (Subtarget->isThumb1Only()) { 17716 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 17717 // must be non-extending/truncating, i32, with an offset of 4. 17718 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 17719 if (Op->getOpcode() != ISD::ADD || !isNonExt) 17720 return false; 17721 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 17722 if (!RHS || RHS->getZExtValue() != 4) 17723 return false; 17724 17725 Offset = Op->getOperand(1); 17726 Base = Op->getOperand(0); 17727 AM = ISD::POST_INC; 17728 return true; 17729 } 17730 17731 bool isInc; 17732 bool isLegal = false; 17733 if (VT.isVector()) 17734 isLegal = Subtarget->hasMVEIntegerOps() && 17735 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked, 17736 Subtarget->isLittle(), Base, Offset, 17737 isInc, DAG); 17738 else { 17739 if (Subtarget->isThumb2()) 17740 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17741 isInc, DAG); 17742 else 17743 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17744 isInc, DAG); 17745 } 17746 if (!isLegal) 17747 return false; 17748 17749 if (Ptr != Base) { 17750 // Swap base ptr and offset to catch more post-index load / store when 17751 // it's legal. In Thumb2 mode, offset must be an immediate. 17752 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 17753 !Subtarget->isThumb2()) 17754 std::swap(Base, Offset); 17755 17756 // Post-indexed load / store update the base pointer. 17757 if (Ptr != Base) 17758 return false; 17759 } 17760 17761 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 17762 return true; 17763 } 17764 17765 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 17766 KnownBits &Known, 17767 const APInt &DemandedElts, 17768 const SelectionDAG &DAG, 17769 unsigned Depth) const { 17770 unsigned BitWidth = Known.getBitWidth(); 17771 Known.resetAll(); 17772 switch (Op.getOpcode()) { 17773 default: break; 17774 case ARMISD::ADDC: 17775 case ARMISD::ADDE: 17776 case ARMISD::SUBC: 17777 case ARMISD::SUBE: 17778 // Special cases when we convert a carry to a boolean. 17779 if (Op.getResNo() == 0) { 17780 SDValue LHS = Op.getOperand(0); 17781 SDValue RHS = Op.getOperand(1); 17782 // (ADDE 0, 0, C) will give us a single bit. 17783 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 17784 isNullConstant(RHS)) { 17785 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 17786 return; 17787 } 17788 } 17789 break; 17790 case ARMISD::CMOV: { 17791 // Bits are known zero/one if known on the LHS and RHS. 17792 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 17793 if (Known.isUnknown()) 17794 return; 17795 17796 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 17797 Known = KnownBits::commonBits(Known, KnownRHS); 17798 return; 17799 } 17800 case ISD::INTRINSIC_W_CHAIN: { 17801 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 17802 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 17803 switch (IntID) { 17804 default: return; 17805 case Intrinsic::arm_ldaex: 17806 case Intrinsic::arm_ldrex: { 17807 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 17808 unsigned MemBits = VT.getScalarSizeInBits(); 17809 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 17810 return; 17811 } 17812 } 17813 } 17814 case ARMISD::BFI: { 17815 // Conservatively, we can recurse down the first operand 17816 // and just mask out all affected bits. 17817 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 17818 17819 // The operand to BFI is already a mask suitable for removing the bits it 17820 // sets. 17821 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 17822 const APInt &Mask = CI->getAPIntValue(); 17823 Known.Zero &= Mask; 17824 Known.One &= Mask; 17825 return; 17826 } 17827 case ARMISD::VGETLANEs: 17828 case ARMISD::VGETLANEu: { 17829 const SDValue &SrcSV = Op.getOperand(0); 17830 EVT VecVT = SrcSV.getValueType(); 17831 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 17832 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 17833 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 17834 assert(Pos->getAPIntValue().ult(NumSrcElts) && 17835 "VGETLANE index out of bounds"); 17836 unsigned Idx = Pos->getZExtValue(); 17837 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 17838 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 17839 17840 EVT VT = Op.getValueType(); 17841 const unsigned DstSz = VT.getScalarSizeInBits(); 17842 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 17843 (void)SrcSz; 17844 assert(SrcSz == Known.getBitWidth()); 17845 assert(DstSz > SrcSz); 17846 if (Op.getOpcode() == ARMISD::VGETLANEs) 17847 Known = Known.sext(DstSz); 17848 else { 17849 Known = Known.zext(DstSz); 17850 } 17851 assert(DstSz == Known.getBitWidth()); 17852 break; 17853 } 17854 case ARMISD::VMOVrh: { 17855 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 17856 assert(KnownOp.getBitWidth() == 16); 17857 Known = KnownOp.zext(32); 17858 break; 17859 } 17860 case ARMISD::CSINC: 17861 case ARMISD::CSINV: 17862 case ARMISD::CSNEG: { 17863 KnownBits KnownOp0 = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 17864 KnownBits KnownOp1 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); 17865 17866 // The result is either: 17867 // CSINC: KnownOp0 or KnownOp1 + 1 17868 // CSINV: KnownOp0 or ~KnownOp1 17869 // CSNEG: KnownOp0 or KnownOp1 * -1 17870 if (Op.getOpcode() == ARMISD::CSINC) 17871 KnownOp1 = KnownBits::computeForAddSub( 17872 true, false, KnownOp1, KnownBits::makeConstant(APInt(32, 1))); 17873 else if (Op.getOpcode() == ARMISD::CSINV) 17874 std::swap(KnownOp1.Zero, KnownOp1.One); 17875 else if (Op.getOpcode() == ARMISD::CSNEG) 17876 KnownOp1 = KnownBits::mul( 17877 KnownOp1, KnownBits::makeConstant(APInt(32, -1))); 17878 17879 Known = KnownBits::commonBits(KnownOp0, KnownOp1); 17880 break; 17881 } 17882 } 17883 } 17884 17885 bool ARMTargetLowering::targetShrinkDemandedConstant( 17886 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 17887 TargetLoweringOpt &TLO) const { 17888 // Delay optimization, so we don't have to deal with illegal types, or block 17889 // optimizations. 17890 if (!TLO.LegalOps) 17891 return false; 17892 17893 // Only optimize AND for now. 17894 if (Op.getOpcode() != ISD::AND) 17895 return false; 17896 17897 EVT VT = Op.getValueType(); 17898 17899 // Ignore vectors. 17900 if (VT.isVector()) 17901 return false; 17902 17903 assert(VT == MVT::i32 && "Unexpected integer type"); 17904 17905 // Make sure the RHS really is a constant. 17906 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 17907 if (!C) 17908 return false; 17909 17910 unsigned Mask = C->getZExtValue(); 17911 17912 unsigned Demanded = DemandedBits.getZExtValue(); 17913 unsigned ShrunkMask = Mask & Demanded; 17914 unsigned ExpandedMask = Mask | ~Demanded; 17915 17916 // If the mask is all zeros, let the target-independent code replace the 17917 // result with zero. 17918 if (ShrunkMask == 0) 17919 return false; 17920 17921 // If the mask is all ones, erase the AND. (Currently, the target-independent 17922 // code won't do this, so we have to do it explicitly to avoid an infinite 17923 // loop in obscure cases.) 17924 if (ExpandedMask == ~0U) 17925 return TLO.CombineTo(Op, Op.getOperand(0)); 17926 17927 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 17928 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 17929 }; 17930 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 17931 if (NewMask == Mask) 17932 return true; 17933 SDLoc DL(Op); 17934 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 17935 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 17936 return TLO.CombineTo(Op, NewOp); 17937 }; 17938 17939 // Prefer uxtb mask. 17940 if (IsLegalMask(0xFF)) 17941 return UseMask(0xFF); 17942 17943 // Prefer uxth mask. 17944 if (IsLegalMask(0xFFFF)) 17945 return UseMask(0xFFFF); 17946 17947 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 17948 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17949 if (ShrunkMask < 256) 17950 return UseMask(ShrunkMask); 17951 17952 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 17953 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17954 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 17955 return UseMask(ExpandedMask); 17956 17957 // Potential improvements: 17958 // 17959 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 17960 // We could try to prefer Thumb1 immediates which can be lowered to a 17961 // two-instruction sequence. 17962 // We could try to recognize more legal ARM/Thumb2 immediates here. 17963 17964 return false; 17965 } 17966 17967 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode( 17968 SDValue Op, const APInt &OriginalDemandedBits, 17969 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 17970 unsigned Depth) const { 17971 unsigned Opc = Op.getOpcode(); 17972 17973 switch (Opc) { 17974 case ARMISD::ASRL: 17975 case ARMISD::LSRL: { 17976 // If this is result 0 and the other result is unused, see if the demand 17977 // bits allow us to shrink this long shift into a standard small shift in 17978 // the opposite direction. 17979 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) && 17980 isa<ConstantSDNode>(Op->getOperand(2))) { 17981 unsigned ShAmt = Op->getConstantOperandVal(2); 17982 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf( 17983 APInt::getAllOnesValue(32) << (32 - ShAmt))) 17984 return TLO.CombineTo( 17985 Op, TLO.DAG.getNode( 17986 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1), 17987 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32))); 17988 } 17989 break; 17990 } 17991 } 17992 17993 return TargetLowering::SimplifyDemandedBitsForTargetNode( 17994 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth); 17995 } 17996 17997 //===----------------------------------------------------------------------===// 17998 // ARM Inline Assembly Support 17999 //===----------------------------------------------------------------------===// 18000 18001 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 18002 // Looking for "rev" which is V6+. 18003 if (!Subtarget->hasV6Ops()) 18004 return false; 18005 18006 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand()); 18007 std::string AsmStr = IA->getAsmString(); 18008 SmallVector<StringRef, 4> AsmPieces; 18009 SplitString(AsmStr, AsmPieces, ";\n"); 18010 18011 switch (AsmPieces.size()) { 18012 default: return false; 18013 case 1: 18014 AsmStr = std::string(AsmPieces[0]); 18015 AsmPieces.clear(); 18016 SplitString(AsmStr, AsmPieces, " \t,"); 18017 18018 // rev $0, $1 18019 if (AsmPieces.size() == 3 && 18020 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 18021 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 18022 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 18023 if (Ty && Ty->getBitWidth() == 32) 18024 return IntrinsicLowering::LowerToByteSwap(CI); 18025 } 18026 break; 18027 } 18028 18029 return false; 18030 } 18031 18032 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 18033 // At this point, we have to lower this constraint to something else, so we 18034 // lower it to an "r" or "w". However, by doing this we will force the result 18035 // to be in register, while the X constraint is much more permissive. 18036 // 18037 // Although we are correct (we are free to emit anything, without 18038 // constraints), we might break use cases that would expect us to be more 18039 // efficient and emit something else. 18040 if (!Subtarget->hasVFP2Base()) 18041 return "r"; 18042 if (ConstraintVT.isFloatingPoint()) 18043 return "w"; 18044 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 18045 (ConstraintVT.getSizeInBits() == 64 || 18046 ConstraintVT.getSizeInBits() == 128)) 18047 return "w"; 18048 18049 return "r"; 18050 } 18051 18052 /// getConstraintType - Given a constraint letter, return the type of 18053 /// constraint it is for this target. 18054 ARMTargetLowering::ConstraintType 18055 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 18056 unsigned S = Constraint.size(); 18057 if (S == 1) { 18058 switch (Constraint[0]) { 18059 default: break; 18060 case 'l': return C_RegisterClass; 18061 case 'w': return C_RegisterClass; 18062 case 'h': return C_RegisterClass; 18063 case 'x': return C_RegisterClass; 18064 case 't': return C_RegisterClass; 18065 case 'j': return C_Immediate; // Constant for movw. 18066 // An address with a single base register. Due to the way we 18067 // currently handle addresses it is the same as an 'r' memory constraint. 18068 case 'Q': return C_Memory; 18069 } 18070 } else if (S == 2) { 18071 switch (Constraint[0]) { 18072 default: break; 18073 case 'T': return C_RegisterClass; 18074 // All 'U+' constraints are addresses. 18075 case 'U': return C_Memory; 18076 } 18077 } 18078 return TargetLowering::getConstraintType(Constraint); 18079 } 18080 18081 /// Examine constraint type and operand type and determine a weight value. 18082 /// This object must already have been set up with the operand type 18083 /// and the current alternative constraint selected. 18084 TargetLowering::ConstraintWeight 18085 ARMTargetLowering::getSingleConstraintMatchWeight( 18086 AsmOperandInfo &info, const char *constraint) const { 18087 ConstraintWeight weight = CW_Invalid; 18088 Value *CallOperandVal = info.CallOperandVal; 18089 // If we don't have a value, we can't do a match, 18090 // but allow it at the lowest weight. 18091 if (!CallOperandVal) 18092 return CW_Default; 18093 Type *type = CallOperandVal->getType(); 18094 // Look at the constraint type. 18095 switch (*constraint) { 18096 default: 18097 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 18098 break; 18099 case 'l': 18100 if (type->isIntegerTy()) { 18101 if (Subtarget->isThumb()) 18102 weight = CW_SpecificReg; 18103 else 18104 weight = CW_Register; 18105 } 18106 break; 18107 case 'w': 18108 if (type->isFloatingPointTy()) 18109 weight = CW_Register; 18110 break; 18111 } 18112 return weight; 18113 } 18114 18115 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 18116 18117 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 18118 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 18119 switch (Constraint.size()) { 18120 case 1: 18121 // GCC ARM Constraint Letters 18122 switch (Constraint[0]) { 18123 case 'l': // Low regs or general regs. 18124 if (Subtarget->isThumb()) 18125 return RCPair(0U, &ARM::tGPRRegClass); 18126 return RCPair(0U, &ARM::GPRRegClass); 18127 case 'h': // High regs or no regs. 18128 if (Subtarget->isThumb()) 18129 return RCPair(0U, &ARM::hGPRRegClass); 18130 break; 18131 case 'r': 18132 if (Subtarget->isThumb1Only()) 18133 return RCPair(0U, &ARM::tGPRRegClass); 18134 return RCPair(0U, &ARM::GPRRegClass); 18135 case 'w': 18136 if (VT == MVT::Other) 18137 break; 18138 if (VT == MVT::f32) 18139 return RCPair(0U, &ARM::SPRRegClass); 18140 if (VT.getSizeInBits() == 64) 18141 return RCPair(0U, &ARM::DPRRegClass); 18142 if (VT.getSizeInBits() == 128) 18143 return RCPair(0U, &ARM::QPRRegClass); 18144 break; 18145 case 'x': 18146 if (VT == MVT::Other) 18147 break; 18148 if (VT == MVT::f32) 18149 return RCPair(0U, &ARM::SPR_8RegClass); 18150 if (VT.getSizeInBits() == 64) 18151 return RCPair(0U, &ARM::DPR_8RegClass); 18152 if (VT.getSizeInBits() == 128) 18153 return RCPair(0U, &ARM::QPR_8RegClass); 18154 break; 18155 case 't': 18156 if (VT == MVT::Other) 18157 break; 18158 if (VT == MVT::f32 || VT == MVT::i32) 18159 return RCPair(0U, &ARM::SPRRegClass); 18160 if (VT.getSizeInBits() == 64) 18161 return RCPair(0U, &ARM::DPR_VFP2RegClass); 18162 if (VT.getSizeInBits() == 128) 18163 return RCPair(0U, &ARM::QPR_VFP2RegClass); 18164 break; 18165 } 18166 break; 18167 18168 case 2: 18169 if (Constraint[0] == 'T') { 18170 switch (Constraint[1]) { 18171 default: 18172 break; 18173 case 'e': 18174 return RCPair(0U, &ARM::tGPREvenRegClass); 18175 case 'o': 18176 return RCPair(0U, &ARM::tGPROddRegClass); 18177 } 18178 } 18179 break; 18180 18181 default: 18182 break; 18183 } 18184 18185 if (StringRef("{cc}").equals_lower(Constraint)) 18186 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 18187 18188 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 18189 } 18190 18191 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 18192 /// vector. If it is invalid, don't add anything to Ops. 18193 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 18194 std::string &Constraint, 18195 std::vector<SDValue>&Ops, 18196 SelectionDAG &DAG) const { 18197 SDValue Result; 18198 18199 // Currently only support length 1 constraints. 18200 if (Constraint.length() != 1) return; 18201 18202 char ConstraintLetter = Constraint[0]; 18203 switch (ConstraintLetter) { 18204 default: break; 18205 case 'j': 18206 case 'I': case 'J': case 'K': case 'L': 18207 case 'M': case 'N': case 'O': 18208 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 18209 if (!C) 18210 return; 18211 18212 int64_t CVal64 = C->getSExtValue(); 18213 int CVal = (int) CVal64; 18214 // None of these constraints allow values larger than 32 bits. Check 18215 // that the value fits in an int. 18216 if (CVal != CVal64) 18217 return; 18218 18219 switch (ConstraintLetter) { 18220 case 'j': 18221 // Constant suitable for movw, must be between 0 and 18222 // 65535. 18223 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps())) 18224 if (CVal >= 0 && CVal <= 65535) 18225 break; 18226 return; 18227 case 'I': 18228 if (Subtarget->isThumb1Only()) { 18229 // This must be a constant between 0 and 255, for ADD 18230 // immediates. 18231 if (CVal >= 0 && CVal <= 255) 18232 break; 18233 } else if (Subtarget->isThumb2()) { 18234 // A constant that can be used as an immediate value in a 18235 // data-processing instruction. 18236 if (ARM_AM::getT2SOImmVal(CVal) != -1) 18237 break; 18238 } else { 18239 // A constant that can be used as an immediate value in a 18240 // data-processing instruction. 18241 if (ARM_AM::getSOImmVal(CVal) != -1) 18242 break; 18243 } 18244 return; 18245 18246 case 'J': 18247 if (Subtarget->isThumb1Only()) { 18248 // This must be a constant between -255 and -1, for negated ADD 18249 // immediates. This can be used in GCC with an "n" modifier that 18250 // prints the negated value, for use with SUB instructions. It is 18251 // not useful otherwise but is implemented for compatibility. 18252 if (CVal >= -255 && CVal <= -1) 18253 break; 18254 } else { 18255 // This must be a constant between -4095 and 4095. It is not clear 18256 // what this constraint is intended for. Implemented for 18257 // compatibility with GCC. 18258 if (CVal >= -4095 && CVal <= 4095) 18259 break; 18260 } 18261 return; 18262 18263 case 'K': 18264 if (Subtarget->isThumb1Only()) { 18265 // A 32-bit value where only one byte has a nonzero value. Exclude 18266 // zero to match GCC. This constraint is used by GCC internally for 18267 // constants that can be loaded with a move/shift combination. 18268 // It is not useful otherwise but is implemented for compatibility. 18269 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 18270 break; 18271 } else if (Subtarget->isThumb2()) { 18272 // A constant whose bitwise inverse can be used as an immediate 18273 // value in a data-processing instruction. This can be used in GCC 18274 // with a "B" modifier that prints the inverted value, for use with 18275 // BIC and MVN instructions. It is not useful otherwise but is 18276 // implemented for compatibility. 18277 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 18278 break; 18279 } else { 18280 // A constant whose bitwise inverse can be used as an immediate 18281 // value in a data-processing instruction. This can be used in GCC 18282 // with a "B" modifier that prints the inverted value, for use with 18283 // BIC and MVN instructions. It is not useful otherwise but is 18284 // implemented for compatibility. 18285 if (ARM_AM::getSOImmVal(~CVal) != -1) 18286 break; 18287 } 18288 return; 18289 18290 case 'L': 18291 if (Subtarget->isThumb1Only()) { 18292 // This must be a constant between -7 and 7, 18293 // for 3-operand ADD/SUB immediate instructions. 18294 if (CVal >= -7 && CVal < 7) 18295 break; 18296 } else if (Subtarget->isThumb2()) { 18297 // A constant whose negation can be used as an immediate value in a 18298 // data-processing instruction. This can be used in GCC with an "n" 18299 // modifier that prints the negated value, for use with SUB 18300 // instructions. It is not useful otherwise but is implemented for 18301 // compatibility. 18302 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 18303 break; 18304 } else { 18305 // A constant whose negation can be used as an immediate value in a 18306 // data-processing instruction. This can be used in GCC with an "n" 18307 // modifier that prints the negated value, for use with SUB 18308 // instructions. It is not useful otherwise but is implemented for 18309 // compatibility. 18310 if (ARM_AM::getSOImmVal(-CVal) != -1) 18311 break; 18312 } 18313 return; 18314 18315 case 'M': 18316 if (Subtarget->isThumb1Only()) { 18317 // This must be a multiple of 4 between 0 and 1020, for 18318 // ADD sp + immediate. 18319 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 18320 break; 18321 } else { 18322 // A power of two or a constant between 0 and 32. This is used in 18323 // GCC for the shift amount on shifted register operands, but it is 18324 // useful in general for any shift amounts. 18325 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 18326 break; 18327 } 18328 return; 18329 18330 case 'N': 18331 if (Subtarget->isThumb1Only()) { 18332 // This must be a constant between 0 and 31, for shift amounts. 18333 if (CVal >= 0 && CVal <= 31) 18334 break; 18335 } 18336 return; 18337 18338 case 'O': 18339 if (Subtarget->isThumb1Only()) { 18340 // This must be a multiple of 4 between -508 and 508, for 18341 // ADD/SUB sp = sp + immediate. 18342 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 18343 break; 18344 } 18345 return; 18346 } 18347 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 18348 break; 18349 } 18350 18351 if (Result.getNode()) { 18352 Ops.push_back(Result); 18353 return; 18354 } 18355 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 18356 } 18357 18358 static RTLIB::Libcall getDivRemLibcall( 18359 const SDNode *N, MVT::SimpleValueType SVT) { 18360 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 18361 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 18362 "Unhandled Opcode in getDivRemLibcall"); 18363 bool isSigned = N->getOpcode() == ISD::SDIVREM || 18364 N->getOpcode() == ISD::SREM; 18365 RTLIB::Libcall LC; 18366 switch (SVT) { 18367 default: llvm_unreachable("Unexpected request for libcall!"); 18368 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 18369 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 18370 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 18371 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 18372 } 18373 return LC; 18374 } 18375 18376 static TargetLowering::ArgListTy getDivRemArgList( 18377 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 18378 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 18379 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 18380 "Unhandled Opcode in getDivRemArgList"); 18381 bool isSigned = N->getOpcode() == ISD::SDIVREM || 18382 N->getOpcode() == ISD::SREM; 18383 TargetLowering::ArgListTy Args; 18384 TargetLowering::ArgListEntry Entry; 18385 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 18386 EVT ArgVT = N->getOperand(i).getValueType(); 18387 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 18388 Entry.Node = N->getOperand(i); 18389 Entry.Ty = ArgTy; 18390 Entry.IsSExt = isSigned; 18391 Entry.IsZExt = !isSigned; 18392 Args.push_back(Entry); 18393 } 18394 if (Subtarget->isTargetWindows() && Args.size() >= 2) 18395 std::swap(Args[0], Args[1]); 18396 return Args; 18397 } 18398 18399 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 18400 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 18401 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 18402 Subtarget->isTargetWindows()) && 18403 "Register-based DivRem lowering only"); 18404 unsigned Opcode = Op->getOpcode(); 18405 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 18406 "Invalid opcode for Div/Rem lowering"); 18407 bool isSigned = (Opcode == ISD::SDIVREM); 18408 EVT VT = Op->getValueType(0); 18409 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 18410 SDLoc dl(Op); 18411 18412 // If the target has hardware divide, use divide + multiply + subtract: 18413 // div = a / b 18414 // rem = a - b * div 18415 // return {div, rem} 18416 // This should be lowered into UDIV/SDIV + MLS later on. 18417 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 18418 : Subtarget->hasDivideInARMMode(); 18419 if (hasDivide && Op->getValueType(0).isSimple() && 18420 Op->getSimpleValueType(0) == MVT::i32) { 18421 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 18422 const SDValue Dividend = Op->getOperand(0); 18423 const SDValue Divisor = Op->getOperand(1); 18424 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 18425 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 18426 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 18427 18428 SDValue Values[2] = {Div, Rem}; 18429 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 18430 } 18431 18432 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 18433 VT.getSimpleVT().SimpleTy); 18434 SDValue InChain = DAG.getEntryNode(); 18435 18436 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 18437 DAG.getContext(), 18438 Subtarget); 18439 18440 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 18441 getPointerTy(DAG.getDataLayout())); 18442 18443 Type *RetTy = StructType::get(Ty, Ty); 18444 18445 if (Subtarget->isTargetWindows()) 18446 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 18447 18448 TargetLowering::CallLoweringInfo CLI(DAG); 18449 CLI.setDebugLoc(dl).setChain(InChain) 18450 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 18451 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 18452 18453 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 18454 return CallInfo.first; 18455 } 18456 18457 // Lowers REM using divmod helpers 18458 // see RTABI section 4.2/4.3 18459 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 18460 // Build return types (div and rem) 18461 std::vector<Type*> RetTyParams; 18462 Type *RetTyElement; 18463 18464 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 18465 default: llvm_unreachable("Unexpected request for libcall!"); 18466 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 18467 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 18468 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 18469 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 18470 } 18471 18472 RetTyParams.push_back(RetTyElement); 18473 RetTyParams.push_back(RetTyElement); 18474 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 18475 Type *RetTy = StructType::get(*DAG.getContext(), ret); 18476 18477 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 18478 SimpleTy); 18479 SDValue InChain = DAG.getEntryNode(); 18480 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 18481 Subtarget); 18482 bool isSigned = N->getOpcode() == ISD::SREM; 18483 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 18484 getPointerTy(DAG.getDataLayout())); 18485 18486 if (Subtarget->isTargetWindows()) 18487 InChain = WinDBZCheckDenominator(DAG, N, InChain); 18488 18489 // Lower call 18490 CallLoweringInfo CLI(DAG); 18491 CLI.setChain(InChain) 18492 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 18493 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 18494 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 18495 18496 // Return second (rem) result operand (first contains div) 18497 SDNode *ResNode = CallResult.first.getNode(); 18498 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 18499 return ResNode->getOperand(1); 18500 } 18501 18502 SDValue 18503 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 18504 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 18505 SDLoc DL(Op); 18506 18507 // Get the inputs. 18508 SDValue Chain = Op.getOperand(0); 18509 SDValue Size = Op.getOperand(1); 18510 18511 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 18512 "no-stack-arg-probe")) { 18513 MaybeAlign Align = 18514 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue(); 18515 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 18516 Chain = SP.getValue(1); 18517 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 18518 if (Align) 18519 SP = 18520 DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 18521 DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32)); 18522 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 18523 SDValue Ops[2] = { SP, Chain }; 18524 return DAG.getMergeValues(Ops, DL); 18525 } 18526 18527 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 18528 DAG.getConstant(2, DL, MVT::i32)); 18529 18530 SDValue Flag; 18531 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 18532 Flag = Chain.getValue(1); 18533 18534 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 18535 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 18536 18537 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 18538 Chain = NewSP.getValue(1); 18539 18540 SDValue Ops[2] = { NewSP, Chain }; 18541 return DAG.getMergeValues(Ops, DL); 18542 } 18543 18544 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 18545 bool IsStrict = Op->isStrictFPOpcode(); 18546 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 18547 const unsigned DstSz = Op.getValueType().getSizeInBits(); 18548 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 18549 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 18550 "Unexpected type for custom-lowering FP_EXTEND"); 18551 18552 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 18553 "With both FP DP and 16, any FP conversion is legal!"); 18554 18555 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 18556 "With FP16, 16 to 32 conversion is legal!"); 18557 18558 // Converting from 32 -> 64 is valid if we have FP64. 18559 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) { 18560 // FIXME: Remove this when we have strict fp instruction selection patterns 18561 if (IsStrict) { 18562 SDLoc Loc(Op); 18563 SDValue Result = DAG.getNode(ISD::FP_EXTEND, 18564 Loc, Op.getValueType(), SrcVal); 18565 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 18566 } 18567 return Op; 18568 } 18569 18570 // Either we are converting from 16 -> 64, without FP16 and/or 18571 // FP.double-precision or without Armv8-fp. So we must do it in two 18572 // steps. 18573 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 18574 // without FP16. So we must do a function call. 18575 SDLoc Loc(Op); 18576 RTLIB::Libcall LC; 18577 MakeLibCallOptions CallOptions; 18578 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 18579 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) { 18580 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64()); 18581 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32); 18582 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64); 18583 if (Supported) { 18584 if (IsStrict) { 18585 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc, 18586 {DstVT, MVT::Other}, {Chain, SrcVal}); 18587 Chain = SrcVal.getValue(1); 18588 } else { 18589 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal); 18590 } 18591 } else { 18592 LC = RTLIB::getFPEXT(SrcVT, DstVT); 18593 assert(LC != RTLIB::UNKNOWN_LIBCALL && 18594 "Unexpected type for custom-lowering FP_EXTEND"); 18595 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 18596 Loc, Chain); 18597 } 18598 } 18599 18600 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal; 18601 } 18602 18603 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 18604 bool IsStrict = Op->isStrictFPOpcode(); 18605 18606 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 18607 EVT SrcVT = SrcVal.getValueType(); 18608 EVT DstVT = Op.getValueType(); 18609 const unsigned DstSz = Op.getValueType().getSizeInBits(); 18610 const unsigned SrcSz = SrcVT.getSizeInBits(); 18611 (void)DstSz; 18612 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 18613 "Unexpected type for custom-lowering FP_ROUND"); 18614 18615 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 18616 "With both FP DP and 16, any FP conversion is legal!"); 18617 18618 SDLoc Loc(Op); 18619 18620 // Instruction from 32 -> 16 if hasFP16 is valid 18621 if (SrcSz == 32 && Subtarget->hasFP16()) 18622 return Op; 18623 18624 // Lib call from 32 -> 16 / 64 -> [32, 16] 18625 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 18626 assert(LC != RTLIB::UNKNOWN_LIBCALL && 18627 "Unexpected type for custom-lowering FP_ROUND"); 18628 MakeLibCallOptions CallOptions; 18629 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 18630 SDValue Result; 18631 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 18632 Loc, Chain); 18633 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 18634 } 18635 18636 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 18637 SelectionDAG &DAG) const { 18638 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 18639 MVT HalfT = MVT::i32; 18640 SDLoc dl(N); 18641 SDValue Hi, Lo, Tmp; 18642 18643 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 18644 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 18645 return ; 18646 18647 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 18648 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 18649 18650 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 18651 DAG.getConstant(0, dl, HalfT)); 18652 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 18653 DAG.getConstant(1, dl, HalfT)); 18654 18655 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 18656 DAG.getConstant(OpTypeBits - 1, dl, 18657 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 18658 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 18659 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 18660 SDValue(Lo.getNode(), 1)); 18661 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 18662 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 18663 18664 Results.push_back(Lo); 18665 Results.push_back(Hi); 18666 } 18667 18668 bool 18669 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 18670 // The ARM target isn't yet aware of offsets. 18671 return false; 18672 } 18673 18674 bool ARM::isBitFieldInvertedMask(unsigned v) { 18675 if (v == 0xffffffff) 18676 return false; 18677 18678 // there can be 1's on either or both "outsides", all the "inside" 18679 // bits must be 0's 18680 return isShiftedMask_32(~v); 18681 } 18682 18683 /// isFPImmLegal - Returns true if the target can instruction select the 18684 /// specified FP immediate natively. If false, the legalizer will 18685 /// materialize the FP immediate as a load from a constant pool. 18686 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 18687 bool ForCodeSize) const { 18688 if (!Subtarget->hasVFP3Base()) 18689 return false; 18690 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 18691 return ARM_AM::getFP16Imm(Imm) != -1; 18692 if (VT == MVT::f32 && Subtarget->hasFullFP16() && 18693 ARM_AM::getFP32FP16Imm(Imm) != -1) 18694 return true; 18695 if (VT == MVT::f32) 18696 return ARM_AM::getFP32Imm(Imm) != -1; 18697 if (VT == MVT::f64 && Subtarget->hasFP64()) 18698 return ARM_AM::getFP64Imm(Imm) != -1; 18699 return false; 18700 } 18701 18702 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 18703 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 18704 /// specified in the intrinsic calls. 18705 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 18706 const CallInst &I, 18707 MachineFunction &MF, 18708 unsigned Intrinsic) const { 18709 switch (Intrinsic) { 18710 case Intrinsic::arm_neon_vld1: 18711 case Intrinsic::arm_neon_vld2: 18712 case Intrinsic::arm_neon_vld3: 18713 case Intrinsic::arm_neon_vld4: 18714 case Intrinsic::arm_neon_vld2lane: 18715 case Intrinsic::arm_neon_vld3lane: 18716 case Intrinsic::arm_neon_vld4lane: 18717 case Intrinsic::arm_neon_vld2dup: 18718 case Intrinsic::arm_neon_vld3dup: 18719 case Intrinsic::arm_neon_vld4dup: { 18720 Info.opc = ISD::INTRINSIC_W_CHAIN; 18721 // Conservatively set memVT to the entire set of vectors loaded. 18722 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18723 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18724 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18725 Info.ptrVal = I.getArgOperand(0); 18726 Info.offset = 0; 18727 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18728 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18729 // volatile loads with NEON intrinsics not supported 18730 Info.flags = MachineMemOperand::MOLoad; 18731 return true; 18732 } 18733 case Intrinsic::arm_neon_vld1x2: 18734 case Intrinsic::arm_neon_vld1x3: 18735 case Intrinsic::arm_neon_vld1x4: { 18736 Info.opc = ISD::INTRINSIC_W_CHAIN; 18737 // Conservatively set memVT to the entire set of vectors loaded. 18738 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18739 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18740 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18741 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 18742 Info.offset = 0; 18743 Info.align.reset(); 18744 // volatile loads with NEON intrinsics not supported 18745 Info.flags = MachineMemOperand::MOLoad; 18746 return true; 18747 } 18748 case Intrinsic::arm_neon_vst1: 18749 case Intrinsic::arm_neon_vst2: 18750 case Intrinsic::arm_neon_vst3: 18751 case Intrinsic::arm_neon_vst4: 18752 case Intrinsic::arm_neon_vst2lane: 18753 case Intrinsic::arm_neon_vst3lane: 18754 case Intrinsic::arm_neon_vst4lane: { 18755 Info.opc = ISD::INTRINSIC_VOID; 18756 // Conservatively set memVT to the entire set of vectors stored. 18757 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18758 unsigned NumElts = 0; 18759 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18760 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18761 if (!ArgTy->isVectorTy()) 18762 break; 18763 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18764 } 18765 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18766 Info.ptrVal = I.getArgOperand(0); 18767 Info.offset = 0; 18768 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18769 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18770 // volatile stores with NEON intrinsics not supported 18771 Info.flags = MachineMemOperand::MOStore; 18772 return true; 18773 } 18774 case Intrinsic::arm_neon_vst1x2: 18775 case Intrinsic::arm_neon_vst1x3: 18776 case Intrinsic::arm_neon_vst1x4: { 18777 Info.opc = ISD::INTRINSIC_VOID; 18778 // Conservatively set memVT to the entire set of vectors stored. 18779 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18780 unsigned NumElts = 0; 18781 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18782 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18783 if (!ArgTy->isVectorTy()) 18784 break; 18785 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18786 } 18787 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18788 Info.ptrVal = I.getArgOperand(0); 18789 Info.offset = 0; 18790 Info.align.reset(); 18791 // volatile stores with NEON intrinsics not supported 18792 Info.flags = MachineMemOperand::MOStore; 18793 return true; 18794 } 18795 case Intrinsic::arm_mve_vld2q: 18796 case Intrinsic::arm_mve_vld4q: { 18797 Info.opc = ISD::INTRINSIC_W_CHAIN; 18798 // Conservatively set memVT to the entire set of vectors loaded. 18799 Type *VecTy = cast<StructType>(I.getType())->getElementType(1); 18800 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4; 18801 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18802 Info.ptrVal = I.getArgOperand(0); 18803 Info.offset = 0; 18804 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18805 // volatile loads with MVE intrinsics not supported 18806 Info.flags = MachineMemOperand::MOLoad; 18807 return true; 18808 } 18809 case Intrinsic::arm_mve_vst2q: 18810 case Intrinsic::arm_mve_vst4q: { 18811 Info.opc = ISD::INTRINSIC_VOID; 18812 // Conservatively set memVT to the entire set of vectors stored. 18813 Type *VecTy = I.getArgOperand(1)->getType(); 18814 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4; 18815 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18816 Info.ptrVal = I.getArgOperand(0); 18817 Info.offset = 0; 18818 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18819 // volatile stores with MVE intrinsics not supported 18820 Info.flags = MachineMemOperand::MOStore; 18821 return true; 18822 } 18823 case Intrinsic::arm_ldaex: 18824 case Intrinsic::arm_ldrex: { 18825 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18826 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 18827 Info.opc = ISD::INTRINSIC_W_CHAIN; 18828 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18829 Info.ptrVal = I.getArgOperand(0); 18830 Info.offset = 0; 18831 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18832 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18833 return true; 18834 } 18835 case Intrinsic::arm_stlex: 18836 case Intrinsic::arm_strex: { 18837 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18838 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 18839 Info.opc = ISD::INTRINSIC_W_CHAIN; 18840 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18841 Info.ptrVal = I.getArgOperand(1); 18842 Info.offset = 0; 18843 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18844 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18845 return true; 18846 } 18847 case Intrinsic::arm_stlexd: 18848 case Intrinsic::arm_strexd: 18849 Info.opc = ISD::INTRINSIC_W_CHAIN; 18850 Info.memVT = MVT::i64; 18851 Info.ptrVal = I.getArgOperand(2); 18852 Info.offset = 0; 18853 Info.align = Align(8); 18854 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18855 return true; 18856 18857 case Intrinsic::arm_ldaexd: 18858 case Intrinsic::arm_ldrexd: 18859 Info.opc = ISD::INTRINSIC_W_CHAIN; 18860 Info.memVT = MVT::i64; 18861 Info.ptrVal = I.getArgOperand(0); 18862 Info.offset = 0; 18863 Info.align = Align(8); 18864 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18865 return true; 18866 18867 default: 18868 break; 18869 } 18870 18871 return false; 18872 } 18873 18874 /// Returns true if it is beneficial to convert a load of a constant 18875 /// to just the constant itself. 18876 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 18877 Type *Ty) const { 18878 assert(Ty->isIntegerTy()); 18879 18880 unsigned Bits = Ty->getPrimitiveSizeInBits(); 18881 if (Bits == 0 || Bits > 32) 18882 return false; 18883 return true; 18884 } 18885 18886 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 18887 unsigned Index) const { 18888 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 18889 return false; 18890 18891 return (Index == 0 || Index == ResVT.getVectorNumElements()); 18892 } 18893 18894 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 18895 ARM_MB::MemBOpt Domain) const { 18896 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18897 18898 // First, if the target has no DMB, see what fallback we can use. 18899 if (!Subtarget->hasDataBarrier()) { 18900 // Some ARMv6 cpus can support data barriers with an mcr instruction. 18901 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 18902 // here. 18903 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 18904 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 18905 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 18906 Builder.getInt32(0), Builder.getInt32(7), 18907 Builder.getInt32(10), Builder.getInt32(5)}; 18908 return Builder.CreateCall(MCR, args); 18909 } else { 18910 // Instead of using barriers, atomic accesses on these subtargets use 18911 // libcalls. 18912 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 18913 } 18914 } else { 18915 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 18916 // Only a full system barrier exists in the M-class architectures. 18917 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 18918 Constant *CDomain = Builder.getInt32(Domain); 18919 return Builder.CreateCall(DMB, CDomain); 18920 } 18921 } 18922 18923 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 18924 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 18925 Instruction *Inst, 18926 AtomicOrdering Ord) const { 18927 switch (Ord) { 18928 case AtomicOrdering::NotAtomic: 18929 case AtomicOrdering::Unordered: 18930 llvm_unreachable("Invalid fence: unordered/non-atomic"); 18931 case AtomicOrdering::Monotonic: 18932 case AtomicOrdering::Acquire: 18933 return nullptr; // Nothing to do 18934 case AtomicOrdering::SequentiallyConsistent: 18935 if (!Inst->hasAtomicStore()) 18936 return nullptr; // Nothing to do 18937 LLVM_FALLTHROUGH; 18938 case AtomicOrdering::Release: 18939 case AtomicOrdering::AcquireRelease: 18940 if (Subtarget->preferISHSTBarriers()) 18941 return makeDMB(Builder, ARM_MB::ISHST); 18942 // FIXME: add a comment with a link to documentation justifying this. 18943 else 18944 return makeDMB(Builder, ARM_MB::ISH); 18945 } 18946 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 18947 } 18948 18949 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 18950 Instruction *Inst, 18951 AtomicOrdering Ord) const { 18952 switch (Ord) { 18953 case AtomicOrdering::NotAtomic: 18954 case AtomicOrdering::Unordered: 18955 llvm_unreachable("Invalid fence: unordered/not-atomic"); 18956 case AtomicOrdering::Monotonic: 18957 case AtomicOrdering::Release: 18958 return nullptr; // Nothing to do 18959 case AtomicOrdering::Acquire: 18960 case AtomicOrdering::AcquireRelease: 18961 case AtomicOrdering::SequentiallyConsistent: 18962 return makeDMB(Builder, ARM_MB::ISH); 18963 } 18964 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 18965 } 18966 18967 // Loads and stores less than 64-bits are already atomic; ones above that 18968 // are doomed anyway, so defer to the default libcall and blame the OS when 18969 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18970 // anything for those. 18971 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 18972 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 18973 return (Size == 64) && !Subtarget->isMClass(); 18974 } 18975 18976 // Loads and stores less than 64-bits are already atomic; ones above that 18977 // are doomed anyway, so defer to the default libcall and blame the OS when 18978 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18979 // anything for those. 18980 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 18981 // guarantee, see DDI0406C ARM architecture reference manual, 18982 // sections A8.8.72-74 LDRD) 18983 TargetLowering::AtomicExpansionKind 18984 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 18985 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 18986 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 18987 : AtomicExpansionKind::None; 18988 } 18989 18990 // For the real atomic operations, we have ldrex/strex up to 32 bits, 18991 // and up to 64 bits on the non-M profiles 18992 TargetLowering::AtomicExpansionKind 18993 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18994 if (AI->isFloatingPointOperation()) 18995 return AtomicExpansionKind::CmpXChg; 18996 18997 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18998 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 18999 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 19000 ? AtomicExpansionKind::LLSC 19001 : AtomicExpansionKind::None; 19002 } 19003 19004 // Similar to shouldExpandAtomicRMWInIR, ldrex/strex can be used up to 32 19005 // bits, and up to 64 bits on the non-M profiles. 19006 TargetLowering::AtomicExpansionKind 19007 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 19008 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 19009 // implement cmpxchg without spilling. If the address being exchanged is also 19010 // on the stack and close enough to the spill slot, this can lead to a 19011 // situation where the monitor always gets cleared and the atomic operation 19012 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 19013 unsigned Size = AI->getOperand(1)->getType()->getPrimitiveSizeInBits(); 19014 bool HasAtomicCmpXchg = 19015 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 19016 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg && 19017 Size <= (Subtarget->isMClass() ? 32U : 64U)) 19018 return AtomicExpansionKind::LLSC; 19019 return AtomicExpansionKind::None; 19020 } 19021 19022 bool ARMTargetLowering::shouldInsertFencesForAtomic( 19023 const Instruction *I) const { 19024 return InsertFencesForAtomic; 19025 } 19026 19027 // This has so far only been implemented for MachO. 19028 bool ARMTargetLowering::useLoadStackGuardNode() const { 19029 return Subtarget->isTargetMachO(); 19030 } 19031 19032 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 19033 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 19034 return TargetLowering::insertSSPDeclarations(M); 19035 19036 // MSVC CRT has a global variable holding security cookie. 19037 M.getOrInsertGlobal("__security_cookie", 19038 Type::getInt8PtrTy(M.getContext())); 19039 19040 // MSVC CRT has a function to validate security cookie. 19041 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 19042 "__security_check_cookie", Type::getVoidTy(M.getContext()), 19043 Type::getInt8PtrTy(M.getContext())); 19044 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 19045 F->addAttribute(1, Attribute::AttrKind::InReg); 19046 } 19047 19048 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 19049 // MSVC CRT has a global variable holding security cookie. 19050 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 19051 return M.getGlobalVariable("__security_cookie"); 19052 return TargetLowering::getSDagStackGuard(M); 19053 } 19054 19055 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 19056 // MSVC CRT has a function to validate security cookie. 19057 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 19058 return M.getFunction("__security_check_cookie"); 19059 return TargetLowering::getSSPStackGuardCheck(M); 19060 } 19061 19062 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 19063 unsigned &Cost) const { 19064 // If we do not have NEON, vector types are not natively supported. 19065 if (!Subtarget->hasNEON()) 19066 return false; 19067 19068 // Floating point values and vector values map to the same register file. 19069 // Therefore, although we could do a store extract of a vector type, this is 19070 // better to leave at float as we have more freedom in the addressing mode for 19071 // those. 19072 if (VectorTy->isFPOrFPVectorTy()) 19073 return false; 19074 19075 // If the index is unknown at compile time, this is very expensive to lower 19076 // and it is not possible to combine the store with the extract. 19077 if (!isa<ConstantInt>(Idx)) 19078 return false; 19079 19080 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 19081 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize(); 19082 // We can do a store + vector extract on any vector that fits perfectly in a D 19083 // or Q register. 19084 if (BitWidth == 64 || BitWidth == 128) { 19085 Cost = 0; 19086 return true; 19087 } 19088 return false; 19089 } 19090 19091 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 19092 return Subtarget->hasV6T2Ops(); 19093 } 19094 19095 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 19096 return Subtarget->hasV6T2Ops(); 19097 } 19098 19099 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 19100 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows(); 19101 } 19102 19103 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 19104 AtomicOrdering Ord) const { 19105 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 19106 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 19107 bool IsAcquire = isAcquireOrStronger(Ord); 19108 19109 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 19110 // intrinsic must return {i32, i32} and we have to recombine them into a 19111 // single i64 here. 19112 if (ValTy->getPrimitiveSizeInBits() == 64) { 19113 Intrinsic::ID Int = 19114 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 19115 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 19116 19117 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 19118 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 19119 19120 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 19121 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 19122 if (!Subtarget->isLittle()) 19123 std::swap (Lo, Hi); 19124 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 19125 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 19126 return Builder.CreateOr( 19127 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 19128 } 19129 19130 Type *Tys[] = { Addr->getType() }; 19131 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 19132 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 19133 19134 return Builder.CreateTruncOrBitCast( 19135 Builder.CreateCall(Ldrex, Addr), 19136 cast<PointerType>(Addr->getType())->getElementType()); 19137 } 19138 19139 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 19140 IRBuilder<> &Builder) const { 19141 if (!Subtarget->hasV7Ops()) 19142 return; 19143 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 19144 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 19145 } 19146 19147 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 19148 Value *Addr, 19149 AtomicOrdering Ord) const { 19150 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 19151 bool IsRelease = isReleaseOrStronger(Ord); 19152 19153 // Since the intrinsics must have legal type, the i64 intrinsics take two 19154 // parameters: "i32, i32". We must marshal Val into the appropriate form 19155 // before the call. 19156 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 19157 Intrinsic::ID Int = 19158 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 19159 Function *Strex = Intrinsic::getDeclaration(M, Int); 19160 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 19161 19162 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 19163 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 19164 if (!Subtarget->isLittle()) 19165 std::swap(Lo, Hi); 19166 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 19167 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 19168 } 19169 19170 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 19171 Type *Tys[] = { Addr->getType() }; 19172 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 19173 19174 return Builder.CreateCall( 19175 Strex, {Builder.CreateZExtOrBitCast( 19176 Val, Strex->getFunctionType()->getParamType(0)), 19177 Addr}); 19178 } 19179 19180 19181 bool ARMTargetLowering::alignLoopsWithOptSize() const { 19182 return Subtarget->isMClass(); 19183 } 19184 19185 /// A helper function for determining the number of interleaved accesses we 19186 /// will generate when lowering accesses of the given type. 19187 unsigned 19188 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 19189 const DataLayout &DL) const { 19190 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 19191 } 19192 19193 bool ARMTargetLowering::isLegalInterleavedAccessType( 19194 unsigned Factor, FixedVectorType *VecTy, Align Alignment, 19195 const DataLayout &DL) const { 19196 19197 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 19198 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 19199 19200 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) 19201 return false; 19202 19203 // Ensure the vector doesn't have f16 elements. Even though we could do an 19204 // i16 vldN, we can't hold the f16 vectors and will end up converting via 19205 // f32. 19206 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy()) 19207 return false; 19208 if (Subtarget->hasMVEIntegerOps() && Factor == 3) 19209 return false; 19210 19211 // Ensure the number of vector elements is greater than 1. 19212 if (VecTy->getNumElements() < 2) 19213 return false; 19214 19215 // Ensure the element type is legal. 19216 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 19217 return false; 19218 // And the alignment if high enough under MVE. 19219 if (Subtarget->hasMVEIntegerOps() && Alignment < ElSize / 8) 19220 return false; 19221 19222 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 19223 // 128 will be split into multiple interleaved accesses. 19224 if (Subtarget->hasNEON() && VecSize == 64) 19225 return true; 19226 return VecSize % 128 == 0; 19227 } 19228 19229 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const { 19230 if (Subtarget->hasNEON()) 19231 return 4; 19232 if (Subtarget->hasMVEIntegerOps()) 19233 return MVEMaxSupportedInterleaveFactor; 19234 return TargetLoweringBase::getMaxSupportedInterleaveFactor(); 19235 } 19236 19237 /// Lower an interleaved load into a vldN intrinsic. 19238 /// 19239 /// E.g. Lower an interleaved load (Factor = 2): 19240 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 19241 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 19242 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 19243 /// 19244 /// Into: 19245 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 19246 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 19247 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 19248 bool ARMTargetLowering::lowerInterleavedLoad( 19249 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 19250 ArrayRef<unsigned> Indices, unsigned Factor) const { 19251 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 19252 "Invalid interleave factor"); 19253 assert(!Shuffles.empty() && "Empty shufflevector input"); 19254 assert(Shuffles.size() == Indices.size() && 19255 "Unmatched number of shufflevectors and indices"); 19256 19257 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType()); 19258 Type *EltTy = VecTy->getElementType(); 19259 19260 const DataLayout &DL = LI->getModule()->getDataLayout(); 19261 Align Alignment = LI->getAlign(); 19262 19263 // Skip if we do not have NEON and skip illegal vector types. We can 19264 // "legalize" wide vector types into multiple interleaved accesses as long as 19265 // the vector types are divisible by 128. 19266 if (!isLegalInterleavedAccessType(Factor, VecTy, Alignment, DL)) 19267 return false; 19268 19269 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 19270 19271 // A pointer vector can not be the return type of the ldN intrinsics. Need to 19272 // load integer vectors first and then convert to pointer vectors. 19273 if (EltTy->isPointerTy()) 19274 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy); 19275 19276 IRBuilder<> Builder(LI); 19277 19278 // The base address of the load. 19279 Value *BaseAddr = LI->getPointerOperand(); 19280 19281 if (NumLoads > 1) { 19282 // If we're going to generate more than one load, reset the sub-vector type 19283 // to something legal. 19284 VecTy = FixedVectorType::get(VecTy->getElementType(), 19285 VecTy->getNumElements() / NumLoads); 19286 19287 // We will compute the pointer operand of each load from the original base 19288 // address using GEPs. Cast the base address to a pointer to the scalar 19289 // element type. 19290 BaseAddr = Builder.CreateBitCast( 19291 BaseAddr, 19292 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 19293 } 19294 19295 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 19296 19297 auto createLoadIntrinsic = [&](Value *BaseAddr) { 19298 if (Subtarget->hasNEON()) { 19299 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 19300 Type *Tys[] = {VecTy, Int8Ptr}; 19301 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 19302 Intrinsic::arm_neon_vld3, 19303 Intrinsic::arm_neon_vld4}; 19304 Function *VldnFunc = 19305 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 19306 19307 SmallVector<Value *, 2> Ops; 19308 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 19309 Ops.push_back(Builder.getInt32(LI->getAlignment())); 19310 19311 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 19312 } else { 19313 assert((Factor == 2 || Factor == 4) && 19314 "expected interleave factor of 2 or 4 for MVE"); 19315 Intrinsic::ID LoadInts = 19316 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q; 19317 Type *VecEltTy = 19318 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()); 19319 Type *Tys[] = {VecTy, VecEltTy}; 19320 Function *VldnFunc = 19321 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys); 19322 19323 SmallVector<Value *, 2> Ops; 19324 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy)); 19325 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 19326 } 19327 }; 19328 19329 // Holds sub-vectors extracted from the load intrinsic return values. The 19330 // sub-vectors are associated with the shufflevector instructions they will 19331 // replace. 19332 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 19333 19334 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 19335 // If we're generating more than one load, compute the base address of 19336 // subsequent loads as an offset from the previous. 19337 if (LoadCount > 0) 19338 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr, 19339 VecTy->getNumElements() * Factor); 19340 19341 CallInst *VldN = createLoadIntrinsic(BaseAddr); 19342 19343 // Replace uses of each shufflevector with the corresponding vector loaded 19344 // by ldN. 19345 for (unsigned i = 0; i < Shuffles.size(); i++) { 19346 ShuffleVectorInst *SV = Shuffles[i]; 19347 unsigned Index = Indices[i]; 19348 19349 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 19350 19351 // Convert the integer vector to pointer vector if the element is pointer. 19352 if (EltTy->isPointerTy()) 19353 SubVec = Builder.CreateIntToPtr( 19354 SubVec, 19355 FixedVectorType::get(SV->getType()->getElementType(), VecTy)); 19356 19357 SubVecs[SV].push_back(SubVec); 19358 } 19359 } 19360 19361 // Replace uses of the shufflevector instructions with the sub-vectors 19362 // returned by the load intrinsic. If a shufflevector instruction is 19363 // associated with more than one sub-vector, those sub-vectors will be 19364 // concatenated into a single wide vector. 19365 for (ShuffleVectorInst *SVI : Shuffles) { 19366 auto &SubVec = SubVecs[SVI]; 19367 auto *WideVec = 19368 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 19369 SVI->replaceAllUsesWith(WideVec); 19370 } 19371 19372 return true; 19373 } 19374 19375 /// Lower an interleaved store into a vstN intrinsic. 19376 /// 19377 /// E.g. Lower an interleaved store (Factor = 3): 19378 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 19379 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 19380 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 19381 /// 19382 /// Into: 19383 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 19384 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 19385 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 19386 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 19387 /// 19388 /// Note that the new shufflevectors will be removed and we'll only generate one 19389 /// vst3 instruction in CodeGen. 19390 /// 19391 /// Example for a more general valid mask (Factor 3). Lower: 19392 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 19393 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 19394 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 19395 /// 19396 /// Into: 19397 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 19398 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 19399 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 19400 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 19401 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 19402 ShuffleVectorInst *SVI, 19403 unsigned Factor) const { 19404 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 19405 "Invalid interleave factor"); 19406 19407 auto *VecTy = cast<FixedVectorType>(SVI->getType()); 19408 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 19409 19410 unsigned LaneLen = VecTy->getNumElements() / Factor; 19411 Type *EltTy = VecTy->getElementType(); 19412 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen); 19413 19414 const DataLayout &DL = SI->getModule()->getDataLayout(); 19415 Align Alignment = SI->getAlign(); 19416 19417 // Skip if we do not have NEON and skip illegal vector types. We can 19418 // "legalize" wide vector types into multiple interleaved accesses as long as 19419 // the vector types are divisible by 128. 19420 if (!isLegalInterleavedAccessType(Factor, SubVecTy, Alignment, DL)) 19421 return false; 19422 19423 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 19424 19425 Value *Op0 = SVI->getOperand(0); 19426 Value *Op1 = SVI->getOperand(1); 19427 IRBuilder<> Builder(SI); 19428 19429 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 19430 // vectors to integer vectors. 19431 if (EltTy->isPointerTy()) { 19432 Type *IntTy = DL.getIntPtrType(EltTy); 19433 19434 // Convert to the corresponding integer vector. 19435 auto *IntVecTy = 19436 FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType())); 19437 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 19438 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 19439 19440 SubVecTy = FixedVectorType::get(IntTy, LaneLen); 19441 } 19442 19443 // The base address of the store. 19444 Value *BaseAddr = SI->getPointerOperand(); 19445 19446 if (NumStores > 1) { 19447 // If we're going to generate more than one store, reset the lane length 19448 // and sub-vector type to something legal. 19449 LaneLen /= NumStores; 19450 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen); 19451 19452 // We will compute the pointer operand of each store from the original base 19453 // address using GEPs. Cast the base address to a pointer to the scalar 19454 // element type. 19455 BaseAddr = Builder.CreateBitCast( 19456 BaseAddr, 19457 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 19458 } 19459 19460 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 19461 19462 auto Mask = SVI->getShuffleMask(); 19463 19464 auto createStoreIntrinsic = [&](Value *BaseAddr, 19465 SmallVectorImpl<Value *> &Shuffles) { 19466 if (Subtarget->hasNEON()) { 19467 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 19468 Intrinsic::arm_neon_vst3, 19469 Intrinsic::arm_neon_vst4}; 19470 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 19471 Type *Tys[] = {Int8Ptr, SubVecTy}; 19472 19473 Function *VstNFunc = Intrinsic::getDeclaration( 19474 SI->getModule(), StoreInts[Factor - 2], Tys); 19475 19476 SmallVector<Value *, 6> Ops; 19477 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 19478 append_range(Ops, Shuffles); 19479 Ops.push_back(Builder.getInt32(SI->getAlignment())); 19480 Builder.CreateCall(VstNFunc, Ops); 19481 } else { 19482 assert((Factor == 2 || Factor == 4) && 19483 "expected interleave factor of 2 or 4 for MVE"); 19484 Intrinsic::ID StoreInts = 19485 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q; 19486 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo( 19487 SI->getPointerAddressSpace()); 19488 Type *Tys[] = {EltPtrTy, SubVecTy}; 19489 Function *VstNFunc = 19490 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys); 19491 19492 SmallVector<Value *, 6> Ops; 19493 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy)); 19494 append_range(Ops, Shuffles); 19495 for (unsigned F = 0; F < Factor; F++) { 19496 Ops.push_back(Builder.getInt32(F)); 19497 Builder.CreateCall(VstNFunc, Ops); 19498 Ops.pop_back(); 19499 } 19500 } 19501 }; 19502 19503 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 19504 // If we generating more than one store, we compute the base address of 19505 // subsequent stores as an offset from the previous. 19506 if (StoreCount > 0) 19507 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 19508 BaseAddr, LaneLen * Factor); 19509 19510 SmallVector<Value *, 4> Shuffles; 19511 19512 // Split the shufflevector operands into sub vectors for the new vstN call. 19513 for (unsigned i = 0; i < Factor; i++) { 19514 unsigned IdxI = StoreCount * LaneLen * Factor + i; 19515 if (Mask[IdxI] >= 0) { 19516 Shuffles.push_back(Builder.CreateShuffleVector( 19517 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0))); 19518 } else { 19519 unsigned StartMask = 0; 19520 for (unsigned j = 1; j < LaneLen; j++) { 19521 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 19522 if (Mask[IdxJ * Factor + IdxI] >= 0) { 19523 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 19524 break; 19525 } 19526 } 19527 // Note: If all elements in a chunk are undefs, StartMask=0! 19528 // Note: Filling undef gaps with random elements is ok, since 19529 // those elements were being written anyway (with undefs). 19530 // In the case of all undefs we're defaulting to using elems from 0 19531 // Note: StartMask cannot be negative, it's checked in 19532 // isReInterleaveMask 19533 Shuffles.push_back(Builder.CreateShuffleVector( 19534 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0))); 19535 } 19536 } 19537 19538 createStoreIntrinsic(BaseAddr, Shuffles); 19539 } 19540 return true; 19541 } 19542 19543 enum HABaseType { 19544 HA_UNKNOWN = 0, 19545 HA_FLOAT, 19546 HA_DOUBLE, 19547 HA_VECT64, 19548 HA_VECT128 19549 }; 19550 19551 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 19552 uint64_t &Members) { 19553 if (auto *ST = dyn_cast<StructType>(Ty)) { 19554 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 19555 uint64_t SubMembers = 0; 19556 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 19557 return false; 19558 Members += SubMembers; 19559 } 19560 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 19561 uint64_t SubMembers = 0; 19562 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 19563 return false; 19564 Members += SubMembers * AT->getNumElements(); 19565 } else if (Ty->isFloatTy()) { 19566 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 19567 return false; 19568 Members = 1; 19569 Base = HA_FLOAT; 19570 } else if (Ty->isDoubleTy()) { 19571 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 19572 return false; 19573 Members = 1; 19574 Base = HA_DOUBLE; 19575 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 19576 Members = 1; 19577 switch (Base) { 19578 case HA_FLOAT: 19579 case HA_DOUBLE: 19580 return false; 19581 case HA_VECT64: 19582 return VT->getPrimitiveSizeInBits().getFixedSize() == 64; 19583 case HA_VECT128: 19584 return VT->getPrimitiveSizeInBits().getFixedSize() == 128; 19585 case HA_UNKNOWN: 19586 switch (VT->getPrimitiveSizeInBits().getFixedSize()) { 19587 case 64: 19588 Base = HA_VECT64; 19589 return true; 19590 case 128: 19591 Base = HA_VECT128; 19592 return true; 19593 default: 19594 return false; 19595 } 19596 } 19597 } 19598 19599 return (Members > 0 && Members <= 4); 19600 } 19601 19602 /// Return the correct alignment for the current calling convention. 19603 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 19604 DataLayout DL) const { 19605 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy); 19606 if (!ArgTy->isVectorTy()) 19607 return ABITypeAlign; 19608 19609 // Avoid over-aligning vector parameters. It would require realigning the 19610 // stack and waste space for no real benefit. 19611 return std::min(ABITypeAlign, DL.getStackAlignment()); 19612 } 19613 19614 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 19615 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 19616 /// passing according to AAPCS rules. 19617 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 19618 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 19619 if (getEffectiveCallingConv(CallConv, isVarArg) != 19620 CallingConv::ARM_AAPCS_VFP) 19621 return false; 19622 19623 HABaseType Base = HA_UNKNOWN; 19624 uint64_t Members = 0; 19625 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 19626 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 19627 19628 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 19629 return IsHA || IsIntArray; 19630 } 19631 19632 Register ARMTargetLowering::getExceptionPointerRegister( 19633 const Constant *PersonalityFn) const { 19634 // Platforms which do not use SjLj EH may return values in these registers 19635 // via the personality function. 19636 return Subtarget->useSjLjEH() ? Register() : ARM::R0; 19637 } 19638 19639 Register ARMTargetLowering::getExceptionSelectorRegister( 19640 const Constant *PersonalityFn) const { 19641 // Platforms which do not use SjLj EH may return values in these registers 19642 // via the personality function. 19643 return Subtarget->useSjLjEH() ? Register() : ARM::R1; 19644 } 19645 19646 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 19647 // Update IsSplitCSR in ARMFunctionInfo. 19648 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 19649 AFI->setIsSplitCSR(true); 19650 } 19651 19652 void ARMTargetLowering::insertCopiesSplitCSR( 19653 MachineBasicBlock *Entry, 19654 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 19655 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 19656 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 19657 if (!IStart) 19658 return; 19659 19660 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 19661 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 19662 MachineBasicBlock::iterator MBBI = Entry->begin(); 19663 for (const MCPhysReg *I = IStart; *I; ++I) { 19664 const TargetRegisterClass *RC = nullptr; 19665 if (ARM::GPRRegClass.contains(*I)) 19666 RC = &ARM::GPRRegClass; 19667 else if (ARM::DPRRegClass.contains(*I)) 19668 RC = &ARM::DPRRegClass; 19669 else 19670 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 19671 19672 Register NewVR = MRI->createVirtualRegister(RC); 19673 // Create copy from CSR to a virtual register. 19674 // FIXME: this currently does not emit CFI pseudo-instructions, it works 19675 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 19676 // nounwind. If we want to generalize this later, we may need to emit 19677 // CFI pseudo-instructions. 19678 assert(Entry->getParent()->getFunction().hasFnAttribute( 19679 Attribute::NoUnwind) && 19680 "Function should be nounwind in insertCopiesSplitCSR!"); 19681 Entry->addLiveIn(*I); 19682 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 19683 .addReg(*I); 19684 19685 // Insert the copy-back instructions right before the terminator. 19686 for (auto *Exit : Exits) 19687 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 19688 TII->get(TargetOpcode::COPY), *I) 19689 .addReg(NewVR); 19690 } 19691 } 19692 19693 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 19694 MF.getFrameInfo().computeMaxCallFrameSize(MF); 19695 TargetLoweringBase::finalizeLowering(MF); 19696 } 19697