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 "MCTargetDesc/ARMAddressingModes.h" 25 #include "MCTargetDesc/ARMBaseInfo.h" 26 #include "Utils/ARMBaseInfo.h" 27 #include "llvm/ADT/APFloat.h" 28 #include "llvm/ADT/APInt.h" 29 #include "llvm/ADT/ArrayRef.h" 30 #include "llvm/ADT/BitVector.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringRef.h" 38 #include "llvm/ADT/StringSwitch.h" 39 #include "llvm/ADT/Triple.h" 40 #include "llvm/ADT/Twine.h" 41 #include "llvm/Analysis/VectorUtils.h" 42 #include "llvm/CodeGen/CallingConvLower.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/IntrinsicLowering.h" 45 #include "llvm/CodeGen/MachineBasicBlock.h" 46 #include "llvm/CodeGen/MachineConstantPool.h" 47 #include "llvm/CodeGen/MachineFrameInfo.h" 48 #include "llvm/CodeGen/MachineFunction.h" 49 #include "llvm/CodeGen/MachineInstr.h" 50 #include "llvm/CodeGen/MachineInstrBuilder.h" 51 #include "llvm/CodeGen/MachineJumpTableInfo.h" 52 #include "llvm/CodeGen/MachineMemOperand.h" 53 #include "llvm/CodeGen/MachineOperand.h" 54 #include "llvm/CodeGen/MachineRegisterInfo.h" 55 #include "llvm/CodeGen/RuntimeLibcalls.h" 56 #include "llvm/CodeGen/SelectionDAG.h" 57 #include "llvm/CodeGen/SelectionDAGNodes.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/IR/Attributes.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugLoc.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GlobalAlias.h" 73 #include "llvm/IR/GlobalValue.h" 74 #include "llvm/IR/GlobalVariable.h" 75 #include "llvm/IR/IRBuilder.h" 76 #include "llvm/IR/InlineAsm.h" 77 #include "llvm/IR/Instruction.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/IntrinsicInst.h" 80 #include "llvm/IR/Intrinsics.h" 81 #include "llvm/IR/IntrinsicsARM.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Type.h" 85 #include "llvm/IR/User.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/MC/MCInstrDesc.h" 88 #include "llvm/MC/MCInstrItineraries.h" 89 #include "llvm/MC/MCRegisterInfo.h" 90 #include "llvm/MC/MCSchedule.h" 91 #include "llvm/Support/AtomicOrdering.h" 92 #include "llvm/Support/BranchProbability.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CodeGen.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/ErrorHandling.h" 99 #include "llvm/Support/KnownBits.h" 100 #include "llvm/Support/MachineValueType.h" 101 #include "llvm/Support/MathExtras.h" 102 #include "llvm/Support/raw_ostream.h" 103 #include "llvm/Target/TargetMachine.h" 104 #include "llvm/Target/TargetOptions.h" 105 #include <algorithm> 106 #include <cassert> 107 #include <cstdint> 108 #include <cstdlib> 109 #include <iterator> 110 #include <limits> 111 #include <string> 112 #include <tuple> 113 #include <utility> 114 #include <vector> 115 116 using namespace llvm; 117 using namespace llvm::PatternMatch; 118 119 #define DEBUG_TYPE "arm-isel" 120 121 STATISTIC(NumTailCalls, "Number of tail calls"); 122 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 123 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 124 STATISTIC(NumConstpoolPromoted, 125 "Number of constants with their storage promoted into constant pools"); 126 127 static cl::opt<bool> 128 ARMInterworking("arm-interworking", cl::Hidden, 129 cl::desc("Enable / disable ARM interworking (for debugging only)"), 130 cl::init(true)); 131 132 static cl::opt<bool> EnableConstpoolPromotion( 133 "arm-promote-constant", cl::Hidden, 134 cl::desc("Enable / disable promotion of unnamed_addr constants into " 135 "constant pools"), 136 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 137 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 138 "arm-promote-constant-max-size", cl::Hidden, 139 cl::desc("Maximum size of constant to promote into a constant pool"), 140 cl::init(64)); 141 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 142 "arm-promote-constant-max-total", cl::Hidden, 143 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 144 cl::init(128)); 145 146 static cl::opt<unsigned> 147 MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden, 148 cl::desc("Maximum interleave factor for MVE VLDn to generate."), 149 cl::init(2)); 150 151 // The APCS parameter registers. 152 static const MCPhysReg GPRArgRegs[] = { 153 ARM::R0, ARM::R1, ARM::R2, ARM::R3 154 }; 155 156 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 157 MVT PromotedBitwiseVT) { 158 if (VT != PromotedLdStVT) { 159 setOperationAction(ISD::LOAD, VT, Promote); 160 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 161 162 setOperationAction(ISD::STORE, VT, Promote); 163 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 164 } 165 166 MVT ElemTy = VT.getVectorElementType(); 167 if (ElemTy != MVT::f64) 168 setOperationAction(ISD::SETCC, VT, Custom); 169 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 170 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 171 if (ElemTy == MVT::i32) { 172 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 173 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 174 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 175 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 176 } else { 177 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 178 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 179 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 180 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 181 } 182 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 183 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 184 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 185 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 186 setOperationAction(ISD::SELECT, VT, Expand); 187 setOperationAction(ISD::SELECT_CC, VT, Expand); 188 setOperationAction(ISD::VSELECT, VT, Expand); 189 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 190 if (VT.isInteger()) { 191 setOperationAction(ISD::SHL, VT, Custom); 192 setOperationAction(ISD::SRA, VT, Custom); 193 setOperationAction(ISD::SRL, VT, Custom); 194 } 195 196 // Promote all bit-wise operations. 197 if (VT.isInteger() && VT != PromotedBitwiseVT) { 198 setOperationAction(ISD::AND, VT, Promote); 199 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 200 setOperationAction(ISD::OR, VT, Promote); 201 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 202 setOperationAction(ISD::XOR, VT, Promote); 203 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 204 } 205 206 // Neon does not support vector divide/remainder operations. 207 setOperationAction(ISD::SDIV, VT, Expand); 208 setOperationAction(ISD::UDIV, VT, Expand); 209 setOperationAction(ISD::FDIV, VT, Expand); 210 setOperationAction(ISD::SREM, VT, Expand); 211 setOperationAction(ISD::UREM, VT, Expand); 212 setOperationAction(ISD::FREM, VT, Expand); 213 214 if (!VT.isFloatingPoint() && 215 VT != MVT::v2i64 && VT != MVT::v1i64) 216 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 217 setOperationAction(Opcode, VT, Legal); 218 if (!VT.isFloatingPoint()) 219 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}) 220 setOperationAction(Opcode, VT, Legal); 221 } 222 223 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 224 addRegisterClass(VT, &ARM::DPRRegClass); 225 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 226 } 227 228 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 229 addRegisterClass(VT, &ARM::DPairRegClass); 230 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 231 } 232 233 void ARMTargetLowering::setAllExpand(MVT VT) { 234 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc) 235 setOperationAction(Opc, VT, Expand); 236 237 // We support these really simple operations even on types where all 238 // the actual arithmetic has to be broken down into simpler 239 // operations or turned into library calls. 240 setOperationAction(ISD::BITCAST, VT, Legal); 241 setOperationAction(ISD::LOAD, VT, Legal); 242 setOperationAction(ISD::STORE, VT, Legal); 243 setOperationAction(ISD::UNDEF, VT, Legal); 244 } 245 246 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To, 247 LegalizeAction Action) { 248 setLoadExtAction(ISD::EXTLOAD, From, To, Action); 249 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action); 250 setLoadExtAction(ISD::SEXTLOAD, From, To, Action); 251 } 252 253 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) { 254 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 }; 255 256 for (auto VT : IntTypes) { 257 addRegisterClass(VT, &ARM::MQPRRegClass); 258 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 259 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 260 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 261 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 262 setOperationAction(ISD::SHL, VT, Custom); 263 setOperationAction(ISD::SRA, VT, Custom); 264 setOperationAction(ISD::SRL, VT, Custom); 265 setOperationAction(ISD::SMIN, VT, Legal); 266 setOperationAction(ISD::SMAX, VT, Legal); 267 setOperationAction(ISD::UMIN, VT, Legal); 268 setOperationAction(ISD::UMAX, VT, Legal); 269 setOperationAction(ISD::ABS, VT, Legal); 270 setOperationAction(ISD::SETCC, VT, Custom); 271 setOperationAction(ISD::MLOAD, VT, Custom); 272 setOperationAction(ISD::MSTORE, VT, Legal); 273 setOperationAction(ISD::CTLZ, VT, Legal); 274 setOperationAction(ISD::CTTZ, VT, Custom); 275 setOperationAction(ISD::BITREVERSE, VT, Legal); 276 setOperationAction(ISD::BSWAP, VT, Legal); 277 setOperationAction(ISD::SADDSAT, VT, Legal); 278 setOperationAction(ISD::UADDSAT, VT, Legal); 279 setOperationAction(ISD::SSUBSAT, VT, Legal); 280 setOperationAction(ISD::USUBSAT, VT, Legal); 281 282 // No native support for these. 283 setOperationAction(ISD::UDIV, VT, Expand); 284 setOperationAction(ISD::SDIV, VT, Expand); 285 setOperationAction(ISD::UREM, VT, Expand); 286 setOperationAction(ISD::SREM, VT, Expand); 287 setOperationAction(ISD::CTPOP, VT, Expand); 288 289 // Vector reductions 290 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal); 291 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal); 292 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal); 293 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal); 294 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal); 295 296 if (!HasMVEFP) { 297 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 298 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 299 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 300 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 301 } 302 303 // Pre and Post inc are supported on loads and stores 304 for (unsigned im = (unsigned)ISD::PRE_INC; 305 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 306 setIndexedLoadAction(im, VT, Legal); 307 setIndexedStoreAction(im, VT, Legal); 308 setIndexedMaskedLoadAction(im, VT, Legal); 309 setIndexedMaskedStoreAction(im, VT, Legal); 310 } 311 } 312 313 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 314 for (auto VT : FloatTypes) { 315 addRegisterClass(VT, &ARM::MQPRRegClass); 316 if (!HasMVEFP) 317 setAllExpand(VT); 318 319 // These are legal or custom whether we have MVE.fp or not 320 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 321 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 322 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 324 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 325 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 326 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 327 setOperationAction(ISD::SETCC, VT, Custom); 328 setOperationAction(ISD::MLOAD, VT, Custom); 329 setOperationAction(ISD::MSTORE, VT, Legal); 330 331 // Pre and Post inc are supported on loads and stores 332 for (unsigned im = (unsigned)ISD::PRE_INC; 333 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 334 setIndexedLoadAction(im, VT, Legal); 335 setIndexedStoreAction(im, VT, Legal); 336 setIndexedMaskedLoadAction(im, VT, Legal); 337 setIndexedMaskedStoreAction(im, VT, Legal); 338 } 339 340 if (HasMVEFP) { 341 setOperationAction(ISD::FMINNUM, VT, Legal); 342 setOperationAction(ISD::FMAXNUM, VT, Legal); 343 setOperationAction(ISD::FROUND, VT, Legal); 344 345 // No native support for these. 346 setOperationAction(ISD::FDIV, VT, Expand); 347 setOperationAction(ISD::FREM, VT, Expand); 348 setOperationAction(ISD::FSQRT, VT, Expand); 349 setOperationAction(ISD::FSIN, VT, Expand); 350 setOperationAction(ISD::FCOS, VT, Expand); 351 setOperationAction(ISD::FPOW, VT, Expand); 352 setOperationAction(ISD::FLOG, VT, Expand); 353 setOperationAction(ISD::FLOG2, VT, Expand); 354 setOperationAction(ISD::FLOG10, VT, Expand); 355 setOperationAction(ISD::FEXP, VT, Expand); 356 setOperationAction(ISD::FEXP2, VT, Expand); 357 setOperationAction(ISD::FNEARBYINT, VT, Expand); 358 } 359 } 360 361 // We 'support' these types up to bitcast/load/store level, regardless of 362 // MVE integer-only / float support. Only doing FP data processing on the FP 363 // vector types is inhibited at integer-only level. 364 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 365 for (auto VT : LongTypes) { 366 addRegisterClass(VT, &ARM::MQPRRegClass); 367 setAllExpand(VT); 368 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 369 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 370 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 371 } 372 // We can do bitwise operations on v2i64 vectors 373 setOperationAction(ISD::AND, MVT::v2i64, Legal); 374 setOperationAction(ISD::OR, MVT::v2i64, Legal); 375 setOperationAction(ISD::XOR, MVT::v2i64, Legal); 376 377 // It is legal to extload from v4i8 to v4i16 or v4i32. 378 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 379 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 380 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 381 382 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16. 383 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 384 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 385 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 386 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Legal); 387 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal); 388 389 // Some truncating stores are legal too. 390 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 391 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 392 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 393 394 // Pre and Post inc on these are legal, given the correct extends 395 for (unsigned im = (unsigned)ISD::PRE_INC; 396 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 397 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) { 398 setIndexedLoadAction(im, VT, Legal); 399 setIndexedStoreAction(im, VT, Legal); 400 setIndexedMaskedLoadAction(im, VT, Legal); 401 setIndexedMaskedStoreAction(im, VT, Legal); 402 } 403 } 404 405 // Predicate types 406 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1}; 407 for (auto VT : pTypes) { 408 addRegisterClass(VT, &ARM::VCCRRegClass); 409 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 410 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 411 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 412 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 413 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 414 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 415 setOperationAction(ISD::SETCC, VT, Custom); 416 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 417 setOperationAction(ISD::LOAD, VT, Custom); 418 setOperationAction(ISD::STORE, VT, Custom); 419 } 420 } 421 422 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 423 const ARMSubtarget &STI) 424 : TargetLowering(TM), Subtarget(&STI) { 425 RegInfo = Subtarget->getRegisterInfo(); 426 Itins = Subtarget->getInstrItineraryData(); 427 428 setBooleanContents(ZeroOrOneBooleanContent); 429 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 430 431 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 432 !Subtarget->isTargetWatchOS()) { 433 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 434 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 435 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 436 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 437 : CallingConv::ARM_AAPCS); 438 } 439 440 if (Subtarget->isTargetMachO()) { 441 // Uses VFP for Thumb libfuncs if available. 442 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 443 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 444 static const struct { 445 const RTLIB::Libcall Op; 446 const char * const Name; 447 const ISD::CondCode Cond; 448 } LibraryCalls[] = { 449 // Single-precision floating-point arithmetic. 450 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 451 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 452 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 453 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 454 455 // Double-precision floating-point arithmetic. 456 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 457 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 458 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 459 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 460 461 // Single-precision comparisons. 462 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 463 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 464 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 465 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 466 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 467 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 468 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 469 470 // Double-precision comparisons. 471 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 472 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 473 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 474 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 475 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 476 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 477 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 478 479 // Floating-point to integer conversions. 480 // i64 conversions are done via library routines even when generating VFP 481 // instructions, so use the same ones. 482 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 483 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 484 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 485 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 486 487 // Conversions between floating types. 488 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 489 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 490 491 // Integer to floating-point conversions. 492 // i64 conversions are done via library routines even when generating VFP 493 // instructions, so use the same ones. 494 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 495 // e.g., __floatunsidf vs. __floatunssidfvfp. 496 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 497 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 498 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 499 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 500 }; 501 502 for (const auto &LC : LibraryCalls) { 503 setLibcallName(LC.Op, LC.Name); 504 if (LC.Cond != ISD::SETCC_INVALID) 505 setCmpLibcallCC(LC.Op, LC.Cond); 506 } 507 } 508 } 509 510 // These libcalls are not available in 32-bit. 511 setLibcallName(RTLIB::SHL_I128, nullptr); 512 setLibcallName(RTLIB::SRL_I128, nullptr); 513 setLibcallName(RTLIB::SRA_I128, nullptr); 514 515 // RTLIB 516 if (Subtarget->isAAPCS_ABI() && 517 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 518 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 519 static const struct { 520 const RTLIB::Libcall Op; 521 const char * const Name; 522 const CallingConv::ID CC; 523 const ISD::CondCode Cond; 524 } LibraryCalls[] = { 525 // Double-precision floating-point arithmetic helper functions 526 // RTABI chapter 4.1.2, Table 2 527 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 528 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 529 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 530 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 531 532 // Double-precision floating-point comparison helper functions 533 // RTABI chapter 4.1.2, Table 3 534 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 535 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 536 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 537 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 538 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 539 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 540 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 541 542 // Single-precision floating-point arithmetic helper functions 543 // RTABI chapter 4.1.2, Table 4 544 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 545 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 546 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 547 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 548 549 // Single-precision floating-point comparison helper functions 550 // RTABI chapter 4.1.2, Table 5 551 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 552 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 553 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 554 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 555 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 556 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 557 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 558 559 // Floating-point to integer conversions. 560 // RTABI chapter 4.1.2, Table 6 561 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 562 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 563 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 564 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 565 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 566 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 567 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 568 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 569 570 // Conversions between floating types. 571 // RTABI chapter 4.1.2, Table 7 572 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 573 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 574 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 575 576 // Integer to floating-point conversions. 577 // RTABI chapter 4.1.2, Table 8 578 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 579 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 580 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 581 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 582 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 583 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 584 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 585 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 586 587 // Long long helper functions 588 // RTABI chapter 4.2, Table 9 589 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 590 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 591 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 592 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 593 594 // Integer division functions 595 // RTABI chapter 4.3.1 596 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 597 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 598 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 599 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 600 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 601 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 602 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 603 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 604 }; 605 606 for (const auto &LC : LibraryCalls) { 607 setLibcallName(LC.Op, LC.Name); 608 setLibcallCallingConv(LC.Op, LC.CC); 609 if (LC.Cond != ISD::SETCC_INVALID) 610 setCmpLibcallCC(LC.Op, LC.Cond); 611 } 612 613 // EABI dependent RTLIB 614 if (TM.Options.EABIVersion == EABI::EABI4 || 615 TM.Options.EABIVersion == EABI::EABI5) { 616 static const struct { 617 const RTLIB::Libcall Op; 618 const char *const Name; 619 const CallingConv::ID CC; 620 const ISD::CondCode Cond; 621 } MemOpsLibraryCalls[] = { 622 // Memory operations 623 // RTABI chapter 4.3.4 624 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 625 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 626 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 627 }; 628 629 for (const auto &LC : MemOpsLibraryCalls) { 630 setLibcallName(LC.Op, LC.Name); 631 setLibcallCallingConv(LC.Op, LC.CC); 632 if (LC.Cond != ISD::SETCC_INVALID) 633 setCmpLibcallCC(LC.Op, LC.Cond); 634 } 635 } 636 } 637 638 if (Subtarget->isTargetWindows()) { 639 static const struct { 640 const RTLIB::Libcall Op; 641 const char * const Name; 642 const CallingConv::ID CC; 643 } LibraryCalls[] = { 644 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 645 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 646 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 647 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 648 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 649 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 650 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 651 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 652 }; 653 654 for (const auto &LC : LibraryCalls) { 655 setLibcallName(LC.Op, LC.Name); 656 setLibcallCallingConv(LC.Op, LC.CC); 657 } 658 } 659 660 // Use divmod compiler-rt calls for iOS 5.0 and later. 661 if (Subtarget->isTargetMachO() && 662 !(Subtarget->isTargetIOS() && 663 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 664 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 665 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 666 } 667 668 // The half <-> float conversion functions are always soft-float on 669 // non-watchos platforms, but are needed for some targets which use a 670 // hard-float calling convention by default. 671 if (!Subtarget->isTargetWatchABI()) { 672 if (Subtarget->isAAPCS_ABI()) { 673 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 674 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 675 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 676 } else { 677 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 678 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 679 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 680 } 681 } 682 683 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 684 // a __gnu_ prefix (which is the default). 685 if (Subtarget->isTargetAEABI()) { 686 static const struct { 687 const RTLIB::Libcall Op; 688 const char * const Name; 689 const CallingConv::ID CC; 690 } LibraryCalls[] = { 691 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 692 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 693 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 694 }; 695 696 for (const auto &LC : LibraryCalls) { 697 setLibcallName(LC.Op, LC.Name); 698 setLibcallCallingConv(LC.Op, LC.CC); 699 } 700 } 701 702 if (Subtarget->isThumb1Only()) 703 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 704 else 705 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 706 707 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 708 Subtarget->hasFPRegs()) { 709 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 710 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 711 if (!Subtarget->hasVFP2Base()) 712 setAllExpand(MVT::f32); 713 if (!Subtarget->hasFP64()) 714 setAllExpand(MVT::f64); 715 } 716 717 if (Subtarget->hasFullFP16()) { 718 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 719 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 720 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 721 722 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 723 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 724 } 725 726 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 727 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 728 setTruncStoreAction(VT, InnerVT, Expand); 729 addAllExtLoads(VT, InnerVT, Expand); 730 } 731 732 setOperationAction(ISD::MULHS, VT, Expand); 733 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 734 setOperationAction(ISD::MULHU, VT, Expand); 735 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 736 737 setOperationAction(ISD::BSWAP, VT, Expand); 738 } 739 740 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 741 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 742 743 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 744 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 745 746 if (Subtarget->hasMVEIntegerOps()) 747 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 748 749 // Combine low-overhead loop intrinsics so that we can lower i1 types. 750 if (Subtarget->hasLOB()) { 751 setTargetDAGCombine(ISD::BRCOND); 752 setTargetDAGCombine(ISD::BR_CC); 753 } 754 755 if (Subtarget->hasNEON()) { 756 addDRTypeForNEON(MVT::v2f32); 757 addDRTypeForNEON(MVT::v8i8); 758 addDRTypeForNEON(MVT::v4i16); 759 addDRTypeForNEON(MVT::v2i32); 760 addDRTypeForNEON(MVT::v1i64); 761 762 addQRTypeForNEON(MVT::v4f32); 763 addQRTypeForNEON(MVT::v2f64); 764 addQRTypeForNEON(MVT::v16i8); 765 addQRTypeForNEON(MVT::v8i16); 766 addQRTypeForNEON(MVT::v4i32); 767 addQRTypeForNEON(MVT::v2i64); 768 769 if (Subtarget->hasFullFP16()) { 770 addQRTypeForNEON(MVT::v8f16); 771 addDRTypeForNEON(MVT::v4f16); 772 } 773 } 774 775 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 776 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 777 // none of Neon, MVE or VFP supports any arithmetic operations on it. 778 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 779 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 780 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 781 // FIXME: Code duplication: FDIV and FREM are expanded always, see 782 // ARMTargetLowering::addTypeForNEON method for details. 783 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 784 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 785 // FIXME: Create unittest. 786 // In another words, find a way when "copysign" appears in DAG with vector 787 // operands. 788 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 789 // FIXME: Code duplication: SETCC has custom operation action, see 790 // ARMTargetLowering::addTypeForNEON method for details. 791 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 792 // FIXME: Create unittest for FNEG and for FABS. 793 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 794 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 795 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 796 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 797 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 798 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 799 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 800 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 801 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 802 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 803 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 804 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 805 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 806 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 807 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 808 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 809 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 810 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 811 } 812 813 if (Subtarget->hasNEON()) { 814 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 815 // supported for v4f32. 816 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 817 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 818 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 819 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 820 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 821 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 822 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 823 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 824 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 825 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 826 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 827 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 828 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 829 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 830 831 // Mark v2f32 intrinsics. 832 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 833 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 834 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 835 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 836 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 837 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 838 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 839 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 840 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 841 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 842 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 843 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 844 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 845 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 846 847 // Neon does not support some operations on v1i64 and v2i64 types. 848 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 849 // Custom handling for some quad-vector types to detect VMULL. 850 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 851 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 852 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 853 // Custom handling for some vector types to avoid expensive expansions 854 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 855 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 856 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 857 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 858 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 859 // a destination type that is wider than the source, and nor does 860 // it have a FP_TO_[SU]INT instruction with a narrower destination than 861 // source. 862 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 863 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 864 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 865 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 866 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 867 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 868 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 869 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 870 871 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 872 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 873 874 // NEON does not have single instruction CTPOP for vectors with element 875 // types wider than 8-bits. However, custom lowering can leverage the 876 // v8i8/v16i8 vcnt instruction. 877 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 878 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 879 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 880 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 881 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 882 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 883 884 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 885 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 886 887 // NEON does not have single instruction CTTZ for vectors. 888 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 889 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 890 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 891 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 892 893 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 894 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 895 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 896 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 897 898 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 899 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 900 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 901 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 902 903 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 904 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 905 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 906 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 907 908 // NEON only has FMA instructions as of VFP4. 909 if (!Subtarget->hasVFP4Base()) { 910 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 911 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 912 } 913 914 setTargetDAGCombine(ISD::SHL); 915 setTargetDAGCombine(ISD::SRL); 916 setTargetDAGCombine(ISD::SRA); 917 setTargetDAGCombine(ISD::FP_TO_SINT); 918 setTargetDAGCombine(ISD::FP_TO_UINT); 919 setTargetDAGCombine(ISD::FDIV); 920 setTargetDAGCombine(ISD::LOAD); 921 922 // It is legal to extload from v4i8 to v4i16 or v4i32. 923 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 924 MVT::v2i32}) { 925 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 926 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 927 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 928 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 929 } 930 } 931 } 932 933 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 934 setTargetDAGCombine(ISD::BUILD_VECTOR); 935 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 936 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 937 setTargetDAGCombine(ISD::STORE); 938 setTargetDAGCombine(ISD::SIGN_EXTEND); 939 setTargetDAGCombine(ISD::ZERO_EXTEND); 940 setTargetDAGCombine(ISD::ANY_EXTEND); 941 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 942 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 943 setTargetDAGCombine(ISD::INTRINSIC_VOID); 944 setTargetDAGCombine(ISD::VECREDUCE_ADD); 945 setTargetDAGCombine(ISD::ADD); 946 setTargetDAGCombine(ISD::BITCAST); 947 } 948 949 if (!Subtarget->hasFP64()) { 950 // When targeting a floating-point unit with only single-precision 951 // operations, f64 is legal for the few double-precision instructions which 952 // are present However, no double-precision operations other than moves, 953 // loads and stores are provided by the hardware. 954 setOperationAction(ISD::FADD, MVT::f64, Expand); 955 setOperationAction(ISD::FSUB, MVT::f64, Expand); 956 setOperationAction(ISD::FMUL, MVT::f64, Expand); 957 setOperationAction(ISD::FMA, MVT::f64, Expand); 958 setOperationAction(ISD::FDIV, MVT::f64, Expand); 959 setOperationAction(ISD::FREM, MVT::f64, Expand); 960 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 961 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 962 setOperationAction(ISD::FNEG, MVT::f64, Expand); 963 setOperationAction(ISD::FABS, MVT::f64, Expand); 964 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 965 setOperationAction(ISD::FSIN, MVT::f64, Expand); 966 setOperationAction(ISD::FCOS, MVT::f64, Expand); 967 setOperationAction(ISD::FPOW, MVT::f64, Expand); 968 setOperationAction(ISD::FLOG, MVT::f64, Expand); 969 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 970 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 971 setOperationAction(ISD::FEXP, MVT::f64, Expand); 972 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 973 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 974 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 975 setOperationAction(ISD::FRINT, MVT::f64, Expand); 976 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 977 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 978 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 979 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 980 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 981 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 982 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 983 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 984 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 985 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 986 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 987 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom); 988 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom); 989 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 990 } 991 992 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 993 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 994 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom); 995 if (Subtarget->hasFullFP16()) { 996 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 997 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom); 998 } 999 } 1000 1001 if (!Subtarget->hasFP16()) { 1002 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 1003 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom); 1004 } 1005 1006 computeRegisterProperties(Subtarget->getRegisterInfo()); 1007 1008 // ARM does not have floating-point extending loads. 1009 for (MVT VT : MVT::fp_valuetypes()) { 1010 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 1011 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 1012 } 1013 1014 // ... or truncating stores 1015 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 1016 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 1017 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 1018 1019 // ARM does not have i1 sign extending load. 1020 for (MVT VT : MVT::integer_valuetypes()) 1021 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 1022 1023 // ARM supports all 4 flavors of integer indexed load / store. 1024 if (!Subtarget->isThumb1Only()) { 1025 for (unsigned im = (unsigned)ISD::PRE_INC; 1026 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1027 setIndexedLoadAction(im, MVT::i1, Legal); 1028 setIndexedLoadAction(im, MVT::i8, Legal); 1029 setIndexedLoadAction(im, MVT::i16, Legal); 1030 setIndexedLoadAction(im, MVT::i32, Legal); 1031 setIndexedStoreAction(im, MVT::i1, Legal); 1032 setIndexedStoreAction(im, MVT::i8, Legal); 1033 setIndexedStoreAction(im, MVT::i16, Legal); 1034 setIndexedStoreAction(im, MVT::i32, Legal); 1035 } 1036 } else { 1037 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 1038 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 1039 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 1040 } 1041 1042 setOperationAction(ISD::SADDO, MVT::i32, Custom); 1043 setOperationAction(ISD::UADDO, MVT::i32, Custom); 1044 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 1045 setOperationAction(ISD::USUBO, MVT::i32, Custom); 1046 1047 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 1048 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 1049 if (Subtarget->hasDSP()) { 1050 setOperationAction(ISD::SADDSAT, MVT::i8, Custom); 1051 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom); 1052 setOperationAction(ISD::SADDSAT, MVT::i16, Custom); 1053 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom); 1054 } 1055 if (Subtarget->hasBaseDSP()) { 1056 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 1057 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 1058 } 1059 1060 // i64 operation support. 1061 setOperationAction(ISD::MUL, MVT::i64, Expand); 1062 setOperationAction(ISD::MULHU, MVT::i32, Expand); 1063 if (Subtarget->isThumb1Only()) { 1064 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 1065 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 1066 } 1067 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 1068 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 1069 setOperationAction(ISD::MULHS, MVT::i32, Expand); 1070 1071 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 1072 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 1073 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 1074 setOperationAction(ISD::SRL, MVT::i64, Custom); 1075 setOperationAction(ISD::SRA, MVT::i64, Custom); 1076 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 1077 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 1078 setOperationAction(ISD::LOAD, MVT::i64, Custom); 1079 setOperationAction(ISD::STORE, MVT::i64, Custom); 1080 1081 // MVE lowers 64 bit shifts to lsll and lsrl 1082 // assuming that ISD::SRL and SRA of i64 are already marked custom 1083 if (Subtarget->hasMVEIntegerOps()) 1084 setOperationAction(ISD::SHL, MVT::i64, Custom); 1085 1086 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1087 if (Subtarget->isThumb1Only()) { 1088 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1089 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1090 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1091 } 1092 1093 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1094 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1095 1096 // ARM does not have ROTL. 1097 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1098 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1099 setOperationAction(ISD::ROTL, VT, Expand); 1100 setOperationAction(ISD::ROTR, VT, Expand); 1101 } 1102 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1103 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1104 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1105 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1106 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1107 } 1108 1109 // @llvm.readcyclecounter requires the Performance Monitors extension. 1110 // Default to the 0 expansion on unsupported platforms. 1111 // FIXME: Technically there are older ARM CPUs that have 1112 // implementation-specific ways of obtaining this information. 1113 if (Subtarget->hasPerfMon()) 1114 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1115 1116 // Only ARMv6 has BSWAP. 1117 if (!Subtarget->hasV6Ops()) 1118 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1119 1120 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1121 : Subtarget->hasDivideInARMMode(); 1122 if (!hasDivide) { 1123 // These are expanded into libcalls if the cpu doesn't have HW divider. 1124 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1125 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1126 } 1127 1128 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1129 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1130 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1131 1132 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1133 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1134 } 1135 1136 setOperationAction(ISD::SREM, MVT::i32, Expand); 1137 setOperationAction(ISD::UREM, MVT::i32, Expand); 1138 1139 // Register based DivRem for AEABI (RTABI 4.2) 1140 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1141 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1142 Subtarget->isTargetWindows()) { 1143 setOperationAction(ISD::SREM, MVT::i64, Custom); 1144 setOperationAction(ISD::UREM, MVT::i64, Custom); 1145 HasStandaloneRem = false; 1146 1147 if (Subtarget->isTargetWindows()) { 1148 const struct { 1149 const RTLIB::Libcall Op; 1150 const char * const Name; 1151 const CallingConv::ID CC; 1152 } LibraryCalls[] = { 1153 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1154 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1155 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1156 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1157 1158 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1159 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1160 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1161 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1162 }; 1163 1164 for (const auto &LC : LibraryCalls) { 1165 setLibcallName(LC.Op, LC.Name); 1166 setLibcallCallingConv(LC.Op, LC.CC); 1167 } 1168 } else { 1169 const struct { 1170 const RTLIB::Libcall Op; 1171 const char * const Name; 1172 const CallingConv::ID CC; 1173 } LibraryCalls[] = { 1174 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1175 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1176 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1177 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1178 1179 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1180 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1181 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1182 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1183 }; 1184 1185 for (const auto &LC : LibraryCalls) { 1186 setLibcallName(LC.Op, LC.Name); 1187 setLibcallCallingConv(LC.Op, LC.CC); 1188 } 1189 } 1190 1191 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1192 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1193 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1194 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1195 } else { 1196 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1197 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1198 } 1199 1200 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 1201 // MSVCRT doesn't have powi; fall back to pow 1202 setLibcallName(RTLIB::POWI_F32, nullptr); 1203 setLibcallName(RTLIB::POWI_F64, nullptr); 1204 } 1205 1206 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1207 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1208 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1209 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1210 1211 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1212 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1213 1214 // Use the default implementation. 1215 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1216 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1217 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1218 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1219 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1220 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1221 1222 if (Subtarget->isTargetWindows()) 1223 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1224 else 1225 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1226 1227 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1228 // the default expansion. 1229 InsertFencesForAtomic = false; 1230 if (Subtarget->hasAnyDataBarrier() && 1231 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1232 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1233 // to ldrex/strex loops already. 1234 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1235 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1236 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1237 1238 // On v8, we have particularly efficient implementations of atomic fences 1239 // if they can be combined with nearby atomic loads and stores. 1240 if (!Subtarget->hasAcquireRelease() || 1241 getTargetMachine().getOptLevel() == 0) { 1242 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1243 InsertFencesForAtomic = true; 1244 } 1245 } else { 1246 // If there's anything we can use as a barrier, go through custom lowering 1247 // for ATOMIC_FENCE. 1248 // If target has DMB in thumb, Fences can be inserted. 1249 if (Subtarget->hasDataBarrier()) 1250 InsertFencesForAtomic = true; 1251 1252 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1253 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1254 1255 // Set them all for expansion, which will force libcalls. 1256 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1257 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1258 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1259 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1260 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1261 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1262 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1263 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1264 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1265 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1266 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1267 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1268 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1269 // Unordered/Monotonic case. 1270 if (!InsertFencesForAtomic) { 1271 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1272 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1273 } 1274 } 1275 1276 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1277 1278 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1279 if (!Subtarget->hasV6Ops()) { 1280 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1281 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1282 } 1283 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1284 1285 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1286 !Subtarget->isThumb1Only()) { 1287 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1288 // iff target supports vfp2. 1289 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1290 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1291 } 1292 1293 // We want to custom lower some of our intrinsics. 1294 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1295 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1296 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1297 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1298 if (Subtarget->useSjLjEH()) 1299 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1300 1301 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1302 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1303 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1304 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1305 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1306 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1307 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1308 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1309 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1310 if (Subtarget->hasFullFP16()) { 1311 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1312 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1313 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1314 } 1315 1316 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1317 1318 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1319 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1320 if (Subtarget->hasFullFP16()) 1321 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1322 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1323 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1324 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1325 1326 // We don't support sin/cos/fmod/copysign/pow 1327 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1328 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1329 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1330 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1331 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1332 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1333 setOperationAction(ISD::FREM, MVT::f64, Expand); 1334 setOperationAction(ISD::FREM, MVT::f32, Expand); 1335 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1336 !Subtarget->isThumb1Only()) { 1337 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1338 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1339 } 1340 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1341 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1342 1343 if (!Subtarget->hasVFP4Base()) { 1344 setOperationAction(ISD::FMA, MVT::f64, Expand); 1345 setOperationAction(ISD::FMA, MVT::f32, Expand); 1346 } 1347 1348 // Various VFP goodness 1349 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1350 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1351 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1352 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1353 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1354 } 1355 1356 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1357 if (!Subtarget->hasFP16()) { 1358 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1359 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1360 } 1361 1362 // Strict floating-point comparisons need custom lowering. 1363 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 1364 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 1365 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 1366 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 1367 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 1368 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 1369 } 1370 1371 // Use __sincos_stret if available. 1372 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1373 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1374 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1375 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1376 } 1377 1378 // FP-ARMv8 implements a lot of rounding-like FP operations. 1379 if (Subtarget->hasFPARMv8Base()) { 1380 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1381 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1382 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1383 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1384 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1385 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1386 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1387 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1388 if (Subtarget->hasNEON()) { 1389 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1390 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1391 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1392 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1393 } 1394 1395 if (Subtarget->hasFP64()) { 1396 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1397 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1398 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1399 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1400 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1401 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1402 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1403 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1404 } 1405 } 1406 1407 // FP16 often need to be promoted to call lib functions 1408 if (Subtarget->hasFullFP16()) { 1409 setOperationAction(ISD::FREM, MVT::f16, Promote); 1410 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1411 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1412 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1413 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1414 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1415 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1416 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1417 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1418 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1419 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1420 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1421 1422 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1423 } 1424 1425 if (Subtarget->hasNEON()) { 1426 // vmin and vmax aren't available in a scalar form, so we can use 1427 // a NEON instruction with an undef lane instead. This has a performance 1428 // penalty on some cores, so we don't do this unless we have been 1429 // asked to by the core tuning model. 1430 if (Subtarget->useNEONForSinglePrecisionFP()) { 1431 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1432 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1433 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1434 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1435 } 1436 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1437 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1438 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1439 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1440 1441 if (Subtarget->hasFullFP16()) { 1442 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1443 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1444 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1445 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1446 1447 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1448 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1449 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1450 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1451 } 1452 } 1453 1454 // We have target-specific dag combine patterns for the following nodes: 1455 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1456 setTargetDAGCombine(ISD::ADD); 1457 setTargetDAGCombine(ISD::SUB); 1458 setTargetDAGCombine(ISD::MUL); 1459 setTargetDAGCombine(ISD::AND); 1460 setTargetDAGCombine(ISD::OR); 1461 setTargetDAGCombine(ISD::XOR); 1462 1463 if (Subtarget->hasV6Ops()) 1464 setTargetDAGCombine(ISD::SRL); 1465 if (Subtarget->isThumb1Only()) 1466 setTargetDAGCombine(ISD::SHL); 1467 1468 setStackPointerRegisterToSaveRestore(ARM::SP); 1469 1470 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1471 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1472 setSchedulingPreference(Sched::RegPressure); 1473 else 1474 setSchedulingPreference(Sched::Hybrid); 1475 1476 //// temporary - rewrite interface to use type 1477 MaxStoresPerMemset = 8; 1478 MaxStoresPerMemsetOptSize = 4; 1479 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1480 MaxStoresPerMemcpyOptSize = 2; 1481 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1482 MaxStoresPerMemmoveOptSize = 2; 1483 1484 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1485 // are at least 4 bytes aligned. 1486 setMinStackArgumentAlignment(Align(4)); 1487 1488 // Prefer likely predicted branches to selects on out-of-order cores. 1489 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1490 1491 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment())); 1492 1493 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4)); 1494 1495 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1496 setTargetDAGCombine(ISD::ABS); 1497 } 1498 1499 bool ARMTargetLowering::useSoftFloat() const { 1500 return Subtarget->useSoftFloat(); 1501 } 1502 1503 // FIXME: It might make sense to define the representative register class as the 1504 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1505 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1506 // SPR's representative would be DPR_VFP2. This should work well if register 1507 // pressure tracking were modified such that a register use would increment the 1508 // pressure of the register class's representative and all of it's super 1509 // classes' representatives transitively. We have not implemented this because 1510 // of the difficulty prior to coalescing of modeling operand register classes 1511 // due to the common occurrence of cross class copies and subregister insertions 1512 // and extractions. 1513 std::pair<const TargetRegisterClass *, uint8_t> 1514 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1515 MVT VT) const { 1516 const TargetRegisterClass *RRC = nullptr; 1517 uint8_t Cost = 1; 1518 switch (VT.SimpleTy) { 1519 default: 1520 return TargetLowering::findRepresentativeClass(TRI, VT); 1521 // Use DPR as representative register class for all floating point 1522 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1523 // the cost is 1 for both f32 and f64. 1524 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1525 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1526 RRC = &ARM::DPRRegClass; 1527 // When NEON is used for SP, only half of the register file is available 1528 // because operations that define both SP and DP results will be constrained 1529 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1530 // coalescing by double-counting the SP regs. See the FIXME above. 1531 if (Subtarget->useNEONForSinglePrecisionFP()) 1532 Cost = 2; 1533 break; 1534 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1535 case MVT::v4f32: case MVT::v2f64: 1536 RRC = &ARM::DPRRegClass; 1537 Cost = 2; 1538 break; 1539 case MVT::v4i64: 1540 RRC = &ARM::DPRRegClass; 1541 Cost = 4; 1542 break; 1543 case MVT::v8i64: 1544 RRC = &ARM::DPRRegClass; 1545 Cost = 8; 1546 break; 1547 } 1548 return std::make_pair(RRC, Cost); 1549 } 1550 1551 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1552 switch ((ARMISD::NodeType)Opcode) { 1553 case ARMISD::FIRST_NUMBER: break; 1554 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1555 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1556 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1557 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1558 case ARMISD::CALL: return "ARMISD::CALL"; 1559 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1560 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1561 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1562 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1563 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1564 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1565 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1566 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1567 case ARMISD::CMP: return "ARMISD::CMP"; 1568 case ARMISD::CMN: return "ARMISD::CMN"; 1569 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1570 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1571 case ARMISD::CMPFPE: return "ARMISD::CMPFPE"; 1572 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1573 case ARMISD::CMPFPEw0: return "ARMISD::CMPFPEw0"; 1574 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1575 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1576 1577 case ARMISD::CMOV: return "ARMISD::CMOV"; 1578 case ARMISD::SUBS: return "ARMISD::SUBS"; 1579 1580 case ARMISD::SSAT: return "ARMISD::SSAT"; 1581 case ARMISD::USAT: return "ARMISD::USAT"; 1582 1583 case ARMISD::ASRL: return "ARMISD::ASRL"; 1584 case ARMISD::LSRL: return "ARMISD::LSRL"; 1585 case ARMISD::LSLL: return "ARMISD::LSLL"; 1586 1587 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1588 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1589 case ARMISD::RRX: return "ARMISD::RRX"; 1590 1591 case ARMISD::ADDC: return "ARMISD::ADDC"; 1592 case ARMISD::ADDE: return "ARMISD::ADDE"; 1593 case ARMISD::SUBC: return "ARMISD::SUBC"; 1594 case ARMISD::SUBE: return "ARMISD::SUBE"; 1595 case ARMISD::LSLS: return "ARMISD::LSLS"; 1596 1597 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1598 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1599 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1600 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1601 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1602 1603 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1604 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1605 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1606 1607 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1608 1609 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1610 1611 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1612 1613 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1614 1615 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1616 1617 case ARMISD::LDRD: return "ARMISD::LDRD"; 1618 case ARMISD::STRD: return "ARMISD::STRD"; 1619 1620 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1621 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1622 1623 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST"; 1624 case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST"; 1625 case ARMISD::VCMP: return "ARMISD::VCMP"; 1626 case ARMISD::VCMPZ: return "ARMISD::VCMPZ"; 1627 case ARMISD::VTST: return "ARMISD::VTST"; 1628 1629 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1630 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1631 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1632 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1633 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1634 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1635 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1636 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1637 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1638 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1639 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1640 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1641 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1642 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1643 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1644 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1645 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1646 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1647 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1648 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1649 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1650 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1651 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1652 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1653 case ARMISD::VDUP: return "ARMISD::VDUP"; 1654 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1655 case ARMISD::VEXT: return "ARMISD::VEXT"; 1656 case ARMISD::VREV64: return "ARMISD::VREV64"; 1657 case ARMISD::VREV32: return "ARMISD::VREV32"; 1658 case ARMISD::VREV16: return "ARMISD::VREV16"; 1659 case ARMISD::VZIP: return "ARMISD::VZIP"; 1660 case ARMISD::VUZP: return "ARMISD::VUZP"; 1661 case ARMISD::VTRN: return "ARMISD::VTRN"; 1662 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1663 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1664 case ARMISD::VMOVN: return "ARMISD::VMOVN"; 1665 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1666 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1667 case ARMISD::VADDVs: return "ARMISD::VADDVs"; 1668 case ARMISD::VADDVu: return "ARMISD::VADDVu"; 1669 case ARMISD::VADDLVs: return "ARMISD::VADDLVs"; 1670 case ARMISD::VADDLVu: return "ARMISD::VADDLVu"; 1671 case ARMISD::VADDLVAs: return "ARMISD::VADDLVAs"; 1672 case ARMISD::VADDLVAu: return "ARMISD::VADDLVAu"; 1673 case ARMISD::VADDLVps: return "ARMISD::VADDLVps"; 1674 case ARMISD::VADDLVpu: return "ARMISD::VADDLVpu"; 1675 case ARMISD::VADDLVAps: return "ARMISD::VADDLVAps"; 1676 case ARMISD::VADDLVApu: return "ARMISD::VADDLVApu"; 1677 case ARMISD::VMLAVs: return "ARMISD::VMLAVs"; 1678 case ARMISD::VMLAVu: return "ARMISD::VMLAVu"; 1679 case ARMISD::VMLALVs: return "ARMISD::VMLALVs"; 1680 case ARMISD::VMLALVu: return "ARMISD::VMLALVu"; 1681 case ARMISD::VMLALVAs: return "ARMISD::VMLALVAs"; 1682 case ARMISD::VMLALVAu: return "ARMISD::VMLALVAu"; 1683 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1684 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1685 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1686 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1687 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1688 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1689 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1690 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1691 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1692 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1693 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1694 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1695 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1696 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1697 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1698 case ARMISD::QADD16b: return "ARMISD::QADD16b"; 1699 case ARMISD::QSUB16b: return "ARMISD::QSUB16b"; 1700 case ARMISD::QADD8b: return "ARMISD::QADD8b"; 1701 case ARMISD::QSUB8b: return "ARMISD::QSUB8b"; 1702 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1703 case ARMISD::BFI: return "ARMISD::BFI"; 1704 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1705 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1706 case ARMISD::VBSL: return "ARMISD::VBSL"; 1707 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1708 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1709 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1710 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1711 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1712 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1713 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1714 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1715 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1716 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1717 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1718 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1719 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1720 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1721 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1722 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1723 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1724 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1725 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1726 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1727 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1728 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1729 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1730 case ARMISD::WLS: return "ARMISD::WLS"; 1731 case ARMISD::LE: return "ARMISD::LE"; 1732 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1733 case ARMISD::CSINV: return "ARMISD::CSINV"; 1734 case ARMISD::CSNEG: return "ARMISD::CSNEG"; 1735 case ARMISD::CSINC: return "ARMISD::CSINC"; 1736 } 1737 return nullptr; 1738 } 1739 1740 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1741 EVT VT) const { 1742 if (!VT.isVector()) 1743 return getPointerTy(DL); 1744 1745 // MVE has a predicate register. 1746 if (Subtarget->hasMVEIntegerOps() && 1747 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1748 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1749 return VT.changeVectorElementTypeToInteger(); 1750 } 1751 1752 /// getRegClassFor - Return the register class that should be used for the 1753 /// specified value type. 1754 const TargetRegisterClass * 1755 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1756 (void)isDivergent; 1757 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1758 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1759 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1760 // MVE Q registers. 1761 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1762 if (VT == MVT::v4i64) 1763 return &ARM::QQPRRegClass; 1764 if (VT == MVT::v8i64) 1765 return &ARM::QQQQPRRegClass; 1766 } 1767 return TargetLowering::getRegClassFor(VT); 1768 } 1769 1770 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1771 // source/dest is aligned and the copy size is large enough. We therefore want 1772 // to align such objects passed to memory intrinsics. 1773 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1774 unsigned &PrefAlign) const { 1775 if (!isa<MemIntrinsic>(CI)) 1776 return false; 1777 MinSize = 8; 1778 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1779 // cycle faster than 4-byte aligned LDM. 1780 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1781 return true; 1782 } 1783 1784 // Create a fast isel object. 1785 FastISel * 1786 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1787 const TargetLibraryInfo *libInfo) const { 1788 return ARM::createFastISel(funcInfo, libInfo); 1789 } 1790 1791 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1792 unsigned NumVals = N->getNumValues(); 1793 if (!NumVals) 1794 return Sched::RegPressure; 1795 1796 for (unsigned i = 0; i != NumVals; ++i) { 1797 EVT VT = N->getValueType(i); 1798 if (VT == MVT::Glue || VT == MVT::Other) 1799 continue; 1800 if (VT.isFloatingPoint() || VT.isVector()) 1801 return Sched::ILP; 1802 } 1803 1804 if (!N->isMachineOpcode()) 1805 return Sched::RegPressure; 1806 1807 // Load are scheduled for latency even if there instruction itinerary 1808 // is not available. 1809 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1810 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1811 1812 if (MCID.getNumDefs() == 0) 1813 return Sched::RegPressure; 1814 if (!Itins->isEmpty() && 1815 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1816 return Sched::ILP; 1817 1818 return Sched::RegPressure; 1819 } 1820 1821 //===----------------------------------------------------------------------===// 1822 // Lowering Code 1823 //===----------------------------------------------------------------------===// 1824 1825 static bool isSRL16(const SDValue &Op) { 1826 if (Op.getOpcode() != ISD::SRL) 1827 return false; 1828 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1829 return Const->getZExtValue() == 16; 1830 return false; 1831 } 1832 1833 static bool isSRA16(const SDValue &Op) { 1834 if (Op.getOpcode() != ISD::SRA) 1835 return false; 1836 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1837 return Const->getZExtValue() == 16; 1838 return false; 1839 } 1840 1841 static bool isSHL16(const SDValue &Op) { 1842 if (Op.getOpcode() != ISD::SHL) 1843 return false; 1844 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1845 return Const->getZExtValue() == 16; 1846 return false; 1847 } 1848 1849 // Check for a signed 16-bit value. We special case SRA because it makes it 1850 // more simple when also looking for SRAs that aren't sign extending a 1851 // smaller value. Without the check, we'd need to take extra care with 1852 // checking order for some operations. 1853 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1854 if (isSRA16(Op)) 1855 return isSHL16(Op.getOperand(0)); 1856 return DAG.ComputeNumSignBits(Op) == 17; 1857 } 1858 1859 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1860 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1861 switch (CC) { 1862 default: llvm_unreachable("Unknown condition code!"); 1863 case ISD::SETNE: return ARMCC::NE; 1864 case ISD::SETEQ: return ARMCC::EQ; 1865 case ISD::SETGT: return ARMCC::GT; 1866 case ISD::SETGE: return ARMCC::GE; 1867 case ISD::SETLT: return ARMCC::LT; 1868 case ISD::SETLE: return ARMCC::LE; 1869 case ISD::SETUGT: return ARMCC::HI; 1870 case ISD::SETUGE: return ARMCC::HS; 1871 case ISD::SETULT: return ARMCC::LO; 1872 case ISD::SETULE: return ARMCC::LS; 1873 } 1874 } 1875 1876 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1877 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1878 ARMCC::CondCodes &CondCode2) { 1879 CondCode2 = ARMCC::AL; 1880 switch (CC) { 1881 default: llvm_unreachable("Unknown FP condition!"); 1882 case ISD::SETEQ: 1883 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1884 case ISD::SETGT: 1885 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1886 case ISD::SETGE: 1887 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1888 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1889 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1890 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1891 case ISD::SETO: CondCode = ARMCC::VC; break; 1892 case ISD::SETUO: CondCode = ARMCC::VS; break; 1893 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1894 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1895 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1896 case ISD::SETLT: 1897 case ISD::SETULT: CondCode = ARMCC::LT; break; 1898 case ISD::SETLE: 1899 case ISD::SETULE: CondCode = ARMCC::LE; break; 1900 case ISD::SETNE: 1901 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1902 } 1903 } 1904 1905 //===----------------------------------------------------------------------===// 1906 // Calling Convention Implementation 1907 //===----------------------------------------------------------------------===// 1908 1909 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1910 /// account presence of floating point hardware and calling convention 1911 /// limitations, such as support for variadic functions. 1912 CallingConv::ID 1913 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1914 bool isVarArg) const { 1915 switch (CC) { 1916 default: 1917 report_fatal_error("Unsupported calling convention"); 1918 case CallingConv::ARM_AAPCS: 1919 case CallingConv::ARM_APCS: 1920 case CallingConv::GHC: 1921 case CallingConv::CFGuard_Check: 1922 return CC; 1923 case CallingConv::PreserveMost: 1924 return CallingConv::PreserveMost; 1925 case CallingConv::ARM_AAPCS_VFP: 1926 case CallingConv::Swift: 1927 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1928 case CallingConv::C: 1929 if (!Subtarget->isAAPCS_ABI()) 1930 return CallingConv::ARM_APCS; 1931 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1932 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1933 !isVarArg) 1934 return CallingConv::ARM_AAPCS_VFP; 1935 else 1936 return CallingConv::ARM_AAPCS; 1937 case CallingConv::Fast: 1938 case CallingConv::CXX_FAST_TLS: 1939 if (!Subtarget->isAAPCS_ABI()) { 1940 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 1941 return CallingConv::Fast; 1942 return CallingConv::ARM_APCS; 1943 } else if (Subtarget->hasVFP2Base() && 1944 !Subtarget->isThumb1Only() && !isVarArg) 1945 return CallingConv::ARM_AAPCS_VFP; 1946 else 1947 return CallingConv::ARM_AAPCS; 1948 } 1949 } 1950 1951 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1952 bool isVarArg) const { 1953 return CCAssignFnForNode(CC, false, isVarArg); 1954 } 1955 1956 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1957 bool isVarArg) const { 1958 return CCAssignFnForNode(CC, true, isVarArg); 1959 } 1960 1961 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1962 /// CallingConvention. 1963 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1964 bool Return, 1965 bool isVarArg) const { 1966 switch (getEffectiveCallingConv(CC, isVarArg)) { 1967 default: 1968 report_fatal_error("Unsupported calling convention"); 1969 case CallingConv::ARM_APCS: 1970 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1971 case CallingConv::ARM_AAPCS: 1972 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1973 case CallingConv::ARM_AAPCS_VFP: 1974 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1975 case CallingConv::Fast: 1976 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1977 case CallingConv::GHC: 1978 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1979 case CallingConv::PreserveMost: 1980 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1981 case CallingConv::CFGuard_Check: 1982 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check); 1983 } 1984 } 1985 1986 /// LowerCallResult - Lower the result values of a call into the 1987 /// appropriate copies out of appropriate physical registers. 1988 SDValue ARMTargetLowering::LowerCallResult( 1989 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1990 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1991 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1992 SDValue ThisVal) const { 1993 // Assign locations to each value returned by this call. 1994 SmallVector<CCValAssign, 16> RVLocs; 1995 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1996 *DAG.getContext()); 1997 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1998 1999 // Copy all of the result registers out of their specified physreg. 2000 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2001 CCValAssign VA = RVLocs[i]; 2002 2003 // Pass 'this' value directly from the argument to return value, to avoid 2004 // reg unit interference 2005 if (i == 0 && isThisReturn) { 2006 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 2007 "unexpected return calling convention register assignment"); 2008 InVals.push_back(ThisVal); 2009 continue; 2010 } 2011 2012 SDValue Val; 2013 if (VA.needsCustom()) { 2014 // Handle f64 or half of a v2f64. 2015 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2016 InFlag); 2017 Chain = Lo.getValue(1); 2018 InFlag = Lo.getValue(2); 2019 VA = RVLocs[++i]; // skip ahead to next loc 2020 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2021 InFlag); 2022 Chain = Hi.getValue(1); 2023 InFlag = Hi.getValue(2); 2024 if (!Subtarget->isLittle()) 2025 std::swap (Lo, Hi); 2026 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2027 2028 if (VA.getLocVT() == MVT::v2f64) { 2029 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 2030 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2031 DAG.getConstant(0, dl, MVT::i32)); 2032 2033 VA = RVLocs[++i]; // skip ahead to next loc 2034 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2035 Chain = Lo.getValue(1); 2036 InFlag = Lo.getValue(2); 2037 VA = RVLocs[++i]; // skip ahead to next loc 2038 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2039 Chain = Hi.getValue(1); 2040 InFlag = Hi.getValue(2); 2041 if (!Subtarget->isLittle()) 2042 std::swap (Lo, Hi); 2043 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2044 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2045 DAG.getConstant(1, dl, MVT::i32)); 2046 } 2047 } else { 2048 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 2049 InFlag); 2050 Chain = Val.getValue(1); 2051 InFlag = Val.getValue(2); 2052 } 2053 2054 switch (VA.getLocInfo()) { 2055 default: llvm_unreachable("Unknown loc info!"); 2056 case CCValAssign::Full: break; 2057 case CCValAssign::BCvt: 2058 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 2059 break; 2060 } 2061 2062 InVals.push_back(Val); 2063 } 2064 2065 return Chain; 2066 } 2067 2068 /// LowerMemOpCallTo - Store the argument to the stack. 2069 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 2070 SDValue Arg, const SDLoc &dl, 2071 SelectionDAG &DAG, 2072 const CCValAssign &VA, 2073 ISD::ArgFlagsTy Flags) const { 2074 unsigned LocMemOffset = VA.getLocMemOffset(); 2075 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2076 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 2077 StackPtr, PtrOff); 2078 return DAG.getStore( 2079 Chain, dl, Arg, PtrOff, 2080 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 2081 } 2082 2083 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 2084 SDValue Chain, SDValue &Arg, 2085 RegsToPassVector &RegsToPass, 2086 CCValAssign &VA, CCValAssign &NextVA, 2087 SDValue &StackPtr, 2088 SmallVectorImpl<SDValue> &MemOpChains, 2089 ISD::ArgFlagsTy Flags) const { 2090 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2091 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2092 unsigned id = Subtarget->isLittle() ? 0 : 1; 2093 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2094 2095 if (NextVA.isRegLoc()) 2096 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2097 else { 2098 assert(NextVA.isMemLoc()); 2099 if (!StackPtr.getNode()) 2100 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2101 getPointerTy(DAG.getDataLayout())); 2102 2103 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2104 dl, DAG, NextVA, 2105 Flags)); 2106 } 2107 } 2108 2109 /// LowerCall - Lowering a call into a callseq_start <- 2110 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2111 /// nodes. 2112 SDValue 2113 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2114 SmallVectorImpl<SDValue> &InVals) const { 2115 SelectionDAG &DAG = CLI.DAG; 2116 SDLoc &dl = CLI.DL; 2117 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2118 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2119 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2120 SDValue Chain = CLI.Chain; 2121 SDValue Callee = CLI.Callee; 2122 bool &isTailCall = CLI.IsTailCall; 2123 CallingConv::ID CallConv = CLI.CallConv; 2124 bool doesNotRet = CLI.DoesNotReturn; 2125 bool isVarArg = CLI.IsVarArg; 2126 2127 MachineFunction &MF = DAG.getMachineFunction(); 2128 MachineFunction::CallSiteInfo CSInfo; 2129 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2130 bool isThisReturn = false; 2131 bool PreferIndirect = false; 2132 2133 // Disable tail calls if they're not supported. 2134 if (!Subtarget->supportsTailCall()) 2135 isTailCall = false; 2136 2137 if (isa<GlobalAddressSDNode>(Callee)) { 2138 // If we're optimizing for minimum size and the function is called three or 2139 // more times in this block, we can improve codesize by calling indirectly 2140 // as BLXr has a 16-bit encoding. 2141 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2142 if (CLI.CB) { 2143 auto *BB = CLI.CB->getParent(); 2144 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2145 count_if(GV->users(), [&BB](const User *U) { 2146 return isa<Instruction>(U) && 2147 cast<Instruction>(U)->getParent() == BB; 2148 }) > 2; 2149 } 2150 } 2151 if (isTailCall) { 2152 // Check if it's really possible to do a tail call. 2153 isTailCall = IsEligibleForTailCallOptimization( 2154 Callee, CallConv, isVarArg, isStructRet, 2155 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2156 PreferIndirect); 2157 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall()) 2158 report_fatal_error("failed to perform tail call elimination on a call " 2159 "site marked musttail"); 2160 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2161 // detected sibcalls. 2162 if (isTailCall) 2163 ++NumTailCalls; 2164 } 2165 2166 // Analyze operands of the call, assigning locations to each operand. 2167 SmallVector<CCValAssign, 16> ArgLocs; 2168 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2169 *DAG.getContext()); 2170 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2171 2172 // Get a count of how many bytes are to be pushed on the stack. 2173 unsigned NumBytes = CCInfo.getNextStackOffset(); 2174 2175 if (isTailCall) { 2176 // For tail calls, memory operands are available in our caller's stack. 2177 NumBytes = 0; 2178 } else { 2179 // Adjust the stack pointer for the new arguments... 2180 // These operations are automatically eliminated by the prolog/epilog pass 2181 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2182 } 2183 2184 SDValue StackPtr = 2185 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2186 2187 RegsToPassVector RegsToPass; 2188 SmallVector<SDValue, 8> MemOpChains; 2189 2190 // Walk the register/memloc assignments, inserting copies/loads. In the case 2191 // of tail call optimization, arguments are handled later. 2192 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2193 i != e; 2194 ++i, ++realArgIdx) { 2195 CCValAssign &VA = ArgLocs[i]; 2196 SDValue Arg = OutVals[realArgIdx]; 2197 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2198 bool isByVal = Flags.isByVal(); 2199 2200 // Promote the value if needed. 2201 switch (VA.getLocInfo()) { 2202 default: llvm_unreachable("Unknown loc info!"); 2203 case CCValAssign::Full: break; 2204 case CCValAssign::SExt: 2205 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2206 break; 2207 case CCValAssign::ZExt: 2208 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2209 break; 2210 case CCValAssign::AExt: 2211 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2212 break; 2213 case CCValAssign::BCvt: 2214 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2215 break; 2216 } 2217 2218 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2219 if (VA.needsCustom()) { 2220 if (VA.getLocVT() == MVT::v2f64) { 2221 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2222 DAG.getConstant(0, dl, MVT::i32)); 2223 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2224 DAG.getConstant(1, dl, MVT::i32)); 2225 2226 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 2227 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2228 2229 VA = ArgLocs[++i]; // skip ahead to next loc 2230 if (VA.isRegLoc()) { 2231 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 2232 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2233 } else { 2234 assert(VA.isMemLoc()); 2235 2236 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 2237 dl, DAG, VA, Flags)); 2238 } 2239 } else { 2240 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2241 StackPtr, MemOpChains, Flags); 2242 } 2243 } else if (VA.isRegLoc()) { 2244 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2245 Outs[0].VT == MVT::i32) { 2246 assert(VA.getLocVT() == MVT::i32 && 2247 "unexpected calling convention register assignment"); 2248 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2249 "unexpected use of 'returned'"); 2250 isThisReturn = true; 2251 } 2252 const TargetOptions &Options = DAG.getTarget().Options; 2253 if (Options.EmitCallSiteInfo) 2254 CSInfo.emplace_back(VA.getLocReg(), i); 2255 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2256 } else if (isByVal) { 2257 assert(VA.isMemLoc()); 2258 unsigned offset = 0; 2259 2260 // True if this byval aggregate will be split between registers 2261 // and memory. 2262 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2263 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2264 2265 if (CurByValIdx < ByValArgsCount) { 2266 2267 unsigned RegBegin, RegEnd; 2268 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2269 2270 EVT PtrVT = 2271 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2272 unsigned int i, j; 2273 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2274 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2275 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2276 SDValue Load = 2277 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(), 2278 DAG.InferPtrAlign(AddArg)); 2279 MemOpChains.push_back(Load.getValue(1)); 2280 RegsToPass.push_back(std::make_pair(j, Load)); 2281 } 2282 2283 // If parameter size outsides register area, "offset" value 2284 // helps us to calculate stack slot for remained part properly. 2285 offset = RegEnd - RegBegin; 2286 2287 CCInfo.nextInRegsParam(); 2288 } 2289 2290 if (Flags.getByValSize() > 4*offset) { 2291 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2292 unsigned LocMemOffset = VA.getLocMemOffset(); 2293 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2294 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2295 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2296 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2297 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2298 MVT::i32); 2299 SDValue AlignNode = 2300 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32); 2301 2302 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2303 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2304 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2305 Ops)); 2306 } 2307 } else if (!isTailCall) { 2308 assert(VA.isMemLoc()); 2309 2310 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2311 dl, DAG, VA, Flags)); 2312 } 2313 } 2314 2315 if (!MemOpChains.empty()) 2316 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2317 2318 // Build a sequence of copy-to-reg nodes chained together with token chain 2319 // and flag operands which copy the outgoing args into the appropriate regs. 2320 SDValue InFlag; 2321 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2322 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2323 RegsToPass[i].second, InFlag); 2324 InFlag = Chain.getValue(1); 2325 } 2326 2327 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2328 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2329 // node so that legalize doesn't hack it. 2330 bool isDirect = false; 2331 2332 const TargetMachine &TM = getTargetMachine(); 2333 const Module *Mod = MF.getFunction().getParent(); 2334 const GlobalValue *GV = nullptr; 2335 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2336 GV = G->getGlobal(); 2337 bool isStub = 2338 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2339 2340 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2341 bool isLocalARMFunc = false; 2342 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2343 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2344 2345 if (Subtarget->genLongCalls()) { 2346 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2347 "long-calls codegen is not position independent!"); 2348 // Handle a global address or an external symbol. If it's not one of 2349 // those, the target's already in a register, so we don't need to do 2350 // anything extra. 2351 if (isa<GlobalAddressSDNode>(Callee)) { 2352 // Create a constant pool entry for the callee address 2353 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2354 ARMConstantPoolValue *CPV = 2355 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2356 2357 // Get the address of the callee into a register 2358 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2359 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2360 Callee = DAG.getLoad( 2361 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2362 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2363 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2364 const char *Sym = S->getSymbol(); 2365 2366 // Create a constant pool entry for the callee address 2367 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2368 ARMConstantPoolValue *CPV = 2369 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2370 ARMPCLabelIndex, 0); 2371 // Get the address of the callee into a register 2372 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2373 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2374 Callee = DAG.getLoad( 2375 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2376 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2377 } 2378 } else if (isa<GlobalAddressSDNode>(Callee)) { 2379 if (!PreferIndirect) { 2380 isDirect = true; 2381 bool isDef = GV->isStrongDefinitionForLinker(); 2382 2383 // ARM call to a local ARM function is predicable. 2384 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2385 // tBX takes a register source operand. 2386 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2387 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2388 Callee = DAG.getNode( 2389 ARMISD::WrapperPIC, dl, PtrVt, 2390 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2391 Callee = DAG.getLoad( 2392 PtrVt, dl, DAG.getEntryNode(), Callee, 2393 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2394 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2395 MachineMemOperand::MOInvariant); 2396 } else if (Subtarget->isTargetCOFF()) { 2397 assert(Subtarget->isTargetWindows() && 2398 "Windows is the only supported COFF target"); 2399 unsigned TargetFlags = ARMII::MO_NO_FLAG; 2400 if (GV->hasDLLImportStorageClass()) 2401 TargetFlags = ARMII::MO_DLLIMPORT; 2402 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 2403 TargetFlags = ARMII::MO_COFFSTUB; 2404 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2405 TargetFlags); 2406 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 2407 Callee = 2408 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2409 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2410 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2411 } else { 2412 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2413 } 2414 } 2415 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2416 isDirect = true; 2417 // tBX takes a register source operand. 2418 const char *Sym = S->getSymbol(); 2419 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2420 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2421 ARMConstantPoolValue *CPV = 2422 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2423 ARMPCLabelIndex, 4); 2424 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2425 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2426 Callee = DAG.getLoad( 2427 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2428 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2429 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2430 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2431 } else { 2432 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2433 } 2434 } 2435 2436 // FIXME: handle tail calls differently. 2437 unsigned CallOpc; 2438 if (Subtarget->isThumb()) { 2439 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2440 CallOpc = ARMISD::CALL_NOLINK; 2441 else 2442 CallOpc = ARMISD::CALL; 2443 } else { 2444 if (!isDirect && !Subtarget->hasV5TOps()) 2445 CallOpc = ARMISD::CALL_NOLINK; 2446 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2447 // Emit regular call when code size is the priority 2448 !Subtarget->hasMinSize()) 2449 // "mov lr, pc; b _foo" to avoid confusing the RSP 2450 CallOpc = ARMISD::CALL_NOLINK; 2451 else 2452 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2453 } 2454 2455 std::vector<SDValue> Ops; 2456 Ops.push_back(Chain); 2457 Ops.push_back(Callee); 2458 2459 // Add argument registers to the end of the list so that they are known live 2460 // into the call. 2461 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2462 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2463 RegsToPass[i].second.getValueType())); 2464 2465 // Add a register mask operand representing the call-preserved registers. 2466 if (!isTailCall) { 2467 const uint32_t *Mask; 2468 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2469 if (isThisReturn) { 2470 // For 'this' returns, use the R0-preserving mask if applicable 2471 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2472 if (!Mask) { 2473 // Set isThisReturn to false if the calling convention is not one that 2474 // allows 'returned' to be modeled in this way, so LowerCallResult does 2475 // not try to pass 'this' straight through 2476 isThisReturn = false; 2477 Mask = ARI->getCallPreservedMask(MF, CallConv); 2478 } 2479 } else 2480 Mask = ARI->getCallPreservedMask(MF, CallConv); 2481 2482 assert(Mask && "Missing call preserved mask for calling convention"); 2483 Ops.push_back(DAG.getRegisterMask(Mask)); 2484 } 2485 2486 if (InFlag.getNode()) 2487 Ops.push_back(InFlag); 2488 2489 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2490 if (isTailCall) { 2491 MF.getFrameInfo().setHasTailCall(); 2492 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2493 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 2494 return Ret; 2495 } 2496 2497 // Returns a chain and a flag for retval copy to use. 2498 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2499 InFlag = Chain.getValue(1); 2500 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 2501 2502 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2503 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2504 if (!Ins.empty()) 2505 InFlag = Chain.getValue(1); 2506 2507 // Handle result values, copying them out of physregs into vregs that we 2508 // return. 2509 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2510 InVals, isThisReturn, 2511 isThisReturn ? OutVals[0] : SDValue()); 2512 } 2513 2514 /// HandleByVal - Every parameter *after* a byval parameter is passed 2515 /// on the stack. Remember the next parameter register to allocate, 2516 /// and then confiscate the rest of the parameter registers to insure 2517 /// this. 2518 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2519 unsigned Align) const { 2520 // Byval (as with any stack) slots are always at least 4 byte aligned. 2521 Align = std::max(Align, 4U); 2522 2523 unsigned Reg = State->AllocateReg(GPRArgRegs); 2524 if (!Reg) 2525 return; 2526 2527 unsigned AlignInRegs = Align / 4; 2528 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2529 for (unsigned i = 0; i < Waste; ++i) 2530 Reg = State->AllocateReg(GPRArgRegs); 2531 2532 if (!Reg) 2533 return; 2534 2535 unsigned Excess = 4 * (ARM::R4 - Reg); 2536 2537 // Special case when NSAA != SP and parameter size greater than size of 2538 // all remained GPR regs. In that case we can't split parameter, we must 2539 // send it to stack. We also must set NCRN to R4, so waste all 2540 // remained registers. 2541 const unsigned NSAAOffset = State->getNextStackOffset(); 2542 if (NSAAOffset != 0 && Size > Excess) { 2543 while (State->AllocateReg(GPRArgRegs)) 2544 ; 2545 return; 2546 } 2547 2548 // First register for byval parameter is the first register that wasn't 2549 // allocated before this method call, so it would be "reg". 2550 // If parameter is small enough to be saved in range [reg, r4), then 2551 // the end (first after last) register would be reg + param-size-in-regs, 2552 // else parameter would be splitted between registers and stack, 2553 // end register would be r4 in this case. 2554 unsigned ByValRegBegin = Reg; 2555 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2556 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2557 // Note, first register is allocated in the beginning of function already, 2558 // allocate remained amount of registers we need. 2559 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2560 State->AllocateReg(GPRArgRegs); 2561 // A byval parameter that is split between registers and memory needs its 2562 // size truncated here. 2563 // In the case where the entire structure fits in registers, we set the 2564 // size in memory to zero. 2565 Size = std::max<int>(Size - Excess, 0); 2566 } 2567 2568 /// MatchingStackOffset - Return true if the given stack call argument is 2569 /// already available in the same position (relatively) of the caller's 2570 /// incoming argument stack. 2571 static 2572 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2573 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2574 const TargetInstrInfo *TII) { 2575 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2576 int FI = std::numeric_limits<int>::max(); 2577 if (Arg.getOpcode() == ISD::CopyFromReg) { 2578 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2579 if (!Register::isVirtualRegister(VR)) 2580 return false; 2581 MachineInstr *Def = MRI->getVRegDef(VR); 2582 if (!Def) 2583 return false; 2584 if (!Flags.isByVal()) { 2585 if (!TII->isLoadFromStackSlot(*Def, FI)) 2586 return false; 2587 } else { 2588 return false; 2589 } 2590 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2591 if (Flags.isByVal()) 2592 // ByVal argument is passed in as a pointer but it's now being 2593 // dereferenced. e.g. 2594 // define @foo(%struct.X* %A) { 2595 // tail call @bar(%struct.X* byval %A) 2596 // } 2597 return false; 2598 SDValue Ptr = Ld->getBasePtr(); 2599 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2600 if (!FINode) 2601 return false; 2602 FI = FINode->getIndex(); 2603 } else 2604 return false; 2605 2606 assert(FI != std::numeric_limits<int>::max()); 2607 if (!MFI.isFixedObjectIndex(FI)) 2608 return false; 2609 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2610 } 2611 2612 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2613 /// for tail call optimization. Targets which want to do tail call 2614 /// optimization should implement this function. 2615 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2616 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2617 bool isCalleeStructRet, bool isCallerStructRet, 2618 const SmallVectorImpl<ISD::OutputArg> &Outs, 2619 const SmallVectorImpl<SDValue> &OutVals, 2620 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2621 const bool isIndirect) const { 2622 MachineFunction &MF = DAG.getMachineFunction(); 2623 const Function &CallerF = MF.getFunction(); 2624 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2625 2626 assert(Subtarget->supportsTailCall()); 2627 2628 // Indirect tail calls cannot be optimized for Thumb1 if the args 2629 // to the call take up r0-r3. The reason is that there are no legal registers 2630 // left to hold the pointer to the function to be called. 2631 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2632 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2633 return false; 2634 2635 // Look for obvious safe cases to perform tail call optimization that do not 2636 // require ABI changes. This is what gcc calls sibcall. 2637 2638 // Exception-handling functions need a special set of instructions to indicate 2639 // a return to the hardware. Tail-calling another function would probably 2640 // break this. 2641 if (CallerF.hasFnAttribute("interrupt")) 2642 return false; 2643 2644 // Also avoid sibcall optimization if either caller or callee uses struct 2645 // return semantics. 2646 if (isCalleeStructRet || isCallerStructRet) 2647 return false; 2648 2649 // Externally-defined functions with weak linkage should not be 2650 // tail-called on ARM when the OS does not support dynamic 2651 // pre-emption of symbols, as the AAELF spec requires normal calls 2652 // to undefined weak functions to be replaced with a NOP or jump to the 2653 // next instruction. The behaviour of branch instructions in this 2654 // situation (as used for tail calls) is implementation-defined, so we 2655 // cannot rely on the linker replacing the tail call with a return. 2656 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2657 const GlobalValue *GV = G->getGlobal(); 2658 const Triple &TT = getTargetMachine().getTargetTriple(); 2659 if (GV->hasExternalWeakLinkage() && 2660 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2661 return false; 2662 } 2663 2664 // Check that the call results are passed in the same way. 2665 LLVMContext &C = *DAG.getContext(); 2666 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2667 CCAssignFnForReturn(CalleeCC, isVarArg), 2668 CCAssignFnForReturn(CallerCC, isVarArg))) 2669 return false; 2670 // The callee has to preserve all registers the caller needs to preserve. 2671 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2672 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2673 if (CalleeCC != CallerCC) { 2674 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2675 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2676 return false; 2677 } 2678 2679 // If Caller's vararg or byval argument has been split between registers and 2680 // stack, do not perform tail call, since part of the argument is in caller's 2681 // local frame. 2682 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2683 if (AFI_Caller->getArgRegsSaveSize()) 2684 return false; 2685 2686 // If the callee takes no arguments then go on to check the results of the 2687 // call. 2688 if (!Outs.empty()) { 2689 // Check if stack adjustment is needed. For now, do not do this if any 2690 // argument is passed on the stack. 2691 SmallVector<CCValAssign, 16> ArgLocs; 2692 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2693 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2694 if (CCInfo.getNextStackOffset()) { 2695 // Check if the arguments are already laid out in the right way as 2696 // the caller's fixed stack objects. 2697 MachineFrameInfo &MFI = MF.getFrameInfo(); 2698 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2699 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2700 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2701 i != e; 2702 ++i, ++realArgIdx) { 2703 CCValAssign &VA = ArgLocs[i]; 2704 EVT RegVT = VA.getLocVT(); 2705 SDValue Arg = OutVals[realArgIdx]; 2706 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2707 if (VA.getLocInfo() == CCValAssign::Indirect) 2708 return false; 2709 if (VA.needsCustom()) { 2710 // f64 and vector types are split into multiple registers or 2711 // register/stack-slot combinations. The types will not match 2712 // the registers; give up on memory f64 refs until we figure 2713 // out what to do about this. 2714 if (!VA.isRegLoc()) 2715 return false; 2716 if (!ArgLocs[++i].isRegLoc()) 2717 return false; 2718 if (RegVT == MVT::v2f64) { 2719 if (!ArgLocs[++i].isRegLoc()) 2720 return false; 2721 if (!ArgLocs[++i].isRegLoc()) 2722 return false; 2723 } 2724 } else if (!VA.isRegLoc()) { 2725 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2726 MFI, MRI, TII)) 2727 return false; 2728 } 2729 } 2730 } 2731 2732 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2733 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2734 return false; 2735 } 2736 2737 return true; 2738 } 2739 2740 bool 2741 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2742 MachineFunction &MF, bool isVarArg, 2743 const SmallVectorImpl<ISD::OutputArg> &Outs, 2744 LLVMContext &Context) const { 2745 SmallVector<CCValAssign, 16> RVLocs; 2746 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2747 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2748 } 2749 2750 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2751 const SDLoc &DL, SelectionDAG &DAG) { 2752 const MachineFunction &MF = DAG.getMachineFunction(); 2753 const Function &F = MF.getFunction(); 2754 2755 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2756 2757 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2758 // version of the "preferred return address". These offsets affect the return 2759 // instruction if this is a return from PL1 without hypervisor extensions. 2760 // IRQ/FIQ: +4 "subs pc, lr, #4" 2761 // SWI: 0 "subs pc, lr, #0" 2762 // ABORT: +4 "subs pc, lr, #4" 2763 // UNDEF: +4/+2 "subs pc, lr, #0" 2764 // UNDEF varies depending on where the exception came from ARM or Thumb 2765 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2766 2767 int64_t LROffset; 2768 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2769 IntKind == "ABORT") 2770 LROffset = 4; 2771 else if (IntKind == "SWI" || IntKind == "UNDEF") 2772 LROffset = 0; 2773 else 2774 report_fatal_error("Unsupported interrupt attribute. If present, value " 2775 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2776 2777 RetOps.insert(RetOps.begin() + 1, 2778 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2779 2780 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2781 } 2782 2783 SDValue 2784 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2785 bool isVarArg, 2786 const SmallVectorImpl<ISD::OutputArg> &Outs, 2787 const SmallVectorImpl<SDValue> &OutVals, 2788 const SDLoc &dl, SelectionDAG &DAG) const { 2789 // CCValAssign - represent the assignment of the return value to a location. 2790 SmallVector<CCValAssign, 16> RVLocs; 2791 2792 // CCState - Info about the registers and stack slots. 2793 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2794 *DAG.getContext()); 2795 2796 // Analyze outgoing return values. 2797 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2798 2799 SDValue Flag; 2800 SmallVector<SDValue, 4> RetOps; 2801 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2802 bool isLittleEndian = Subtarget->isLittle(); 2803 2804 MachineFunction &MF = DAG.getMachineFunction(); 2805 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2806 AFI->setReturnRegsCount(RVLocs.size()); 2807 2808 // Copy the result values into the output registers. 2809 for (unsigned i = 0, realRVLocIdx = 0; 2810 i != RVLocs.size(); 2811 ++i, ++realRVLocIdx) { 2812 CCValAssign &VA = RVLocs[i]; 2813 assert(VA.isRegLoc() && "Can only return in registers!"); 2814 2815 SDValue Arg = OutVals[realRVLocIdx]; 2816 bool ReturnF16 = false; 2817 2818 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2819 // Half-precision return values can be returned like this: 2820 // 2821 // t11 f16 = fadd ... 2822 // t12: i16 = bitcast t11 2823 // t13: i32 = zero_extend t12 2824 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2825 // 2826 // to avoid code generation for bitcasts, we simply set Arg to the node 2827 // that produces the f16 value, t11 in this case. 2828 // 2829 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2830 SDValue ZE = Arg.getOperand(0); 2831 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2832 SDValue BC = ZE.getOperand(0); 2833 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2834 Arg = BC.getOperand(0); 2835 ReturnF16 = true; 2836 } 2837 } 2838 } 2839 } 2840 2841 switch (VA.getLocInfo()) { 2842 default: llvm_unreachable("Unknown loc info!"); 2843 case CCValAssign::Full: break; 2844 case CCValAssign::BCvt: 2845 if (!ReturnF16) 2846 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2847 break; 2848 } 2849 2850 if (VA.needsCustom()) { 2851 if (VA.getLocVT() == MVT::v2f64) { 2852 // Extract the first half and return it in two registers. 2853 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2854 DAG.getConstant(0, dl, MVT::i32)); 2855 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2856 DAG.getVTList(MVT::i32, MVT::i32), Half); 2857 2858 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2859 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2860 Flag); 2861 Flag = Chain.getValue(1); 2862 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2863 VA = RVLocs[++i]; // skip ahead to next loc 2864 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2865 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2866 Flag); 2867 Flag = Chain.getValue(1); 2868 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2869 VA = RVLocs[++i]; // skip ahead to next loc 2870 2871 // Extract the 2nd half and fall through to handle it as an f64 value. 2872 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2873 DAG.getConstant(1, dl, MVT::i32)); 2874 } 2875 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2876 // available. 2877 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2878 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2879 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2880 fmrrd.getValue(isLittleEndian ? 0 : 1), 2881 Flag); 2882 Flag = Chain.getValue(1); 2883 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2884 VA = RVLocs[++i]; // skip ahead to next loc 2885 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2886 fmrrd.getValue(isLittleEndian ? 1 : 0), 2887 Flag); 2888 } else 2889 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2890 2891 // Guarantee that all emitted copies are 2892 // stuck together, avoiding something bad. 2893 Flag = Chain.getValue(1); 2894 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2895 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2896 } 2897 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2898 const MCPhysReg *I = 2899 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2900 if (I) { 2901 for (; *I; ++I) { 2902 if (ARM::GPRRegClass.contains(*I)) 2903 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2904 else if (ARM::DPRRegClass.contains(*I)) 2905 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2906 else 2907 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2908 } 2909 } 2910 2911 // Update chain and glue. 2912 RetOps[0] = Chain; 2913 if (Flag.getNode()) 2914 RetOps.push_back(Flag); 2915 2916 // CPUs which aren't M-class use a special sequence to return from 2917 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2918 // though we use "subs pc, lr, #N"). 2919 // 2920 // M-class CPUs actually use a normal return sequence with a special 2921 // (hardware-provided) value in LR, so the normal code path works. 2922 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2923 !Subtarget->isMClass()) { 2924 if (Subtarget->isThumb1Only()) 2925 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2926 return LowerInterruptReturn(RetOps, dl, DAG); 2927 } 2928 2929 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2930 } 2931 2932 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2933 if (N->getNumValues() != 1) 2934 return false; 2935 if (!N->hasNUsesOfValue(1, 0)) 2936 return false; 2937 2938 SDValue TCChain = Chain; 2939 SDNode *Copy = *N->use_begin(); 2940 if (Copy->getOpcode() == ISD::CopyToReg) { 2941 // If the copy has a glue operand, we conservatively assume it isn't safe to 2942 // perform a tail call. 2943 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2944 return false; 2945 TCChain = Copy->getOperand(0); 2946 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2947 SDNode *VMov = Copy; 2948 // f64 returned in a pair of GPRs. 2949 SmallPtrSet<SDNode*, 2> Copies; 2950 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2951 UI != UE; ++UI) { 2952 if (UI->getOpcode() != ISD::CopyToReg) 2953 return false; 2954 Copies.insert(*UI); 2955 } 2956 if (Copies.size() > 2) 2957 return false; 2958 2959 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2960 UI != UE; ++UI) { 2961 SDValue UseChain = UI->getOperand(0); 2962 if (Copies.count(UseChain.getNode())) 2963 // Second CopyToReg 2964 Copy = *UI; 2965 else { 2966 // We are at the top of this chain. 2967 // If the copy has a glue operand, we conservatively assume it 2968 // isn't safe to perform a tail call. 2969 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2970 return false; 2971 // First CopyToReg 2972 TCChain = UseChain; 2973 } 2974 } 2975 } else if (Copy->getOpcode() == ISD::BITCAST) { 2976 // f32 returned in a single GPR. 2977 if (!Copy->hasOneUse()) 2978 return false; 2979 Copy = *Copy->use_begin(); 2980 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2981 return false; 2982 // If the copy has a glue operand, we conservatively assume it isn't safe to 2983 // perform a tail call. 2984 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2985 return false; 2986 TCChain = Copy->getOperand(0); 2987 } else { 2988 return false; 2989 } 2990 2991 bool HasRet = false; 2992 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2993 UI != UE; ++UI) { 2994 if (UI->getOpcode() != ARMISD::RET_FLAG && 2995 UI->getOpcode() != ARMISD::INTRET_FLAG) 2996 return false; 2997 HasRet = true; 2998 } 2999 3000 if (!HasRet) 3001 return false; 3002 3003 Chain = TCChain; 3004 return true; 3005 } 3006 3007 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3008 if (!Subtarget->supportsTailCall()) 3009 return false; 3010 3011 if (!CI->isTailCall()) 3012 return false; 3013 3014 return true; 3015 } 3016 3017 // Trying to write a 64 bit value so need to split into two 32 bit values first, 3018 // and pass the lower and high parts through. 3019 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 3020 SDLoc DL(Op); 3021 SDValue WriteValue = Op->getOperand(2); 3022 3023 // This function is only supposed to be called for i64 type argument. 3024 assert(WriteValue.getValueType() == MVT::i64 3025 && "LowerWRITE_REGISTER called for non-i64 type argument."); 3026 3027 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3028 DAG.getConstant(0, DL, MVT::i32)); 3029 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3030 DAG.getConstant(1, DL, MVT::i32)); 3031 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 3032 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 3033 } 3034 3035 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 3036 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 3037 // one of the above mentioned nodes. It has to be wrapped because otherwise 3038 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 3039 // be used to form addressing mode. These wrapped nodes will be selected 3040 // into MOVi. 3041 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 3042 SelectionDAG &DAG) const { 3043 EVT PtrVT = Op.getValueType(); 3044 // FIXME there is no actual debug info here 3045 SDLoc dl(Op); 3046 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3047 SDValue Res; 3048 3049 // When generating execute-only code Constant Pools must be promoted to the 3050 // global data section. It's a bit ugly that we can't share them across basic 3051 // blocks, but this way we guarantee that execute-only behaves correct with 3052 // position-independent addressing modes. 3053 if (Subtarget->genExecuteOnly()) { 3054 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3055 auto T = const_cast<Type*>(CP->getType()); 3056 auto C = const_cast<Constant*>(CP->getConstVal()); 3057 auto M = const_cast<Module*>(DAG.getMachineFunction(). 3058 getFunction().getParent()); 3059 auto GV = new GlobalVariable( 3060 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 3061 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 3062 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 3063 Twine(AFI->createPICLabelUId()) 3064 ); 3065 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 3066 dl, PtrVT); 3067 return LowerGlobalAddress(GA, DAG); 3068 } 3069 3070 if (CP->isMachineConstantPoolEntry()) 3071 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 3072 CP->getAlignment()); 3073 else 3074 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 3075 CP->getAlignment()); 3076 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 3077 } 3078 3079 unsigned ARMTargetLowering::getJumpTableEncoding() const { 3080 return MachineJumpTableInfo::EK_Inline; 3081 } 3082 3083 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 3084 SelectionDAG &DAG) const { 3085 MachineFunction &MF = DAG.getMachineFunction(); 3086 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3087 unsigned ARMPCLabelIndex = 0; 3088 SDLoc DL(Op); 3089 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3090 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 3091 SDValue CPAddr; 3092 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 3093 if (!IsPositionIndependent) { 3094 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 3095 } else { 3096 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3097 ARMPCLabelIndex = AFI->createPICLabelUId(); 3098 ARMConstantPoolValue *CPV = 3099 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3100 ARMCP::CPBlockAddress, PCAdj); 3101 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3102 } 3103 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3104 SDValue Result = DAG.getLoad( 3105 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3106 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3107 if (!IsPositionIndependent) 3108 return Result; 3109 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3110 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3111 } 3112 3113 /// Convert a TLS address reference into the correct sequence of loads 3114 /// and calls to compute the variable's address for Darwin, and return an 3115 /// SDValue containing the final node. 3116 3117 /// Darwin only has one TLS scheme which must be capable of dealing with the 3118 /// fully general situation, in the worst case. This means: 3119 /// + "extern __thread" declaration. 3120 /// + Defined in a possibly unknown dynamic library. 3121 /// 3122 /// The general system is that each __thread variable has a [3 x i32] descriptor 3123 /// which contains information used by the runtime to calculate the address. The 3124 /// only part of this the compiler needs to know about is the first word, which 3125 /// contains a function pointer that must be called with the address of the 3126 /// entire descriptor in "r0". 3127 /// 3128 /// Since this descriptor may be in a different unit, in general access must 3129 /// proceed along the usual ARM rules. A common sequence to produce is: 3130 /// 3131 /// movw rT1, :lower16:_var$non_lazy_ptr 3132 /// movt rT1, :upper16:_var$non_lazy_ptr 3133 /// ldr r0, [rT1] 3134 /// ldr rT2, [r0] 3135 /// blx rT2 3136 /// [...address now in r0...] 3137 SDValue 3138 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3139 SelectionDAG &DAG) const { 3140 assert(Subtarget->isTargetDarwin() && 3141 "This function expects a Darwin target"); 3142 SDLoc DL(Op); 3143 3144 // First step is to get the address of the actua global symbol. This is where 3145 // the TLS descriptor lives. 3146 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3147 3148 // The first entry in the descriptor is a function pointer that we must call 3149 // to obtain the address of the variable. 3150 SDValue Chain = DAG.getEntryNode(); 3151 SDValue FuncTLVGet = DAG.getLoad( 3152 MVT::i32, DL, Chain, DescAddr, 3153 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3154 /* Alignment = */ 4, 3155 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3156 MachineMemOperand::MOInvariant); 3157 Chain = FuncTLVGet.getValue(1); 3158 3159 MachineFunction &F = DAG.getMachineFunction(); 3160 MachineFrameInfo &MFI = F.getFrameInfo(); 3161 MFI.setAdjustsStack(true); 3162 3163 // TLS calls preserve all registers except those that absolutely must be 3164 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3165 // silly). 3166 auto TRI = 3167 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3168 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3169 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3170 3171 // Finally, we can make the call. This is just a degenerate version of a 3172 // normal AArch64 call node: r0 takes the address of the descriptor, and 3173 // returns the address of the variable in this thread. 3174 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3175 Chain = 3176 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3177 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3178 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3179 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3180 } 3181 3182 SDValue 3183 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3184 SelectionDAG &DAG) const { 3185 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3186 3187 SDValue Chain = DAG.getEntryNode(); 3188 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3189 SDLoc DL(Op); 3190 3191 // Load the current TEB (thread environment block) 3192 SDValue Ops[] = {Chain, 3193 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3194 DAG.getTargetConstant(15, DL, MVT::i32), 3195 DAG.getTargetConstant(0, DL, MVT::i32), 3196 DAG.getTargetConstant(13, DL, MVT::i32), 3197 DAG.getTargetConstant(0, DL, MVT::i32), 3198 DAG.getTargetConstant(2, DL, MVT::i32)}; 3199 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3200 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3201 3202 SDValue TEB = CurrentTEB.getValue(0); 3203 Chain = CurrentTEB.getValue(1); 3204 3205 // Load the ThreadLocalStoragePointer from the TEB 3206 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3207 SDValue TLSArray = 3208 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3209 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3210 3211 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3212 // offset into the TLSArray. 3213 3214 // Load the TLS index from the C runtime 3215 SDValue TLSIndex = 3216 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3217 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3218 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3219 3220 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3221 DAG.getConstant(2, DL, MVT::i32)); 3222 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3223 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3224 MachinePointerInfo()); 3225 3226 // Get the offset of the start of the .tls section (section base) 3227 const auto *GA = cast<GlobalAddressSDNode>(Op); 3228 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3229 SDValue Offset = DAG.getLoad( 3230 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3231 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 3232 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3233 3234 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3235 } 3236 3237 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3238 SDValue 3239 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3240 SelectionDAG &DAG) const { 3241 SDLoc dl(GA); 3242 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3243 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3244 MachineFunction &MF = DAG.getMachineFunction(); 3245 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3246 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3247 ARMConstantPoolValue *CPV = 3248 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3249 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3250 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3251 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3252 Argument = DAG.getLoad( 3253 PtrVT, dl, DAG.getEntryNode(), Argument, 3254 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3255 SDValue Chain = Argument.getValue(1); 3256 3257 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3258 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3259 3260 // call __tls_get_addr. 3261 ArgListTy Args; 3262 ArgListEntry Entry; 3263 Entry.Node = Argument; 3264 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3265 Args.push_back(Entry); 3266 3267 // FIXME: is there useful debug info available here? 3268 TargetLowering::CallLoweringInfo CLI(DAG); 3269 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3270 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3271 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3272 3273 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3274 return CallResult.first; 3275 } 3276 3277 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3278 // "local exec" model. 3279 SDValue 3280 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3281 SelectionDAG &DAG, 3282 TLSModel::Model model) const { 3283 const GlobalValue *GV = GA->getGlobal(); 3284 SDLoc dl(GA); 3285 SDValue Offset; 3286 SDValue Chain = DAG.getEntryNode(); 3287 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3288 // Get the Thread Pointer 3289 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3290 3291 if (model == TLSModel::InitialExec) { 3292 MachineFunction &MF = DAG.getMachineFunction(); 3293 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3294 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3295 // Initial exec model. 3296 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3297 ARMConstantPoolValue *CPV = 3298 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3299 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3300 true); 3301 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3302 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3303 Offset = DAG.getLoad( 3304 PtrVT, dl, Chain, Offset, 3305 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3306 Chain = Offset.getValue(1); 3307 3308 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3309 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3310 3311 Offset = DAG.getLoad( 3312 PtrVT, dl, Chain, Offset, 3313 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3314 } else { 3315 // local exec model 3316 assert(model == TLSModel::LocalExec); 3317 ARMConstantPoolValue *CPV = 3318 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3319 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3320 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3321 Offset = DAG.getLoad( 3322 PtrVT, dl, Chain, Offset, 3323 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3324 } 3325 3326 // The address of the thread local variable is the add of the thread 3327 // pointer with the offset of the variable. 3328 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3329 } 3330 3331 SDValue 3332 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3333 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3334 if (DAG.getTarget().useEmulatedTLS()) 3335 return LowerToTLSEmulatedModel(GA, DAG); 3336 3337 if (Subtarget->isTargetDarwin()) 3338 return LowerGlobalTLSAddressDarwin(Op, DAG); 3339 3340 if (Subtarget->isTargetWindows()) 3341 return LowerGlobalTLSAddressWindows(Op, DAG); 3342 3343 // TODO: implement the "local dynamic" model 3344 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3345 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3346 3347 switch (model) { 3348 case TLSModel::GeneralDynamic: 3349 case TLSModel::LocalDynamic: 3350 return LowerToTLSGeneralDynamicModel(GA, DAG); 3351 case TLSModel::InitialExec: 3352 case TLSModel::LocalExec: 3353 return LowerToTLSExecModels(GA, DAG, model); 3354 } 3355 llvm_unreachable("bogus TLS model"); 3356 } 3357 3358 /// Return true if all users of V are within function F, looking through 3359 /// ConstantExprs. 3360 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3361 SmallVector<const User*,4> Worklist; 3362 for (auto *U : V->users()) 3363 Worklist.push_back(U); 3364 while (!Worklist.empty()) { 3365 auto *U = Worklist.pop_back_val(); 3366 if (isa<ConstantExpr>(U)) { 3367 for (auto *UU : U->users()) 3368 Worklist.push_back(UU); 3369 continue; 3370 } 3371 3372 auto *I = dyn_cast<Instruction>(U); 3373 if (!I || I->getParent()->getParent() != F) 3374 return false; 3375 } 3376 return true; 3377 } 3378 3379 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3380 const GlobalValue *GV, SelectionDAG &DAG, 3381 EVT PtrVT, const SDLoc &dl) { 3382 // If we're creating a pool entry for a constant global with unnamed address, 3383 // and the global is small enough, we can emit it inline into the constant pool 3384 // to save ourselves an indirection. 3385 // 3386 // This is a win if the constant is only used in one function (so it doesn't 3387 // need to be duplicated) or duplicating the constant wouldn't increase code 3388 // size (implying the constant is no larger than 4 bytes). 3389 const Function &F = DAG.getMachineFunction().getFunction(); 3390 3391 // We rely on this decision to inline being idemopotent and unrelated to the 3392 // use-site. We know that if we inline a variable at one use site, we'll 3393 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3394 // doesn't know about this optimization, so bail out if it's enabled else 3395 // we could decide to inline here (and thus never emit the GV) but require 3396 // the GV from fast-isel generated code. 3397 if (!EnableConstpoolPromotion || 3398 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3399 return SDValue(); 3400 3401 auto *GVar = dyn_cast<GlobalVariable>(GV); 3402 if (!GVar || !GVar->hasInitializer() || 3403 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3404 !GVar->hasLocalLinkage()) 3405 return SDValue(); 3406 3407 // If we inline a value that contains relocations, we move the relocations 3408 // from .data to .text. This is not allowed in position-independent code. 3409 auto *Init = GVar->getInitializer(); 3410 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3411 Init->needsRelocation()) 3412 return SDValue(); 3413 3414 // The constant islands pass can only really deal with alignment requests 3415 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3416 // any type wanting greater alignment requirements than 4 bytes. We also 3417 // can only promote constants that are multiples of 4 bytes in size or 3418 // are paddable to a multiple of 4. Currently we only try and pad constants 3419 // that are strings for simplicity. 3420 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3421 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3422 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3423 unsigned RequiredPadding = 4 - (Size % 4); 3424 bool PaddingPossible = 3425 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3426 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3427 Size == 0) 3428 return SDValue(); 3429 3430 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3431 MachineFunction &MF = DAG.getMachineFunction(); 3432 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3433 3434 // We can't bloat the constant pool too much, else the ConstantIslands pass 3435 // may fail to converge. If we haven't promoted this global yet (it may have 3436 // multiple uses), and promoting it would increase the constant pool size (Sz 3437 // > 4), ensure we have space to do so up to MaxTotal. 3438 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3439 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3440 ConstpoolPromotionMaxTotal) 3441 return SDValue(); 3442 3443 // This is only valid if all users are in a single function; we can't clone 3444 // the constant in general. The LLVM IR unnamed_addr allows merging 3445 // constants, but not cloning them. 3446 // 3447 // We could potentially allow cloning if we could prove all uses of the 3448 // constant in the current function don't care about the address, like 3449 // printf format strings. But that isn't implemented for now. 3450 if (!allUsersAreInFunction(GVar, &F)) 3451 return SDValue(); 3452 3453 // We're going to inline this global. Pad it out if needed. 3454 if (RequiredPadding != 4) { 3455 StringRef S = CDAInit->getAsString(); 3456 3457 SmallVector<uint8_t,16> V(S.size()); 3458 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3459 while (RequiredPadding--) 3460 V.push_back(0); 3461 Init = ConstantDataArray::get(*DAG.getContext(), V); 3462 } 3463 3464 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3465 SDValue CPAddr = 3466 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3467 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3468 AFI->markGlobalAsPromotedToConstantPool(GVar); 3469 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3470 PaddedSize - 4); 3471 } 3472 ++NumConstpoolPromoted; 3473 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3474 } 3475 3476 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3477 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3478 if (!(GV = GA->getBaseObject())) 3479 return false; 3480 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3481 return V->isConstant(); 3482 return isa<Function>(GV); 3483 } 3484 3485 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3486 SelectionDAG &DAG) const { 3487 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3488 default: llvm_unreachable("unknown object format"); 3489 case Triple::COFF: 3490 return LowerGlobalAddressWindows(Op, DAG); 3491 case Triple::ELF: 3492 return LowerGlobalAddressELF(Op, DAG); 3493 case Triple::MachO: 3494 return LowerGlobalAddressDarwin(Op, DAG); 3495 } 3496 } 3497 3498 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3499 SelectionDAG &DAG) const { 3500 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3501 SDLoc dl(Op); 3502 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3503 const TargetMachine &TM = getTargetMachine(); 3504 bool IsRO = isReadOnly(GV); 3505 3506 // promoteToConstantPool only if not generating XO text section 3507 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3508 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3509 return V; 3510 3511 if (isPositionIndependent()) { 3512 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3513 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3514 UseGOT_PREL ? ARMII::MO_GOT : 0); 3515 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3516 if (UseGOT_PREL) 3517 Result = 3518 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3519 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3520 return Result; 3521 } else if (Subtarget->isROPI() && IsRO) { 3522 // PC-relative. 3523 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3524 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3525 return Result; 3526 } else if (Subtarget->isRWPI() && !IsRO) { 3527 // SB-relative. 3528 SDValue RelAddr; 3529 if (Subtarget->useMovt()) { 3530 ++NumMovwMovt; 3531 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3532 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3533 } else { // use literal pool for address constant 3534 ARMConstantPoolValue *CPV = 3535 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3536 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3537 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3538 RelAddr = DAG.getLoad( 3539 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3540 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3541 } 3542 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3543 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3544 return Result; 3545 } 3546 3547 // If we have T2 ops, we can materialize the address directly via movt/movw 3548 // pair. This is always cheaper. 3549 if (Subtarget->useMovt()) { 3550 ++NumMovwMovt; 3551 // FIXME: Once remat is capable of dealing with instructions with register 3552 // operands, expand this into two nodes. 3553 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3554 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3555 } else { 3556 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3557 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3558 return DAG.getLoad( 3559 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3560 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3561 } 3562 } 3563 3564 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3565 SelectionDAG &DAG) const { 3566 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3567 "ROPI/RWPI not currently supported for Darwin"); 3568 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3569 SDLoc dl(Op); 3570 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3571 3572 if (Subtarget->useMovt()) 3573 ++NumMovwMovt; 3574 3575 // FIXME: Once remat is capable of dealing with instructions with register 3576 // operands, expand this into multiple nodes 3577 unsigned Wrapper = 3578 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3579 3580 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3581 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3582 3583 if (Subtarget->isGVIndirectSymbol(GV)) 3584 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3585 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3586 return Result; 3587 } 3588 3589 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3590 SelectionDAG &DAG) const { 3591 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3592 assert(Subtarget->useMovt() && 3593 "Windows on ARM expects to use movw/movt"); 3594 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3595 "ROPI/RWPI not currently supported for Windows"); 3596 3597 const TargetMachine &TM = getTargetMachine(); 3598 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3599 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3600 if (GV->hasDLLImportStorageClass()) 3601 TargetFlags = ARMII::MO_DLLIMPORT; 3602 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3603 TargetFlags = ARMII::MO_COFFSTUB; 3604 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3605 SDValue Result; 3606 SDLoc DL(Op); 3607 3608 ++NumMovwMovt; 3609 3610 // FIXME: Once remat is capable of dealing with instructions with register 3611 // operands, expand this into two nodes. 3612 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3613 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3614 TargetFlags)); 3615 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3616 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3617 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3618 return Result; 3619 } 3620 3621 SDValue 3622 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3623 SDLoc dl(Op); 3624 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3625 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3626 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3627 Op.getOperand(1), Val); 3628 } 3629 3630 SDValue 3631 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3632 SDLoc dl(Op); 3633 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3634 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3635 } 3636 3637 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3638 SelectionDAG &DAG) const { 3639 SDLoc dl(Op); 3640 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3641 Op.getOperand(0)); 3642 } 3643 3644 SDValue ARMTargetLowering::LowerINTRINSIC_VOID( 3645 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const { 3646 unsigned IntNo = 3647 cast<ConstantSDNode>( 3648 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other)) 3649 ->getZExtValue(); 3650 switch (IntNo) { 3651 default: 3652 return SDValue(); // Don't custom lower most intrinsics. 3653 case Intrinsic::arm_gnu_eabi_mcount: { 3654 MachineFunction &MF = DAG.getMachineFunction(); 3655 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3656 SDLoc dl(Op); 3657 SDValue Chain = Op.getOperand(0); 3658 // call "\01__gnu_mcount_nc" 3659 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 3660 const uint32_t *Mask = 3661 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3662 assert(Mask && "Missing call preserved mask for calling convention"); 3663 // Mark LR an implicit live-in. 3664 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3665 SDValue ReturnAddress = 3666 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT); 3667 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue}; 3668 SDValue Callee = 3669 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0); 3670 SDValue RegisterMask = DAG.getRegisterMask(Mask); 3671 if (Subtarget->isThumb()) 3672 return SDValue( 3673 DAG.getMachineNode( 3674 ARM::tBL_PUSHLR, dl, ResultTys, 3675 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT), 3676 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}), 3677 0); 3678 return SDValue( 3679 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys, 3680 {ReturnAddress, Callee, RegisterMask, Chain}), 3681 0); 3682 } 3683 } 3684 } 3685 3686 SDValue 3687 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3688 const ARMSubtarget *Subtarget) const { 3689 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3690 SDLoc dl(Op); 3691 switch (IntNo) { 3692 default: return SDValue(); // Don't custom lower most intrinsics. 3693 case Intrinsic::thread_pointer: { 3694 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3695 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3696 } 3697 case Intrinsic::arm_cls: { 3698 const SDValue &Operand = Op.getOperand(1); 3699 const EVT VTy = Op.getValueType(); 3700 SDValue SRA = 3701 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy)); 3702 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand); 3703 SDValue SHL = 3704 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy)); 3705 SDValue OR = 3706 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy)); 3707 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR); 3708 return Result; 3709 } 3710 case Intrinsic::arm_cls64: { 3711 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x)) 3712 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x))) 3713 const SDValue &Operand = Op.getOperand(1); 3714 const EVT VTy = Op.getValueType(); 3715 3716 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3717 DAG.getConstant(1, dl, VTy)); 3718 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3719 DAG.getConstant(0, dl, VTy)); 3720 SDValue Constant0 = DAG.getConstant(0, dl, VTy); 3721 SDValue Constant1 = DAG.getConstant(1, dl, VTy); 3722 SDValue Constant31 = DAG.getConstant(31, dl, VTy); 3723 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31); 3724 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi); 3725 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1); 3726 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1); 3727 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi); 3728 SDValue CheckLo = 3729 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ); 3730 SDValue HiIsZero = 3731 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ); 3732 SDValue AdjustedLo = 3733 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy)); 3734 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo); 3735 SDValue Result = 3736 DAG.getSelect(dl, VTy, CheckLo, 3737 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi); 3738 return Result; 3739 } 3740 case Intrinsic::eh_sjlj_lsda: { 3741 MachineFunction &MF = DAG.getMachineFunction(); 3742 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3743 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3744 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3745 SDValue CPAddr; 3746 bool IsPositionIndependent = isPositionIndependent(); 3747 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3748 ARMConstantPoolValue *CPV = 3749 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3750 ARMCP::CPLSDA, PCAdj); 3751 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3752 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3753 SDValue Result = DAG.getLoad( 3754 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3755 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3756 3757 if (IsPositionIndependent) { 3758 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3759 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3760 } 3761 return Result; 3762 } 3763 case Intrinsic::arm_neon_vabs: 3764 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3765 Op.getOperand(1)); 3766 case Intrinsic::arm_neon_vmulls: 3767 case Intrinsic::arm_neon_vmullu: { 3768 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3769 ? ARMISD::VMULLs : ARMISD::VMULLu; 3770 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3771 Op.getOperand(1), Op.getOperand(2)); 3772 } 3773 case Intrinsic::arm_neon_vminnm: 3774 case Intrinsic::arm_neon_vmaxnm: { 3775 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3776 ? ISD::FMINNUM : ISD::FMAXNUM; 3777 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3778 Op.getOperand(1), Op.getOperand(2)); 3779 } 3780 case Intrinsic::arm_neon_vminu: 3781 case Intrinsic::arm_neon_vmaxu: { 3782 if (Op.getValueType().isFloatingPoint()) 3783 return SDValue(); 3784 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3785 ? ISD::UMIN : ISD::UMAX; 3786 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3787 Op.getOperand(1), Op.getOperand(2)); 3788 } 3789 case Intrinsic::arm_neon_vmins: 3790 case Intrinsic::arm_neon_vmaxs: { 3791 // v{min,max}s is overloaded between signed integers and floats. 3792 if (!Op.getValueType().isFloatingPoint()) { 3793 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3794 ? ISD::SMIN : ISD::SMAX; 3795 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3796 Op.getOperand(1), Op.getOperand(2)); 3797 } 3798 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3799 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3800 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3801 Op.getOperand(1), Op.getOperand(2)); 3802 } 3803 case Intrinsic::arm_neon_vtbl1: 3804 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3805 Op.getOperand(1), Op.getOperand(2)); 3806 case Intrinsic::arm_neon_vtbl2: 3807 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3808 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3809 case Intrinsic::arm_mve_pred_i2v: 3810 case Intrinsic::arm_mve_pred_v2i: 3811 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(), 3812 Op.getOperand(1)); 3813 case Intrinsic::arm_mve_vreinterpretq: 3814 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(), 3815 Op.getOperand(1)); 3816 case Intrinsic::arm_mve_lsll: 3817 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(), 3818 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3819 case Intrinsic::arm_mve_asrl: 3820 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(), 3821 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3822 } 3823 } 3824 3825 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3826 const ARMSubtarget *Subtarget) { 3827 SDLoc dl(Op); 3828 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3829 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3830 if (SSID == SyncScope::SingleThread) 3831 return Op; 3832 3833 if (!Subtarget->hasDataBarrier()) { 3834 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3835 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3836 // here. 3837 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3838 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3839 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3840 DAG.getConstant(0, dl, MVT::i32)); 3841 } 3842 3843 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3844 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3845 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3846 if (Subtarget->isMClass()) { 3847 // Only a full system barrier exists in the M-class architectures. 3848 Domain = ARM_MB::SY; 3849 } else if (Subtarget->preferISHSTBarriers() && 3850 Ord == AtomicOrdering::Release) { 3851 // Swift happens to implement ISHST barriers in a way that's compatible with 3852 // Release semantics but weaker than ISH so we'd be fools not to use 3853 // it. Beware: other processors probably don't! 3854 Domain = ARM_MB::ISHST; 3855 } 3856 3857 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3858 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3859 DAG.getConstant(Domain, dl, MVT::i32)); 3860 } 3861 3862 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3863 const ARMSubtarget *Subtarget) { 3864 // ARM pre v5TE and Thumb1 does not have preload instructions. 3865 if (!(Subtarget->isThumb2() || 3866 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3867 // Just preserve the chain. 3868 return Op.getOperand(0); 3869 3870 SDLoc dl(Op); 3871 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3872 if (!isRead && 3873 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3874 // ARMv7 with MP extension has PLDW. 3875 return Op.getOperand(0); 3876 3877 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3878 if (Subtarget->isThumb()) { 3879 // Invert the bits. 3880 isRead = ~isRead & 1; 3881 isData = ~isData & 1; 3882 } 3883 3884 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3885 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3886 DAG.getConstant(isData, dl, MVT::i32)); 3887 } 3888 3889 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3890 MachineFunction &MF = DAG.getMachineFunction(); 3891 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3892 3893 // vastart just stores the address of the VarArgsFrameIndex slot into the 3894 // memory location argument. 3895 SDLoc dl(Op); 3896 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3897 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3898 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3899 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3900 MachinePointerInfo(SV)); 3901 } 3902 3903 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3904 CCValAssign &NextVA, 3905 SDValue &Root, 3906 SelectionDAG &DAG, 3907 const SDLoc &dl) const { 3908 MachineFunction &MF = DAG.getMachineFunction(); 3909 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3910 3911 const TargetRegisterClass *RC; 3912 if (AFI->isThumb1OnlyFunction()) 3913 RC = &ARM::tGPRRegClass; 3914 else 3915 RC = &ARM::GPRRegClass; 3916 3917 // Transform the arguments stored in physical registers into virtual ones. 3918 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3919 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3920 3921 SDValue ArgValue2; 3922 if (NextVA.isMemLoc()) { 3923 MachineFrameInfo &MFI = MF.getFrameInfo(); 3924 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3925 3926 // Create load node to retrieve arguments from the stack. 3927 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3928 ArgValue2 = DAG.getLoad( 3929 MVT::i32, dl, Root, FIN, 3930 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3931 } else { 3932 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3933 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3934 } 3935 if (!Subtarget->isLittle()) 3936 std::swap (ArgValue, ArgValue2); 3937 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3938 } 3939 3940 // The remaining GPRs hold either the beginning of variable-argument 3941 // data, or the beginning of an aggregate passed by value (usually 3942 // byval). Either way, we allocate stack slots adjacent to the data 3943 // provided by our caller, and store the unallocated registers there. 3944 // If this is a variadic function, the va_list pointer will begin with 3945 // these values; otherwise, this reassembles a (byval) structure that 3946 // was split between registers and memory. 3947 // Return: The frame index registers were stored into. 3948 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3949 const SDLoc &dl, SDValue &Chain, 3950 const Value *OrigArg, 3951 unsigned InRegsParamRecordIdx, 3952 int ArgOffset, unsigned ArgSize) const { 3953 // Currently, two use-cases possible: 3954 // Case #1. Non-var-args function, and we meet first byval parameter. 3955 // Setup first unallocated register as first byval register; 3956 // eat all remained registers 3957 // (these two actions are performed by HandleByVal method). 3958 // Then, here, we initialize stack frame with 3959 // "store-reg" instructions. 3960 // Case #2. Var-args function, that doesn't contain byval parameters. 3961 // The same: eat all remained unallocated registers, 3962 // initialize stack frame. 3963 3964 MachineFunction &MF = DAG.getMachineFunction(); 3965 MachineFrameInfo &MFI = MF.getFrameInfo(); 3966 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3967 unsigned RBegin, REnd; 3968 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3969 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3970 } else { 3971 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3972 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3973 REnd = ARM::R4; 3974 } 3975 3976 if (REnd != RBegin) 3977 ArgOffset = -4 * (ARM::R4 - RBegin); 3978 3979 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3980 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3981 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3982 3983 SmallVector<SDValue, 4> MemOps; 3984 const TargetRegisterClass *RC = 3985 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3986 3987 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3988 unsigned VReg = MF.addLiveIn(Reg, RC); 3989 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3990 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3991 MachinePointerInfo(OrigArg, 4 * i)); 3992 MemOps.push_back(Store); 3993 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3994 } 3995 3996 if (!MemOps.empty()) 3997 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3998 return FrameIndex; 3999 } 4000 4001 // Setup stack frame, the va_list pointer will start from. 4002 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 4003 const SDLoc &dl, SDValue &Chain, 4004 unsigned ArgOffset, 4005 unsigned TotalArgRegsSaveSize, 4006 bool ForceMutable) const { 4007 MachineFunction &MF = DAG.getMachineFunction(); 4008 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4009 4010 // Try to store any remaining integer argument regs 4011 // to their spots on the stack so that they may be loaded by dereferencing 4012 // the result of va_next. 4013 // If there is no regs to be stored, just point address after last 4014 // argument passed via stack. 4015 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 4016 CCInfo.getInRegsParamsCount(), 4017 CCInfo.getNextStackOffset(), 4018 std::max(4U, TotalArgRegsSaveSize)); 4019 AFI->setVarArgsFrameIndex(FrameIndex); 4020 } 4021 4022 SDValue ARMTargetLowering::LowerFormalArguments( 4023 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4024 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4025 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4026 MachineFunction &MF = DAG.getMachineFunction(); 4027 MachineFrameInfo &MFI = MF.getFrameInfo(); 4028 4029 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4030 4031 // Assign locations to all of the incoming arguments. 4032 SmallVector<CCValAssign, 16> ArgLocs; 4033 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4034 *DAG.getContext()); 4035 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 4036 4037 SmallVector<SDValue, 16> ArgValues; 4038 SDValue ArgValue; 4039 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4040 unsigned CurArgIdx = 0; 4041 4042 // Initially ArgRegsSaveSize is zero. 4043 // Then we increase this value each time we meet byval parameter. 4044 // We also increase this value in case of varargs function. 4045 AFI->setArgRegsSaveSize(0); 4046 4047 // Calculate the amount of stack space that we need to allocate to store 4048 // byval and variadic arguments that are passed in registers. 4049 // We need to know this before we allocate the first byval or variadic 4050 // argument, as they will be allocated a stack slot below the CFA (Canonical 4051 // Frame Address, the stack pointer at entry to the function). 4052 unsigned ArgRegBegin = ARM::R4; 4053 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4054 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 4055 break; 4056 4057 CCValAssign &VA = ArgLocs[i]; 4058 unsigned Index = VA.getValNo(); 4059 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 4060 if (!Flags.isByVal()) 4061 continue; 4062 4063 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 4064 unsigned RBegin, REnd; 4065 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 4066 ArgRegBegin = std::min(ArgRegBegin, RBegin); 4067 4068 CCInfo.nextInRegsParam(); 4069 } 4070 CCInfo.rewindByValRegsInfo(); 4071 4072 int lastInsIndex = -1; 4073 if (isVarArg && MFI.hasVAStart()) { 4074 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4075 if (RegIdx != array_lengthof(GPRArgRegs)) 4076 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 4077 } 4078 4079 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 4080 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 4081 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4082 4083 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4084 CCValAssign &VA = ArgLocs[i]; 4085 if (Ins[VA.getValNo()].isOrigArg()) { 4086 std::advance(CurOrigArg, 4087 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 4088 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 4089 } 4090 // Arguments stored in registers. 4091 if (VA.isRegLoc()) { 4092 EVT RegVT = VA.getLocVT(); 4093 4094 if (VA.needsCustom()) { 4095 // f64 and vector types are split up into multiple registers or 4096 // combinations of registers and stack slots. 4097 if (VA.getLocVT() == MVT::v2f64) { 4098 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 4099 Chain, DAG, dl); 4100 VA = ArgLocs[++i]; // skip ahead to next loc 4101 SDValue ArgValue2; 4102 if (VA.isMemLoc()) { 4103 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 4104 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4105 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 4106 MachinePointerInfo::getFixedStack( 4107 DAG.getMachineFunction(), FI)); 4108 } else { 4109 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 4110 Chain, DAG, dl); 4111 } 4112 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 4113 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 4114 ArgValue, ArgValue1, 4115 DAG.getIntPtrConstant(0, dl)); 4116 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 4117 ArgValue, ArgValue2, 4118 DAG.getIntPtrConstant(1, dl)); 4119 } else 4120 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4121 } else { 4122 const TargetRegisterClass *RC; 4123 4124 4125 if (RegVT == MVT::f16) 4126 RC = &ARM::HPRRegClass; 4127 else if (RegVT == MVT::f32) 4128 RC = &ARM::SPRRegClass; 4129 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 4130 RC = &ARM::DPRRegClass; 4131 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 4132 RC = &ARM::QPRRegClass; 4133 else if (RegVT == MVT::i32) 4134 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 4135 : &ARM::GPRRegClass; 4136 else 4137 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4138 4139 // Transform the arguments in physical registers into virtual ones. 4140 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4141 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 4142 4143 // If this value is passed in r0 and has the returned attribute (e.g. 4144 // C++ 'structors), record this fact for later use. 4145 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 4146 AFI->setPreservesR0(); 4147 } 4148 } 4149 4150 // If this is an 8 or 16-bit value, it is really passed promoted 4151 // to 32 bits. Insert an assert[sz]ext to capture this, then 4152 // truncate to the right size. 4153 switch (VA.getLocInfo()) { 4154 default: llvm_unreachable("Unknown loc info!"); 4155 case CCValAssign::Full: break; 4156 case CCValAssign::BCvt: 4157 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 4158 break; 4159 case CCValAssign::SExt: 4160 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 4161 DAG.getValueType(VA.getValVT())); 4162 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4163 break; 4164 case CCValAssign::ZExt: 4165 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 4166 DAG.getValueType(VA.getValVT())); 4167 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4168 break; 4169 } 4170 4171 InVals.push_back(ArgValue); 4172 } else { // VA.isRegLoc() 4173 // sanity check 4174 assert(VA.isMemLoc()); 4175 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 4176 4177 int index = VA.getValNo(); 4178 4179 // Some Ins[] entries become multiple ArgLoc[] entries. 4180 // Process them only once. 4181 if (index != lastInsIndex) 4182 { 4183 ISD::ArgFlagsTy Flags = Ins[index].Flags; 4184 // FIXME: For now, all byval parameter objects are marked mutable. 4185 // This can be changed with more analysis. 4186 // In case of tail call optimization mark all arguments mutable. 4187 // Since they could be overwritten by lowering of arguments in case of 4188 // a tail call. 4189 if (Flags.isByVal()) { 4190 assert(Ins[index].isOrigArg() && 4191 "Byval arguments cannot be implicit"); 4192 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 4193 4194 int FrameIndex = StoreByValRegs( 4195 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4196 VA.getLocMemOffset(), Flags.getByValSize()); 4197 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4198 CCInfo.nextInRegsParam(); 4199 } else { 4200 unsigned FIOffset = VA.getLocMemOffset(); 4201 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4202 FIOffset, true); 4203 4204 // Create load nodes to retrieve arguments from the stack. 4205 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4206 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4207 MachinePointerInfo::getFixedStack( 4208 DAG.getMachineFunction(), FI))); 4209 } 4210 lastInsIndex = index; 4211 } 4212 } 4213 } 4214 4215 // varargs 4216 if (isVarArg && MFI.hasVAStart()) 4217 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 4218 CCInfo.getNextStackOffset(), 4219 TotalArgRegsSaveSize); 4220 4221 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4222 4223 return Chain; 4224 } 4225 4226 /// isFloatingPointZero - Return true if this is +0.0. 4227 static bool isFloatingPointZero(SDValue Op) { 4228 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4229 return CFP->getValueAPF().isPosZero(); 4230 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4231 // Maybe this has already been legalized into the constant pool? 4232 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4233 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4234 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4235 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4236 return CFP->getValueAPF().isPosZero(); 4237 } 4238 } else if (Op->getOpcode() == ISD::BITCAST && 4239 Op->getValueType(0) == MVT::f64) { 4240 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4241 // created by LowerConstantFP(). 4242 SDValue BitcastOp = Op->getOperand(0); 4243 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4244 isNullConstant(BitcastOp->getOperand(0))) 4245 return true; 4246 } 4247 return false; 4248 } 4249 4250 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4251 /// the given operands. 4252 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4253 SDValue &ARMcc, SelectionDAG &DAG, 4254 const SDLoc &dl) const { 4255 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4256 unsigned C = RHSC->getZExtValue(); 4257 if (!isLegalICmpImmediate((int32_t)C)) { 4258 // Constant does not fit, try adjusting it by one. 4259 switch (CC) { 4260 default: break; 4261 case ISD::SETLT: 4262 case ISD::SETGE: 4263 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4264 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4265 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4266 } 4267 break; 4268 case ISD::SETULT: 4269 case ISD::SETUGE: 4270 if (C != 0 && isLegalICmpImmediate(C-1)) { 4271 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4272 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4273 } 4274 break; 4275 case ISD::SETLE: 4276 case ISD::SETGT: 4277 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4278 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4279 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4280 } 4281 break; 4282 case ISD::SETULE: 4283 case ISD::SETUGT: 4284 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4285 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4286 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4287 } 4288 break; 4289 } 4290 } 4291 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4292 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4293 // In ARM and Thumb-2, the compare instructions can shift their second 4294 // operand. 4295 CC = ISD::getSetCCSwappedOperands(CC); 4296 std::swap(LHS, RHS); 4297 } 4298 4299 // Thumb1 has very limited immediate modes, so turning an "and" into a 4300 // shift can save multiple instructions. 4301 // 4302 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4303 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4304 // own. If it's the operand to an unsigned comparison with an immediate, 4305 // we can eliminate one of the shifts: we transform 4306 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4307 // 4308 // We avoid transforming cases which aren't profitable due to encoding 4309 // details: 4310 // 4311 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4312 // would not; in that case, we're essentially trading one immediate load for 4313 // another. 4314 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4315 // 3. C2 is zero; we have other code for this special case. 4316 // 4317 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4318 // instruction, since the AND is always one instruction anyway, but we could 4319 // use narrow instructions in some cases. 4320 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4321 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4322 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4323 !isSignedIntSetCC(CC)) { 4324 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4325 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4326 uint64_t RHSV = RHSC->getZExtValue(); 4327 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4328 unsigned ShiftBits = countLeadingZeros(Mask); 4329 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4330 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4331 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4332 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4333 } 4334 } 4335 } 4336 4337 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4338 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4339 // way a cmp would. 4340 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4341 // some tweaks to the heuristics for the previous and->shift transform. 4342 // FIXME: Optimize cases where the LHS isn't a shift. 4343 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4344 isa<ConstantSDNode>(RHS) && 4345 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4346 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4347 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4348 unsigned ShiftAmt = 4349 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4350 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4351 DAG.getVTList(MVT::i32, MVT::i32), 4352 LHS.getOperand(0), 4353 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4354 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4355 Shift.getValue(1), SDValue()); 4356 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4357 return Chain.getValue(1); 4358 } 4359 4360 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4361 4362 // If the RHS is a constant zero then the V (overflow) flag will never be 4363 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4364 // simpler for other passes (like the peephole optimiser) to deal with. 4365 if (isNullConstant(RHS)) { 4366 switch (CondCode) { 4367 default: break; 4368 case ARMCC::GE: 4369 CondCode = ARMCC::PL; 4370 break; 4371 case ARMCC::LT: 4372 CondCode = ARMCC::MI; 4373 break; 4374 } 4375 } 4376 4377 ARMISD::NodeType CompareType; 4378 switch (CondCode) { 4379 default: 4380 CompareType = ARMISD::CMP; 4381 break; 4382 case ARMCC::EQ: 4383 case ARMCC::NE: 4384 // Uses only Z Flag 4385 CompareType = ARMISD::CMPZ; 4386 break; 4387 } 4388 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4389 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4390 } 4391 4392 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4393 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4394 SelectionDAG &DAG, const SDLoc &dl, 4395 bool Signaling) const { 4396 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4397 SDValue Cmp; 4398 if (!isFloatingPointZero(RHS)) 4399 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, 4400 dl, MVT::Glue, LHS, RHS); 4401 else 4402 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, 4403 dl, MVT::Glue, LHS); 4404 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4405 } 4406 4407 /// duplicateCmp - Glue values can have only one use, so this function 4408 /// duplicates a comparison node. 4409 SDValue 4410 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4411 unsigned Opc = Cmp.getOpcode(); 4412 SDLoc DL(Cmp); 4413 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4414 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4415 4416 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4417 Cmp = Cmp.getOperand(0); 4418 Opc = Cmp.getOpcode(); 4419 if (Opc == ARMISD::CMPFP) 4420 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4421 else { 4422 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4423 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 4424 } 4425 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4426 } 4427 4428 // This function returns three things: the arithmetic computation itself 4429 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4430 // comparison and the condition code define the case in which the arithmetic 4431 // computation *does not* overflow. 4432 std::pair<SDValue, SDValue> 4433 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4434 SDValue &ARMcc) const { 4435 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4436 4437 SDValue Value, OverflowCmp; 4438 SDValue LHS = Op.getOperand(0); 4439 SDValue RHS = Op.getOperand(1); 4440 SDLoc dl(Op); 4441 4442 // FIXME: We are currently always generating CMPs because we don't support 4443 // generating CMN through the backend. This is not as good as the natural 4444 // CMP case because it causes a register dependency and cannot be folded 4445 // later. 4446 4447 switch (Op.getOpcode()) { 4448 default: 4449 llvm_unreachable("Unknown overflow instruction!"); 4450 case ISD::SADDO: 4451 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4452 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4453 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4454 break; 4455 case ISD::UADDO: 4456 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4457 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4458 // We do not use it in the USUBO case as Value may not be used. 4459 Value = DAG.getNode(ARMISD::ADDC, dl, 4460 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4461 .getValue(0); 4462 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4463 break; 4464 case ISD::SSUBO: 4465 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4466 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4467 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4468 break; 4469 case ISD::USUBO: 4470 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4471 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4472 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4473 break; 4474 case ISD::UMULO: 4475 // We generate a UMUL_LOHI and then check if the high word is 0. 4476 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4477 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4478 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4479 LHS, RHS); 4480 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4481 DAG.getConstant(0, dl, MVT::i32)); 4482 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4483 break; 4484 case ISD::SMULO: 4485 // We generate a SMUL_LOHI and then check if all the bits of the high word 4486 // are the same as the sign bit of the low word. 4487 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4488 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4489 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4490 LHS, RHS); 4491 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4492 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4493 Value.getValue(0), 4494 DAG.getConstant(31, dl, MVT::i32))); 4495 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4496 break; 4497 } // switch (...) 4498 4499 return std::make_pair(Value, OverflowCmp); 4500 } 4501 4502 SDValue 4503 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4504 // Let legalize expand this if it isn't a legal type yet. 4505 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4506 return SDValue(); 4507 4508 SDValue Value, OverflowCmp; 4509 SDValue ARMcc; 4510 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4511 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4512 SDLoc dl(Op); 4513 // We use 0 and 1 as false and true values. 4514 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4515 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4516 EVT VT = Op.getValueType(); 4517 4518 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4519 ARMcc, CCR, OverflowCmp); 4520 4521 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4522 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4523 } 4524 4525 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4526 SelectionDAG &DAG) { 4527 SDLoc DL(BoolCarry); 4528 EVT CarryVT = BoolCarry.getValueType(); 4529 4530 // This converts the boolean value carry into the carry flag by doing 4531 // ARMISD::SUBC Carry, 1 4532 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4533 DAG.getVTList(CarryVT, MVT::i32), 4534 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4535 return Carry.getValue(1); 4536 } 4537 4538 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4539 SelectionDAG &DAG) { 4540 SDLoc DL(Flags); 4541 4542 // Now convert the carry flag into a boolean carry. We do this 4543 // using ARMISD:ADDE 0, 0, Carry 4544 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4545 DAG.getConstant(0, DL, MVT::i32), 4546 DAG.getConstant(0, DL, MVT::i32), Flags); 4547 } 4548 4549 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4550 SelectionDAG &DAG) const { 4551 // Let legalize expand this if it isn't a legal type yet. 4552 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4553 return SDValue(); 4554 4555 SDValue LHS = Op.getOperand(0); 4556 SDValue RHS = Op.getOperand(1); 4557 SDLoc dl(Op); 4558 4559 EVT VT = Op.getValueType(); 4560 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4561 SDValue Value; 4562 SDValue Overflow; 4563 switch (Op.getOpcode()) { 4564 default: 4565 llvm_unreachable("Unknown overflow instruction!"); 4566 case ISD::UADDO: 4567 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4568 // Convert the carry flag into a boolean value. 4569 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4570 break; 4571 case ISD::USUBO: { 4572 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4573 // Convert the carry flag into a boolean value. 4574 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4575 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4576 // value. So compute 1 - C. 4577 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4578 DAG.getConstant(1, dl, MVT::i32), Overflow); 4579 break; 4580 } 4581 } 4582 4583 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4584 } 4585 4586 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG, 4587 const ARMSubtarget *Subtarget) { 4588 EVT VT = Op.getValueType(); 4589 if (!Subtarget->hasDSP()) 4590 return SDValue(); 4591 if (!VT.isSimple()) 4592 return SDValue(); 4593 4594 unsigned NewOpcode; 4595 bool IsAdd = Op->getOpcode() == ISD::SADDSAT; 4596 switch (VT.getSimpleVT().SimpleTy) { 4597 default: 4598 return SDValue(); 4599 case MVT::i8: 4600 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b; 4601 break; 4602 case MVT::i16: 4603 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b; 4604 break; 4605 } 4606 4607 SDLoc dl(Op); 4608 SDValue Add = 4609 DAG.getNode(NewOpcode, dl, MVT::i32, 4610 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32), 4611 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32)); 4612 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add); 4613 } 4614 4615 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4616 SDValue Cond = Op.getOperand(0); 4617 SDValue SelectTrue = Op.getOperand(1); 4618 SDValue SelectFalse = Op.getOperand(2); 4619 SDLoc dl(Op); 4620 unsigned Opc = Cond.getOpcode(); 4621 4622 if (Cond.getResNo() == 1 && 4623 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4624 Opc == ISD::USUBO)) { 4625 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4626 return SDValue(); 4627 4628 SDValue Value, OverflowCmp; 4629 SDValue ARMcc; 4630 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4631 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4632 EVT VT = Op.getValueType(); 4633 4634 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4635 OverflowCmp, DAG); 4636 } 4637 4638 // Convert: 4639 // 4640 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4641 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4642 // 4643 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4644 const ConstantSDNode *CMOVTrue = 4645 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4646 const ConstantSDNode *CMOVFalse = 4647 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4648 4649 if (CMOVTrue && CMOVFalse) { 4650 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4651 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4652 4653 SDValue True; 4654 SDValue False; 4655 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4656 True = SelectTrue; 4657 False = SelectFalse; 4658 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4659 True = SelectFalse; 4660 False = SelectTrue; 4661 } 4662 4663 if (True.getNode() && False.getNode()) { 4664 EVT VT = Op.getValueType(); 4665 SDValue ARMcc = Cond.getOperand(2); 4666 SDValue CCR = Cond.getOperand(3); 4667 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4668 assert(True.getValueType() == VT); 4669 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4670 } 4671 } 4672 } 4673 4674 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4675 // undefined bits before doing a full-word comparison with zero. 4676 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4677 DAG.getConstant(1, dl, Cond.getValueType())); 4678 4679 return DAG.getSelectCC(dl, Cond, 4680 DAG.getConstant(0, dl, Cond.getValueType()), 4681 SelectTrue, SelectFalse, ISD::SETNE); 4682 } 4683 4684 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4685 bool &swpCmpOps, bool &swpVselOps) { 4686 // Start by selecting the GE condition code for opcodes that return true for 4687 // 'equality' 4688 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4689 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4690 CondCode = ARMCC::GE; 4691 4692 // and GT for opcodes that return false for 'equality'. 4693 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4694 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4695 CondCode = ARMCC::GT; 4696 4697 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4698 // to swap the compare operands. 4699 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4700 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4701 swpCmpOps = true; 4702 4703 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4704 // If we have an unordered opcode, we need to swap the operands to the VSEL 4705 // instruction (effectively negating the condition). 4706 // 4707 // This also has the effect of swapping which one of 'less' or 'greater' 4708 // returns true, so we also swap the compare operands. It also switches 4709 // whether we return true for 'equality', so we compensate by picking the 4710 // opposite condition code to our original choice. 4711 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4712 CC == ISD::SETUGT) { 4713 swpCmpOps = !swpCmpOps; 4714 swpVselOps = !swpVselOps; 4715 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4716 } 4717 4718 // 'ordered' is 'anything but unordered', so use the VS condition code and 4719 // swap the VSEL operands. 4720 if (CC == ISD::SETO) { 4721 CondCode = ARMCC::VS; 4722 swpVselOps = true; 4723 } 4724 4725 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4726 // code and swap the VSEL operands. Also do this if we don't care about the 4727 // unordered case. 4728 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4729 CondCode = ARMCC::EQ; 4730 swpVselOps = true; 4731 } 4732 } 4733 4734 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4735 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4736 SDValue Cmp, SelectionDAG &DAG) const { 4737 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4738 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4739 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4740 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4741 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4742 4743 SDValue TrueLow = TrueVal.getValue(0); 4744 SDValue TrueHigh = TrueVal.getValue(1); 4745 SDValue FalseLow = FalseVal.getValue(0); 4746 SDValue FalseHigh = FalseVal.getValue(1); 4747 4748 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4749 ARMcc, CCR, Cmp); 4750 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4751 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4752 4753 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4754 } else { 4755 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4756 Cmp); 4757 } 4758 } 4759 4760 static bool isGTorGE(ISD::CondCode CC) { 4761 return CC == ISD::SETGT || CC == ISD::SETGE; 4762 } 4763 4764 static bool isLTorLE(ISD::CondCode CC) { 4765 return CC == ISD::SETLT || CC == ISD::SETLE; 4766 } 4767 4768 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4769 // All of these conditions (and their <= and >= counterparts) will do: 4770 // x < k ? k : x 4771 // x > k ? x : k 4772 // k < x ? x : k 4773 // k > x ? k : x 4774 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4775 const SDValue TrueVal, const SDValue FalseVal, 4776 const ISD::CondCode CC, const SDValue K) { 4777 return (isGTorGE(CC) && 4778 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4779 (isLTorLE(CC) && 4780 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4781 } 4782 4783 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4784 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4785 const SDValue TrueVal, const SDValue FalseVal, 4786 const ISD::CondCode CC, const SDValue K) { 4787 return (isGTorGE(CC) && 4788 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4789 (isLTorLE(CC) && 4790 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4791 } 4792 4793 // Check if two chained conditionals could be converted into SSAT or USAT. 4794 // 4795 // SSAT can replace a set of two conditional selectors that bound a number to an 4796 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4797 // 4798 // x < -k ? -k : (x > k ? k : x) 4799 // x < -k ? -k : (x < k ? x : k) 4800 // x > -k ? (x > k ? k : x) : -k 4801 // x < k ? (x < -k ? -k : x) : k 4802 // etc. 4803 // 4804 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4805 // a power of 2. 4806 // 4807 // It returns true if the conversion can be done, false otherwise. 4808 // Additionally, the variable is returned in parameter V, the constant in K and 4809 // usat is set to true if the conditional represents an unsigned saturation 4810 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4811 uint64_t &K, bool &usat) { 4812 SDValue LHS1 = Op.getOperand(0); 4813 SDValue RHS1 = Op.getOperand(1); 4814 SDValue TrueVal1 = Op.getOperand(2); 4815 SDValue FalseVal1 = Op.getOperand(3); 4816 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4817 4818 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4819 if (Op2.getOpcode() != ISD::SELECT_CC) 4820 return false; 4821 4822 SDValue LHS2 = Op2.getOperand(0); 4823 SDValue RHS2 = Op2.getOperand(1); 4824 SDValue TrueVal2 = Op2.getOperand(2); 4825 SDValue FalseVal2 = Op2.getOperand(3); 4826 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4827 4828 // Find out which are the constants and which are the variables 4829 // in each conditional 4830 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4831 ? &RHS1 4832 : nullptr; 4833 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4834 ? &RHS2 4835 : nullptr; 4836 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4837 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4838 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4839 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4840 4841 // We must detect cases where the original operations worked with 16- or 4842 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4843 // must work with sign-extended values but the select operations return 4844 // the original non-extended value. 4845 SDValue V2TmpReg = V2Tmp; 4846 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4847 V2TmpReg = V2Tmp->getOperand(0); 4848 4849 // Check that the registers and the constants have the correct values 4850 // in both conditionals 4851 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4852 V2TmpReg != V2) 4853 return false; 4854 4855 // Figure out which conditional is saturating the lower/upper bound. 4856 const SDValue *LowerCheckOp = 4857 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4858 ? &Op 4859 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4860 ? &Op2 4861 : nullptr; 4862 const SDValue *UpperCheckOp = 4863 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4864 ? &Op 4865 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4866 ? &Op2 4867 : nullptr; 4868 4869 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4870 return false; 4871 4872 // Check that the constant in the lower-bound check is 4873 // the opposite of the constant in the upper-bound check 4874 // in 1's complement. 4875 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4876 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4877 int64_t PosVal = std::max(Val1, Val2); 4878 int64_t NegVal = std::min(Val1, Val2); 4879 4880 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4881 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4882 isPowerOf2_64(PosVal + 1)) { 4883 4884 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4885 if (Val1 == ~Val2) 4886 usat = false; 4887 else if (NegVal == 0) 4888 usat = true; 4889 else 4890 return false; 4891 4892 V = V2; 4893 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4894 4895 return true; 4896 } 4897 4898 return false; 4899 } 4900 4901 // Check if a condition of the type x < k ? k : x can be converted into a 4902 // bit operation instead of conditional moves. 4903 // Currently this is allowed given: 4904 // - The conditions and values match up 4905 // - k is 0 or -1 (all ones) 4906 // This function will not check the last condition, thats up to the caller 4907 // It returns true if the transformation can be made, and in such case 4908 // returns x in V, and k in SatK. 4909 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4910 SDValue &SatK) 4911 { 4912 SDValue LHS = Op.getOperand(0); 4913 SDValue RHS = Op.getOperand(1); 4914 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4915 SDValue TrueVal = Op.getOperand(2); 4916 SDValue FalseVal = Op.getOperand(3); 4917 4918 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4919 ? &RHS 4920 : nullptr; 4921 4922 // No constant operation in comparison, early out 4923 if (!K) 4924 return false; 4925 4926 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4927 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4928 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4929 4930 // If the constant on left and right side, or variable on left and right, 4931 // does not match, early out 4932 if (*K != KTmp || V != VTmp) 4933 return false; 4934 4935 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4936 SatK = *K; 4937 return true; 4938 } 4939 4940 return false; 4941 } 4942 4943 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 4944 if (VT == MVT::f32) 4945 return !Subtarget->hasVFP2Base(); 4946 if (VT == MVT::f64) 4947 return !Subtarget->hasFP64(); 4948 if (VT == MVT::f16) 4949 return !Subtarget->hasFullFP16(); 4950 return false; 4951 } 4952 4953 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4954 EVT VT = Op.getValueType(); 4955 SDLoc dl(Op); 4956 4957 // Try to convert two saturating conditional selects into a single SSAT 4958 SDValue SatValue; 4959 uint64_t SatConstant; 4960 bool SatUSat; 4961 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4962 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4963 if (SatUSat) 4964 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4965 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4966 else 4967 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4968 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4969 } 4970 4971 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4972 // into more efficient bit operations, which is possible when k is 0 or -1 4973 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4974 // single instructions. On Thumb the shift and the bit operation will be two 4975 // instructions. 4976 // Only allow this transformation on full-width (32-bit) operations 4977 SDValue LowerSatConstant; 4978 if (VT == MVT::i32 && 4979 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4980 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4981 DAG.getConstant(31, dl, VT)); 4982 if (isNullConstant(LowerSatConstant)) { 4983 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4984 DAG.getAllOnesConstant(dl, VT)); 4985 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4986 } else if (isAllOnesConstant(LowerSatConstant)) 4987 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4988 } 4989 4990 SDValue LHS = Op.getOperand(0); 4991 SDValue RHS = Op.getOperand(1); 4992 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4993 SDValue TrueVal = Op.getOperand(2); 4994 SDValue FalseVal = Op.getOperand(3); 4995 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal); 4996 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal); 4997 4998 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal && 4999 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) { 5000 unsigned TVal = CTVal->getZExtValue(); 5001 unsigned FVal = CFVal->getZExtValue(); 5002 unsigned Opcode = 0; 5003 5004 if (TVal == ~FVal) { 5005 Opcode = ARMISD::CSINV; 5006 } else if (TVal == ~FVal + 1) { 5007 Opcode = ARMISD::CSNEG; 5008 } else if (TVal + 1 == FVal) { 5009 Opcode = ARMISD::CSINC; 5010 } else if (TVal == FVal + 1) { 5011 Opcode = ARMISD::CSINC; 5012 std::swap(TrueVal, FalseVal); 5013 std::swap(TVal, FVal); 5014 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5015 } 5016 5017 if (Opcode) { 5018 // If one of the constants is cheaper than another, materialise the 5019 // cheaper one and let the csel generate the other. 5020 if (Opcode != ARMISD::CSINC && 5021 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) { 5022 std::swap(TrueVal, FalseVal); 5023 std::swap(TVal, FVal); 5024 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5025 } 5026 5027 // Attempt to use ZR checking TVal is 0, possibly inverting the condition 5028 // to get there. CSINC not is invertable like the other two (~(~a) == a, 5029 // -(-a) == a, but (a+1)+1 != a). 5030 if (FVal == 0 && Opcode != ARMISD::CSINC) { 5031 std::swap(TrueVal, FalseVal); 5032 std::swap(TVal, FVal); 5033 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5034 } 5035 if (TVal == 0) 5036 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32); 5037 5038 // Drops F's value because we can get it by inverting/negating TVal. 5039 FalseVal = TrueVal; 5040 5041 SDValue ARMcc; 5042 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5043 EVT VT = TrueVal.getValueType(); 5044 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp); 5045 } 5046 } 5047 5048 if (isUnsupportedFloatingType(LHS.getValueType())) { 5049 DAG.getTargetLoweringInfo().softenSetCCOperands( 5050 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5051 5052 // If softenSetCCOperands only returned one value, we should compare it to 5053 // zero. 5054 if (!RHS.getNode()) { 5055 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5056 CC = ISD::SETNE; 5057 } 5058 } 5059 5060 if (LHS.getValueType() == MVT::i32) { 5061 // Try to generate VSEL on ARMv8. 5062 // The VSEL instruction can't use all the usual ARM condition 5063 // codes: it only has two bits to select the condition code, so it's 5064 // constrained to use only GE, GT, VS and EQ. 5065 // 5066 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 5067 // swap the operands of the previous compare instruction (effectively 5068 // inverting the compare condition, swapping 'less' and 'greater') and 5069 // sometimes need to swap the operands to the VSEL (which inverts the 5070 // condition in the sense of firing whenever the previous condition didn't) 5071 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 5072 TrueVal.getValueType() == MVT::f32 || 5073 TrueVal.getValueType() == MVT::f64)) { 5074 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5075 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 5076 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 5077 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5078 std::swap(TrueVal, FalseVal); 5079 } 5080 } 5081 5082 SDValue ARMcc; 5083 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5084 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5085 // Choose GE over PL, which vsel does now support 5086 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 5087 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 5088 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5089 } 5090 5091 ARMCC::CondCodes CondCode, CondCode2; 5092 FPCCToARMCC(CC, CondCode, CondCode2); 5093 5094 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 5095 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 5096 // must use VSEL (limited condition codes), due to not having conditional f16 5097 // moves. 5098 if (Subtarget->hasFPARMv8Base() && 5099 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 5100 (TrueVal.getValueType() == MVT::f16 || 5101 TrueVal.getValueType() == MVT::f32 || 5102 TrueVal.getValueType() == MVT::f64)) { 5103 bool swpCmpOps = false; 5104 bool swpVselOps = false; 5105 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 5106 5107 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 5108 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 5109 if (swpCmpOps) 5110 std::swap(LHS, RHS); 5111 if (swpVselOps) 5112 std::swap(TrueVal, FalseVal); 5113 } 5114 } 5115 5116 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5117 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5118 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5119 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5120 if (CondCode2 != ARMCC::AL) { 5121 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 5122 // FIXME: Needs another CMP because flag can have but one use. 5123 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 5124 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 5125 } 5126 return Result; 5127 } 5128 5129 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 5130 /// to morph to an integer compare sequence. 5131 static bool canChangeToInt(SDValue Op, bool &SeenZero, 5132 const ARMSubtarget *Subtarget) { 5133 SDNode *N = Op.getNode(); 5134 if (!N->hasOneUse()) 5135 // Otherwise it requires moving the value from fp to integer registers. 5136 return false; 5137 if (!N->getNumValues()) 5138 return false; 5139 EVT VT = Op.getValueType(); 5140 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 5141 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 5142 // vmrs are very slow, e.g. cortex-a8. 5143 return false; 5144 5145 if (isFloatingPointZero(Op)) { 5146 SeenZero = true; 5147 return true; 5148 } 5149 return ISD::isNormalLoad(N); 5150 } 5151 5152 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 5153 if (isFloatingPointZero(Op)) 5154 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 5155 5156 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 5157 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 5158 Ld->getPointerInfo(), Ld->getAlignment(), 5159 Ld->getMemOperand()->getFlags()); 5160 5161 llvm_unreachable("Unknown VFP cmp argument!"); 5162 } 5163 5164 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 5165 SDValue &RetVal1, SDValue &RetVal2) { 5166 SDLoc dl(Op); 5167 5168 if (isFloatingPointZero(Op)) { 5169 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 5170 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 5171 return; 5172 } 5173 5174 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 5175 SDValue Ptr = Ld->getBasePtr(); 5176 RetVal1 = 5177 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 5178 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 5179 5180 EVT PtrType = Ptr.getValueType(); 5181 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 5182 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 5183 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 5184 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 5185 Ld->getPointerInfo().getWithOffset(4), NewAlign, 5186 Ld->getMemOperand()->getFlags()); 5187 return; 5188 } 5189 5190 llvm_unreachable("Unknown VFP cmp argument!"); 5191 } 5192 5193 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 5194 /// f32 and even f64 comparisons to integer ones. 5195 SDValue 5196 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 5197 SDValue Chain = Op.getOperand(0); 5198 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5199 SDValue LHS = Op.getOperand(2); 5200 SDValue RHS = Op.getOperand(3); 5201 SDValue Dest = Op.getOperand(4); 5202 SDLoc dl(Op); 5203 5204 bool LHSSeenZero = false; 5205 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 5206 bool RHSSeenZero = false; 5207 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 5208 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 5209 // If unsafe fp math optimization is enabled and there are no other uses of 5210 // the CMP operands, and the condition code is EQ or NE, we can optimize it 5211 // to an integer comparison. 5212 if (CC == ISD::SETOEQ) 5213 CC = ISD::SETEQ; 5214 else if (CC == ISD::SETUNE) 5215 CC = ISD::SETNE; 5216 5217 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5218 SDValue ARMcc; 5219 if (LHS.getValueType() == MVT::f32) { 5220 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5221 bitcastf32Toi32(LHS, DAG), Mask); 5222 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5223 bitcastf32Toi32(RHS, DAG), Mask); 5224 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5225 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5226 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5227 Chain, Dest, ARMcc, CCR, Cmp); 5228 } 5229 5230 SDValue LHS1, LHS2; 5231 SDValue RHS1, RHS2; 5232 expandf64Toi32(LHS, DAG, LHS1, LHS2); 5233 expandf64Toi32(RHS, DAG, RHS1, RHS2); 5234 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 5235 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 5236 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5237 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5238 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5239 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 5240 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 5241 } 5242 5243 return SDValue(); 5244 } 5245 5246 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 5247 SDValue Chain = Op.getOperand(0); 5248 SDValue Cond = Op.getOperand(1); 5249 SDValue Dest = Op.getOperand(2); 5250 SDLoc dl(Op); 5251 5252 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5253 // instruction. 5254 unsigned Opc = Cond.getOpcode(); 5255 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5256 !Subtarget->isThumb1Only(); 5257 if (Cond.getResNo() == 1 && 5258 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5259 Opc == ISD::USUBO || OptimizeMul)) { 5260 // Only lower legal XALUO ops. 5261 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 5262 return SDValue(); 5263 5264 // The actual operation with overflow check. 5265 SDValue Value, OverflowCmp; 5266 SDValue ARMcc; 5267 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 5268 5269 // Reverse the condition code. 5270 ARMCC::CondCodes CondCode = 5271 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5272 CondCode = ARMCC::getOppositeCondition(CondCode); 5273 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5274 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5275 5276 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5277 OverflowCmp); 5278 } 5279 5280 return SDValue(); 5281 } 5282 5283 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5284 SDValue Chain = Op.getOperand(0); 5285 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5286 SDValue LHS = Op.getOperand(2); 5287 SDValue RHS = Op.getOperand(3); 5288 SDValue Dest = Op.getOperand(4); 5289 SDLoc dl(Op); 5290 5291 if (isUnsupportedFloatingType(LHS.getValueType())) { 5292 DAG.getTargetLoweringInfo().softenSetCCOperands( 5293 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5294 5295 // If softenSetCCOperands only returned one value, we should compare it to 5296 // zero. 5297 if (!RHS.getNode()) { 5298 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5299 CC = ISD::SETNE; 5300 } 5301 } 5302 5303 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5304 // instruction. 5305 unsigned Opc = LHS.getOpcode(); 5306 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5307 !Subtarget->isThumb1Only(); 5308 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5309 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5310 Opc == ISD::USUBO || OptimizeMul) && 5311 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5312 // Only lower legal XALUO ops. 5313 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5314 return SDValue(); 5315 5316 // The actual operation with overflow check. 5317 SDValue Value, OverflowCmp; 5318 SDValue ARMcc; 5319 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5320 5321 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5322 // Reverse the condition code. 5323 ARMCC::CondCodes CondCode = 5324 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5325 CondCode = ARMCC::getOppositeCondition(CondCode); 5326 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5327 } 5328 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5329 5330 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5331 OverflowCmp); 5332 } 5333 5334 if (LHS.getValueType() == MVT::i32) { 5335 SDValue ARMcc; 5336 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5337 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5338 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5339 Chain, Dest, ARMcc, CCR, Cmp); 5340 } 5341 5342 if (getTargetMachine().Options.UnsafeFPMath && 5343 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5344 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5345 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5346 return Result; 5347 } 5348 5349 ARMCC::CondCodes CondCode, CondCode2; 5350 FPCCToARMCC(CC, CondCode, CondCode2); 5351 5352 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5353 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5354 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5355 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5356 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5357 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5358 if (CondCode2 != ARMCC::AL) { 5359 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5360 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5361 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5362 } 5363 return Res; 5364 } 5365 5366 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5367 SDValue Chain = Op.getOperand(0); 5368 SDValue Table = Op.getOperand(1); 5369 SDValue Index = Op.getOperand(2); 5370 SDLoc dl(Op); 5371 5372 EVT PTy = getPointerTy(DAG.getDataLayout()); 5373 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5374 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5375 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5376 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5377 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5378 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5379 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5380 // which does another jump to the destination. This also makes it easier 5381 // to translate it to TBB / TBH later (Thumb2 only). 5382 // FIXME: This might not work if the function is extremely large. 5383 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5384 Addr, Op.getOperand(2), JTI); 5385 } 5386 if (isPositionIndependent() || Subtarget->isROPI()) { 5387 Addr = 5388 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5389 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5390 Chain = Addr.getValue(1); 5391 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5392 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5393 } else { 5394 Addr = 5395 DAG.getLoad(PTy, dl, Chain, Addr, 5396 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5397 Chain = Addr.getValue(1); 5398 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5399 } 5400 } 5401 5402 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5403 EVT VT = Op.getValueType(); 5404 SDLoc dl(Op); 5405 5406 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5407 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5408 return Op; 5409 return DAG.UnrollVectorOp(Op.getNode()); 5410 } 5411 5412 const bool HasFullFP16 = 5413 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5414 5415 EVT NewTy; 5416 const EVT OpTy = Op.getOperand(0).getValueType(); 5417 if (OpTy == MVT::v4f32) 5418 NewTy = MVT::v4i32; 5419 else if (OpTy == MVT::v4f16 && HasFullFP16) 5420 NewTy = MVT::v4i16; 5421 else if (OpTy == MVT::v8f16 && HasFullFP16) 5422 NewTy = MVT::v8i16; 5423 else 5424 llvm_unreachable("Invalid type for custom lowering!"); 5425 5426 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5427 return DAG.UnrollVectorOp(Op.getNode()); 5428 5429 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5430 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5431 } 5432 5433 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5434 EVT VT = Op.getValueType(); 5435 if (VT.isVector()) 5436 return LowerVectorFP_TO_INT(Op, DAG); 5437 5438 bool IsStrict = Op->isStrictFPOpcode(); 5439 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 5440 5441 if (isUnsupportedFloatingType(SrcVal.getValueType())) { 5442 RTLIB::Libcall LC; 5443 if (Op.getOpcode() == ISD::FP_TO_SINT || 5444 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 5445 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), 5446 Op.getValueType()); 5447 else 5448 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), 5449 Op.getValueType()); 5450 SDLoc Loc(Op); 5451 MakeLibCallOptions CallOptions; 5452 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 5453 SDValue Result; 5454 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 5455 CallOptions, Loc, Chain); 5456 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 5457 } 5458 5459 // FIXME: Remove this when we have strict fp instruction selection patterns 5460 if (IsStrict) { 5461 SDLoc Loc(Op); 5462 SDValue Result = 5463 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT 5464 : ISD::FP_TO_UINT, 5465 Loc, Op.getValueType(), SrcVal); 5466 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 5467 } 5468 5469 return Op; 5470 } 5471 5472 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5473 EVT VT = Op.getValueType(); 5474 SDLoc dl(Op); 5475 5476 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5477 if (VT.getVectorElementType() == MVT::f32) 5478 return Op; 5479 return DAG.UnrollVectorOp(Op.getNode()); 5480 } 5481 5482 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5483 Op.getOperand(0).getValueType() == MVT::v8i16) && 5484 "Invalid type for custom lowering!"); 5485 5486 const bool HasFullFP16 = 5487 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5488 5489 EVT DestVecType; 5490 if (VT == MVT::v4f32) 5491 DestVecType = MVT::v4i32; 5492 else if (VT == MVT::v4f16 && HasFullFP16) 5493 DestVecType = MVT::v4i16; 5494 else if (VT == MVT::v8f16 && HasFullFP16) 5495 DestVecType = MVT::v8i16; 5496 else 5497 return DAG.UnrollVectorOp(Op.getNode()); 5498 5499 unsigned CastOpc; 5500 unsigned Opc; 5501 switch (Op.getOpcode()) { 5502 default: llvm_unreachable("Invalid opcode!"); 5503 case ISD::SINT_TO_FP: 5504 CastOpc = ISD::SIGN_EXTEND; 5505 Opc = ISD::SINT_TO_FP; 5506 break; 5507 case ISD::UINT_TO_FP: 5508 CastOpc = ISD::ZERO_EXTEND; 5509 Opc = ISD::UINT_TO_FP; 5510 break; 5511 } 5512 5513 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5514 return DAG.getNode(Opc, dl, VT, Op); 5515 } 5516 5517 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5518 EVT VT = Op.getValueType(); 5519 if (VT.isVector()) 5520 return LowerVectorINT_TO_FP(Op, DAG); 5521 if (isUnsupportedFloatingType(VT)) { 5522 RTLIB::Libcall LC; 5523 if (Op.getOpcode() == ISD::SINT_TO_FP) 5524 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5525 Op.getValueType()); 5526 else 5527 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5528 Op.getValueType()); 5529 MakeLibCallOptions CallOptions; 5530 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5531 CallOptions, SDLoc(Op)).first; 5532 } 5533 5534 return Op; 5535 } 5536 5537 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5538 // Implement fcopysign with a fabs and a conditional fneg. 5539 SDValue Tmp0 = Op.getOperand(0); 5540 SDValue Tmp1 = Op.getOperand(1); 5541 SDLoc dl(Op); 5542 EVT VT = Op.getValueType(); 5543 EVT SrcVT = Tmp1.getValueType(); 5544 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5545 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5546 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5547 5548 if (UseNEON) { 5549 // Use VBSL to copy the sign bit. 5550 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5551 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5552 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5553 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5554 if (VT == MVT::f64) 5555 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5556 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5557 DAG.getConstant(32, dl, MVT::i32)); 5558 else /*if (VT == MVT::f32)*/ 5559 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5560 if (SrcVT == MVT::f32) { 5561 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5562 if (VT == MVT::f64) 5563 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5564 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5565 DAG.getConstant(32, dl, MVT::i32)); 5566 } else if (VT == MVT::f32) 5567 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5568 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5569 DAG.getConstant(32, dl, MVT::i32)); 5570 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5571 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5572 5573 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5574 dl, MVT::i32); 5575 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5576 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5577 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5578 5579 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5580 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5581 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5582 if (VT == MVT::f32) { 5583 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5584 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5585 DAG.getConstant(0, dl, MVT::i32)); 5586 } else { 5587 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5588 } 5589 5590 return Res; 5591 } 5592 5593 // Bitcast operand 1 to i32. 5594 if (SrcVT == MVT::f64) 5595 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5596 Tmp1).getValue(1); 5597 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5598 5599 // Or in the signbit with integer operations. 5600 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5601 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5602 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5603 if (VT == MVT::f32) { 5604 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5605 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5606 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5607 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5608 } 5609 5610 // f64: Or the high part with signbit and then combine two parts. 5611 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5612 Tmp0); 5613 SDValue Lo = Tmp0.getValue(0); 5614 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5615 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5616 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5617 } 5618 5619 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5620 MachineFunction &MF = DAG.getMachineFunction(); 5621 MachineFrameInfo &MFI = MF.getFrameInfo(); 5622 MFI.setReturnAddressIsTaken(true); 5623 5624 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5625 return SDValue(); 5626 5627 EVT VT = Op.getValueType(); 5628 SDLoc dl(Op); 5629 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5630 if (Depth) { 5631 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5632 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5633 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5634 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5635 MachinePointerInfo()); 5636 } 5637 5638 // Return LR, which contains the return address. Mark it an implicit live-in. 5639 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5640 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5641 } 5642 5643 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5644 const ARMBaseRegisterInfo &ARI = 5645 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5646 MachineFunction &MF = DAG.getMachineFunction(); 5647 MachineFrameInfo &MFI = MF.getFrameInfo(); 5648 MFI.setFrameAddressIsTaken(true); 5649 5650 EVT VT = Op.getValueType(); 5651 SDLoc dl(Op); // FIXME probably not meaningful 5652 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5653 Register FrameReg = ARI.getFrameRegister(MF); 5654 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5655 while (Depth--) 5656 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5657 MachinePointerInfo()); 5658 return FrameAddr; 5659 } 5660 5661 // FIXME? Maybe this could be a TableGen attribute on some registers and 5662 // this table could be generated automatically from RegInfo. 5663 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT, 5664 const MachineFunction &MF) const { 5665 Register Reg = StringSwitch<unsigned>(RegName) 5666 .Case("sp", ARM::SP) 5667 .Default(0); 5668 if (Reg) 5669 return Reg; 5670 report_fatal_error(Twine("Invalid register name \"" 5671 + StringRef(RegName) + "\".")); 5672 } 5673 5674 // Result is 64 bit value so split into two 32 bit values and return as a 5675 // pair of values. 5676 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5677 SelectionDAG &DAG) { 5678 SDLoc DL(N); 5679 5680 // This function is only supposed to be called for i64 type destination. 5681 assert(N->getValueType(0) == MVT::i64 5682 && "ExpandREAD_REGISTER called for non-i64 type result."); 5683 5684 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5685 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5686 N->getOperand(0), 5687 N->getOperand(1)); 5688 5689 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5690 Read.getValue(1))); 5691 Results.push_back(Read.getOperand(0)); 5692 } 5693 5694 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5695 /// When \p DstVT, the destination type of \p BC, is on the vector 5696 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5697 /// it might be possible to combine them, such that everything stays on the 5698 /// vector register bank. 5699 /// \p return The node that would replace \p BT, if the combine 5700 /// is possible. 5701 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5702 SelectionDAG &DAG) { 5703 SDValue Op = BC->getOperand(0); 5704 EVT DstVT = BC->getValueType(0); 5705 5706 // The only vector instruction that can produce a scalar (remember, 5707 // since the bitcast was about to be turned into VMOVDRR, the source 5708 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5709 // Moreover, we can do this combine only if there is one use. 5710 // Finally, if the destination type is not a vector, there is not 5711 // much point on forcing everything on the vector bank. 5712 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5713 !Op.hasOneUse()) 5714 return SDValue(); 5715 5716 // If the index is not constant, we will introduce an additional 5717 // multiply that will stick. 5718 // Give up in that case. 5719 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5720 if (!Index) 5721 return SDValue(); 5722 unsigned DstNumElt = DstVT.getVectorNumElements(); 5723 5724 // Compute the new index. 5725 const APInt &APIntIndex = Index->getAPIntValue(); 5726 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5727 NewIndex *= APIntIndex; 5728 // Check if the new constant index fits into i32. 5729 if (NewIndex.getBitWidth() > 32) 5730 return SDValue(); 5731 5732 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5733 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5734 SDLoc dl(Op); 5735 SDValue ExtractSrc = Op.getOperand(0); 5736 EVT VecVT = EVT::getVectorVT( 5737 *DAG.getContext(), DstVT.getScalarType(), 5738 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5739 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5740 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5741 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5742 } 5743 5744 /// ExpandBITCAST - If the target supports VFP, this function is called to 5745 /// expand a bit convert where either the source or destination type is i64 to 5746 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5747 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5748 /// vectors), since the legalizer won't know what to do with that. 5749 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5750 const ARMSubtarget *Subtarget) { 5751 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5752 SDLoc dl(N); 5753 SDValue Op = N->getOperand(0); 5754 5755 // This function is only supposed to be called for i64 types, either as the 5756 // source or destination of the bit convert. 5757 EVT SrcVT = Op.getValueType(); 5758 EVT DstVT = N->getValueType(0); 5759 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5760 5761 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5762 if (!HasFullFP16) 5763 return SDValue(); 5764 // SoftFP: read half-precision arguments: 5765 // 5766 // t2: i32,ch = ... 5767 // t7: i16 = truncate t2 <~~~~ Op 5768 // t8: f16 = bitcast t7 <~~~~ N 5769 // 5770 if (Op.getOperand(0).getValueType() == MVT::i32) 5771 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5772 MVT::f16, Op.getOperand(0)); 5773 5774 return SDValue(); 5775 } 5776 5777 // Half-precision return values 5778 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5779 if (!HasFullFP16) 5780 return SDValue(); 5781 // 5782 // t11: f16 = fadd t8, t10 5783 // t12: i16 = bitcast t11 <~~~ SDNode N 5784 // t13: i32 = zero_extend t12 5785 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5786 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5787 // 5788 // transform this into: 5789 // 5790 // t20: i32 = ARMISD::VMOVrh t11 5791 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5792 // 5793 auto ZeroExtend = N->use_begin(); 5794 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5795 ZeroExtend->getValueType(0) != MVT::i32) 5796 return SDValue(); 5797 5798 auto Copy = ZeroExtend->use_begin(); 5799 if (Copy->getOpcode() == ISD::CopyToReg && 5800 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5801 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5802 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5803 return Cvt; 5804 } 5805 return SDValue(); 5806 } 5807 5808 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5809 return SDValue(); 5810 5811 // Turn i64->f64 into VMOVDRR. 5812 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5813 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5814 // if we can combine the bitcast with its source. 5815 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5816 return Val; 5817 5818 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5819 DAG.getConstant(0, dl, MVT::i32)); 5820 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5821 DAG.getConstant(1, dl, MVT::i32)); 5822 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5823 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5824 } 5825 5826 // Turn f64->i64 into VMOVRRD. 5827 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5828 SDValue Cvt; 5829 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5830 SrcVT.getVectorNumElements() > 1) 5831 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5832 DAG.getVTList(MVT::i32, MVT::i32), 5833 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5834 else 5835 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5836 DAG.getVTList(MVT::i32, MVT::i32), Op); 5837 // Merge the pieces into a single i64 value. 5838 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5839 } 5840 5841 return SDValue(); 5842 } 5843 5844 /// getZeroVector - Returns a vector of specified type with all zero elements. 5845 /// Zero vectors are used to represent vector negation and in those cases 5846 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5847 /// not support i64 elements, so sometimes the zero vectors will need to be 5848 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5849 /// zero vector. 5850 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5851 assert(VT.isVector() && "Expected a vector type"); 5852 // The canonical modified immediate encoding of a zero vector is....0! 5853 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5854 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5855 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5856 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5857 } 5858 5859 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5860 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5861 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5862 SelectionDAG &DAG) const { 5863 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5864 EVT VT = Op.getValueType(); 5865 unsigned VTBits = VT.getSizeInBits(); 5866 SDLoc dl(Op); 5867 SDValue ShOpLo = Op.getOperand(0); 5868 SDValue ShOpHi = Op.getOperand(1); 5869 SDValue ShAmt = Op.getOperand(2); 5870 SDValue ARMcc; 5871 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5872 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5873 5874 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5875 5876 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5877 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5878 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5879 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5880 DAG.getConstant(VTBits, dl, MVT::i32)); 5881 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5882 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5883 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5884 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5885 ISD::SETGE, ARMcc, DAG, dl); 5886 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5887 ARMcc, CCR, CmpLo); 5888 5889 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5890 SDValue HiBigShift = Opc == ISD::SRA 5891 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5892 DAG.getConstant(VTBits - 1, dl, VT)) 5893 : DAG.getConstant(0, dl, VT); 5894 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5895 ISD::SETGE, ARMcc, DAG, dl); 5896 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5897 ARMcc, CCR, CmpHi); 5898 5899 SDValue Ops[2] = { Lo, Hi }; 5900 return DAG.getMergeValues(Ops, dl); 5901 } 5902 5903 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5904 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5905 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5906 SelectionDAG &DAG) const { 5907 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5908 EVT VT = Op.getValueType(); 5909 unsigned VTBits = VT.getSizeInBits(); 5910 SDLoc dl(Op); 5911 SDValue ShOpLo = Op.getOperand(0); 5912 SDValue ShOpHi = Op.getOperand(1); 5913 SDValue ShAmt = Op.getOperand(2); 5914 SDValue ARMcc; 5915 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5916 5917 assert(Op.getOpcode() == ISD::SHL_PARTS); 5918 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5919 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5920 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5921 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5922 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5923 5924 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5925 DAG.getConstant(VTBits, dl, MVT::i32)); 5926 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5927 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5928 ISD::SETGE, ARMcc, DAG, dl); 5929 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5930 ARMcc, CCR, CmpHi); 5931 5932 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5933 ISD::SETGE, ARMcc, DAG, dl); 5934 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5935 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5936 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5937 5938 SDValue Ops[2] = { Lo, Hi }; 5939 return DAG.getMergeValues(Ops, dl); 5940 } 5941 5942 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5943 SelectionDAG &DAG) const { 5944 // The rounding mode is in bits 23:22 of the FPSCR. 5945 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5946 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5947 // so that the shift + and get folded into a bitfield extract. 5948 SDLoc dl(Op); 5949 SDValue Chain = Op.getOperand(0); 5950 SDValue Ops[] = {Chain, 5951 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)}; 5952 5953 SDValue FPSCR = 5954 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops); 5955 Chain = FPSCR.getValue(1); 5956 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5957 DAG.getConstant(1U << 22, dl, MVT::i32)); 5958 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5959 DAG.getConstant(22, dl, MVT::i32)); 5960 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5961 DAG.getConstant(3, dl, MVT::i32)); 5962 return DAG.getMergeValues({And, Chain}, dl); 5963 } 5964 5965 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5966 const ARMSubtarget *ST) { 5967 SDLoc dl(N); 5968 EVT VT = N->getValueType(0); 5969 if (VT.isVector() && ST->hasNEON()) { 5970 5971 // Compute the least significant set bit: LSB = X & -X 5972 SDValue X = N->getOperand(0); 5973 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5974 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5975 5976 EVT ElemTy = VT.getVectorElementType(); 5977 5978 if (ElemTy == MVT::i8) { 5979 // Compute with: cttz(x) = ctpop(lsb - 1) 5980 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5981 DAG.getTargetConstant(1, dl, ElemTy)); 5982 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5983 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5984 } 5985 5986 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5987 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5988 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5989 unsigned NumBits = ElemTy.getSizeInBits(); 5990 SDValue WidthMinus1 = 5991 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5992 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5993 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5994 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5995 } 5996 5997 // Compute with: cttz(x) = ctpop(lsb - 1) 5998 5999 // Compute LSB - 1. 6000 SDValue Bits; 6001 if (ElemTy == MVT::i64) { 6002 // Load constant 0xffff'ffff'ffff'ffff to register. 6003 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6004 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 6005 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 6006 } else { 6007 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6008 DAG.getTargetConstant(1, dl, ElemTy)); 6009 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6010 } 6011 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6012 } 6013 6014 if (!ST->hasV6T2Ops()) 6015 return SDValue(); 6016 6017 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 6018 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 6019 } 6020 6021 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 6022 const ARMSubtarget *ST) { 6023 EVT VT = N->getValueType(0); 6024 SDLoc DL(N); 6025 6026 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 6027 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6028 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6029 "Unexpected type for custom ctpop lowering"); 6030 6031 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6032 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6033 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 6034 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 6035 6036 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6037 unsigned EltSize = 8; 6038 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6039 while (EltSize != VT.getScalarSizeInBits()) { 6040 SmallVector<SDValue, 8> Ops; 6041 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 6042 TLI.getPointerTy(DAG.getDataLayout()))); 6043 Ops.push_back(Res); 6044 6045 EltSize *= 2; 6046 NumElts /= 2; 6047 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6048 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 6049 } 6050 6051 return Res; 6052 } 6053 6054 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 6055 /// operand of a vector shift operation, where all the elements of the 6056 /// build_vector must have the same constant integer value. 6057 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6058 // Ignore bit_converts. 6059 while (Op.getOpcode() == ISD::BITCAST) 6060 Op = Op.getOperand(0); 6061 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6062 APInt SplatBits, SplatUndef; 6063 unsigned SplatBitSize; 6064 bool HasAnyUndefs; 6065 if (!BVN || 6066 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 6067 ElementBits) || 6068 SplatBitSize > ElementBits) 6069 return false; 6070 Cnt = SplatBits.getSExtValue(); 6071 return true; 6072 } 6073 6074 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6075 /// operand of a vector shift left operation. That value must be in the range: 6076 /// 0 <= Value < ElementBits for a left shift; or 6077 /// 0 <= Value <= ElementBits for a long left shift. 6078 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6079 assert(VT.isVector() && "vector shift count is not a vector type"); 6080 int64_t ElementBits = VT.getScalarSizeInBits(); 6081 if (!getVShiftImm(Op, ElementBits, Cnt)) 6082 return false; 6083 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6084 } 6085 6086 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6087 /// operand of a vector shift right operation. For a shift opcode, the value 6088 /// is positive, but for an intrinsic the value count must be negative. The 6089 /// absolute value must be in the range: 6090 /// 1 <= |Value| <= ElementBits for a right shift; or 6091 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 6092 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 6093 int64_t &Cnt) { 6094 assert(VT.isVector() && "vector shift count is not a vector type"); 6095 int64_t ElementBits = VT.getScalarSizeInBits(); 6096 if (!getVShiftImm(Op, ElementBits, Cnt)) 6097 return false; 6098 if (!isIntrinsic) 6099 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6100 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 6101 Cnt = -Cnt; 6102 return true; 6103 } 6104 return false; 6105 } 6106 6107 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 6108 const ARMSubtarget *ST) { 6109 EVT VT = N->getValueType(0); 6110 SDLoc dl(N); 6111 int64_t Cnt; 6112 6113 if (!VT.isVector()) 6114 return SDValue(); 6115 6116 // We essentially have two forms here. Shift by an immediate and shift by a 6117 // vector register (there are also shift by a gpr, but that is just handled 6118 // with a tablegen pattern). We cannot easily match shift by an immediate in 6119 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 6120 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 6121 // signed or unsigned, and a negative shift indicates a shift right). 6122 if (N->getOpcode() == ISD::SHL) { 6123 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 6124 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 6125 DAG.getConstant(Cnt, dl, MVT::i32)); 6126 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 6127 N->getOperand(1)); 6128 } 6129 6130 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 6131 "unexpected vector shift opcode"); 6132 6133 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 6134 unsigned VShiftOpc = 6135 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 6136 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 6137 DAG.getConstant(Cnt, dl, MVT::i32)); 6138 } 6139 6140 // Other right shifts we don't have operations for (we use a shift left by a 6141 // negative number). 6142 EVT ShiftVT = N->getOperand(1).getValueType(); 6143 SDValue NegatedCount = DAG.getNode( 6144 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 6145 unsigned VShiftOpc = 6146 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 6147 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 6148 } 6149 6150 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 6151 const ARMSubtarget *ST) { 6152 EVT VT = N->getValueType(0); 6153 SDLoc dl(N); 6154 6155 // We can get here for a node like i32 = ISD::SHL i32, i64 6156 if (VT != MVT::i64) 6157 return SDValue(); 6158 6159 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 6160 N->getOpcode() == ISD::SHL) && 6161 "Unknown shift to lower!"); 6162 6163 unsigned ShOpc = N->getOpcode(); 6164 if (ST->hasMVEIntegerOps()) { 6165 SDValue ShAmt = N->getOperand(1); 6166 unsigned ShPartsOpc = ARMISD::LSLL; 6167 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 6168 6169 // If the shift amount is greater than 32 or has a greater bitwidth than 64 6170 // then do the default optimisation 6171 if (ShAmt->getValueType(0).getSizeInBits() > 64 || 6172 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32))) 6173 return SDValue(); 6174 6175 // Extract the lower 32 bits of the shift amount if it's not an i32 6176 if (ShAmt->getValueType(0) != MVT::i32) 6177 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32); 6178 6179 if (ShOpc == ISD::SRL) { 6180 if (!Con) 6181 // There is no t2LSRLr instruction so negate and perform an lsll if the 6182 // shift amount is in a register, emulating a right shift. 6183 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6184 DAG.getConstant(0, dl, MVT::i32), ShAmt); 6185 else 6186 // Else generate an lsrl on the immediate shift amount 6187 ShPartsOpc = ARMISD::LSRL; 6188 } else if (ShOpc == ISD::SRA) 6189 ShPartsOpc = ARMISD::ASRL; 6190 6191 // Lower 32 bits of the destination/source 6192 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6193 DAG.getConstant(0, dl, MVT::i32)); 6194 // Upper 32 bits of the destination/source 6195 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6196 DAG.getConstant(1, dl, MVT::i32)); 6197 6198 // Generate the shift operation as computed above 6199 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 6200 ShAmt); 6201 // The upper 32 bits come from the second return value of lsll 6202 Hi = SDValue(Lo.getNode(), 1); 6203 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6204 } 6205 6206 // We only lower SRA, SRL of 1 here, all others use generic lowering. 6207 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 6208 return SDValue(); 6209 6210 // If we are in thumb mode, we don't have RRX. 6211 if (ST->isThumb1Only()) 6212 return SDValue(); 6213 6214 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 6215 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6216 DAG.getConstant(0, dl, MVT::i32)); 6217 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6218 DAG.getConstant(1, dl, MVT::i32)); 6219 6220 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 6221 // captures the result into a carry flag. 6222 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 6223 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 6224 6225 // The low part is an ARMISD::RRX operand, which shifts the carry in. 6226 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 6227 6228 // Merge the pieces into a single i64 value. 6229 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6230 } 6231 6232 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 6233 const ARMSubtarget *ST) { 6234 bool Invert = false; 6235 bool Swap = false; 6236 unsigned Opc = ARMCC::AL; 6237 6238 SDValue Op0 = Op.getOperand(0); 6239 SDValue Op1 = Op.getOperand(1); 6240 SDValue CC = Op.getOperand(2); 6241 EVT VT = Op.getValueType(); 6242 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 6243 SDLoc dl(Op); 6244 6245 EVT CmpVT; 6246 if (ST->hasNEON()) 6247 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 6248 else { 6249 assert(ST->hasMVEIntegerOps() && 6250 "No hardware support for integer vector comparison!"); 6251 6252 if (Op.getValueType().getVectorElementType() != MVT::i1) 6253 return SDValue(); 6254 6255 // Make sure we expand floating point setcc to scalar if we do not have 6256 // mve.fp, so that we can handle them from there. 6257 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 6258 return SDValue(); 6259 6260 CmpVT = VT; 6261 } 6262 6263 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 6264 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 6265 // Special-case integer 64-bit equality comparisons. They aren't legal, 6266 // but they can be lowered with a few vector instructions. 6267 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 6268 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 6269 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 6270 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 6271 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 6272 DAG.getCondCode(ISD::SETEQ)); 6273 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 6274 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 6275 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 6276 if (SetCCOpcode == ISD::SETNE) 6277 Merged = DAG.getNOT(dl, Merged, CmpVT); 6278 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6279 return Merged; 6280 } 6281 6282 if (CmpVT.getVectorElementType() == MVT::i64) 6283 // 64-bit comparisons are not legal in general. 6284 return SDValue(); 6285 6286 if (Op1.getValueType().isFloatingPoint()) { 6287 switch (SetCCOpcode) { 6288 default: llvm_unreachable("Illegal FP comparison"); 6289 case ISD::SETUNE: 6290 case ISD::SETNE: 6291 if (ST->hasMVEFloatOps()) { 6292 Opc = ARMCC::NE; break; 6293 } else { 6294 Invert = true; LLVM_FALLTHROUGH; 6295 } 6296 case ISD::SETOEQ: 6297 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6298 case ISD::SETOLT: 6299 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6300 case ISD::SETOGT: 6301 case ISD::SETGT: Opc = ARMCC::GT; break; 6302 case ISD::SETOLE: 6303 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6304 case ISD::SETOGE: 6305 case ISD::SETGE: Opc = ARMCC::GE; break; 6306 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6307 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6308 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6309 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6310 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6311 case ISD::SETONE: { 6312 // Expand this to (OLT | OGT). 6313 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6314 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6315 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6316 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6317 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6318 if (Invert) 6319 Result = DAG.getNOT(dl, Result, VT); 6320 return Result; 6321 } 6322 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6323 case ISD::SETO: { 6324 // Expand this to (OLT | OGE). 6325 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6326 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6327 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6328 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6329 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6330 if (Invert) 6331 Result = DAG.getNOT(dl, Result, VT); 6332 return Result; 6333 } 6334 } 6335 } else { 6336 // Integer comparisons. 6337 switch (SetCCOpcode) { 6338 default: llvm_unreachable("Illegal integer comparison"); 6339 case ISD::SETNE: 6340 if (ST->hasMVEIntegerOps()) { 6341 Opc = ARMCC::NE; break; 6342 } else { 6343 Invert = true; LLVM_FALLTHROUGH; 6344 } 6345 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6346 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6347 case ISD::SETGT: Opc = ARMCC::GT; break; 6348 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6349 case ISD::SETGE: Opc = ARMCC::GE; break; 6350 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6351 case ISD::SETUGT: Opc = ARMCC::HI; break; 6352 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6353 case ISD::SETUGE: Opc = ARMCC::HS; break; 6354 } 6355 6356 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6357 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6358 SDValue AndOp; 6359 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6360 AndOp = Op0; 6361 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6362 AndOp = Op1; 6363 6364 // Ignore bitconvert. 6365 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6366 AndOp = AndOp.getOperand(0); 6367 6368 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6369 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6370 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6371 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6372 if (!Invert) 6373 Result = DAG.getNOT(dl, Result, VT); 6374 return Result; 6375 } 6376 } 6377 } 6378 6379 if (Swap) 6380 std::swap(Op0, Op1); 6381 6382 // If one of the operands is a constant vector zero, attempt to fold the 6383 // comparison to a specialized compare-against-zero form. 6384 SDValue SingleOp; 6385 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6386 SingleOp = Op0; 6387 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6388 if (Opc == ARMCC::GE) 6389 Opc = ARMCC::LE; 6390 else if (Opc == ARMCC::GT) 6391 Opc = ARMCC::LT; 6392 SingleOp = Op1; 6393 } 6394 6395 SDValue Result; 6396 if (SingleOp.getNode()) { 6397 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6398 DAG.getConstant(Opc, dl, MVT::i32)); 6399 } else { 6400 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6401 DAG.getConstant(Opc, dl, MVT::i32)); 6402 } 6403 6404 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6405 6406 if (Invert) 6407 Result = DAG.getNOT(dl, Result, VT); 6408 6409 return Result; 6410 } 6411 6412 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6413 SDValue LHS = Op.getOperand(0); 6414 SDValue RHS = Op.getOperand(1); 6415 SDValue Carry = Op.getOperand(2); 6416 SDValue Cond = Op.getOperand(3); 6417 SDLoc DL(Op); 6418 6419 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6420 6421 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6422 // have to invert the carry first. 6423 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6424 DAG.getConstant(1, DL, MVT::i32), Carry); 6425 // This converts the boolean value carry into the carry flag. 6426 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6427 6428 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6429 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6430 6431 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6432 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6433 SDValue ARMcc = DAG.getConstant( 6434 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6435 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6436 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6437 Cmp.getValue(1), SDValue()); 6438 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6439 CCR, Chain.getValue(1)); 6440 } 6441 6442 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6443 /// valid vector constant for a NEON or MVE instruction with a "modified 6444 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6445 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6446 unsigned SplatBitSize, SelectionDAG &DAG, 6447 const SDLoc &dl, EVT &VT, EVT VectorVT, 6448 VMOVModImmType type) { 6449 unsigned OpCmode, Imm; 6450 bool is128Bits = VectorVT.is128BitVector(); 6451 6452 // SplatBitSize is set to the smallest size that splats the vector, so a 6453 // zero vector will always have SplatBitSize == 8. However, NEON modified 6454 // immediate instructions others than VMOV do not support the 8-bit encoding 6455 // of a zero vector, and the default encoding of zero is supposed to be the 6456 // 32-bit version. 6457 if (SplatBits == 0) 6458 SplatBitSize = 32; 6459 6460 switch (SplatBitSize) { 6461 case 8: 6462 if (type != VMOVModImm) 6463 return SDValue(); 6464 // Any 1-byte value is OK. Op=0, Cmode=1110. 6465 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6466 OpCmode = 0xe; 6467 Imm = SplatBits; 6468 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6469 break; 6470 6471 case 16: 6472 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6473 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6474 if ((SplatBits & ~0xff) == 0) { 6475 // Value = 0x00nn: Op=x, Cmode=100x. 6476 OpCmode = 0x8; 6477 Imm = SplatBits; 6478 break; 6479 } 6480 if ((SplatBits & ~0xff00) == 0) { 6481 // Value = 0xnn00: Op=x, Cmode=101x. 6482 OpCmode = 0xa; 6483 Imm = SplatBits >> 8; 6484 break; 6485 } 6486 return SDValue(); 6487 6488 case 32: 6489 // NEON's 32-bit VMOV supports splat values where: 6490 // * only one byte is nonzero, or 6491 // * the least significant byte is 0xff and the second byte is nonzero, or 6492 // * the least significant 2 bytes are 0xff and the third is nonzero. 6493 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6494 if ((SplatBits & ~0xff) == 0) { 6495 // Value = 0x000000nn: Op=x, Cmode=000x. 6496 OpCmode = 0; 6497 Imm = SplatBits; 6498 break; 6499 } 6500 if ((SplatBits & ~0xff00) == 0) { 6501 // Value = 0x0000nn00: Op=x, Cmode=001x. 6502 OpCmode = 0x2; 6503 Imm = SplatBits >> 8; 6504 break; 6505 } 6506 if ((SplatBits & ~0xff0000) == 0) { 6507 // Value = 0x00nn0000: Op=x, Cmode=010x. 6508 OpCmode = 0x4; 6509 Imm = SplatBits >> 16; 6510 break; 6511 } 6512 if ((SplatBits & ~0xff000000) == 0) { 6513 // Value = 0xnn000000: Op=x, Cmode=011x. 6514 OpCmode = 0x6; 6515 Imm = SplatBits >> 24; 6516 break; 6517 } 6518 6519 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6520 if (type == OtherModImm) return SDValue(); 6521 6522 if ((SplatBits & ~0xffff) == 0 && 6523 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6524 // Value = 0x0000nnff: Op=x, Cmode=1100. 6525 OpCmode = 0xc; 6526 Imm = SplatBits >> 8; 6527 break; 6528 } 6529 6530 // cmode == 0b1101 is not supported for MVE VMVN 6531 if (type == MVEVMVNModImm) 6532 return SDValue(); 6533 6534 if ((SplatBits & ~0xffffff) == 0 && 6535 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6536 // Value = 0x00nnffff: Op=x, Cmode=1101. 6537 OpCmode = 0xd; 6538 Imm = SplatBits >> 16; 6539 break; 6540 } 6541 6542 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6543 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6544 // VMOV.I32. A (very) minor optimization would be to replicate the value 6545 // and fall through here to test for a valid 64-bit splat. But, then the 6546 // caller would also need to check and handle the change in size. 6547 return SDValue(); 6548 6549 case 64: { 6550 if (type != VMOVModImm) 6551 return SDValue(); 6552 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6553 uint64_t BitMask = 0xff; 6554 uint64_t Val = 0; 6555 unsigned ImmMask = 1; 6556 Imm = 0; 6557 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6558 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6559 Val |= BitMask; 6560 Imm |= ImmMask; 6561 } else if ((SplatBits & BitMask) != 0) { 6562 return SDValue(); 6563 } 6564 BitMask <<= 8; 6565 ImmMask <<= 1; 6566 } 6567 6568 if (DAG.getDataLayout().isBigEndian()) { 6569 // Reverse the order of elements within the vector. 6570 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8; 6571 unsigned Mask = (1 << BytesPerElem) - 1; 6572 unsigned NumElems = 8 / BytesPerElem; 6573 unsigned NewImm = 0; 6574 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) { 6575 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask); 6576 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem; 6577 } 6578 Imm = NewImm; 6579 } 6580 6581 // Op=1, Cmode=1110. 6582 OpCmode = 0x1e; 6583 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6584 break; 6585 } 6586 6587 default: 6588 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6589 } 6590 6591 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6592 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6593 } 6594 6595 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6596 const ARMSubtarget *ST) const { 6597 EVT VT = Op.getValueType(); 6598 bool IsDouble = (VT == MVT::f64); 6599 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6600 const APFloat &FPVal = CFP->getValueAPF(); 6601 6602 // Prevent floating-point constants from using literal loads 6603 // when execute-only is enabled. 6604 if (ST->genExecuteOnly()) { 6605 // If we can represent the constant as an immediate, don't lower it 6606 if (isFPImmLegal(FPVal, VT)) 6607 return Op; 6608 // Otherwise, construct as integer, and move to float register 6609 APInt INTVal = FPVal.bitcastToAPInt(); 6610 SDLoc DL(CFP); 6611 switch (VT.getSimpleVT().SimpleTy) { 6612 default: 6613 llvm_unreachable("Unknown floating point type!"); 6614 break; 6615 case MVT::f64: { 6616 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6617 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6618 if (!ST->isLittle()) 6619 std::swap(Lo, Hi); 6620 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6621 } 6622 case MVT::f32: 6623 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6624 DAG.getConstant(INTVal, DL, MVT::i32)); 6625 } 6626 } 6627 6628 if (!ST->hasVFP3Base()) 6629 return SDValue(); 6630 6631 // Use the default (constant pool) lowering for double constants when we have 6632 // an SP-only FPU 6633 if (IsDouble && !Subtarget->hasFP64()) 6634 return SDValue(); 6635 6636 // Try splatting with a VMOV.f32... 6637 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6638 6639 if (ImmVal != -1) { 6640 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6641 // We have code in place to select a valid ConstantFP already, no need to 6642 // do any mangling. 6643 return Op; 6644 } 6645 6646 // It's a float and we are trying to use NEON operations where 6647 // possible. Lower it to a splat followed by an extract. 6648 SDLoc DL(Op); 6649 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6650 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6651 NewVal); 6652 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6653 DAG.getConstant(0, DL, MVT::i32)); 6654 } 6655 6656 // The rest of our options are NEON only, make sure that's allowed before 6657 // proceeding.. 6658 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6659 return SDValue(); 6660 6661 EVT VMovVT; 6662 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6663 6664 // It wouldn't really be worth bothering for doubles except for one very 6665 // important value, which does happen to match: 0.0. So make sure we don't do 6666 // anything stupid. 6667 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6668 return SDValue(); 6669 6670 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6671 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6672 VMovVT, VT, VMOVModImm); 6673 if (NewVal != SDValue()) { 6674 SDLoc DL(Op); 6675 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6676 NewVal); 6677 if (IsDouble) 6678 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6679 6680 // It's a float: cast and extract a vector element. 6681 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6682 VecConstant); 6683 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6684 DAG.getConstant(0, DL, MVT::i32)); 6685 } 6686 6687 // Finally, try a VMVN.i32 6688 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6689 VT, VMVNModImm); 6690 if (NewVal != SDValue()) { 6691 SDLoc DL(Op); 6692 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6693 6694 if (IsDouble) 6695 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6696 6697 // It's a float: cast and extract a vector element. 6698 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6699 VecConstant); 6700 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6701 DAG.getConstant(0, DL, MVT::i32)); 6702 } 6703 6704 return SDValue(); 6705 } 6706 6707 // check if an VEXT instruction can handle the shuffle mask when the 6708 // vector sources of the shuffle are the same. 6709 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6710 unsigned NumElts = VT.getVectorNumElements(); 6711 6712 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6713 if (M[0] < 0) 6714 return false; 6715 6716 Imm = M[0]; 6717 6718 // If this is a VEXT shuffle, the immediate value is the index of the first 6719 // element. The other shuffle indices must be the successive elements after 6720 // the first one. 6721 unsigned ExpectedElt = Imm; 6722 for (unsigned i = 1; i < NumElts; ++i) { 6723 // Increment the expected index. If it wraps around, just follow it 6724 // back to index zero and keep going. 6725 ++ExpectedElt; 6726 if (ExpectedElt == NumElts) 6727 ExpectedElt = 0; 6728 6729 if (M[i] < 0) continue; // ignore UNDEF indices 6730 if (ExpectedElt != static_cast<unsigned>(M[i])) 6731 return false; 6732 } 6733 6734 return true; 6735 } 6736 6737 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6738 bool &ReverseVEXT, unsigned &Imm) { 6739 unsigned NumElts = VT.getVectorNumElements(); 6740 ReverseVEXT = false; 6741 6742 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6743 if (M[0] < 0) 6744 return false; 6745 6746 Imm = M[0]; 6747 6748 // If this is a VEXT shuffle, the immediate value is the index of the first 6749 // element. The other shuffle indices must be the successive elements after 6750 // the first one. 6751 unsigned ExpectedElt = Imm; 6752 for (unsigned i = 1; i < NumElts; ++i) { 6753 // Increment the expected index. If it wraps around, it may still be 6754 // a VEXT but the source vectors must be swapped. 6755 ExpectedElt += 1; 6756 if (ExpectedElt == NumElts * 2) { 6757 ExpectedElt = 0; 6758 ReverseVEXT = true; 6759 } 6760 6761 if (M[i] < 0) continue; // ignore UNDEF indices 6762 if (ExpectedElt != static_cast<unsigned>(M[i])) 6763 return false; 6764 } 6765 6766 // Adjust the index value if the source operands will be swapped. 6767 if (ReverseVEXT) 6768 Imm -= NumElts; 6769 6770 return true; 6771 } 6772 6773 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6774 /// instruction with the specified blocksize. (The order of the elements 6775 /// within each block of the vector is reversed.) 6776 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6777 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6778 "Only possible block sizes for VREV are: 16, 32, 64"); 6779 6780 unsigned EltSz = VT.getScalarSizeInBits(); 6781 if (EltSz == 64) 6782 return false; 6783 6784 unsigned NumElts = VT.getVectorNumElements(); 6785 unsigned BlockElts = M[0] + 1; 6786 // If the first shuffle index is UNDEF, be optimistic. 6787 if (M[0] < 0) 6788 BlockElts = BlockSize / EltSz; 6789 6790 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6791 return false; 6792 6793 for (unsigned i = 0; i < NumElts; ++i) { 6794 if (M[i] < 0) continue; // ignore UNDEF indices 6795 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6796 return false; 6797 } 6798 6799 return true; 6800 } 6801 6802 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6803 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6804 // range, then 0 is placed into the resulting vector. So pretty much any mask 6805 // of 8 elements can work here. 6806 return VT == MVT::v8i8 && M.size() == 8; 6807 } 6808 6809 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6810 unsigned Index) { 6811 if (Mask.size() == Elements * 2) 6812 return Index / Elements; 6813 return Mask[Index] == 0 ? 0 : 1; 6814 } 6815 6816 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6817 // checking that pairs of elements in the shuffle mask represent the same index 6818 // in each vector, incrementing the expected index by 2 at each step. 6819 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6820 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6821 // v2={e,f,g,h} 6822 // WhichResult gives the offset for each element in the mask based on which 6823 // of the two results it belongs to. 6824 // 6825 // The transpose can be represented either as: 6826 // result1 = shufflevector v1, v2, result1_shuffle_mask 6827 // result2 = shufflevector v1, v2, result2_shuffle_mask 6828 // where v1/v2 and the shuffle masks have the same number of elements 6829 // (here WhichResult (see below) indicates which result is being checked) 6830 // 6831 // or as: 6832 // results = shufflevector v1, v2, shuffle_mask 6833 // where both results are returned in one vector and the shuffle mask has twice 6834 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6835 // want to check the low half and high half of the shuffle mask as if it were 6836 // the other case 6837 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6838 unsigned EltSz = VT.getScalarSizeInBits(); 6839 if (EltSz == 64) 6840 return false; 6841 6842 unsigned NumElts = VT.getVectorNumElements(); 6843 if (M.size() != NumElts && M.size() != NumElts*2) 6844 return false; 6845 6846 // If the mask is twice as long as the input vector then we need to check the 6847 // upper and lower parts of the mask with a matching value for WhichResult 6848 // FIXME: A mask with only even values will be rejected in case the first 6849 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6850 // M[0] is used to determine WhichResult 6851 for (unsigned i = 0; i < M.size(); i += NumElts) { 6852 WhichResult = SelectPairHalf(NumElts, M, i); 6853 for (unsigned j = 0; j < NumElts; j += 2) { 6854 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6855 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6856 return false; 6857 } 6858 } 6859 6860 if (M.size() == NumElts*2) 6861 WhichResult = 0; 6862 6863 return true; 6864 } 6865 6866 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6867 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6868 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6869 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6870 unsigned EltSz = VT.getScalarSizeInBits(); 6871 if (EltSz == 64) 6872 return false; 6873 6874 unsigned NumElts = VT.getVectorNumElements(); 6875 if (M.size() != NumElts && M.size() != NumElts*2) 6876 return false; 6877 6878 for (unsigned i = 0; i < M.size(); i += NumElts) { 6879 WhichResult = SelectPairHalf(NumElts, M, i); 6880 for (unsigned j = 0; j < NumElts; j += 2) { 6881 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6882 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6883 return false; 6884 } 6885 } 6886 6887 if (M.size() == NumElts*2) 6888 WhichResult = 0; 6889 6890 return true; 6891 } 6892 6893 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6894 // that the mask elements are either all even and in steps of size 2 or all odd 6895 // and in steps of size 2. 6896 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6897 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6898 // v2={e,f,g,h} 6899 // Requires similar checks to that of isVTRNMask with 6900 // respect the how results are returned. 6901 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6902 unsigned EltSz = VT.getScalarSizeInBits(); 6903 if (EltSz == 64) 6904 return false; 6905 6906 unsigned NumElts = VT.getVectorNumElements(); 6907 if (M.size() != NumElts && M.size() != NumElts*2) 6908 return false; 6909 6910 for (unsigned i = 0; i < M.size(); i += NumElts) { 6911 WhichResult = SelectPairHalf(NumElts, M, i); 6912 for (unsigned j = 0; j < NumElts; ++j) { 6913 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6914 return false; 6915 } 6916 } 6917 6918 if (M.size() == NumElts*2) 6919 WhichResult = 0; 6920 6921 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6922 if (VT.is64BitVector() && EltSz == 32) 6923 return false; 6924 6925 return true; 6926 } 6927 6928 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6929 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6930 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6931 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6932 unsigned EltSz = VT.getScalarSizeInBits(); 6933 if (EltSz == 64) 6934 return false; 6935 6936 unsigned NumElts = VT.getVectorNumElements(); 6937 if (M.size() != NumElts && M.size() != NumElts*2) 6938 return false; 6939 6940 unsigned Half = NumElts / 2; 6941 for (unsigned i = 0; i < M.size(); i += NumElts) { 6942 WhichResult = SelectPairHalf(NumElts, M, i); 6943 for (unsigned j = 0; j < NumElts; j += Half) { 6944 unsigned Idx = WhichResult; 6945 for (unsigned k = 0; k < Half; ++k) { 6946 int MIdx = M[i + j + k]; 6947 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6948 return false; 6949 Idx += 2; 6950 } 6951 } 6952 } 6953 6954 if (M.size() == NumElts*2) 6955 WhichResult = 0; 6956 6957 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6958 if (VT.is64BitVector() && EltSz == 32) 6959 return false; 6960 6961 return true; 6962 } 6963 6964 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6965 // that pairs of elements of the shufflemask represent the same index in each 6966 // vector incrementing sequentially through the vectors. 6967 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6968 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6969 // v2={e,f,g,h} 6970 // Requires similar checks to that of isVTRNMask with respect the how results 6971 // are returned. 6972 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6973 unsigned EltSz = VT.getScalarSizeInBits(); 6974 if (EltSz == 64) 6975 return false; 6976 6977 unsigned NumElts = VT.getVectorNumElements(); 6978 if (M.size() != NumElts && M.size() != NumElts*2) 6979 return false; 6980 6981 for (unsigned i = 0; i < M.size(); i += NumElts) { 6982 WhichResult = SelectPairHalf(NumElts, M, i); 6983 unsigned Idx = WhichResult * NumElts / 2; 6984 for (unsigned j = 0; j < NumElts; j += 2) { 6985 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6986 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6987 return false; 6988 Idx += 1; 6989 } 6990 } 6991 6992 if (M.size() == NumElts*2) 6993 WhichResult = 0; 6994 6995 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6996 if (VT.is64BitVector() && EltSz == 32) 6997 return false; 6998 6999 return true; 7000 } 7001 7002 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 7003 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7004 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 7005 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7006 unsigned EltSz = VT.getScalarSizeInBits(); 7007 if (EltSz == 64) 7008 return false; 7009 7010 unsigned NumElts = VT.getVectorNumElements(); 7011 if (M.size() != NumElts && M.size() != NumElts*2) 7012 return false; 7013 7014 for (unsigned i = 0; i < M.size(); i += NumElts) { 7015 WhichResult = SelectPairHalf(NumElts, M, i); 7016 unsigned Idx = WhichResult * NumElts / 2; 7017 for (unsigned j = 0; j < NumElts; j += 2) { 7018 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7019 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 7020 return false; 7021 Idx += 1; 7022 } 7023 } 7024 7025 if (M.size() == NumElts*2) 7026 WhichResult = 0; 7027 7028 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7029 if (VT.is64BitVector() && EltSz == 32) 7030 return false; 7031 7032 return true; 7033 } 7034 7035 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 7036 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 7037 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 7038 unsigned &WhichResult, 7039 bool &isV_UNDEF) { 7040 isV_UNDEF = false; 7041 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 7042 return ARMISD::VTRN; 7043 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 7044 return ARMISD::VUZP; 7045 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 7046 return ARMISD::VZIP; 7047 7048 isV_UNDEF = true; 7049 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7050 return ARMISD::VTRN; 7051 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7052 return ARMISD::VUZP; 7053 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7054 return ARMISD::VZIP; 7055 7056 return 0; 7057 } 7058 7059 /// \return true if this is a reverse operation on an vector. 7060 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 7061 unsigned NumElts = VT.getVectorNumElements(); 7062 // Make sure the mask has the right size. 7063 if (NumElts != M.size()) 7064 return false; 7065 7066 // Look for <15, ..., 3, -1, 1, 0>. 7067 for (unsigned i = 0; i != NumElts; ++i) 7068 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 7069 return false; 7070 7071 return true; 7072 } 7073 7074 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) { 7075 unsigned NumElts = VT.getVectorNumElements(); 7076 // Make sure the mask has the right size. 7077 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8)) 7078 return false; 7079 7080 // If Top 7081 // Look for <0, N, 2, N+2, 4, N+4, ..>. 7082 // This inserts Input2 into Input1 7083 // else if not Top 7084 // Look for <0, N+1, 2, N+3, 4, N+5, ..> 7085 // This inserts Input1 into Input2 7086 unsigned Offset = Top ? 0 : 1; 7087 for (unsigned i = 0; i < NumElts; i+=2) { 7088 if (M[i] >= 0 && M[i] != (int)i) 7089 return false; 7090 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset)) 7091 return false; 7092 } 7093 7094 return true; 7095 } 7096 7097 // If N is an integer constant that can be moved into a register in one 7098 // instruction, return an SDValue of such a constant (will become a MOV 7099 // instruction). Otherwise return null. 7100 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 7101 const ARMSubtarget *ST, const SDLoc &dl) { 7102 uint64_t Val; 7103 if (!isa<ConstantSDNode>(N)) 7104 return SDValue(); 7105 Val = cast<ConstantSDNode>(N)->getZExtValue(); 7106 7107 if (ST->isThumb1Only()) { 7108 if (Val <= 255 || ~Val <= 255) 7109 return DAG.getConstant(Val, dl, MVT::i32); 7110 } else { 7111 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 7112 return DAG.getConstant(Val, dl, MVT::i32); 7113 } 7114 return SDValue(); 7115 } 7116 7117 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 7118 const ARMSubtarget *ST) { 7119 SDLoc dl(Op); 7120 EVT VT = Op.getValueType(); 7121 7122 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 7123 7124 unsigned NumElts = VT.getVectorNumElements(); 7125 unsigned BoolMask; 7126 unsigned BitsPerBool; 7127 if (NumElts == 4) { 7128 BitsPerBool = 4; 7129 BoolMask = 0xf; 7130 } else if (NumElts == 8) { 7131 BitsPerBool = 2; 7132 BoolMask = 0x3; 7133 } else if (NumElts == 16) { 7134 BitsPerBool = 1; 7135 BoolMask = 0x1; 7136 } else 7137 return SDValue(); 7138 7139 // If this is a single value copied into all lanes (a splat), we can just sign 7140 // extend that single value 7141 SDValue FirstOp = Op.getOperand(0); 7142 if (!isa<ConstantSDNode>(FirstOp) && 7143 std::all_of(std::next(Op->op_begin()), Op->op_end(), 7144 [&FirstOp](SDUse &U) { 7145 return U.get().isUndef() || U.get() == FirstOp; 7146 })) { 7147 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp, 7148 DAG.getValueType(MVT::i1)); 7149 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext); 7150 } 7151 7152 // First create base with bits set where known 7153 unsigned Bits32 = 0; 7154 for (unsigned i = 0; i < NumElts; ++i) { 7155 SDValue V = Op.getOperand(i); 7156 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 7157 continue; 7158 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 7159 if (BitSet) 7160 Bits32 |= BoolMask << (i * BitsPerBool); 7161 } 7162 7163 // Add in unknown nodes 7164 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 7165 DAG.getConstant(Bits32, dl, MVT::i32)); 7166 for (unsigned i = 0; i < NumElts; ++i) { 7167 SDValue V = Op.getOperand(i); 7168 if (isa<ConstantSDNode>(V) || V.isUndef()) 7169 continue; 7170 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 7171 DAG.getConstant(i, dl, MVT::i32)); 7172 } 7173 7174 return Base; 7175 } 7176 7177 // If this is a case we can't handle, return null and let the default 7178 // expansion code take care of it. 7179 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 7180 const ARMSubtarget *ST) const { 7181 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7182 SDLoc dl(Op); 7183 EVT VT = Op.getValueType(); 7184 7185 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7186 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 7187 7188 APInt SplatBits, SplatUndef; 7189 unsigned SplatBitSize; 7190 bool HasAnyUndefs; 7191 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7192 if (SplatUndef.isAllOnesValue()) 7193 return DAG.getUNDEF(VT); 7194 7195 if ((ST->hasNEON() && SplatBitSize <= 64) || 7196 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) { 7197 // Check if an immediate VMOV works. 7198 EVT VmovVT; 7199 SDValue Val = 7200 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 7201 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm); 7202 7203 if (Val.getNode()) { 7204 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 7205 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7206 } 7207 7208 // Try an immediate VMVN. 7209 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 7210 Val = isVMOVModifiedImm( 7211 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT, 7212 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 7213 if (Val.getNode()) { 7214 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 7215 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7216 } 7217 7218 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 7219 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 7220 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 7221 if (ImmVal != -1) { 7222 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 7223 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 7224 } 7225 } 7226 } 7227 } 7228 7229 // Scan through the operands to see if only one value is used. 7230 // 7231 // As an optimisation, even if more than one value is used it may be more 7232 // profitable to splat with one value then change some lanes. 7233 // 7234 // Heuristically we decide to do this if the vector has a "dominant" value, 7235 // defined as splatted to more than half of the lanes. 7236 unsigned NumElts = VT.getVectorNumElements(); 7237 bool isOnlyLowElement = true; 7238 bool usesOnlyOneValue = true; 7239 bool hasDominantValue = false; 7240 bool isConstant = true; 7241 7242 // Map of the number of times a particular SDValue appears in the 7243 // element list. 7244 DenseMap<SDValue, unsigned> ValueCounts; 7245 SDValue Value; 7246 for (unsigned i = 0; i < NumElts; ++i) { 7247 SDValue V = Op.getOperand(i); 7248 if (V.isUndef()) 7249 continue; 7250 if (i > 0) 7251 isOnlyLowElement = false; 7252 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7253 isConstant = false; 7254 7255 ValueCounts.insert(std::make_pair(V, 0)); 7256 unsigned &Count = ValueCounts[V]; 7257 7258 // Is this value dominant? (takes up more than half of the lanes) 7259 if (++Count > (NumElts / 2)) { 7260 hasDominantValue = true; 7261 Value = V; 7262 } 7263 } 7264 if (ValueCounts.size() != 1) 7265 usesOnlyOneValue = false; 7266 if (!Value.getNode() && !ValueCounts.empty()) 7267 Value = ValueCounts.begin()->first; 7268 7269 if (ValueCounts.empty()) 7270 return DAG.getUNDEF(VT); 7271 7272 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 7273 // Keep going if we are hitting this case. 7274 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 7275 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7276 7277 unsigned EltSize = VT.getScalarSizeInBits(); 7278 7279 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 7280 // i32 and try again. 7281 if (hasDominantValue && EltSize <= 32) { 7282 if (!isConstant) { 7283 SDValue N; 7284 7285 // If we are VDUPing a value that comes directly from a vector, that will 7286 // cause an unnecessary move to and from a GPR, where instead we could 7287 // just use VDUPLANE. We can only do this if the lane being extracted 7288 // is at a constant index, as the VDUP from lane instructions only have 7289 // constant-index forms. 7290 ConstantSDNode *constIndex; 7291 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7292 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 7293 // We need to create a new undef vector to use for the VDUPLANE if the 7294 // size of the vector from which we get the value is different than the 7295 // size of the vector that we need to create. We will insert the element 7296 // such that the register coalescer will remove unnecessary copies. 7297 if (VT != Value->getOperand(0).getValueType()) { 7298 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 7299 VT.getVectorNumElements(); 7300 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7301 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 7302 Value, DAG.getConstant(index, dl, MVT::i32)), 7303 DAG.getConstant(index, dl, MVT::i32)); 7304 } else 7305 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7306 Value->getOperand(0), Value->getOperand(1)); 7307 } else 7308 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 7309 7310 if (!usesOnlyOneValue) { 7311 // The dominant value was splatted as 'N', but we now have to insert 7312 // all differing elements. 7313 for (unsigned I = 0; I < NumElts; ++I) { 7314 if (Op.getOperand(I) == Value) 7315 continue; 7316 SmallVector<SDValue, 3> Ops; 7317 Ops.push_back(N); 7318 Ops.push_back(Op.getOperand(I)); 7319 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7320 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7321 } 7322 } 7323 return N; 7324 } 7325 if (VT.getVectorElementType().isFloatingPoint()) { 7326 SmallVector<SDValue, 8> Ops; 7327 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7328 assert(FVT == MVT::f32 || FVT == MVT::f16); 7329 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7330 for (unsigned i = 0; i < NumElts; ++i) 7331 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7332 Op.getOperand(i))); 7333 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7334 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7335 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7336 if (Val.getNode()) 7337 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7338 } 7339 if (usesOnlyOneValue) { 7340 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7341 if (isConstant && Val.getNode()) 7342 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7343 } 7344 } 7345 7346 // If all elements are constants and the case above didn't get hit, fall back 7347 // to the default expansion, which will generate a load from the constant 7348 // pool. 7349 if (isConstant) 7350 return SDValue(); 7351 7352 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 7353 if (NumElts >= 4) { 7354 SDValue shuffle = ReconstructShuffle(Op, DAG); 7355 if (shuffle != SDValue()) 7356 return shuffle; 7357 } 7358 7359 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7360 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7361 // into two 64-bit vectors; we might discover a better way to lower it. 7362 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7363 EVT ExtVT = VT.getVectorElementType(); 7364 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7365 SDValue Lower = 7366 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7367 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7368 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7369 SDValue Upper = DAG.getBuildVector( 7370 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7371 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7372 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7373 if (Lower && Upper) 7374 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7375 } 7376 7377 // Vectors with 32- or 64-bit elements can be built by directly assigning 7378 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7379 // will be legalized. 7380 if (EltSize >= 32) { 7381 // Do the expansion with floating-point types, since that is what the VFP 7382 // registers are defined to use, and since i64 is not legal. 7383 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7384 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7385 SmallVector<SDValue, 8> Ops; 7386 for (unsigned i = 0; i < NumElts; ++i) 7387 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7388 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7389 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7390 } 7391 7392 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7393 // know the default expansion would otherwise fall back on something even 7394 // worse. For a vector with one or two non-undef values, that's 7395 // scalar_to_vector for the elements followed by a shuffle (provided the 7396 // shuffle is valid for the target) and materialization element by element 7397 // on the stack followed by a load for everything else. 7398 if (!isConstant && !usesOnlyOneValue) { 7399 SDValue Vec = DAG.getUNDEF(VT); 7400 for (unsigned i = 0 ; i < NumElts; ++i) { 7401 SDValue V = Op.getOperand(i); 7402 if (V.isUndef()) 7403 continue; 7404 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7405 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7406 } 7407 return Vec; 7408 } 7409 7410 return SDValue(); 7411 } 7412 7413 // Gather data to see if the operation can be modelled as a 7414 // shuffle in combination with VEXTs. 7415 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7416 SelectionDAG &DAG) const { 7417 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7418 SDLoc dl(Op); 7419 EVT VT = Op.getValueType(); 7420 unsigned NumElts = VT.getVectorNumElements(); 7421 7422 struct ShuffleSourceInfo { 7423 SDValue Vec; 7424 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7425 unsigned MaxElt = 0; 7426 7427 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7428 // be compatible with the shuffle we intend to construct. As a result 7429 // ShuffleVec will be some sliding window into the original Vec. 7430 SDValue ShuffleVec; 7431 7432 // Code should guarantee that element i in Vec starts at element "WindowBase 7433 // + i * WindowScale in ShuffleVec". 7434 int WindowBase = 0; 7435 int WindowScale = 1; 7436 7437 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7438 7439 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7440 }; 7441 7442 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7443 // node. 7444 SmallVector<ShuffleSourceInfo, 2> Sources; 7445 for (unsigned i = 0; i < NumElts; ++i) { 7446 SDValue V = Op.getOperand(i); 7447 if (V.isUndef()) 7448 continue; 7449 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7450 // A shuffle can only come from building a vector from various 7451 // elements of other vectors. 7452 return SDValue(); 7453 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7454 // Furthermore, shuffles require a constant mask, whereas extractelts 7455 // accept variable indices. 7456 return SDValue(); 7457 } 7458 7459 // Add this element source to the list if it's not already there. 7460 SDValue SourceVec = V.getOperand(0); 7461 auto Source = llvm::find(Sources, SourceVec); 7462 if (Source == Sources.end()) 7463 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7464 7465 // Update the minimum and maximum lane number seen. 7466 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7467 Source->MinElt = std::min(Source->MinElt, EltNo); 7468 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7469 } 7470 7471 // Currently only do something sane when at most two source vectors 7472 // are involved. 7473 if (Sources.size() > 2) 7474 return SDValue(); 7475 7476 // Find out the smallest element size among result and two sources, and use 7477 // it as element size to build the shuffle_vector. 7478 EVT SmallestEltTy = VT.getVectorElementType(); 7479 for (auto &Source : Sources) { 7480 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7481 if (SrcEltTy.bitsLT(SmallestEltTy)) 7482 SmallestEltTy = SrcEltTy; 7483 } 7484 unsigned ResMultiplier = 7485 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7486 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7487 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7488 7489 // If the source vector is too wide or too narrow, we may nevertheless be able 7490 // to construct a compatible shuffle either by concatenating it with UNDEF or 7491 // extracting a suitable range of elements. 7492 for (auto &Src : Sources) { 7493 EVT SrcVT = Src.ShuffleVec.getValueType(); 7494 7495 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 7496 continue; 7497 7498 // This stage of the search produces a source with the same element type as 7499 // the original, but with a total width matching the BUILD_VECTOR output. 7500 EVT EltVT = SrcVT.getVectorElementType(); 7501 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 7502 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7503 7504 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 7505 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 7506 return SDValue(); 7507 // We can pad out the smaller vector for free, so if it's part of a 7508 // shuffle... 7509 Src.ShuffleVec = 7510 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7511 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7512 continue; 7513 } 7514 7515 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 7516 return SDValue(); 7517 7518 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7519 // Span too large for a VEXT to cope 7520 return SDValue(); 7521 } 7522 7523 if (Src.MinElt >= NumSrcElts) { 7524 // The extraction can just take the second half 7525 Src.ShuffleVec = 7526 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7527 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7528 Src.WindowBase = -NumSrcElts; 7529 } else if (Src.MaxElt < NumSrcElts) { 7530 // The extraction can just take the first half 7531 Src.ShuffleVec = 7532 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7533 DAG.getConstant(0, dl, MVT::i32)); 7534 } else { 7535 // An actual VEXT is needed 7536 SDValue VEXTSrc1 = 7537 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7538 DAG.getConstant(0, dl, MVT::i32)); 7539 SDValue VEXTSrc2 = 7540 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7541 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7542 7543 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7544 VEXTSrc2, 7545 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7546 Src.WindowBase = -Src.MinElt; 7547 } 7548 } 7549 7550 // Another possible incompatibility occurs from the vector element types. We 7551 // can fix this by bitcasting the source vectors to the same type we intend 7552 // for the shuffle. 7553 for (auto &Src : Sources) { 7554 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7555 if (SrcEltTy == SmallestEltTy) 7556 continue; 7557 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7558 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec); 7559 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7560 Src.WindowBase *= Src.WindowScale; 7561 } 7562 7563 // Final sanity check before we try to actually produce a shuffle. 7564 LLVM_DEBUG(for (auto Src 7565 : Sources) 7566 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7567 7568 // The stars all align, our next step is to produce the mask for the shuffle. 7569 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7570 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7571 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7572 SDValue Entry = Op.getOperand(i); 7573 if (Entry.isUndef()) 7574 continue; 7575 7576 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7577 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7578 7579 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7580 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7581 // segment. 7582 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7583 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 7584 VT.getScalarSizeInBits()); 7585 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7586 7587 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7588 // starting at the appropriate offset. 7589 int *LaneMask = &Mask[i * ResMultiplier]; 7590 7591 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7592 ExtractBase += NumElts * (Src - Sources.begin()); 7593 for (int j = 0; j < LanesDefined; ++j) 7594 LaneMask[j] = ExtractBase + j; 7595 } 7596 7597 7598 // We can't handle more than two sources. This should have already 7599 // been checked before this point. 7600 assert(Sources.size() <= 2 && "Too many sources!"); 7601 7602 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7603 for (unsigned i = 0; i < Sources.size(); ++i) 7604 ShuffleOps[i] = Sources[i].ShuffleVec; 7605 7606 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7607 ShuffleOps[1], Mask, DAG); 7608 if (!Shuffle) 7609 return SDValue(); 7610 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle); 7611 } 7612 7613 enum ShuffleOpCodes { 7614 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7615 OP_VREV, 7616 OP_VDUP0, 7617 OP_VDUP1, 7618 OP_VDUP2, 7619 OP_VDUP3, 7620 OP_VEXT1, 7621 OP_VEXT2, 7622 OP_VEXT3, 7623 OP_VUZPL, // VUZP, left result 7624 OP_VUZPR, // VUZP, right result 7625 OP_VZIPL, // VZIP, left result 7626 OP_VZIPR, // VZIP, right result 7627 OP_VTRNL, // VTRN, left result 7628 OP_VTRNR // VTRN, right result 7629 }; 7630 7631 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7632 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7633 switch (OpNum) { 7634 case OP_COPY: 7635 case OP_VREV: 7636 case OP_VDUP0: 7637 case OP_VDUP1: 7638 case OP_VDUP2: 7639 case OP_VDUP3: 7640 return true; 7641 } 7642 return false; 7643 } 7644 7645 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7646 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7647 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7648 /// are assumed to be legal. 7649 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7650 if (VT.getVectorNumElements() == 4 && 7651 (VT.is128BitVector() || VT.is64BitVector())) { 7652 unsigned PFIndexes[4]; 7653 for (unsigned i = 0; i != 4; ++i) { 7654 if (M[i] < 0) 7655 PFIndexes[i] = 8; 7656 else 7657 PFIndexes[i] = M[i]; 7658 } 7659 7660 // Compute the index in the perfect shuffle table. 7661 unsigned PFTableIndex = 7662 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7663 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7664 unsigned Cost = (PFEntry >> 30); 7665 7666 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7667 return true; 7668 } 7669 7670 bool ReverseVEXT, isV_UNDEF; 7671 unsigned Imm, WhichResult; 7672 7673 unsigned EltSize = VT.getScalarSizeInBits(); 7674 if (EltSize >= 32 || 7675 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7676 ShuffleVectorInst::isIdentityMask(M) || 7677 isVREVMask(M, VT, 64) || 7678 isVREVMask(M, VT, 32) || 7679 isVREVMask(M, VT, 16)) 7680 return true; 7681 else if (Subtarget->hasNEON() && 7682 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7683 isVTBLMask(M, VT) || 7684 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7685 return true; 7686 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7687 isReverseMask(M, VT)) 7688 return true; 7689 else if (Subtarget->hasMVEIntegerOps() && 7690 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1))) 7691 return true; 7692 else 7693 return false; 7694 } 7695 7696 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7697 /// the specified operations to build the shuffle. 7698 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7699 SDValue RHS, SelectionDAG &DAG, 7700 const SDLoc &dl) { 7701 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7702 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7703 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7704 7705 if (OpNum == OP_COPY) { 7706 if (LHSID == (1*9+2)*9+3) return LHS; 7707 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7708 return RHS; 7709 } 7710 7711 SDValue OpLHS, OpRHS; 7712 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7713 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7714 EVT VT = OpLHS.getValueType(); 7715 7716 switch (OpNum) { 7717 default: llvm_unreachable("Unknown shuffle opcode!"); 7718 case OP_VREV: 7719 // VREV divides the vector in half and swaps within the half. 7720 if (VT.getVectorElementType() == MVT::i32 || 7721 VT.getVectorElementType() == MVT::f32) 7722 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7723 // vrev <4 x i16> -> VREV32 7724 if (VT.getVectorElementType() == MVT::i16) 7725 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7726 // vrev <4 x i8> -> VREV16 7727 assert(VT.getVectorElementType() == MVT::i8); 7728 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 7729 case OP_VDUP0: 7730 case OP_VDUP1: 7731 case OP_VDUP2: 7732 case OP_VDUP3: 7733 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7734 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 7735 case OP_VEXT1: 7736 case OP_VEXT2: 7737 case OP_VEXT3: 7738 return DAG.getNode(ARMISD::VEXT, dl, VT, 7739 OpLHS, OpRHS, 7740 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 7741 case OP_VUZPL: 7742 case OP_VUZPR: 7743 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7744 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7745 case OP_VZIPL: 7746 case OP_VZIPR: 7747 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7748 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7749 case OP_VTRNL: 7750 case OP_VTRNR: 7751 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7752 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7753 } 7754 } 7755 7756 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7757 ArrayRef<int> ShuffleMask, 7758 SelectionDAG &DAG) { 7759 // Check to see if we can use the VTBL instruction. 7760 SDValue V1 = Op.getOperand(0); 7761 SDValue V2 = Op.getOperand(1); 7762 SDLoc DL(Op); 7763 7764 SmallVector<SDValue, 8> VTBLMask; 7765 for (ArrayRef<int>::iterator 7766 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7767 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7768 7769 if (V2.getNode()->isUndef()) 7770 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7771 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7772 7773 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7774 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7775 } 7776 7777 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7778 SelectionDAG &DAG) { 7779 SDLoc DL(Op); 7780 SDValue OpLHS = Op.getOperand(0); 7781 EVT VT = OpLHS.getValueType(); 7782 7783 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7784 "Expect an v8i16/v16i8 type"); 7785 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7786 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7787 // extract the first 8 bytes into the top double word and the last 8 bytes 7788 // into the bottom double word. The v8i16 case is similar. 7789 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7790 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7791 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7792 } 7793 7794 static EVT getVectorTyFromPredicateVector(EVT VT) { 7795 switch (VT.getSimpleVT().SimpleTy) { 7796 case MVT::v4i1: 7797 return MVT::v4i32; 7798 case MVT::v8i1: 7799 return MVT::v8i16; 7800 case MVT::v16i1: 7801 return MVT::v16i8; 7802 default: 7803 llvm_unreachable("Unexpected vector predicate type"); 7804 } 7805 } 7806 7807 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 7808 SelectionDAG &DAG) { 7809 // Converting from boolean predicates to integers involves creating a vector 7810 // of all ones or all zeroes and selecting the lanes based upon the real 7811 // predicate. 7812 SDValue AllOnes = 7813 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 7814 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 7815 7816 SDValue AllZeroes = 7817 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 7818 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 7819 7820 // Get full vector type from predicate type 7821 EVT NewVT = getVectorTyFromPredicateVector(VT); 7822 7823 SDValue RecastV1; 7824 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 7825 // this to a v16i1. This cannot be done with an ordinary bitcast because the 7826 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 7827 // since we know in hardware the sizes are really the same. 7828 if (VT != MVT::v16i1) 7829 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 7830 else 7831 RecastV1 = Pred; 7832 7833 // Select either all ones or zeroes depending upon the real predicate bits. 7834 SDValue PredAsVector = 7835 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 7836 7837 // Recast our new predicate-as-integer v16i8 vector into something 7838 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 7839 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 7840 } 7841 7842 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 7843 const ARMSubtarget *ST) { 7844 EVT VT = Op.getValueType(); 7845 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7846 ArrayRef<int> ShuffleMask = SVN->getMask(); 7847 7848 assert(ST->hasMVEIntegerOps() && 7849 "No support for vector shuffle of boolean predicates"); 7850 7851 SDValue V1 = Op.getOperand(0); 7852 SDLoc dl(Op); 7853 if (isReverseMask(ShuffleMask, VT)) { 7854 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 7855 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 7856 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 7857 DAG.getConstant(16, dl, MVT::i32)); 7858 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 7859 } 7860 7861 // Until we can come up with optimised cases for every single vector 7862 // shuffle in existence we have chosen the least painful strategy. This is 7863 // to essentially promote the boolean predicate to a 8-bit integer, where 7864 // each predicate represents a byte. Then we fall back on a normal integer 7865 // vector shuffle and convert the result back into a predicate vector. In 7866 // many cases the generated code might be even better than scalar code 7867 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 7868 // fields in a register into 8 other arbitrary 2-bit fields! 7869 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 7870 EVT NewVT = PredAsVector.getValueType(); 7871 7872 // Do the shuffle! 7873 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 7874 DAG.getUNDEF(NewVT), ShuffleMask); 7875 7876 // Now return the result of comparing the shuffled vector with zero, 7877 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7878 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 7879 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7880 } 7881 7882 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op, 7883 ArrayRef<int> ShuffleMask, 7884 SelectionDAG &DAG) { 7885 // Attempt to lower the vector shuffle using as many whole register movs as 7886 // possible. This is useful for types smaller than 32bits, which would 7887 // often otherwise become a series for grp movs. 7888 SDLoc dl(Op); 7889 EVT VT = Op.getValueType(); 7890 if (VT.getScalarSizeInBits() >= 32) 7891 return SDValue(); 7892 7893 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && 7894 "Unexpected vector type"); 7895 int NumElts = VT.getVectorNumElements(); 7896 int QuarterSize = NumElts / 4; 7897 // The four final parts of the vector, as i32's 7898 SDValue Parts[4]; 7899 7900 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not 7901 // <u,u,u,u>), returning the vmov lane index 7902 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) { 7903 // Detect which mov lane this would be from the first non-undef element. 7904 int MovIdx = -1; 7905 for (int i = 0; i < Length; i++) { 7906 if (ShuffleMask[Start + i] >= 0) { 7907 if (ShuffleMask[Start + i] % Length != i) 7908 return -1; 7909 MovIdx = ShuffleMask[Start + i] / Length; 7910 break; 7911 } 7912 } 7913 // If all items are undef, leave this for other combines 7914 if (MovIdx == -1) 7915 return -1; 7916 // Check the remaining values are the correct part of the same mov 7917 for (int i = 1; i < Length; i++) { 7918 if (ShuffleMask[Start + i] >= 0 && 7919 (ShuffleMask[Start + i] / Length != MovIdx || 7920 ShuffleMask[Start + i] % Length != i)) 7921 return -1; 7922 } 7923 return MovIdx; 7924 }; 7925 7926 for (int Part = 0; Part < 4; ++Part) { 7927 // Does this part look like a mov 7928 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize); 7929 if (Elt != -1) { 7930 SDValue Input = Op->getOperand(0); 7931 if (Elt >= 4) { 7932 Input = Op->getOperand(1); 7933 Elt -= 4; 7934 } 7935 SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input); 7936 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast, 7937 DAG.getConstant(Elt, dl, MVT::i32)); 7938 } 7939 } 7940 7941 // Nothing interesting found, just return 7942 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3]) 7943 return SDValue(); 7944 7945 // The other parts need to be built with the old shuffle vector, cast to a 7946 // v4i32 and extract_vector_elts 7947 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) { 7948 SmallVector<int, 16> NewShuffleMask; 7949 for (int Part = 0; Part < 4; ++Part) 7950 for (int i = 0; i < QuarterSize; i++) 7951 NewShuffleMask.push_back( 7952 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]); 7953 SDValue NewShuffle = DAG.getVectorShuffle( 7954 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask); 7955 SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle); 7956 7957 for (int Part = 0; Part < 4; ++Part) 7958 if (!Parts[Part]) 7959 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7960 BitCast, DAG.getConstant(Part, dl, MVT::i32)); 7961 } 7962 // Build a vector out of the various parts and bitcast it back to the original 7963 // type. 7964 SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts); 7965 return DAG.getBitcast(VT, NewVec); 7966 } 7967 7968 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 7969 const ARMSubtarget *ST) { 7970 SDValue V1 = Op.getOperand(0); 7971 SDValue V2 = Op.getOperand(1); 7972 SDLoc dl(Op); 7973 EVT VT = Op.getValueType(); 7974 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7975 unsigned EltSize = VT.getScalarSizeInBits(); 7976 7977 if (ST->hasMVEIntegerOps() && EltSize == 1) 7978 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 7979 7980 // Convert shuffles that are directly supported on NEON to target-specific 7981 // DAG nodes, instead of keeping them as shuffles and matching them again 7982 // during code selection. This is more efficient and avoids the possibility 7983 // of inconsistencies between legalization and selection. 7984 // FIXME: floating-point vectors should be canonicalized to integer vectors 7985 // of the same time so that they get CSEd properly. 7986 ArrayRef<int> ShuffleMask = SVN->getMask(); 7987 7988 if (EltSize <= 32) { 7989 if (SVN->isSplat()) { 7990 int Lane = SVN->getSplatIndex(); 7991 // If this is undef splat, generate it via "just" vdup, if possible. 7992 if (Lane == -1) Lane = 0; 7993 7994 // Test if V1 is a SCALAR_TO_VECTOR. 7995 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7996 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7997 } 7998 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7999 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 8000 // reaches it). 8001 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 8002 !isa<ConstantSDNode>(V1.getOperand(0))) { 8003 bool IsScalarToVector = true; 8004 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 8005 if (!V1.getOperand(i).isUndef()) { 8006 IsScalarToVector = false; 8007 break; 8008 } 8009 if (IsScalarToVector) 8010 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8011 } 8012 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 8013 DAG.getConstant(Lane, dl, MVT::i32)); 8014 } 8015 8016 bool ReverseVEXT = false; 8017 unsigned Imm = 0; 8018 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 8019 if (ReverseVEXT) 8020 std::swap(V1, V2); 8021 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 8022 DAG.getConstant(Imm, dl, MVT::i32)); 8023 } 8024 8025 if (isVREVMask(ShuffleMask, VT, 64)) 8026 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 8027 if (isVREVMask(ShuffleMask, VT, 32)) 8028 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 8029 if (isVREVMask(ShuffleMask, VT, 16)) 8030 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 8031 8032 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 8033 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 8034 DAG.getConstant(Imm, dl, MVT::i32)); 8035 } 8036 8037 // Check for Neon shuffles that modify both input vectors in place. 8038 // If both results are used, i.e., if there are two shuffles with the same 8039 // source operands and with masks corresponding to both results of one of 8040 // these operations, DAG memoization will ensure that a single node is 8041 // used for both shuffles. 8042 unsigned WhichResult = 0; 8043 bool isV_UNDEF = false; 8044 if (ST->hasNEON()) { 8045 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8046 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 8047 if (isV_UNDEF) 8048 V2 = V1; 8049 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 8050 .getValue(WhichResult); 8051 } 8052 } 8053 if (ST->hasMVEIntegerOps()) { 8054 if (isVMOVNMask(ShuffleMask, VT, 0)) 8055 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1, 8056 DAG.getConstant(0, dl, MVT::i32)); 8057 if (isVMOVNMask(ShuffleMask, VT, 1)) 8058 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2, 8059 DAG.getConstant(1, dl, MVT::i32)); 8060 } 8061 8062 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 8063 // shuffles that produce a result larger than their operands with: 8064 // shuffle(concat(v1, undef), concat(v2, undef)) 8065 // -> 8066 // shuffle(concat(v1, v2), undef) 8067 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 8068 // 8069 // This is useful in the general case, but there are special cases where 8070 // native shuffles produce larger results: the two-result ops. 8071 // 8072 // Look through the concat when lowering them: 8073 // shuffle(concat(v1, v2), undef) 8074 // -> 8075 // concat(VZIP(v1, v2):0, :1) 8076 // 8077 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 8078 SDValue SubV1 = V1->getOperand(0); 8079 SDValue SubV2 = V1->getOperand(1); 8080 EVT SubVT = SubV1.getValueType(); 8081 8082 // We expect these to have been canonicalized to -1. 8083 assert(llvm::all_of(ShuffleMask, [&](int i) { 8084 return i < (int)VT.getVectorNumElements(); 8085 }) && "Unexpected shuffle index into UNDEF operand!"); 8086 8087 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8088 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 8089 if (isV_UNDEF) 8090 SubV2 = SubV1; 8091 assert((WhichResult == 0) && 8092 "In-place shuffle of concat can only have one result!"); 8093 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 8094 SubV1, SubV2); 8095 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 8096 Res.getValue(1)); 8097 } 8098 } 8099 } 8100 8101 // If the shuffle is not directly supported and it has 4 elements, use 8102 // the PerfectShuffle-generated table to synthesize it from other shuffles. 8103 unsigned NumElts = VT.getVectorNumElements(); 8104 if (NumElts == 4) { 8105 unsigned PFIndexes[4]; 8106 for (unsigned i = 0; i != 4; ++i) { 8107 if (ShuffleMask[i] < 0) 8108 PFIndexes[i] = 8; 8109 else 8110 PFIndexes[i] = ShuffleMask[i]; 8111 } 8112 8113 // Compute the index in the perfect shuffle table. 8114 unsigned PFTableIndex = 8115 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8116 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8117 unsigned Cost = (PFEntry >> 30); 8118 8119 if (Cost <= 4) { 8120 if (ST->hasNEON()) 8121 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8122 else if (isLegalMVEShuffleOp(PFEntry)) { 8123 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8124 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8125 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 8126 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 8127 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 8128 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8129 } 8130 } 8131 } 8132 8133 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 8134 if (EltSize >= 32) { 8135 // Do the expansion with floating-point types, since that is what the VFP 8136 // registers are defined to use, and since i64 is not legal. 8137 EVT EltVT = EVT::getFloatingPointVT(EltSize); 8138 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 8139 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 8140 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 8141 SmallVector<SDValue, 8> Ops; 8142 for (unsigned i = 0; i < NumElts; ++i) { 8143 if (ShuffleMask[i] < 0) 8144 Ops.push_back(DAG.getUNDEF(EltVT)); 8145 else 8146 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 8147 ShuffleMask[i] < (int)NumElts ? V1 : V2, 8148 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 8149 dl, MVT::i32))); 8150 } 8151 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 8152 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8153 } 8154 8155 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 8156 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 8157 8158 if (ST->hasNEON() && VT == MVT::v8i8) 8159 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 8160 return NewOp; 8161 8162 if (ST->hasMVEIntegerOps()) 8163 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG)) 8164 return NewOp; 8165 8166 return SDValue(); 8167 } 8168 8169 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8170 const ARMSubtarget *ST) { 8171 EVT VecVT = Op.getOperand(0).getValueType(); 8172 SDLoc dl(Op); 8173 8174 assert(ST->hasMVEIntegerOps() && 8175 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8176 8177 SDValue Conv = 8178 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8179 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8180 unsigned LaneWidth = 8181 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8182 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 8183 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 8184 Op.getOperand(1), DAG.getValueType(MVT::i1)); 8185 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 8186 DAG.getConstant(~Mask, dl, MVT::i32)); 8187 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 8188 } 8189 8190 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8191 SelectionDAG &DAG) const { 8192 // INSERT_VECTOR_ELT is legal only for immediate indexes. 8193 SDValue Lane = Op.getOperand(2); 8194 if (!isa<ConstantSDNode>(Lane)) 8195 return SDValue(); 8196 8197 SDValue Elt = Op.getOperand(1); 8198 EVT EltVT = Elt.getValueType(); 8199 8200 if (Subtarget->hasMVEIntegerOps() && 8201 Op.getValueType().getScalarSizeInBits() == 1) 8202 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 8203 8204 if (getTypeAction(*DAG.getContext(), EltVT) == 8205 TargetLowering::TypePromoteFloat) { 8206 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 8207 // but the type system will try to do that if we don't intervene. 8208 // Reinterpret any such vector-element insertion as one with the 8209 // corresponding integer types. 8210 8211 SDLoc dl(Op); 8212 8213 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 8214 assert(getTypeAction(*DAG.getContext(), IEltVT) != 8215 TargetLowering::TypePromoteFloat); 8216 8217 SDValue VecIn = Op.getOperand(0); 8218 EVT VecVT = VecIn.getValueType(); 8219 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 8220 VecVT.getVectorNumElements()); 8221 8222 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 8223 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 8224 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 8225 IVecIn, IElt, Lane); 8226 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 8227 } 8228 8229 return Op; 8230 } 8231 8232 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8233 const ARMSubtarget *ST) { 8234 EVT VecVT = Op.getOperand(0).getValueType(); 8235 SDLoc dl(Op); 8236 8237 assert(ST->hasMVEIntegerOps() && 8238 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8239 8240 SDValue Conv = 8241 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8242 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8243 unsigned LaneWidth = 8244 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8245 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 8246 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 8247 return Shift; 8248 } 8249 8250 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 8251 const ARMSubtarget *ST) { 8252 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 8253 SDValue Lane = Op.getOperand(1); 8254 if (!isa<ConstantSDNode>(Lane)) 8255 return SDValue(); 8256 8257 SDValue Vec = Op.getOperand(0); 8258 EVT VT = Vec.getValueType(); 8259 8260 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8261 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 8262 8263 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 8264 SDLoc dl(Op); 8265 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 8266 } 8267 8268 return Op; 8269 } 8270 8271 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 8272 const ARMSubtarget *ST) { 8273 SDValue V1 = Op.getOperand(0); 8274 SDValue V2 = Op.getOperand(1); 8275 SDLoc dl(Op); 8276 EVT VT = Op.getValueType(); 8277 EVT Op1VT = V1.getValueType(); 8278 EVT Op2VT = V2.getValueType(); 8279 unsigned NumElts = VT.getVectorNumElements(); 8280 8281 assert(Op1VT == Op2VT && "Operand types don't match!"); 8282 assert(VT.getScalarSizeInBits() == 1 && 8283 "Unexpected custom CONCAT_VECTORS lowering"); 8284 assert(ST->hasMVEIntegerOps() && 8285 "CONCAT_VECTORS lowering only supported for MVE"); 8286 8287 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8288 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 8289 8290 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 8291 // promoted to v8i16, etc. 8292 8293 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8294 8295 // Extract the vector elements from Op1 and Op2 one by one and truncate them 8296 // to be the right size for the destination. For example, if Op1 is v4i1 then 8297 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 8298 // which when promoted is v8i16. That means each i32 element from Op1 needs 8299 // truncating to i16 and inserting in the result. 8300 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 8301 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 8302 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 8303 EVT NewVT = NewV.getValueType(); 8304 EVT ConcatVT = ConVec.getValueType(); 8305 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 8306 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 8307 DAG.getIntPtrConstant(i, dl)); 8308 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 8309 DAG.getConstant(j, dl, MVT::i32)); 8310 } 8311 return ConVec; 8312 }; 8313 unsigned j = 0; 8314 ConVec = ExractInto(NewV1, ConVec, j); 8315 ConVec = ExractInto(NewV2, ConVec, j); 8316 8317 // Now return the result of comparing the subvector with zero, 8318 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8319 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 8320 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8321 } 8322 8323 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 8324 const ARMSubtarget *ST) { 8325 EVT VT = Op->getValueType(0); 8326 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8327 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 8328 8329 // The only time a CONCAT_VECTORS operation can have legal types is when 8330 // two 64-bit vectors are concatenated to a 128-bit vector. 8331 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 8332 "unexpected CONCAT_VECTORS"); 8333 SDLoc dl(Op); 8334 SDValue Val = DAG.getUNDEF(MVT::v2f64); 8335 SDValue Op0 = Op.getOperand(0); 8336 SDValue Op1 = Op.getOperand(1); 8337 if (!Op0.isUndef()) 8338 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8339 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 8340 DAG.getIntPtrConstant(0, dl)); 8341 if (!Op1.isUndef()) 8342 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8343 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 8344 DAG.getIntPtrConstant(1, dl)); 8345 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 8346 } 8347 8348 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 8349 const ARMSubtarget *ST) { 8350 SDValue V1 = Op.getOperand(0); 8351 SDValue V2 = Op.getOperand(1); 8352 SDLoc dl(Op); 8353 EVT VT = Op.getValueType(); 8354 EVT Op1VT = V1.getValueType(); 8355 unsigned NumElts = VT.getVectorNumElements(); 8356 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 8357 8358 assert(VT.getScalarSizeInBits() == 1 && 8359 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 8360 assert(ST->hasMVEIntegerOps() && 8361 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 8362 8363 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8364 8365 // We now have Op1 promoted to a vector of integers, where v8i1 gets 8366 // promoted to v8i16, etc. 8367 8368 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8369 8370 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 8371 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 8372 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 8373 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 8374 DAG.getIntPtrConstant(i, dl)); 8375 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 8376 DAG.getConstant(j, dl, MVT::i32)); 8377 } 8378 8379 // Now return the result of comparing the subvector with zero, 8380 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8381 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 8382 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8383 } 8384 8385 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 8386 /// element has been zero/sign-extended, depending on the isSigned parameter, 8387 /// from an integer type half its size. 8388 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 8389 bool isSigned) { 8390 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 8391 EVT VT = N->getValueType(0); 8392 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 8393 SDNode *BVN = N->getOperand(0).getNode(); 8394 if (BVN->getValueType(0) != MVT::v4i32 || 8395 BVN->getOpcode() != ISD::BUILD_VECTOR) 8396 return false; 8397 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8398 unsigned HiElt = 1 - LoElt; 8399 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 8400 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 8401 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 8402 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 8403 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 8404 return false; 8405 if (isSigned) { 8406 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 8407 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 8408 return true; 8409 } else { 8410 if (Hi0->isNullValue() && Hi1->isNullValue()) 8411 return true; 8412 } 8413 return false; 8414 } 8415 8416 if (N->getOpcode() != ISD::BUILD_VECTOR) 8417 return false; 8418 8419 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8420 SDNode *Elt = N->getOperand(i).getNode(); 8421 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8422 unsigned EltSize = VT.getScalarSizeInBits(); 8423 unsigned HalfSize = EltSize / 2; 8424 if (isSigned) { 8425 if (!isIntN(HalfSize, C->getSExtValue())) 8426 return false; 8427 } else { 8428 if (!isUIntN(HalfSize, C->getZExtValue())) 8429 return false; 8430 } 8431 continue; 8432 } 8433 return false; 8434 } 8435 8436 return true; 8437 } 8438 8439 /// isSignExtended - Check if a node is a vector value that is sign-extended 8440 /// or a constant BUILD_VECTOR with sign-extended elements. 8441 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8442 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8443 return true; 8444 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8445 return true; 8446 return false; 8447 } 8448 8449 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8450 /// or a constant BUILD_VECTOR with zero-extended elements. 8451 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8452 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8453 return true; 8454 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8455 return true; 8456 return false; 8457 } 8458 8459 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8460 if (OrigVT.getSizeInBits() >= 64) 8461 return OrigVT; 8462 8463 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8464 8465 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8466 switch (OrigSimpleTy) { 8467 default: llvm_unreachable("Unexpected Vector Type"); 8468 case MVT::v2i8: 8469 case MVT::v2i16: 8470 return MVT::v2i32; 8471 case MVT::v4i8: 8472 return MVT::v4i16; 8473 } 8474 } 8475 8476 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8477 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8478 /// We insert the required extension here to get the vector to fill a D register. 8479 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8480 const EVT &OrigTy, 8481 const EVT &ExtTy, 8482 unsigned ExtOpcode) { 8483 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8484 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8485 // 64-bits we need to insert a new extension so that it will be 64-bits. 8486 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8487 if (OrigTy.getSizeInBits() >= 64) 8488 return N; 8489 8490 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8491 EVT NewVT = getExtensionTo64Bits(OrigTy); 8492 8493 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8494 } 8495 8496 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8497 /// does not do any sign/zero extension. If the original vector is less 8498 /// than 64 bits, an appropriate extension will be added after the load to 8499 /// reach a total size of 64 bits. We have to add the extension separately 8500 /// because ARM does not have a sign/zero extending load for vectors. 8501 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8502 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8503 8504 // The load already has the right type. 8505 if (ExtendedTy == LD->getMemoryVT()) 8506 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8507 LD->getBasePtr(), LD->getPointerInfo(), 8508 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8509 8510 // We need to create a zextload/sextload. We cannot just create a load 8511 // followed by a zext/zext node because LowerMUL is also run during normal 8512 // operation legalization where we can't create illegal types. 8513 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8514 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8515 LD->getMemoryVT(), LD->getAlignment(), 8516 LD->getMemOperand()->getFlags()); 8517 } 8518 8519 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8520 /// extending load, or BUILD_VECTOR with extended elements, return the 8521 /// unextended value. The unextended vector should be 64 bits so that it can 8522 /// be used as an operand to a VMULL instruction. If the original vector size 8523 /// before extension is less than 64 bits we add a an extension to resize 8524 /// the vector to 64 bits. 8525 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8526 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8527 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8528 N->getOperand(0)->getValueType(0), 8529 N->getValueType(0), 8530 N->getOpcode()); 8531 8532 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8533 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8534 "Expected extending load"); 8535 8536 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8537 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8538 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8539 SDValue extLoad = 8540 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8541 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8542 8543 return newLoad; 8544 } 8545 8546 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8547 // have been legalized as a BITCAST from v4i32. 8548 if (N->getOpcode() == ISD::BITCAST) { 8549 SDNode *BVN = N->getOperand(0).getNode(); 8550 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8551 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8552 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8553 return DAG.getBuildVector( 8554 MVT::v2i32, SDLoc(N), 8555 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8556 } 8557 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8558 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8559 EVT VT = N->getValueType(0); 8560 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8561 unsigned NumElts = VT.getVectorNumElements(); 8562 MVT TruncVT = MVT::getIntegerVT(EltSize); 8563 SmallVector<SDValue, 8> Ops; 8564 SDLoc dl(N); 8565 for (unsigned i = 0; i != NumElts; ++i) { 8566 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8567 const APInt &CInt = C->getAPIntValue(); 8568 // Element types smaller than 32 bits are not legal, so use i32 elements. 8569 // The values are implicitly truncated so sext vs. zext doesn't matter. 8570 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8571 } 8572 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8573 } 8574 8575 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8576 unsigned Opcode = N->getOpcode(); 8577 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8578 SDNode *N0 = N->getOperand(0).getNode(); 8579 SDNode *N1 = N->getOperand(1).getNode(); 8580 return N0->hasOneUse() && N1->hasOneUse() && 8581 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8582 } 8583 return false; 8584 } 8585 8586 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8587 unsigned Opcode = N->getOpcode(); 8588 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8589 SDNode *N0 = N->getOperand(0).getNode(); 8590 SDNode *N1 = N->getOperand(1).getNode(); 8591 return N0->hasOneUse() && N1->hasOneUse() && 8592 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8593 } 8594 return false; 8595 } 8596 8597 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8598 // Multiplications are only custom-lowered for 128-bit vectors so that 8599 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8600 EVT VT = Op.getValueType(); 8601 assert(VT.is128BitVector() && VT.isInteger() && 8602 "unexpected type for custom-lowering ISD::MUL"); 8603 SDNode *N0 = Op.getOperand(0).getNode(); 8604 SDNode *N1 = Op.getOperand(1).getNode(); 8605 unsigned NewOpc = 0; 8606 bool isMLA = false; 8607 bool isN0SExt = isSignExtended(N0, DAG); 8608 bool isN1SExt = isSignExtended(N1, DAG); 8609 if (isN0SExt && isN1SExt) 8610 NewOpc = ARMISD::VMULLs; 8611 else { 8612 bool isN0ZExt = isZeroExtended(N0, DAG); 8613 bool isN1ZExt = isZeroExtended(N1, DAG); 8614 if (isN0ZExt && isN1ZExt) 8615 NewOpc = ARMISD::VMULLu; 8616 else if (isN1SExt || isN1ZExt) { 8617 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8618 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8619 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8620 NewOpc = ARMISD::VMULLs; 8621 isMLA = true; 8622 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8623 NewOpc = ARMISD::VMULLu; 8624 isMLA = true; 8625 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8626 std::swap(N0, N1); 8627 NewOpc = ARMISD::VMULLu; 8628 isMLA = true; 8629 } 8630 } 8631 8632 if (!NewOpc) { 8633 if (VT == MVT::v2i64) 8634 // Fall through to expand this. It is not legal. 8635 return SDValue(); 8636 else 8637 // Other vector multiplications are legal. 8638 return Op; 8639 } 8640 } 8641 8642 // Legalize to a VMULL instruction. 8643 SDLoc DL(Op); 8644 SDValue Op0; 8645 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8646 if (!isMLA) { 8647 Op0 = SkipExtensionForVMULL(N0, DAG); 8648 assert(Op0.getValueType().is64BitVector() && 8649 Op1.getValueType().is64BitVector() && 8650 "unexpected types for extended operands to VMULL"); 8651 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8652 } 8653 8654 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8655 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8656 // vmull q0, d4, d6 8657 // vmlal q0, d5, d6 8658 // is faster than 8659 // vaddl q0, d4, d5 8660 // vmovl q1, d6 8661 // vmul q0, q0, q1 8662 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8663 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8664 EVT Op1VT = Op1.getValueType(); 8665 return DAG.getNode(N0->getOpcode(), DL, VT, 8666 DAG.getNode(NewOpc, DL, VT, 8667 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8668 DAG.getNode(NewOpc, DL, VT, 8669 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8670 } 8671 8672 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8673 SelectionDAG &DAG) { 8674 // TODO: Should this propagate fast-math-flags? 8675 8676 // Convert to float 8677 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8678 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8679 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8680 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8681 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8682 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8683 // Get reciprocal estimate. 8684 // float4 recip = vrecpeq_f32(yf); 8685 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8686 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8687 Y); 8688 // Because char has a smaller range than uchar, we can actually get away 8689 // without any newton steps. This requires that we use a weird bias 8690 // of 0xb000, however (again, this has been exhaustively tested). 8691 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8692 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8693 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8694 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8695 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8696 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8697 // Convert back to short. 8698 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8699 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8700 return X; 8701 } 8702 8703 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8704 SelectionDAG &DAG) { 8705 // TODO: Should this propagate fast-math-flags? 8706 8707 SDValue N2; 8708 // Convert to float. 8709 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8710 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8711 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8712 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8713 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8714 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8715 8716 // Use reciprocal estimate and one refinement step. 8717 // float4 recip = vrecpeq_f32(yf); 8718 // recip *= vrecpsq_f32(yf, recip); 8719 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8720 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8721 N1); 8722 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8723 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8724 N1, N2); 8725 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8726 // Because short has a smaller range than ushort, we can actually get away 8727 // with only a single newton step. This requires that we use a weird bias 8728 // of 89, however (again, this has been exhaustively tested). 8729 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 8730 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8731 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8732 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 8733 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8734 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8735 // Convert back to integer and return. 8736 // return vmovn_s32(vcvt_s32_f32(result)); 8737 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8738 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8739 return N0; 8740 } 8741 8742 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 8743 const ARMSubtarget *ST) { 8744 EVT VT = Op.getValueType(); 8745 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8746 "unexpected type for custom-lowering ISD::SDIV"); 8747 8748 SDLoc dl(Op); 8749 SDValue N0 = Op.getOperand(0); 8750 SDValue N1 = Op.getOperand(1); 8751 SDValue N2, N3; 8752 8753 if (VT == MVT::v8i8) { 8754 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 8755 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 8756 8757 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8758 DAG.getIntPtrConstant(4, dl)); 8759 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8760 DAG.getIntPtrConstant(4, dl)); 8761 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8762 DAG.getIntPtrConstant(0, dl)); 8763 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8764 DAG.getIntPtrConstant(0, dl)); 8765 8766 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 8767 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 8768 8769 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8770 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8771 8772 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 8773 return N0; 8774 } 8775 return LowerSDIV_v4i16(N0, N1, dl, DAG); 8776 } 8777 8778 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 8779 const ARMSubtarget *ST) { 8780 // TODO: Should this propagate fast-math-flags? 8781 EVT VT = Op.getValueType(); 8782 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8783 "unexpected type for custom-lowering ISD::UDIV"); 8784 8785 SDLoc dl(Op); 8786 SDValue N0 = Op.getOperand(0); 8787 SDValue N1 = Op.getOperand(1); 8788 SDValue N2, N3; 8789 8790 if (VT == MVT::v8i8) { 8791 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 8792 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 8793 8794 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8795 DAG.getIntPtrConstant(4, dl)); 8796 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8797 DAG.getIntPtrConstant(4, dl)); 8798 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8799 DAG.getIntPtrConstant(0, dl)); 8800 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8801 DAG.getIntPtrConstant(0, dl)); 8802 8803 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 8804 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 8805 8806 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8807 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8808 8809 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 8810 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 8811 MVT::i32), 8812 N0); 8813 return N0; 8814 } 8815 8816 // v4i16 sdiv ... Convert to float. 8817 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 8818 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 8819 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 8820 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 8821 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8822 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8823 8824 // Use reciprocal estimate and two refinement steps. 8825 // float4 recip = vrecpeq_f32(yf); 8826 // recip *= vrecpsq_f32(yf, recip); 8827 // recip *= vrecpsq_f32(yf, recip); 8828 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8829 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8830 BN1); 8831 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8832 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8833 BN1, N2); 8834 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8835 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8836 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8837 BN1, N2); 8838 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8839 // Simply multiplying by the reciprocal estimate can leave us a few ulps 8840 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 8841 // and that it will never cause us to return an answer too large). 8842 // float4 result = as_float4(as_int4(xf*recip) + 2); 8843 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8844 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8845 N1 = DAG.getConstant(2, dl, MVT::v4i32); 8846 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8847 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8848 // Convert back to integer and return. 8849 // return vmovn_u32(vcvt_s32_f32(result)); 8850 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8851 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8852 return N0; 8853 } 8854 8855 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 8856 SDNode *N = Op.getNode(); 8857 EVT VT = N->getValueType(0); 8858 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 8859 8860 SDValue Carry = Op.getOperand(2); 8861 8862 SDLoc DL(Op); 8863 8864 SDValue Result; 8865 if (Op.getOpcode() == ISD::ADDCARRY) { 8866 // This converts the boolean value carry into the carry flag. 8867 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8868 8869 // Do the addition proper using the carry flag we wanted. 8870 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 8871 Op.getOperand(1), Carry); 8872 8873 // Now convert the carry flag into a boolean value. 8874 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8875 } else { 8876 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 8877 // have to invert the carry first. 8878 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8879 DAG.getConstant(1, DL, MVT::i32), Carry); 8880 // This converts the boolean value carry into the carry flag. 8881 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8882 8883 // Do the subtraction proper using the carry flag we wanted. 8884 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 8885 Op.getOperand(1), Carry); 8886 8887 // Now convert the carry flag into a boolean value. 8888 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8889 // But the carry returned by ARMISD::SUBE is not a borrow as expected 8890 // by ISD::SUBCARRY, so compute 1 - C. 8891 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8892 DAG.getConstant(1, DL, MVT::i32), Carry); 8893 } 8894 8895 // Return both values. 8896 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 8897 } 8898 8899 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 8900 assert(Subtarget->isTargetDarwin()); 8901 8902 // For iOS, we want to call an alternative entry point: __sincos_stret, 8903 // return values are passed via sret. 8904 SDLoc dl(Op); 8905 SDValue Arg = Op.getOperand(0); 8906 EVT ArgVT = Arg.getValueType(); 8907 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 8908 auto PtrVT = getPointerTy(DAG.getDataLayout()); 8909 8910 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8911 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8912 8913 // Pair of floats / doubles used to pass the result. 8914 Type *RetTy = StructType::get(ArgTy, ArgTy); 8915 auto &DL = DAG.getDataLayout(); 8916 8917 ArgListTy Args; 8918 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 8919 SDValue SRet; 8920 if (ShouldUseSRet) { 8921 // Create stack object for sret. 8922 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 8923 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 8924 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 8925 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 8926 8927 ArgListEntry Entry; 8928 Entry.Node = SRet; 8929 Entry.Ty = RetTy->getPointerTo(); 8930 Entry.IsSExt = false; 8931 Entry.IsZExt = false; 8932 Entry.IsSRet = true; 8933 Args.push_back(Entry); 8934 RetTy = Type::getVoidTy(*DAG.getContext()); 8935 } 8936 8937 ArgListEntry Entry; 8938 Entry.Node = Arg; 8939 Entry.Ty = ArgTy; 8940 Entry.IsSExt = false; 8941 Entry.IsZExt = false; 8942 Args.push_back(Entry); 8943 8944 RTLIB::Libcall LC = 8945 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 8946 const char *LibcallName = getLibcallName(LC); 8947 CallingConv::ID CC = getLibcallCallingConv(LC); 8948 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 8949 8950 TargetLowering::CallLoweringInfo CLI(DAG); 8951 CLI.setDebugLoc(dl) 8952 .setChain(DAG.getEntryNode()) 8953 .setCallee(CC, RetTy, Callee, std::move(Args)) 8954 .setDiscardResult(ShouldUseSRet); 8955 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8956 8957 if (!ShouldUseSRet) 8958 return CallResult.first; 8959 8960 SDValue LoadSin = 8961 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 8962 8963 // Address of cos field. 8964 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 8965 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 8966 SDValue LoadCos = 8967 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 8968 8969 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 8970 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 8971 LoadSin.getValue(0), LoadCos.getValue(0)); 8972 } 8973 8974 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 8975 bool Signed, 8976 SDValue &Chain) const { 8977 EVT VT = Op.getValueType(); 8978 assert((VT == MVT::i32 || VT == MVT::i64) && 8979 "unexpected type for custom lowering DIV"); 8980 SDLoc dl(Op); 8981 8982 const auto &DL = DAG.getDataLayout(); 8983 const auto &TLI = DAG.getTargetLoweringInfo(); 8984 8985 const char *Name = nullptr; 8986 if (Signed) 8987 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 8988 else 8989 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 8990 8991 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 8992 8993 ARMTargetLowering::ArgListTy Args; 8994 8995 for (auto AI : {1, 0}) { 8996 ArgListEntry Arg; 8997 Arg.Node = Op.getOperand(AI); 8998 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 8999 Args.push_back(Arg); 9000 } 9001 9002 CallLoweringInfo CLI(DAG); 9003 CLI.setDebugLoc(dl) 9004 .setChain(Chain) 9005 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 9006 ES, std::move(Args)); 9007 9008 return LowerCallTo(CLI).first; 9009 } 9010 9011 // This is a code size optimisation: return the original SDIV node to 9012 // DAGCombiner when we don't want to expand SDIV into a sequence of 9013 // instructions, and an empty node otherwise which will cause the 9014 // SDIV to be expanded in DAGCombine. 9015 SDValue 9016 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 9017 SelectionDAG &DAG, 9018 SmallVectorImpl<SDNode *> &Created) const { 9019 // TODO: Support SREM 9020 if (N->getOpcode() != ISD::SDIV) 9021 return SDValue(); 9022 9023 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 9024 const bool MinSize = ST.hasMinSize(); 9025 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 9026 : ST.hasDivideInARMMode(); 9027 9028 // Don't touch vector types; rewriting this may lead to scalarizing 9029 // the int divs. 9030 if (N->getOperand(0).getValueType().isVector()) 9031 return SDValue(); 9032 9033 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 9034 // hwdiv support for this to be really profitable. 9035 if (!(MinSize && HasDivide)) 9036 return SDValue(); 9037 9038 // ARM mode is a bit simpler than Thumb: we can handle large power 9039 // of 2 immediates with 1 mov instruction; no further checks required, 9040 // just return the sdiv node. 9041 if (!ST.isThumb()) 9042 return SDValue(N, 0); 9043 9044 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 9045 // and thus lose the code size benefits of a MOVS that requires only 2. 9046 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 9047 // but as it's doing exactly this, it's not worth the trouble to get TTI. 9048 if (Divisor.sgt(128)) 9049 return SDValue(); 9050 9051 return SDValue(N, 0); 9052 } 9053 9054 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 9055 bool Signed) const { 9056 assert(Op.getValueType() == MVT::i32 && 9057 "unexpected type for custom lowering DIV"); 9058 SDLoc dl(Op); 9059 9060 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 9061 DAG.getEntryNode(), Op.getOperand(1)); 9062 9063 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9064 } 9065 9066 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 9067 SDLoc DL(N); 9068 SDValue Op = N->getOperand(1); 9069 if (N->getValueType(0) == MVT::i32) 9070 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 9071 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9072 DAG.getConstant(0, DL, MVT::i32)); 9073 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9074 DAG.getConstant(1, DL, MVT::i32)); 9075 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 9076 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 9077 } 9078 9079 void ARMTargetLowering::ExpandDIV_Windows( 9080 SDValue Op, SelectionDAG &DAG, bool Signed, 9081 SmallVectorImpl<SDValue> &Results) const { 9082 const auto &DL = DAG.getDataLayout(); 9083 const auto &TLI = DAG.getTargetLoweringInfo(); 9084 9085 assert(Op.getValueType() == MVT::i64 && 9086 "unexpected type for custom lowering DIV"); 9087 SDLoc dl(Op); 9088 9089 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 9090 9091 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9092 9093 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 9094 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 9095 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 9096 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 9097 9098 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper)); 9099 } 9100 9101 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) { 9102 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode()); 9103 EVT MemVT = LD->getMemoryVT(); 9104 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9105 "Expected a predicate type!"); 9106 assert(MemVT == Op.getValueType()); 9107 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && 9108 "Expected a non-extending load"); 9109 assert(LD->isUnindexed() && "Expected a unindexed load"); 9110 9111 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit 9112 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We 9113 // need to make sure that 8/4 bits are actually loaded into the correct 9114 // place, which means loading the value and then shuffling the values into 9115 // the bottom bits of the predicate. 9116 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect 9117 // for BE). 9118 9119 SDLoc dl(Op); 9120 SDValue Load = DAG.getExtLoad( 9121 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(), 9122 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9123 LD->getMemOperand()); 9124 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load); 9125 if (MemVT != MVT::v16i1) 9126 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred, 9127 DAG.getConstant(0, dl, MVT::i32)); 9128 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl); 9129 } 9130 9131 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results, 9132 SelectionDAG &DAG) const { 9133 LoadSDNode *LD = cast<LoadSDNode>(N); 9134 EVT MemVT = LD->getMemoryVT(); 9135 assert(LD->isUnindexed() && "Loads should be unindexed at this point."); 9136 9137 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9138 !Subtarget->isThumb1Only() && LD->isVolatile()) { 9139 SDLoc dl(N); 9140 SDValue Result = DAG.getMemIntrinsicNode( 9141 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}), 9142 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand()); 9143 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1); 9144 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0); 9145 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 9146 Results.append({Pair, Result.getValue(2)}); 9147 } 9148 } 9149 9150 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) { 9151 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9152 EVT MemVT = ST->getMemoryVT(); 9153 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9154 "Expected a predicate type!"); 9155 assert(MemVT == ST->getValue().getValueType()); 9156 assert(!ST->isTruncatingStore() && "Expected a non-extending store"); 9157 assert(ST->isUnindexed() && "Expected a unindexed store"); 9158 9159 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits 9160 // unset and a scalar store. 9161 SDLoc dl(Op); 9162 SDValue Build = ST->getValue(); 9163 if (MemVT != MVT::v16i1) { 9164 SmallVector<SDValue, 16> Ops; 9165 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) 9166 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build, 9167 DAG.getConstant(I, dl, MVT::i32))); 9168 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++) 9169 Ops.push_back(DAG.getUNDEF(MVT::i32)); 9170 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops); 9171 } 9172 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build); 9173 return DAG.getTruncStore( 9174 ST->getChain(), dl, GRP, ST->getBasePtr(), 9175 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9176 ST->getMemOperand()); 9177 } 9178 9179 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG, 9180 const ARMSubtarget *Subtarget) { 9181 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9182 EVT MemVT = ST->getMemoryVT(); 9183 assert(ST->isUnindexed() && "Stores should be unindexed at this point."); 9184 9185 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9186 !Subtarget->isThumb1Only() && ST->isVolatile()) { 9187 SDNode *N = Op.getNode(); 9188 SDLoc dl(N); 9189 9190 SDValue Lo = DAG.getNode( 9191 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9192 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl, 9193 MVT::i32)); 9194 SDValue Hi = DAG.getNode( 9195 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9196 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl, 9197 MVT::i32)); 9198 9199 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other), 9200 {ST->getChain(), Lo, Hi, ST->getBasePtr()}, 9201 MemVT, ST->getMemOperand()); 9202 } else if (Subtarget->hasMVEIntegerOps() && 9203 ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || 9204 MemVT == MVT::v16i1))) { 9205 return LowerPredicateStore(Op, DAG); 9206 } 9207 9208 return SDValue(); 9209 } 9210 9211 static bool isZeroVector(SDValue N) { 9212 return (ISD::isBuildVectorAllZeros(N.getNode()) || 9213 (N->getOpcode() == ARMISD::VMOVIMM && 9214 isNullConstant(N->getOperand(0)))); 9215 } 9216 9217 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) { 9218 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode()); 9219 MVT VT = Op.getSimpleValueType(); 9220 SDValue Mask = N->getMask(); 9221 SDValue PassThru = N->getPassThru(); 9222 SDLoc dl(Op); 9223 9224 if (isZeroVector(PassThru)) 9225 return Op; 9226 9227 // MVE Masked loads use zero as the passthru value. Here we convert undef to 9228 // zero too, and other values are lowered to a select. 9229 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 9230 DAG.getTargetConstant(0, dl, MVT::i32)); 9231 SDValue NewLoad = DAG.getMaskedLoad( 9232 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec, 9233 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(), 9234 N->getExtensionType(), N->isExpandingLoad()); 9235 SDValue Combo = NewLoad; 9236 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST || 9237 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) && 9238 isZeroVector(PassThru->getOperand(0)); 9239 if (!PassThru.isUndef() && !PassThruIsCastZero) 9240 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru); 9241 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl); 9242 } 9243 9244 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 9245 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 9246 // Acquire/Release load/store is not legal for targets without a dmb or 9247 // equivalent available. 9248 return SDValue(); 9249 9250 // Monotonic load/store is legal for all targets. 9251 return Op; 9252 } 9253 9254 static void ReplaceREADCYCLECOUNTER(SDNode *N, 9255 SmallVectorImpl<SDValue> &Results, 9256 SelectionDAG &DAG, 9257 const ARMSubtarget *Subtarget) { 9258 SDLoc DL(N); 9259 // Under Power Management extensions, the cycle-count is: 9260 // mrc p15, #0, <Rt>, c9, c13, #0 9261 SDValue Ops[] = { N->getOperand(0), // Chain 9262 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 9263 DAG.getTargetConstant(15, DL, MVT::i32), 9264 DAG.getTargetConstant(0, DL, MVT::i32), 9265 DAG.getTargetConstant(9, DL, MVT::i32), 9266 DAG.getTargetConstant(13, DL, MVT::i32), 9267 DAG.getTargetConstant(0, DL, MVT::i32) 9268 }; 9269 9270 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 9271 DAG.getVTList(MVT::i32, MVT::Other), Ops); 9272 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 9273 DAG.getConstant(0, DL, MVT::i32))); 9274 Results.push_back(Cycles32.getValue(1)); 9275 } 9276 9277 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 9278 SDLoc dl(V.getNode()); 9279 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 9280 SDValue VHi = DAG.getAnyExtOrTrunc( 9281 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 9282 dl, MVT::i32); 9283 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9284 if (isBigEndian) 9285 std::swap (VLo, VHi); 9286 SDValue RegClass = 9287 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 9288 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 9289 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 9290 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 9291 return SDValue( 9292 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 9293 } 9294 9295 static void ReplaceCMP_SWAP_64Results(SDNode *N, 9296 SmallVectorImpl<SDValue> & Results, 9297 SelectionDAG &DAG) { 9298 assert(N->getValueType(0) == MVT::i64 && 9299 "AtomicCmpSwap on types less than 64 should be legal"); 9300 SDValue Ops[] = {N->getOperand(1), 9301 createGPRPairNode(DAG, N->getOperand(2)), 9302 createGPRPairNode(DAG, N->getOperand(3)), 9303 N->getOperand(0)}; 9304 SDNode *CmpSwap = DAG.getMachineNode( 9305 ARM::CMP_SWAP_64, SDLoc(N), 9306 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 9307 9308 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 9309 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 9310 9311 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9312 9313 SDValue Lo = 9314 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 9315 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9316 SDValue Hi = 9317 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 9318 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9319 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi)); 9320 Results.push_back(SDValue(CmpSwap, 2)); 9321 } 9322 9323 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const { 9324 SDLoc dl(Op); 9325 EVT VT = Op.getValueType(); 9326 SDValue Chain = Op.getOperand(0); 9327 SDValue LHS = Op.getOperand(1); 9328 SDValue RHS = Op.getOperand(2); 9329 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get(); 9330 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 9331 9332 // If we don't have instructions of this float type then soften to a libcall 9333 // and use SETCC instead. 9334 if (isUnsupportedFloatingType(LHS.getValueType())) { 9335 DAG.getTargetLoweringInfo().softenSetCCOperands( 9336 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling); 9337 if (!RHS.getNode()) { 9338 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 9339 CC = ISD::SETNE; 9340 } 9341 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS, 9342 DAG.getCondCode(CC)); 9343 return DAG.getMergeValues({Result, Chain}, dl); 9344 } 9345 9346 ARMCC::CondCodes CondCode, CondCode2; 9347 FPCCToARMCC(CC, CondCode, CondCode2); 9348 9349 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit 9350 // in CMPFP and CMPFPE, but instead it should be made explicit by these 9351 // instructions using a chain instead of glue. This would also fix the problem 9352 // here (and also in LowerSELECT_CC) where we generate two comparisons when 9353 // CondCode2 != AL. 9354 SDValue True = DAG.getConstant(1, dl, VT); 9355 SDValue False = DAG.getConstant(0, dl, VT); 9356 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 9357 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 9358 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9359 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG); 9360 if (CondCode2 != ARMCC::AL) { 9361 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 9362 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9363 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG); 9364 } 9365 return DAG.getMergeValues({Result, Chain}, dl); 9366 } 9367 9368 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9369 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 9370 switch (Op.getOpcode()) { 9371 default: llvm_unreachable("Don't know how to custom lower this!"); 9372 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 9373 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9374 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9375 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9376 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9377 case ISD::SELECT: return LowerSELECT(Op, DAG); 9378 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9379 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9380 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 9381 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 9382 case ISD::VASTART: return LowerVASTART(Op, DAG); 9383 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 9384 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 9385 case ISD::SINT_TO_FP: 9386 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9387 case ISD::STRICT_FP_TO_SINT: 9388 case ISD::STRICT_FP_TO_UINT: 9389 case ISD::FP_TO_SINT: 9390 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 9391 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9392 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9393 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9394 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 9395 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 9396 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 9397 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget); 9398 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 9399 Subtarget); 9400 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 9401 case ISD::SHL: 9402 case ISD::SRL: 9403 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 9404 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 9405 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 9406 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 9407 case ISD::SRL_PARTS: 9408 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 9409 case ISD::CTTZ: 9410 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 9411 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 9412 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 9413 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 9414 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 9415 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 9416 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 9417 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 9418 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9419 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 9420 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 9421 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9422 case ISD::MUL: return LowerMUL(Op, DAG); 9423 case ISD::SDIV: 9424 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9425 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 9426 return LowerSDIV(Op, DAG, Subtarget); 9427 case ISD::UDIV: 9428 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9429 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 9430 return LowerUDIV(Op, DAG, Subtarget); 9431 case ISD::ADDCARRY: 9432 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 9433 case ISD::SADDO: 9434 case ISD::SSUBO: 9435 return LowerSignedALUO(Op, DAG); 9436 case ISD::UADDO: 9437 case ISD::USUBO: 9438 return LowerUnsignedALUO(Op, DAG); 9439 case ISD::SADDSAT: 9440 case ISD::SSUBSAT: 9441 return LowerSADDSUBSAT(Op, DAG, Subtarget); 9442 case ISD::LOAD: 9443 return LowerPredicateLoad(Op, DAG); 9444 case ISD::STORE: 9445 return LowerSTORE(Op, DAG, Subtarget); 9446 case ISD::MLOAD: 9447 return LowerMLOAD(Op, DAG); 9448 case ISD::ATOMIC_LOAD: 9449 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 9450 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 9451 case ISD::SDIVREM: 9452 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 9453 case ISD::DYNAMIC_STACKALLOC: 9454 if (Subtarget->isTargetWindows()) 9455 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9456 llvm_unreachable("Don't know how to custom lower this!"); 9457 case ISD::STRICT_FP_ROUND: 9458 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 9459 case ISD::STRICT_FP_EXTEND: 9460 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9461 case ISD::STRICT_FSETCC: 9462 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG); 9463 case ARMISD::WIN__DBZCHK: return SDValue(); 9464 } 9465 } 9466 9467 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 9468 SelectionDAG &DAG) { 9469 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9470 unsigned Opc = 0; 9471 if (IntNo == Intrinsic::arm_smlald) 9472 Opc = ARMISD::SMLALD; 9473 else if (IntNo == Intrinsic::arm_smlaldx) 9474 Opc = ARMISD::SMLALDX; 9475 else if (IntNo == Intrinsic::arm_smlsld) 9476 Opc = ARMISD::SMLSLD; 9477 else if (IntNo == Intrinsic::arm_smlsldx) 9478 Opc = ARMISD::SMLSLDX; 9479 else 9480 return; 9481 9482 SDLoc dl(N); 9483 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9484 N->getOperand(3), 9485 DAG.getConstant(0, dl, MVT::i32)); 9486 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9487 N->getOperand(3), 9488 DAG.getConstant(1, dl, MVT::i32)); 9489 9490 SDValue LongMul = DAG.getNode(Opc, dl, 9491 DAG.getVTList(MVT::i32, MVT::i32), 9492 N->getOperand(1), N->getOperand(2), 9493 Lo, Hi); 9494 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, 9495 LongMul.getValue(0), LongMul.getValue(1))); 9496 } 9497 9498 /// ReplaceNodeResults - Replace the results of node with an illegal result 9499 /// type with new values built out of custom code. 9500 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 9501 SmallVectorImpl<SDValue> &Results, 9502 SelectionDAG &DAG) const { 9503 SDValue Res; 9504 switch (N->getOpcode()) { 9505 default: 9506 llvm_unreachable("Don't know how to custom expand this!"); 9507 case ISD::READ_REGISTER: 9508 ExpandREAD_REGISTER(N, Results, DAG); 9509 break; 9510 case ISD::BITCAST: 9511 Res = ExpandBITCAST(N, DAG, Subtarget); 9512 break; 9513 case ISD::SRL: 9514 case ISD::SRA: 9515 case ISD::SHL: 9516 Res = Expand64BitShift(N, DAG, Subtarget); 9517 break; 9518 case ISD::SREM: 9519 case ISD::UREM: 9520 Res = LowerREM(N, DAG); 9521 break; 9522 case ISD::SDIVREM: 9523 case ISD::UDIVREM: 9524 Res = LowerDivRem(SDValue(N, 0), DAG); 9525 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 9526 Results.push_back(Res.getValue(0)); 9527 Results.push_back(Res.getValue(1)); 9528 return; 9529 case ISD::SADDSAT: 9530 case ISD::SSUBSAT: 9531 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget); 9532 break; 9533 case ISD::READCYCLECOUNTER: 9534 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 9535 return; 9536 case ISD::UDIV: 9537 case ISD::SDIV: 9538 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 9539 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 9540 Results); 9541 case ISD::ATOMIC_CMP_SWAP: 9542 ReplaceCMP_SWAP_64Results(N, Results, DAG); 9543 return; 9544 case ISD::INTRINSIC_WO_CHAIN: 9545 return ReplaceLongIntrinsic(N, Results, DAG); 9546 case ISD::ABS: 9547 lowerABS(N, Results, DAG); 9548 return ; 9549 case ISD::LOAD: 9550 LowerLOAD(N, Results, DAG); 9551 break; 9552 } 9553 if (Res.getNode()) 9554 Results.push_back(Res); 9555 } 9556 9557 //===----------------------------------------------------------------------===// 9558 // ARM Scheduler Hooks 9559 //===----------------------------------------------------------------------===// 9560 9561 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 9562 /// registers the function context. 9563 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 9564 MachineBasicBlock *MBB, 9565 MachineBasicBlock *DispatchBB, 9566 int FI) const { 9567 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 9568 "ROPI/RWPI not currently supported with SjLj"); 9569 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9570 DebugLoc dl = MI.getDebugLoc(); 9571 MachineFunction *MF = MBB->getParent(); 9572 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9573 MachineConstantPool *MCP = MF->getConstantPool(); 9574 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 9575 const Function &F = MF->getFunction(); 9576 9577 bool isThumb = Subtarget->isThumb(); 9578 bool isThumb2 = Subtarget->isThumb2(); 9579 9580 unsigned PCLabelId = AFI->createPICLabelUId(); 9581 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 9582 ARMConstantPoolValue *CPV = 9583 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 9584 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 9585 9586 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 9587 : &ARM::GPRRegClass; 9588 9589 // Grab constant pool and fixed stack memory operands. 9590 MachineMemOperand *CPMMO = 9591 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9592 MachineMemOperand::MOLoad, 4, Align(4)); 9593 9594 MachineMemOperand *FIMMOSt = 9595 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 9596 MachineMemOperand::MOStore, 4, Align(4)); 9597 9598 // Load the address of the dispatch MBB into the jump buffer. 9599 if (isThumb2) { 9600 // Incoming value: jbuf 9601 // ldr.n r5, LCPI1_1 9602 // orr r5, r5, #1 9603 // add r5, pc 9604 // str r5, [$jbuf, #+4] ; &jbuf[1] 9605 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9606 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9607 .addConstantPoolIndex(CPI) 9608 .addMemOperand(CPMMO) 9609 .add(predOps(ARMCC::AL)); 9610 // Set the low bit because of thumb mode. 9611 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9612 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9613 .addReg(NewVReg1, RegState::Kill) 9614 .addImm(0x01) 9615 .add(predOps(ARMCC::AL)) 9616 .add(condCodeOp()); 9617 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9618 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9619 .addReg(NewVReg2, RegState::Kill) 9620 .addImm(PCLabelId); 9621 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9622 .addReg(NewVReg3, RegState::Kill) 9623 .addFrameIndex(FI) 9624 .addImm(36) // &jbuf[1] :: pc 9625 .addMemOperand(FIMMOSt) 9626 .add(predOps(ARMCC::AL)); 9627 } else if (isThumb) { 9628 // Incoming value: jbuf 9629 // ldr.n r1, LCPI1_4 9630 // add r1, pc 9631 // mov r2, #1 9632 // orrs r1, r2 9633 // add r2, $jbuf, #+4 ; &jbuf[1] 9634 // str r1, [r2] 9635 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9636 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 9637 .addConstantPoolIndex(CPI) 9638 .addMemOperand(CPMMO) 9639 .add(predOps(ARMCC::AL)); 9640 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9641 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 9642 .addReg(NewVReg1, RegState::Kill) 9643 .addImm(PCLabelId); 9644 // Set the low bit because of thumb mode. 9645 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9646 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 9647 .addReg(ARM::CPSR, RegState::Define) 9648 .addImm(1) 9649 .add(predOps(ARMCC::AL)); 9650 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9651 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 9652 .addReg(ARM::CPSR, RegState::Define) 9653 .addReg(NewVReg2, RegState::Kill) 9654 .addReg(NewVReg3, RegState::Kill) 9655 .add(predOps(ARMCC::AL)); 9656 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9657 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 9658 .addFrameIndex(FI) 9659 .addImm(36); // &jbuf[1] :: pc 9660 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 9661 .addReg(NewVReg4, RegState::Kill) 9662 .addReg(NewVReg5, RegState::Kill) 9663 .addImm(0) 9664 .addMemOperand(FIMMOSt) 9665 .add(predOps(ARMCC::AL)); 9666 } else { 9667 // Incoming value: jbuf 9668 // ldr r1, LCPI1_1 9669 // add r1, pc, r1 9670 // str r1, [$jbuf, #+4] ; &jbuf[1] 9671 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9672 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 9673 .addConstantPoolIndex(CPI) 9674 .addImm(0) 9675 .addMemOperand(CPMMO) 9676 .add(predOps(ARMCC::AL)); 9677 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9678 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 9679 .addReg(NewVReg1, RegState::Kill) 9680 .addImm(PCLabelId) 9681 .add(predOps(ARMCC::AL)); 9682 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 9683 .addReg(NewVReg2, RegState::Kill) 9684 .addFrameIndex(FI) 9685 .addImm(36) // &jbuf[1] :: pc 9686 .addMemOperand(FIMMOSt) 9687 .add(predOps(ARMCC::AL)); 9688 } 9689 } 9690 9691 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 9692 MachineBasicBlock *MBB) const { 9693 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9694 DebugLoc dl = MI.getDebugLoc(); 9695 MachineFunction *MF = MBB->getParent(); 9696 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9697 MachineFrameInfo &MFI = MF->getFrameInfo(); 9698 int FI = MFI.getFunctionContextIndex(); 9699 9700 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 9701 : &ARM::GPRnopcRegClass; 9702 9703 // Get a mapping of the call site numbers to all of the landing pads they're 9704 // associated with. 9705 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 9706 unsigned MaxCSNum = 0; 9707 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 9708 ++BB) { 9709 if (!BB->isEHPad()) continue; 9710 9711 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 9712 // pad. 9713 for (MachineBasicBlock::iterator 9714 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 9715 if (!II->isEHLabel()) continue; 9716 9717 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 9718 if (!MF->hasCallSiteLandingPad(Sym)) continue; 9719 9720 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 9721 for (SmallVectorImpl<unsigned>::iterator 9722 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 9723 CSI != CSE; ++CSI) { 9724 CallSiteNumToLPad[*CSI].push_back(&*BB); 9725 MaxCSNum = std::max(MaxCSNum, *CSI); 9726 } 9727 break; 9728 } 9729 } 9730 9731 // Get an ordered list of the machine basic blocks for the jump table. 9732 std::vector<MachineBasicBlock*> LPadList; 9733 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 9734 LPadList.reserve(CallSiteNumToLPad.size()); 9735 for (unsigned I = 1; I <= MaxCSNum; ++I) { 9736 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 9737 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9738 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 9739 LPadList.push_back(*II); 9740 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 9741 } 9742 } 9743 9744 assert(!LPadList.empty() && 9745 "No landing pad destinations for the dispatch jump table!"); 9746 9747 // Create the jump table and associated information. 9748 MachineJumpTableInfo *JTI = 9749 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 9750 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 9751 9752 // Create the MBBs for the dispatch code. 9753 9754 // Shove the dispatch's address into the return slot in the function context. 9755 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 9756 DispatchBB->setIsEHPad(); 9757 9758 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9759 unsigned trap_opcode; 9760 if (Subtarget->isThumb()) 9761 trap_opcode = ARM::tTRAP; 9762 else 9763 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 9764 9765 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 9766 DispatchBB->addSuccessor(TrapBB); 9767 9768 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 9769 DispatchBB->addSuccessor(DispContBB); 9770 9771 // Insert and MBBs. 9772 MF->insert(MF->end(), DispatchBB); 9773 MF->insert(MF->end(), DispContBB); 9774 MF->insert(MF->end(), TrapBB); 9775 9776 // Insert code into the entry block that creates and registers the function 9777 // context. 9778 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 9779 9780 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 9781 MachinePointerInfo::getFixedStack(*MF, FI), 9782 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4)); 9783 9784 MachineInstrBuilder MIB; 9785 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 9786 9787 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 9788 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 9789 9790 // Add a register mask with no preserved registers. This results in all 9791 // registers being marked as clobbered. This can't work if the dispatch block 9792 // is in a Thumb1 function and is linked with ARM code which uses the FP 9793 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 9794 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 9795 9796 bool IsPositionIndependent = isPositionIndependent(); 9797 unsigned NumLPads = LPadList.size(); 9798 if (Subtarget->isThumb2()) { 9799 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9800 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 9801 .addFrameIndex(FI) 9802 .addImm(4) 9803 .addMemOperand(FIMMOLd) 9804 .add(predOps(ARMCC::AL)); 9805 9806 if (NumLPads < 256) { 9807 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 9808 .addReg(NewVReg1) 9809 .addImm(LPadList.size()) 9810 .add(predOps(ARMCC::AL)); 9811 } else { 9812 Register VReg1 = MRI->createVirtualRegister(TRC); 9813 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 9814 .addImm(NumLPads & 0xFFFF) 9815 .add(predOps(ARMCC::AL)); 9816 9817 unsigned VReg2 = VReg1; 9818 if ((NumLPads & 0xFFFF0000) != 0) { 9819 VReg2 = MRI->createVirtualRegister(TRC); 9820 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 9821 .addReg(VReg1) 9822 .addImm(NumLPads >> 16) 9823 .add(predOps(ARMCC::AL)); 9824 } 9825 9826 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 9827 .addReg(NewVReg1) 9828 .addReg(VReg2) 9829 .add(predOps(ARMCC::AL)); 9830 } 9831 9832 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 9833 .addMBB(TrapBB) 9834 .addImm(ARMCC::HI) 9835 .addReg(ARM::CPSR); 9836 9837 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9838 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 9839 .addJumpTableIndex(MJTI) 9840 .add(predOps(ARMCC::AL)); 9841 9842 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9843 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 9844 .addReg(NewVReg3, RegState::Kill) 9845 .addReg(NewVReg1) 9846 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9847 .add(predOps(ARMCC::AL)) 9848 .add(condCodeOp()); 9849 9850 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 9851 .addReg(NewVReg4, RegState::Kill) 9852 .addReg(NewVReg1) 9853 .addJumpTableIndex(MJTI); 9854 } else if (Subtarget->isThumb()) { 9855 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9856 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 9857 .addFrameIndex(FI) 9858 .addImm(1) 9859 .addMemOperand(FIMMOLd) 9860 .add(predOps(ARMCC::AL)); 9861 9862 if (NumLPads < 256) { 9863 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 9864 .addReg(NewVReg1) 9865 .addImm(NumLPads) 9866 .add(predOps(ARMCC::AL)); 9867 } else { 9868 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9869 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9870 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9871 9872 // MachineConstantPool wants an explicit alignment. 9873 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9874 if (Align == 0) 9875 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9876 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9877 9878 Register VReg1 = MRI->createVirtualRegister(TRC); 9879 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 9880 .addReg(VReg1, RegState::Define) 9881 .addConstantPoolIndex(Idx) 9882 .add(predOps(ARMCC::AL)); 9883 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 9884 .addReg(NewVReg1) 9885 .addReg(VReg1) 9886 .add(predOps(ARMCC::AL)); 9887 } 9888 9889 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 9890 .addMBB(TrapBB) 9891 .addImm(ARMCC::HI) 9892 .addReg(ARM::CPSR); 9893 9894 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9895 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 9896 .addReg(ARM::CPSR, RegState::Define) 9897 .addReg(NewVReg1) 9898 .addImm(2) 9899 .add(predOps(ARMCC::AL)); 9900 9901 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9902 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 9903 .addJumpTableIndex(MJTI) 9904 .add(predOps(ARMCC::AL)); 9905 9906 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9907 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 9908 .addReg(ARM::CPSR, RegState::Define) 9909 .addReg(NewVReg2, RegState::Kill) 9910 .addReg(NewVReg3) 9911 .add(predOps(ARMCC::AL)); 9912 9913 MachineMemOperand *JTMMOLd = 9914 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 9915 MachineMemOperand::MOLoad, 4, Align(4)); 9916 9917 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9918 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 9919 .addReg(NewVReg4, RegState::Kill) 9920 .addImm(0) 9921 .addMemOperand(JTMMOLd) 9922 .add(predOps(ARMCC::AL)); 9923 9924 unsigned NewVReg6 = NewVReg5; 9925 if (IsPositionIndependent) { 9926 NewVReg6 = MRI->createVirtualRegister(TRC); 9927 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 9928 .addReg(ARM::CPSR, RegState::Define) 9929 .addReg(NewVReg5, RegState::Kill) 9930 .addReg(NewVReg3) 9931 .add(predOps(ARMCC::AL)); 9932 } 9933 9934 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 9935 .addReg(NewVReg6, RegState::Kill) 9936 .addJumpTableIndex(MJTI); 9937 } else { 9938 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9939 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 9940 .addFrameIndex(FI) 9941 .addImm(4) 9942 .addMemOperand(FIMMOLd) 9943 .add(predOps(ARMCC::AL)); 9944 9945 if (NumLPads < 256) { 9946 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 9947 .addReg(NewVReg1) 9948 .addImm(NumLPads) 9949 .add(predOps(ARMCC::AL)); 9950 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 9951 Register VReg1 = MRI->createVirtualRegister(TRC); 9952 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 9953 .addImm(NumLPads & 0xFFFF) 9954 .add(predOps(ARMCC::AL)); 9955 9956 unsigned VReg2 = VReg1; 9957 if ((NumLPads & 0xFFFF0000) != 0) { 9958 VReg2 = MRI->createVirtualRegister(TRC); 9959 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 9960 .addReg(VReg1) 9961 .addImm(NumLPads >> 16) 9962 .add(predOps(ARMCC::AL)); 9963 } 9964 9965 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9966 .addReg(NewVReg1) 9967 .addReg(VReg2) 9968 .add(predOps(ARMCC::AL)); 9969 } else { 9970 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9971 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9972 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9973 9974 // MachineConstantPool wants an explicit alignment. 9975 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9976 if (Align == 0) 9977 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9978 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9979 9980 Register VReg1 = MRI->createVirtualRegister(TRC); 9981 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 9982 .addReg(VReg1, RegState::Define) 9983 .addConstantPoolIndex(Idx) 9984 .addImm(0) 9985 .add(predOps(ARMCC::AL)); 9986 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9987 .addReg(NewVReg1) 9988 .addReg(VReg1, RegState::Kill) 9989 .add(predOps(ARMCC::AL)); 9990 } 9991 9992 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 9993 .addMBB(TrapBB) 9994 .addImm(ARMCC::HI) 9995 .addReg(ARM::CPSR); 9996 9997 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9998 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 9999 .addReg(NewVReg1) 10000 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10001 .add(predOps(ARMCC::AL)) 10002 .add(condCodeOp()); 10003 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10004 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 10005 .addJumpTableIndex(MJTI) 10006 .add(predOps(ARMCC::AL)); 10007 10008 MachineMemOperand *JTMMOLd = 10009 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10010 MachineMemOperand::MOLoad, 4, Align(4)); 10011 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10012 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 10013 .addReg(NewVReg3, RegState::Kill) 10014 .addReg(NewVReg4) 10015 .addImm(0) 10016 .addMemOperand(JTMMOLd) 10017 .add(predOps(ARMCC::AL)); 10018 10019 if (IsPositionIndependent) { 10020 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 10021 .addReg(NewVReg5, RegState::Kill) 10022 .addReg(NewVReg4) 10023 .addJumpTableIndex(MJTI); 10024 } else { 10025 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 10026 .addReg(NewVReg5, RegState::Kill) 10027 .addJumpTableIndex(MJTI); 10028 } 10029 } 10030 10031 // Add the jump table entries as successors to the MBB. 10032 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 10033 for (std::vector<MachineBasicBlock*>::iterator 10034 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 10035 MachineBasicBlock *CurMBB = *I; 10036 if (SeenMBBs.insert(CurMBB).second) 10037 DispContBB->addSuccessor(CurMBB); 10038 } 10039 10040 // N.B. the order the invoke BBs are processed in doesn't matter here. 10041 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 10042 SmallVector<MachineBasicBlock*, 64> MBBLPads; 10043 for (MachineBasicBlock *BB : InvokeBBs) { 10044 10045 // Remove the landing pad successor from the invoke block and replace it 10046 // with the new dispatch block. 10047 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 10048 BB->succ_end()); 10049 while (!Successors.empty()) { 10050 MachineBasicBlock *SMBB = Successors.pop_back_val(); 10051 if (SMBB->isEHPad()) { 10052 BB->removeSuccessor(SMBB); 10053 MBBLPads.push_back(SMBB); 10054 } 10055 } 10056 10057 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 10058 BB->normalizeSuccProbs(); 10059 10060 // Find the invoke call and mark all of the callee-saved registers as 10061 // 'implicit defined' so that they're spilled. This prevents code from 10062 // moving instructions to before the EH block, where they will never be 10063 // executed. 10064 for (MachineBasicBlock::reverse_iterator 10065 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 10066 if (!II->isCall()) continue; 10067 10068 DenseMap<unsigned, bool> DefRegs; 10069 for (MachineInstr::mop_iterator 10070 OI = II->operands_begin(), OE = II->operands_end(); 10071 OI != OE; ++OI) { 10072 if (!OI->isReg()) continue; 10073 DefRegs[OI->getReg()] = true; 10074 } 10075 10076 MachineInstrBuilder MIB(*MF, &*II); 10077 10078 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 10079 unsigned Reg = SavedRegs[i]; 10080 if (Subtarget->isThumb2() && 10081 !ARM::tGPRRegClass.contains(Reg) && 10082 !ARM::hGPRRegClass.contains(Reg)) 10083 continue; 10084 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 10085 continue; 10086 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 10087 continue; 10088 if (!DefRegs[Reg]) 10089 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 10090 } 10091 10092 break; 10093 } 10094 } 10095 10096 // Mark all former landing pads as non-landing pads. The dispatch is the only 10097 // landing pad now. 10098 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10099 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 10100 (*I)->setIsEHPad(false); 10101 10102 // The instruction is gone now. 10103 MI.eraseFromParent(); 10104 } 10105 10106 static 10107 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 10108 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 10109 E = MBB->succ_end(); I != E; ++I) 10110 if (*I != Succ) 10111 return *I; 10112 llvm_unreachable("Expecting a BB with two successors!"); 10113 } 10114 10115 /// Return the load opcode for a given load size. If load size >= 8, 10116 /// neon opcode will be returned. 10117 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 10118 if (LdSize >= 8) 10119 return LdSize == 16 ? ARM::VLD1q32wb_fixed 10120 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 10121 if (IsThumb1) 10122 return LdSize == 4 ? ARM::tLDRi 10123 : LdSize == 2 ? ARM::tLDRHi 10124 : LdSize == 1 ? ARM::tLDRBi : 0; 10125 if (IsThumb2) 10126 return LdSize == 4 ? ARM::t2LDR_POST 10127 : LdSize == 2 ? ARM::t2LDRH_POST 10128 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 10129 return LdSize == 4 ? ARM::LDR_POST_IMM 10130 : LdSize == 2 ? ARM::LDRH_POST 10131 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 10132 } 10133 10134 /// Return the store opcode for a given store size. If store size >= 8, 10135 /// neon opcode will be returned. 10136 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 10137 if (StSize >= 8) 10138 return StSize == 16 ? ARM::VST1q32wb_fixed 10139 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 10140 if (IsThumb1) 10141 return StSize == 4 ? ARM::tSTRi 10142 : StSize == 2 ? ARM::tSTRHi 10143 : StSize == 1 ? ARM::tSTRBi : 0; 10144 if (IsThumb2) 10145 return StSize == 4 ? ARM::t2STR_POST 10146 : StSize == 2 ? ARM::t2STRH_POST 10147 : StSize == 1 ? ARM::t2STRB_POST : 0; 10148 return StSize == 4 ? ARM::STR_POST_IMM 10149 : StSize == 2 ? ARM::STRH_POST 10150 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 10151 } 10152 10153 /// Emit a post-increment load operation with given size. The instructions 10154 /// will be added to BB at Pos. 10155 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10156 const TargetInstrInfo *TII, const DebugLoc &dl, 10157 unsigned LdSize, unsigned Data, unsigned AddrIn, 10158 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10159 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 10160 assert(LdOpc != 0 && "Should have a load opcode"); 10161 if (LdSize >= 8) { 10162 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10163 .addReg(AddrOut, RegState::Define) 10164 .addReg(AddrIn) 10165 .addImm(0) 10166 .add(predOps(ARMCC::AL)); 10167 } else if (IsThumb1) { 10168 // load + update AddrIn 10169 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10170 .addReg(AddrIn) 10171 .addImm(0) 10172 .add(predOps(ARMCC::AL)); 10173 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10174 .add(t1CondCodeOp()) 10175 .addReg(AddrIn) 10176 .addImm(LdSize) 10177 .add(predOps(ARMCC::AL)); 10178 } else if (IsThumb2) { 10179 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10180 .addReg(AddrOut, RegState::Define) 10181 .addReg(AddrIn) 10182 .addImm(LdSize) 10183 .add(predOps(ARMCC::AL)); 10184 } else { // arm 10185 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10186 .addReg(AddrOut, RegState::Define) 10187 .addReg(AddrIn) 10188 .addReg(0) 10189 .addImm(LdSize) 10190 .add(predOps(ARMCC::AL)); 10191 } 10192 } 10193 10194 /// Emit a post-increment store operation with given size. The instructions 10195 /// will be added to BB at Pos. 10196 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10197 const TargetInstrInfo *TII, const DebugLoc &dl, 10198 unsigned StSize, unsigned Data, unsigned AddrIn, 10199 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10200 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 10201 assert(StOpc != 0 && "Should have a store opcode"); 10202 if (StSize >= 8) { 10203 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10204 .addReg(AddrIn) 10205 .addImm(0) 10206 .addReg(Data) 10207 .add(predOps(ARMCC::AL)); 10208 } else if (IsThumb1) { 10209 // store + update AddrIn 10210 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 10211 .addReg(Data) 10212 .addReg(AddrIn) 10213 .addImm(0) 10214 .add(predOps(ARMCC::AL)); 10215 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10216 .add(t1CondCodeOp()) 10217 .addReg(AddrIn) 10218 .addImm(StSize) 10219 .add(predOps(ARMCC::AL)); 10220 } else if (IsThumb2) { 10221 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10222 .addReg(Data) 10223 .addReg(AddrIn) 10224 .addImm(StSize) 10225 .add(predOps(ARMCC::AL)); 10226 } else { // arm 10227 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10228 .addReg(Data) 10229 .addReg(AddrIn) 10230 .addReg(0) 10231 .addImm(StSize) 10232 .add(predOps(ARMCC::AL)); 10233 } 10234 } 10235 10236 MachineBasicBlock * 10237 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 10238 MachineBasicBlock *BB) const { 10239 // This pseudo instruction has 3 operands: dst, src, size 10240 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 10241 // Otherwise, we will generate unrolled scalar copies. 10242 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10243 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10244 MachineFunction::iterator It = ++BB->getIterator(); 10245 10246 Register dest = MI.getOperand(0).getReg(); 10247 Register src = MI.getOperand(1).getReg(); 10248 unsigned SizeVal = MI.getOperand(2).getImm(); 10249 unsigned Alignment = MI.getOperand(3).getImm(); 10250 DebugLoc dl = MI.getDebugLoc(); 10251 10252 MachineFunction *MF = BB->getParent(); 10253 MachineRegisterInfo &MRI = MF->getRegInfo(); 10254 unsigned UnitSize = 0; 10255 const TargetRegisterClass *TRC = nullptr; 10256 const TargetRegisterClass *VecTRC = nullptr; 10257 10258 bool IsThumb1 = Subtarget->isThumb1Only(); 10259 bool IsThumb2 = Subtarget->isThumb2(); 10260 bool IsThumb = Subtarget->isThumb(); 10261 10262 if (Alignment & 1) { 10263 UnitSize = 1; 10264 } else if (Alignment & 2) { 10265 UnitSize = 2; 10266 } else { 10267 // Check whether we can use NEON instructions. 10268 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 10269 Subtarget->hasNEON()) { 10270 if ((Alignment % 16 == 0) && SizeVal >= 16) 10271 UnitSize = 16; 10272 else if ((Alignment % 8 == 0) && SizeVal >= 8) 10273 UnitSize = 8; 10274 } 10275 // Can't use NEON instructions. 10276 if (UnitSize == 0) 10277 UnitSize = 4; 10278 } 10279 10280 // Select the correct opcode and register class for unit size load/store 10281 bool IsNeon = UnitSize >= 8; 10282 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 10283 if (IsNeon) 10284 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 10285 : UnitSize == 8 ? &ARM::DPRRegClass 10286 : nullptr; 10287 10288 unsigned BytesLeft = SizeVal % UnitSize; 10289 unsigned LoopSize = SizeVal - BytesLeft; 10290 10291 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 10292 // Use LDR and STR to copy. 10293 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 10294 // [destOut] = STR_POST(scratch, destIn, UnitSize) 10295 unsigned srcIn = src; 10296 unsigned destIn = dest; 10297 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 10298 Register srcOut = MRI.createVirtualRegister(TRC); 10299 Register destOut = MRI.createVirtualRegister(TRC); 10300 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10301 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 10302 IsThumb1, IsThumb2); 10303 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 10304 IsThumb1, IsThumb2); 10305 srcIn = srcOut; 10306 destIn = destOut; 10307 } 10308 10309 // Handle the leftover bytes with LDRB and STRB. 10310 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 10311 // [destOut] = STRB_POST(scratch, destIn, 1) 10312 for (unsigned i = 0; i < BytesLeft; i++) { 10313 Register srcOut = MRI.createVirtualRegister(TRC); 10314 Register destOut = MRI.createVirtualRegister(TRC); 10315 Register scratch = MRI.createVirtualRegister(TRC); 10316 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 10317 IsThumb1, IsThumb2); 10318 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 10319 IsThumb1, IsThumb2); 10320 srcIn = srcOut; 10321 destIn = destOut; 10322 } 10323 MI.eraseFromParent(); // The instruction is gone now. 10324 return BB; 10325 } 10326 10327 // Expand the pseudo op to a loop. 10328 // thisMBB: 10329 // ... 10330 // movw varEnd, # --> with thumb2 10331 // movt varEnd, # 10332 // ldrcp varEnd, idx --> without thumb2 10333 // fallthrough --> loopMBB 10334 // loopMBB: 10335 // PHI varPhi, varEnd, varLoop 10336 // PHI srcPhi, src, srcLoop 10337 // PHI destPhi, dst, destLoop 10338 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10339 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 10340 // subs varLoop, varPhi, #UnitSize 10341 // bne loopMBB 10342 // fallthrough --> exitMBB 10343 // exitMBB: 10344 // epilogue to handle left-over bytes 10345 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10346 // [destOut] = STRB_POST(scratch, destLoop, 1) 10347 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10348 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10349 MF->insert(It, loopMBB); 10350 MF->insert(It, exitMBB); 10351 10352 // Transfer the remainder of BB and its successor edges to exitMBB. 10353 exitMBB->splice(exitMBB->begin(), BB, 10354 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10355 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10356 10357 // Load an immediate to varEnd. 10358 Register varEnd = MRI.createVirtualRegister(TRC); 10359 if (Subtarget->useMovt()) { 10360 unsigned Vtmp = varEnd; 10361 if ((LoopSize & 0xFFFF0000) != 0) 10362 Vtmp = MRI.createVirtualRegister(TRC); 10363 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 10364 .addImm(LoopSize & 0xFFFF) 10365 .add(predOps(ARMCC::AL)); 10366 10367 if ((LoopSize & 0xFFFF0000) != 0) 10368 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 10369 .addReg(Vtmp) 10370 .addImm(LoopSize >> 16) 10371 .add(predOps(ARMCC::AL)); 10372 } else { 10373 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10374 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10375 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 10376 10377 // MachineConstantPool wants an explicit alignment. 10378 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10379 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment.value()); 10380 MachineMemOperand *CPMMO = 10381 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 10382 MachineMemOperand::MOLoad, 4, Align(4)); 10383 10384 if (IsThumb) 10385 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 10386 .addReg(varEnd, RegState::Define) 10387 .addConstantPoolIndex(Idx) 10388 .add(predOps(ARMCC::AL)) 10389 .addMemOperand(CPMMO); 10390 else 10391 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 10392 .addReg(varEnd, RegState::Define) 10393 .addConstantPoolIndex(Idx) 10394 .addImm(0) 10395 .add(predOps(ARMCC::AL)) 10396 .addMemOperand(CPMMO); 10397 } 10398 BB->addSuccessor(loopMBB); 10399 10400 // Generate the loop body: 10401 // varPhi = PHI(varLoop, varEnd) 10402 // srcPhi = PHI(srcLoop, src) 10403 // destPhi = PHI(destLoop, dst) 10404 MachineBasicBlock *entryBB = BB; 10405 BB = loopMBB; 10406 Register varLoop = MRI.createVirtualRegister(TRC); 10407 Register varPhi = MRI.createVirtualRegister(TRC); 10408 Register srcLoop = MRI.createVirtualRegister(TRC); 10409 Register srcPhi = MRI.createVirtualRegister(TRC); 10410 Register destLoop = MRI.createVirtualRegister(TRC); 10411 Register destPhi = MRI.createVirtualRegister(TRC); 10412 10413 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 10414 .addReg(varLoop).addMBB(loopMBB) 10415 .addReg(varEnd).addMBB(entryBB); 10416 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 10417 .addReg(srcLoop).addMBB(loopMBB) 10418 .addReg(src).addMBB(entryBB); 10419 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 10420 .addReg(destLoop).addMBB(loopMBB) 10421 .addReg(dest).addMBB(entryBB); 10422 10423 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10424 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 10425 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10426 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 10427 IsThumb1, IsThumb2); 10428 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 10429 IsThumb1, IsThumb2); 10430 10431 // Decrement loop variable by UnitSize. 10432 if (IsThumb1) { 10433 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 10434 .add(t1CondCodeOp()) 10435 .addReg(varPhi) 10436 .addImm(UnitSize) 10437 .add(predOps(ARMCC::AL)); 10438 } else { 10439 MachineInstrBuilder MIB = 10440 BuildMI(*BB, BB->end(), dl, 10441 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 10442 MIB.addReg(varPhi) 10443 .addImm(UnitSize) 10444 .add(predOps(ARMCC::AL)) 10445 .add(condCodeOp()); 10446 MIB->getOperand(5).setReg(ARM::CPSR); 10447 MIB->getOperand(5).setIsDef(true); 10448 } 10449 BuildMI(*BB, BB->end(), dl, 10450 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10451 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 10452 10453 // loopMBB can loop back to loopMBB or fall through to exitMBB. 10454 BB->addSuccessor(loopMBB); 10455 BB->addSuccessor(exitMBB); 10456 10457 // Add epilogue to handle BytesLeft. 10458 BB = exitMBB; 10459 auto StartOfExit = exitMBB->begin(); 10460 10461 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10462 // [destOut] = STRB_POST(scratch, destLoop, 1) 10463 unsigned srcIn = srcLoop; 10464 unsigned destIn = destLoop; 10465 for (unsigned i = 0; i < BytesLeft; i++) { 10466 Register srcOut = MRI.createVirtualRegister(TRC); 10467 Register destOut = MRI.createVirtualRegister(TRC); 10468 Register scratch = MRI.createVirtualRegister(TRC); 10469 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 10470 IsThumb1, IsThumb2); 10471 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 10472 IsThumb1, IsThumb2); 10473 srcIn = srcOut; 10474 destIn = destOut; 10475 } 10476 10477 MI.eraseFromParent(); // The instruction is gone now. 10478 return BB; 10479 } 10480 10481 MachineBasicBlock * 10482 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 10483 MachineBasicBlock *MBB) const { 10484 const TargetMachine &TM = getTargetMachine(); 10485 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 10486 DebugLoc DL = MI.getDebugLoc(); 10487 10488 assert(Subtarget->isTargetWindows() && 10489 "__chkstk is only supported on Windows"); 10490 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 10491 10492 // __chkstk takes the number of words to allocate on the stack in R4, and 10493 // returns the stack adjustment in number of bytes in R4. This will not 10494 // clober any other registers (other than the obvious lr). 10495 // 10496 // Although, technically, IP should be considered a register which may be 10497 // clobbered, the call itself will not touch it. Windows on ARM is a pure 10498 // thumb-2 environment, so there is no interworking required. As a result, we 10499 // do not expect a veneer to be emitted by the linker, clobbering IP. 10500 // 10501 // Each module receives its own copy of __chkstk, so no import thunk is 10502 // required, again, ensuring that IP is not clobbered. 10503 // 10504 // Finally, although some linkers may theoretically provide a trampoline for 10505 // out of range calls (which is quite common due to a 32M range limitation of 10506 // branches for Thumb), we can generate the long-call version via 10507 // -mcmodel=large, alleviating the need for the trampoline which may clobber 10508 // IP. 10509 10510 switch (TM.getCodeModel()) { 10511 case CodeModel::Tiny: 10512 llvm_unreachable("Tiny code model not available on ARM."); 10513 case CodeModel::Small: 10514 case CodeModel::Medium: 10515 case CodeModel::Kernel: 10516 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 10517 .add(predOps(ARMCC::AL)) 10518 .addExternalSymbol("__chkstk") 10519 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10520 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10521 .addReg(ARM::R12, 10522 RegState::Implicit | RegState::Define | RegState::Dead) 10523 .addReg(ARM::CPSR, 10524 RegState::Implicit | RegState::Define | RegState::Dead); 10525 break; 10526 case CodeModel::Large: { 10527 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10528 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 10529 10530 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 10531 .addExternalSymbol("__chkstk"); 10532 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 10533 .add(predOps(ARMCC::AL)) 10534 .addReg(Reg, RegState::Kill) 10535 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10536 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10537 .addReg(ARM::R12, 10538 RegState::Implicit | RegState::Define | RegState::Dead) 10539 .addReg(ARM::CPSR, 10540 RegState::Implicit | RegState::Define | RegState::Dead); 10541 break; 10542 } 10543 } 10544 10545 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 10546 .addReg(ARM::SP, RegState::Kill) 10547 .addReg(ARM::R4, RegState::Kill) 10548 .setMIFlags(MachineInstr::FrameSetup) 10549 .add(predOps(ARMCC::AL)) 10550 .add(condCodeOp()); 10551 10552 MI.eraseFromParent(); 10553 return MBB; 10554 } 10555 10556 MachineBasicBlock * 10557 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 10558 MachineBasicBlock *MBB) const { 10559 DebugLoc DL = MI.getDebugLoc(); 10560 MachineFunction *MF = MBB->getParent(); 10561 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10562 10563 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 10564 MF->insert(++MBB->getIterator(), ContBB); 10565 ContBB->splice(ContBB->begin(), MBB, 10566 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10567 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 10568 MBB->addSuccessor(ContBB); 10569 10570 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10571 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 10572 MF->push_back(TrapBB); 10573 MBB->addSuccessor(TrapBB); 10574 10575 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 10576 .addReg(MI.getOperand(0).getReg()) 10577 .addImm(0) 10578 .add(predOps(ARMCC::AL)); 10579 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 10580 .addMBB(TrapBB) 10581 .addImm(ARMCC::EQ) 10582 .addReg(ARM::CPSR); 10583 10584 MI.eraseFromParent(); 10585 return ContBB; 10586 } 10587 10588 // The CPSR operand of SelectItr might be missing a kill marker 10589 // because there were multiple uses of CPSR, and ISel didn't know 10590 // which to mark. Figure out whether SelectItr should have had a 10591 // kill marker, and set it if it should. Returns the correct kill 10592 // marker value. 10593 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 10594 MachineBasicBlock* BB, 10595 const TargetRegisterInfo* TRI) { 10596 // Scan forward through BB for a use/def of CPSR. 10597 MachineBasicBlock::iterator miI(std::next(SelectItr)); 10598 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 10599 const MachineInstr& mi = *miI; 10600 if (mi.readsRegister(ARM::CPSR)) 10601 return false; 10602 if (mi.definesRegister(ARM::CPSR)) 10603 break; // Should have kill-flag - update below. 10604 } 10605 10606 // If we hit the end of the block, check whether CPSR is live into a 10607 // successor. 10608 if (miI == BB->end()) { 10609 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10610 sEnd = BB->succ_end(); 10611 sItr != sEnd; ++sItr) { 10612 MachineBasicBlock* succ = *sItr; 10613 if (succ->isLiveIn(ARM::CPSR)) 10614 return false; 10615 } 10616 } 10617 10618 // We found a def, or hit the end of the basic block and CPSR wasn't live 10619 // out. SelectMI should have a kill flag on CPSR. 10620 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10621 return true; 10622 } 10623 10624 MachineBasicBlock * 10625 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10626 MachineBasicBlock *BB) const { 10627 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10628 DebugLoc dl = MI.getDebugLoc(); 10629 bool isThumb2 = Subtarget->isThumb2(); 10630 switch (MI.getOpcode()) { 10631 default: { 10632 MI.print(errs()); 10633 llvm_unreachable("Unexpected instr type to insert"); 10634 } 10635 10636 // Thumb1 post-indexed loads are really just single-register LDMs. 10637 case ARM::tLDR_postidx: { 10638 MachineOperand Def(MI.getOperand(1)); 10639 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 10640 .add(Def) // Rn_wb 10641 .add(MI.getOperand(2)) // Rn 10642 .add(MI.getOperand(3)) // PredImm 10643 .add(MI.getOperand(4)) // PredReg 10644 .add(MI.getOperand(0)) // Rt 10645 .cloneMemRefs(MI); 10646 MI.eraseFromParent(); 10647 return BB; 10648 } 10649 10650 // The Thumb2 pre-indexed stores have the same MI operands, they just 10651 // define them differently in the .td files from the isel patterns, so 10652 // they need pseudos. 10653 case ARM::t2STR_preidx: 10654 MI.setDesc(TII->get(ARM::t2STR_PRE)); 10655 return BB; 10656 case ARM::t2STRB_preidx: 10657 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 10658 return BB; 10659 case ARM::t2STRH_preidx: 10660 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 10661 return BB; 10662 10663 case ARM::STRi_preidx: 10664 case ARM::STRBi_preidx: { 10665 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 10666 : ARM::STRB_PRE_IMM; 10667 // Decode the offset. 10668 unsigned Offset = MI.getOperand(4).getImm(); 10669 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 10670 Offset = ARM_AM::getAM2Offset(Offset); 10671 if (isSub) 10672 Offset = -Offset; 10673 10674 MachineMemOperand *MMO = *MI.memoperands_begin(); 10675 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 10676 .add(MI.getOperand(0)) // Rn_wb 10677 .add(MI.getOperand(1)) // Rt 10678 .add(MI.getOperand(2)) // Rn 10679 .addImm(Offset) // offset (skip GPR==zero_reg) 10680 .add(MI.getOperand(5)) // pred 10681 .add(MI.getOperand(6)) 10682 .addMemOperand(MMO); 10683 MI.eraseFromParent(); 10684 return BB; 10685 } 10686 case ARM::STRr_preidx: 10687 case ARM::STRBr_preidx: 10688 case ARM::STRH_preidx: { 10689 unsigned NewOpc; 10690 switch (MI.getOpcode()) { 10691 default: llvm_unreachable("unexpected opcode!"); 10692 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 10693 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 10694 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 10695 } 10696 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 10697 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 10698 MIB.add(MI.getOperand(i)); 10699 MI.eraseFromParent(); 10700 return BB; 10701 } 10702 10703 case ARM::tMOVCCr_pseudo: { 10704 // To "insert" a SELECT_CC instruction, we actually have to insert the 10705 // diamond control-flow pattern. The incoming instruction knows the 10706 // destination vreg to set, the condition code register to branch on, the 10707 // true/false values to select between, and a branch opcode to use. 10708 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10709 MachineFunction::iterator It = ++BB->getIterator(); 10710 10711 // thisMBB: 10712 // ... 10713 // TrueVal = ... 10714 // cmpTY ccX, r1, r2 10715 // bCC copy1MBB 10716 // fallthrough --> copy0MBB 10717 MachineBasicBlock *thisMBB = BB; 10718 MachineFunction *F = BB->getParent(); 10719 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10720 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10721 F->insert(It, copy0MBB); 10722 F->insert(It, sinkMBB); 10723 10724 // Check whether CPSR is live past the tMOVCCr_pseudo. 10725 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10726 if (!MI.killsRegister(ARM::CPSR) && 10727 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 10728 copy0MBB->addLiveIn(ARM::CPSR); 10729 sinkMBB->addLiveIn(ARM::CPSR); 10730 } 10731 10732 // Transfer the remainder of BB and its successor edges to sinkMBB. 10733 sinkMBB->splice(sinkMBB->begin(), BB, 10734 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10735 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10736 10737 BB->addSuccessor(copy0MBB); 10738 BB->addSuccessor(sinkMBB); 10739 10740 BuildMI(BB, dl, TII->get(ARM::tBcc)) 10741 .addMBB(sinkMBB) 10742 .addImm(MI.getOperand(3).getImm()) 10743 .addReg(MI.getOperand(4).getReg()); 10744 10745 // copy0MBB: 10746 // %FalseValue = ... 10747 // # fallthrough to sinkMBB 10748 BB = copy0MBB; 10749 10750 // Update machine-CFG edges 10751 BB->addSuccessor(sinkMBB); 10752 10753 // sinkMBB: 10754 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10755 // ... 10756 BB = sinkMBB; 10757 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 10758 .addReg(MI.getOperand(1).getReg()) 10759 .addMBB(copy0MBB) 10760 .addReg(MI.getOperand(2).getReg()) 10761 .addMBB(thisMBB); 10762 10763 MI.eraseFromParent(); // The pseudo instruction is gone now. 10764 return BB; 10765 } 10766 10767 case ARM::BCCi64: 10768 case ARM::BCCZi64: { 10769 // If there is an unconditional branch to the other successor, remove it. 10770 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10771 10772 // Compare both parts that make up the double comparison separately for 10773 // equality. 10774 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 10775 10776 Register LHS1 = MI.getOperand(1).getReg(); 10777 Register LHS2 = MI.getOperand(2).getReg(); 10778 if (RHSisZero) { 10779 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10780 .addReg(LHS1) 10781 .addImm(0) 10782 .add(predOps(ARMCC::AL)); 10783 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10784 .addReg(LHS2).addImm(0) 10785 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10786 } else { 10787 Register RHS1 = MI.getOperand(3).getReg(); 10788 Register RHS2 = MI.getOperand(4).getReg(); 10789 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10790 .addReg(LHS1) 10791 .addReg(RHS1) 10792 .add(predOps(ARMCC::AL)); 10793 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10794 .addReg(LHS2).addReg(RHS2) 10795 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10796 } 10797 10798 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 10799 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 10800 if (MI.getOperand(0).getImm() == ARMCC::NE) 10801 std::swap(destMBB, exitMBB); 10802 10803 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10804 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 10805 if (isThumb2) 10806 BuildMI(BB, dl, TII->get(ARM::t2B)) 10807 .addMBB(exitMBB) 10808 .add(predOps(ARMCC::AL)); 10809 else 10810 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 10811 10812 MI.eraseFromParent(); // The pseudo instruction is gone now. 10813 return BB; 10814 } 10815 10816 case ARM::Int_eh_sjlj_setjmp: 10817 case ARM::Int_eh_sjlj_setjmp_nofp: 10818 case ARM::tInt_eh_sjlj_setjmp: 10819 case ARM::t2Int_eh_sjlj_setjmp: 10820 case ARM::t2Int_eh_sjlj_setjmp_nofp: 10821 return BB; 10822 10823 case ARM::Int_eh_sjlj_setup_dispatch: 10824 EmitSjLjDispatchBlock(MI, BB); 10825 return BB; 10826 10827 case ARM::ABS: 10828 case ARM::t2ABS: { 10829 // To insert an ABS instruction, we have to insert the 10830 // diamond control-flow pattern. The incoming instruction knows the 10831 // source vreg to test against 0, the destination vreg to set, 10832 // the condition code register to branch on, the 10833 // true/false values to select between, and a branch opcode to use. 10834 // It transforms 10835 // V1 = ABS V0 10836 // into 10837 // V2 = MOVS V0 10838 // BCC (branch to SinkBB if V0 >= 0) 10839 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 10840 // SinkBB: V1 = PHI(V2, V3) 10841 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10842 MachineFunction::iterator BBI = ++BB->getIterator(); 10843 MachineFunction *Fn = BB->getParent(); 10844 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10845 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10846 Fn->insert(BBI, RSBBB); 10847 Fn->insert(BBI, SinkBB); 10848 10849 Register ABSSrcReg = MI.getOperand(1).getReg(); 10850 Register ABSDstReg = MI.getOperand(0).getReg(); 10851 bool ABSSrcKIll = MI.getOperand(1).isKill(); 10852 bool isThumb2 = Subtarget->isThumb2(); 10853 MachineRegisterInfo &MRI = Fn->getRegInfo(); 10854 // In Thumb mode S must not be specified if source register is the SP or 10855 // PC and if destination register is the SP, so restrict register class 10856 Register NewRsbDstReg = MRI.createVirtualRegister( 10857 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 10858 10859 // Transfer the remainder of BB and its successor edges to sinkMBB. 10860 SinkBB->splice(SinkBB->begin(), BB, 10861 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10862 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 10863 10864 BB->addSuccessor(RSBBB); 10865 BB->addSuccessor(SinkBB); 10866 10867 // fall through to SinkMBB 10868 RSBBB->addSuccessor(SinkBB); 10869 10870 // insert a cmp at the end of BB 10871 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10872 .addReg(ABSSrcReg) 10873 .addImm(0) 10874 .add(predOps(ARMCC::AL)); 10875 10876 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 10877 BuildMI(BB, dl, 10878 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 10879 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 10880 10881 // insert rsbri in RSBBB 10882 // Note: BCC and rsbri will be converted into predicated rsbmi 10883 // by if-conversion pass 10884 BuildMI(*RSBBB, RSBBB->begin(), dl, 10885 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 10886 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 10887 .addImm(0) 10888 .add(predOps(ARMCC::AL)) 10889 .add(condCodeOp()); 10890 10891 // insert PHI in SinkBB, 10892 // reuse ABSDstReg to not change uses of ABS instruction 10893 BuildMI(*SinkBB, SinkBB->begin(), dl, 10894 TII->get(ARM::PHI), ABSDstReg) 10895 .addReg(NewRsbDstReg).addMBB(RSBBB) 10896 .addReg(ABSSrcReg).addMBB(BB); 10897 10898 // remove ABS instruction 10899 MI.eraseFromParent(); 10900 10901 // return last added BB 10902 return SinkBB; 10903 } 10904 case ARM::COPY_STRUCT_BYVAL_I32: 10905 ++NumLoopByVals; 10906 return EmitStructByval(MI, BB); 10907 case ARM::WIN__CHKSTK: 10908 return EmitLowered__chkstk(MI, BB); 10909 case ARM::WIN__DBZCHK: 10910 return EmitLowered__dbzchk(MI, BB); 10911 } 10912 } 10913 10914 /// Attaches vregs to MEMCPY that it will use as scratch registers 10915 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 10916 /// instead of as a custom inserter because we need the use list from the SDNode. 10917 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 10918 MachineInstr &MI, const SDNode *Node) { 10919 bool isThumb1 = Subtarget->isThumb1Only(); 10920 10921 DebugLoc DL = MI.getDebugLoc(); 10922 MachineFunction *MF = MI.getParent()->getParent(); 10923 MachineRegisterInfo &MRI = MF->getRegInfo(); 10924 MachineInstrBuilder MIB(*MF, MI); 10925 10926 // If the new dst/src is unused mark it as dead. 10927 if (!Node->hasAnyUseOfValue(0)) { 10928 MI.getOperand(0).setIsDead(true); 10929 } 10930 if (!Node->hasAnyUseOfValue(1)) { 10931 MI.getOperand(1).setIsDead(true); 10932 } 10933 10934 // The MEMCPY both defines and kills the scratch registers. 10935 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 10936 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 10937 : &ARM::GPRRegClass); 10938 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 10939 } 10940 } 10941 10942 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10943 SDNode *Node) const { 10944 if (MI.getOpcode() == ARM::MEMCPY) { 10945 attachMEMCPYScratchRegs(Subtarget, MI, Node); 10946 return; 10947 } 10948 10949 const MCInstrDesc *MCID = &MI.getDesc(); 10950 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 10951 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 10952 // operand is still set to noreg. If needed, set the optional operand's 10953 // register to CPSR, and remove the redundant implicit def. 10954 // 10955 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 10956 10957 // Rename pseudo opcodes. 10958 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 10959 unsigned ccOutIdx; 10960 if (NewOpc) { 10961 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 10962 MCID = &TII->get(NewOpc); 10963 10964 assert(MCID->getNumOperands() == 10965 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 10966 && "converted opcode should be the same except for cc_out" 10967 " (and, on Thumb1, pred)"); 10968 10969 MI.setDesc(*MCID); 10970 10971 // Add the optional cc_out operand 10972 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 10973 10974 // On Thumb1, move all input operands to the end, then add the predicate 10975 if (Subtarget->isThumb1Only()) { 10976 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 10977 MI.addOperand(MI.getOperand(1)); 10978 MI.RemoveOperand(1); 10979 } 10980 10981 // Restore the ties 10982 for (unsigned i = MI.getNumOperands(); i--;) { 10983 const MachineOperand& op = MI.getOperand(i); 10984 if (op.isReg() && op.isUse()) { 10985 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 10986 if (DefIdx != -1) 10987 MI.tieOperands(DefIdx, i); 10988 } 10989 } 10990 10991 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 10992 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 10993 ccOutIdx = 1; 10994 } else 10995 ccOutIdx = MCID->getNumOperands() - 1; 10996 } else 10997 ccOutIdx = MCID->getNumOperands() - 1; 10998 10999 // Any ARM instruction that sets the 's' bit should specify an optional 11000 // "cc_out" operand in the last operand position. 11001 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 11002 assert(!NewOpc && "Optional cc_out operand required"); 11003 return; 11004 } 11005 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 11006 // since we already have an optional CPSR def. 11007 bool definesCPSR = false; 11008 bool deadCPSR = false; 11009 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 11010 ++i) { 11011 const MachineOperand &MO = MI.getOperand(i); 11012 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 11013 definesCPSR = true; 11014 if (MO.isDead()) 11015 deadCPSR = true; 11016 MI.RemoveOperand(i); 11017 break; 11018 } 11019 } 11020 if (!definesCPSR) { 11021 assert(!NewOpc && "Optional cc_out operand required"); 11022 return; 11023 } 11024 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 11025 if (deadCPSR) { 11026 assert(!MI.getOperand(ccOutIdx).getReg() && 11027 "expect uninitialized optional cc_out operand"); 11028 // Thumb1 instructions must have the S bit even if the CPSR is dead. 11029 if (!Subtarget->isThumb1Only()) 11030 return; 11031 } 11032 11033 // If this instruction was defined with an optional CPSR def and its dag node 11034 // had a live implicit CPSR def, then activate the optional CPSR def. 11035 MachineOperand &MO = MI.getOperand(ccOutIdx); 11036 MO.setReg(ARM::CPSR); 11037 MO.setIsDef(true); 11038 } 11039 11040 //===----------------------------------------------------------------------===// 11041 // ARM Optimization Hooks 11042 //===----------------------------------------------------------------------===// 11043 11044 // Helper function that checks if N is a null or all ones constant. 11045 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 11046 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 11047 } 11048 11049 // Return true if N is conditionally 0 or all ones. 11050 // Detects these expressions where cc is an i1 value: 11051 // 11052 // (select cc 0, y) [AllOnes=0] 11053 // (select cc y, 0) [AllOnes=0] 11054 // (zext cc) [AllOnes=0] 11055 // (sext cc) [AllOnes=0/1] 11056 // (select cc -1, y) [AllOnes=1] 11057 // (select cc y, -1) [AllOnes=1] 11058 // 11059 // Invert is set when N is the null/all ones constant when CC is false. 11060 // OtherOp is set to the alternative value of N. 11061 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 11062 SDValue &CC, bool &Invert, 11063 SDValue &OtherOp, 11064 SelectionDAG &DAG) { 11065 switch (N->getOpcode()) { 11066 default: return false; 11067 case ISD::SELECT: { 11068 CC = N->getOperand(0); 11069 SDValue N1 = N->getOperand(1); 11070 SDValue N2 = N->getOperand(2); 11071 if (isZeroOrAllOnes(N1, AllOnes)) { 11072 Invert = false; 11073 OtherOp = N2; 11074 return true; 11075 } 11076 if (isZeroOrAllOnes(N2, AllOnes)) { 11077 Invert = true; 11078 OtherOp = N1; 11079 return true; 11080 } 11081 return false; 11082 } 11083 case ISD::ZERO_EXTEND: 11084 // (zext cc) can never be the all ones value. 11085 if (AllOnes) 11086 return false; 11087 LLVM_FALLTHROUGH; 11088 case ISD::SIGN_EXTEND: { 11089 SDLoc dl(N); 11090 EVT VT = N->getValueType(0); 11091 CC = N->getOperand(0); 11092 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 11093 return false; 11094 Invert = !AllOnes; 11095 if (AllOnes) 11096 // When looking for an AllOnes constant, N is an sext, and the 'other' 11097 // value is 0. 11098 OtherOp = DAG.getConstant(0, dl, VT); 11099 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11100 // When looking for a 0 constant, N can be zext or sext. 11101 OtherOp = DAG.getConstant(1, dl, VT); 11102 else 11103 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 11104 VT); 11105 return true; 11106 } 11107 } 11108 } 11109 11110 // Combine a constant select operand into its use: 11111 // 11112 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11113 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11114 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 11115 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11116 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11117 // 11118 // The transform is rejected if the select doesn't have a constant operand that 11119 // is null, or all ones when AllOnes is set. 11120 // 11121 // Also recognize sext/zext from i1: 11122 // 11123 // (add (zext cc), x) -> (select cc (add x, 1), x) 11124 // (add (sext cc), x) -> (select cc (add x, -1), x) 11125 // 11126 // These transformations eventually create predicated instructions. 11127 // 11128 // @param N The node to transform. 11129 // @param Slct The N operand that is a select. 11130 // @param OtherOp The other N operand (x above). 11131 // @param DCI Context. 11132 // @param AllOnes Require the select constant to be all ones instead of null. 11133 // @returns The new node, or SDValue() on failure. 11134 static 11135 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 11136 TargetLowering::DAGCombinerInfo &DCI, 11137 bool AllOnes = false) { 11138 SelectionDAG &DAG = DCI.DAG; 11139 EVT VT = N->getValueType(0); 11140 SDValue NonConstantVal; 11141 SDValue CCOp; 11142 bool SwapSelectOps; 11143 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 11144 NonConstantVal, DAG)) 11145 return SDValue(); 11146 11147 // Slct is now know to be the desired identity constant when CC is true. 11148 SDValue TrueVal = OtherOp; 11149 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 11150 OtherOp, NonConstantVal); 11151 // Unless SwapSelectOps says CC should be false. 11152 if (SwapSelectOps) 11153 std::swap(TrueVal, FalseVal); 11154 11155 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 11156 CCOp, TrueVal, FalseVal); 11157 } 11158 11159 // Attempt combineSelectAndUse on each operand of a commutative operator N. 11160 static 11161 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 11162 TargetLowering::DAGCombinerInfo &DCI) { 11163 SDValue N0 = N->getOperand(0); 11164 SDValue N1 = N->getOperand(1); 11165 if (N0.getNode()->hasOneUse()) 11166 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 11167 return Result; 11168 if (N1.getNode()->hasOneUse()) 11169 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 11170 return Result; 11171 return SDValue(); 11172 } 11173 11174 static bool IsVUZPShuffleNode(SDNode *N) { 11175 // VUZP shuffle node. 11176 if (N->getOpcode() == ARMISD::VUZP) 11177 return true; 11178 11179 // "VUZP" on i32 is an alias for VTRN. 11180 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 11181 return true; 11182 11183 return false; 11184 } 11185 11186 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 11187 TargetLowering::DAGCombinerInfo &DCI, 11188 const ARMSubtarget *Subtarget) { 11189 // Look for ADD(VUZP.0, VUZP.1). 11190 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 11191 N0 == N1) 11192 return SDValue(); 11193 11194 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 11195 if (!N->getValueType(0).is64BitVector()) 11196 return SDValue(); 11197 11198 // Generate vpadd. 11199 SelectionDAG &DAG = DCI.DAG; 11200 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11201 SDLoc dl(N); 11202 SDNode *Unzip = N0.getNode(); 11203 EVT VT = N->getValueType(0); 11204 11205 SmallVector<SDValue, 8> Ops; 11206 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 11207 TLI.getPointerTy(DAG.getDataLayout()))); 11208 Ops.push_back(Unzip->getOperand(0)); 11209 Ops.push_back(Unzip->getOperand(1)); 11210 11211 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11212 } 11213 11214 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11215 TargetLowering::DAGCombinerInfo &DCI, 11216 const ARMSubtarget *Subtarget) { 11217 // Check for two extended operands. 11218 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 11219 N1.getOpcode() == ISD::SIGN_EXTEND) && 11220 !(N0.getOpcode() == ISD::ZERO_EXTEND && 11221 N1.getOpcode() == ISD::ZERO_EXTEND)) 11222 return SDValue(); 11223 11224 SDValue N00 = N0.getOperand(0); 11225 SDValue N10 = N1.getOperand(0); 11226 11227 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 11228 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 11229 N00 == N10) 11230 return SDValue(); 11231 11232 // We only recognize Q register paddl here; this can't be reached until 11233 // after type legalization. 11234 if (!N00.getValueType().is64BitVector() || 11235 !N0.getValueType().is128BitVector()) 11236 return SDValue(); 11237 11238 // Generate vpaddl. 11239 SelectionDAG &DAG = DCI.DAG; 11240 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11241 SDLoc dl(N); 11242 EVT VT = N->getValueType(0); 11243 11244 SmallVector<SDValue, 8> Ops; 11245 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 11246 unsigned Opcode; 11247 if (N0.getOpcode() == ISD::SIGN_EXTEND) 11248 Opcode = Intrinsic::arm_neon_vpaddls; 11249 else 11250 Opcode = Intrinsic::arm_neon_vpaddlu; 11251 Ops.push_back(DAG.getConstant(Opcode, dl, 11252 TLI.getPointerTy(DAG.getDataLayout()))); 11253 EVT ElemTy = N00.getValueType().getVectorElementType(); 11254 unsigned NumElts = VT.getVectorNumElements(); 11255 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 11256 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 11257 N00.getOperand(0), N00.getOperand(1)); 11258 Ops.push_back(Concat); 11259 11260 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11261 } 11262 11263 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 11264 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 11265 // much easier to match. 11266 static SDValue 11267 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11268 TargetLowering::DAGCombinerInfo &DCI, 11269 const ARMSubtarget *Subtarget) { 11270 // Only perform optimization if after legalize, and if NEON is available. We 11271 // also expected both operands to be BUILD_VECTORs. 11272 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 11273 || N0.getOpcode() != ISD::BUILD_VECTOR 11274 || N1.getOpcode() != ISD::BUILD_VECTOR) 11275 return SDValue(); 11276 11277 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 11278 EVT VT = N->getValueType(0); 11279 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 11280 return SDValue(); 11281 11282 // Check that the vector operands are of the right form. 11283 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 11284 // operands, where N is the size of the formed vector. 11285 // Each EXTRACT_VECTOR should have the same input vector and odd or even 11286 // index such that we have a pair wise add pattern. 11287 11288 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 11289 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11290 return SDValue(); 11291 SDValue Vec = N0->getOperand(0)->getOperand(0); 11292 SDNode *V = Vec.getNode(); 11293 unsigned nextIndex = 0; 11294 11295 // For each operands to the ADD which are BUILD_VECTORs, 11296 // check to see if each of their operands are an EXTRACT_VECTOR with 11297 // the same vector and appropriate index. 11298 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 11299 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 11300 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11301 11302 SDValue ExtVec0 = N0->getOperand(i); 11303 SDValue ExtVec1 = N1->getOperand(i); 11304 11305 // First operand is the vector, verify its the same. 11306 if (V != ExtVec0->getOperand(0).getNode() || 11307 V != ExtVec1->getOperand(0).getNode()) 11308 return SDValue(); 11309 11310 // Second is the constant, verify its correct. 11311 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 11312 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 11313 11314 // For the constant, we want to see all the even or all the odd. 11315 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 11316 || C1->getZExtValue() != nextIndex+1) 11317 return SDValue(); 11318 11319 // Increment index. 11320 nextIndex+=2; 11321 } else 11322 return SDValue(); 11323 } 11324 11325 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 11326 // we're using the entire input vector, otherwise there's a size/legality 11327 // mismatch somewhere. 11328 if (nextIndex != Vec.getValueType().getVectorNumElements() || 11329 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 11330 return SDValue(); 11331 11332 // Create VPADDL node. 11333 SelectionDAG &DAG = DCI.DAG; 11334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11335 11336 SDLoc dl(N); 11337 11338 // Build operand list. 11339 SmallVector<SDValue, 8> Ops; 11340 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 11341 TLI.getPointerTy(DAG.getDataLayout()))); 11342 11343 // Input is the vector. 11344 Ops.push_back(Vec); 11345 11346 // Get widened type and narrowed type. 11347 MVT widenType; 11348 unsigned numElem = VT.getVectorNumElements(); 11349 11350 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 11351 switch (inputLaneType.getSimpleVT().SimpleTy) { 11352 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 11353 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 11354 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 11355 default: 11356 llvm_unreachable("Invalid vector element type for padd optimization."); 11357 } 11358 11359 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 11360 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 11361 return DAG.getNode(ExtOp, dl, VT, tmp); 11362 } 11363 11364 static SDValue findMUL_LOHI(SDValue V) { 11365 if (V->getOpcode() == ISD::UMUL_LOHI || 11366 V->getOpcode() == ISD::SMUL_LOHI) 11367 return V; 11368 return SDValue(); 11369 } 11370 11371 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 11372 TargetLowering::DAGCombinerInfo &DCI, 11373 const ARMSubtarget *Subtarget) { 11374 if (!Subtarget->hasBaseDSP()) 11375 return SDValue(); 11376 11377 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 11378 // accumulates the product into a 64-bit value. The 16-bit values will 11379 // be sign extended somehow or SRA'd into 32-bit values 11380 // (addc (adde (mul 16bit, 16bit), lo), hi) 11381 SDValue Mul = AddcNode->getOperand(0); 11382 SDValue Lo = AddcNode->getOperand(1); 11383 if (Mul.getOpcode() != ISD::MUL) { 11384 Lo = AddcNode->getOperand(0); 11385 Mul = AddcNode->getOperand(1); 11386 if (Mul.getOpcode() != ISD::MUL) 11387 return SDValue(); 11388 } 11389 11390 SDValue SRA = AddeNode->getOperand(0); 11391 SDValue Hi = AddeNode->getOperand(1); 11392 if (SRA.getOpcode() != ISD::SRA) { 11393 SRA = AddeNode->getOperand(1); 11394 Hi = AddeNode->getOperand(0); 11395 if (SRA.getOpcode() != ISD::SRA) 11396 return SDValue(); 11397 } 11398 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 11399 if (Const->getZExtValue() != 31) 11400 return SDValue(); 11401 } else 11402 return SDValue(); 11403 11404 if (SRA.getOperand(0) != Mul) 11405 return SDValue(); 11406 11407 SelectionDAG &DAG = DCI.DAG; 11408 SDLoc dl(AddcNode); 11409 unsigned Opcode = 0; 11410 SDValue Op0; 11411 SDValue Op1; 11412 11413 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 11414 Opcode = ARMISD::SMLALBB; 11415 Op0 = Mul.getOperand(0); 11416 Op1 = Mul.getOperand(1); 11417 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 11418 Opcode = ARMISD::SMLALBT; 11419 Op0 = Mul.getOperand(0); 11420 Op1 = Mul.getOperand(1).getOperand(0); 11421 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 11422 Opcode = ARMISD::SMLALTB; 11423 Op0 = Mul.getOperand(0).getOperand(0); 11424 Op1 = Mul.getOperand(1); 11425 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 11426 Opcode = ARMISD::SMLALTT; 11427 Op0 = Mul->getOperand(0).getOperand(0); 11428 Op1 = Mul->getOperand(1).getOperand(0); 11429 } 11430 11431 if (!Op0 || !Op1) 11432 return SDValue(); 11433 11434 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 11435 Op0, Op1, Lo, Hi); 11436 // Replace the ADDs' nodes uses by the MLA node's values. 11437 SDValue HiMLALResult(SMLAL.getNode(), 1); 11438 SDValue LoMLALResult(SMLAL.getNode(), 0); 11439 11440 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 11441 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 11442 11443 // Return original node to notify the driver to stop replacing. 11444 SDValue resNode(AddcNode, 0); 11445 return resNode; 11446 } 11447 11448 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 11449 TargetLowering::DAGCombinerInfo &DCI, 11450 const ARMSubtarget *Subtarget) { 11451 // Look for multiply add opportunities. 11452 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 11453 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 11454 // a glue link from the first add to the second add. 11455 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 11456 // a S/UMLAL instruction. 11457 // UMUL_LOHI 11458 // / :lo \ :hi 11459 // V \ [no multiline comment] 11460 // loAdd -> ADDC | 11461 // \ :carry / 11462 // V V 11463 // ADDE <- hiAdd 11464 // 11465 // In the special case where only the higher part of a signed result is used 11466 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 11467 // a constant with the exact value of 0x80000000, we recognize we are dealing 11468 // with a "rounded multiply and add" (or subtract) and transform it into 11469 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 11470 11471 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 11472 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 11473 "Expect an ADDE or SUBE"); 11474 11475 assert(AddeSubeNode->getNumOperands() == 3 && 11476 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 11477 "ADDE node has the wrong inputs"); 11478 11479 // Check that we are chained to the right ADDC or SUBC node. 11480 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 11481 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 11482 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 11483 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 11484 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 11485 return SDValue(); 11486 11487 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 11488 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 11489 11490 // Check if the two operands are from the same mul_lohi node. 11491 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 11492 return SDValue(); 11493 11494 assert(AddcSubcNode->getNumValues() == 2 && 11495 AddcSubcNode->getValueType(0) == MVT::i32 && 11496 "Expect ADDC with two result values. First: i32"); 11497 11498 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 11499 // maybe a SMLAL which multiplies two 16-bit values. 11500 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 11501 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 11502 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 11503 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 11504 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 11505 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 11506 11507 // Check for the triangle shape. 11508 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 11509 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 11510 11511 // Make sure that the ADDE/SUBE operands are not coming from the same node. 11512 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 11513 return SDValue(); 11514 11515 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 11516 bool IsLeftOperandMUL = false; 11517 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 11518 if (MULOp == SDValue()) 11519 MULOp = findMUL_LOHI(AddeSubeOp1); 11520 else 11521 IsLeftOperandMUL = true; 11522 if (MULOp == SDValue()) 11523 return SDValue(); 11524 11525 // Figure out the right opcode. 11526 unsigned Opc = MULOp->getOpcode(); 11527 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 11528 11529 // Figure out the high and low input values to the MLAL node. 11530 SDValue *HiAddSub = nullptr; 11531 SDValue *LoMul = nullptr; 11532 SDValue *LowAddSub = nullptr; 11533 11534 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 11535 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 11536 return SDValue(); 11537 11538 if (IsLeftOperandMUL) 11539 HiAddSub = &AddeSubeOp1; 11540 else 11541 HiAddSub = &AddeSubeOp0; 11542 11543 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 11544 // whose low result is fed to the ADDC/SUBC we are checking. 11545 11546 if (AddcSubcOp0 == MULOp.getValue(0)) { 11547 LoMul = &AddcSubcOp0; 11548 LowAddSub = &AddcSubcOp1; 11549 } 11550 if (AddcSubcOp1 == MULOp.getValue(0)) { 11551 LoMul = &AddcSubcOp1; 11552 LowAddSub = &AddcSubcOp0; 11553 } 11554 11555 if (!LoMul) 11556 return SDValue(); 11557 11558 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 11559 // the replacement below will create a cycle. 11560 if (AddcSubcNode == HiAddSub->getNode() || 11561 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 11562 return SDValue(); 11563 11564 // Create the merged node. 11565 SelectionDAG &DAG = DCI.DAG; 11566 11567 // Start building operand list. 11568 SmallVector<SDValue, 8> Ops; 11569 Ops.push_back(LoMul->getOperand(0)); 11570 Ops.push_back(LoMul->getOperand(1)); 11571 11572 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 11573 // the case, we must be doing signed multiplication and only use the higher 11574 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 11575 // addition or subtraction with the value of 0x800000. 11576 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 11577 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 11578 LowAddSub->getNode()->getOpcode() == ISD::Constant && 11579 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 11580 0x80000000) { 11581 Ops.push_back(*HiAddSub); 11582 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 11583 FinalOpc = ARMISD::SMMLSR; 11584 } else { 11585 FinalOpc = ARMISD::SMMLAR; 11586 } 11587 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 11588 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 11589 11590 return SDValue(AddeSubeNode, 0); 11591 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 11592 // SMMLS is generated during instruction selection and the rest of this 11593 // function can not handle the case where AddcSubcNode is a SUBC. 11594 return SDValue(); 11595 11596 // Finish building the operand list for {U/S}MLAL 11597 Ops.push_back(*LowAddSub); 11598 Ops.push_back(*HiAddSub); 11599 11600 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11601 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11602 11603 // Replace the ADDs' nodes uses by the MLA node's values. 11604 SDValue HiMLALResult(MLALNode.getNode(), 1); 11605 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11606 11607 SDValue LoMLALResult(MLALNode.getNode(), 0); 11608 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11609 11610 // Return original node to notify the driver to stop replacing. 11611 return SDValue(AddeSubeNode, 0); 11612 } 11613 11614 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11615 TargetLowering::DAGCombinerInfo &DCI, 11616 const ARMSubtarget *Subtarget) { 11617 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11618 // While trying to combine for the other MLAL nodes, first search for the 11619 // chance to use UMAAL. Check if Addc uses a node which has already 11620 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11621 // as the addend, and it's handled in PerformUMLALCombine. 11622 11623 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11624 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11625 11626 // Check that we have a glued ADDC node. 11627 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11628 if (AddcNode->getOpcode() != ARMISD::ADDC) 11629 return SDValue(); 11630 11631 // Find the converted UMAAL or quit if it doesn't exist. 11632 SDNode *UmlalNode = nullptr; 11633 SDValue AddHi; 11634 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11635 UmlalNode = AddcNode->getOperand(0).getNode(); 11636 AddHi = AddcNode->getOperand(1); 11637 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 11638 UmlalNode = AddcNode->getOperand(1).getNode(); 11639 AddHi = AddcNode->getOperand(0); 11640 } else { 11641 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11642 } 11643 11644 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 11645 // the ADDC as well as Zero. 11646 if (!isNullConstant(UmlalNode->getOperand(3))) 11647 return SDValue(); 11648 11649 if ((isNullConstant(AddeNode->getOperand(0)) && 11650 AddeNode->getOperand(1).getNode() == UmlalNode) || 11651 (AddeNode->getOperand(0).getNode() == UmlalNode && 11652 isNullConstant(AddeNode->getOperand(1)))) { 11653 SelectionDAG &DAG = DCI.DAG; 11654 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 11655 UmlalNode->getOperand(2), AddHi }; 11656 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 11657 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11658 11659 // Replace the ADDs' nodes uses by the UMAAL node's values. 11660 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 11661 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 11662 11663 // Return original node to notify the driver to stop replacing. 11664 return SDValue(AddeNode, 0); 11665 } 11666 return SDValue(); 11667 } 11668 11669 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 11670 const ARMSubtarget *Subtarget) { 11671 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11672 return SDValue(); 11673 11674 // Check that we have a pair of ADDC and ADDE as operands. 11675 // Both addends of the ADDE must be zero. 11676 SDNode* AddcNode = N->getOperand(2).getNode(); 11677 SDNode* AddeNode = N->getOperand(3).getNode(); 11678 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 11679 (AddeNode->getOpcode() == ARMISD::ADDE) && 11680 isNullConstant(AddeNode->getOperand(0)) && 11681 isNullConstant(AddeNode->getOperand(1)) && 11682 (AddeNode->getOperand(2).getNode() == AddcNode)) 11683 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 11684 DAG.getVTList(MVT::i32, MVT::i32), 11685 {N->getOperand(0), N->getOperand(1), 11686 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 11687 else 11688 return SDValue(); 11689 } 11690 11691 static SDValue PerformAddcSubcCombine(SDNode *N, 11692 TargetLowering::DAGCombinerInfo &DCI, 11693 const ARMSubtarget *Subtarget) { 11694 SelectionDAG &DAG(DCI.DAG); 11695 11696 if (N->getOpcode() == ARMISD::SUBC) { 11697 // (SUBC (ADDE 0, 0, C), 1) -> C 11698 SDValue LHS = N->getOperand(0); 11699 SDValue RHS = N->getOperand(1); 11700 if (LHS->getOpcode() == ARMISD::ADDE && 11701 isNullConstant(LHS->getOperand(0)) && 11702 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 11703 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 11704 } 11705 } 11706 11707 if (Subtarget->isThumb1Only()) { 11708 SDValue RHS = N->getOperand(1); 11709 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11710 int32_t imm = C->getSExtValue(); 11711 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 11712 SDLoc DL(N); 11713 RHS = DAG.getConstant(-imm, DL, MVT::i32); 11714 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 11715 : ARMISD::ADDC; 11716 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 11717 } 11718 } 11719 } 11720 11721 return SDValue(); 11722 } 11723 11724 static SDValue PerformAddeSubeCombine(SDNode *N, 11725 TargetLowering::DAGCombinerInfo &DCI, 11726 const ARMSubtarget *Subtarget) { 11727 if (Subtarget->isThumb1Only()) { 11728 SelectionDAG &DAG = DCI.DAG; 11729 SDValue RHS = N->getOperand(1); 11730 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11731 int64_t imm = C->getSExtValue(); 11732 if (imm < 0) { 11733 SDLoc DL(N); 11734 11735 // The with-carry-in form matches bitwise not instead of the negation. 11736 // Effectively, the inverse interpretation of the carry flag already 11737 // accounts for part of the negation. 11738 RHS = DAG.getConstant(~imm, DL, MVT::i32); 11739 11740 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 11741 : ARMISD::ADDE; 11742 return DAG.getNode(Opcode, DL, N->getVTList(), 11743 N->getOperand(0), RHS, N->getOperand(2)); 11744 } 11745 } 11746 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 11747 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 11748 } 11749 return SDValue(); 11750 } 11751 11752 static SDValue PerformABSCombine(SDNode *N, 11753 TargetLowering::DAGCombinerInfo &DCI, 11754 const ARMSubtarget *Subtarget) { 11755 SDValue res; 11756 SelectionDAG &DAG = DCI.DAG; 11757 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11758 11759 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 11760 return SDValue(); 11761 11762 if (!TLI.expandABS(N, res, DAG)) 11763 return SDValue(); 11764 11765 return res; 11766 } 11767 11768 /// PerformADDECombine - Target-specific dag combine transform from 11769 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 11770 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 11771 static SDValue PerformADDECombine(SDNode *N, 11772 TargetLowering::DAGCombinerInfo &DCI, 11773 const ARMSubtarget *Subtarget) { 11774 // Only ARM and Thumb2 support UMLAL/SMLAL. 11775 if (Subtarget->isThumb1Only()) 11776 return PerformAddeSubeCombine(N, DCI, Subtarget); 11777 11778 // Only perform the checks after legalize when the pattern is available. 11779 if (DCI.isBeforeLegalize()) return SDValue(); 11780 11781 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 11782 } 11783 11784 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 11785 /// operands N0 and N1. This is a helper for PerformADDCombine that is 11786 /// called with the default operands, and if that fails, with commuted 11787 /// operands. 11788 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 11789 TargetLowering::DAGCombinerInfo &DCI, 11790 const ARMSubtarget *Subtarget){ 11791 // Attempt to create vpadd for this add. 11792 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 11793 return Result; 11794 11795 // Attempt to create vpaddl for this add. 11796 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 11797 return Result; 11798 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 11799 Subtarget)) 11800 return Result; 11801 11802 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11803 if (N0.getNode()->hasOneUse()) 11804 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 11805 return Result; 11806 return SDValue(); 11807 } 11808 11809 static SDValue PerformADDVecReduce(SDNode *N, 11810 TargetLowering::DAGCombinerInfo &DCI, 11811 const ARMSubtarget *Subtarget) { 11812 if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64) 11813 return SDValue(); 11814 11815 SDValue N0 = N->getOperand(0); 11816 SDValue N1 = N->getOperand(1); 11817 11818 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this 11819 // will look like: 11820 // t1: i32,i32 = ARMISD::VADDLVs x 11821 // t2: i64 = build_pair t1, t1:1 11822 // t3: i64 = add t2, y 11823 // We also need to check for sext / zext and commutitive adds. 11824 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA, 11825 SDValue NB) { 11826 if (NB->getOpcode() != ISD::BUILD_PAIR) 11827 return SDValue(); 11828 SDValue VecRed = NB->getOperand(0); 11829 if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 || 11830 NB->getOperand(1) != SDValue(VecRed.getNode(), 1)) 11831 return SDValue(); 11832 11833 SDLoc dl(N); 11834 SmallVector<SDValue, 4> Ops; 11835 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 11836 DCI.DAG.getConstant(0, dl, MVT::i32))); 11837 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 11838 DCI.DAG.getConstant(1, dl, MVT::i32))); 11839 for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++) 11840 Ops.push_back(VecRed->getOperand(i)); 11841 SDValue Red = DCI.DAG.getNode(OpcodeA, dl, 11842 DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops); 11843 return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red, 11844 SDValue(Red.getNode(), 1)); 11845 }; 11846 11847 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1)) 11848 return M; 11849 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1)) 11850 return M; 11851 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0)) 11852 return M; 11853 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0)) 11854 return M; 11855 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1)) 11856 return M; 11857 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1)) 11858 return M; 11859 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0)) 11860 return M; 11861 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0)) 11862 return M; 11863 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1)) 11864 return M; 11865 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1)) 11866 return M; 11867 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0)) 11868 return M; 11869 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0)) 11870 return M; 11871 return SDValue(); 11872 } 11873 11874 bool 11875 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 11876 CombineLevel Level) const { 11877 if (Level == BeforeLegalizeTypes) 11878 return true; 11879 11880 if (N->getOpcode() != ISD::SHL) 11881 return true; 11882 11883 if (Subtarget->isThumb1Only()) { 11884 // Avoid making expensive immediates by commuting shifts. (This logic 11885 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 11886 // for free.) 11887 if (N->getOpcode() != ISD::SHL) 11888 return true; 11889 SDValue N1 = N->getOperand(0); 11890 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 11891 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 11892 return true; 11893 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 11894 if (Const->getAPIntValue().ult(256)) 11895 return false; 11896 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 11897 Const->getAPIntValue().sgt(-256)) 11898 return false; 11899 } 11900 return true; 11901 } 11902 11903 // Turn off commute-with-shift transform after legalization, so it doesn't 11904 // conflict with PerformSHLSimplify. (We could try to detect when 11905 // PerformSHLSimplify would trigger more precisely, but it isn't 11906 // really necessary.) 11907 return false; 11908 } 11909 11910 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 11911 const SDNode *N, CombineLevel Level) const { 11912 if (!Subtarget->isThumb1Only()) 11913 return true; 11914 11915 if (Level == BeforeLegalizeTypes) 11916 return true; 11917 11918 return false; 11919 } 11920 11921 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 11922 if (!Subtarget->hasNEON()) { 11923 if (Subtarget->isThumb1Only()) 11924 return VT.getScalarSizeInBits() <= 32; 11925 return true; 11926 } 11927 return VT.isScalarInteger(); 11928 } 11929 11930 static SDValue PerformSHLSimplify(SDNode *N, 11931 TargetLowering::DAGCombinerInfo &DCI, 11932 const ARMSubtarget *ST) { 11933 // Allow the generic combiner to identify potential bswaps. 11934 if (DCI.isBeforeLegalize()) 11935 return SDValue(); 11936 11937 // DAG combiner will fold: 11938 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 11939 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 11940 // Other code patterns that can be also be modified have the following form: 11941 // b + ((a << 1) | 510) 11942 // b + ((a << 1) & 510) 11943 // b + ((a << 1) ^ 510) 11944 // b + ((a << 1) + 510) 11945 11946 // Many instructions can perform the shift for free, but it requires both 11947 // the operands to be registers. If c1 << c2 is too large, a mov immediate 11948 // instruction will needed. So, unfold back to the original pattern if: 11949 // - if c1 and c2 are small enough that they don't require mov imms. 11950 // - the user(s) of the node can perform an shl 11951 11952 // No shifted operands for 16-bit instructions. 11953 if (ST->isThumb() && ST->isThumb1Only()) 11954 return SDValue(); 11955 11956 // Check that all the users could perform the shl themselves. 11957 for (auto U : N->uses()) { 11958 switch(U->getOpcode()) { 11959 default: 11960 return SDValue(); 11961 case ISD::SUB: 11962 case ISD::ADD: 11963 case ISD::AND: 11964 case ISD::OR: 11965 case ISD::XOR: 11966 case ISD::SETCC: 11967 case ARMISD::CMP: 11968 // Check that the user isn't already using a constant because there 11969 // aren't any instructions that support an immediate operand and a 11970 // shifted operand. 11971 if (isa<ConstantSDNode>(U->getOperand(0)) || 11972 isa<ConstantSDNode>(U->getOperand(1))) 11973 return SDValue(); 11974 11975 // Check that it's not already using a shift. 11976 if (U->getOperand(0).getOpcode() == ISD::SHL || 11977 U->getOperand(1).getOpcode() == ISD::SHL) 11978 return SDValue(); 11979 break; 11980 } 11981 } 11982 11983 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 11984 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 11985 return SDValue(); 11986 11987 if (N->getOperand(0).getOpcode() != ISD::SHL) 11988 return SDValue(); 11989 11990 SDValue SHL = N->getOperand(0); 11991 11992 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11993 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 11994 if (!C1ShlC2 || !C2) 11995 return SDValue(); 11996 11997 APInt C2Int = C2->getAPIntValue(); 11998 APInt C1Int = C1ShlC2->getAPIntValue(); 11999 12000 // Check that performing a lshr will not lose any information. 12001 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 12002 C2Int.getBitWidth() - C2->getZExtValue()); 12003 if ((C1Int & Mask) != C1Int) 12004 return SDValue(); 12005 12006 // Shift the first constant. 12007 C1Int.lshrInPlace(C2Int); 12008 12009 // The immediates are encoded as an 8-bit value that can be rotated. 12010 auto LargeImm = [](const APInt &Imm) { 12011 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 12012 return Imm.getBitWidth() - Zeros > 8; 12013 }; 12014 12015 if (LargeImm(C1Int) || LargeImm(C2Int)) 12016 return SDValue(); 12017 12018 SelectionDAG &DAG = DCI.DAG; 12019 SDLoc dl(N); 12020 SDValue X = SHL.getOperand(0); 12021 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 12022 DAG.getConstant(C1Int, dl, MVT::i32)); 12023 // Shift left to compensate for the lshr of C1Int. 12024 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 12025 12026 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 12027 SHL.dump(); N->dump()); 12028 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 12029 return Res; 12030 } 12031 12032 12033 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 12034 /// 12035 static SDValue PerformADDCombine(SDNode *N, 12036 TargetLowering::DAGCombinerInfo &DCI, 12037 const ARMSubtarget *Subtarget) { 12038 SDValue N0 = N->getOperand(0); 12039 SDValue N1 = N->getOperand(1); 12040 12041 // Only works one way, because it needs an immediate operand. 12042 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12043 return Result; 12044 12045 if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget)) 12046 return Result; 12047 12048 // First try with the default operand order. 12049 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 12050 return Result; 12051 12052 // If that didn't work, try again with the operands commuted. 12053 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 12054 } 12055 12056 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 12057 /// 12058 static SDValue PerformSUBCombine(SDNode *N, 12059 TargetLowering::DAGCombinerInfo &DCI, 12060 const ARMSubtarget *Subtarget) { 12061 SDValue N0 = N->getOperand(0); 12062 SDValue N1 = N->getOperand(1); 12063 12064 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 12065 if (N1.getNode()->hasOneUse()) 12066 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 12067 return Result; 12068 12069 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector()) 12070 return SDValue(); 12071 12072 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x)) 12073 // so that we can readily pattern match more mve instructions which can use 12074 // a scalar operand. 12075 SDValue VDup = N->getOperand(1); 12076 if (VDup->getOpcode() != ARMISD::VDUP) 12077 return SDValue(); 12078 12079 SDValue VMov = N->getOperand(0); 12080 if (VMov->getOpcode() == ISD::BITCAST) 12081 VMov = VMov->getOperand(0); 12082 12083 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov)) 12084 return SDValue(); 12085 12086 SDLoc dl(N); 12087 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32, 12088 DCI.DAG.getConstant(0, dl, MVT::i32), 12089 VDup->getOperand(0)); 12090 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate); 12091 } 12092 12093 /// PerformVMULCombine 12094 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 12095 /// special multiplier accumulator forwarding. 12096 /// vmul d3, d0, d2 12097 /// vmla d3, d1, d2 12098 /// is faster than 12099 /// vadd d3, d0, d1 12100 /// vmul d3, d3, d2 12101 // However, for (A + B) * (A + B), 12102 // vadd d2, d0, d1 12103 // vmul d3, d0, d2 12104 // vmla d3, d1, d2 12105 // is slower than 12106 // vadd d2, d0, d1 12107 // vmul d3, d2, d2 12108 static SDValue PerformVMULCombine(SDNode *N, 12109 TargetLowering::DAGCombinerInfo &DCI, 12110 const ARMSubtarget *Subtarget) { 12111 if (!Subtarget->hasVMLxForwarding()) 12112 return SDValue(); 12113 12114 SelectionDAG &DAG = DCI.DAG; 12115 SDValue N0 = N->getOperand(0); 12116 SDValue N1 = N->getOperand(1); 12117 unsigned Opcode = N0.getOpcode(); 12118 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12119 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 12120 Opcode = N1.getOpcode(); 12121 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12122 Opcode != ISD::FADD && Opcode != ISD::FSUB) 12123 return SDValue(); 12124 std::swap(N0, N1); 12125 } 12126 12127 if (N0 == N1) 12128 return SDValue(); 12129 12130 EVT VT = N->getValueType(0); 12131 SDLoc DL(N); 12132 SDValue N00 = N0->getOperand(0); 12133 SDValue N01 = N0->getOperand(1); 12134 return DAG.getNode(Opcode, DL, VT, 12135 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 12136 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 12137 } 12138 12139 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG, 12140 const ARMSubtarget *Subtarget) { 12141 EVT VT = N->getValueType(0); 12142 if (VT != MVT::v2i64) 12143 return SDValue(); 12144 12145 SDValue N0 = N->getOperand(0); 12146 SDValue N1 = N->getOperand(1); 12147 12148 auto IsSignExt = [&](SDValue Op) { 12149 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG) 12150 return SDValue(); 12151 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT(); 12152 if (VT.getScalarSizeInBits() == 32) 12153 return Op->getOperand(0); 12154 return SDValue(); 12155 }; 12156 auto IsZeroExt = [&](SDValue Op) { 12157 // Zero extends are a little more awkward. At the point we are matching 12158 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask. 12159 // That might be before of after a bitcast depending on how the and is 12160 // placed. Because this has to look through bitcasts, it is currently only 12161 // supported on LE. 12162 if (!Subtarget->isLittle()) 12163 return SDValue(); 12164 12165 SDValue And = Op; 12166 if (And->getOpcode() == ISD::BITCAST) 12167 And = And->getOperand(0); 12168 if (And->getOpcode() != ISD::AND) 12169 return SDValue(); 12170 SDValue Mask = And->getOperand(1); 12171 if (Mask->getOpcode() == ISD::BITCAST) 12172 Mask = Mask->getOperand(0); 12173 12174 if (Mask->getOpcode() != ISD::BUILD_VECTOR || 12175 Mask.getValueType() != MVT::v4i32) 12176 return SDValue(); 12177 if (isAllOnesConstant(Mask->getOperand(0)) && 12178 isNullConstant(Mask->getOperand(1)) && 12179 isAllOnesConstant(Mask->getOperand(2)) && 12180 isNullConstant(Mask->getOperand(3))) 12181 return And->getOperand(0); 12182 return SDValue(); 12183 }; 12184 12185 SDLoc dl(N); 12186 if (SDValue Op0 = IsSignExt(N0)) { 12187 if (SDValue Op1 = IsSignExt(N1)) { 12188 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12189 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12190 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a); 12191 } 12192 } 12193 if (SDValue Op0 = IsZeroExt(N0)) { 12194 if (SDValue Op1 = IsZeroExt(N1)) { 12195 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12196 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12197 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a); 12198 } 12199 } 12200 12201 return SDValue(); 12202 } 12203 12204 static SDValue PerformMULCombine(SDNode *N, 12205 TargetLowering::DAGCombinerInfo &DCI, 12206 const ARMSubtarget *Subtarget) { 12207 SelectionDAG &DAG = DCI.DAG; 12208 12209 EVT VT = N->getValueType(0); 12210 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64) 12211 return PerformMVEVMULLCombine(N, DAG, Subtarget); 12212 12213 if (Subtarget->isThumb1Only()) 12214 return SDValue(); 12215 12216 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12217 return SDValue(); 12218 12219 if (VT.is64BitVector() || VT.is128BitVector()) 12220 return PerformVMULCombine(N, DCI, Subtarget); 12221 if (VT != MVT::i32) 12222 return SDValue(); 12223 12224 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12225 if (!C) 12226 return SDValue(); 12227 12228 int64_t MulAmt = C->getSExtValue(); 12229 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 12230 12231 ShiftAmt = ShiftAmt & (32 - 1); 12232 SDValue V = N->getOperand(0); 12233 SDLoc DL(N); 12234 12235 SDValue Res; 12236 MulAmt >>= ShiftAmt; 12237 12238 if (MulAmt >= 0) { 12239 if (isPowerOf2_32(MulAmt - 1)) { 12240 // (mul x, 2^N + 1) => (add (shl x, N), x) 12241 Res = DAG.getNode(ISD::ADD, DL, VT, 12242 V, 12243 DAG.getNode(ISD::SHL, DL, VT, 12244 V, 12245 DAG.getConstant(Log2_32(MulAmt - 1), DL, 12246 MVT::i32))); 12247 } else if (isPowerOf2_32(MulAmt + 1)) { 12248 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12249 Res = DAG.getNode(ISD::SUB, DL, VT, 12250 DAG.getNode(ISD::SHL, DL, VT, 12251 V, 12252 DAG.getConstant(Log2_32(MulAmt + 1), DL, 12253 MVT::i32)), 12254 V); 12255 } else 12256 return SDValue(); 12257 } else { 12258 uint64_t MulAmtAbs = -MulAmt; 12259 if (isPowerOf2_32(MulAmtAbs + 1)) { 12260 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12261 Res = DAG.getNode(ISD::SUB, DL, VT, 12262 V, 12263 DAG.getNode(ISD::SHL, DL, VT, 12264 V, 12265 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 12266 MVT::i32))); 12267 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 12268 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12269 Res = DAG.getNode(ISD::ADD, DL, VT, 12270 V, 12271 DAG.getNode(ISD::SHL, DL, VT, 12272 V, 12273 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 12274 MVT::i32))); 12275 Res = DAG.getNode(ISD::SUB, DL, VT, 12276 DAG.getConstant(0, DL, MVT::i32), Res); 12277 } else 12278 return SDValue(); 12279 } 12280 12281 if (ShiftAmt != 0) 12282 Res = DAG.getNode(ISD::SHL, DL, VT, 12283 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 12284 12285 // Do not add new nodes to DAG combiner worklist. 12286 DCI.CombineTo(N, Res, false); 12287 return SDValue(); 12288 } 12289 12290 static SDValue CombineANDShift(SDNode *N, 12291 TargetLowering::DAGCombinerInfo &DCI, 12292 const ARMSubtarget *Subtarget) { 12293 // Allow DAGCombine to pattern-match before we touch the canonical form. 12294 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12295 return SDValue(); 12296 12297 if (N->getValueType(0) != MVT::i32) 12298 return SDValue(); 12299 12300 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12301 if (!N1C) 12302 return SDValue(); 12303 12304 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 12305 // Don't transform uxtb/uxth. 12306 if (C1 == 255 || C1 == 65535) 12307 return SDValue(); 12308 12309 SDNode *N0 = N->getOperand(0).getNode(); 12310 if (!N0->hasOneUse()) 12311 return SDValue(); 12312 12313 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 12314 return SDValue(); 12315 12316 bool LeftShift = N0->getOpcode() == ISD::SHL; 12317 12318 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12319 if (!N01C) 12320 return SDValue(); 12321 12322 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 12323 if (!C2 || C2 >= 32) 12324 return SDValue(); 12325 12326 // Clear irrelevant bits in the mask. 12327 if (LeftShift) 12328 C1 &= (-1U << C2); 12329 else 12330 C1 &= (-1U >> C2); 12331 12332 SelectionDAG &DAG = DCI.DAG; 12333 SDLoc DL(N); 12334 12335 // We have a pattern of the form "(and (shl x, c2) c1)" or 12336 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 12337 // transform to a pair of shifts, to save materializing c1. 12338 12339 // First pattern: right shift, then mask off leading bits. 12340 // FIXME: Use demanded bits? 12341 if (!LeftShift && isMask_32(C1)) { 12342 uint32_t C3 = countLeadingZeros(C1); 12343 if (C2 < C3) { 12344 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12345 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12346 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12347 DAG.getConstant(C3, DL, MVT::i32)); 12348 } 12349 } 12350 12351 // First pattern, reversed: left shift, then mask off trailing bits. 12352 if (LeftShift && isMask_32(~C1)) { 12353 uint32_t C3 = countTrailingZeros(C1); 12354 if (C2 < C3) { 12355 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12356 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12357 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12358 DAG.getConstant(C3, DL, MVT::i32)); 12359 } 12360 } 12361 12362 // Second pattern: left shift, then mask off leading bits. 12363 // FIXME: Use demanded bits? 12364 if (LeftShift && isShiftedMask_32(C1)) { 12365 uint32_t Trailing = countTrailingZeros(C1); 12366 uint32_t C3 = countLeadingZeros(C1); 12367 if (Trailing == C2 && C2 + C3 < 32) { 12368 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12369 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12370 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12371 DAG.getConstant(C3, DL, MVT::i32)); 12372 } 12373 } 12374 12375 // Second pattern, reversed: right shift, then mask off trailing bits. 12376 // FIXME: Handle other patterns of known/demanded bits. 12377 if (!LeftShift && isShiftedMask_32(C1)) { 12378 uint32_t Leading = countLeadingZeros(C1); 12379 uint32_t C3 = countTrailingZeros(C1); 12380 if (Leading == C2 && C2 + C3 < 32) { 12381 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12382 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12383 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12384 DAG.getConstant(C3, DL, MVT::i32)); 12385 } 12386 } 12387 12388 // FIXME: Transform "(and (shl x, c2) c1)" -> 12389 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 12390 // c1. 12391 return SDValue(); 12392 } 12393 12394 static SDValue PerformANDCombine(SDNode *N, 12395 TargetLowering::DAGCombinerInfo &DCI, 12396 const ARMSubtarget *Subtarget) { 12397 // Attempt to use immediate-form VBIC 12398 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12399 SDLoc dl(N); 12400 EVT VT = N->getValueType(0); 12401 SelectionDAG &DAG = DCI.DAG; 12402 12403 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12404 return SDValue(); 12405 12406 APInt SplatBits, SplatUndef; 12407 unsigned SplatBitSize; 12408 bool HasAnyUndefs; 12409 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 12410 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12411 if (SplatBitSize <= 64) { 12412 EVT VbicVT; 12413 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 12414 SplatUndef.getZExtValue(), SplatBitSize, 12415 DAG, dl, VbicVT, VT, OtherModImm); 12416 if (Val.getNode()) { 12417 SDValue Input = 12418 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 12419 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 12420 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 12421 } 12422 } 12423 } 12424 12425 if (!Subtarget->isThumb1Only()) { 12426 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 12427 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 12428 return Result; 12429 12430 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12431 return Result; 12432 } 12433 12434 if (Subtarget->isThumb1Only()) 12435 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 12436 return Result; 12437 12438 return SDValue(); 12439 } 12440 12441 // Try combining OR nodes to SMULWB, SMULWT. 12442 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 12443 TargetLowering::DAGCombinerInfo &DCI, 12444 const ARMSubtarget *Subtarget) { 12445 if (!Subtarget->hasV6Ops() || 12446 (Subtarget->isThumb() && 12447 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 12448 return SDValue(); 12449 12450 SDValue SRL = OR->getOperand(0); 12451 SDValue SHL = OR->getOperand(1); 12452 12453 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 12454 SRL = OR->getOperand(1); 12455 SHL = OR->getOperand(0); 12456 } 12457 if (!isSRL16(SRL) || !isSHL16(SHL)) 12458 return SDValue(); 12459 12460 // The first operands to the shifts need to be the two results from the 12461 // same smul_lohi node. 12462 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 12463 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 12464 return SDValue(); 12465 12466 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 12467 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 12468 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 12469 return SDValue(); 12470 12471 // Now we have: 12472 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 12473 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 12474 // For SMUWB the 16-bit value will signed extended somehow. 12475 // For SMULWT only the SRA is required. 12476 // Check both sides of SMUL_LOHI 12477 SDValue OpS16 = SMULLOHI->getOperand(0); 12478 SDValue OpS32 = SMULLOHI->getOperand(1); 12479 12480 SelectionDAG &DAG = DCI.DAG; 12481 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 12482 OpS16 = OpS32; 12483 OpS32 = SMULLOHI->getOperand(0); 12484 } 12485 12486 SDLoc dl(OR); 12487 unsigned Opcode = 0; 12488 if (isS16(OpS16, DAG)) 12489 Opcode = ARMISD::SMULWB; 12490 else if (isSRA16(OpS16)) { 12491 Opcode = ARMISD::SMULWT; 12492 OpS16 = OpS16->getOperand(0); 12493 } 12494 else 12495 return SDValue(); 12496 12497 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 12498 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 12499 return SDValue(OR, 0); 12500 } 12501 12502 static SDValue PerformORCombineToBFI(SDNode *N, 12503 TargetLowering::DAGCombinerInfo &DCI, 12504 const ARMSubtarget *Subtarget) { 12505 // BFI is only available on V6T2+ 12506 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 12507 return SDValue(); 12508 12509 EVT VT = N->getValueType(0); 12510 SDValue N0 = N->getOperand(0); 12511 SDValue N1 = N->getOperand(1); 12512 SelectionDAG &DAG = DCI.DAG; 12513 SDLoc DL(N); 12514 // 1) or (and A, mask), val => ARMbfi A, val, mask 12515 // iff (val & mask) == val 12516 // 12517 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 12518 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 12519 // && mask == ~mask2 12520 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 12521 // && ~mask == mask2 12522 // (i.e., copy a bitfield value into another bitfield of the same width) 12523 12524 if (VT != MVT::i32) 12525 return SDValue(); 12526 12527 SDValue N00 = N0.getOperand(0); 12528 12529 // The value and the mask need to be constants so we can verify this is 12530 // actually a bitfield set. If the mask is 0xffff, we can do better 12531 // via a movt instruction, so don't use BFI in that case. 12532 SDValue MaskOp = N0.getOperand(1); 12533 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 12534 if (!MaskC) 12535 return SDValue(); 12536 unsigned Mask = MaskC->getZExtValue(); 12537 if (Mask == 0xffff) 12538 return SDValue(); 12539 SDValue Res; 12540 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 12541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 12542 if (N1C) { 12543 unsigned Val = N1C->getZExtValue(); 12544 if ((Val & ~Mask) != Val) 12545 return SDValue(); 12546 12547 if (ARM::isBitFieldInvertedMask(Mask)) { 12548 Val >>= countTrailingZeros(~Mask); 12549 12550 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 12551 DAG.getConstant(Val, DL, MVT::i32), 12552 DAG.getConstant(Mask, DL, MVT::i32)); 12553 12554 DCI.CombineTo(N, Res, false); 12555 // Return value from the original node to inform the combiner than N is 12556 // now dead. 12557 return SDValue(N, 0); 12558 } 12559 } else if (N1.getOpcode() == ISD::AND) { 12560 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 12561 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12562 if (!N11C) 12563 return SDValue(); 12564 unsigned Mask2 = N11C->getZExtValue(); 12565 12566 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 12567 // as is to match. 12568 if (ARM::isBitFieldInvertedMask(Mask) && 12569 (Mask == ~Mask2)) { 12570 // The pack halfword instruction works better for masks that fit it, 12571 // so use that when it's available. 12572 if (Subtarget->hasDSP() && 12573 (Mask == 0xffff || Mask == 0xffff0000)) 12574 return SDValue(); 12575 // 2a 12576 unsigned amt = countTrailingZeros(Mask2); 12577 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 12578 DAG.getConstant(amt, DL, MVT::i32)); 12579 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 12580 DAG.getConstant(Mask, DL, MVT::i32)); 12581 DCI.CombineTo(N, Res, false); 12582 // Return value from the original node to inform the combiner than N is 12583 // now dead. 12584 return SDValue(N, 0); 12585 } else if (ARM::isBitFieldInvertedMask(~Mask) && 12586 (~Mask == Mask2)) { 12587 // The pack halfword instruction works better for masks that fit it, 12588 // so use that when it's available. 12589 if (Subtarget->hasDSP() && 12590 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 12591 return SDValue(); 12592 // 2b 12593 unsigned lsb = countTrailingZeros(Mask); 12594 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 12595 DAG.getConstant(lsb, DL, MVT::i32)); 12596 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 12597 DAG.getConstant(Mask2, DL, MVT::i32)); 12598 DCI.CombineTo(N, Res, false); 12599 // Return value from the original node to inform the combiner than N is 12600 // now dead. 12601 return SDValue(N, 0); 12602 } 12603 } 12604 12605 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 12606 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 12607 ARM::isBitFieldInvertedMask(~Mask)) { 12608 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 12609 // where lsb(mask) == #shamt and masked bits of B are known zero. 12610 SDValue ShAmt = N00.getOperand(1); 12611 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 12612 unsigned LSB = countTrailingZeros(Mask); 12613 if (ShAmtC != LSB) 12614 return SDValue(); 12615 12616 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 12617 DAG.getConstant(~Mask, DL, MVT::i32)); 12618 12619 DCI.CombineTo(N, Res, false); 12620 // Return value from the original node to inform the combiner than N is 12621 // now dead. 12622 return SDValue(N, 0); 12623 } 12624 12625 return SDValue(); 12626 } 12627 12628 static bool isValidMVECond(unsigned CC, bool IsFloat) { 12629 switch (CC) { 12630 case ARMCC::EQ: 12631 case ARMCC::NE: 12632 case ARMCC::LE: 12633 case ARMCC::GT: 12634 case ARMCC::GE: 12635 case ARMCC::LT: 12636 return true; 12637 case ARMCC::HS: 12638 case ARMCC::HI: 12639 return !IsFloat; 12640 default: 12641 return false; 12642 }; 12643 } 12644 12645 static SDValue PerformORCombine_i1(SDNode *N, 12646 TargetLowering::DAGCombinerInfo &DCI, 12647 const ARMSubtarget *Subtarget) { 12648 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 12649 // together with predicates 12650 EVT VT = N->getValueType(0); 12651 SDValue N0 = N->getOperand(0); 12652 SDValue N1 = N->getOperand(1); 12653 12654 ARMCC::CondCodes CondCode0 = ARMCC::AL; 12655 ARMCC::CondCodes CondCode1 = ARMCC::AL; 12656 if (N0->getOpcode() == ARMISD::VCMP) 12657 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2)) 12658 ->getZExtValue(); 12659 else if (N0->getOpcode() == ARMISD::VCMPZ) 12660 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1)) 12661 ->getZExtValue(); 12662 if (N1->getOpcode() == ARMISD::VCMP) 12663 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2)) 12664 ->getZExtValue(); 12665 else if (N1->getOpcode() == ARMISD::VCMPZ) 12666 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1)) 12667 ->getZExtValue(); 12668 12669 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL) 12670 return SDValue(); 12671 12672 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0); 12673 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1); 12674 12675 if (!isValidMVECond(Opposite0, 12676 N0->getOperand(0)->getValueType(0).isFloatingPoint()) || 12677 !isValidMVECond(Opposite1, 12678 N1->getOperand(0)->getValueType(0).isFloatingPoint())) 12679 return SDValue(); 12680 12681 SmallVector<SDValue, 4> Ops0; 12682 Ops0.push_back(N0->getOperand(0)); 12683 if (N0->getOpcode() == ARMISD::VCMP) 12684 Ops0.push_back(N0->getOperand(1)); 12685 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32)); 12686 SmallVector<SDValue, 4> Ops1; 12687 Ops1.push_back(N1->getOperand(0)); 12688 if (N1->getOpcode() == ARMISD::VCMP) 12689 Ops1.push_back(N1->getOperand(1)); 12690 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32)); 12691 12692 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0); 12693 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1); 12694 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1); 12695 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And, 12696 DCI.DAG.getAllOnesConstant(SDLoc(N), VT)); 12697 } 12698 12699 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 12700 static SDValue PerformORCombine(SDNode *N, 12701 TargetLowering::DAGCombinerInfo &DCI, 12702 const ARMSubtarget *Subtarget) { 12703 // Attempt to use immediate-form VORR 12704 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12705 SDLoc dl(N); 12706 EVT VT = N->getValueType(0); 12707 SelectionDAG &DAG = DCI.DAG; 12708 12709 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12710 return SDValue(); 12711 12712 APInt SplatBits, SplatUndef; 12713 unsigned SplatBitSize; 12714 bool HasAnyUndefs; 12715 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 12716 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12717 if (SplatBitSize <= 64) { 12718 EVT VorrVT; 12719 SDValue Val = 12720 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 12721 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm); 12722 if (Val.getNode()) { 12723 SDValue Input = 12724 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 12725 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 12726 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 12727 } 12728 } 12729 } 12730 12731 if (!Subtarget->isThumb1Only()) { 12732 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 12733 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12734 return Result; 12735 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 12736 return Result; 12737 } 12738 12739 SDValue N0 = N->getOperand(0); 12740 SDValue N1 = N->getOperand(1); 12741 12742 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 12743 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 12744 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 12745 12746 // The code below optimizes (or (and X, Y), Z). 12747 // The AND operand needs to have a single user to make these optimizations 12748 // profitable. 12749 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 12750 return SDValue(); 12751 12752 APInt SplatUndef; 12753 unsigned SplatBitSize; 12754 bool HasAnyUndefs; 12755 12756 APInt SplatBits0, SplatBits1; 12757 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 12758 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 12759 // Ensure that the second operand of both ands are constants 12760 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 12761 HasAnyUndefs) && !HasAnyUndefs) { 12762 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 12763 HasAnyUndefs) && !HasAnyUndefs) { 12764 // Ensure that the bit width of the constants are the same and that 12765 // the splat arguments are logical inverses as per the pattern we 12766 // are trying to simplify. 12767 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 12768 SplatBits0 == ~SplatBits1) { 12769 // Canonicalize the vector type to make instruction selection 12770 // simpler. 12771 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 12772 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 12773 N0->getOperand(1), 12774 N0->getOperand(0), 12775 N1->getOperand(0)); 12776 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 12777 } 12778 } 12779 } 12780 } 12781 12782 if (Subtarget->hasMVEIntegerOps() && 12783 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 12784 return PerformORCombine_i1(N, DCI, Subtarget); 12785 12786 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 12787 // reasonable. 12788 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 12789 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 12790 return Res; 12791 } 12792 12793 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12794 return Result; 12795 12796 return SDValue(); 12797 } 12798 12799 static SDValue PerformXORCombine(SDNode *N, 12800 TargetLowering::DAGCombinerInfo &DCI, 12801 const ARMSubtarget *Subtarget) { 12802 EVT VT = N->getValueType(0); 12803 SelectionDAG &DAG = DCI.DAG; 12804 12805 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12806 return SDValue(); 12807 12808 if (!Subtarget->isThumb1Only()) { 12809 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 12810 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12811 return Result; 12812 12813 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12814 return Result; 12815 } 12816 12817 return SDValue(); 12818 } 12819 12820 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 12821 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 12822 // their position in "to" (Rd). 12823 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 12824 assert(N->getOpcode() == ARMISD::BFI); 12825 12826 SDValue From = N->getOperand(1); 12827 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 12828 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 12829 12830 // If the Base came from a SHR #C, we can deduce that it is really testing bit 12831 // #C in the base of the SHR. 12832 if (From->getOpcode() == ISD::SRL && 12833 isa<ConstantSDNode>(From->getOperand(1))) { 12834 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 12835 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 12836 FromMask <<= Shift.getLimitedValue(31); 12837 From = From->getOperand(0); 12838 } 12839 12840 return From; 12841 } 12842 12843 // If A and B contain one contiguous set of bits, does A | B == A . B? 12844 // 12845 // Neither A nor B must be zero. 12846 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 12847 unsigned LastActiveBitInA = A.countTrailingZeros(); 12848 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 12849 return LastActiveBitInA - 1 == FirstActiveBitInB; 12850 } 12851 12852 static SDValue FindBFIToCombineWith(SDNode *N) { 12853 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 12854 // if one exists. 12855 APInt ToMask, FromMask; 12856 SDValue From = ParseBFI(N, ToMask, FromMask); 12857 SDValue To = N->getOperand(0); 12858 12859 // Now check for a compatible BFI to merge with. We can pass through BFIs that 12860 // aren't compatible, but not if they set the same bit in their destination as 12861 // we do (or that of any BFI we're going to combine with). 12862 SDValue V = To; 12863 APInt CombinedToMask = ToMask; 12864 while (V.getOpcode() == ARMISD::BFI) { 12865 APInt NewToMask, NewFromMask; 12866 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 12867 if (NewFrom != From) { 12868 // This BFI has a different base. Keep going. 12869 CombinedToMask |= NewToMask; 12870 V = V.getOperand(0); 12871 continue; 12872 } 12873 12874 // Do the written bits conflict with any we've seen so far? 12875 if ((NewToMask & CombinedToMask).getBoolValue()) 12876 // Conflicting bits - bail out because going further is unsafe. 12877 return SDValue(); 12878 12879 // Are the new bits contiguous when combined with the old bits? 12880 if (BitsProperlyConcatenate(ToMask, NewToMask) && 12881 BitsProperlyConcatenate(FromMask, NewFromMask)) 12882 return V; 12883 if (BitsProperlyConcatenate(NewToMask, ToMask) && 12884 BitsProperlyConcatenate(NewFromMask, FromMask)) 12885 return V; 12886 12887 // We've seen a write to some bits, so track it. 12888 CombinedToMask |= NewToMask; 12889 // Keep going... 12890 V = V.getOperand(0); 12891 } 12892 12893 return SDValue(); 12894 } 12895 12896 static SDValue PerformBFICombine(SDNode *N, 12897 TargetLowering::DAGCombinerInfo &DCI) { 12898 SDValue N1 = N->getOperand(1); 12899 if (N1.getOpcode() == ISD::AND) { 12900 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 12901 // the bits being cleared by the AND are not demanded by the BFI. 12902 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12903 if (!N11C) 12904 return SDValue(); 12905 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12906 unsigned LSB = countTrailingZeros(~InvMask); 12907 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 12908 assert(Width < 12909 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 12910 "undefined behavior"); 12911 unsigned Mask = (1u << Width) - 1; 12912 unsigned Mask2 = N11C->getZExtValue(); 12913 if ((Mask & (~Mask2)) == 0) 12914 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 12915 N->getOperand(0), N1.getOperand(0), 12916 N->getOperand(2)); 12917 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 12918 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 12919 // Keep track of any consecutive bits set that all come from the same base 12920 // value. We can combine these together into a single BFI. 12921 SDValue CombineBFI = FindBFIToCombineWith(N); 12922 if (CombineBFI == SDValue()) 12923 return SDValue(); 12924 12925 // We've found a BFI. 12926 APInt ToMask1, FromMask1; 12927 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 12928 12929 APInt ToMask2, FromMask2; 12930 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 12931 assert(From1 == From2); 12932 (void)From2; 12933 12934 // First, unlink CombineBFI. 12935 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 12936 // Then create a new BFI, combining the two together. 12937 APInt NewFromMask = FromMask1 | FromMask2; 12938 APInt NewToMask = ToMask1 | ToMask2; 12939 12940 EVT VT = N->getValueType(0); 12941 SDLoc dl(N); 12942 12943 if (NewFromMask[0] == 0) 12944 From1 = DCI.DAG.getNode( 12945 ISD::SRL, dl, VT, From1, 12946 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 12947 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 12948 DCI.DAG.getConstant(~NewToMask, dl, VT)); 12949 } 12950 return SDValue(); 12951 } 12952 12953 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 12954 /// ARMISD::VMOVRRD. 12955 static SDValue PerformVMOVRRDCombine(SDNode *N, 12956 TargetLowering::DAGCombinerInfo &DCI, 12957 const ARMSubtarget *Subtarget) { 12958 // vmovrrd(vmovdrr x, y) -> x,y 12959 SDValue InDouble = N->getOperand(0); 12960 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 12961 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 12962 12963 // vmovrrd(load f64) -> (load i32), (load i32) 12964 SDNode *InNode = InDouble.getNode(); 12965 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 12966 InNode->getValueType(0) == MVT::f64 && 12967 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 12968 !cast<LoadSDNode>(InNode)->isVolatile()) { 12969 // TODO: Should this be done for non-FrameIndex operands? 12970 LoadSDNode *LD = cast<LoadSDNode>(InNode); 12971 12972 SelectionDAG &DAG = DCI.DAG; 12973 SDLoc DL(LD); 12974 SDValue BasePtr = LD->getBasePtr(); 12975 SDValue NewLD1 = 12976 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 12977 LD->getAlignment(), LD->getMemOperand()->getFlags()); 12978 12979 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12980 DAG.getConstant(4, DL, MVT::i32)); 12981 12982 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 12983 LD->getPointerInfo().getWithOffset(4), 12984 std::min(4U, LD->getAlignment()), 12985 LD->getMemOperand()->getFlags()); 12986 12987 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 12988 if (DCI.DAG.getDataLayout().isBigEndian()) 12989 std::swap (NewLD1, NewLD2); 12990 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 12991 return Result; 12992 } 12993 12994 return SDValue(); 12995 } 12996 12997 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 12998 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 12999 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 13000 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 13001 SDValue Op0 = N->getOperand(0); 13002 SDValue Op1 = N->getOperand(1); 13003 if (Op0.getOpcode() == ISD::BITCAST) 13004 Op0 = Op0.getOperand(0); 13005 if (Op1.getOpcode() == ISD::BITCAST) 13006 Op1 = Op1.getOperand(0); 13007 if (Op0.getOpcode() == ARMISD::VMOVRRD && 13008 Op0.getNode() == Op1.getNode() && 13009 Op0.getResNo() == 0 && Op1.getResNo() == 1) 13010 return DAG.getNode(ISD::BITCAST, SDLoc(N), 13011 N->getValueType(0), Op0.getOperand(0)); 13012 return SDValue(); 13013 } 13014 13015 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13016 // FullFP16: half values are passed in S-registers, and we don't 13017 // need any of the bitcast and moves: 13018 // 13019 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 13020 // t5: i32 = bitcast t2 13021 // t18: f16 = ARMISD::VMOVhr t5 13022 SDValue BC = N->getOperand(0); 13023 if (BC->getOpcode() != ISD::BITCAST) 13024 return SDValue(); 13025 SDValue Copy = BC->getOperand(0); 13026 if (Copy.getValueType() != MVT::f32 || Copy->getOpcode() != ISD::CopyFromReg) 13027 return SDValue(); 13028 13029 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)}; 13030 SDValue NewCopy = DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), MVT::f16, Ops); 13031 return NewCopy; 13032 } 13033 13034 static SDValue PerformVMOVrhCombine(SDNode *N, 13035 TargetLowering::DAGCombinerInfo &DCI) { 13036 SDValue N0 = N->getOperand(0); 13037 EVT VT = N->getValueType(0); 13038 13039 // fold (VMOVrh (load x)) -> (zextload (i16*)x) 13040 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) { 13041 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 13042 13043 SDValue Load = 13044 DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(), 13045 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand()); 13046 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13047 DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 13048 return Load; 13049 } 13050 13051 return SDValue(); 13052 } 13053 13054 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 13055 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 13056 /// i64 vector to have f64 elements, since the value can then be loaded 13057 /// directly into a VFP register. 13058 static bool hasNormalLoadOperand(SDNode *N) { 13059 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 13060 for (unsigned i = 0; i < NumElts; ++i) { 13061 SDNode *Elt = N->getOperand(i).getNode(); 13062 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 13063 return true; 13064 } 13065 return false; 13066 } 13067 13068 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 13069 /// ISD::BUILD_VECTOR. 13070 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 13071 TargetLowering::DAGCombinerInfo &DCI, 13072 const ARMSubtarget *Subtarget) { 13073 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 13074 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 13075 // into a pair of GPRs, which is fine when the value is used as a scalar, 13076 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 13077 SelectionDAG &DAG = DCI.DAG; 13078 if (N->getNumOperands() == 2) 13079 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 13080 return RV; 13081 13082 // Load i64 elements as f64 values so that type legalization does not split 13083 // them up into i32 values. 13084 EVT VT = N->getValueType(0); 13085 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 13086 return SDValue(); 13087 SDLoc dl(N); 13088 SmallVector<SDValue, 8> Ops; 13089 unsigned NumElts = VT.getVectorNumElements(); 13090 for (unsigned i = 0; i < NumElts; ++i) { 13091 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 13092 Ops.push_back(V); 13093 // Make the DAGCombiner fold the bitcast. 13094 DCI.AddToWorklist(V.getNode()); 13095 } 13096 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 13097 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 13098 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 13099 } 13100 13101 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 13102 static SDValue 13103 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13104 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 13105 // At that time, we may have inserted bitcasts from integer to float. 13106 // If these bitcasts have survived DAGCombine, change the lowering of this 13107 // BUILD_VECTOR in something more vector friendly, i.e., that does not 13108 // force to use floating point types. 13109 13110 // Make sure we can change the type of the vector. 13111 // This is possible iff: 13112 // 1. The vector is only used in a bitcast to a integer type. I.e., 13113 // 1.1. Vector is used only once. 13114 // 1.2. Use is a bit convert to an integer type. 13115 // 2. The size of its operands are 32-bits (64-bits are not legal). 13116 EVT VT = N->getValueType(0); 13117 EVT EltVT = VT.getVectorElementType(); 13118 13119 // Check 1.1. and 2. 13120 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 13121 return SDValue(); 13122 13123 // By construction, the input type must be float. 13124 assert(EltVT == MVT::f32 && "Unexpected type!"); 13125 13126 // Check 1.2. 13127 SDNode *Use = *N->use_begin(); 13128 if (Use->getOpcode() != ISD::BITCAST || 13129 Use->getValueType(0).isFloatingPoint()) 13130 return SDValue(); 13131 13132 // Check profitability. 13133 // Model is, if more than half of the relevant operands are bitcast from 13134 // i32, turn the build_vector into a sequence of insert_vector_elt. 13135 // Relevant operands are everything that is not statically 13136 // (i.e., at compile time) bitcasted. 13137 unsigned NumOfBitCastedElts = 0; 13138 unsigned NumElts = VT.getVectorNumElements(); 13139 unsigned NumOfRelevantElts = NumElts; 13140 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 13141 SDValue Elt = N->getOperand(Idx); 13142 if (Elt->getOpcode() == ISD::BITCAST) { 13143 // Assume only bit cast to i32 will go away. 13144 if (Elt->getOperand(0).getValueType() == MVT::i32) 13145 ++NumOfBitCastedElts; 13146 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 13147 // Constants are statically casted, thus do not count them as 13148 // relevant operands. 13149 --NumOfRelevantElts; 13150 } 13151 13152 // Check if more than half of the elements require a non-free bitcast. 13153 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 13154 return SDValue(); 13155 13156 SelectionDAG &DAG = DCI.DAG; 13157 // Create the new vector type. 13158 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 13159 // Check if the type is legal. 13160 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13161 if (!TLI.isTypeLegal(VecVT)) 13162 return SDValue(); 13163 13164 // Combine: 13165 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 13166 // => BITCAST INSERT_VECTOR_ELT 13167 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 13168 // (BITCAST EN), N. 13169 SDValue Vec = DAG.getUNDEF(VecVT); 13170 SDLoc dl(N); 13171 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 13172 SDValue V = N->getOperand(Idx); 13173 if (V.isUndef()) 13174 continue; 13175 if (V.getOpcode() == ISD::BITCAST && 13176 V->getOperand(0).getValueType() == MVT::i32) 13177 // Fold obvious case. 13178 V = V.getOperand(0); 13179 else { 13180 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 13181 // Make the DAGCombiner fold the bitcasts. 13182 DCI.AddToWorklist(V.getNode()); 13183 } 13184 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 13185 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 13186 } 13187 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 13188 // Make the DAGCombiner fold the bitcasts. 13189 DCI.AddToWorklist(Vec.getNode()); 13190 return Vec; 13191 } 13192 13193 static SDValue 13194 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13195 EVT VT = N->getValueType(0); 13196 SDValue Op = N->getOperand(0); 13197 SDLoc dl(N); 13198 13199 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x) 13200 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) { 13201 // If the valuetypes are the same, we can remove the cast entirely. 13202 if (Op->getOperand(0).getValueType() == VT) 13203 return Op->getOperand(0); 13204 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, 13205 Op->getOperand(0).getValueType(), Op->getOperand(0)); 13206 } 13207 13208 return SDValue(); 13209 } 13210 13211 static SDValue 13212 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 13213 const ARMSubtarget *ST) { 13214 EVT VT = N->getValueType(0); 13215 SDValue Op = N->getOperand(0); 13216 SDLoc dl(N); 13217 13218 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST 13219 if (ST->isLittle()) 13220 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op); 13221 13222 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x) 13223 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) { 13224 // If the valuetypes are the same, we can remove the cast entirely. 13225 if (Op->getOperand(0).getValueType() == VT) 13226 return Op->getOperand(0); 13227 return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0)); 13228 } 13229 13230 return SDValue(); 13231 } 13232 13233 static SDValue PerformVCMPCombine(SDNode *N, 13234 TargetLowering::DAGCombinerInfo &DCI, 13235 const ARMSubtarget *Subtarget) { 13236 if (!Subtarget->hasMVEIntegerOps()) 13237 return SDValue(); 13238 13239 EVT VT = N->getValueType(0); 13240 SDValue Op0 = N->getOperand(0); 13241 SDValue Op1 = N->getOperand(1); 13242 ARMCC::CondCodes Cond = 13243 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13244 SDLoc dl(N); 13245 13246 // vcmp X, 0, cc -> vcmpz X, cc 13247 if (isZeroVector(Op1)) 13248 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, 13249 N->getOperand(2)); 13250 13251 unsigned SwappedCond = getSwappedCondition(Cond); 13252 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) { 13253 // vcmp 0, X, cc -> vcmpz X, reversed(cc) 13254 if (isZeroVector(Op0)) 13255 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1, 13256 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13257 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc) 13258 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP) 13259 return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0, 13260 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13261 } 13262 13263 return SDValue(); 13264 } 13265 13266 /// PerformInsertEltCombine - Target-specific dag combine xforms for 13267 /// ISD::INSERT_VECTOR_ELT. 13268 static SDValue PerformInsertEltCombine(SDNode *N, 13269 TargetLowering::DAGCombinerInfo &DCI) { 13270 // Bitcast an i64 load inserted into a vector to f64. 13271 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13272 EVT VT = N->getValueType(0); 13273 SDNode *Elt = N->getOperand(1).getNode(); 13274 if (VT.getVectorElementType() != MVT::i64 || 13275 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 13276 return SDValue(); 13277 13278 SelectionDAG &DAG = DCI.DAG; 13279 SDLoc dl(N); 13280 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13281 VT.getVectorNumElements()); 13282 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 13283 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 13284 // Make the DAGCombiner fold the bitcasts. 13285 DCI.AddToWorklist(Vec.getNode()); 13286 DCI.AddToWorklist(V.getNode()); 13287 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 13288 Vec, V, N->getOperand(2)); 13289 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 13290 } 13291 13292 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 13293 /// ISD::VECTOR_SHUFFLE. 13294 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 13295 // The LLVM shufflevector instruction does not require the shuffle mask 13296 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 13297 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 13298 // operands do not match the mask length, they are extended by concatenating 13299 // them with undef vectors. That is probably the right thing for other 13300 // targets, but for NEON it is better to concatenate two double-register 13301 // size vector operands into a single quad-register size vector. Do that 13302 // transformation here: 13303 // shuffle(concat(v1, undef), concat(v2, undef)) -> 13304 // shuffle(concat(v1, v2), undef) 13305 SDValue Op0 = N->getOperand(0); 13306 SDValue Op1 = N->getOperand(1); 13307 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 13308 Op1.getOpcode() != ISD::CONCAT_VECTORS || 13309 Op0.getNumOperands() != 2 || 13310 Op1.getNumOperands() != 2) 13311 return SDValue(); 13312 SDValue Concat0Op1 = Op0.getOperand(1); 13313 SDValue Concat1Op1 = Op1.getOperand(1); 13314 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 13315 return SDValue(); 13316 // Skip the transformation if any of the types are illegal. 13317 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13318 EVT VT = N->getValueType(0); 13319 if (!TLI.isTypeLegal(VT) || 13320 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 13321 !TLI.isTypeLegal(Concat1Op1.getValueType())) 13322 return SDValue(); 13323 13324 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13325 Op0.getOperand(0), Op1.getOperand(0)); 13326 // Translate the shuffle mask. 13327 SmallVector<int, 16> NewMask; 13328 unsigned NumElts = VT.getVectorNumElements(); 13329 unsigned HalfElts = NumElts/2; 13330 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13331 for (unsigned n = 0; n < NumElts; ++n) { 13332 int MaskElt = SVN->getMaskElt(n); 13333 int NewElt = -1; 13334 if (MaskElt < (int)HalfElts) 13335 NewElt = MaskElt; 13336 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 13337 NewElt = HalfElts + MaskElt - NumElts; 13338 NewMask.push_back(NewElt); 13339 } 13340 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 13341 DAG.getUNDEF(VT), NewMask); 13342 } 13343 13344 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 13345 /// NEON load/store intrinsics, and generic vector load/stores, to merge 13346 /// base address updates. 13347 /// For generic load/stores, the memory type is assumed to be a vector. 13348 /// The caller is assumed to have checked legality. 13349 static SDValue CombineBaseUpdate(SDNode *N, 13350 TargetLowering::DAGCombinerInfo &DCI) { 13351 SelectionDAG &DAG = DCI.DAG; 13352 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 13353 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 13354 const bool isStore = N->getOpcode() == ISD::STORE; 13355 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 13356 SDValue Addr = N->getOperand(AddrOpIdx); 13357 MemSDNode *MemN = cast<MemSDNode>(N); 13358 SDLoc dl(N); 13359 13360 // Search for a use of the address operand that is an increment. 13361 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 13362 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 13363 SDNode *User = *UI; 13364 if (User->getOpcode() != ISD::ADD || 13365 UI.getUse().getResNo() != Addr.getResNo()) 13366 continue; 13367 13368 // Check that the add is independent of the load/store. Otherwise, folding 13369 // it would create a cycle. We can avoid searching through Addr as it's a 13370 // predecessor to both. 13371 SmallPtrSet<const SDNode *, 32> Visited; 13372 SmallVector<const SDNode *, 16> Worklist; 13373 Visited.insert(Addr.getNode()); 13374 Worklist.push_back(N); 13375 Worklist.push_back(User); 13376 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 13377 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 13378 continue; 13379 13380 // Find the new opcode for the updating load/store. 13381 bool isLoadOp = true; 13382 bool isLaneOp = false; 13383 unsigned NewOpc = 0; 13384 unsigned NumVecs = 0; 13385 if (isIntrinsic) { 13386 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 13387 switch (IntNo) { 13388 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 13389 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 13390 NumVecs = 1; break; 13391 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 13392 NumVecs = 2; break; 13393 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 13394 NumVecs = 3; break; 13395 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 13396 NumVecs = 4; break; 13397 case Intrinsic::arm_neon_vld2dup: 13398 case Intrinsic::arm_neon_vld3dup: 13399 case Intrinsic::arm_neon_vld4dup: 13400 // TODO: Support updating VLDxDUP nodes. For now, we just skip 13401 // combining base updates for such intrinsics. 13402 continue; 13403 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 13404 NumVecs = 2; isLaneOp = true; break; 13405 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 13406 NumVecs = 3; isLaneOp = true; break; 13407 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 13408 NumVecs = 4; isLaneOp = true; break; 13409 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 13410 NumVecs = 1; isLoadOp = false; break; 13411 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 13412 NumVecs = 2; isLoadOp = false; break; 13413 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 13414 NumVecs = 3; isLoadOp = false; break; 13415 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 13416 NumVecs = 4; isLoadOp = false; break; 13417 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 13418 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 13419 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 13420 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 13421 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 13422 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 13423 } 13424 } else { 13425 isLaneOp = true; 13426 switch (N->getOpcode()) { 13427 default: llvm_unreachable("unexpected opcode for Neon base update"); 13428 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 13429 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 13430 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 13431 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 13432 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 13433 NumVecs = 1; isLaneOp = false; break; 13434 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 13435 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 13436 } 13437 } 13438 13439 // Find the size of memory referenced by the load/store. 13440 EVT VecTy; 13441 if (isLoadOp) { 13442 VecTy = N->getValueType(0); 13443 } else if (isIntrinsic) { 13444 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 13445 } else { 13446 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 13447 VecTy = N->getOperand(1).getValueType(); 13448 } 13449 13450 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 13451 if (isLaneOp) 13452 NumBytes /= VecTy.getVectorNumElements(); 13453 13454 // If the increment is a constant, it must match the memory ref size. 13455 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 13456 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 13457 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 13458 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 13459 // separate instructions that make it harder to use a non-constant update. 13460 continue; 13461 } 13462 13463 // OK, we found an ADD we can fold into the base update. 13464 // Now, create a _UPD node, taking care of not breaking alignment. 13465 13466 EVT AlignedVecTy = VecTy; 13467 unsigned Alignment = MemN->getAlignment(); 13468 13469 // If this is a less-than-standard-aligned load/store, change the type to 13470 // match the standard alignment. 13471 // The alignment is overlooked when selecting _UPD variants; and it's 13472 // easier to introduce bitcasts here than fix that. 13473 // There are 3 ways to get to this base-update combine: 13474 // - intrinsics: they are assumed to be properly aligned (to the standard 13475 // alignment of the memory type), so we don't need to do anything. 13476 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 13477 // intrinsics, so, likewise, there's nothing to do. 13478 // - generic load/store instructions: the alignment is specified as an 13479 // explicit operand, rather than implicitly as the standard alignment 13480 // of the memory type (like the intrisics). We need to change the 13481 // memory type to match the explicit alignment. That way, we don't 13482 // generate non-standard-aligned ARMISD::VLDx nodes. 13483 if (isa<LSBaseSDNode>(N)) { 13484 if (Alignment == 0) 13485 Alignment = 1; 13486 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 13487 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 13488 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 13489 assert(!isLaneOp && "Unexpected generic load/store lane."); 13490 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 13491 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 13492 } 13493 // Don't set an explicit alignment on regular load/stores that we want 13494 // to transform to VLD/VST 1_UPD nodes. 13495 // This matches the behavior of regular load/stores, which only get an 13496 // explicit alignment if the MMO alignment is larger than the standard 13497 // alignment of the memory type. 13498 // Intrinsics, however, always get an explicit alignment, set to the 13499 // alignment of the MMO. 13500 Alignment = 1; 13501 } 13502 13503 // Create the new updating load/store node. 13504 // First, create an SDVTList for the new updating node's results. 13505 EVT Tys[6]; 13506 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 13507 unsigned n; 13508 for (n = 0; n < NumResultVecs; ++n) 13509 Tys[n] = AlignedVecTy; 13510 Tys[n++] = MVT::i32; 13511 Tys[n] = MVT::Other; 13512 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 13513 13514 // Then, gather the new node's operands. 13515 SmallVector<SDValue, 8> Ops; 13516 Ops.push_back(N->getOperand(0)); // incoming chain 13517 Ops.push_back(N->getOperand(AddrOpIdx)); 13518 Ops.push_back(Inc); 13519 13520 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 13521 // Try to match the intrinsic's signature 13522 Ops.push_back(StN->getValue()); 13523 } else { 13524 // Loads (and of course intrinsics) match the intrinsics' signature, 13525 // so just add all but the alignment operand. 13526 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 13527 Ops.push_back(N->getOperand(i)); 13528 } 13529 13530 // For all node types, the alignment operand is always the last one. 13531 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 13532 13533 // If this is a non-standard-aligned STORE, the penultimate operand is the 13534 // stored value. Bitcast it to the aligned type. 13535 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 13536 SDValue &StVal = Ops[Ops.size()-2]; 13537 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 13538 } 13539 13540 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 13541 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 13542 MemN->getMemOperand()); 13543 13544 // Update the uses. 13545 SmallVector<SDValue, 5> NewResults; 13546 for (unsigned i = 0; i < NumResultVecs; ++i) 13547 NewResults.push_back(SDValue(UpdN.getNode(), i)); 13548 13549 // If this is an non-standard-aligned LOAD, the first result is the loaded 13550 // value. Bitcast it to the expected result type. 13551 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 13552 SDValue &LdVal = NewResults[0]; 13553 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 13554 } 13555 13556 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 13557 DCI.CombineTo(N, NewResults); 13558 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 13559 13560 break; 13561 } 13562 return SDValue(); 13563 } 13564 13565 static SDValue PerformVLDCombine(SDNode *N, 13566 TargetLowering::DAGCombinerInfo &DCI) { 13567 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13568 return SDValue(); 13569 13570 return CombineBaseUpdate(N, DCI); 13571 } 13572 13573 static SDValue PerformMVEVLDCombine(SDNode *N, 13574 TargetLowering::DAGCombinerInfo &DCI) { 13575 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13576 return SDValue(); 13577 13578 SelectionDAG &DAG = DCI.DAG; 13579 SDValue Addr = N->getOperand(2); 13580 MemSDNode *MemN = cast<MemSDNode>(N); 13581 SDLoc dl(N); 13582 13583 // For the stores, where there are multiple intrinsics we only actually want 13584 // to post-inc the last of the them. 13585 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 13586 if (IntNo == Intrinsic::arm_mve_vst2q && 13587 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1) 13588 return SDValue(); 13589 if (IntNo == Intrinsic::arm_mve_vst4q && 13590 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3) 13591 return SDValue(); 13592 13593 // Search for a use of the address operand that is an increment. 13594 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 13595 UE = Addr.getNode()->use_end(); 13596 UI != UE; ++UI) { 13597 SDNode *User = *UI; 13598 if (User->getOpcode() != ISD::ADD || 13599 UI.getUse().getResNo() != Addr.getResNo()) 13600 continue; 13601 13602 // Check that the add is independent of the load/store. Otherwise, folding 13603 // it would create a cycle. We can avoid searching through Addr as it's a 13604 // predecessor to both. 13605 SmallPtrSet<const SDNode *, 32> Visited; 13606 SmallVector<const SDNode *, 16> Worklist; 13607 Visited.insert(Addr.getNode()); 13608 Worklist.push_back(N); 13609 Worklist.push_back(User); 13610 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 13611 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 13612 continue; 13613 13614 // Find the new opcode for the updating load/store. 13615 bool isLoadOp = true; 13616 unsigned NewOpc = 0; 13617 unsigned NumVecs = 0; 13618 switch (IntNo) { 13619 default: 13620 llvm_unreachable("unexpected intrinsic for MVE VLDn combine"); 13621 case Intrinsic::arm_mve_vld2q: 13622 NewOpc = ARMISD::VLD2_UPD; 13623 NumVecs = 2; 13624 break; 13625 case Intrinsic::arm_mve_vld4q: 13626 NewOpc = ARMISD::VLD4_UPD; 13627 NumVecs = 4; 13628 break; 13629 case Intrinsic::arm_mve_vst2q: 13630 NewOpc = ARMISD::VST2_UPD; 13631 NumVecs = 2; 13632 isLoadOp = false; 13633 break; 13634 case Intrinsic::arm_mve_vst4q: 13635 NewOpc = ARMISD::VST4_UPD; 13636 NumVecs = 4; 13637 isLoadOp = false; 13638 break; 13639 } 13640 13641 // Find the size of memory referenced by the load/store. 13642 EVT VecTy; 13643 if (isLoadOp) { 13644 VecTy = N->getValueType(0); 13645 } else { 13646 VecTy = N->getOperand(3).getValueType(); 13647 } 13648 13649 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 13650 13651 // If the increment is a constant, it must match the memory ref size. 13652 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 13653 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 13654 if (!CInc || CInc->getZExtValue() != NumBytes) 13655 continue; 13656 13657 // Create the new updating load/store node. 13658 // First, create an SDVTList for the new updating node's results. 13659 EVT Tys[6]; 13660 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 13661 unsigned n; 13662 for (n = 0; n < NumResultVecs; ++n) 13663 Tys[n] = VecTy; 13664 Tys[n++] = MVT::i32; 13665 Tys[n] = MVT::Other; 13666 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 13667 13668 // Then, gather the new node's operands. 13669 SmallVector<SDValue, 8> Ops; 13670 Ops.push_back(N->getOperand(0)); // incoming chain 13671 Ops.push_back(N->getOperand(2)); // ptr 13672 Ops.push_back(Inc); 13673 13674 for (unsigned i = 3; i < N->getNumOperands(); ++i) 13675 Ops.push_back(N->getOperand(i)); 13676 13677 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy, 13678 MemN->getMemOperand()); 13679 13680 // Update the uses. 13681 SmallVector<SDValue, 5> NewResults; 13682 for (unsigned i = 0; i < NumResultVecs; ++i) 13683 NewResults.push_back(SDValue(UpdN.getNode(), i)); 13684 13685 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain 13686 DCI.CombineTo(N, NewResults); 13687 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 13688 13689 break; 13690 } 13691 13692 return SDValue(); 13693 } 13694 13695 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 13696 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 13697 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 13698 /// return true. 13699 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13700 SelectionDAG &DAG = DCI.DAG; 13701 EVT VT = N->getValueType(0); 13702 // vldN-dup instructions only support 64-bit vectors for N > 1. 13703 if (!VT.is64BitVector()) 13704 return false; 13705 13706 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 13707 SDNode *VLD = N->getOperand(0).getNode(); 13708 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 13709 return false; 13710 unsigned NumVecs = 0; 13711 unsigned NewOpc = 0; 13712 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 13713 if (IntNo == Intrinsic::arm_neon_vld2lane) { 13714 NumVecs = 2; 13715 NewOpc = ARMISD::VLD2DUP; 13716 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 13717 NumVecs = 3; 13718 NewOpc = ARMISD::VLD3DUP; 13719 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 13720 NumVecs = 4; 13721 NewOpc = ARMISD::VLD4DUP; 13722 } else { 13723 return false; 13724 } 13725 13726 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 13727 // numbers match the load. 13728 unsigned VLDLaneNo = 13729 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 13730 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 13731 UI != UE; ++UI) { 13732 // Ignore uses of the chain result. 13733 if (UI.getUse().getResNo() == NumVecs) 13734 continue; 13735 SDNode *User = *UI; 13736 if (User->getOpcode() != ARMISD::VDUPLANE || 13737 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 13738 return false; 13739 } 13740 13741 // Create the vldN-dup node. 13742 EVT Tys[5]; 13743 unsigned n; 13744 for (n = 0; n < NumVecs; ++n) 13745 Tys[n] = VT; 13746 Tys[n] = MVT::Other; 13747 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 13748 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 13749 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 13750 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 13751 Ops, VLDMemInt->getMemoryVT(), 13752 VLDMemInt->getMemOperand()); 13753 13754 // Update the uses. 13755 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 13756 UI != UE; ++UI) { 13757 unsigned ResNo = UI.getUse().getResNo(); 13758 // Ignore uses of the chain result. 13759 if (ResNo == NumVecs) 13760 continue; 13761 SDNode *User = *UI; 13762 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 13763 } 13764 13765 // Now the vldN-lane intrinsic is dead except for its chain result. 13766 // Update uses of the chain. 13767 std::vector<SDValue> VLDDupResults; 13768 for (unsigned n = 0; n < NumVecs; ++n) 13769 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 13770 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 13771 DCI.CombineTo(VLD, VLDDupResults); 13772 13773 return true; 13774 } 13775 13776 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 13777 /// ARMISD::VDUPLANE. 13778 static SDValue PerformVDUPLANECombine(SDNode *N, 13779 TargetLowering::DAGCombinerInfo &DCI) { 13780 SDValue Op = N->getOperand(0); 13781 13782 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 13783 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 13784 if (CombineVLDDUP(N, DCI)) 13785 return SDValue(N, 0); 13786 13787 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 13788 // redundant. Ignore bit_converts for now; element sizes are checked below. 13789 while (Op.getOpcode() == ISD::BITCAST) 13790 Op = Op.getOperand(0); 13791 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 13792 return SDValue(); 13793 13794 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 13795 unsigned EltSize = Op.getScalarValueSizeInBits(); 13796 // The canonical VMOV for a zero vector uses a 32-bit element size. 13797 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13798 unsigned EltBits; 13799 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 13800 EltSize = 8; 13801 EVT VT = N->getValueType(0); 13802 if (EltSize > VT.getScalarSizeInBits()) 13803 return SDValue(); 13804 13805 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 13806 } 13807 13808 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 13809 static SDValue PerformVDUPCombine(SDNode *N, 13810 TargetLowering::DAGCombinerInfo &DCI, 13811 const ARMSubtarget *Subtarget) { 13812 SelectionDAG &DAG = DCI.DAG; 13813 SDValue Op = N->getOperand(0); 13814 SDLoc dl(N); 13815 13816 if (Subtarget->hasMVEIntegerOps()) { 13817 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will 13818 // need to come from a GPR. 13819 if (Op.getValueType() == MVT::f32) 13820 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 13821 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op)); 13822 else if (Op.getValueType() == MVT::f16) 13823 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 13824 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op)); 13825 } 13826 13827 if (!Subtarget->hasNEON()) 13828 return SDValue(); 13829 13830 // Match VDUP(LOAD) -> VLD1DUP. 13831 // We match this pattern here rather than waiting for isel because the 13832 // transform is only legal for unindexed loads. 13833 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 13834 if (LD && Op.hasOneUse() && LD->isUnindexed() && 13835 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 13836 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 13837 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 13838 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 13839 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 13840 Ops, LD->getMemoryVT(), 13841 LD->getMemOperand()); 13842 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 13843 return VLDDup; 13844 } 13845 13846 return SDValue(); 13847 } 13848 13849 static SDValue PerformLOADCombine(SDNode *N, 13850 TargetLowering::DAGCombinerInfo &DCI) { 13851 EVT VT = N->getValueType(0); 13852 13853 // If this is a legal vector load, try to combine it into a VLD1_UPD. 13854 if (ISD::isNormalLoad(N) && VT.isVector() && 13855 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13856 return CombineBaseUpdate(N, DCI); 13857 13858 return SDValue(); 13859 } 13860 13861 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 13862 // pack all of the elements in one place. Next, store to memory in fewer 13863 // chunks. 13864 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St, 13865 SelectionDAG &DAG) { 13866 SDValue StVal = St->getValue(); 13867 EVT VT = StVal.getValueType(); 13868 if (!St->isTruncatingStore() || !VT.isVector()) 13869 return SDValue(); 13870 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13871 EVT StVT = St->getMemoryVT(); 13872 unsigned NumElems = VT.getVectorNumElements(); 13873 assert(StVT != VT && "Cannot truncate to the same type"); 13874 unsigned FromEltSz = VT.getScalarSizeInBits(); 13875 unsigned ToEltSz = StVT.getScalarSizeInBits(); 13876 13877 // From, To sizes and ElemCount must be pow of two 13878 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) 13879 return SDValue(); 13880 13881 // We are going to use the original vector elt for storing. 13882 // Accumulated smaller vector elements must be a multiple of the store size. 13883 if (0 != (NumElems * FromEltSz) % ToEltSz) 13884 return SDValue(); 13885 13886 unsigned SizeRatio = FromEltSz / ToEltSz; 13887 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 13888 13889 // Create a type on which we perform the shuffle. 13890 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 13891 NumElems * SizeRatio); 13892 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 13893 13894 SDLoc DL(St); 13895 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 13896 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 13897 for (unsigned i = 0; i < NumElems; ++i) 13898 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1 13899 : i * SizeRatio; 13900 13901 // Can't shuffle using an illegal type. 13902 if (!TLI.isTypeLegal(WideVecVT)) 13903 return SDValue(); 13904 13905 SDValue Shuff = DAG.getVectorShuffle( 13906 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec); 13907 // At this point all of the data is stored at the bottom of the 13908 // register. We now need to save it to mem. 13909 13910 // Find the largest store unit 13911 MVT StoreType = MVT::i8; 13912 for (MVT Tp : MVT::integer_valuetypes()) { 13913 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 13914 StoreType = Tp; 13915 } 13916 // Didn't find a legal store type. 13917 if (!TLI.isTypeLegal(StoreType)) 13918 return SDValue(); 13919 13920 // Bitcast the original vector into a vector of store-size units 13921 EVT StoreVecVT = 13922 EVT::getVectorVT(*DAG.getContext(), StoreType, 13923 VT.getSizeInBits() / EVT(StoreType).getSizeInBits()); 13924 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 13925 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 13926 SmallVector<SDValue, 8> Chains; 13927 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 13928 TLI.getPointerTy(DAG.getDataLayout())); 13929 SDValue BasePtr = St->getBasePtr(); 13930 13931 // Perform one or more big stores into memory. 13932 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits(); 13933 for (unsigned I = 0; I < E; I++) { 13934 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType, 13935 ShuffWide, DAG.getIntPtrConstant(I, DL)); 13936 SDValue Ch = 13937 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(), 13938 St->getAlignment(), St->getMemOperand()->getFlags()); 13939 BasePtr = 13940 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment); 13941 Chains.push_back(Ch); 13942 } 13943 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 13944 } 13945 13946 // Try taking a single vector store from an truncate (which would otherwise turn 13947 // into an expensive buildvector) and splitting it into a series of narrowing 13948 // stores. 13949 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, 13950 SelectionDAG &DAG) { 13951 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed()) 13952 return SDValue(); 13953 SDValue Trunc = St->getValue(); 13954 if (Trunc->getOpcode() != ISD::TRUNCATE) 13955 return SDValue(); 13956 EVT FromVT = Trunc->getOperand(0).getValueType(); 13957 EVT ToVT = Trunc.getValueType(); 13958 if (!ToVT.isVector()) 13959 return SDValue(); 13960 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 13961 EVT ToEltVT = ToVT.getVectorElementType(); 13962 EVT FromEltVT = FromVT.getVectorElementType(); 13963 13964 unsigned NumElements = 0; 13965 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8)) 13966 NumElements = 4; 13967 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8) 13968 NumElements = 8; 13969 if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements || 13970 FromVT.getVectorNumElements() % NumElements != 0) 13971 return SDValue(); 13972 13973 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so 13974 // use the VMOVN over splitting the store. We are looking for patterns of: 13975 // !rev: 0 N 1 N+1 2 N+2 ... 13976 // rev: N 0 N+1 1 N+2 2 ... 13977 auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) { 13978 unsigned NumElts = ToVT.getVectorNumElements(); 13979 if (NumElts != M.size() || (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)) 13980 return false; 13981 13982 unsigned Off0 = rev ? NumElts : 0; 13983 unsigned Off1 = rev ? 0 : NumElts; 13984 13985 for (unsigned i = 0; i < NumElts; i += 2) { 13986 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2)) 13987 return false; 13988 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2)) 13989 return false; 13990 } 13991 13992 return true; 13993 }; 13994 13995 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0))) 13996 if (isVMOVNOriginalMask(Shuffle->getMask(), false) || 13997 isVMOVNOriginalMask(Shuffle->getMask(), true)) 13998 return SDValue(); 13999 14000 SDLoc DL(St); 14001 // Details about the old store 14002 SDValue Ch = St->getChain(); 14003 SDValue BasePtr = St->getBasePtr(); 14004 Align Alignment = St->getOriginalAlign(); 14005 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags(); 14006 AAMDNodes AAInfo = St->getAAInfo(); 14007 14008 EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements); 14009 EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements); 14010 14011 SmallVector<SDValue, 4> Stores; 14012 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 14013 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8; 14014 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset); 14015 14016 SDValue Extract = 14017 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0), 14018 DAG.getConstant(i * NumElements, DL, MVT::i32)); 14019 SDValue Store = DAG.getTruncStore( 14020 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset), 14021 NewToVT, Alignment.value(), MMOFlags, AAInfo); 14022 Stores.push_back(Store); 14023 } 14024 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores); 14025 } 14026 14027 /// PerformSTORECombine - Target-specific dag combine xforms for 14028 /// ISD::STORE. 14029 static SDValue PerformSTORECombine(SDNode *N, 14030 TargetLowering::DAGCombinerInfo &DCI, 14031 const ARMSubtarget *Subtarget) { 14032 StoreSDNode *St = cast<StoreSDNode>(N); 14033 if (St->isVolatile()) 14034 return SDValue(); 14035 SDValue StVal = St->getValue(); 14036 EVT VT = StVal.getValueType(); 14037 14038 if (Subtarget->hasNEON()) 14039 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG)) 14040 return Store; 14041 14042 if (Subtarget->hasMVEIntegerOps()) 14043 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG)) 14044 return NewToken; 14045 14046 if (!ISD::isNormalStore(St)) 14047 return SDValue(); 14048 14049 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 14050 // ARM stores of arguments in the same cache line. 14051 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 14052 StVal.getNode()->hasOneUse()) { 14053 SelectionDAG &DAG = DCI.DAG; 14054 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 14055 SDLoc DL(St); 14056 SDValue BasePtr = St->getBasePtr(); 14057 SDValue NewST1 = DAG.getStore( 14058 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 14059 BasePtr, St->getPointerInfo(), St->getAlignment(), 14060 St->getMemOperand()->getFlags()); 14061 14062 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 14063 DAG.getConstant(4, DL, MVT::i32)); 14064 return DAG.getStore(NewST1.getValue(0), DL, 14065 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 14066 OffsetPtr, St->getPointerInfo(), 14067 std::min(4U, St->getAlignment() / 2), 14068 St->getMemOperand()->getFlags()); 14069 } 14070 14071 if (StVal.getValueType() == MVT::i64 && 14072 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14073 14074 // Bitcast an i64 store extracted from a vector to f64. 14075 // Otherwise, the i64 value will be legalized to a pair of i32 values. 14076 SelectionDAG &DAG = DCI.DAG; 14077 SDLoc dl(StVal); 14078 SDValue IntVec = StVal.getOperand(0); 14079 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 14080 IntVec.getValueType().getVectorNumElements()); 14081 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 14082 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 14083 Vec, StVal.getOperand(1)); 14084 dl = SDLoc(N); 14085 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 14086 // Make the DAGCombiner fold the bitcasts. 14087 DCI.AddToWorklist(Vec.getNode()); 14088 DCI.AddToWorklist(ExtElt.getNode()); 14089 DCI.AddToWorklist(V.getNode()); 14090 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 14091 St->getPointerInfo(), St->getAlignment(), 14092 St->getMemOperand()->getFlags(), St->getAAInfo()); 14093 } 14094 14095 // If this is a legal vector store, try to combine it into a VST1_UPD. 14096 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() && 14097 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14098 return CombineBaseUpdate(N, DCI); 14099 14100 return SDValue(); 14101 } 14102 14103 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 14104 /// can replace combinations of VMUL and VCVT (floating-point to integer) 14105 /// when the VMUL has a constant operand that is a power of 2. 14106 /// 14107 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14108 /// vmul.f32 d16, d17, d16 14109 /// vcvt.s32.f32 d16, d16 14110 /// becomes: 14111 /// vcvt.s32.f32 d16, d16, #3 14112 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 14113 const ARMSubtarget *Subtarget) { 14114 if (!Subtarget->hasNEON()) 14115 return SDValue(); 14116 14117 SDValue Op = N->getOperand(0); 14118 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 14119 Op.getOpcode() != ISD::FMUL) 14120 return SDValue(); 14121 14122 SDValue ConstVec = Op->getOperand(1); 14123 if (!isa<BuildVectorSDNode>(ConstVec)) 14124 return SDValue(); 14125 14126 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 14127 uint32_t FloatBits = FloatTy.getSizeInBits(); 14128 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 14129 uint32_t IntBits = IntTy.getSizeInBits(); 14130 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14131 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14132 // These instructions only exist converting from f32 to i32. We can handle 14133 // smaller integers by generating an extra truncate, but larger ones would 14134 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14135 // these intructions only support v2i32/v4i32 types. 14136 return SDValue(); 14137 } 14138 14139 BitVector UndefElements; 14140 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14141 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14142 if (C == -1 || C == 0 || C > 32) 14143 return SDValue(); 14144 14145 SDLoc dl(N); 14146 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 14147 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 14148 Intrinsic::arm_neon_vcvtfp2fxu; 14149 SDValue FixConv = DAG.getNode( 14150 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14151 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 14152 DAG.getConstant(C, dl, MVT::i32)); 14153 14154 if (IntBits < FloatBits) 14155 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 14156 14157 return FixConv; 14158 } 14159 14160 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 14161 /// can replace combinations of VCVT (integer to floating-point) and VDIV 14162 /// when the VDIV has a constant operand that is a power of 2. 14163 /// 14164 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14165 /// vcvt.f32.s32 d16, d16 14166 /// vdiv.f32 d16, d17, d16 14167 /// becomes: 14168 /// vcvt.f32.s32 d16, d16, #3 14169 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 14170 const ARMSubtarget *Subtarget) { 14171 if (!Subtarget->hasNEON()) 14172 return SDValue(); 14173 14174 SDValue Op = N->getOperand(0); 14175 unsigned OpOpcode = Op.getNode()->getOpcode(); 14176 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 14177 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 14178 return SDValue(); 14179 14180 SDValue ConstVec = N->getOperand(1); 14181 if (!isa<BuildVectorSDNode>(ConstVec)) 14182 return SDValue(); 14183 14184 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 14185 uint32_t FloatBits = FloatTy.getSizeInBits(); 14186 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 14187 uint32_t IntBits = IntTy.getSizeInBits(); 14188 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14189 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14190 // These instructions only exist converting from i32 to f32. We can handle 14191 // smaller integers by generating an extra extend, but larger ones would 14192 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14193 // these intructions only support v2i32/v4i32 types. 14194 return SDValue(); 14195 } 14196 14197 BitVector UndefElements; 14198 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14199 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14200 if (C == -1 || C == 0 || C > 32) 14201 return SDValue(); 14202 14203 SDLoc dl(N); 14204 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 14205 SDValue ConvInput = Op.getOperand(0); 14206 if (IntBits < FloatBits) 14207 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 14208 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14209 ConvInput); 14210 14211 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 14212 Intrinsic::arm_neon_vcvtfxu2fp; 14213 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 14214 Op.getValueType(), 14215 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 14216 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 14217 } 14218 14219 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG, 14220 const ARMSubtarget *ST) { 14221 if (!ST->hasMVEIntegerOps()) 14222 return SDValue(); 14223 14224 assert(N->getOpcode() == ISD::VECREDUCE_ADD); 14225 EVT ResVT = N->getValueType(0); 14226 SDValue N0 = N->getOperand(0); 14227 SDLoc dl(N); 14228 14229 // We are looking for something that will have illegal types if left alone, 14230 // but that we can convert to a single instruction undef MVE. For example 14231 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A 14232 // or 14233 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B 14234 14235 // Cases: 14236 // VADDV u/s 8/16/32 14237 // VMLAV u/s 8/16/32 14238 // VADDLV u/s 32 14239 // VMLALV u/s 16/32 14240 14241 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) { 14242 if (ResVT != RetTy || N0->getOpcode() != ExtendCode) 14243 return SDValue(); 14244 SDValue A = N0->getOperand(0); 14245 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14246 return A; 14247 return SDValue(); 14248 }; 14249 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 14250 SDValue &A, SDValue &B) { 14251 if (ResVT != RetTy || N0->getOpcode() != ISD::MUL) 14252 return false; 14253 SDValue ExtA = N0->getOperand(0); 14254 SDValue ExtB = N0->getOperand(1); 14255 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 14256 return false; 14257 A = ExtA->getOperand(0); 14258 B = ExtB->getOperand(0); 14259 if (A.getValueType() == B.getValueType() && 14260 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14261 return true; 14262 return false; 14263 }; 14264 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) { 14265 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops); 14266 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node, 14267 SDValue(Node.getNode(), 1)); 14268 }; 14269 14270 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8})) 14271 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A); 14272 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8})) 14273 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A); 14274 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32})) 14275 return Create64bitNode(ARMISD::VADDLVs, {A}); 14276 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32})) 14277 return Create64bitNode(ARMISD::VADDLVu, {A}); 14278 14279 SDValue A, B; 14280 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 14281 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B); 14282 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 14283 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B); 14284 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 14285 return Create64bitNode(ARMISD::VMLALVs, {A, B}); 14286 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 14287 return Create64bitNode(ARMISD::VMLALVu, {A, B}); 14288 return SDValue(); 14289 } 14290 14291 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) { 14292 SDLoc DL(N); 14293 SDValue Op0 = N->getOperand(0); 14294 SDValue Op1 = N->getOperand(1); 14295 14296 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from 14297 // uses of the intrinsics. 14298 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 14299 int ShiftAmt = C->getSExtValue(); 14300 if (ShiftAmt == 0) { 14301 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL); 14302 DAG.ReplaceAllUsesWith(N, Merge.getNode()); 14303 return SDValue(); 14304 } 14305 14306 if (ShiftAmt >= -32 && ShiftAmt < 0) { 14307 unsigned NewOpcode = 14308 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL; 14309 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1, 14310 DAG.getConstant(-ShiftAmt, DL, MVT::i32)); 14311 DAG.ReplaceAllUsesWith(N, NewShift.getNode()); 14312 return NewShift; 14313 } 14314 } 14315 14316 return SDValue(); 14317 } 14318 14319 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 14320 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N, 14321 DAGCombinerInfo &DCI) const { 14322 SelectionDAG &DAG = DCI.DAG; 14323 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14324 switch (IntNo) { 14325 default: 14326 // Don't do anything for most intrinsics. 14327 break; 14328 14329 // Vector shifts: check for immediate versions and lower them. 14330 // Note: This is done during DAG combining instead of DAG legalizing because 14331 // the build_vectors for 64-bit vector element shift counts are generally 14332 // not legal, and it is hard to see their values after they get legalized to 14333 // loads from a constant pool. 14334 case Intrinsic::arm_neon_vshifts: 14335 case Intrinsic::arm_neon_vshiftu: 14336 case Intrinsic::arm_neon_vrshifts: 14337 case Intrinsic::arm_neon_vrshiftu: 14338 case Intrinsic::arm_neon_vrshiftn: 14339 case Intrinsic::arm_neon_vqshifts: 14340 case Intrinsic::arm_neon_vqshiftu: 14341 case Intrinsic::arm_neon_vqshiftsu: 14342 case Intrinsic::arm_neon_vqshiftns: 14343 case Intrinsic::arm_neon_vqshiftnu: 14344 case Intrinsic::arm_neon_vqshiftnsu: 14345 case Intrinsic::arm_neon_vqrshiftns: 14346 case Intrinsic::arm_neon_vqrshiftnu: 14347 case Intrinsic::arm_neon_vqrshiftnsu: { 14348 EVT VT = N->getOperand(1).getValueType(); 14349 int64_t Cnt; 14350 unsigned VShiftOpc = 0; 14351 14352 switch (IntNo) { 14353 case Intrinsic::arm_neon_vshifts: 14354 case Intrinsic::arm_neon_vshiftu: 14355 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 14356 VShiftOpc = ARMISD::VSHLIMM; 14357 break; 14358 } 14359 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 14360 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 14361 : ARMISD::VSHRuIMM); 14362 break; 14363 } 14364 return SDValue(); 14365 14366 case Intrinsic::arm_neon_vrshifts: 14367 case Intrinsic::arm_neon_vrshiftu: 14368 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 14369 break; 14370 return SDValue(); 14371 14372 case Intrinsic::arm_neon_vqshifts: 14373 case Intrinsic::arm_neon_vqshiftu: 14374 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 14375 break; 14376 return SDValue(); 14377 14378 case Intrinsic::arm_neon_vqshiftsu: 14379 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 14380 break; 14381 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 14382 14383 case Intrinsic::arm_neon_vrshiftn: 14384 case Intrinsic::arm_neon_vqshiftns: 14385 case Intrinsic::arm_neon_vqshiftnu: 14386 case Intrinsic::arm_neon_vqshiftnsu: 14387 case Intrinsic::arm_neon_vqrshiftns: 14388 case Intrinsic::arm_neon_vqrshiftnu: 14389 case Intrinsic::arm_neon_vqrshiftnsu: 14390 // Narrowing shifts require an immediate right shift. 14391 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 14392 break; 14393 llvm_unreachable("invalid shift count for narrowing vector shift " 14394 "intrinsic"); 14395 14396 default: 14397 llvm_unreachable("unhandled vector shift"); 14398 } 14399 14400 switch (IntNo) { 14401 case Intrinsic::arm_neon_vshifts: 14402 case Intrinsic::arm_neon_vshiftu: 14403 // Opcode already set above. 14404 break; 14405 case Intrinsic::arm_neon_vrshifts: 14406 VShiftOpc = ARMISD::VRSHRsIMM; 14407 break; 14408 case Intrinsic::arm_neon_vrshiftu: 14409 VShiftOpc = ARMISD::VRSHRuIMM; 14410 break; 14411 case Intrinsic::arm_neon_vrshiftn: 14412 VShiftOpc = ARMISD::VRSHRNIMM; 14413 break; 14414 case Intrinsic::arm_neon_vqshifts: 14415 VShiftOpc = ARMISD::VQSHLsIMM; 14416 break; 14417 case Intrinsic::arm_neon_vqshiftu: 14418 VShiftOpc = ARMISD::VQSHLuIMM; 14419 break; 14420 case Intrinsic::arm_neon_vqshiftsu: 14421 VShiftOpc = ARMISD::VQSHLsuIMM; 14422 break; 14423 case Intrinsic::arm_neon_vqshiftns: 14424 VShiftOpc = ARMISD::VQSHRNsIMM; 14425 break; 14426 case Intrinsic::arm_neon_vqshiftnu: 14427 VShiftOpc = ARMISD::VQSHRNuIMM; 14428 break; 14429 case Intrinsic::arm_neon_vqshiftnsu: 14430 VShiftOpc = ARMISD::VQSHRNsuIMM; 14431 break; 14432 case Intrinsic::arm_neon_vqrshiftns: 14433 VShiftOpc = ARMISD::VQRSHRNsIMM; 14434 break; 14435 case Intrinsic::arm_neon_vqrshiftnu: 14436 VShiftOpc = ARMISD::VQRSHRNuIMM; 14437 break; 14438 case Intrinsic::arm_neon_vqrshiftnsu: 14439 VShiftOpc = ARMISD::VQRSHRNsuIMM; 14440 break; 14441 } 14442 14443 SDLoc dl(N); 14444 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 14445 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 14446 } 14447 14448 case Intrinsic::arm_neon_vshiftins: { 14449 EVT VT = N->getOperand(1).getValueType(); 14450 int64_t Cnt; 14451 unsigned VShiftOpc = 0; 14452 14453 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 14454 VShiftOpc = ARMISD::VSLIIMM; 14455 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 14456 VShiftOpc = ARMISD::VSRIIMM; 14457 else { 14458 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 14459 } 14460 14461 SDLoc dl(N); 14462 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 14463 N->getOperand(1), N->getOperand(2), 14464 DAG.getConstant(Cnt, dl, MVT::i32)); 14465 } 14466 14467 case Intrinsic::arm_neon_vqrshifts: 14468 case Intrinsic::arm_neon_vqrshiftu: 14469 // No immediate versions of these to check for. 14470 break; 14471 14472 case Intrinsic::arm_mve_vqdmlah: 14473 case Intrinsic::arm_mve_vqdmlash: 14474 case Intrinsic::arm_mve_vqrdmlah: 14475 case Intrinsic::arm_mve_vqrdmlash: 14476 case Intrinsic::arm_mve_vmla_n_predicated: 14477 case Intrinsic::arm_mve_vmlas_n_predicated: 14478 case Intrinsic::arm_mve_vqdmlah_predicated: 14479 case Intrinsic::arm_mve_vqdmlash_predicated: 14480 case Intrinsic::arm_mve_vqrdmlah_predicated: 14481 case Intrinsic::arm_mve_vqrdmlash_predicated: { 14482 // These intrinsics all take an i32 scalar operand which is narrowed to the 14483 // size of a single lane of the vector type they return. So we don't need 14484 // any bits of that operand above that point, which allows us to eliminate 14485 // uxth/sxth. 14486 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits(); 14487 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 14488 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI)) 14489 return SDValue(); 14490 break; 14491 } 14492 14493 case Intrinsic::arm_mve_minv: 14494 case Intrinsic::arm_mve_maxv: 14495 case Intrinsic::arm_mve_minav: 14496 case Intrinsic::arm_mve_maxav: 14497 case Intrinsic::arm_mve_minv_predicated: 14498 case Intrinsic::arm_mve_maxv_predicated: 14499 case Intrinsic::arm_mve_minav_predicated: 14500 case Intrinsic::arm_mve_maxav_predicated: { 14501 // These intrinsics all take an i32 scalar operand which is narrowed to the 14502 // size of a single lane of the vector type they take as the other input. 14503 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits(); 14504 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 14505 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 14506 return SDValue(); 14507 break; 14508 } 14509 14510 case Intrinsic::arm_mve_addv: { 14511 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node, 14512 // which allow PerformADDVecReduce to turn it into VADDLV when possible. 14513 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 14514 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs; 14515 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1)); 14516 } 14517 14518 case Intrinsic::arm_mve_addlv: 14519 case Intrinsic::arm_mve_addlv_predicated: { 14520 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR 14521 // which recombines the two outputs into an i64 14522 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 14523 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ? 14524 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) : 14525 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps); 14526 14527 SmallVector<SDValue, 4> Ops; 14528 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++) 14529 if (i != 2) // skip the unsigned flag 14530 Ops.push_back(N->getOperand(i)); 14531 14532 SDLoc dl(N); 14533 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops); 14534 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0), 14535 val.getValue(1)); 14536 } 14537 } 14538 14539 return SDValue(); 14540 } 14541 14542 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 14543 /// lowers them. As with the vector shift intrinsics, this is done during DAG 14544 /// combining instead of DAG legalizing because the build_vectors for 64-bit 14545 /// vector element shift counts are generally not legal, and it is hard to see 14546 /// their values after they get legalized to loads from a constant pool. 14547 static SDValue PerformShiftCombine(SDNode *N, 14548 TargetLowering::DAGCombinerInfo &DCI, 14549 const ARMSubtarget *ST) { 14550 SelectionDAG &DAG = DCI.DAG; 14551 EVT VT = N->getValueType(0); 14552 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 14553 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 14554 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 14555 SDValue N1 = N->getOperand(1); 14556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 14557 SDValue N0 = N->getOperand(0); 14558 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 14559 DAG.MaskedValueIsZero(N0.getOperand(0), 14560 APInt::getHighBitsSet(32, 16))) 14561 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 14562 } 14563 } 14564 14565 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 14566 N->getOperand(0)->getOpcode() == ISD::AND && 14567 N->getOperand(0)->hasOneUse()) { 14568 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14569 return SDValue(); 14570 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 14571 // usually show up because instcombine prefers to canonicalize it to 14572 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 14573 // out of GEP lowering in some cases. 14574 SDValue N0 = N->getOperand(0); 14575 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14576 if (!ShiftAmtNode) 14577 return SDValue(); 14578 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 14579 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14580 if (!AndMaskNode) 14581 return SDValue(); 14582 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 14583 // Don't transform uxtb/uxth. 14584 if (AndMask == 255 || AndMask == 65535) 14585 return SDValue(); 14586 if (isMask_32(AndMask)) { 14587 uint32_t MaskedBits = countLeadingZeros(AndMask); 14588 if (MaskedBits > ShiftAmt) { 14589 SDLoc DL(N); 14590 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 14591 DAG.getConstant(MaskedBits, DL, MVT::i32)); 14592 return DAG.getNode( 14593 ISD::SRL, DL, MVT::i32, SHL, 14594 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 14595 } 14596 } 14597 } 14598 14599 // Nothing to be done for scalar shifts. 14600 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14601 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 14602 return SDValue(); 14603 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 14604 return SDValue(); 14605 14606 int64_t Cnt; 14607 14608 switch (N->getOpcode()) { 14609 default: llvm_unreachable("unexpected shift opcode"); 14610 14611 case ISD::SHL: 14612 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 14613 SDLoc dl(N); 14614 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 14615 DAG.getConstant(Cnt, dl, MVT::i32)); 14616 } 14617 break; 14618 14619 case ISD::SRA: 14620 case ISD::SRL: 14621 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 14622 unsigned VShiftOpc = 14623 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 14624 SDLoc dl(N); 14625 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 14626 DAG.getConstant(Cnt, dl, MVT::i32)); 14627 } 14628 } 14629 return SDValue(); 14630 } 14631 14632 // Look for a sign/zero extend of a larger than legal load. This can be split 14633 // into two extending loads, which are simpler to deal with than an arbitrary 14634 // sign extend. 14635 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) { 14636 SDValue N0 = N->getOperand(0); 14637 if (N0.getOpcode() != ISD::LOAD) 14638 return SDValue(); 14639 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode()); 14640 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() || 14641 LD->getExtensionType() != ISD::NON_EXTLOAD) 14642 return SDValue(); 14643 EVT FromVT = LD->getValueType(0); 14644 EVT ToVT = N->getValueType(0); 14645 if (!ToVT.isVector()) 14646 return SDValue(); 14647 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 14648 EVT ToEltVT = ToVT.getVectorElementType(); 14649 EVT FromEltVT = FromVT.getVectorElementType(); 14650 14651 unsigned NumElements = 0; 14652 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8)) 14653 NumElements = 4; 14654 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8) 14655 NumElements = 8; 14656 if (NumElements == 0 || 14657 FromVT.getVectorNumElements() == NumElements || 14658 FromVT.getVectorNumElements() % NumElements != 0 || 14659 !isPowerOf2_32(NumElements)) 14660 return SDValue(); 14661 14662 SDLoc DL(LD); 14663 // Details about the old load 14664 SDValue Ch = LD->getChain(); 14665 SDValue BasePtr = LD->getBasePtr(); 14666 Align Alignment = LD->getOriginalAlign(); 14667 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 14668 AAMDNodes AAInfo = LD->getAAInfo(); 14669 14670 ISD::LoadExtType NewExtType = 14671 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 14672 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType()); 14673 EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext()); 14674 EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext()); 14675 unsigned NewOffset = NewFromVT.getSizeInBits() / 8; 14676 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset); 14677 14678 // Split the load in half, each side of which is extended separately. This 14679 // is good enough, as legalisation will take it from there. They are either 14680 // already legal or they will be split further into something that is 14681 // legal. 14682 SDValue NewLoad1 = DAG.getLoad( 14683 ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset, 14684 LD->getPointerInfo(), NewFromVT, Alignment.value(), MMOFlags, AAInfo); 14685 SDValue NewLoad2 = 14686 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset, 14687 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT, 14688 Alignment.value(), MMOFlags, AAInfo); 14689 14690 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 14691 SDValue(NewLoad1.getNode(), 1), 14692 SDValue(NewLoad2.getNode(), 1)); 14693 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain); 14694 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2); 14695 } 14696 14697 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 14698 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 14699 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 14700 const ARMSubtarget *ST) { 14701 SDValue N0 = N->getOperand(0); 14702 14703 // Check for sign- and zero-extensions of vector extract operations of 8- and 14704 // 16-bit vector elements. NEON and MVE support these directly. They are 14705 // handled during DAG combining because type legalization will promote them 14706 // to 32-bit types and it is messy to recognize the operations after that. 14707 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) && 14708 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14709 SDValue Vec = N0.getOperand(0); 14710 SDValue Lane = N0.getOperand(1); 14711 EVT VT = N->getValueType(0); 14712 EVT EltVT = N0.getValueType(); 14713 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14714 14715 if (VT == MVT::i32 && 14716 (EltVT == MVT::i8 || EltVT == MVT::i16) && 14717 TLI.isTypeLegal(Vec.getValueType()) && 14718 isa<ConstantSDNode>(Lane)) { 14719 14720 unsigned Opc = 0; 14721 switch (N->getOpcode()) { 14722 default: llvm_unreachable("unexpected opcode"); 14723 case ISD::SIGN_EXTEND: 14724 Opc = ARMISD::VGETLANEs; 14725 break; 14726 case ISD::ZERO_EXTEND: 14727 case ISD::ANY_EXTEND: 14728 Opc = ARMISD::VGETLANEu; 14729 break; 14730 } 14731 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 14732 } 14733 } 14734 14735 if (ST->hasMVEIntegerOps()) 14736 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 14737 return NewLoad; 14738 14739 return SDValue(); 14740 } 14741 14742 static const APInt *isPowerOf2Constant(SDValue V) { 14743 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 14744 if (!C) 14745 return nullptr; 14746 const APInt *CV = &C->getAPIntValue(); 14747 return CV->isPowerOf2() ? CV : nullptr; 14748 } 14749 14750 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 14751 // If we have a CMOV, OR and AND combination such as: 14752 // if (x & CN) 14753 // y |= CM; 14754 // 14755 // And: 14756 // * CN is a single bit; 14757 // * All bits covered by CM are known zero in y 14758 // 14759 // Then we can convert this into a sequence of BFI instructions. This will 14760 // always be a win if CM is a single bit, will always be no worse than the 14761 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 14762 // three bits (due to the extra IT instruction). 14763 14764 SDValue Op0 = CMOV->getOperand(0); 14765 SDValue Op1 = CMOV->getOperand(1); 14766 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 14767 auto CC = CCNode->getAPIntValue().getLimitedValue(); 14768 SDValue CmpZ = CMOV->getOperand(4); 14769 14770 // The compare must be against zero. 14771 if (!isNullConstant(CmpZ->getOperand(1))) 14772 return SDValue(); 14773 14774 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 14775 SDValue And = CmpZ->getOperand(0); 14776 if (And->getOpcode() != ISD::AND) 14777 return SDValue(); 14778 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 14779 if (!AndC) 14780 return SDValue(); 14781 SDValue X = And->getOperand(0); 14782 14783 if (CC == ARMCC::EQ) { 14784 // We're performing an "equal to zero" compare. Swap the operands so we 14785 // canonicalize on a "not equal to zero" compare. 14786 std::swap(Op0, Op1); 14787 } else { 14788 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 14789 } 14790 14791 if (Op1->getOpcode() != ISD::OR) 14792 return SDValue(); 14793 14794 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 14795 if (!OrC) 14796 return SDValue(); 14797 SDValue Y = Op1->getOperand(0); 14798 14799 if (Op0 != Y) 14800 return SDValue(); 14801 14802 // Now, is it profitable to continue? 14803 APInt OrCI = OrC->getAPIntValue(); 14804 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 14805 if (OrCI.countPopulation() > Heuristic) 14806 return SDValue(); 14807 14808 // Lastly, can we determine that the bits defined by OrCI 14809 // are zero in Y? 14810 KnownBits Known = DAG.computeKnownBits(Y); 14811 if ((OrCI & Known.Zero) != OrCI) 14812 return SDValue(); 14813 14814 // OK, we can do the combine. 14815 SDValue V = Y; 14816 SDLoc dl(X); 14817 EVT VT = X.getValueType(); 14818 unsigned BitInX = AndC->logBase2(); 14819 14820 if (BitInX != 0) { 14821 // We must shift X first. 14822 X = DAG.getNode(ISD::SRL, dl, VT, X, 14823 DAG.getConstant(BitInX, dl, VT)); 14824 } 14825 14826 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 14827 BitInY < NumActiveBits; ++BitInY) { 14828 if (OrCI[BitInY] == 0) 14829 continue; 14830 APInt Mask(VT.getSizeInBits(), 0); 14831 Mask.setBit(BitInY); 14832 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 14833 // Confusingly, the operand is an *inverted* mask. 14834 DAG.getConstant(~Mask, dl, VT)); 14835 } 14836 14837 return V; 14838 } 14839 14840 // Given N, the value controlling the conditional branch, search for the loop 14841 // intrinsic, returning it, along with how the value is used. We need to handle 14842 // patterns such as the following: 14843 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 14844 // (brcond (setcc (loop.decrement), 0, eq), exit) 14845 // (brcond (setcc (loop.decrement), 0, ne), header) 14846 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 14847 bool &Negate) { 14848 switch (N->getOpcode()) { 14849 default: 14850 break; 14851 case ISD::XOR: { 14852 if (!isa<ConstantSDNode>(N.getOperand(1))) 14853 return SDValue(); 14854 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 14855 return SDValue(); 14856 Negate = !Negate; 14857 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 14858 } 14859 case ISD::SETCC: { 14860 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 14861 if (!Const) 14862 return SDValue(); 14863 if (Const->isNullValue()) 14864 Imm = 0; 14865 else if (Const->isOne()) 14866 Imm = 1; 14867 else 14868 return SDValue(); 14869 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 14870 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 14871 } 14872 case ISD::INTRINSIC_W_CHAIN: { 14873 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 14874 if (IntOp != Intrinsic::test_set_loop_iterations && 14875 IntOp != Intrinsic::loop_decrement_reg) 14876 return SDValue(); 14877 return N; 14878 } 14879 } 14880 return SDValue(); 14881 } 14882 14883 static SDValue PerformHWLoopCombine(SDNode *N, 14884 TargetLowering::DAGCombinerInfo &DCI, 14885 const ARMSubtarget *ST) { 14886 14887 // The hwloop intrinsics that we're interested are used for control-flow, 14888 // either for entering or exiting the loop: 14889 // - test.set.loop.iterations will test whether its operand is zero. If it 14890 // is zero, the proceeding branch should not enter the loop. 14891 // - loop.decrement.reg also tests whether its operand is zero. If it is 14892 // zero, the proceeding branch should not branch back to the beginning of 14893 // the loop. 14894 // So here, we need to check that how the brcond is using the result of each 14895 // of the intrinsics to ensure that we're branching to the right place at the 14896 // right time. 14897 14898 ISD::CondCode CC; 14899 SDValue Cond; 14900 int Imm = 1; 14901 bool Negate = false; 14902 SDValue Chain = N->getOperand(0); 14903 SDValue Dest; 14904 14905 if (N->getOpcode() == ISD::BRCOND) { 14906 CC = ISD::SETEQ; 14907 Cond = N->getOperand(1); 14908 Dest = N->getOperand(2); 14909 } else { 14910 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 14911 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14912 Cond = N->getOperand(2); 14913 Dest = N->getOperand(4); 14914 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 14915 if (!Const->isOne() && !Const->isNullValue()) 14916 return SDValue(); 14917 Imm = Const->getZExtValue(); 14918 } else 14919 return SDValue(); 14920 } 14921 14922 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 14923 if (!Int) 14924 return SDValue(); 14925 14926 if (Negate) 14927 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32); 14928 14929 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 14930 return (CC == ISD::SETEQ && Imm == 0) || 14931 (CC == ISD::SETNE && Imm == 1) || 14932 (CC == ISD::SETLT && Imm == 1) || 14933 (CC == ISD::SETULT && Imm == 1); 14934 }; 14935 14936 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 14937 return (CC == ISD::SETEQ && Imm == 1) || 14938 (CC == ISD::SETNE && Imm == 0) || 14939 (CC == ISD::SETGT && Imm == 0) || 14940 (CC == ISD::SETUGT && Imm == 0) || 14941 (CC == ISD::SETGE && Imm == 1) || 14942 (CC == ISD::SETUGE && Imm == 1); 14943 }; 14944 14945 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 14946 "unsupported condition"); 14947 14948 SDLoc dl(Int); 14949 SelectionDAG &DAG = DCI.DAG; 14950 SDValue Elements = Int.getOperand(2); 14951 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 14952 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 14953 && "expected single br user"); 14954 SDNode *Br = *N->use_begin(); 14955 SDValue OtherTarget = Br->getOperand(1); 14956 14957 // Update the unconditional branch to branch to the given Dest. 14958 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 14959 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 14960 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 14961 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 14962 }; 14963 14964 if (IntOp == Intrinsic::test_set_loop_iterations) { 14965 SDValue Res; 14966 // We expect this 'instruction' to branch when the counter is zero. 14967 if (IsTrueIfZero(CC, Imm)) { 14968 SDValue Ops[] = { Chain, Elements, Dest }; 14969 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 14970 } else { 14971 // The logic is the reverse of what we need for WLS, so find the other 14972 // basic block target: the target of the proceeding br. 14973 UpdateUncondBr(Br, Dest, DAG); 14974 14975 SDValue Ops[] = { Chain, Elements, OtherTarget }; 14976 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 14977 } 14978 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 14979 return Res; 14980 } else { 14981 SDValue Size = DAG.getTargetConstant( 14982 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 14983 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 14984 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 14985 DAG.getVTList(MVT::i32, MVT::Other), Args); 14986 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 14987 14988 // We expect this instruction to branch when the count is not zero. 14989 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 14990 14991 // Update the unconditional branch to target the loop preheader if we've 14992 // found the condition has been reversed. 14993 if (Target == OtherTarget) 14994 UpdateUncondBr(Br, Dest, DAG); 14995 14996 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14997 SDValue(LoopDec.getNode(), 1), Chain); 14998 14999 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 15000 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 15001 } 15002 return SDValue(); 15003 } 15004 15005 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 15006 SDValue 15007 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 15008 SDValue Cmp = N->getOperand(4); 15009 if (Cmp.getOpcode() != ARMISD::CMPZ) 15010 // Only looking at NE cases. 15011 return SDValue(); 15012 15013 EVT VT = N->getValueType(0); 15014 SDLoc dl(N); 15015 SDValue LHS = Cmp.getOperand(0); 15016 SDValue RHS = Cmp.getOperand(1); 15017 SDValue Chain = N->getOperand(0); 15018 SDValue BB = N->getOperand(1); 15019 SDValue ARMcc = N->getOperand(2); 15020 ARMCC::CondCodes CC = 15021 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 15022 15023 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 15024 // -> (brcond Chain BB CC CPSR Cmp) 15025 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 15026 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 15027 LHS->getOperand(0)->hasOneUse()) { 15028 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 15029 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 15030 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 15031 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 15032 if ((LHS00C && LHS00C->getZExtValue() == 0) && 15033 (LHS01C && LHS01C->getZExtValue() == 1) && 15034 (LHS1C && LHS1C->getZExtValue() == 1) && 15035 (RHSC && RHSC->getZExtValue() == 0)) { 15036 return DAG.getNode( 15037 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 15038 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 15039 } 15040 } 15041 15042 return SDValue(); 15043 } 15044 15045 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 15046 SDValue 15047 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 15048 SDValue Cmp = N->getOperand(4); 15049 if (Cmp.getOpcode() != ARMISD::CMPZ) 15050 // Only looking at EQ and NE cases. 15051 return SDValue(); 15052 15053 EVT VT = N->getValueType(0); 15054 SDLoc dl(N); 15055 SDValue LHS = Cmp.getOperand(0); 15056 SDValue RHS = Cmp.getOperand(1); 15057 SDValue FalseVal = N->getOperand(0); 15058 SDValue TrueVal = N->getOperand(1); 15059 SDValue ARMcc = N->getOperand(2); 15060 ARMCC::CondCodes CC = 15061 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 15062 15063 // BFI is only available on V6T2+. 15064 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 15065 SDValue R = PerformCMOVToBFICombine(N, DAG); 15066 if (R) 15067 return R; 15068 } 15069 15070 // Simplify 15071 // mov r1, r0 15072 // cmp r1, x 15073 // mov r0, y 15074 // moveq r0, x 15075 // to 15076 // cmp r0, x 15077 // movne r0, y 15078 // 15079 // mov r1, r0 15080 // cmp r1, x 15081 // mov r0, x 15082 // movne r0, y 15083 // to 15084 // cmp r0, x 15085 // movne r0, y 15086 /// FIXME: Turn this into a target neutral optimization? 15087 SDValue Res; 15088 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 15089 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 15090 N->getOperand(3), Cmp); 15091 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 15092 SDValue ARMcc; 15093 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 15094 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 15095 N->getOperand(3), NewCmp); 15096 } 15097 15098 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 15099 // -> (cmov F T CC CPSR Cmp) 15100 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 15101 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 15102 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 15103 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 15104 if ((LHS0C && LHS0C->getZExtValue() == 0) && 15105 (LHS1C && LHS1C->getZExtValue() == 1) && 15106 (RHSC && RHSC->getZExtValue() == 0)) { 15107 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 15108 LHS->getOperand(2), LHS->getOperand(3), 15109 LHS->getOperand(4)); 15110 } 15111 } 15112 15113 if (!VT.isInteger()) 15114 return SDValue(); 15115 15116 // Materialize a boolean comparison for integers so we can avoid branching. 15117 if (isNullConstant(FalseVal)) { 15118 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 15119 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 15120 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 15121 // right 5 bits will make that 32 be 1, otherwise it will be 0. 15122 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 15123 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 15124 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 15125 DAG.getConstant(5, dl, MVT::i32)); 15126 } else { 15127 // CMOV 0, 1, ==, (CMPZ x, y) -> 15128 // (ADDCARRY (SUB x, y), t:0, t:1) 15129 // where t = (SUBCARRY 0, (SUB x, y), 0) 15130 // 15131 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 15132 // x != y. In other words, a carry C == 1 when x == y, C == 0 15133 // otherwise. 15134 // The final ADDCARRY computes 15135 // x - y + (0 - (x - y)) + C == C 15136 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 15137 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 15138 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 15139 // ISD::SUBCARRY returns a borrow but we want the carry here 15140 // actually. 15141 SDValue Carry = 15142 DAG.getNode(ISD::SUB, dl, MVT::i32, 15143 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 15144 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 15145 } 15146 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 15147 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 15148 // This seems pointless but will allow us to combine it further below. 15149 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 15150 SDValue Sub = 15151 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 15152 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 15153 Sub.getValue(1), SDValue()); 15154 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 15155 N->getOperand(3), CPSRGlue.getValue(1)); 15156 FalseVal = Sub; 15157 } 15158 } else if (isNullConstant(TrueVal)) { 15159 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 15160 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 15161 // This seems pointless but will allow us to combine it further below 15162 // Note that we change == for != as this is the dual for the case above. 15163 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 15164 SDValue Sub = 15165 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 15166 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 15167 Sub.getValue(1), SDValue()); 15168 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 15169 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 15170 N->getOperand(3), CPSRGlue.getValue(1)); 15171 FalseVal = Sub; 15172 } 15173 } 15174 15175 // On Thumb1, the DAG above may be further combined if z is a power of 2 15176 // (z == 2 ^ K). 15177 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 15178 // t1 = (USUBO (SUB x, y), 1) 15179 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 15180 // Result = if K != 0 then (SHL t2:0, K) else t2:0 15181 // 15182 // This also handles the special case of comparing against zero; it's 15183 // essentially, the same pattern, except there's no SUBS: 15184 // CMOV x, z, !=, (CMPZ x, 0) -> 15185 // t1 = (USUBO x, 1) 15186 // t2 = (SUBCARRY x, t1:0, t1:1) 15187 // Result = if K != 0 then (SHL t2:0, K) else t2:0 15188 const APInt *TrueConst; 15189 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 15190 ((FalseVal.getOpcode() == ARMISD::SUBS && 15191 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 15192 (FalseVal == LHS && isNullConstant(RHS))) && 15193 (TrueConst = isPowerOf2Constant(TrueVal))) { 15194 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 15195 unsigned ShiftAmount = TrueConst->logBase2(); 15196 if (ShiftAmount) 15197 TrueVal = DAG.getConstant(1, dl, VT); 15198 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 15199 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 15200 15201 if (ShiftAmount) 15202 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 15203 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 15204 } 15205 15206 if (Res.getNode()) { 15207 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 15208 // Capture demanded bits information that would be otherwise lost. 15209 if (Known.Zero == 0xfffffffe) 15210 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 15211 DAG.getValueType(MVT::i1)); 15212 else if (Known.Zero == 0xffffff00) 15213 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 15214 DAG.getValueType(MVT::i8)); 15215 else if (Known.Zero == 0xffff0000) 15216 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 15217 DAG.getValueType(MVT::i16)); 15218 } 15219 15220 return Res; 15221 } 15222 15223 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) { 15224 SDValue Src = N->getOperand(0); 15225 15226 // We may have a bitcast of something that has already had this bitcast 15227 // combine performed on it, so skip past any VECTOR_REG_CASTs. 15228 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST) 15229 Src = Src.getOperand(0); 15230 15231 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that 15232 // would be generated is at least the width of the element type. 15233 EVT SrcVT = Src.getValueType(); 15234 EVT DstVT = N->getValueType(0); 15235 if ((Src.getOpcode() == ARMISD::VMOVIMM || 15236 Src.getOpcode() == ARMISD::VMVNIMM || 15237 Src.getOpcode() == ARMISD::VMOVFPIMM) && 15238 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() && 15239 DAG.getDataLayout().isBigEndian()) 15240 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src); 15241 15242 return SDValue(); 15243 } 15244 15245 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 15246 DAGCombinerInfo &DCI) const { 15247 switch (N->getOpcode()) { 15248 default: break; 15249 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 15250 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 15251 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 15252 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 15253 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget); 15254 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 15255 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 15256 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 15257 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 15258 case ISD::BRCOND: 15259 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 15260 case ARMISD::ADDC: 15261 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 15262 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 15263 case ARMISD::BFI: return PerformBFICombine(N, DCI); 15264 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 15265 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 15266 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI); 15267 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI); 15268 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget); 15269 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 15270 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 15271 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 15272 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 15273 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 15274 case ISD::FP_TO_SINT: 15275 case ISD::FP_TO_UINT: 15276 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 15277 case ISD::FDIV: 15278 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 15279 case ISD::INTRINSIC_WO_CHAIN: 15280 return PerformIntrinsicCombine(N, DCI); 15281 case ISD::SHL: 15282 case ISD::SRA: 15283 case ISD::SRL: 15284 return PerformShiftCombine(N, DCI, Subtarget); 15285 case ISD::SIGN_EXTEND: 15286 case ISD::ZERO_EXTEND: 15287 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 15288 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 15289 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 15290 case ISD::LOAD: return PerformLOADCombine(N, DCI); 15291 case ARMISD::VLD1DUP: 15292 case ARMISD::VLD2DUP: 15293 case ARMISD::VLD3DUP: 15294 case ARMISD::VLD4DUP: 15295 return PerformVLDCombine(N, DCI); 15296 case ARMISD::BUILD_VECTOR: 15297 return PerformARMBUILD_VECTORCombine(N, DCI); 15298 case ISD::BITCAST: 15299 return PerformBITCASTCombine(N, DCI.DAG); 15300 case ARMISD::PREDICATE_CAST: 15301 return PerformPREDICATE_CASTCombine(N, DCI); 15302 case ARMISD::VECTOR_REG_CAST: 15303 return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget); 15304 case ARMISD::VCMP: 15305 return PerformVCMPCombine(N, DCI, Subtarget); 15306 case ISD::VECREDUCE_ADD: 15307 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget); 15308 case ARMISD::ASRL: 15309 case ARMISD::LSRL: 15310 case ARMISD::LSLL: 15311 return PerformLongShiftCombine(N, DCI.DAG); 15312 case ARMISD::SMULWB: { 15313 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 15314 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 15315 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 15316 return SDValue(); 15317 break; 15318 } 15319 case ARMISD::SMULWT: { 15320 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 15321 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 15322 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 15323 return SDValue(); 15324 break; 15325 } 15326 case ARMISD::SMLALBB: 15327 case ARMISD::QADD16b: 15328 case ARMISD::QSUB16b: { 15329 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 15330 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 15331 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 15332 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 15333 return SDValue(); 15334 break; 15335 } 15336 case ARMISD::SMLALBT: { 15337 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 15338 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 15339 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 15340 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 15341 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 15342 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 15343 return SDValue(); 15344 break; 15345 } 15346 case ARMISD::SMLALTB: { 15347 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 15348 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 15349 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 15350 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 15351 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 15352 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 15353 return SDValue(); 15354 break; 15355 } 15356 case ARMISD::SMLALTT: { 15357 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 15358 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 15359 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 15360 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 15361 return SDValue(); 15362 break; 15363 } 15364 case ARMISD::QADD8b: 15365 case ARMISD::QSUB8b: { 15366 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 15367 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8); 15368 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 15369 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 15370 return SDValue(); 15371 break; 15372 } 15373 case ISD::INTRINSIC_VOID: 15374 case ISD::INTRINSIC_W_CHAIN: 15375 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15376 case Intrinsic::arm_neon_vld1: 15377 case Intrinsic::arm_neon_vld1x2: 15378 case Intrinsic::arm_neon_vld1x3: 15379 case Intrinsic::arm_neon_vld1x4: 15380 case Intrinsic::arm_neon_vld2: 15381 case Intrinsic::arm_neon_vld3: 15382 case Intrinsic::arm_neon_vld4: 15383 case Intrinsic::arm_neon_vld2lane: 15384 case Intrinsic::arm_neon_vld3lane: 15385 case Intrinsic::arm_neon_vld4lane: 15386 case Intrinsic::arm_neon_vld2dup: 15387 case Intrinsic::arm_neon_vld3dup: 15388 case Intrinsic::arm_neon_vld4dup: 15389 case Intrinsic::arm_neon_vst1: 15390 case Intrinsic::arm_neon_vst1x2: 15391 case Intrinsic::arm_neon_vst1x3: 15392 case Intrinsic::arm_neon_vst1x4: 15393 case Intrinsic::arm_neon_vst2: 15394 case Intrinsic::arm_neon_vst3: 15395 case Intrinsic::arm_neon_vst4: 15396 case Intrinsic::arm_neon_vst2lane: 15397 case Intrinsic::arm_neon_vst3lane: 15398 case Intrinsic::arm_neon_vst4lane: 15399 return PerformVLDCombine(N, DCI); 15400 case Intrinsic::arm_mve_vld2q: 15401 case Intrinsic::arm_mve_vld4q: 15402 case Intrinsic::arm_mve_vst2q: 15403 case Intrinsic::arm_mve_vst4q: 15404 return PerformMVEVLDCombine(N, DCI); 15405 default: break; 15406 } 15407 break; 15408 } 15409 return SDValue(); 15410 } 15411 15412 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 15413 EVT VT) const { 15414 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 15415 } 15416 15417 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 15418 unsigned Alignment, 15419 MachineMemOperand::Flags, 15420 bool *Fast) const { 15421 // Depends what it gets converted into if the type is weird. 15422 if (!VT.isSimple()) 15423 return false; 15424 15425 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus 15426 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 15427 auto Ty = VT.getSimpleVT().SimpleTy; 15428 15429 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 15430 // Unaligned access can use (for example) LRDB, LRDH, LDR 15431 if (AllowsUnaligned) { 15432 if (Fast) 15433 *Fast = Subtarget->hasV7Ops(); 15434 return true; 15435 } 15436 } 15437 15438 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 15439 // For any little-endian targets with neon, we can support unaligned ld/st 15440 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 15441 // A big-endian target may also explicitly support unaligned accesses 15442 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 15443 if (Fast) 15444 *Fast = true; 15445 return true; 15446 } 15447 } 15448 15449 if (!Subtarget->hasMVEIntegerOps()) 15450 return false; 15451 15452 // These are for predicates 15453 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 15454 if (Fast) 15455 *Fast = true; 15456 return true; 15457 } 15458 15459 // These are for truncated stores/narrowing loads. They are fine so long as 15460 // the alignment is at least the size of the item being loaded 15461 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 15462 Alignment >= VT.getScalarSizeInBits() / 8) { 15463 if (Fast) 15464 *Fast = true; 15465 return true; 15466 } 15467 15468 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 15469 // VSTRW.U32 all store the vector register in exactly the same format, and 15470 // differ only in the range of their immediate offset field and the required 15471 // alignment. So there is always a store that can be used, regardless of 15472 // actual type. 15473 // 15474 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 15475 // VREV64.8) pair and get the same effect. This will likely be better than 15476 // aligning the vector through the stack. 15477 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 15478 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 15479 Ty == MVT::v2f64) { 15480 if (Fast) 15481 *Fast = true; 15482 return true; 15483 } 15484 15485 return false; 15486 } 15487 15488 15489 EVT ARMTargetLowering::getOptimalMemOpType( 15490 const MemOp &Op, const AttributeList &FuncAttributes) const { 15491 // See if we can use NEON instructions for this... 15492 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() && 15493 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15494 bool Fast; 15495 if (Op.size() >= 16 && 15496 (Op.isAligned(Align(16)) || 15497 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 15498 MachineMemOperand::MONone, &Fast) && 15499 Fast))) { 15500 return MVT::v2f64; 15501 } else if (Op.size() >= 8 && 15502 (Op.isAligned(Align(8)) || 15503 (allowsMisalignedMemoryAccesses( 15504 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 15505 Fast))) { 15506 return MVT::f64; 15507 } 15508 } 15509 15510 // Let the target-independent logic figure it out. 15511 return MVT::Other; 15512 } 15513 15514 // 64-bit integers are split into their high and low parts and held in two 15515 // different registers, so the trunc is free since the low register can just 15516 // be used. 15517 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 15518 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 15519 return false; 15520 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 15521 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 15522 return (SrcBits == 64 && DestBits == 32); 15523 } 15524 15525 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 15526 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 15527 !DstVT.isInteger()) 15528 return false; 15529 unsigned SrcBits = SrcVT.getSizeInBits(); 15530 unsigned DestBits = DstVT.getSizeInBits(); 15531 return (SrcBits == 64 && DestBits == 32); 15532 } 15533 15534 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15535 if (Val.getOpcode() != ISD::LOAD) 15536 return false; 15537 15538 EVT VT1 = Val.getValueType(); 15539 if (!VT1.isSimple() || !VT1.isInteger() || 15540 !VT2.isSimple() || !VT2.isInteger()) 15541 return false; 15542 15543 switch (VT1.getSimpleVT().SimpleTy) { 15544 default: break; 15545 case MVT::i1: 15546 case MVT::i8: 15547 case MVT::i16: 15548 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 15549 return true; 15550 } 15551 15552 return false; 15553 } 15554 15555 bool ARMTargetLowering::isFNegFree(EVT VT) const { 15556 if (!VT.isSimple()) 15557 return false; 15558 15559 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 15560 // negate values directly (fneg is free). So, we don't want to let the DAG 15561 // combiner rewrite fneg into xors and some other instructions. For f16 and 15562 // FullFP16 argument passing, some bitcast nodes may be introduced, 15563 // triggering this DAG combine rewrite, so we are avoiding that with this. 15564 switch (VT.getSimpleVT().SimpleTy) { 15565 default: break; 15566 case MVT::f16: 15567 return Subtarget->hasFullFP16(); 15568 } 15569 15570 return false; 15571 } 15572 15573 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 15574 /// of the vector elements. 15575 static bool areExtractExts(Value *Ext1, Value *Ext2) { 15576 auto areExtDoubled = [](Instruction *Ext) { 15577 return Ext->getType()->getScalarSizeInBits() == 15578 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 15579 }; 15580 15581 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 15582 !match(Ext2, m_ZExtOrSExt(m_Value())) || 15583 !areExtDoubled(cast<Instruction>(Ext1)) || 15584 !areExtDoubled(cast<Instruction>(Ext2))) 15585 return false; 15586 15587 return true; 15588 } 15589 15590 /// Check if sinking \p I's operands to I's basic block is profitable, because 15591 /// the operands can be folded into a target instruction, e.g. 15592 /// sext/zext can be folded into vsubl. 15593 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 15594 SmallVectorImpl<Use *> &Ops) const { 15595 if (!I->getType()->isVectorTy()) 15596 return false; 15597 15598 if (Subtarget->hasNEON()) { 15599 switch (I->getOpcode()) { 15600 case Instruction::Sub: 15601 case Instruction::Add: { 15602 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 15603 return false; 15604 Ops.push_back(&I->getOperandUse(0)); 15605 Ops.push_back(&I->getOperandUse(1)); 15606 return true; 15607 } 15608 default: 15609 return false; 15610 } 15611 } 15612 15613 if (!Subtarget->hasMVEIntegerOps()) 15614 return false; 15615 15616 auto IsFMSMul = [&](Instruction *I) { 15617 if (!I->hasOneUse()) 15618 return false; 15619 auto *Sub = cast<Instruction>(*I->users().begin()); 15620 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I; 15621 }; 15622 15623 auto IsSinker = [&](Instruction *I, int Operand) { 15624 switch (I->getOpcode()) { 15625 case Instruction::Add: 15626 case Instruction::Mul: 15627 case Instruction::FAdd: 15628 case Instruction::ICmp: 15629 case Instruction::FCmp: 15630 return true; 15631 case Instruction::FMul: 15632 return !IsFMSMul(I); 15633 case Instruction::Sub: 15634 case Instruction::FSub: 15635 case Instruction::Shl: 15636 case Instruction::LShr: 15637 case Instruction::AShr: 15638 return Operand == 1; 15639 default: 15640 return false; 15641 } 15642 }; 15643 15644 int Op = 0; 15645 if (!isa<ShuffleVectorInst>(I->getOperand(Op))) 15646 Op = 1; 15647 if (!IsSinker(I, Op)) 15648 return false; 15649 if (!match(I->getOperand(Op), 15650 m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()), 15651 m_Undef(), m_ZeroMask()))) { 15652 return false; 15653 } 15654 Instruction *Shuffle = cast<Instruction>(I->getOperand(Op)); 15655 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 15656 // and vector registers 15657 for (Use &U : Shuffle->uses()) { 15658 Instruction *Insn = cast<Instruction>(U.getUser()); 15659 if (!IsSinker(Insn, U.getOperandNo())) 15660 return false; 15661 } 15662 Ops.push_back(&Shuffle->getOperandUse(0)); 15663 Ops.push_back(&I->getOperandUse(Op)); 15664 return true; 15665 } 15666 15667 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 15668 EVT VT = ExtVal.getValueType(); 15669 15670 if (!isTypeLegal(VT)) 15671 return false; 15672 15673 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) { 15674 if (Ld->isExpandingLoad()) 15675 return false; 15676 } 15677 15678 if (Subtarget->hasMVEIntegerOps()) 15679 return true; 15680 15681 // Don't create a loadext if we can fold the extension into a wide/long 15682 // instruction. 15683 // If there's more than one user instruction, the loadext is desirable no 15684 // matter what. There can be two uses by the same instruction. 15685 if (ExtVal->use_empty() || 15686 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 15687 return true; 15688 15689 SDNode *U = *ExtVal->use_begin(); 15690 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 15691 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 15692 return false; 15693 15694 return true; 15695 } 15696 15697 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 15698 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15699 return false; 15700 15701 if (!isTypeLegal(EVT::getEVT(Ty1))) 15702 return false; 15703 15704 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 15705 15706 // Assuming the caller doesn't have a zeroext or signext return parameter, 15707 // truncation all the way down to i1 is valid. 15708 return true; 15709 } 15710 15711 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 15712 const AddrMode &AM, Type *Ty, 15713 unsigned AS) const { 15714 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 15715 if (Subtarget->hasFPAO()) 15716 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 15717 return 0; 15718 } 15719 return -1; 15720 } 15721 15722 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster 15723 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be 15724 /// expanded to FMAs when this method returns true, otherwise fmuladd is 15725 /// expanded to fmul + fadd. 15726 /// 15727 /// ARM supports both fused and unfused multiply-add operations; we already 15728 /// lower a pair of fmul and fadd to the latter so it's not clear that there 15729 /// would be a gain or that the gain would be worthwhile enough to risk 15730 /// correctness bugs. 15731 /// 15732 /// For MVE, we set this to true as it helps simplify the need for some 15733 /// patterns (and we don't have the non-fused floating point instruction). 15734 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15735 EVT VT) const { 15736 if (!VT.isSimple()) 15737 return false; 15738 15739 switch (VT.getSimpleVT().SimpleTy) { 15740 case MVT::v4f32: 15741 case MVT::v8f16: 15742 return Subtarget->hasMVEFloatOps(); 15743 case MVT::f16: 15744 return Subtarget->useFPVFMx16(); 15745 case MVT::f32: 15746 return Subtarget->useFPVFMx(); 15747 case MVT::f64: 15748 return Subtarget->useFPVFMx64(); 15749 default: 15750 break; 15751 } 15752 15753 return false; 15754 } 15755 15756 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 15757 if (V < 0) 15758 return false; 15759 15760 unsigned Scale = 1; 15761 switch (VT.getSimpleVT().SimpleTy) { 15762 case MVT::i1: 15763 case MVT::i8: 15764 // Scale == 1; 15765 break; 15766 case MVT::i16: 15767 // Scale == 2; 15768 Scale = 2; 15769 break; 15770 default: 15771 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 15772 // Scale == 4; 15773 Scale = 4; 15774 break; 15775 } 15776 15777 if ((V & (Scale - 1)) != 0) 15778 return false; 15779 return isUInt<5>(V / Scale); 15780 } 15781 15782 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 15783 const ARMSubtarget *Subtarget) { 15784 if (!VT.isInteger() && !VT.isFloatingPoint()) 15785 return false; 15786 if (VT.isVector() && Subtarget->hasNEON()) 15787 return false; 15788 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 15789 !Subtarget->hasMVEFloatOps()) 15790 return false; 15791 15792 bool IsNeg = false; 15793 if (V < 0) { 15794 IsNeg = true; 15795 V = -V; 15796 } 15797 15798 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U); 15799 15800 // MVE: size * imm7 15801 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 15802 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 15803 case MVT::i32: 15804 case MVT::f32: 15805 return isShiftedUInt<7,2>(V); 15806 case MVT::i16: 15807 case MVT::f16: 15808 return isShiftedUInt<7,1>(V); 15809 case MVT::i8: 15810 return isUInt<7>(V); 15811 default: 15812 return false; 15813 } 15814 } 15815 15816 // half VLDR: 2 * imm8 15817 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 15818 return isShiftedUInt<8, 1>(V); 15819 // VLDR and LDRD: 4 * imm8 15820 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 15821 return isShiftedUInt<8, 2>(V); 15822 15823 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 15824 // + imm12 or - imm8 15825 if (IsNeg) 15826 return isUInt<8>(V); 15827 return isUInt<12>(V); 15828 } 15829 15830 return false; 15831 } 15832 15833 /// isLegalAddressImmediate - Return true if the integer value can be used 15834 /// as the offset of the target addressing mode for load / store of the 15835 /// given type. 15836 static bool isLegalAddressImmediate(int64_t V, EVT VT, 15837 const ARMSubtarget *Subtarget) { 15838 if (V == 0) 15839 return true; 15840 15841 if (!VT.isSimple()) 15842 return false; 15843 15844 if (Subtarget->isThumb1Only()) 15845 return isLegalT1AddressImmediate(V, VT); 15846 else if (Subtarget->isThumb2()) 15847 return isLegalT2AddressImmediate(V, VT, Subtarget); 15848 15849 // ARM mode. 15850 if (V < 0) 15851 V = - V; 15852 switch (VT.getSimpleVT().SimpleTy) { 15853 default: return false; 15854 case MVT::i1: 15855 case MVT::i8: 15856 case MVT::i32: 15857 // +- imm12 15858 return isUInt<12>(V); 15859 case MVT::i16: 15860 // +- imm8 15861 return isUInt<8>(V); 15862 case MVT::f32: 15863 case MVT::f64: 15864 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 15865 return false; 15866 return isShiftedUInt<8, 2>(V); 15867 } 15868 } 15869 15870 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 15871 EVT VT) const { 15872 int Scale = AM.Scale; 15873 if (Scale < 0) 15874 return false; 15875 15876 switch (VT.getSimpleVT().SimpleTy) { 15877 default: return false; 15878 case MVT::i1: 15879 case MVT::i8: 15880 case MVT::i16: 15881 case MVT::i32: 15882 if (Scale == 1) 15883 return true; 15884 // r + r << imm 15885 Scale = Scale & ~1; 15886 return Scale == 2 || Scale == 4 || Scale == 8; 15887 case MVT::i64: 15888 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 15889 // version in Thumb mode. 15890 // r + r 15891 if (Scale == 1) 15892 return true; 15893 // r * 2 (this can be lowered to r + r). 15894 if (!AM.HasBaseReg && Scale == 2) 15895 return true; 15896 return false; 15897 case MVT::isVoid: 15898 // Note, we allow "void" uses (basically, uses that aren't loads or 15899 // stores), because arm allows folding a scale into many arithmetic 15900 // operations. This should be made more precise and revisited later. 15901 15902 // Allow r << imm, but the imm has to be a multiple of two. 15903 if (Scale & 1) return false; 15904 return isPowerOf2_32(Scale); 15905 } 15906 } 15907 15908 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 15909 EVT VT) const { 15910 const int Scale = AM.Scale; 15911 15912 // Negative scales are not supported in Thumb1. 15913 if (Scale < 0) 15914 return false; 15915 15916 // Thumb1 addressing modes do not support register scaling excepting the 15917 // following cases: 15918 // 1. Scale == 1 means no scaling. 15919 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 15920 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 15921 } 15922 15923 /// isLegalAddressingMode - Return true if the addressing mode represented 15924 /// by AM is legal for this target, for a load/store of the specified type. 15925 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15926 const AddrMode &AM, Type *Ty, 15927 unsigned AS, Instruction *I) const { 15928 EVT VT = getValueType(DL, Ty, true); 15929 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 15930 return false; 15931 15932 // Can never fold addr of global into load/store. 15933 if (AM.BaseGV) 15934 return false; 15935 15936 switch (AM.Scale) { 15937 case 0: // no scale reg, must be "r+i" or "r", or "i". 15938 break; 15939 default: 15940 // ARM doesn't support any R+R*scale+imm addr modes. 15941 if (AM.BaseOffs) 15942 return false; 15943 15944 if (!VT.isSimple()) 15945 return false; 15946 15947 if (Subtarget->isThumb1Only()) 15948 return isLegalT1ScaledAddressingMode(AM, VT); 15949 15950 if (Subtarget->isThumb2()) 15951 return isLegalT2ScaledAddressingMode(AM, VT); 15952 15953 int Scale = AM.Scale; 15954 switch (VT.getSimpleVT().SimpleTy) { 15955 default: return false; 15956 case MVT::i1: 15957 case MVT::i8: 15958 case MVT::i32: 15959 if (Scale < 0) Scale = -Scale; 15960 if (Scale == 1) 15961 return true; 15962 // r + r << imm 15963 return isPowerOf2_32(Scale & ~1); 15964 case MVT::i16: 15965 case MVT::i64: 15966 // r +/- r 15967 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 15968 return true; 15969 // r * 2 (this can be lowered to r + r). 15970 if (!AM.HasBaseReg && Scale == 2) 15971 return true; 15972 return false; 15973 15974 case MVT::isVoid: 15975 // Note, we allow "void" uses (basically, uses that aren't loads or 15976 // stores), because arm allows folding a scale into many arithmetic 15977 // operations. This should be made more precise and revisited later. 15978 15979 // Allow r << imm, but the imm has to be a multiple of two. 15980 if (Scale & 1) return false; 15981 return isPowerOf2_32(Scale); 15982 } 15983 } 15984 return true; 15985 } 15986 15987 /// isLegalICmpImmediate - Return true if the specified immediate is legal 15988 /// icmp immediate, that is the target has icmp instructions which can compare 15989 /// a register against the immediate without having to materialize the 15990 /// immediate into a register. 15991 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15992 // Thumb2 and ARM modes can use cmn for negative immediates. 15993 if (!Subtarget->isThumb()) 15994 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 15995 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 15996 if (Subtarget->isThumb2()) 15997 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 15998 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 15999 // Thumb1 doesn't have cmn, and only 8-bit immediates. 16000 return Imm >= 0 && Imm <= 255; 16001 } 16002 16003 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 16004 /// *or sub* immediate, that is the target has add or sub instructions which can 16005 /// add a register with the immediate without having to materialize the 16006 /// immediate into a register. 16007 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16008 // Same encoding for add/sub, just flip the sign. 16009 int64_t AbsImm = std::abs(Imm); 16010 if (!Subtarget->isThumb()) 16011 return ARM_AM::getSOImmVal(AbsImm) != -1; 16012 if (Subtarget->isThumb2()) 16013 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 16014 // Thumb1 only has 8-bit unsigned immediate. 16015 return AbsImm >= 0 && AbsImm <= 255; 16016 } 16017 16018 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 16019 bool isSEXTLoad, SDValue &Base, 16020 SDValue &Offset, bool &isInc, 16021 SelectionDAG &DAG) { 16022 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 16023 return false; 16024 16025 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 16026 // AddressingMode 3 16027 Base = Ptr->getOperand(0); 16028 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 16029 int RHSC = (int)RHS->getZExtValue(); 16030 if (RHSC < 0 && RHSC > -256) { 16031 assert(Ptr->getOpcode() == ISD::ADD); 16032 isInc = false; 16033 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16034 return true; 16035 } 16036 } 16037 isInc = (Ptr->getOpcode() == ISD::ADD); 16038 Offset = Ptr->getOperand(1); 16039 return true; 16040 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 16041 // AddressingMode 2 16042 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 16043 int RHSC = (int)RHS->getZExtValue(); 16044 if (RHSC < 0 && RHSC > -0x1000) { 16045 assert(Ptr->getOpcode() == ISD::ADD); 16046 isInc = false; 16047 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16048 Base = Ptr->getOperand(0); 16049 return true; 16050 } 16051 } 16052 16053 if (Ptr->getOpcode() == ISD::ADD) { 16054 isInc = true; 16055 ARM_AM::ShiftOpc ShOpcVal= 16056 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 16057 if (ShOpcVal != ARM_AM::no_shift) { 16058 Base = Ptr->getOperand(1); 16059 Offset = Ptr->getOperand(0); 16060 } else { 16061 Base = Ptr->getOperand(0); 16062 Offset = Ptr->getOperand(1); 16063 } 16064 return true; 16065 } 16066 16067 isInc = (Ptr->getOpcode() == ISD::ADD); 16068 Base = Ptr->getOperand(0); 16069 Offset = Ptr->getOperand(1); 16070 return true; 16071 } 16072 16073 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 16074 return false; 16075 } 16076 16077 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 16078 bool isSEXTLoad, SDValue &Base, 16079 SDValue &Offset, bool &isInc, 16080 SelectionDAG &DAG) { 16081 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 16082 return false; 16083 16084 Base = Ptr->getOperand(0); 16085 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 16086 int RHSC = (int)RHS->getZExtValue(); 16087 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 16088 assert(Ptr->getOpcode() == ISD::ADD); 16089 isInc = false; 16090 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16091 return true; 16092 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 16093 isInc = Ptr->getOpcode() == ISD::ADD; 16094 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16095 return true; 16096 } 16097 } 16098 16099 return false; 16100 } 16101 16102 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align, 16103 bool isSEXTLoad, bool IsMasked, bool isLE, 16104 SDValue &Base, SDValue &Offset, 16105 bool &isInc, SelectionDAG &DAG) { 16106 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 16107 return false; 16108 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 16109 return false; 16110 16111 // We allow LE non-masked loads to change the type (for example use a vldrb.8 16112 // as opposed to a vldrw.32). This can allow extra addressing modes or 16113 // alignments for what is otherwise an equivalent instruction. 16114 bool CanChangeType = isLE && !IsMasked; 16115 16116 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 16117 int RHSC = (int)RHS->getZExtValue(); 16118 16119 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 16120 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 16121 assert(Ptr->getOpcode() == ISD::ADD); 16122 isInc = false; 16123 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16124 return true; 16125 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 16126 isInc = Ptr->getOpcode() == ISD::ADD; 16127 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 16128 return true; 16129 } 16130 return false; 16131 }; 16132 16133 // Try to find a matching instruction based on s/zext, Alignment, Offset and 16134 // (in BE/masked) type. 16135 Base = Ptr->getOperand(0); 16136 if (VT == MVT::v4i16) { 16137 if (Align >= 2 && IsInRange(RHSC, 0x80, 2)) 16138 return true; 16139 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 16140 if (IsInRange(RHSC, 0x80, 1)) 16141 return true; 16142 } else if (Align >= 4 && 16143 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) && 16144 IsInRange(RHSC, 0x80, 4)) 16145 return true; 16146 else if (Align >= 2 && 16147 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) && 16148 IsInRange(RHSC, 0x80, 2)) 16149 return true; 16150 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 16151 return true; 16152 return false; 16153 } 16154 16155 /// getPreIndexedAddressParts - returns true by value, base pointer and 16156 /// offset pointer and addressing mode by reference if the node's address 16157 /// can be legally represented as pre-indexed load / store address. 16158 bool 16159 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 16160 SDValue &Offset, 16161 ISD::MemIndexedMode &AM, 16162 SelectionDAG &DAG) const { 16163 if (Subtarget->isThumb1Only()) 16164 return false; 16165 16166 EVT VT; 16167 SDValue Ptr; 16168 unsigned Align; 16169 bool isSEXTLoad = false; 16170 bool IsMasked = false; 16171 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 16172 Ptr = LD->getBasePtr(); 16173 VT = LD->getMemoryVT(); 16174 Align = LD->getAlignment(); 16175 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 16176 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 16177 Ptr = ST->getBasePtr(); 16178 VT = ST->getMemoryVT(); 16179 Align = ST->getAlignment(); 16180 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 16181 Ptr = LD->getBasePtr(); 16182 VT = LD->getMemoryVT(); 16183 Align = LD->getAlignment(); 16184 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 16185 IsMasked = true; 16186 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 16187 Ptr = ST->getBasePtr(); 16188 VT = ST->getMemoryVT(); 16189 Align = ST->getAlignment(); 16190 IsMasked = true; 16191 } else 16192 return false; 16193 16194 bool isInc; 16195 bool isLegal = false; 16196 if (VT.isVector()) 16197 isLegal = Subtarget->hasMVEIntegerOps() && 16198 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad, 16199 IsMasked, Subtarget->isLittle(), Base, 16200 Offset, isInc, DAG); 16201 else { 16202 if (Subtarget->isThumb2()) 16203 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 16204 Offset, isInc, DAG); 16205 else 16206 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 16207 Offset, isInc, DAG); 16208 } 16209 if (!isLegal) 16210 return false; 16211 16212 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 16213 return true; 16214 } 16215 16216 /// getPostIndexedAddressParts - returns true by value, base pointer and 16217 /// offset pointer and addressing mode by reference if this node can be 16218 /// combined with a load / store to form a post-indexed load / store. 16219 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 16220 SDValue &Base, 16221 SDValue &Offset, 16222 ISD::MemIndexedMode &AM, 16223 SelectionDAG &DAG) const { 16224 EVT VT; 16225 SDValue Ptr; 16226 unsigned Align; 16227 bool isSEXTLoad = false, isNonExt; 16228 bool IsMasked = false; 16229 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 16230 VT = LD->getMemoryVT(); 16231 Ptr = LD->getBasePtr(); 16232 Align = LD->getAlignment(); 16233 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 16234 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 16235 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 16236 VT = ST->getMemoryVT(); 16237 Ptr = ST->getBasePtr(); 16238 Align = ST->getAlignment(); 16239 isNonExt = !ST->isTruncatingStore(); 16240 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 16241 VT = LD->getMemoryVT(); 16242 Ptr = LD->getBasePtr(); 16243 Align = LD->getAlignment(); 16244 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 16245 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 16246 IsMasked = true; 16247 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 16248 VT = ST->getMemoryVT(); 16249 Ptr = ST->getBasePtr(); 16250 Align = ST->getAlignment(); 16251 isNonExt = !ST->isTruncatingStore(); 16252 IsMasked = true; 16253 } else 16254 return false; 16255 16256 if (Subtarget->isThumb1Only()) { 16257 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 16258 // must be non-extending/truncating, i32, with an offset of 4. 16259 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 16260 if (Op->getOpcode() != ISD::ADD || !isNonExt) 16261 return false; 16262 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 16263 if (!RHS || RHS->getZExtValue() != 4) 16264 return false; 16265 16266 Offset = Op->getOperand(1); 16267 Base = Op->getOperand(0); 16268 AM = ISD::POST_INC; 16269 return true; 16270 } 16271 16272 bool isInc; 16273 bool isLegal = false; 16274 if (VT.isVector()) 16275 isLegal = Subtarget->hasMVEIntegerOps() && 16276 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad, IsMasked, 16277 Subtarget->isLittle(), Base, Offset, 16278 isInc, DAG); 16279 else { 16280 if (Subtarget->isThumb2()) 16281 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 16282 isInc, DAG); 16283 else 16284 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 16285 isInc, DAG); 16286 } 16287 if (!isLegal) 16288 return false; 16289 16290 if (Ptr != Base) { 16291 // Swap base ptr and offset to catch more post-index load / store when 16292 // it's legal. In Thumb2 mode, offset must be an immediate. 16293 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 16294 !Subtarget->isThumb2()) 16295 std::swap(Base, Offset); 16296 16297 // Post-indexed load / store update the base pointer. 16298 if (Ptr != Base) 16299 return false; 16300 } 16301 16302 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 16303 return true; 16304 } 16305 16306 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 16307 KnownBits &Known, 16308 const APInt &DemandedElts, 16309 const SelectionDAG &DAG, 16310 unsigned Depth) const { 16311 unsigned BitWidth = Known.getBitWidth(); 16312 Known.resetAll(); 16313 switch (Op.getOpcode()) { 16314 default: break; 16315 case ARMISD::ADDC: 16316 case ARMISD::ADDE: 16317 case ARMISD::SUBC: 16318 case ARMISD::SUBE: 16319 // Special cases when we convert a carry to a boolean. 16320 if (Op.getResNo() == 0) { 16321 SDValue LHS = Op.getOperand(0); 16322 SDValue RHS = Op.getOperand(1); 16323 // (ADDE 0, 0, C) will give us a single bit. 16324 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 16325 isNullConstant(RHS)) { 16326 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 16327 return; 16328 } 16329 } 16330 break; 16331 case ARMISD::CMOV: { 16332 // Bits are known zero/one if known on the LHS and RHS. 16333 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 16334 if (Known.isUnknown()) 16335 return; 16336 16337 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 16338 Known.Zero &= KnownRHS.Zero; 16339 Known.One &= KnownRHS.One; 16340 return; 16341 } 16342 case ISD::INTRINSIC_W_CHAIN: { 16343 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 16344 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 16345 switch (IntID) { 16346 default: return; 16347 case Intrinsic::arm_ldaex: 16348 case Intrinsic::arm_ldrex: { 16349 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 16350 unsigned MemBits = VT.getScalarSizeInBits(); 16351 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 16352 return; 16353 } 16354 } 16355 } 16356 case ARMISD::BFI: { 16357 // Conservatively, we can recurse down the first operand 16358 // and just mask out all affected bits. 16359 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 16360 16361 // The operand to BFI is already a mask suitable for removing the bits it 16362 // sets. 16363 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 16364 const APInt &Mask = CI->getAPIntValue(); 16365 Known.Zero &= Mask; 16366 Known.One &= Mask; 16367 return; 16368 } 16369 case ARMISD::VGETLANEs: 16370 case ARMISD::VGETLANEu: { 16371 const SDValue &SrcSV = Op.getOperand(0); 16372 EVT VecVT = SrcSV.getValueType(); 16373 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 16374 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 16375 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 16376 assert(Pos->getAPIntValue().ult(NumSrcElts) && 16377 "VGETLANE index out of bounds"); 16378 unsigned Idx = Pos->getZExtValue(); 16379 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 16380 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 16381 16382 EVT VT = Op.getValueType(); 16383 const unsigned DstSz = VT.getScalarSizeInBits(); 16384 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 16385 (void)SrcSz; 16386 assert(SrcSz == Known.getBitWidth()); 16387 assert(DstSz > SrcSz); 16388 if (Op.getOpcode() == ARMISD::VGETLANEs) 16389 Known = Known.sext(DstSz); 16390 else { 16391 Known = Known.zext(DstSz); 16392 } 16393 assert(DstSz == Known.getBitWidth()); 16394 break; 16395 } 16396 } 16397 } 16398 16399 bool 16400 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 16401 const APInt &DemandedAPInt, 16402 TargetLoweringOpt &TLO) const { 16403 // Delay optimization, so we don't have to deal with illegal types, or block 16404 // optimizations. 16405 if (!TLO.LegalOps) 16406 return false; 16407 16408 // Only optimize AND for now. 16409 if (Op.getOpcode() != ISD::AND) 16410 return false; 16411 16412 EVT VT = Op.getValueType(); 16413 16414 // Ignore vectors. 16415 if (VT.isVector()) 16416 return false; 16417 16418 assert(VT == MVT::i32 && "Unexpected integer type"); 16419 16420 // Make sure the RHS really is a constant. 16421 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 16422 if (!C) 16423 return false; 16424 16425 unsigned Mask = C->getZExtValue(); 16426 16427 unsigned Demanded = DemandedAPInt.getZExtValue(); 16428 unsigned ShrunkMask = Mask & Demanded; 16429 unsigned ExpandedMask = Mask | ~Demanded; 16430 16431 // If the mask is all zeros, let the target-independent code replace the 16432 // result with zero. 16433 if (ShrunkMask == 0) 16434 return false; 16435 16436 // If the mask is all ones, erase the AND. (Currently, the target-independent 16437 // code won't do this, so we have to do it explicitly to avoid an infinite 16438 // loop in obscure cases.) 16439 if (ExpandedMask == ~0U) 16440 return TLO.CombineTo(Op, Op.getOperand(0)); 16441 16442 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 16443 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 16444 }; 16445 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 16446 if (NewMask == Mask) 16447 return true; 16448 SDLoc DL(Op); 16449 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 16450 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 16451 return TLO.CombineTo(Op, NewOp); 16452 }; 16453 16454 // Prefer uxtb mask. 16455 if (IsLegalMask(0xFF)) 16456 return UseMask(0xFF); 16457 16458 // Prefer uxth mask. 16459 if (IsLegalMask(0xFFFF)) 16460 return UseMask(0xFFFF); 16461 16462 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 16463 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 16464 if (ShrunkMask < 256) 16465 return UseMask(ShrunkMask); 16466 16467 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 16468 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 16469 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 16470 return UseMask(ExpandedMask); 16471 16472 // Potential improvements: 16473 // 16474 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 16475 // We could try to prefer Thumb1 immediates which can be lowered to a 16476 // two-instruction sequence. 16477 // We could try to recognize more legal ARM/Thumb2 immediates here. 16478 16479 return false; 16480 } 16481 16482 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode( 16483 SDValue Op, const APInt &OriginalDemandedBits, 16484 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 16485 unsigned Depth) const { 16486 unsigned Opc = Op.getOpcode(); 16487 16488 switch (Opc) { 16489 case ARMISD::ASRL: 16490 case ARMISD::LSRL: { 16491 // If this is result 0 and the other result is unused, see if the demand 16492 // bits allow us to shrink this long shift into a standard small shift in 16493 // the opposite direction. 16494 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) && 16495 isa<ConstantSDNode>(Op->getOperand(2))) { 16496 unsigned ShAmt = Op->getConstantOperandVal(2); 16497 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf( 16498 APInt::getAllOnesValue(32) << (32 - ShAmt))) 16499 return TLO.CombineTo( 16500 Op, TLO.DAG.getNode( 16501 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1), 16502 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32))); 16503 } 16504 break; 16505 } 16506 } 16507 16508 return TargetLowering::SimplifyDemandedBitsForTargetNode( 16509 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth); 16510 } 16511 16512 //===----------------------------------------------------------------------===// 16513 // ARM Inline Assembly Support 16514 //===----------------------------------------------------------------------===// 16515 16516 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 16517 // Looking for "rev" which is V6+. 16518 if (!Subtarget->hasV6Ops()) 16519 return false; 16520 16521 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 16522 std::string AsmStr = IA->getAsmString(); 16523 SmallVector<StringRef, 4> AsmPieces; 16524 SplitString(AsmStr, AsmPieces, ";\n"); 16525 16526 switch (AsmPieces.size()) { 16527 default: return false; 16528 case 1: 16529 AsmStr = std::string(AsmPieces[0]); 16530 AsmPieces.clear(); 16531 SplitString(AsmStr, AsmPieces, " \t,"); 16532 16533 // rev $0, $1 16534 if (AsmPieces.size() == 3 && 16535 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 16536 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 16537 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 16538 if (Ty && Ty->getBitWidth() == 32) 16539 return IntrinsicLowering::LowerToByteSwap(CI); 16540 } 16541 break; 16542 } 16543 16544 return false; 16545 } 16546 16547 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 16548 // At this point, we have to lower this constraint to something else, so we 16549 // lower it to an "r" or "w". However, by doing this we will force the result 16550 // to be in register, while the X constraint is much more permissive. 16551 // 16552 // Although we are correct (we are free to emit anything, without 16553 // constraints), we might break use cases that would expect us to be more 16554 // efficient and emit something else. 16555 if (!Subtarget->hasVFP2Base()) 16556 return "r"; 16557 if (ConstraintVT.isFloatingPoint()) 16558 return "w"; 16559 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 16560 (ConstraintVT.getSizeInBits() == 64 || 16561 ConstraintVT.getSizeInBits() == 128)) 16562 return "w"; 16563 16564 return "r"; 16565 } 16566 16567 /// getConstraintType - Given a constraint letter, return the type of 16568 /// constraint it is for this target. 16569 ARMTargetLowering::ConstraintType 16570 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 16571 unsigned S = Constraint.size(); 16572 if (S == 1) { 16573 switch (Constraint[0]) { 16574 default: break; 16575 case 'l': return C_RegisterClass; 16576 case 'w': return C_RegisterClass; 16577 case 'h': return C_RegisterClass; 16578 case 'x': return C_RegisterClass; 16579 case 't': return C_RegisterClass; 16580 case 'j': return C_Immediate; // Constant for movw. 16581 // An address with a single base register. Due to the way we 16582 // currently handle addresses it is the same as an 'r' memory constraint. 16583 case 'Q': return C_Memory; 16584 } 16585 } else if (S == 2) { 16586 switch (Constraint[0]) { 16587 default: break; 16588 case 'T': return C_RegisterClass; 16589 // All 'U+' constraints are addresses. 16590 case 'U': return C_Memory; 16591 } 16592 } 16593 return TargetLowering::getConstraintType(Constraint); 16594 } 16595 16596 /// Examine constraint type and operand type and determine a weight value. 16597 /// This object must already have been set up with the operand type 16598 /// and the current alternative constraint selected. 16599 TargetLowering::ConstraintWeight 16600 ARMTargetLowering::getSingleConstraintMatchWeight( 16601 AsmOperandInfo &info, const char *constraint) const { 16602 ConstraintWeight weight = CW_Invalid; 16603 Value *CallOperandVal = info.CallOperandVal; 16604 // If we don't have a value, we can't do a match, 16605 // but allow it at the lowest weight. 16606 if (!CallOperandVal) 16607 return CW_Default; 16608 Type *type = CallOperandVal->getType(); 16609 // Look at the constraint type. 16610 switch (*constraint) { 16611 default: 16612 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 16613 break; 16614 case 'l': 16615 if (type->isIntegerTy()) { 16616 if (Subtarget->isThumb()) 16617 weight = CW_SpecificReg; 16618 else 16619 weight = CW_Register; 16620 } 16621 break; 16622 case 'w': 16623 if (type->isFloatingPointTy()) 16624 weight = CW_Register; 16625 break; 16626 } 16627 return weight; 16628 } 16629 16630 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 16631 16632 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 16633 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 16634 switch (Constraint.size()) { 16635 case 1: 16636 // GCC ARM Constraint Letters 16637 switch (Constraint[0]) { 16638 case 'l': // Low regs or general regs. 16639 if (Subtarget->isThumb()) 16640 return RCPair(0U, &ARM::tGPRRegClass); 16641 return RCPair(0U, &ARM::GPRRegClass); 16642 case 'h': // High regs or no regs. 16643 if (Subtarget->isThumb()) 16644 return RCPair(0U, &ARM::hGPRRegClass); 16645 break; 16646 case 'r': 16647 if (Subtarget->isThumb1Only()) 16648 return RCPair(0U, &ARM::tGPRRegClass); 16649 return RCPair(0U, &ARM::GPRRegClass); 16650 case 'w': 16651 if (VT == MVT::Other) 16652 break; 16653 if (VT == MVT::f32) 16654 return RCPair(0U, &ARM::SPRRegClass); 16655 if (VT.getSizeInBits() == 64) 16656 return RCPair(0U, &ARM::DPRRegClass); 16657 if (VT.getSizeInBits() == 128) 16658 return RCPair(0U, &ARM::QPRRegClass); 16659 break; 16660 case 'x': 16661 if (VT == MVT::Other) 16662 break; 16663 if (VT == MVT::f32) 16664 return RCPair(0U, &ARM::SPR_8RegClass); 16665 if (VT.getSizeInBits() == 64) 16666 return RCPair(0U, &ARM::DPR_8RegClass); 16667 if (VT.getSizeInBits() == 128) 16668 return RCPair(0U, &ARM::QPR_8RegClass); 16669 break; 16670 case 't': 16671 if (VT == MVT::Other) 16672 break; 16673 if (VT == MVT::f32 || VT == MVT::i32) 16674 return RCPair(0U, &ARM::SPRRegClass); 16675 if (VT.getSizeInBits() == 64) 16676 return RCPair(0U, &ARM::DPR_VFP2RegClass); 16677 if (VT.getSizeInBits() == 128) 16678 return RCPair(0U, &ARM::QPR_VFP2RegClass); 16679 break; 16680 } 16681 break; 16682 16683 case 2: 16684 if (Constraint[0] == 'T') { 16685 switch (Constraint[1]) { 16686 default: 16687 break; 16688 case 'e': 16689 return RCPair(0U, &ARM::tGPREvenRegClass); 16690 case 'o': 16691 return RCPair(0U, &ARM::tGPROddRegClass); 16692 } 16693 } 16694 break; 16695 16696 default: 16697 break; 16698 } 16699 16700 if (StringRef("{cc}").equals_lower(Constraint)) 16701 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 16702 16703 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 16704 } 16705 16706 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 16707 /// vector. If it is invalid, don't add anything to Ops. 16708 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 16709 std::string &Constraint, 16710 std::vector<SDValue>&Ops, 16711 SelectionDAG &DAG) const { 16712 SDValue Result; 16713 16714 // Currently only support length 1 constraints. 16715 if (Constraint.length() != 1) return; 16716 16717 char ConstraintLetter = Constraint[0]; 16718 switch (ConstraintLetter) { 16719 default: break; 16720 case 'j': 16721 case 'I': case 'J': case 'K': case 'L': 16722 case 'M': case 'N': case 'O': 16723 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 16724 if (!C) 16725 return; 16726 16727 int64_t CVal64 = C->getSExtValue(); 16728 int CVal = (int) CVal64; 16729 // None of these constraints allow values larger than 32 bits. Check 16730 // that the value fits in an int. 16731 if (CVal != CVal64) 16732 return; 16733 16734 switch (ConstraintLetter) { 16735 case 'j': 16736 // Constant suitable for movw, must be between 0 and 16737 // 65535. 16738 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps())) 16739 if (CVal >= 0 && CVal <= 65535) 16740 break; 16741 return; 16742 case 'I': 16743 if (Subtarget->isThumb1Only()) { 16744 // This must be a constant between 0 and 255, for ADD 16745 // immediates. 16746 if (CVal >= 0 && CVal <= 255) 16747 break; 16748 } else if (Subtarget->isThumb2()) { 16749 // A constant that can be used as an immediate value in a 16750 // data-processing instruction. 16751 if (ARM_AM::getT2SOImmVal(CVal) != -1) 16752 break; 16753 } else { 16754 // A constant that can be used as an immediate value in a 16755 // data-processing instruction. 16756 if (ARM_AM::getSOImmVal(CVal) != -1) 16757 break; 16758 } 16759 return; 16760 16761 case 'J': 16762 if (Subtarget->isThumb1Only()) { 16763 // This must be a constant between -255 and -1, for negated ADD 16764 // immediates. This can be used in GCC with an "n" modifier that 16765 // prints the negated value, for use with SUB instructions. It is 16766 // not useful otherwise but is implemented for compatibility. 16767 if (CVal >= -255 && CVal <= -1) 16768 break; 16769 } else { 16770 // This must be a constant between -4095 and 4095. It is not clear 16771 // what this constraint is intended for. Implemented for 16772 // compatibility with GCC. 16773 if (CVal >= -4095 && CVal <= 4095) 16774 break; 16775 } 16776 return; 16777 16778 case 'K': 16779 if (Subtarget->isThumb1Only()) { 16780 // A 32-bit value where only one byte has a nonzero value. Exclude 16781 // zero to match GCC. This constraint is used by GCC internally for 16782 // constants that can be loaded with a move/shift combination. 16783 // It is not useful otherwise but is implemented for compatibility. 16784 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 16785 break; 16786 } else if (Subtarget->isThumb2()) { 16787 // A constant whose bitwise inverse can be used as an immediate 16788 // value in a data-processing instruction. This can be used in GCC 16789 // with a "B" modifier that prints the inverted value, for use with 16790 // BIC and MVN instructions. It is not useful otherwise but is 16791 // implemented for compatibility. 16792 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 16793 break; 16794 } else { 16795 // A constant whose bitwise inverse can be used as an immediate 16796 // value in a data-processing instruction. This can be used in GCC 16797 // with a "B" modifier that prints the inverted value, for use with 16798 // BIC and MVN instructions. It is not useful otherwise but is 16799 // implemented for compatibility. 16800 if (ARM_AM::getSOImmVal(~CVal) != -1) 16801 break; 16802 } 16803 return; 16804 16805 case 'L': 16806 if (Subtarget->isThumb1Only()) { 16807 // This must be a constant between -7 and 7, 16808 // for 3-operand ADD/SUB immediate instructions. 16809 if (CVal >= -7 && CVal < 7) 16810 break; 16811 } else if (Subtarget->isThumb2()) { 16812 // A constant whose negation can be used as an immediate value in a 16813 // data-processing instruction. This can be used in GCC with an "n" 16814 // modifier that prints the negated value, for use with SUB 16815 // instructions. It is not useful otherwise but is implemented for 16816 // compatibility. 16817 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 16818 break; 16819 } else { 16820 // A constant whose negation can be used as an immediate value in a 16821 // data-processing instruction. This can be used in GCC with an "n" 16822 // modifier that prints the negated value, for use with SUB 16823 // instructions. It is not useful otherwise but is implemented for 16824 // compatibility. 16825 if (ARM_AM::getSOImmVal(-CVal) != -1) 16826 break; 16827 } 16828 return; 16829 16830 case 'M': 16831 if (Subtarget->isThumb1Only()) { 16832 // This must be a multiple of 4 between 0 and 1020, for 16833 // ADD sp + immediate. 16834 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 16835 break; 16836 } else { 16837 // A power of two or a constant between 0 and 32. This is used in 16838 // GCC for the shift amount on shifted register operands, but it is 16839 // useful in general for any shift amounts. 16840 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 16841 break; 16842 } 16843 return; 16844 16845 case 'N': 16846 if (Subtarget->isThumb1Only()) { 16847 // This must be a constant between 0 and 31, for shift amounts. 16848 if (CVal >= 0 && CVal <= 31) 16849 break; 16850 } 16851 return; 16852 16853 case 'O': 16854 if (Subtarget->isThumb1Only()) { 16855 // This must be a multiple of 4 between -508 and 508, for 16856 // ADD/SUB sp = sp + immediate. 16857 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 16858 break; 16859 } 16860 return; 16861 } 16862 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 16863 break; 16864 } 16865 16866 if (Result.getNode()) { 16867 Ops.push_back(Result); 16868 return; 16869 } 16870 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16871 } 16872 16873 static RTLIB::Libcall getDivRemLibcall( 16874 const SDNode *N, MVT::SimpleValueType SVT) { 16875 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 16876 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 16877 "Unhandled Opcode in getDivRemLibcall"); 16878 bool isSigned = N->getOpcode() == ISD::SDIVREM || 16879 N->getOpcode() == ISD::SREM; 16880 RTLIB::Libcall LC; 16881 switch (SVT) { 16882 default: llvm_unreachable("Unexpected request for libcall!"); 16883 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 16884 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 16885 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 16886 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 16887 } 16888 return LC; 16889 } 16890 16891 static TargetLowering::ArgListTy getDivRemArgList( 16892 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 16893 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 16894 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 16895 "Unhandled Opcode in getDivRemArgList"); 16896 bool isSigned = N->getOpcode() == ISD::SDIVREM || 16897 N->getOpcode() == ISD::SREM; 16898 TargetLowering::ArgListTy Args; 16899 TargetLowering::ArgListEntry Entry; 16900 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 16901 EVT ArgVT = N->getOperand(i).getValueType(); 16902 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 16903 Entry.Node = N->getOperand(i); 16904 Entry.Ty = ArgTy; 16905 Entry.IsSExt = isSigned; 16906 Entry.IsZExt = !isSigned; 16907 Args.push_back(Entry); 16908 } 16909 if (Subtarget->isTargetWindows() && Args.size() >= 2) 16910 std::swap(Args[0], Args[1]); 16911 return Args; 16912 } 16913 16914 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 16915 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 16916 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 16917 Subtarget->isTargetWindows()) && 16918 "Register-based DivRem lowering only"); 16919 unsigned Opcode = Op->getOpcode(); 16920 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 16921 "Invalid opcode for Div/Rem lowering"); 16922 bool isSigned = (Opcode == ISD::SDIVREM); 16923 EVT VT = Op->getValueType(0); 16924 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 16925 SDLoc dl(Op); 16926 16927 // If the target has hardware divide, use divide + multiply + subtract: 16928 // div = a / b 16929 // rem = a - b * div 16930 // return {div, rem} 16931 // This should be lowered into UDIV/SDIV + MLS later on. 16932 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 16933 : Subtarget->hasDivideInARMMode(); 16934 if (hasDivide && Op->getValueType(0).isSimple() && 16935 Op->getSimpleValueType(0) == MVT::i32) { 16936 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 16937 const SDValue Dividend = Op->getOperand(0); 16938 const SDValue Divisor = Op->getOperand(1); 16939 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 16940 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 16941 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 16942 16943 SDValue Values[2] = {Div, Rem}; 16944 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 16945 } 16946 16947 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 16948 VT.getSimpleVT().SimpleTy); 16949 SDValue InChain = DAG.getEntryNode(); 16950 16951 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 16952 DAG.getContext(), 16953 Subtarget); 16954 16955 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 16956 getPointerTy(DAG.getDataLayout())); 16957 16958 Type *RetTy = StructType::get(Ty, Ty); 16959 16960 if (Subtarget->isTargetWindows()) 16961 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 16962 16963 TargetLowering::CallLoweringInfo CLI(DAG); 16964 CLI.setDebugLoc(dl).setChain(InChain) 16965 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 16966 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 16967 16968 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 16969 return CallInfo.first; 16970 } 16971 16972 // Lowers REM using divmod helpers 16973 // see RTABI section 4.2/4.3 16974 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 16975 // Build return types (div and rem) 16976 std::vector<Type*> RetTyParams; 16977 Type *RetTyElement; 16978 16979 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 16980 default: llvm_unreachable("Unexpected request for libcall!"); 16981 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 16982 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 16983 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 16984 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 16985 } 16986 16987 RetTyParams.push_back(RetTyElement); 16988 RetTyParams.push_back(RetTyElement); 16989 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 16990 Type *RetTy = StructType::get(*DAG.getContext(), ret); 16991 16992 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 16993 SimpleTy); 16994 SDValue InChain = DAG.getEntryNode(); 16995 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 16996 Subtarget); 16997 bool isSigned = N->getOpcode() == ISD::SREM; 16998 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 16999 getPointerTy(DAG.getDataLayout())); 17000 17001 if (Subtarget->isTargetWindows()) 17002 InChain = WinDBZCheckDenominator(DAG, N, InChain); 17003 17004 // Lower call 17005 CallLoweringInfo CLI(DAG); 17006 CLI.setChain(InChain) 17007 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 17008 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 17009 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 17010 17011 // Return second (rem) result operand (first contains div) 17012 SDNode *ResNode = CallResult.first.getNode(); 17013 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 17014 return ResNode->getOperand(1); 17015 } 17016 17017 SDValue 17018 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 17019 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 17020 SDLoc DL(Op); 17021 17022 // Get the inputs. 17023 SDValue Chain = Op.getOperand(0); 17024 SDValue Size = Op.getOperand(1); 17025 17026 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 17027 "no-stack-arg-probe")) { 17028 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 17029 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 17030 Chain = SP.getValue(1); 17031 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 17032 if (Align) 17033 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 17034 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 17035 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 17036 SDValue Ops[2] = { SP, Chain }; 17037 return DAG.getMergeValues(Ops, DL); 17038 } 17039 17040 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 17041 DAG.getConstant(2, DL, MVT::i32)); 17042 17043 SDValue Flag; 17044 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 17045 Flag = Chain.getValue(1); 17046 17047 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 17048 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 17049 17050 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 17051 Chain = NewSP.getValue(1); 17052 17053 SDValue Ops[2] = { NewSP, Chain }; 17054 return DAG.getMergeValues(Ops, DL); 17055 } 17056 17057 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 17058 bool IsStrict = Op->isStrictFPOpcode(); 17059 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 17060 const unsigned DstSz = Op.getValueType().getSizeInBits(); 17061 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 17062 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 17063 "Unexpected type for custom-lowering FP_EXTEND"); 17064 17065 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 17066 "With both FP DP and 16, any FP conversion is legal!"); 17067 17068 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 17069 "With FP16, 16 to 32 conversion is legal!"); 17070 17071 // Converting from 32 -> 64 is valid if we have FP64. 17072 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) { 17073 // FIXME: Remove this when we have strict fp instruction selection patterns 17074 if (IsStrict) { 17075 SDLoc Loc(Op); 17076 SDValue Result = DAG.getNode(ISD::FP_EXTEND, 17077 Loc, Op.getValueType(), SrcVal); 17078 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 17079 } 17080 return Op; 17081 } 17082 17083 // Either we are converting from 16 -> 64, without FP16 and/or 17084 // FP.double-precision or without Armv8-fp. So we must do it in two 17085 // steps. 17086 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 17087 // without FP16. So we must do a function call. 17088 SDLoc Loc(Op); 17089 RTLIB::Libcall LC; 17090 MakeLibCallOptions CallOptions; 17091 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 17092 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) { 17093 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64()); 17094 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32); 17095 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64); 17096 if (Supported) { 17097 if (IsStrict) { 17098 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc, 17099 {DstVT, MVT::Other}, {Chain, SrcVal}); 17100 Chain = SrcVal.getValue(1); 17101 } else { 17102 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal); 17103 } 17104 } else { 17105 LC = RTLIB::getFPEXT(SrcVT, DstVT); 17106 assert(LC != RTLIB::UNKNOWN_LIBCALL && 17107 "Unexpected type for custom-lowering FP_EXTEND"); 17108 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 17109 Loc, Chain); 17110 } 17111 } 17112 17113 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal; 17114 } 17115 17116 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 17117 bool IsStrict = Op->isStrictFPOpcode(); 17118 17119 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 17120 EVT SrcVT = SrcVal.getValueType(); 17121 EVT DstVT = Op.getValueType(); 17122 const unsigned DstSz = Op.getValueType().getSizeInBits(); 17123 const unsigned SrcSz = SrcVT.getSizeInBits(); 17124 (void)DstSz; 17125 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 17126 "Unexpected type for custom-lowering FP_ROUND"); 17127 17128 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 17129 "With both FP DP and 16, any FP conversion is legal!"); 17130 17131 SDLoc Loc(Op); 17132 17133 // Instruction from 32 -> 16 if hasFP16 is valid 17134 if (SrcSz == 32 && Subtarget->hasFP16()) 17135 return Op; 17136 17137 // Lib call from 32 -> 16 / 64 -> [32, 16] 17138 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 17139 assert(LC != RTLIB::UNKNOWN_LIBCALL && 17140 "Unexpected type for custom-lowering FP_ROUND"); 17141 MakeLibCallOptions CallOptions; 17142 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 17143 SDValue Result; 17144 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 17145 Loc, Chain); 17146 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 17147 } 17148 17149 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 17150 SelectionDAG &DAG) const { 17151 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 17152 MVT HalfT = MVT::i32; 17153 SDLoc dl(N); 17154 SDValue Hi, Lo, Tmp; 17155 17156 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 17157 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 17158 return ; 17159 17160 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 17161 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 17162 17163 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 17164 DAG.getConstant(0, dl, HalfT)); 17165 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 17166 DAG.getConstant(1, dl, HalfT)); 17167 17168 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 17169 DAG.getConstant(OpTypeBits - 1, dl, 17170 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 17171 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 17172 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 17173 SDValue(Lo.getNode(), 1)); 17174 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 17175 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 17176 17177 Results.push_back(Lo); 17178 Results.push_back(Hi); 17179 } 17180 17181 bool 17182 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 17183 // The ARM target isn't yet aware of offsets. 17184 return false; 17185 } 17186 17187 bool ARM::isBitFieldInvertedMask(unsigned v) { 17188 if (v == 0xffffffff) 17189 return false; 17190 17191 // there can be 1's on either or both "outsides", all the "inside" 17192 // bits must be 0's 17193 return isShiftedMask_32(~v); 17194 } 17195 17196 /// isFPImmLegal - Returns true if the target can instruction select the 17197 /// specified FP immediate natively. If false, the legalizer will 17198 /// materialize the FP immediate as a load from a constant pool. 17199 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 17200 bool ForCodeSize) const { 17201 if (!Subtarget->hasVFP3Base()) 17202 return false; 17203 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 17204 return ARM_AM::getFP16Imm(Imm) != -1; 17205 if (VT == MVT::f32) 17206 return ARM_AM::getFP32Imm(Imm) != -1; 17207 if (VT == MVT::f64 && Subtarget->hasFP64()) 17208 return ARM_AM::getFP64Imm(Imm) != -1; 17209 return false; 17210 } 17211 17212 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 17213 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 17214 /// specified in the intrinsic calls. 17215 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 17216 const CallInst &I, 17217 MachineFunction &MF, 17218 unsigned Intrinsic) const { 17219 switch (Intrinsic) { 17220 case Intrinsic::arm_neon_vld1: 17221 case Intrinsic::arm_neon_vld2: 17222 case Intrinsic::arm_neon_vld3: 17223 case Intrinsic::arm_neon_vld4: 17224 case Intrinsic::arm_neon_vld2lane: 17225 case Intrinsic::arm_neon_vld3lane: 17226 case Intrinsic::arm_neon_vld4lane: 17227 case Intrinsic::arm_neon_vld2dup: 17228 case Intrinsic::arm_neon_vld3dup: 17229 case Intrinsic::arm_neon_vld4dup: { 17230 Info.opc = ISD::INTRINSIC_W_CHAIN; 17231 // Conservatively set memVT to the entire set of vectors loaded. 17232 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 17233 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 17234 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 17235 Info.ptrVal = I.getArgOperand(0); 17236 Info.offset = 0; 17237 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 17238 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 17239 // volatile loads with NEON intrinsics not supported 17240 Info.flags = MachineMemOperand::MOLoad; 17241 return true; 17242 } 17243 case Intrinsic::arm_neon_vld1x2: 17244 case Intrinsic::arm_neon_vld1x3: 17245 case Intrinsic::arm_neon_vld1x4: { 17246 Info.opc = ISD::INTRINSIC_W_CHAIN; 17247 // Conservatively set memVT to the entire set of vectors loaded. 17248 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 17249 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 17250 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 17251 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 17252 Info.offset = 0; 17253 Info.align.reset(); 17254 // volatile loads with NEON intrinsics not supported 17255 Info.flags = MachineMemOperand::MOLoad; 17256 return true; 17257 } 17258 case Intrinsic::arm_neon_vst1: 17259 case Intrinsic::arm_neon_vst2: 17260 case Intrinsic::arm_neon_vst3: 17261 case Intrinsic::arm_neon_vst4: 17262 case Intrinsic::arm_neon_vst2lane: 17263 case Intrinsic::arm_neon_vst3lane: 17264 case Intrinsic::arm_neon_vst4lane: { 17265 Info.opc = ISD::INTRINSIC_VOID; 17266 // Conservatively set memVT to the entire set of vectors stored. 17267 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 17268 unsigned NumElts = 0; 17269 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 17270 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 17271 if (!ArgTy->isVectorTy()) 17272 break; 17273 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 17274 } 17275 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 17276 Info.ptrVal = I.getArgOperand(0); 17277 Info.offset = 0; 17278 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 17279 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 17280 // volatile stores with NEON intrinsics not supported 17281 Info.flags = MachineMemOperand::MOStore; 17282 return true; 17283 } 17284 case Intrinsic::arm_neon_vst1x2: 17285 case Intrinsic::arm_neon_vst1x3: 17286 case Intrinsic::arm_neon_vst1x4: { 17287 Info.opc = ISD::INTRINSIC_VOID; 17288 // Conservatively set memVT to the entire set of vectors stored. 17289 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 17290 unsigned NumElts = 0; 17291 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 17292 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 17293 if (!ArgTy->isVectorTy()) 17294 break; 17295 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 17296 } 17297 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 17298 Info.ptrVal = I.getArgOperand(0); 17299 Info.offset = 0; 17300 Info.align.reset(); 17301 // volatile stores with NEON intrinsics not supported 17302 Info.flags = MachineMemOperand::MOStore; 17303 return true; 17304 } 17305 case Intrinsic::arm_mve_vld2q: 17306 case Intrinsic::arm_mve_vld4q: { 17307 Info.opc = ISD::INTRINSIC_W_CHAIN; 17308 // Conservatively set memVT to the entire set of vectors loaded. 17309 Type *VecTy = cast<StructType>(I.getType())->getElementType(1); 17310 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4; 17311 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 17312 Info.ptrVal = I.getArgOperand(0); 17313 Info.offset = 0; 17314 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 17315 // volatile loads with MVE intrinsics not supported 17316 Info.flags = MachineMemOperand::MOLoad; 17317 return true; 17318 } 17319 case Intrinsic::arm_mve_vst2q: 17320 case Intrinsic::arm_mve_vst4q: { 17321 Info.opc = ISD::INTRINSIC_VOID; 17322 // Conservatively set memVT to the entire set of vectors stored. 17323 Type *VecTy = I.getArgOperand(1)->getType(); 17324 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4; 17325 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 17326 Info.ptrVal = I.getArgOperand(0); 17327 Info.offset = 0; 17328 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 17329 // volatile stores with MVE intrinsics not supported 17330 Info.flags = MachineMemOperand::MOStore; 17331 return true; 17332 } 17333 case Intrinsic::arm_ldaex: 17334 case Intrinsic::arm_ldrex: { 17335 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 17336 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 17337 Info.opc = ISD::INTRINSIC_W_CHAIN; 17338 Info.memVT = MVT::getVT(PtrTy->getElementType()); 17339 Info.ptrVal = I.getArgOperand(0); 17340 Info.offset = 0; 17341 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 17342 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 17343 return true; 17344 } 17345 case Intrinsic::arm_stlex: 17346 case Intrinsic::arm_strex: { 17347 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 17348 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 17349 Info.opc = ISD::INTRINSIC_W_CHAIN; 17350 Info.memVT = MVT::getVT(PtrTy->getElementType()); 17351 Info.ptrVal = I.getArgOperand(1); 17352 Info.offset = 0; 17353 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 17354 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 17355 return true; 17356 } 17357 case Intrinsic::arm_stlexd: 17358 case Intrinsic::arm_strexd: 17359 Info.opc = ISD::INTRINSIC_W_CHAIN; 17360 Info.memVT = MVT::i64; 17361 Info.ptrVal = I.getArgOperand(2); 17362 Info.offset = 0; 17363 Info.align = Align(8); 17364 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 17365 return true; 17366 17367 case Intrinsic::arm_ldaexd: 17368 case Intrinsic::arm_ldrexd: 17369 Info.opc = ISD::INTRINSIC_W_CHAIN; 17370 Info.memVT = MVT::i64; 17371 Info.ptrVal = I.getArgOperand(0); 17372 Info.offset = 0; 17373 Info.align = Align(8); 17374 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 17375 return true; 17376 17377 default: 17378 break; 17379 } 17380 17381 return false; 17382 } 17383 17384 /// Returns true if it is beneficial to convert a load of a constant 17385 /// to just the constant itself. 17386 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 17387 Type *Ty) const { 17388 assert(Ty->isIntegerTy()); 17389 17390 unsigned Bits = Ty->getPrimitiveSizeInBits(); 17391 if (Bits == 0 || Bits > 32) 17392 return false; 17393 return true; 17394 } 17395 17396 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 17397 unsigned Index) const { 17398 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 17399 return false; 17400 17401 return (Index == 0 || Index == ResVT.getVectorNumElements()); 17402 } 17403 17404 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 17405 ARM_MB::MemBOpt Domain) const { 17406 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 17407 17408 // First, if the target has no DMB, see what fallback we can use. 17409 if (!Subtarget->hasDataBarrier()) { 17410 // Some ARMv6 cpus can support data barriers with an mcr instruction. 17411 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 17412 // here. 17413 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 17414 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 17415 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 17416 Builder.getInt32(0), Builder.getInt32(7), 17417 Builder.getInt32(10), Builder.getInt32(5)}; 17418 return Builder.CreateCall(MCR, args); 17419 } else { 17420 // Instead of using barriers, atomic accesses on these subtargets use 17421 // libcalls. 17422 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 17423 } 17424 } else { 17425 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 17426 // Only a full system barrier exists in the M-class architectures. 17427 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 17428 Constant *CDomain = Builder.getInt32(Domain); 17429 return Builder.CreateCall(DMB, CDomain); 17430 } 17431 } 17432 17433 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 17434 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 17435 Instruction *Inst, 17436 AtomicOrdering Ord) const { 17437 switch (Ord) { 17438 case AtomicOrdering::NotAtomic: 17439 case AtomicOrdering::Unordered: 17440 llvm_unreachable("Invalid fence: unordered/non-atomic"); 17441 case AtomicOrdering::Monotonic: 17442 case AtomicOrdering::Acquire: 17443 return nullptr; // Nothing to do 17444 case AtomicOrdering::SequentiallyConsistent: 17445 if (!Inst->hasAtomicStore()) 17446 return nullptr; // Nothing to do 17447 LLVM_FALLTHROUGH; 17448 case AtomicOrdering::Release: 17449 case AtomicOrdering::AcquireRelease: 17450 if (Subtarget->preferISHSTBarriers()) 17451 return makeDMB(Builder, ARM_MB::ISHST); 17452 // FIXME: add a comment with a link to documentation justifying this. 17453 else 17454 return makeDMB(Builder, ARM_MB::ISH); 17455 } 17456 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 17457 } 17458 17459 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 17460 Instruction *Inst, 17461 AtomicOrdering Ord) const { 17462 switch (Ord) { 17463 case AtomicOrdering::NotAtomic: 17464 case AtomicOrdering::Unordered: 17465 llvm_unreachable("Invalid fence: unordered/not-atomic"); 17466 case AtomicOrdering::Monotonic: 17467 case AtomicOrdering::Release: 17468 return nullptr; // Nothing to do 17469 case AtomicOrdering::Acquire: 17470 case AtomicOrdering::AcquireRelease: 17471 case AtomicOrdering::SequentiallyConsistent: 17472 return makeDMB(Builder, ARM_MB::ISH); 17473 } 17474 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 17475 } 17476 17477 // Loads and stores less than 64-bits are already atomic; ones above that 17478 // are doomed anyway, so defer to the default libcall and blame the OS when 17479 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 17480 // anything for those. 17481 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 17482 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 17483 return (Size == 64) && !Subtarget->isMClass(); 17484 } 17485 17486 // Loads and stores less than 64-bits are already atomic; ones above that 17487 // are doomed anyway, so defer to the default libcall and blame the OS when 17488 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 17489 // anything for those. 17490 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 17491 // guarantee, see DDI0406C ARM architecture reference manual, 17492 // sections A8.8.72-74 LDRD) 17493 TargetLowering::AtomicExpansionKind 17494 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 17495 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 17496 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 17497 : AtomicExpansionKind::None; 17498 } 17499 17500 // For the real atomic operations, we have ldrex/strex up to 32 bits, 17501 // and up to 64 bits on the non-M profiles 17502 TargetLowering::AtomicExpansionKind 17503 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 17504 if (AI->isFloatingPointOperation()) 17505 return AtomicExpansionKind::CmpXChg; 17506 17507 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 17508 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 17509 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 17510 ? AtomicExpansionKind::LLSC 17511 : AtomicExpansionKind::None; 17512 } 17513 17514 TargetLowering::AtomicExpansionKind 17515 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 17516 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 17517 // implement cmpxchg without spilling. If the address being exchanged is also 17518 // on the stack and close enough to the spill slot, this can lead to a 17519 // situation where the monitor always gets cleared and the atomic operation 17520 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 17521 bool HasAtomicCmpXchg = 17522 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 17523 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 17524 return AtomicExpansionKind::LLSC; 17525 return AtomicExpansionKind::None; 17526 } 17527 17528 bool ARMTargetLowering::shouldInsertFencesForAtomic( 17529 const Instruction *I) const { 17530 return InsertFencesForAtomic; 17531 } 17532 17533 // This has so far only been implemented for MachO. 17534 bool ARMTargetLowering::useLoadStackGuardNode() const { 17535 return Subtarget->isTargetMachO(); 17536 } 17537 17538 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 17539 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 17540 return TargetLowering::insertSSPDeclarations(M); 17541 17542 // MSVC CRT has a global variable holding security cookie. 17543 M.getOrInsertGlobal("__security_cookie", 17544 Type::getInt8PtrTy(M.getContext())); 17545 17546 // MSVC CRT has a function to validate security cookie. 17547 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 17548 "__security_check_cookie", Type::getVoidTy(M.getContext()), 17549 Type::getInt8PtrTy(M.getContext())); 17550 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 17551 F->addAttribute(1, Attribute::AttrKind::InReg); 17552 } 17553 17554 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 17555 // MSVC CRT has a global variable holding security cookie. 17556 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 17557 return M.getGlobalVariable("__security_cookie"); 17558 return TargetLowering::getSDagStackGuard(M); 17559 } 17560 17561 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 17562 // MSVC CRT has a function to validate security cookie. 17563 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 17564 return M.getFunction("__security_check_cookie"); 17565 return TargetLowering::getSSPStackGuardCheck(M); 17566 } 17567 17568 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 17569 unsigned &Cost) const { 17570 // If we do not have NEON, vector types are not natively supported. 17571 if (!Subtarget->hasNEON()) 17572 return false; 17573 17574 // Floating point values and vector values map to the same register file. 17575 // Therefore, although we could do a store extract of a vector type, this is 17576 // better to leave at float as we have more freedom in the addressing mode for 17577 // those. 17578 if (VectorTy->isFPOrFPVectorTy()) 17579 return false; 17580 17581 // If the index is unknown at compile time, this is very expensive to lower 17582 // and it is not possible to combine the store with the extract. 17583 if (!isa<ConstantInt>(Idx)) 17584 return false; 17585 17586 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 17587 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 17588 // We can do a store + vector extract on any vector that fits perfectly in a D 17589 // or Q register. 17590 if (BitWidth == 64 || BitWidth == 128) { 17591 Cost = 0; 17592 return true; 17593 } 17594 return false; 17595 } 17596 17597 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 17598 return Subtarget->hasV6T2Ops(); 17599 } 17600 17601 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 17602 return Subtarget->hasV6T2Ops(); 17603 } 17604 17605 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 17606 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows(); 17607 } 17608 17609 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 17610 AtomicOrdering Ord) const { 17611 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 17612 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 17613 bool IsAcquire = isAcquireOrStronger(Ord); 17614 17615 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 17616 // intrinsic must return {i32, i32} and we have to recombine them into a 17617 // single i64 here. 17618 if (ValTy->getPrimitiveSizeInBits() == 64) { 17619 Intrinsic::ID Int = 17620 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 17621 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 17622 17623 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 17624 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 17625 17626 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 17627 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 17628 if (!Subtarget->isLittle()) 17629 std::swap (Lo, Hi); 17630 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 17631 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 17632 return Builder.CreateOr( 17633 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 17634 } 17635 17636 Type *Tys[] = { Addr->getType() }; 17637 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 17638 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 17639 17640 return Builder.CreateTruncOrBitCast( 17641 Builder.CreateCall(Ldrex, Addr), 17642 cast<PointerType>(Addr->getType())->getElementType()); 17643 } 17644 17645 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 17646 IRBuilder<> &Builder) const { 17647 if (!Subtarget->hasV7Ops()) 17648 return; 17649 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 17650 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 17651 } 17652 17653 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 17654 Value *Addr, 17655 AtomicOrdering Ord) const { 17656 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 17657 bool IsRelease = isReleaseOrStronger(Ord); 17658 17659 // Since the intrinsics must have legal type, the i64 intrinsics take two 17660 // parameters: "i32, i32". We must marshal Val into the appropriate form 17661 // before the call. 17662 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 17663 Intrinsic::ID Int = 17664 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 17665 Function *Strex = Intrinsic::getDeclaration(M, Int); 17666 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 17667 17668 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 17669 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 17670 if (!Subtarget->isLittle()) 17671 std::swap(Lo, Hi); 17672 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 17673 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 17674 } 17675 17676 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 17677 Type *Tys[] = { Addr->getType() }; 17678 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 17679 17680 return Builder.CreateCall( 17681 Strex, {Builder.CreateZExtOrBitCast( 17682 Val, Strex->getFunctionType()->getParamType(0)), 17683 Addr}); 17684 } 17685 17686 17687 bool ARMTargetLowering::alignLoopsWithOptSize() const { 17688 return Subtarget->isMClass(); 17689 } 17690 17691 /// A helper function for determining the number of interleaved accesses we 17692 /// will generate when lowering accesses of the given type. 17693 unsigned 17694 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 17695 const DataLayout &DL) const { 17696 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 17697 } 17698 17699 bool ARMTargetLowering::isLegalInterleavedAccessType( 17700 unsigned Factor, VectorType *VecTy, const DataLayout &DL) const { 17701 17702 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 17703 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 17704 17705 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) 17706 return false; 17707 17708 // Ensure the vector doesn't have f16 elements. Even though we could do an 17709 // i16 vldN, we can't hold the f16 vectors and will end up converting via 17710 // f32. 17711 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy()) 17712 return false; 17713 if (Subtarget->hasMVEIntegerOps() && Factor == 3) 17714 return false; 17715 17716 // Ensure the number of vector elements is greater than 1. 17717 if (VecTy->getNumElements() < 2) 17718 return false; 17719 17720 // Ensure the element type is legal. 17721 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 17722 return false; 17723 17724 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 17725 // 128 will be split into multiple interleaved accesses. 17726 if (Subtarget->hasNEON() && VecSize == 64) 17727 return true; 17728 return VecSize % 128 == 0; 17729 } 17730 17731 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const { 17732 if (Subtarget->hasNEON()) 17733 return 4; 17734 if (Subtarget->hasMVEIntegerOps()) 17735 return MVEMaxSupportedInterleaveFactor; 17736 return TargetLoweringBase::getMaxSupportedInterleaveFactor(); 17737 } 17738 17739 /// Lower an interleaved load into a vldN intrinsic. 17740 /// 17741 /// E.g. Lower an interleaved load (Factor = 2): 17742 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 17743 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 17744 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 17745 /// 17746 /// Into: 17747 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 17748 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 17749 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 17750 bool ARMTargetLowering::lowerInterleavedLoad( 17751 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 17752 ArrayRef<unsigned> Indices, unsigned Factor) const { 17753 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 17754 "Invalid interleave factor"); 17755 assert(!Shuffles.empty() && "Empty shufflevector input"); 17756 assert(Shuffles.size() == Indices.size() && 17757 "Unmatched number of shufflevectors and indices"); 17758 17759 VectorType *VecTy = Shuffles[0]->getType(); 17760 Type *EltTy = VecTy->getElementType(); 17761 17762 const DataLayout &DL = LI->getModule()->getDataLayout(); 17763 17764 // Skip if we do not have NEON and skip illegal vector types. We can 17765 // "legalize" wide vector types into multiple interleaved accesses as long as 17766 // the vector types are divisible by 128. 17767 if (!isLegalInterleavedAccessType(Factor, VecTy, DL)) 17768 return false; 17769 17770 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 17771 17772 // A pointer vector can not be the return type of the ldN intrinsics. Need to 17773 // load integer vectors first and then convert to pointer vectors. 17774 if (EltTy->isPointerTy()) 17775 VecTy = VectorType::get(DL.getIntPtrType(EltTy), VecTy->getNumElements()); 17776 17777 IRBuilder<> Builder(LI); 17778 17779 // The base address of the load. 17780 Value *BaseAddr = LI->getPointerOperand(); 17781 17782 if (NumLoads > 1) { 17783 // If we're going to generate more than one load, reset the sub-vector type 17784 // to something legal. 17785 VecTy = VectorType::get(VecTy->getElementType(), 17786 VecTy->getNumElements() / NumLoads); 17787 17788 // We will compute the pointer operand of each load from the original base 17789 // address using GEPs. Cast the base address to a pointer to the scalar 17790 // element type. 17791 BaseAddr = Builder.CreateBitCast( 17792 BaseAddr, 17793 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 17794 } 17795 17796 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 17797 17798 auto createLoadIntrinsic = [&](Value *BaseAddr) { 17799 if (Subtarget->hasNEON()) { 17800 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 17801 Type *Tys[] = {VecTy, Int8Ptr}; 17802 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 17803 Intrinsic::arm_neon_vld3, 17804 Intrinsic::arm_neon_vld4}; 17805 Function *VldnFunc = 17806 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 17807 17808 SmallVector<Value *, 2> Ops; 17809 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 17810 Ops.push_back(Builder.getInt32(LI->getAlignment())); 17811 17812 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 17813 } else { 17814 assert((Factor == 2 || Factor == 4) && 17815 "expected interleave factor of 2 or 4 for MVE"); 17816 Intrinsic::ID LoadInts = 17817 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q; 17818 Type *VecEltTy = 17819 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()); 17820 Type *Tys[] = {VecTy, VecEltTy}; 17821 Function *VldnFunc = 17822 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys); 17823 17824 SmallVector<Value *, 2> Ops; 17825 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy)); 17826 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 17827 } 17828 }; 17829 17830 // Holds sub-vectors extracted from the load intrinsic return values. The 17831 // sub-vectors are associated with the shufflevector instructions they will 17832 // replace. 17833 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 17834 17835 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 17836 // If we're generating more than one load, compute the base address of 17837 // subsequent loads as an offset from the previous. 17838 if (LoadCount > 0) 17839 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr, 17840 VecTy->getNumElements() * Factor); 17841 17842 CallInst *VldN = createLoadIntrinsic(BaseAddr); 17843 17844 // Replace uses of each shufflevector with the corresponding vector loaded 17845 // by ldN. 17846 for (unsigned i = 0; i < Shuffles.size(); i++) { 17847 ShuffleVectorInst *SV = Shuffles[i]; 17848 unsigned Index = Indices[i]; 17849 17850 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 17851 17852 // Convert the integer vector to pointer vector if the element is pointer. 17853 if (EltTy->isPointerTy()) 17854 SubVec = Builder.CreateIntToPtr( 17855 SubVec, VectorType::get(SV->getType()->getElementType(), 17856 VecTy->getNumElements())); 17857 17858 SubVecs[SV].push_back(SubVec); 17859 } 17860 } 17861 17862 // Replace uses of the shufflevector instructions with the sub-vectors 17863 // returned by the load intrinsic. If a shufflevector instruction is 17864 // associated with more than one sub-vector, those sub-vectors will be 17865 // concatenated into a single wide vector. 17866 for (ShuffleVectorInst *SVI : Shuffles) { 17867 auto &SubVec = SubVecs[SVI]; 17868 auto *WideVec = 17869 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 17870 SVI->replaceAllUsesWith(WideVec); 17871 } 17872 17873 return true; 17874 } 17875 17876 /// Lower an interleaved store into a vstN intrinsic. 17877 /// 17878 /// E.g. Lower an interleaved store (Factor = 3): 17879 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 17880 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 17881 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 17882 /// 17883 /// Into: 17884 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 17885 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 17886 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 17887 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 17888 /// 17889 /// Note that the new shufflevectors will be removed and we'll only generate one 17890 /// vst3 instruction in CodeGen. 17891 /// 17892 /// Example for a more general valid mask (Factor 3). Lower: 17893 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 17894 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 17895 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 17896 /// 17897 /// Into: 17898 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 17899 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 17900 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 17901 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 17902 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 17903 ShuffleVectorInst *SVI, 17904 unsigned Factor) const { 17905 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 17906 "Invalid interleave factor"); 17907 17908 VectorType *VecTy = SVI->getType(); 17909 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 17910 17911 unsigned LaneLen = VecTy->getNumElements() / Factor; 17912 Type *EltTy = VecTy->getElementType(); 17913 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 17914 17915 const DataLayout &DL = SI->getModule()->getDataLayout(); 17916 17917 // Skip if we do not have NEON and skip illegal vector types. We can 17918 // "legalize" wide vector types into multiple interleaved accesses as long as 17919 // the vector types are divisible by 128. 17920 if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL)) 17921 return false; 17922 17923 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 17924 17925 Value *Op0 = SVI->getOperand(0); 17926 Value *Op1 = SVI->getOperand(1); 17927 IRBuilder<> Builder(SI); 17928 17929 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 17930 // vectors to integer vectors. 17931 if (EltTy->isPointerTy()) { 17932 Type *IntTy = DL.getIntPtrType(EltTy); 17933 17934 // Convert to the corresponding integer vector. 17935 Type *IntVecTy = VectorType::get( 17936 IntTy, cast<VectorType>(Op0->getType())->getNumElements()); 17937 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 17938 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 17939 17940 SubVecTy = VectorType::get(IntTy, LaneLen); 17941 } 17942 17943 // The base address of the store. 17944 Value *BaseAddr = SI->getPointerOperand(); 17945 17946 if (NumStores > 1) { 17947 // If we're going to generate more than one store, reset the lane length 17948 // and sub-vector type to something legal. 17949 LaneLen /= NumStores; 17950 SubVecTy = VectorType::get(SubVecTy->getElementType(), LaneLen); 17951 17952 // We will compute the pointer operand of each store from the original base 17953 // address using GEPs. Cast the base address to a pointer to the scalar 17954 // element type. 17955 BaseAddr = Builder.CreateBitCast( 17956 BaseAddr, 17957 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 17958 } 17959 17960 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 17961 17962 auto Mask = SVI->getShuffleMask(); 17963 17964 auto createStoreIntrinsic = [&](Value *BaseAddr, 17965 SmallVectorImpl<Value *> &Shuffles) { 17966 if (Subtarget->hasNEON()) { 17967 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 17968 Intrinsic::arm_neon_vst3, 17969 Intrinsic::arm_neon_vst4}; 17970 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 17971 Type *Tys[] = {Int8Ptr, SubVecTy}; 17972 17973 Function *VstNFunc = Intrinsic::getDeclaration( 17974 SI->getModule(), StoreInts[Factor - 2], Tys); 17975 17976 SmallVector<Value *, 6> Ops; 17977 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 17978 for (auto S : Shuffles) 17979 Ops.push_back(S); 17980 Ops.push_back(Builder.getInt32(SI->getAlignment())); 17981 Builder.CreateCall(VstNFunc, Ops); 17982 } else { 17983 assert((Factor == 2 || Factor == 4) && 17984 "expected interleave factor of 2 or 4 for MVE"); 17985 Intrinsic::ID StoreInts = 17986 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q; 17987 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo( 17988 SI->getPointerAddressSpace()); 17989 Type *Tys[] = {EltPtrTy, SubVecTy}; 17990 Function *VstNFunc = 17991 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys); 17992 17993 SmallVector<Value *, 6> Ops; 17994 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy)); 17995 for (auto S : Shuffles) 17996 Ops.push_back(S); 17997 for (unsigned F = 0; F < Factor; F++) { 17998 Ops.push_back(Builder.getInt32(F)); 17999 Builder.CreateCall(VstNFunc, Ops); 18000 Ops.pop_back(); 18001 } 18002 } 18003 }; 18004 18005 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 18006 // If we generating more than one store, we compute the base address of 18007 // subsequent stores as an offset from the previous. 18008 if (StoreCount > 0) 18009 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 18010 BaseAddr, LaneLen * Factor); 18011 18012 SmallVector<Value *, 4> Shuffles; 18013 18014 // Split the shufflevector operands into sub vectors for the new vstN call. 18015 for (unsigned i = 0; i < Factor; i++) { 18016 unsigned IdxI = StoreCount * LaneLen * Factor + i; 18017 if (Mask[IdxI] >= 0) { 18018 Shuffles.push_back(Builder.CreateShuffleVector( 18019 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 18020 } else { 18021 unsigned StartMask = 0; 18022 for (unsigned j = 1; j < LaneLen; j++) { 18023 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 18024 if (Mask[IdxJ * Factor + IdxI] >= 0) { 18025 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 18026 break; 18027 } 18028 } 18029 // Note: If all elements in a chunk are undefs, StartMask=0! 18030 // Note: Filling undef gaps with random elements is ok, since 18031 // those elements were being written anyway (with undefs). 18032 // In the case of all undefs we're defaulting to using elems from 0 18033 // Note: StartMask cannot be negative, it's checked in 18034 // isReInterleaveMask 18035 Shuffles.push_back(Builder.CreateShuffleVector( 18036 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 18037 } 18038 } 18039 18040 createStoreIntrinsic(BaseAddr, Shuffles); 18041 } 18042 return true; 18043 } 18044 18045 enum HABaseType { 18046 HA_UNKNOWN = 0, 18047 HA_FLOAT, 18048 HA_DOUBLE, 18049 HA_VECT64, 18050 HA_VECT128 18051 }; 18052 18053 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 18054 uint64_t &Members) { 18055 if (auto *ST = dyn_cast<StructType>(Ty)) { 18056 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 18057 uint64_t SubMembers = 0; 18058 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 18059 return false; 18060 Members += SubMembers; 18061 } 18062 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 18063 uint64_t SubMembers = 0; 18064 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 18065 return false; 18066 Members += SubMembers * AT->getNumElements(); 18067 } else if (Ty->isFloatTy()) { 18068 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 18069 return false; 18070 Members = 1; 18071 Base = HA_FLOAT; 18072 } else if (Ty->isDoubleTy()) { 18073 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 18074 return false; 18075 Members = 1; 18076 Base = HA_DOUBLE; 18077 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 18078 Members = 1; 18079 switch (Base) { 18080 case HA_FLOAT: 18081 case HA_DOUBLE: 18082 return false; 18083 case HA_VECT64: 18084 return VT->getBitWidth() == 64; 18085 case HA_VECT128: 18086 return VT->getBitWidth() == 128; 18087 case HA_UNKNOWN: 18088 switch (VT->getBitWidth()) { 18089 case 64: 18090 Base = HA_VECT64; 18091 return true; 18092 case 128: 18093 Base = HA_VECT128; 18094 return true; 18095 default: 18096 return false; 18097 } 18098 } 18099 } 18100 18101 return (Members > 0 && Members <= 4); 18102 } 18103 18104 /// Return the correct alignment for the current calling convention. 18105 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 18106 DataLayout DL) const { 18107 const Align ABITypeAlign(DL.getABITypeAlignment(ArgTy)); 18108 if (!ArgTy->isVectorTy()) 18109 return ABITypeAlign; 18110 18111 // Avoid over-aligning vector parameters. It would require realigning the 18112 // stack and waste space for no real benefit. 18113 return std::min(ABITypeAlign, DL.getStackAlignment()); 18114 } 18115 18116 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 18117 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 18118 /// passing according to AAPCS rules. 18119 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 18120 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 18121 if (getEffectiveCallingConv(CallConv, isVarArg) != 18122 CallingConv::ARM_AAPCS_VFP) 18123 return false; 18124 18125 HABaseType Base = HA_UNKNOWN; 18126 uint64_t Members = 0; 18127 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 18128 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 18129 18130 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 18131 return IsHA || IsIntArray; 18132 } 18133 18134 Register ARMTargetLowering::getExceptionPointerRegister( 18135 const Constant *PersonalityFn) const { 18136 // Platforms which do not use SjLj EH may return values in these registers 18137 // via the personality function. 18138 return Subtarget->useSjLjEH() ? Register() : ARM::R0; 18139 } 18140 18141 Register ARMTargetLowering::getExceptionSelectorRegister( 18142 const Constant *PersonalityFn) const { 18143 // Platforms which do not use SjLj EH may return values in these registers 18144 // via the personality function. 18145 return Subtarget->useSjLjEH() ? Register() : ARM::R1; 18146 } 18147 18148 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 18149 // Update IsSplitCSR in ARMFunctionInfo. 18150 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 18151 AFI->setIsSplitCSR(true); 18152 } 18153 18154 void ARMTargetLowering::insertCopiesSplitCSR( 18155 MachineBasicBlock *Entry, 18156 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 18157 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 18158 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 18159 if (!IStart) 18160 return; 18161 18162 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 18163 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 18164 MachineBasicBlock::iterator MBBI = Entry->begin(); 18165 for (const MCPhysReg *I = IStart; *I; ++I) { 18166 const TargetRegisterClass *RC = nullptr; 18167 if (ARM::GPRRegClass.contains(*I)) 18168 RC = &ARM::GPRRegClass; 18169 else if (ARM::DPRRegClass.contains(*I)) 18170 RC = &ARM::DPRRegClass; 18171 else 18172 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 18173 18174 Register NewVR = MRI->createVirtualRegister(RC); 18175 // Create copy from CSR to a virtual register. 18176 // FIXME: this currently does not emit CFI pseudo-instructions, it works 18177 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 18178 // nounwind. If we want to generalize this later, we may need to emit 18179 // CFI pseudo-instructions. 18180 assert(Entry->getParent()->getFunction().hasFnAttribute( 18181 Attribute::NoUnwind) && 18182 "Function should be nounwind in insertCopiesSplitCSR!"); 18183 Entry->addLiveIn(*I); 18184 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 18185 .addReg(*I); 18186 18187 // Insert the copy-back instructions right before the terminator. 18188 for (auto *Exit : Exits) 18189 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 18190 TII->get(TargetOpcode::COPY), *I) 18191 .addReg(NewVR); 18192 } 18193 } 18194 18195 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 18196 MF.getFrameInfo().computeMaxCallFrameSize(MF); 18197 TargetLoweringBase::finalizeLowering(MF); 18198 } 18199