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::i32, Custom); 721 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 722 723 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 724 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 725 } 726 727 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 728 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 729 setTruncStoreAction(VT, InnerVT, Expand); 730 addAllExtLoads(VT, InnerVT, Expand); 731 } 732 733 setOperationAction(ISD::MULHS, VT, Expand); 734 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 735 setOperationAction(ISD::MULHU, VT, Expand); 736 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 737 738 setOperationAction(ISD::BSWAP, VT, Expand); 739 } 740 741 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 742 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 743 744 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 745 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 746 747 if (Subtarget->hasMVEIntegerOps()) 748 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 749 750 // Combine low-overhead loop intrinsics so that we can lower i1 types. 751 if (Subtarget->hasLOB()) { 752 setTargetDAGCombine(ISD::BRCOND); 753 setTargetDAGCombine(ISD::BR_CC); 754 } 755 756 if (Subtarget->hasNEON()) { 757 addDRTypeForNEON(MVT::v2f32); 758 addDRTypeForNEON(MVT::v8i8); 759 addDRTypeForNEON(MVT::v4i16); 760 addDRTypeForNEON(MVT::v2i32); 761 addDRTypeForNEON(MVT::v1i64); 762 763 addQRTypeForNEON(MVT::v4f32); 764 addQRTypeForNEON(MVT::v2f64); 765 addQRTypeForNEON(MVT::v16i8); 766 addQRTypeForNEON(MVT::v8i16); 767 addQRTypeForNEON(MVT::v4i32); 768 addQRTypeForNEON(MVT::v2i64); 769 770 if (Subtarget->hasFullFP16()) { 771 addQRTypeForNEON(MVT::v8f16); 772 addDRTypeForNEON(MVT::v4f16); 773 } 774 } 775 776 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 777 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 778 // none of Neon, MVE or VFP supports any arithmetic operations on it. 779 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 780 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 781 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 782 // FIXME: Code duplication: FDIV and FREM are expanded always, see 783 // ARMTargetLowering::addTypeForNEON method for details. 784 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 785 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 786 // FIXME: Create unittest. 787 // In another words, find a way when "copysign" appears in DAG with vector 788 // operands. 789 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 790 // FIXME: Code duplication: SETCC has custom operation action, see 791 // ARMTargetLowering::addTypeForNEON method for details. 792 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 793 // FIXME: Create unittest for FNEG and for FABS. 794 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 795 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 796 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 797 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 798 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 799 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 800 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 801 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 802 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 803 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 804 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 805 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 806 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 807 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 808 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 809 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 810 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 811 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 812 } 813 814 if (Subtarget->hasNEON()) { 815 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 816 // supported for v4f32. 817 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 818 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 819 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 820 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 821 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 822 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 823 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 824 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 825 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 826 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 827 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 828 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 829 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 830 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 831 832 // Mark v2f32 intrinsics. 833 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 834 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 835 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 836 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 837 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 838 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 839 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 840 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 841 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 842 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 843 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 844 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 845 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 846 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 847 848 // Neon does not support some operations on v1i64 and v2i64 types. 849 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 850 // Custom handling for some quad-vector types to detect VMULL. 851 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 852 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 853 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 854 // Custom handling for some vector types to avoid expensive expansions 855 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 856 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 857 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 858 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 859 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 860 // a destination type that is wider than the source, and nor does 861 // it have a FP_TO_[SU]INT instruction with a narrower destination than 862 // source. 863 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 864 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 865 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 866 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 867 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 868 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 869 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 870 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 871 872 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 873 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 874 875 // NEON does not have single instruction CTPOP for vectors with element 876 // types wider than 8-bits. However, custom lowering can leverage the 877 // v8i8/v16i8 vcnt instruction. 878 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 879 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 880 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 881 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 882 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 883 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 884 885 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 886 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 887 888 // NEON does not have single instruction CTTZ for vectors. 889 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 890 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 891 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 892 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 893 894 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 895 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 896 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 897 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 898 899 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 900 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 901 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 902 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 903 904 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 905 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 906 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 907 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 908 909 // NEON only has FMA instructions as of VFP4. 910 if (!Subtarget->hasVFP4Base()) { 911 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 912 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 913 } 914 915 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 916 setTargetDAGCombine(ISD::SHL); 917 setTargetDAGCombine(ISD::SRL); 918 setTargetDAGCombine(ISD::SRA); 919 setTargetDAGCombine(ISD::FP_TO_SINT); 920 setTargetDAGCombine(ISD::FP_TO_UINT); 921 setTargetDAGCombine(ISD::FDIV); 922 setTargetDAGCombine(ISD::LOAD); 923 924 // It is legal to extload from v4i8 to v4i16 or v4i32. 925 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 926 MVT::v2i32}) { 927 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 928 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 929 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 930 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 931 } 932 } 933 } 934 935 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 936 setTargetDAGCombine(ISD::BUILD_VECTOR); 937 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 938 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 939 setTargetDAGCombine(ISD::STORE); 940 setTargetDAGCombine(ISD::SIGN_EXTEND); 941 setTargetDAGCombine(ISD::ZERO_EXTEND); 942 setTargetDAGCombine(ISD::ANY_EXTEND); 943 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 944 setTargetDAGCombine(ISD::INTRINSIC_VOID); 945 } 946 947 if (!Subtarget->hasFP64()) { 948 // When targeting a floating-point unit with only single-precision 949 // operations, f64 is legal for the few double-precision instructions which 950 // are present However, no double-precision operations other than moves, 951 // loads and stores are provided by the hardware. 952 setOperationAction(ISD::FADD, MVT::f64, Expand); 953 setOperationAction(ISD::FSUB, MVT::f64, Expand); 954 setOperationAction(ISD::FMUL, MVT::f64, Expand); 955 setOperationAction(ISD::FMA, MVT::f64, Expand); 956 setOperationAction(ISD::FDIV, MVT::f64, Expand); 957 setOperationAction(ISD::FREM, MVT::f64, Expand); 958 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 959 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 960 setOperationAction(ISD::FNEG, MVT::f64, Expand); 961 setOperationAction(ISD::FABS, MVT::f64, Expand); 962 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 963 setOperationAction(ISD::FSIN, MVT::f64, Expand); 964 setOperationAction(ISD::FCOS, MVT::f64, Expand); 965 setOperationAction(ISD::FPOW, MVT::f64, Expand); 966 setOperationAction(ISD::FLOG, MVT::f64, Expand); 967 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 968 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 969 setOperationAction(ISD::FEXP, MVT::f64, Expand); 970 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 971 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 972 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 973 setOperationAction(ISD::FRINT, MVT::f64, Expand); 974 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 975 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 976 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 977 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 978 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 979 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 980 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 981 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 982 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 983 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 984 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 985 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom); 986 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom); 987 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 988 } 989 990 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 991 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 992 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom); 993 if (Subtarget->hasFullFP16()) { 994 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 995 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom); 996 } 997 } 998 999 if (!Subtarget->hasFP16()) { 1000 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 1001 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom); 1002 } 1003 1004 computeRegisterProperties(Subtarget->getRegisterInfo()); 1005 1006 // ARM does not have floating-point extending loads. 1007 for (MVT VT : MVT::fp_valuetypes()) { 1008 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 1009 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 1010 } 1011 1012 // ... or truncating stores 1013 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 1014 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 1015 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 1016 1017 // ARM does not have i1 sign extending load. 1018 for (MVT VT : MVT::integer_valuetypes()) 1019 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 1020 1021 // ARM supports all 4 flavors of integer indexed load / store. 1022 if (!Subtarget->isThumb1Only()) { 1023 for (unsigned im = (unsigned)ISD::PRE_INC; 1024 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1025 setIndexedLoadAction(im, MVT::i1, Legal); 1026 setIndexedLoadAction(im, MVT::i8, Legal); 1027 setIndexedLoadAction(im, MVT::i16, Legal); 1028 setIndexedLoadAction(im, MVT::i32, Legal); 1029 setIndexedStoreAction(im, MVT::i1, Legal); 1030 setIndexedStoreAction(im, MVT::i8, Legal); 1031 setIndexedStoreAction(im, MVT::i16, Legal); 1032 setIndexedStoreAction(im, MVT::i32, Legal); 1033 } 1034 } else { 1035 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 1036 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 1037 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 1038 } 1039 1040 setOperationAction(ISD::SADDO, MVT::i32, Custom); 1041 setOperationAction(ISD::UADDO, MVT::i32, Custom); 1042 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 1043 setOperationAction(ISD::USUBO, MVT::i32, Custom); 1044 1045 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 1046 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 1047 if (Subtarget->hasDSP()) { 1048 setOperationAction(ISD::SADDSAT, MVT::i8, Custom); 1049 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom); 1050 setOperationAction(ISD::SADDSAT, MVT::i16, Custom); 1051 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom); 1052 } 1053 if (Subtarget->hasBaseDSP()) { 1054 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 1055 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 1056 } 1057 1058 // i64 operation support. 1059 setOperationAction(ISD::MUL, MVT::i64, Expand); 1060 setOperationAction(ISD::MULHU, MVT::i32, Expand); 1061 if (Subtarget->isThumb1Only()) { 1062 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 1063 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 1064 } 1065 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 1066 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 1067 setOperationAction(ISD::MULHS, MVT::i32, Expand); 1068 1069 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 1070 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 1071 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 1072 setOperationAction(ISD::SRL, MVT::i64, Custom); 1073 setOperationAction(ISD::SRA, MVT::i64, Custom); 1074 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 1075 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 1076 1077 // MVE lowers 64 bit shifts to lsll and lsrl 1078 // assuming that ISD::SRL and SRA of i64 are already marked custom 1079 if (Subtarget->hasMVEIntegerOps()) 1080 setOperationAction(ISD::SHL, MVT::i64, Custom); 1081 1082 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1083 if (Subtarget->isThumb1Only()) { 1084 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1085 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1086 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1087 } 1088 1089 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1090 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1091 1092 // ARM does not have ROTL. 1093 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1094 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1095 setOperationAction(ISD::ROTL, VT, Expand); 1096 setOperationAction(ISD::ROTR, VT, Expand); 1097 } 1098 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1099 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1100 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1101 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1102 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1103 } 1104 1105 // @llvm.readcyclecounter requires the Performance Monitors extension. 1106 // Default to the 0 expansion on unsupported platforms. 1107 // FIXME: Technically there are older ARM CPUs that have 1108 // implementation-specific ways of obtaining this information. 1109 if (Subtarget->hasPerfMon()) 1110 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1111 1112 // Only ARMv6 has BSWAP. 1113 if (!Subtarget->hasV6Ops()) 1114 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1115 1116 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1117 : Subtarget->hasDivideInARMMode(); 1118 if (!hasDivide) { 1119 // These are expanded into libcalls if the cpu doesn't have HW divider. 1120 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1121 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1122 } 1123 1124 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1125 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1126 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1127 1128 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1129 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1130 } 1131 1132 setOperationAction(ISD::SREM, MVT::i32, Expand); 1133 setOperationAction(ISD::UREM, MVT::i32, Expand); 1134 1135 // Register based DivRem for AEABI (RTABI 4.2) 1136 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1137 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1138 Subtarget->isTargetWindows()) { 1139 setOperationAction(ISD::SREM, MVT::i64, Custom); 1140 setOperationAction(ISD::UREM, MVT::i64, Custom); 1141 HasStandaloneRem = false; 1142 1143 if (Subtarget->isTargetWindows()) { 1144 const struct { 1145 const RTLIB::Libcall Op; 1146 const char * const Name; 1147 const CallingConv::ID CC; 1148 } LibraryCalls[] = { 1149 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1150 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1151 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1152 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1153 1154 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1155 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1156 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1157 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1158 }; 1159 1160 for (const auto &LC : LibraryCalls) { 1161 setLibcallName(LC.Op, LC.Name); 1162 setLibcallCallingConv(LC.Op, LC.CC); 1163 } 1164 } else { 1165 const struct { 1166 const RTLIB::Libcall Op; 1167 const char * const Name; 1168 const CallingConv::ID CC; 1169 } LibraryCalls[] = { 1170 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1171 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1172 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1173 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1174 1175 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1176 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1177 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1178 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1179 }; 1180 1181 for (const auto &LC : LibraryCalls) { 1182 setLibcallName(LC.Op, LC.Name); 1183 setLibcallCallingConv(LC.Op, LC.CC); 1184 } 1185 } 1186 1187 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1188 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1189 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1190 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1191 } else { 1192 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1193 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1194 } 1195 1196 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 1197 // MSVCRT doesn't have powi; fall back to pow 1198 setLibcallName(RTLIB::POWI_F32, nullptr); 1199 setLibcallName(RTLIB::POWI_F64, nullptr); 1200 } 1201 1202 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1203 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1204 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1205 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1206 1207 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1208 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1209 1210 // Use the default implementation. 1211 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1212 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1213 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1214 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1215 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1216 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1217 1218 if (Subtarget->isTargetWindows()) 1219 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1220 else 1221 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1222 1223 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1224 // the default expansion. 1225 InsertFencesForAtomic = false; 1226 if (Subtarget->hasAnyDataBarrier() && 1227 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1228 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1229 // to ldrex/strex loops already. 1230 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1231 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1232 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1233 1234 // On v8, we have particularly efficient implementations of atomic fences 1235 // if they can be combined with nearby atomic loads and stores. 1236 if (!Subtarget->hasAcquireRelease() || 1237 getTargetMachine().getOptLevel() == 0) { 1238 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1239 InsertFencesForAtomic = true; 1240 } 1241 } else { 1242 // If there's anything we can use as a barrier, go through custom lowering 1243 // for ATOMIC_FENCE. 1244 // If target has DMB in thumb, Fences can be inserted. 1245 if (Subtarget->hasDataBarrier()) 1246 InsertFencesForAtomic = true; 1247 1248 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1249 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1250 1251 // Set them all for expansion, which will force libcalls. 1252 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1253 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1254 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1255 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1256 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1257 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1258 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1259 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1260 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1261 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1262 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1263 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1264 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1265 // Unordered/Monotonic case. 1266 if (!InsertFencesForAtomic) { 1267 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1268 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1269 } 1270 } 1271 1272 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1273 1274 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1275 if (!Subtarget->hasV6Ops()) { 1276 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1277 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1278 } 1279 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1280 1281 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1282 !Subtarget->isThumb1Only()) { 1283 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1284 // iff target supports vfp2. 1285 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1286 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1287 } 1288 1289 // We want to custom lower some of our intrinsics. 1290 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1291 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1292 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1293 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1294 if (Subtarget->useSjLjEH()) 1295 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1296 1297 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1298 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1299 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1300 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1301 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1302 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1303 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1304 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1305 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1306 if (Subtarget->hasFullFP16()) { 1307 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1308 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1309 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1310 } 1311 1312 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1313 1314 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1315 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1316 if (Subtarget->hasFullFP16()) 1317 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1318 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1319 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1320 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1321 1322 // We don't support sin/cos/fmod/copysign/pow 1323 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1324 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1325 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1326 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1327 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1328 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1329 setOperationAction(ISD::FREM, MVT::f64, Expand); 1330 setOperationAction(ISD::FREM, MVT::f32, Expand); 1331 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1332 !Subtarget->isThumb1Only()) { 1333 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1334 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1335 } 1336 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1337 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1338 1339 if (!Subtarget->hasVFP4Base()) { 1340 setOperationAction(ISD::FMA, MVT::f64, Expand); 1341 setOperationAction(ISD::FMA, MVT::f32, Expand); 1342 } 1343 1344 // Various VFP goodness 1345 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1346 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1347 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1348 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1349 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1350 } 1351 1352 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1353 if (!Subtarget->hasFP16()) { 1354 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1355 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1356 } 1357 1358 // Strict floating-point comparisons need custom lowering. 1359 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 1360 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 1361 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 1362 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 1363 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 1364 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 1365 } 1366 1367 // Use __sincos_stret if available. 1368 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1369 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1370 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1371 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1372 } 1373 1374 // FP-ARMv8 implements a lot of rounding-like FP operations. 1375 if (Subtarget->hasFPARMv8Base()) { 1376 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1377 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1378 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1379 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1380 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1381 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1382 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1383 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1384 if (Subtarget->hasNEON()) { 1385 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1386 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1387 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1388 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1389 } 1390 1391 if (Subtarget->hasFP64()) { 1392 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1393 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1394 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1395 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1396 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1397 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1398 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1399 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1400 } 1401 } 1402 1403 // FP16 often need to be promoted to call lib functions 1404 if (Subtarget->hasFullFP16()) { 1405 setOperationAction(ISD::FREM, MVT::f16, Promote); 1406 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1407 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1408 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1409 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1410 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1411 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1412 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1413 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1414 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1415 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1416 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1417 1418 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1419 } 1420 1421 if (Subtarget->hasNEON()) { 1422 // vmin and vmax aren't available in a scalar form, so we use 1423 // a NEON instruction with an undef lane instead. 1424 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1425 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1426 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1427 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1428 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1429 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1430 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1431 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1432 1433 if (Subtarget->hasFullFP16()) { 1434 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1435 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1436 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1437 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1438 1439 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1440 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1441 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1442 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1443 } 1444 } 1445 1446 // We have target-specific dag combine patterns for the following nodes: 1447 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1448 setTargetDAGCombine(ISD::ADD); 1449 setTargetDAGCombine(ISD::SUB); 1450 setTargetDAGCombine(ISD::MUL); 1451 setTargetDAGCombine(ISD::AND); 1452 setTargetDAGCombine(ISD::OR); 1453 setTargetDAGCombine(ISD::XOR); 1454 1455 if (Subtarget->hasV6Ops()) 1456 setTargetDAGCombine(ISD::SRL); 1457 if (Subtarget->isThumb1Only()) 1458 setTargetDAGCombine(ISD::SHL); 1459 1460 setStackPointerRegisterToSaveRestore(ARM::SP); 1461 1462 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1463 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1464 setSchedulingPreference(Sched::RegPressure); 1465 else 1466 setSchedulingPreference(Sched::Hybrid); 1467 1468 //// temporary - rewrite interface to use type 1469 MaxStoresPerMemset = 8; 1470 MaxStoresPerMemsetOptSize = 4; 1471 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1472 MaxStoresPerMemcpyOptSize = 2; 1473 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1474 MaxStoresPerMemmoveOptSize = 2; 1475 1476 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1477 // are at least 4 bytes aligned. 1478 setMinStackArgumentAlignment(Align(4)); 1479 1480 // Prefer likely predicted branches to selects on out-of-order cores. 1481 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1482 1483 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment())); 1484 1485 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4)); 1486 1487 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1488 setTargetDAGCombine(ISD::ABS); 1489 } 1490 1491 bool ARMTargetLowering::useSoftFloat() const { 1492 return Subtarget->useSoftFloat(); 1493 } 1494 1495 // FIXME: It might make sense to define the representative register class as the 1496 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1497 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1498 // SPR's representative would be DPR_VFP2. This should work well if register 1499 // pressure tracking were modified such that a register use would increment the 1500 // pressure of the register class's representative and all of it's super 1501 // classes' representatives transitively. We have not implemented this because 1502 // of the difficulty prior to coalescing of modeling operand register classes 1503 // due to the common occurrence of cross class copies and subregister insertions 1504 // and extractions. 1505 std::pair<const TargetRegisterClass *, uint8_t> 1506 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1507 MVT VT) const { 1508 const TargetRegisterClass *RRC = nullptr; 1509 uint8_t Cost = 1; 1510 switch (VT.SimpleTy) { 1511 default: 1512 return TargetLowering::findRepresentativeClass(TRI, VT); 1513 // Use DPR as representative register class for all floating point 1514 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1515 // the cost is 1 for both f32 and f64. 1516 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1517 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1518 RRC = &ARM::DPRRegClass; 1519 // When NEON is used for SP, only half of the register file is available 1520 // because operations that define both SP and DP results will be constrained 1521 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1522 // coalescing by double-counting the SP regs. See the FIXME above. 1523 if (Subtarget->useNEONForSinglePrecisionFP()) 1524 Cost = 2; 1525 break; 1526 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1527 case MVT::v4f32: case MVT::v2f64: 1528 RRC = &ARM::DPRRegClass; 1529 Cost = 2; 1530 break; 1531 case MVT::v4i64: 1532 RRC = &ARM::DPRRegClass; 1533 Cost = 4; 1534 break; 1535 case MVT::v8i64: 1536 RRC = &ARM::DPRRegClass; 1537 Cost = 8; 1538 break; 1539 } 1540 return std::make_pair(RRC, Cost); 1541 } 1542 1543 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1544 switch ((ARMISD::NodeType)Opcode) { 1545 case ARMISD::FIRST_NUMBER: break; 1546 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1547 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1548 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1549 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1550 case ARMISD::CALL: return "ARMISD::CALL"; 1551 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1552 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1553 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1554 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1555 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1556 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1557 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1558 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1559 case ARMISD::CMP: return "ARMISD::CMP"; 1560 case ARMISD::CMN: return "ARMISD::CMN"; 1561 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1562 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1563 case ARMISD::CMPFPE: return "ARMISD::CMPFPE"; 1564 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1565 case ARMISD::CMPFPEw0: return "ARMISD::CMPFPEw0"; 1566 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1567 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1568 1569 case ARMISD::CMOV: return "ARMISD::CMOV"; 1570 case ARMISD::SUBS: return "ARMISD::SUBS"; 1571 1572 case ARMISD::SSAT: return "ARMISD::SSAT"; 1573 case ARMISD::USAT: return "ARMISD::USAT"; 1574 1575 case ARMISD::ASRL: return "ARMISD::ASRL"; 1576 case ARMISD::LSRL: return "ARMISD::LSRL"; 1577 case ARMISD::LSLL: return "ARMISD::LSLL"; 1578 1579 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1580 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1581 case ARMISD::RRX: return "ARMISD::RRX"; 1582 1583 case ARMISD::ADDC: return "ARMISD::ADDC"; 1584 case ARMISD::ADDE: return "ARMISD::ADDE"; 1585 case ARMISD::SUBC: return "ARMISD::SUBC"; 1586 case ARMISD::SUBE: return "ARMISD::SUBE"; 1587 case ARMISD::LSLS: return "ARMISD::LSLS"; 1588 1589 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1590 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1591 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1592 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1593 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1594 1595 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1596 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1597 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1598 1599 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1600 1601 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1602 1603 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1604 1605 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1606 1607 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1608 1609 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1610 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1611 1612 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST"; 1613 case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST"; 1614 case ARMISD::VCMP: return "ARMISD::VCMP"; 1615 case ARMISD::VCMPZ: return "ARMISD::VCMPZ"; 1616 case ARMISD::VTST: return "ARMISD::VTST"; 1617 1618 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1619 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1620 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1621 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1622 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1623 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1624 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1625 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1626 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1627 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1628 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1629 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1630 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1631 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1632 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1633 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1634 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1635 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1636 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1637 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1638 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1639 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1640 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1641 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1642 case ARMISD::VDUP: return "ARMISD::VDUP"; 1643 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1644 case ARMISD::VEXT: return "ARMISD::VEXT"; 1645 case ARMISD::VREV64: return "ARMISD::VREV64"; 1646 case ARMISD::VREV32: return "ARMISD::VREV32"; 1647 case ARMISD::VREV16: return "ARMISD::VREV16"; 1648 case ARMISD::VZIP: return "ARMISD::VZIP"; 1649 case ARMISD::VUZP: return "ARMISD::VUZP"; 1650 case ARMISD::VTRN: return "ARMISD::VTRN"; 1651 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1652 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1653 case ARMISD::VMOVN: return "ARMISD::VMOVN"; 1654 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1655 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1656 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1657 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1658 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1659 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1660 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1661 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1662 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1663 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1664 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1665 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1666 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1667 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1668 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1669 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1670 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1671 case ARMISD::QADD16b: return "ARMISD::QADD16b"; 1672 case ARMISD::QSUB16b: return "ARMISD::QSUB16b"; 1673 case ARMISD::QADD8b: return "ARMISD::QADD8b"; 1674 case ARMISD::QSUB8b: return "ARMISD::QSUB8b"; 1675 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1676 case ARMISD::BFI: return "ARMISD::BFI"; 1677 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1678 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1679 case ARMISD::VBSL: return "ARMISD::VBSL"; 1680 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1681 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1682 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1683 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1684 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1685 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1686 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1687 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1688 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1689 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1690 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1691 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1692 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1693 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1694 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1695 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1696 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1697 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1698 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1699 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1700 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1701 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1702 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1703 case ARMISD::WLS: return "ARMISD::WLS"; 1704 case ARMISD::LE: return "ARMISD::LE"; 1705 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1706 case ARMISD::CSINV: return "ARMISD::CSINV"; 1707 case ARMISD::CSNEG: return "ARMISD::CSNEG"; 1708 case ARMISD::CSINC: return "ARMISD::CSINC"; 1709 } 1710 return nullptr; 1711 } 1712 1713 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1714 EVT VT) const { 1715 if (!VT.isVector()) 1716 return getPointerTy(DL); 1717 1718 // MVE has a predicate register. 1719 if (Subtarget->hasMVEIntegerOps() && 1720 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1721 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1722 return VT.changeVectorElementTypeToInteger(); 1723 } 1724 1725 /// getRegClassFor - Return the register class that should be used for the 1726 /// specified value type. 1727 const TargetRegisterClass * 1728 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1729 (void)isDivergent; 1730 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1731 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1732 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1733 // MVE Q registers. 1734 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1735 if (VT == MVT::v4i64) 1736 return &ARM::QQPRRegClass; 1737 if (VT == MVT::v8i64) 1738 return &ARM::QQQQPRRegClass; 1739 } 1740 return TargetLowering::getRegClassFor(VT); 1741 } 1742 1743 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1744 // source/dest is aligned and the copy size is large enough. We therefore want 1745 // to align such objects passed to memory intrinsics. 1746 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1747 unsigned &PrefAlign) const { 1748 if (!isa<MemIntrinsic>(CI)) 1749 return false; 1750 MinSize = 8; 1751 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1752 // cycle faster than 4-byte aligned LDM. 1753 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1754 return true; 1755 } 1756 1757 // Create a fast isel object. 1758 FastISel * 1759 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1760 const TargetLibraryInfo *libInfo) const { 1761 return ARM::createFastISel(funcInfo, libInfo); 1762 } 1763 1764 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1765 unsigned NumVals = N->getNumValues(); 1766 if (!NumVals) 1767 return Sched::RegPressure; 1768 1769 for (unsigned i = 0; i != NumVals; ++i) { 1770 EVT VT = N->getValueType(i); 1771 if (VT == MVT::Glue || VT == MVT::Other) 1772 continue; 1773 if (VT.isFloatingPoint() || VT.isVector()) 1774 return Sched::ILP; 1775 } 1776 1777 if (!N->isMachineOpcode()) 1778 return Sched::RegPressure; 1779 1780 // Load are scheduled for latency even if there instruction itinerary 1781 // is not available. 1782 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1783 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1784 1785 if (MCID.getNumDefs() == 0) 1786 return Sched::RegPressure; 1787 if (!Itins->isEmpty() && 1788 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1789 return Sched::ILP; 1790 1791 return Sched::RegPressure; 1792 } 1793 1794 //===----------------------------------------------------------------------===// 1795 // Lowering Code 1796 //===----------------------------------------------------------------------===// 1797 1798 static bool isSRL16(const SDValue &Op) { 1799 if (Op.getOpcode() != ISD::SRL) 1800 return false; 1801 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1802 return Const->getZExtValue() == 16; 1803 return false; 1804 } 1805 1806 static bool isSRA16(const SDValue &Op) { 1807 if (Op.getOpcode() != ISD::SRA) 1808 return false; 1809 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1810 return Const->getZExtValue() == 16; 1811 return false; 1812 } 1813 1814 static bool isSHL16(const SDValue &Op) { 1815 if (Op.getOpcode() != ISD::SHL) 1816 return false; 1817 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1818 return Const->getZExtValue() == 16; 1819 return false; 1820 } 1821 1822 // Check for a signed 16-bit value. We special case SRA because it makes it 1823 // more simple when also looking for SRAs that aren't sign extending a 1824 // smaller value. Without the check, we'd need to take extra care with 1825 // checking order for some operations. 1826 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1827 if (isSRA16(Op)) 1828 return isSHL16(Op.getOperand(0)); 1829 return DAG.ComputeNumSignBits(Op) == 17; 1830 } 1831 1832 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1833 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1834 switch (CC) { 1835 default: llvm_unreachable("Unknown condition code!"); 1836 case ISD::SETNE: return ARMCC::NE; 1837 case ISD::SETEQ: return ARMCC::EQ; 1838 case ISD::SETGT: return ARMCC::GT; 1839 case ISD::SETGE: return ARMCC::GE; 1840 case ISD::SETLT: return ARMCC::LT; 1841 case ISD::SETLE: return ARMCC::LE; 1842 case ISD::SETUGT: return ARMCC::HI; 1843 case ISD::SETUGE: return ARMCC::HS; 1844 case ISD::SETULT: return ARMCC::LO; 1845 case ISD::SETULE: return ARMCC::LS; 1846 } 1847 } 1848 1849 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1850 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1851 ARMCC::CondCodes &CondCode2) { 1852 CondCode2 = ARMCC::AL; 1853 switch (CC) { 1854 default: llvm_unreachable("Unknown FP condition!"); 1855 case ISD::SETEQ: 1856 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1857 case ISD::SETGT: 1858 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1859 case ISD::SETGE: 1860 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1861 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1862 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1863 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1864 case ISD::SETO: CondCode = ARMCC::VC; break; 1865 case ISD::SETUO: CondCode = ARMCC::VS; break; 1866 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1867 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1868 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1869 case ISD::SETLT: 1870 case ISD::SETULT: CondCode = ARMCC::LT; break; 1871 case ISD::SETLE: 1872 case ISD::SETULE: CondCode = ARMCC::LE; break; 1873 case ISD::SETNE: 1874 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1875 } 1876 } 1877 1878 //===----------------------------------------------------------------------===// 1879 // Calling Convention Implementation 1880 //===----------------------------------------------------------------------===// 1881 1882 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1883 /// account presence of floating point hardware and calling convention 1884 /// limitations, such as support for variadic functions. 1885 CallingConv::ID 1886 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1887 bool isVarArg) const { 1888 switch (CC) { 1889 default: 1890 report_fatal_error("Unsupported calling convention"); 1891 case CallingConv::ARM_AAPCS: 1892 case CallingConv::ARM_APCS: 1893 case CallingConv::GHC: 1894 case CallingConv::CFGuard_Check: 1895 return CC; 1896 case CallingConv::PreserveMost: 1897 return CallingConv::PreserveMost; 1898 case CallingConv::ARM_AAPCS_VFP: 1899 case CallingConv::Swift: 1900 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1901 case CallingConv::C: 1902 if (!Subtarget->isAAPCS_ABI()) 1903 return CallingConv::ARM_APCS; 1904 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1905 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1906 !isVarArg) 1907 return CallingConv::ARM_AAPCS_VFP; 1908 else 1909 return CallingConv::ARM_AAPCS; 1910 case CallingConv::Fast: 1911 case CallingConv::CXX_FAST_TLS: 1912 if (!Subtarget->isAAPCS_ABI()) { 1913 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 1914 return CallingConv::Fast; 1915 return CallingConv::ARM_APCS; 1916 } else if (Subtarget->hasVFP2Base() && 1917 !Subtarget->isThumb1Only() && !isVarArg) 1918 return CallingConv::ARM_AAPCS_VFP; 1919 else 1920 return CallingConv::ARM_AAPCS; 1921 } 1922 } 1923 1924 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1925 bool isVarArg) const { 1926 return CCAssignFnForNode(CC, false, isVarArg); 1927 } 1928 1929 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1930 bool isVarArg) const { 1931 return CCAssignFnForNode(CC, true, isVarArg); 1932 } 1933 1934 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1935 /// CallingConvention. 1936 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1937 bool Return, 1938 bool isVarArg) const { 1939 switch (getEffectiveCallingConv(CC, isVarArg)) { 1940 default: 1941 report_fatal_error("Unsupported calling convention"); 1942 case CallingConv::ARM_APCS: 1943 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1944 case CallingConv::ARM_AAPCS: 1945 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1946 case CallingConv::ARM_AAPCS_VFP: 1947 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1948 case CallingConv::Fast: 1949 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1950 case CallingConv::GHC: 1951 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1952 case CallingConv::PreserveMost: 1953 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1954 case CallingConv::CFGuard_Check: 1955 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check); 1956 } 1957 } 1958 1959 /// LowerCallResult - Lower the result values of a call into the 1960 /// appropriate copies out of appropriate physical registers. 1961 SDValue ARMTargetLowering::LowerCallResult( 1962 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1963 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1964 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1965 SDValue ThisVal) const { 1966 // Assign locations to each value returned by this call. 1967 SmallVector<CCValAssign, 16> RVLocs; 1968 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1969 *DAG.getContext()); 1970 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1971 1972 // Copy all of the result registers out of their specified physreg. 1973 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1974 CCValAssign VA = RVLocs[i]; 1975 1976 // Pass 'this' value directly from the argument to return value, to avoid 1977 // reg unit interference 1978 if (i == 0 && isThisReturn) { 1979 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1980 "unexpected return calling convention register assignment"); 1981 InVals.push_back(ThisVal); 1982 continue; 1983 } 1984 1985 SDValue Val; 1986 if (VA.needsCustom()) { 1987 // Handle f64 or half of a v2f64. 1988 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1989 InFlag); 1990 Chain = Lo.getValue(1); 1991 InFlag = Lo.getValue(2); 1992 VA = RVLocs[++i]; // skip ahead to next loc 1993 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1994 InFlag); 1995 Chain = Hi.getValue(1); 1996 InFlag = Hi.getValue(2); 1997 if (!Subtarget->isLittle()) 1998 std::swap (Lo, Hi); 1999 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2000 2001 if (VA.getLocVT() == MVT::v2f64) { 2002 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 2003 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2004 DAG.getConstant(0, dl, MVT::i32)); 2005 2006 VA = RVLocs[++i]; // skip ahead to next loc 2007 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2008 Chain = Lo.getValue(1); 2009 InFlag = Lo.getValue(2); 2010 VA = RVLocs[++i]; // skip ahead to next loc 2011 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2012 Chain = Hi.getValue(1); 2013 InFlag = Hi.getValue(2); 2014 if (!Subtarget->isLittle()) 2015 std::swap (Lo, Hi); 2016 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2017 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2018 DAG.getConstant(1, dl, MVT::i32)); 2019 } 2020 } else { 2021 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 2022 InFlag); 2023 Chain = Val.getValue(1); 2024 InFlag = Val.getValue(2); 2025 } 2026 2027 switch (VA.getLocInfo()) { 2028 default: llvm_unreachable("Unknown loc info!"); 2029 case CCValAssign::Full: break; 2030 case CCValAssign::BCvt: 2031 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 2032 break; 2033 } 2034 2035 InVals.push_back(Val); 2036 } 2037 2038 return Chain; 2039 } 2040 2041 /// LowerMemOpCallTo - Store the argument to the stack. 2042 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 2043 SDValue Arg, const SDLoc &dl, 2044 SelectionDAG &DAG, 2045 const CCValAssign &VA, 2046 ISD::ArgFlagsTy Flags) const { 2047 unsigned LocMemOffset = VA.getLocMemOffset(); 2048 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2049 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 2050 StackPtr, PtrOff); 2051 return DAG.getStore( 2052 Chain, dl, Arg, PtrOff, 2053 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 2054 } 2055 2056 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 2057 SDValue Chain, SDValue &Arg, 2058 RegsToPassVector &RegsToPass, 2059 CCValAssign &VA, CCValAssign &NextVA, 2060 SDValue &StackPtr, 2061 SmallVectorImpl<SDValue> &MemOpChains, 2062 ISD::ArgFlagsTy Flags) const { 2063 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2064 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2065 unsigned id = Subtarget->isLittle() ? 0 : 1; 2066 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2067 2068 if (NextVA.isRegLoc()) 2069 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2070 else { 2071 assert(NextVA.isMemLoc()); 2072 if (!StackPtr.getNode()) 2073 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2074 getPointerTy(DAG.getDataLayout())); 2075 2076 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2077 dl, DAG, NextVA, 2078 Flags)); 2079 } 2080 } 2081 2082 /// LowerCall - Lowering a call into a callseq_start <- 2083 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2084 /// nodes. 2085 SDValue 2086 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2087 SmallVectorImpl<SDValue> &InVals) const { 2088 SelectionDAG &DAG = CLI.DAG; 2089 SDLoc &dl = CLI.DL; 2090 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2091 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2092 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2093 SDValue Chain = CLI.Chain; 2094 SDValue Callee = CLI.Callee; 2095 bool &isTailCall = CLI.IsTailCall; 2096 CallingConv::ID CallConv = CLI.CallConv; 2097 bool doesNotRet = CLI.DoesNotReturn; 2098 bool isVarArg = CLI.IsVarArg; 2099 2100 MachineFunction &MF = DAG.getMachineFunction(); 2101 MachineFunction::CallSiteInfo CSInfo; 2102 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2103 bool isThisReturn = false; 2104 bool PreferIndirect = false; 2105 2106 // Disable tail calls if they're not supported. 2107 if (!Subtarget->supportsTailCall()) 2108 isTailCall = false; 2109 2110 if (isa<GlobalAddressSDNode>(Callee)) { 2111 // If we're optimizing for minimum size and the function is called three or 2112 // more times in this block, we can improve codesize by calling indirectly 2113 // as BLXr has a 16-bit encoding. 2114 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2115 if (CLI.CS) { 2116 auto *BB = CLI.CS.getParent(); 2117 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2118 count_if(GV->users(), [&BB](const User *U) { 2119 return isa<Instruction>(U) && 2120 cast<Instruction>(U)->getParent() == BB; 2121 }) > 2; 2122 } 2123 } 2124 if (isTailCall) { 2125 // Check if it's really possible to do a tail call. 2126 isTailCall = IsEligibleForTailCallOptimization( 2127 Callee, CallConv, isVarArg, isStructRet, 2128 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2129 PreferIndirect); 2130 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 2131 report_fatal_error("failed to perform tail call elimination on a call " 2132 "site marked musttail"); 2133 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2134 // detected sibcalls. 2135 if (isTailCall) 2136 ++NumTailCalls; 2137 } 2138 2139 // Analyze operands of the call, assigning locations to each operand. 2140 SmallVector<CCValAssign, 16> ArgLocs; 2141 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2142 *DAG.getContext()); 2143 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2144 2145 // Get a count of how many bytes are to be pushed on the stack. 2146 unsigned NumBytes = CCInfo.getNextStackOffset(); 2147 2148 if (isTailCall) { 2149 // For tail calls, memory operands are available in our caller's stack. 2150 NumBytes = 0; 2151 } else { 2152 // Adjust the stack pointer for the new arguments... 2153 // These operations are automatically eliminated by the prolog/epilog pass 2154 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2155 } 2156 2157 SDValue StackPtr = 2158 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2159 2160 RegsToPassVector RegsToPass; 2161 SmallVector<SDValue, 8> MemOpChains; 2162 2163 // Walk the register/memloc assignments, inserting copies/loads. In the case 2164 // of tail call optimization, arguments are handled later. 2165 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2166 i != e; 2167 ++i, ++realArgIdx) { 2168 CCValAssign &VA = ArgLocs[i]; 2169 SDValue Arg = OutVals[realArgIdx]; 2170 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2171 bool isByVal = Flags.isByVal(); 2172 2173 // Promote the value if needed. 2174 switch (VA.getLocInfo()) { 2175 default: llvm_unreachable("Unknown loc info!"); 2176 case CCValAssign::Full: break; 2177 case CCValAssign::SExt: 2178 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2179 break; 2180 case CCValAssign::ZExt: 2181 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2182 break; 2183 case CCValAssign::AExt: 2184 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2185 break; 2186 case CCValAssign::BCvt: 2187 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2188 break; 2189 } 2190 2191 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2192 if (VA.needsCustom()) { 2193 if (VA.getLocVT() == MVT::v2f64) { 2194 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2195 DAG.getConstant(0, dl, MVT::i32)); 2196 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2197 DAG.getConstant(1, dl, MVT::i32)); 2198 2199 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 2200 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2201 2202 VA = ArgLocs[++i]; // skip ahead to next loc 2203 if (VA.isRegLoc()) { 2204 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 2205 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2206 } else { 2207 assert(VA.isMemLoc()); 2208 2209 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 2210 dl, DAG, VA, Flags)); 2211 } 2212 } else { 2213 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2214 StackPtr, MemOpChains, Flags); 2215 } 2216 } else if (VA.isRegLoc()) { 2217 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2218 Outs[0].VT == MVT::i32) { 2219 assert(VA.getLocVT() == MVT::i32 && 2220 "unexpected calling convention register assignment"); 2221 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2222 "unexpected use of 'returned'"); 2223 isThisReturn = true; 2224 } 2225 const TargetOptions &Options = DAG.getTarget().Options; 2226 if (Options.EnableDebugEntryValues) 2227 CSInfo.emplace_back(VA.getLocReg(), i); 2228 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2229 } else if (isByVal) { 2230 assert(VA.isMemLoc()); 2231 unsigned offset = 0; 2232 2233 // True if this byval aggregate will be split between registers 2234 // and memory. 2235 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2236 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2237 2238 if (CurByValIdx < ByValArgsCount) { 2239 2240 unsigned RegBegin, RegEnd; 2241 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2242 2243 EVT PtrVT = 2244 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2245 unsigned int i, j; 2246 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2247 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2248 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2249 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 2250 MachinePointerInfo(), 2251 DAG.InferPtrAlignment(AddArg)); 2252 MemOpChains.push_back(Load.getValue(1)); 2253 RegsToPass.push_back(std::make_pair(j, Load)); 2254 } 2255 2256 // If parameter size outsides register area, "offset" value 2257 // helps us to calculate stack slot for remained part properly. 2258 offset = RegEnd - RegBegin; 2259 2260 CCInfo.nextInRegsParam(); 2261 } 2262 2263 if (Flags.getByValSize() > 4*offset) { 2264 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2265 unsigned LocMemOffset = VA.getLocMemOffset(); 2266 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2267 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2268 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2269 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2270 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2271 MVT::i32); 2272 SDValue AlignNode = 2273 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32); 2274 2275 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2276 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2277 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2278 Ops)); 2279 } 2280 } else if (!isTailCall) { 2281 assert(VA.isMemLoc()); 2282 2283 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2284 dl, DAG, VA, Flags)); 2285 } 2286 } 2287 2288 if (!MemOpChains.empty()) 2289 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2290 2291 // Build a sequence of copy-to-reg nodes chained together with token chain 2292 // and flag operands which copy the outgoing args into the appropriate regs. 2293 SDValue InFlag; 2294 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2295 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2296 RegsToPass[i].second, InFlag); 2297 InFlag = Chain.getValue(1); 2298 } 2299 2300 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2301 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2302 // node so that legalize doesn't hack it. 2303 bool isDirect = false; 2304 2305 const TargetMachine &TM = getTargetMachine(); 2306 const Module *Mod = MF.getFunction().getParent(); 2307 const GlobalValue *GV = nullptr; 2308 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2309 GV = G->getGlobal(); 2310 bool isStub = 2311 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2312 2313 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2314 bool isLocalARMFunc = false; 2315 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2316 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2317 2318 if (Subtarget->genLongCalls()) { 2319 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2320 "long-calls codegen is not position independent!"); 2321 // Handle a global address or an external symbol. If it's not one of 2322 // those, the target's already in a register, so we don't need to do 2323 // anything extra. 2324 if (isa<GlobalAddressSDNode>(Callee)) { 2325 // Create a constant pool entry for the callee address 2326 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2327 ARMConstantPoolValue *CPV = 2328 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2329 2330 // Get the address of the callee into a register 2331 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2332 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2333 Callee = DAG.getLoad( 2334 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2335 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2336 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2337 const char *Sym = S->getSymbol(); 2338 2339 // Create a constant pool entry for the callee address 2340 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2341 ARMConstantPoolValue *CPV = 2342 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2343 ARMPCLabelIndex, 0); 2344 // Get the address of the callee into a register 2345 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2346 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2347 Callee = DAG.getLoad( 2348 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2349 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2350 } 2351 } else if (isa<GlobalAddressSDNode>(Callee)) { 2352 if (!PreferIndirect) { 2353 isDirect = true; 2354 bool isDef = GV->isStrongDefinitionForLinker(); 2355 2356 // ARM call to a local ARM function is predicable. 2357 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2358 // tBX takes a register source operand. 2359 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2360 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2361 Callee = DAG.getNode( 2362 ARMISD::WrapperPIC, dl, PtrVt, 2363 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2364 Callee = DAG.getLoad( 2365 PtrVt, dl, DAG.getEntryNode(), Callee, 2366 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2367 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2368 MachineMemOperand::MOInvariant); 2369 } else if (Subtarget->isTargetCOFF()) { 2370 assert(Subtarget->isTargetWindows() && 2371 "Windows is the only supported COFF target"); 2372 unsigned TargetFlags = ARMII::MO_NO_FLAG; 2373 if (GV->hasDLLImportStorageClass()) 2374 TargetFlags = ARMII::MO_DLLIMPORT; 2375 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 2376 TargetFlags = ARMII::MO_COFFSTUB; 2377 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2378 TargetFlags); 2379 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 2380 Callee = 2381 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2382 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2383 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2384 } else { 2385 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2386 } 2387 } 2388 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2389 isDirect = true; 2390 // tBX takes a register source operand. 2391 const char *Sym = S->getSymbol(); 2392 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2393 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2394 ARMConstantPoolValue *CPV = 2395 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2396 ARMPCLabelIndex, 4); 2397 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2398 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2399 Callee = DAG.getLoad( 2400 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2401 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2402 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2403 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2404 } else { 2405 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2406 } 2407 } 2408 2409 // FIXME: handle tail calls differently. 2410 unsigned CallOpc; 2411 if (Subtarget->isThumb()) { 2412 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2413 CallOpc = ARMISD::CALL_NOLINK; 2414 else 2415 CallOpc = ARMISD::CALL; 2416 } else { 2417 if (!isDirect && !Subtarget->hasV5TOps()) 2418 CallOpc = ARMISD::CALL_NOLINK; 2419 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2420 // Emit regular call when code size is the priority 2421 !Subtarget->hasMinSize()) 2422 // "mov lr, pc; b _foo" to avoid confusing the RSP 2423 CallOpc = ARMISD::CALL_NOLINK; 2424 else 2425 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2426 } 2427 2428 std::vector<SDValue> Ops; 2429 Ops.push_back(Chain); 2430 Ops.push_back(Callee); 2431 2432 // Add argument registers to the end of the list so that they are known live 2433 // into the call. 2434 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2435 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2436 RegsToPass[i].second.getValueType())); 2437 2438 // Add a register mask operand representing the call-preserved registers. 2439 if (!isTailCall) { 2440 const uint32_t *Mask; 2441 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2442 if (isThisReturn) { 2443 // For 'this' returns, use the R0-preserving mask if applicable 2444 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2445 if (!Mask) { 2446 // Set isThisReturn to false if the calling convention is not one that 2447 // allows 'returned' to be modeled in this way, so LowerCallResult does 2448 // not try to pass 'this' straight through 2449 isThisReturn = false; 2450 Mask = ARI->getCallPreservedMask(MF, CallConv); 2451 } 2452 } else 2453 Mask = ARI->getCallPreservedMask(MF, CallConv); 2454 2455 assert(Mask && "Missing call preserved mask for calling convention"); 2456 Ops.push_back(DAG.getRegisterMask(Mask)); 2457 } 2458 2459 if (InFlag.getNode()) 2460 Ops.push_back(InFlag); 2461 2462 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2463 if (isTailCall) { 2464 MF.getFrameInfo().setHasTailCall(); 2465 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2466 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 2467 return Ret; 2468 } 2469 2470 // Returns a chain and a flag for retval copy to use. 2471 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2472 InFlag = Chain.getValue(1); 2473 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 2474 2475 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2476 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2477 if (!Ins.empty()) 2478 InFlag = Chain.getValue(1); 2479 2480 // Handle result values, copying them out of physregs into vregs that we 2481 // return. 2482 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2483 InVals, isThisReturn, 2484 isThisReturn ? OutVals[0] : SDValue()); 2485 } 2486 2487 /// HandleByVal - Every parameter *after* a byval parameter is passed 2488 /// on the stack. Remember the next parameter register to allocate, 2489 /// and then confiscate the rest of the parameter registers to insure 2490 /// this. 2491 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2492 unsigned Align) const { 2493 // Byval (as with any stack) slots are always at least 4 byte aligned. 2494 Align = std::max(Align, 4U); 2495 2496 unsigned Reg = State->AllocateReg(GPRArgRegs); 2497 if (!Reg) 2498 return; 2499 2500 unsigned AlignInRegs = Align / 4; 2501 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2502 for (unsigned i = 0; i < Waste; ++i) 2503 Reg = State->AllocateReg(GPRArgRegs); 2504 2505 if (!Reg) 2506 return; 2507 2508 unsigned Excess = 4 * (ARM::R4 - Reg); 2509 2510 // Special case when NSAA != SP and parameter size greater than size of 2511 // all remained GPR regs. In that case we can't split parameter, we must 2512 // send it to stack. We also must set NCRN to R4, so waste all 2513 // remained registers. 2514 const unsigned NSAAOffset = State->getNextStackOffset(); 2515 if (NSAAOffset != 0 && Size > Excess) { 2516 while (State->AllocateReg(GPRArgRegs)) 2517 ; 2518 return; 2519 } 2520 2521 // First register for byval parameter is the first register that wasn't 2522 // allocated before this method call, so it would be "reg". 2523 // If parameter is small enough to be saved in range [reg, r4), then 2524 // the end (first after last) register would be reg + param-size-in-regs, 2525 // else parameter would be splitted between registers and stack, 2526 // end register would be r4 in this case. 2527 unsigned ByValRegBegin = Reg; 2528 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2529 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2530 // Note, first register is allocated in the beginning of function already, 2531 // allocate remained amount of registers we need. 2532 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2533 State->AllocateReg(GPRArgRegs); 2534 // A byval parameter that is split between registers and memory needs its 2535 // size truncated here. 2536 // In the case where the entire structure fits in registers, we set the 2537 // size in memory to zero. 2538 Size = std::max<int>(Size - Excess, 0); 2539 } 2540 2541 /// MatchingStackOffset - Return true if the given stack call argument is 2542 /// already available in the same position (relatively) of the caller's 2543 /// incoming argument stack. 2544 static 2545 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2546 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2547 const TargetInstrInfo *TII) { 2548 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2549 int FI = std::numeric_limits<int>::max(); 2550 if (Arg.getOpcode() == ISD::CopyFromReg) { 2551 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2552 if (!Register::isVirtualRegister(VR)) 2553 return false; 2554 MachineInstr *Def = MRI->getVRegDef(VR); 2555 if (!Def) 2556 return false; 2557 if (!Flags.isByVal()) { 2558 if (!TII->isLoadFromStackSlot(*Def, FI)) 2559 return false; 2560 } else { 2561 return false; 2562 } 2563 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2564 if (Flags.isByVal()) 2565 // ByVal argument is passed in as a pointer but it's now being 2566 // dereferenced. e.g. 2567 // define @foo(%struct.X* %A) { 2568 // tail call @bar(%struct.X* byval %A) 2569 // } 2570 return false; 2571 SDValue Ptr = Ld->getBasePtr(); 2572 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2573 if (!FINode) 2574 return false; 2575 FI = FINode->getIndex(); 2576 } else 2577 return false; 2578 2579 assert(FI != std::numeric_limits<int>::max()); 2580 if (!MFI.isFixedObjectIndex(FI)) 2581 return false; 2582 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2583 } 2584 2585 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2586 /// for tail call optimization. Targets which want to do tail call 2587 /// optimization should implement this function. 2588 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2589 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2590 bool isCalleeStructRet, bool isCallerStructRet, 2591 const SmallVectorImpl<ISD::OutputArg> &Outs, 2592 const SmallVectorImpl<SDValue> &OutVals, 2593 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2594 const bool isIndirect) const { 2595 MachineFunction &MF = DAG.getMachineFunction(); 2596 const Function &CallerF = MF.getFunction(); 2597 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2598 2599 assert(Subtarget->supportsTailCall()); 2600 2601 // Indirect tail calls cannot be optimized for Thumb1 if the args 2602 // to the call take up r0-r3. The reason is that there are no legal registers 2603 // left to hold the pointer to the function to be called. 2604 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2605 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2606 return false; 2607 2608 // Look for obvious safe cases to perform tail call optimization that do not 2609 // require ABI changes. This is what gcc calls sibcall. 2610 2611 // Exception-handling functions need a special set of instructions to indicate 2612 // a return to the hardware. Tail-calling another function would probably 2613 // break this. 2614 if (CallerF.hasFnAttribute("interrupt")) 2615 return false; 2616 2617 // Also avoid sibcall optimization if either caller or callee uses struct 2618 // return semantics. 2619 if (isCalleeStructRet || isCallerStructRet) 2620 return false; 2621 2622 // Externally-defined functions with weak linkage should not be 2623 // tail-called on ARM when the OS does not support dynamic 2624 // pre-emption of symbols, as the AAELF spec requires normal calls 2625 // to undefined weak functions to be replaced with a NOP or jump to the 2626 // next instruction. The behaviour of branch instructions in this 2627 // situation (as used for tail calls) is implementation-defined, so we 2628 // cannot rely on the linker replacing the tail call with a return. 2629 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2630 const GlobalValue *GV = G->getGlobal(); 2631 const Triple &TT = getTargetMachine().getTargetTriple(); 2632 if (GV->hasExternalWeakLinkage() && 2633 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2634 return false; 2635 } 2636 2637 // Check that the call results are passed in the same way. 2638 LLVMContext &C = *DAG.getContext(); 2639 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2640 CCAssignFnForReturn(CalleeCC, isVarArg), 2641 CCAssignFnForReturn(CallerCC, isVarArg))) 2642 return false; 2643 // The callee has to preserve all registers the caller needs to preserve. 2644 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2645 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2646 if (CalleeCC != CallerCC) { 2647 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2648 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2649 return false; 2650 } 2651 2652 // If Caller's vararg or byval argument has been split between registers and 2653 // stack, do not perform tail call, since part of the argument is in caller's 2654 // local frame. 2655 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2656 if (AFI_Caller->getArgRegsSaveSize()) 2657 return false; 2658 2659 // If the callee takes no arguments then go on to check the results of the 2660 // call. 2661 if (!Outs.empty()) { 2662 // Check if stack adjustment is needed. For now, do not do this if any 2663 // argument is passed on the stack. 2664 SmallVector<CCValAssign, 16> ArgLocs; 2665 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2666 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2667 if (CCInfo.getNextStackOffset()) { 2668 // Check if the arguments are already laid out in the right way as 2669 // the caller's fixed stack objects. 2670 MachineFrameInfo &MFI = MF.getFrameInfo(); 2671 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2672 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2673 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2674 i != e; 2675 ++i, ++realArgIdx) { 2676 CCValAssign &VA = ArgLocs[i]; 2677 EVT RegVT = VA.getLocVT(); 2678 SDValue Arg = OutVals[realArgIdx]; 2679 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2680 if (VA.getLocInfo() == CCValAssign::Indirect) 2681 return false; 2682 if (VA.needsCustom()) { 2683 // f64 and vector types are split into multiple registers or 2684 // register/stack-slot combinations. The types will not match 2685 // the registers; give up on memory f64 refs until we figure 2686 // out what to do about this. 2687 if (!VA.isRegLoc()) 2688 return false; 2689 if (!ArgLocs[++i].isRegLoc()) 2690 return false; 2691 if (RegVT == MVT::v2f64) { 2692 if (!ArgLocs[++i].isRegLoc()) 2693 return false; 2694 if (!ArgLocs[++i].isRegLoc()) 2695 return false; 2696 } 2697 } else if (!VA.isRegLoc()) { 2698 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2699 MFI, MRI, TII)) 2700 return false; 2701 } 2702 } 2703 } 2704 2705 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2706 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2707 return false; 2708 } 2709 2710 return true; 2711 } 2712 2713 bool 2714 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2715 MachineFunction &MF, bool isVarArg, 2716 const SmallVectorImpl<ISD::OutputArg> &Outs, 2717 LLVMContext &Context) const { 2718 SmallVector<CCValAssign, 16> RVLocs; 2719 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2720 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2721 } 2722 2723 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2724 const SDLoc &DL, SelectionDAG &DAG) { 2725 const MachineFunction &MF = DAG.getMachineFunction(); 2726 const Function &F = MF.getFunction(); 2727 2728 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2729 2730 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2731 // version of the "preferred return address". These offsets affect the return 2732 // instruction if this is a return from PL1 without hypervisor extensions. 2733 // IRQ/FIQ: +4 "subs pc, lr, #4" 2734 // SWI: 0 "subs pc, lr, #0" 2735 // ABORT: +4 "subs pc, lr, #4" 2736 // UNDEF: +4/+2 "subs pc, lr, #0" 2737 // UNDEF varies depending on where the exception came from ARM or Thumb 2738 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2739 2740 int64_t LROffset; 2741 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2742 IntKind == "ABORT") 2743 LROffset = 4; 2744 else if (IntKind == "SWI" || IntKind == "UNDEF") 2745 LROffset = 0; 2746 else 2747 report_fatal_error("Unsupported interrupt attribute. If present, value " 2748 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2749 2750 RetOps.insert(RetOps.begin() + 1, 2751 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2752 2753 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2754 } 2755 2756 SDValue 2757 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2758 bool isVarArg, 2759 const SmallVectorImpl<ISD::OutputArg> &Outs, 2760 const SmallVectorImpl<SDValue> &OutVals, 2761 const SDLoc &dl, SelectionDAG &DAG) const { 2762 // CCValAssign - represent the assignment of the return value to a location. 2763 SmallVector<CCValAssign, 16> RVLocs; 2764 2765 // CCState - Info about the registers and stack slots. 2766 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2767 *DAG.getContext()); 2768 2769 // Analyze outgoing return values. 2770 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2771 2772 SDValue Flag; 2773 SmallVector<SDValue, 4> RetOps; 2774 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2775 bool isLittleEndian = Subtarget->isLittle(); 2776 2777 MachineFunction &MF = DAG.getMachineFunction(); 2778 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2779 AFI->setReturnRegsCount(RVLocs.size()); 2780 2781 // Copy the result values into the output registers. 2782 for (unsigned i = 0, realRVLocIdx = 0; 2783 i != RVLocs.size(); 2784 ++i, ++realRVLocIdx) { 2785 CCValAssign &VA = RVLocs[i]; 2786 assert(VA.isRegLoc() && "Can only return in registers!"); 2787 2788 SDValue Arg = OutVals[realRVLocIdx]; 2789 bool ReturnF16 = false; 2790 2791 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2792 // Half-precision return values can be returned like this: 2793 // 2794 // t11 f16 = fadd ... 2795 // t12: i16 = bitcast t11 2796 // t13: i32 = zero_extend t12 2797 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2798 // 2799 // to avoid code generation for bitcasts, we simply set Arg to the node 2800 // that produces the f16 value, t11 in this case. 2801 // 2802 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2803 SDValue ZE = Arg.getOperand(0); 2804 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2805 SDValue BC = ZE.getOperand(0); 2806 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2807 Arg = BC.getOperand(0); 2808 ReturnF16 = true; 2809 } 2810 } 2811 } 2812 } 2813 2814 switch (VA.getLocInfo()) { 2815 default: llvm_unreachable("Unknown loc info!"); 2816 case CCValAssign::Full: break; 2817 case CCValAssign::BCvt: 2818 if (!ReturnF16) 2819 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2820 break; 2821 } 2822 2823 if (VA.needsCustom()) { 2824 if (VA.getLocVT() == MVT::v2f64) { 2825 // Extract the first half and return it in two registers. 2826 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2827 DAG.getConstant(0, dl, MVT::i32)); 2828 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2829 DAG.getVTList(MVT::i32, MVT::i32), Half); 2830 2831 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2832 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2833 Flag); 2834 Flag = Chain.getValue(1); 2835 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2836 VA = RVLocs[++i]; // skip ahead to next loc 2837 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2838 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2839 Flag); 2840 Flag = Chain.getValue(1); 2841 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2842 VA = RVLocs[++i]; // skip ahead to next loc 2843 2844 // Extract the 2nd half and fall through to handle it as an f64 value. 2845 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2846 DAG.getConstant(1, dl, MVT::i32)); 2847 } 2848 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2849 // available. 2850 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2851 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2852 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2853 fmrrd.getValue(isLittleEndian ? 0 : 1), 2854 Flag); 2855 Flag = Chain.getValue(1); 2856 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2857 VA = RVLocs[++i]; // skip ahead to next loc 2858 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2859 fmrrd.getValue(isLittleEndian ? 1 : 0), 2860 Flag); 2861 } else 2862 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2863 2864 // Guarantee that all emitted copies are 2865 // stuck together, avoiding something bad. 2866 Flag = Chain.getValue(1); 2867 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2868 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2869 } 2870 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2871 const MCPhysReg *I = 2872 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2873 if (I) { 2874 for (; *I; ++I) { 2875 if (ARM::GPRRegClass.contains(*I)) 2876 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2877 else if (ARM::DPRRegClass.contains(*I)) 2878 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2879 else 2880 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2881 } 2882 } 2883 2884 // Update chain and glue. 2885 RetOps[0] = Chain; 2886 if (Flag.getNode()) 2887 RetOps.push_back(Flag); 2888 2889 // CPUs which aren't M-class use a special sequence to return from 2890 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2891 // though we use "subs pc, lr, #N"). 2892 // 2893 // M-class CPUs actually use a normal return sequence with a special 2894 // (hardware-provided) value in LR, so the normal code path works. 2895 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2896 !Subtarget->isMClass()) { 2897 if (Subtarget->isThumb1Only()) 2898 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2899 return LowerInterruptReturn(RetOps, dl, DAG); 2900 } 2901 2902 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2903 } 2904 2905 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2906 if (N->getNumValues() != 1) 2907 return false; 2908 if (!N->hasNUsesOfValue(1, 0)) 2909 return false; 2910 2911 SDValue TCChain = Chain; 2912 SDNode *Copy = *N->use_begin(); 2913 if (Copy->getOpcode() == ISD::CopyToReg) { 2914 // If the copy has a glue operand, we conservatively assume it isn't safe to 2915 // perform a tail call. 2916 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2917 return false; 2918 TCChain = Copy->getOperand(0); 2919 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2920 SDNode *VMov = Copy; 2921 // f64 returned in a pair of GPRs. 2922 SmallPtrSet<SDNode*, 2> Copies; 2923 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2924 UI != UE; ++UI) { 2925 if (UI->getOpcode() != ISD::CopyToReg) 2926 return false; 2927 Copies.insert(*UI); 2928 } 2929 if (Copies.size() > 2) 2930 return false; 2931 2932 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2933 UI != UE; ++UI) { 2934 SDValue UseChain = UI->getOperand(0); 2935 if (Copies.count(UseChain.getNode())) 2936 // Second CopyToReg 2937 Copy = *UI; 2938 else { 2939 // We are at the top of this chain. 2940 // If the copy has a glue operand, we conservatively assume it 2941 // isn't safe to perform a tail call. 2942 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2943 return false; 2944 // First CopyToReg 2945 TCChain = UseChain; 2946 } 2947 } 2948 } else if (Copy->getOpcode() == ISD::BITCAST) { 2949 // f32 returned in a single GPR. 2950 if (!Copy->hasOneUse()) 2951 return false; 2952 Copy = *Copy->use_begin(); 2953 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2954 return false; 2955 // If the copy has a glue operand, we conservatively assume it isn't safe to 2956 // perform a tail call. 2957 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2958 return false; 2959 TCChain = Copy->getOperand(0); 2960 } else { 2961 return false; 2962 } 2963 2964 bool HasRet = false; 2965 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2966 UI != UE; ++UI) { 2967 if (UI->getOpcode() != ARMISD::RET_FLAG && 2968 UI->getOpcode() != ARMISD::INTRET_FLAG) 2969 return false; 2970 HasRet = true; 2971 } 2972 2973 if (!HasRet) 2974 return false; 2975 2976 Chain = TCChain; 2977 return true; 2978 } 2979 2980 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2981 if (!Subtarget->supportsTailCall()) 2982 return false; 2983 2984 if (!CI->isTailCall()) 2985 return false; 2986 2987 return true; 2988 } 2989 2990 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2991 // and pass the lower and high parts through. 2992 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2993 SDLoc DL(Op); 2994 SDValue WriteValue = Op->getOperand(2); 2995 2996 // This function is only supposed to be called for i64 type argument. 2997 assert(WriteValue.getValueType() == MVT::i64 2998 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2999 3000 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3001 DAG.getConstant(0, DL, MVT::i32)); 3002 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3003 DAG.getConstant(1, DL, MVT::i32)); 3004 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 3005 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 3006 } 3007 3008 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 3009 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 3010 // one of the above mentioned nodes. It has to be wrapped because otherwise 3011 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 3012 // be used to form addressing mode. These wrapped nodes will be selected 3013 // into MOVi. 3014 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 3015 SelectionDAG &DAG) const { 3016 EVT PtrVT = Op.getValueType(); 3017 // FIXME there is no actual debug info here 3018 SDLoc dl(Op); 3019 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3020 SDValue Res; 3021 3022 // When generating execute-only code Constant Pools must be promoted to the 3023 // global data section. It's a bit ugly that we can't share them across basic 3024 // blocks, but this way we guarantee that execute-only behaves correct with 3025 // position-independent addressing modes. 3026 if (Subtarget->genExecuteOnly()) { 3027 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3028 auto T = const_cast<Type*>(CP->getType()); 3029 auto C = const_cast<Constant*>(CP->getConstVal()); 3030 auto M = const_cast<Module*>(DAG.getMachineFunction(). 3031 getFunction().getParent()); 3032 auto GV = new GlobalVariable( 3033 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 3034 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 3035 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 3036 Twine(AFI->createPICLabelUId()) 3037 ); 3038 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 3039 dl, PtrVT); 3040 return LowerGlobalAddress(GA, DAG); 3041 } 3042 3043 if (CP->isMachineConstantPoolEntry()) 3044 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 3045 CP->getAlignment()); 3046 else 3047 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 3048 CP->getAlignment()); 3049 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 3050 } 3051 3052 unsigned ARMTargetLowering::getJumpTableEncoding() const { 3053 return MachineJumpTableInfo::EK_Inline; 3054 } 3055 3056 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 3057 SelectionDAG &DAG) const { 3058 MachineFunction &MF = DAG.getMachineFunction(); 3059 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3060 unsigned ARMPCLabelIndex = 0; 3061 SDLoc DL(Op); 3062 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3063 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 3064 SDValue CPAddr; 3065 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 3066 if (!IsPositionIndependent) { 3067 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 3068 } else { 3069 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3070 ARMPCLabelIndex = AFI->createPICLabelUId(); 3071 ARMConstantPoolValue *CPV = 3072 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3073 ARMCP::CPBlockAddress, PCAdj); 3074 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3075 } 3076 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3077 SDValue Result = DAG.getLoad( 3078 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3079 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3080 if (!IsPositionIndependent) 3081 return Result; 3082 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3083 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3084 } 3085 3086 /// Convert a TLS address reference into the correct sequence of loads 3087 /// and calls to compute the variable's address for Darwin, and return an 3088 /// SDValue containing the final node. 3089 3090 /// Darwin only has one TLS scheme which must be capable of dealing with the 3091 /// fully general situation, in the worst case. This means: 3092 /// + "extern __thread" declaration. 3093 /// + Defined in a possibly unknown dynamic library. 3094 /// 3095 /// The general system is that each __thread variable has a [3 x i32] descriptor 3096 /// which contains information used by the runtime to calculate the address. The 3097 /// only part of this the compiler needs to know about is the first word, which 3098 /// contains a function pointer that must be called with the address of the 3099 /// entire descriptor in "r0". 3100 /// 3101 /// Since this descriptor may be in a different unit, in general access must 3102 /// proceed along the usual ARM rules. A common sequence to produce is: 3103 /// 3104 /// movw rT1, :lower16:_var$non_lazy_ptr 3105 /// movt rT1, :upper16:_var$non_lazy_ptr 3106 /// ldr r0, [rT1] 3107 /// ldr rT2, [r0] 3108 /// blx rT2 3109 /// [...address now in r0...] 3110 SDValue 3111 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3112 SelectionDAG &DAG) const { 3113 assert(Subtarget->isTargetDarwin() && 3114 "This function expects a Darwin target"); 3115 SDLoc DL(Op); 3116 3117 // First step is to get the address of the actua global symbol. This is where 3118 // the TLS descriptor lives. 3119 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3120 3121 // The first entry in the descriptor is a function pointer that we must call 3122 // to obtain the address of the variable. 3123 SDValue Chain = DAG.getEntryNode(); 3124 SDValue FuncTLVGet = DAG.getLoad( 3125 MVT::i32, DL, Chain, DescAddr, 3126 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3127 /* Alignment = */ 4, 3128 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3129 MachineMemOperand::MOInvariant); 3130 Chain = FuncTLVGet.getValue(1); 3131 3132 MachineFunction &F = DAG.getMachineFunction(); 3133 MachineFrameInfo &MFI = F.getFrameInfo(); 3134 MFI.setAdjustsStack(true); 3135 3136 // TLS calls preserve all registers except those that absolutely must be 3137 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3138 // silly). 3139 auto TRI = 3140 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3141 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3142 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3143 3144 // Finally, we can make the call. This is just a degenerate version of a 3145 // normal AArch64 call node: r0 takes the address of the descriptor, and 3146 // returns the address of the variable in this thread. 3147 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3148 Chain = 3149 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3150 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3151 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3152 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3153 } 3154 3155 SDValue 3156 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3157 SelectionDAG &DAG) const { 3158 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3159 3160 SDValue Chain = DAG.getEntryNode(); 3161 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3162 SDLoc DL(Op); 3163 3164 // Load the current TEB (thread environment block) 3165 SDValue Ops[] = {Chain, 3166 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3167 DAG.getTargetConstant(15, DL, MVT::i32), 3168 DAG.getTargetConstant(0, DL, MVT::i32), 3169 DAG.getTargetConstant(13, DL, MVT::i32), 3170 DAG.getTargetConstant(0, DL, MVT::i32), 3171 DAG.getTargetConstant(2, DL, MVT::i32)}; 3172 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3173 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3174 3175 SDValue TEB = CurrentTEB.getValue(0); 3176 Chain = CurrentTEB.getValue(1); 3177 3178 // Load the ThreadLocalStoragePointer from the TEB 3179 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3180 SDValue TLSArray = 3181 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3182 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3183 3184 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3185 // offset into the TLSArray. 3186 3187 // Load the TLS index from the C runtime 3188 SDValue TLSIndex = 3189 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3190 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3191 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3192 3193 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3194 DAG.getConstant(2, DL, MVT::i32)); 3195 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3196 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3197 MachinePointerInfo()); 3198 3199 // Get the offset of the start of the .tls section (section base) 3200 const auto *GA = cast<GlobalAddressSDNode>(Op); 3201 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3202 SDValue Offset = DAG.getLoad( 3203 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3204 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 3205 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3206 3207 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3208 } 3209 3210 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3211 SDValue 3212 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3213 SelectionDAG &DAG) const { 3214 SDLoc dl(GA); 3215 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3216 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3217 MachineFunction &MF = DAG.getMachineFunction(); 3218 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3219 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3220 ARMConstantPoolValue *CPV = 3221 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3222 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3223 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3224 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3225 Argument = DAG.getLoad( 3226 PtrVT, dl, DAG.getEntryNode(), Argument, 3227 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3228 SDValue Chain = Argument.getValue(1); 3229 3230 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3231 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3232 3233 // call __tls_get_addr. 3234 ArgListTy Args; 3235 ArgListEntry Entry; 3236 Entry.Node = Argument; 3237 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3238 Args.push_back(Entry); 3239 3240 // FIXME: is there useful debug info available here? 3241 TargetLowering::CallLoweringInfo CLI(DAG); 3242 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3243 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3244 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3245 3246 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3247 return CallResult.first; 3248 } 3249 3250 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3251 // "local exec" model. 3252 SDValue 3253 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3254 SelectionDAG &DAG, 3255 TLSModel::Model model) const { 3256 const GlobalValue *GV = GA->getGlobal(); 3257 SDLoc dl(GA); 3258 SDValue Offset; 3259 SDValue Chain = DAG.getEntryNode(); 3260 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3261 // Get the Thread Pointer 3262 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3263 3264 if (model == TLSModel::InitialExec) { 3265 MachineFunction &MF = DAG.getMachineFunction(); 3266 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3267 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3268 // Initial exec model. 3269 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3270 ARMConstantPoolValue *CPV = 3271 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3272 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3273 true); 3274 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3275 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3276 Offset = DAG.getLoad( 3277 PtrVT, dl, Chain, Offset, 3278 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3279 Chain = Offset.getValue(1); 3280 3281 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3282 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3283 3284 Offset = DAG.getLoad( 3285 PtrVT, dl, Chain, Offset, 3286 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3287 } else { 3288 // local exec model 3289 assert(model == TLSModel::LocalExec); 3290 ARMConstantPoolValue *CPV = 3291 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3292 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3293 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3294 Offset = DAG.getLoad( 3295 PtrVT, dl, Chain, Offset, 3296 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3297 } 3298 3299 // The address of the thread local variable is the add of the thread 3300 // pointer with the offset of the variable. 3301 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3302 } 3303 3304 SDValue 3305 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3306 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3307 if (DAG.getTarget().useEmulatedTLS()) 3308 return LowerToTLSEmulatedModel(GA, DAG); 3309 3310 if (Subtarget->isTargetDarwin()) 3311 return LowerGlobalTLSAddressDarwin(Op, DAG); 3312 3313 if (Subtarget->isTargetWindows()) 3314 return LowerGlobalTLSAddressWindows(Op, DAG); 3315 3316 // TODO: implement the "local dynamic" model 3317 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3318 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3319 3320 switch (model) { 3321 case TLSModel::GeneralDynamic: 3322 case TLSModel::LocalDynamic: 3323 return LowerToTLSGeneralDynamicModel(GA, DAG); 3324 case TLSModel::InitialExec: 3325 case TLSModel::LocalExec: 3326 return LowerToTLSExecModels(GA, DAG, model); 3327 } 3328 llvm_unreachable("bogus TLS model"); 3329 } 3330 3331 /// Return true if all users of V are within function F, looking through 3332 /// ConstantExprs. 3333 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3334 SmallVector<const User*,4> Worklist; 3335 for (auto *U : V->users()) 3336 Worklist.push_back(U); 3337 while (!Worklist.empty()) { 3338 auto *U = Worklist.pop_back_val(); 3339 if (isa<ConstantExpr>(U)) { 3340 for (auto *UU : U->users()) 3341 Worklist.push_back(UU); 3342 continue; 3343 } 3344 3345 auto *I = dyn_cast<Instruction>(U); 3346 if (!I || I->getParent()->getParent() != F) 3347 return false; 3348 } 3349 return true; 3350 } 3351 3352 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3353 const GlobalValue *GV, SelectionDAG &DAG, 3354 EVT PtrVT, const SDLoc &dl) { 3355 // If we're creating a pool entry for a constant global with unnamed address, 3356 // and the global is small enough, we can emit it inline into the constant pool 3357 // to save ourselves an indirection. 3358 // 3359 // This is a win if the constant is only used in one function (so it doesn't 3360 // need to be duplicated) or duplicating the constant wouldn't increase code 3361 // size (implying the constant is no larger than 4 bytes). 3362 const Function &F = DAG.getMachineFunction().getFunction(); 3363 3364 // We rely on this decision to inline being idemopotent and unrelated to the 3365 // use-site. We know that if we inline a variable at one use site, we'll 3366 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3367 // doesn't know about this optimization, so bail out if it's enabled else 3368 // we could decide to inline here (and thus never emit the GV) but require 3369 // the GV from fast-isel generated code. 3370 if (!EnableConstpoolPromotion || 3371 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3372 return SDValue(); 3373 3374 auto *GVar = dyn_cast<GlobalVariable>(GV); 3375 if (!GVar || !GVar->hasInitializer() || 3376 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3377 !GVar->hasLocalLinkage()) 3378 return SDValue(); 3379 3380 // If we inline a value that contains relocations, we move the relocations 3381 // from .data to .text. This is not allowed in position-independent code. 3382 auto *Init = GVar->getInitializer(); 3383 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3384 Init->needsRelocation()) 3385 return SDValue(); 3386 3387 // The constant islands pass can only really deal with alignment requests 3388 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3389 // any type wanting greater alignment requirements than 4 bytes. We also 3390 // can only promote constants that are multiples of 4 bytes in size or 3391 // are paddable to a multiple of 4. Currently we only try and pad constants 3392 // that are strings for simplicity. 3393 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3394 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3395 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3396 unsigned RequiredPadding = 4 - (Size % 4); 3397 bool PaddingPossible = 3398 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3399 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3400 Size == 0) 3401 return SDValue(); 3402 3403 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3404 MachineFunction &MF = DAG.getMachineFunction(); 3405 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3406 3407 // We can't bloat the constant pool too much, else the ConstantIslands pass 3408 // may fail to converge. If we haven't promoted this global yet (it may have 3409 // multiple uses), and promoting it would increase the constant pool size (Sz 3410 // > 4), ensure we have space to do so up to MaxTotal. 3411 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3412 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3413 ConstpoolPromotionMaxTotal) 3414 return SDValue(); 3415 3416 // This is only valid if all users are in a single function; we can't clone 3417 // the constant in general. The LLVM IR unnamed_addr allows merging 3418 // constants, but not cloning them. 3419 // 3420 // We could potentially allow cloning if we could prove all uses of the 3421 // constant in the current function don't care about the address, like 3422 // printf format strings. But that isn't implemented for now. 3423 if (!allUsersAreInFunction(GVar, &F)) 3424 return SDValue(); 3425 3426 // We're going to inline this global. Pad it out if needed. 3427 if (RequiredPadding != 4) { 3428 StringRef S = CDAInit->getAsString(); 3429 3430 SmallVector<uint8_t,16> V(S.size()); 3431 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3432 while (RequiredPadding--) 3433 V.push_back(0); 3434 Init = ConstantDataArray::get(*DAG.getContext(), V); 3435 } 3436 3437 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3438 SDValue CPAddr = 3439 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3440 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3441 AFI->markGlobalAsPromotedToConstantPool(GVar); 3442 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3443 PaddedSize - 4); 3444 } 3445 ++NumConstpoolPromoted; 3446 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3447 } 3448 3449 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3450 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3451 if (!(GV = GA->getBaseObject())) 3452 return false; 3453 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3454 return V->isConstant(); 3455 return isa<Function>(GV); 3456 } 3457 3458 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3459 SelectionDAG &DAG) const { 3460 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3461 default: llvm_unreachable("unknown object format"); 3462 case Triple::COFF: 3463 return LowerGlobalAddressWindows(Op, DAG); 3464 case Triple::ELF: 3465 return LowerGlobalAddressELF(Op, DAG); 3466 case Triple::MachO: 3467 return LowerGlobalAddressDarwin(Op, DAG); 3468 } 3469 } 3470 3471 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3472 SelectionDAG &DAG) const { 3473 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3474 SDLoc dl(Op); 3475 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3476 const TargetMachine &TM = getTargetMachine(); 3477 bool IsRO = isReadOnly(GV); 3478 3479 // promoteToConstantPool only if not generating XO text section 3480 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3481 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3482 return V; 3483 3484 if (isPositionIndependent()) { 3485 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3486 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3487 UseGOT_PREL ? ARMII::MO_GOT : 0); 3488 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3489 if (UseGOT_PREL) 3490 Result = 3491 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3492 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3493 return Result; 3494 } else if (Subtarget->isROPI() && IsRO) { 3495 // PC-relative. 3496 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3497 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3498 return Result; 3499 } else if (Subtarget->isRWPI() && !IsRO) { 3500 // SB-relative. 3501 SDValue RelAddr; 3502 if (Subtarget->useMovt()) { 3503 ++NumMovwMovt; 3504 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3505 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3506 } else { // use literal pool for address constant 3507 ARMConstantPoolValue *CPV = 3508 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3509 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3510 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3511 RelAddr = DAG.getLoad( 3512 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3513 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3514 } 3515 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3516 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3517 return Result; 3518 } 3519 3520 // If we have T2 ops, we can materialize the address directly via movt/movw 3521 // pair. This is always cheaper. 3522 if (Subtarget->useMovt()) { 3523 ++NumMovwMovt; 3524 // FIXME: Once remat is capable of dealing with instructions with register 3525 // operands, expand this into two nodes. 3526 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3527 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3528 } else { 3529 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3530 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3531 return DAG.getLoad( 3532 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3533 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3534 } 3535 } 3536 3537 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3538 SelectionDAG &DAG) const { 3539 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3540 "ROPI/RWPI not currently supported for Darwin"); 3541 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3542 SDLoc dl(Op); 3543 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3544 3545 if (Subtarget->useMovt()) 3546 ++NumMovwMovt; 3547 3548 // FIXME: Once remat is capable of dealing with instructions with register 3549 // operands, expand this into multiple nodes 3550 unsigned Wrapper = 3551 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3552 3553 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3554 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3555 3556 if (Subtarget->isGVIndirectSymbol(GV)) 3557 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3558 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3559 return Result; 3560 } 3561 3562 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3563 SelectionDAG &DAG) const { 3564 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3565 assert(Subtarget->useMovt() && 3566 "Windows on ARM expects to use movw/movt"); 3567 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3568 "ROPI/RWPI not currently supported for Windows"); 3569 3570 const TargetMachine &TM = getTargetMachine(); 3571 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3572 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3573 if (GV->hasDLLImportStorageClass()) 3574 TargetFlags = ARMII::MO_DLLIMPORT; 3575 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3576 TargetFlags = ARMII::MO_COFFSTUB; 3577 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3578 SDValue Result; 3579 SDLoc DL(Op); 3580 3581 ++NumMovwMovt; 3582 3583 // FIXME: Once remat is capable of dealing with instructions with register 3584 // operands, expand this into two nodes. 3585 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3586 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3587 TargetFlags)); 3588 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3589 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3590 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3591 return Result; 3592 } 3593 3594 SDValue 3595 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3596 SDLoc dl(Op); 3597 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3598 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3599 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3600 Op.getOperand(1), Val); 3601 } 3602 3603 SDValue 3604 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3605 SDLoc dl(Op); 3606 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3607 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3608 } 3609 3610 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3611 SelectionDAG &DAG) const { 3612 SDLoc dl(Op); 3613 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3614 Op.getOperand(0)); 3615 } 3616 3617 SDValue ARMTargetLowering::LowerINTRINSIC_VOID( 3618 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const { 3619 unsigned IntNo = 3620 cast<ConstantSDNode>( 3621 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other)) 3622 ->getZExtValue(); 3623 switch (IntNo) { 3624 default: 3625 return SDValue(); // Don't custom lower most intrinsics. 3626 case Intrinsic::arm_gnu_eabi_mcount: { 3627 MachineFunction &MF = DAG.getMachineFunction(); 3628 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3629 SDLoc dl(Op); 3630 SDValue Chain = Op.getOperand(0); 3631 // call "\01__gnu_mcount_nc" 3632 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 3633 const uint32_t *Mask = 3634 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3635 assert(Mask && "Missing call preserved mask for calling convention"); 3636 // Mark LR an implicit live-in. 3637 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3638 SDValue ReturnAddress = 3639 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT); 3640 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue}; 3641 SDValue Callee = 3642 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0); 3643 SDValue RegisterMask = DAG.getRegisterMask(Mask); 3644 if (Subtarget->isThumb()) 3645 return SDValue( 3646 DAG.getMachineNode( 3647 ARM::tBL_PUSHLR, dl, ResultTys, 3648 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT), 3649 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}), 3650 0); 3651 return SDValue( 3652 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys, 3653 {ReturnAddress, Callee, RegisterMask, Chain}), 3654 0); 3655 } 3656 } 3657 } 3658 3659 SDValue 3660 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3661 const ARMSubtarget *Subtarget) const { 3662 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3663 SDLoc dl(Op); 3664 switch (IntNo) { 3665 default: return SDValue(); // Don't custom lower most intrinsics. 3666 case Intrinsic::thread_pointer: { 3667 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3668 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3669 } 3670 case Intrinsic::arm_cls: { 3671 const SDValue &Operand = Op.getOperand(1); 3672 const EVT VTy = Op.getValueType(); 3673 SDValue SRA = 3674 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy)); 3675 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand); 3676 SDValue SHL = 3677 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy)); 3678 SDValue OR = 3679 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy)); 3680 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR); 3681 return Result; 3682 } 3683 case Intrinsic::arm_cls64: { 3684 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x)) 3685 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x))) 3686 const SDValue &Operand = Op.getOperand(1); 3687 const EVT VTy = Op.getValueType(); 3688 3689 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3690 DAG.getConstant(1, dl, VTy)); 3691 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3692 DAG.getConstant(0, dl, VTy)); 3693 SDValue Constant0 = DAG.getConstant(0, dl, VTy); 3694 SDValue Constant1 = DAG.getConstant(1, dl, VTy); 3695 SDValue Constant31 = DAG.getConstant(31, dl, VTy); 3696 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31); 3697 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi); 3698 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1); 3699 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1); 3700 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi); 3701 SDValue CheckLo = 3702 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ); 3703 SDValue HiIsZero = 3704 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ); 3705 SDValue AdjustedLo = 3706 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy)); 3707 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo); 3708 SDValue Result = 3709 DAG.getSelect(dl, VTy, CheckLo, 3710 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi); 3711 return Result; 3712 } 3713 case Intrinsic::eh_sjlj_lsda: { 3714 MachineFunction &MF = DAG.getMachineFunction(); 3715 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3716 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3717 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3718 SDValue CPAddr; 3719 bool IsPositionIndependent = isPositionIndependent(); 3720 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3721 ARMConstantPoolValue *CPV = 3722 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3723 ARMCP::CPLSDA, PCAdj); 3724 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3725 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3726 SDValue Result = DAG.getLoad( 3727 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3728 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3729 3730 if (IsPositionIndependent) { 3731 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3732 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3733 } 3734 return Result; 3735 } 3736 case Intrinsic::arm_neon_vabs: 3737 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3738 Op.getOperand(1)); 3739 case Intrinsic::arm_neon_vmulls: 3740 case Intrinsic::arm_neon_vmullu: { 3741 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3742 ? ARMISD::VMULLs : ARMISD::VMULLu; 3743 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3744 Op.getOperand(1), Op.getOperand(2)); 3745 } 3746 case Intrinsic::arm_neon_vminnm: 3747 case Intrinsic::arm_neon_vmaxnm: { 3748 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3749 ? ISD::FMINNUM : ISD::FMAXNUM; 3750 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3751 Op.getOperand(1), Op.getOperand(2)); 3752 } 3753 case Intrinsic::arm_neon_vminu: 3754 case Intrinsic::arm_neon_vmaxu: { 3755 if (Op.getValueType().isFloatingPoint()) 3756 return SDValue(); 3757 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3758 ? ISD::UMIN : ISD::UMAX; 3759 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3760 Op.getOperand(1), Op.getOperand(2)); 3761 } 3762 case Intrinsic::arm_neon_vmins: 3763 case Intrinsic::arm_neon_vmaxs: { 3764 // v{min,max}s is overloaded between signed integers and floats. 3765 if (!Op.getValueType().isFloatingPoint()) { 3766 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3767 ? ISD::SMIN : ISD::SMAX; 3768 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3769 Op.getOperand(1), Op.getOperand(2)); 3770 } 3771 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3772 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3773 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3774 Op.getOperand(1), Op.getOperand(2)); 3775 } 3776 case Intrinsic::arm_neon_vtbl1: 3777 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3778 Op.getOperand(1), Op.getOperand(2)); 3779 case Intrinsic::arm_neon_vtbl2: 3780 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3781 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3782 case Intrinsic::arm_mve_pred_i2v: 3783 case Intrinsic::arm_mve_pred_v2i: 3784 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(), 3785 Op.getOperand(1)); 3786 case Intrinsic::arm_mve_vreinterpretq: 3787 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(), 3788 Op.getOperand(1)); 3789 } 3790 } 3791 3792 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3793 const ARMSubtarget *Subtarget) { 3794 SDLoc dl(Op); 3795 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3796 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3797 if (SSID == SyncScope::SingleThread) 3798 return Op; 3799 3800 if (!Subtarget->hasDataBarrier()) { 3801 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3802 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3803 // here. 3804 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3805 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3806 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3807 DAG.getConstant(0, dl, MVT::i32)); 3808 } 3809 3810 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3811 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3812 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3813 if (Subtarget->isMClass()) { 3814 // Only a full system barrier exists in the M-class architectures. 3815 Domain = ARM_MB::SY; 3816 } else if (Subtarget->preferISHSTBarriers() && 3817 Ord == AtomicOrdering::Release) { 3818 // Swift happens to implement ISHST barriers in a way that's compatible with 3819 // Release semantics but weaker than ISH so we'd be fools not to use 3820 // it. Beware: other processors probably don't! 3821 Domain = ARM_MB::ISHST; 3822 } 3823 3824 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3825 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3826 DAG.getConstant(Domain, dl, MVT::i32)); 3827 } 3828 3829 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3830 const ARMSubtarget *Subtarget) { 3831 // ARM pre v5TE and Thumb1 does not have preload instructions. 3832 if (!(Subtarget->isThumb2() || 3833 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3834 // Just preserve the chain. 3835 return Op.getOperand(0); 3836 3837 SDLoc dl(Op); 3838 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3839 if (!isRead && 3840 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3841 // ARMv7 with MP extension has PLDW. 3842 return Op.getOperand(0); 3843 3844 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3845 if (Subtarget->isThumb()) { 3846 // Invert the bits. 3847 isRead = ~isRead & 1; 3848 isData = ~isData & 1; 3849 } 3850 3851 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3852 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3853 DAG.getConstant(isData, dl, MVT::i32)); 3854 } 3855 3856 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3857 MachineFunction &MF = DAG.getMachineFunction(); 3858 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3859 3860 // vastart just stores the address of the VarArgsFrameIndex slot into the 3861 // memory location argument. 3862 SDLoc dl(Op); 3863 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3864 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3865 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3866 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3867 MachinePointerInfo(SV)); 3868 } 3869 3870 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3871 CCValAssign &NextVA, 3872 SDValue &Root, 3873 SelectionDAG &DAG, 3874 const SDLoc &dl) const { 3875 MachineFunction &MF = DAG.getMachineFunction(); 3876 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3877 3878 const TargetRegisterClass *RC; 3879 if (AFI->isThumb1OnlyFunction()) 3880 RC = &ARM::tGPRRegClass; 3881 else 3882 RC = &ARM::GPRRegClass; 3883 3884 // Transform the arguments stored in physical registers into virtual ones. 3885 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3886 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3887 3888 SDValue ArgValue2; 3889 if (NextVA.isMemLoc()) { 3890 MachineFrameInfo &MFI = MF.getFrameInfo(); 3891 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3892 3893 // Create load node to retrieve arguments from the stack. 3894 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3895 ArgValue2 = DAG.getLoad( 3896 MVT::i32, dl, Root, FIN, 3897 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3898 } else { 3899 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3900 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3901 } 3902 if (!Subtarget->isLittle()) 3903 std::swap (ArgValue, ArgValue2); 3904 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3905 } 3906 3907 // The remaining GPRs hold either the beginning of variable-argument 3908 // data, or the beginning of an aggregate passed by value (usually 3909 // byval). Either way, we allocate stack slots adjacent to the data 3910 // provided by our caller, and store the unallocated registers there. 3911 // If this is a variadic function, the va_list pointer will begin with 3912 // these values; otherwise, this reassembles a (byval) structure that 3913 // was split between registers and memory. 3914 // Return: The frame index registers were stored into. 3915 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3916 const SDLoc &dl, SDValue &Chain, 3917 const Value *OrigArg, 3918 unsigned InRegsParamRecordIdx, 3919 int ArgOffset, unsigned ArgSize) const { 3920 // Currently, two use-cases possible: 3921 // Case #1. Non-var-args function, and we meet first byval parameter. 3922 // Setup first unallocated register as first byval register; 3923 // eat all remained registers 3924 // (these two actions are performed by HandleByVal method). 3925 // Then, here, we initialize stack frame with 3926 // "store-reg" instructions. 3927 // Case #2. Var-args function, that doesn't contain byval parameters. 3928 // The same: eat all remained unallocated registers, 3929 // initialize stack frame. 3930 3931 MachineFunction &MF = DAG.getMachineFunction(); 3932 MachineFrameInfo &MFI = MF.getFrameInfo(); 3933 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3934 unsigned RBegin, REnd; 3935 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3936 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3937 } else { 3938 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3939 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3940 REnd = ARM::R4; 3941 } 3942 3943 if (REnd != RBegin) 3944 ArgOffset = -4 * (ARM::R4 - RBegin); 3945 3946 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3947 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3948 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3949 3950 SmallVector<SDValue, 4> MemOps; 3951 const TargetRegisterClass *RC = 3952 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3953 3954 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3955 unsigned VReg = MF.addLiveIn(Reg, RC); 3956 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3957 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3958 MachinePointerInfo(OrigArg, 4 * i)); 3959 MemOps.push_back(Store); 3960 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3961 } 3962 3963 if (!MemOps.empty()) 3964 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3965 return FrameIndex; 3966 } 3967 3968 // Setup stack frame, the va_list pointer will start from. 3969 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3970 const SDLoc &dl, SDValue &Chain, 3971 unsigned ArgOffset, 3972 unsigned TotalArgRegsSaveSize, 3973 bool ForceMutable) const { 3974 MachineFunction &MF = DAG.getMachineFunction(); 3975 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3976 3977 // Try to store any remaining integer argument regs 3978 // to their spots on the stack so that they may be loaded by dereferencing 3979 // the result of va_next. 3980 // If there is no regs to be stored, just point address after last 3981 // argument passed via stack. 3982 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3983 CCInfo.getInRegsParamsCount(), 3984 CCInfo.getNextStackOffset(), 3985 std::max(4U, TotalArgRegsSaveSize)); 3986 AFI->setVarArgsFrameIndex(FrameIndex); 3987 } 3988 3989 SDValue ARMTargetLowering::LowerFormalArguments( 3990 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3991 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3992 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3993 MachineFunction &MF = DAG.getMachineFunction(); 3994 MachineFrameInfo &MFI = MF.getFrameInfo(); 3995 3996 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3997 3998 // Assign locations to all of the incoming arguments. 3999 SmallVector<CCValAssign, 16> ArgLocs; 4000 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4001 *DAG.getContext()); 4002 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 4003 4004 SmallVector<SDValue, 16> ArgValues; 4005 SDValue ArgValue; 4006 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4007 unsigned CurArgIdx = 0; 4008 4009 // Initially ArgRegsSaveSize is zero. 4010 // Then we increase this value each time we meet byval parameter. 4011 // We also increase this value in case of varargs function. 4012 AFI->setArgRegsSaveSize(0); 4013 4014 // Calculate the amount of stack space that we need to allocate to store 4015 // byval and variadic arguments that are passed in registers. 4016 // We need to know this before we allocate the first byval or variadic 4017 // argument, as they will be allocated a stack slot below the CFA (Canonical 4018 // Frame Address, the stack pointer at entry to the function). 4019 unsigned ArgRegBegin = ARM::R4; 4020 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4021 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 4022 break; 4023 4024 CCValAssign &VA = ArgLocs[i]; 4025 unsigned Index = VA.getValNo(); 4026 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 4027 if (!Flags.isByVal()) 4028 continue; 4029 4030 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 4031 unsigned RBegin, REnd; 4032 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 4033 ArgRegBegin = std::min(ArgRegBegin, RBegin); 4034 4035 CCInfo.nextInRegsParam(); 4036 } 4037 CCInfo.rewindByValRegsInfo(); 4038 4039 int lastInsIndex = -1; 4040 if (isVarArg && MFI.hasVAStart()) { 4041 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4042 if (RegIdx != array_lengthof(GPRArgRegs)) 4043 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 4044 } 4045 4046 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 4047 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 4048 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4049 4050 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4051 CCValAssign &VA = ArgLocs[i]; 4052 if (Ins[VA.getValNo()].isOrigArg()) { 4053 std::advance(CurOrigArg, 4054 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 4055 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 4056 } 4057 // Arguments stored in registers. 4058 if (VA.isRegLoc()) { 4059 EVT RegVT = VA.getLocVT(); 4060 4061 if (VA.needsCustom()) { 4062 // f64 and vector types are split up into multiple registers or 4063 // combinations of registers and stack slots. 4064 if (VA.getLocVT() == MVT::v2f64) { 4065 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 4066 Chain, DAG, dl); 4067 VA = ArgLocs[++i]; // skip ahead to next loc 4068 SDValue ArgValue2; 4069 if (VA.isMemLoc()) { 4070 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 4071 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4072 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 4073 MachinePointerInfo::getFixedStack( 4074 DAG.getMachineFunction(), FI)); 4075 } else { 4076 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 4077 Chain, DAG, dl); 4078 } 4079 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 4080 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 4081 ArgValue, ArgValue1, 4082 DAG.getIntPtrConstant(0, dl)); 4083 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 4084 ArgValue, ArgValue2, 4085 DAG.getIntPtrConstant(1, dl)); 4086 } else 4087 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4088 } else { 4089 const TargetRegisterClass *RC; 4090 4091 4092 if (RegVT == MVT::f16) 4093 RC = &ARM::HPRRegClass; 4094 else if (RegVT == MVT::f32) 4095 RC = &ARM::SPRRegClass; 4096 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 4097 RC = &ARM::DPRRegClass; 4098 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 4099 RC = &ARM::QPRRegClass; 4100 else if (RegVT == MVT::i32) 4101 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 4102 : &ARM::GPRRegClass; 4103 else 4104 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4105 4106 // Transform the arguments in physical registers into virtual ones. 4107 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4108 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 4109 4110 // If this value is passed in r0 and has the returned attribute (e.g. 4111 // C++ 'structors), record this fact for later use. 4112 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 4113 AFI->setPreservesR0(); 4114 } 4115 } 4116 4117 // If this is an 8 or 16-bit value, it is really passed promoted 4118 // to 32 bits. Insert an assert[sz]ext to capture this, then 4119 // truncate to the right size. 4120 switch (VA.getLocInfo()) { 4121 default: llvm_unreachable("Unknown loc info!"); 4122 case CCValAssign::Full: break; 4123 case CCValAssign::BCvt: 4124 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 4125 break; 4126 case CCValAssign::SExt: 4127 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 4128 DAG.getValueType(VA.getValVT())); 4129 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4130 break; 4131 case CCValAssign::ZExt: 4132 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 4133 DAG.getValueType(VA.getValVT())); 4134 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4135 break; 4136 } 4137 4138 InVals.push_back(ArgValue); 4139 } else { // VA.isRegLoc() 4140 // sanity check 4141 assert(VA.isMemLoc()); 4142 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 4143 4144 int index = VA.getValNo(); 4145 4146 // Some Ins[] entries become multiple ArgLoc[] entries. 4147 // Process them only once. 4148 if (index != lastInsIndex) 4149 { 4150 ISD::ArgFlagsTy Flags = Ins[index].Flags; 4151 // FIXME: For now, all byval parameter objects are marked mutable. 4152 // This can be changed with more analysis. 4153 // In case of tail call optimization mark all arguments mutable. 4154 // Since they could be overwritten by lowering of arguments in case of 4155 // a tail call. 4156 if (Flags.isByVal()) { 4157 assert(Ins[index].isOrigArg() && 4158 "Byval arguments cannot be implicit"); 4159 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 4160 4161 int FrameIndex = StoreByValRegs( 4162 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4163 VA.getLocMemOffset(), Flags.getByValSize()); 4164 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4165 CCInfo.nextInRegsParam(); 4166 } else { 4167 unsigned FIOffset = VA.getLocMemOffset(); 4168 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4169 FIOffset, true); 4170 4171 // Create load nodes to retrieve arguments from the stack. 4172 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4173 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4174 MachinePointerInfo::getFixedStack( 4175 DAG.getMachineFunction(), FI))); 4176 } 4177 lastInsIndex = index; 4178 } 4179 } 4180 } 4181 4182 // varargs 4183 if (isVarArg && MFI.hasVAStart()) 4184 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 4185 CCInfo.getNextStackOffset(), 4186 TotalArgRegsSaveSize); 4187 4188 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4189 4190 return Chain; 4191 } 4192 4193 /// isFloatingPointZero - Return true if this is +0.0. 4194 static bool isFloatingPointZero(SDValue Op) { 4195 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4196 return CFP->getValueAPF().isPosZero(); 4197 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4198 // Maybe this has already been legalized into the constant pool? 4199 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4200 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4201 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4202 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4203 return CFP->getValueAPF().isPosZero(); 4204 } 4205 } else if (Op->getOpcode() == ISD::BITCAST && 4206 Op->getValueType(0) == MVT::f64) { 4207 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4208 // created by LowerConstantFP(). 4209 SDValue BitcastOp = Op->getOperand(0); 4210 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4211 isNullConstant(BitcastOp->getOperand(0))) 4212 return true; 4213 } 4214 return false; 4215 } 4216 4217 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4218 /// the given operands. 4219 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4220 SDValue &ARMcc, SelectionDAG &DAG, 4221 const SDLoc &dl) const { 4222 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4223 unsigned C = RHSC->getZExtValue(); 4224 if (!isLegalICmpImmediate((int32_t)C)) { 4225 // Constant does not fit, try adjusting it by one. 4226 switch (CC) { 4227 default: break; 4228 case ISD::SETLT: 4229 case ISD::SETGE: 4230 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4231 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4232 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4233 } 4234 break; 4235 case ISD::SETULT: 4236 case ISD::SETUGE: 4237 if (C != 0 && isLegalICmpImmediate(C-1)) { 4238 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4239 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4240 } 4241 break; 4242 case ISD::SETLE: 4243 case ISD::SETGT: 4244 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4245 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4246 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4247 } 4248 break; 4249 case ISD::SETULE: 4250 case ISD::SETUGT: 4251 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4252 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4253 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4254 } 4255 break; 4256 } 4257 } 4258 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4259 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4260 // In ARM and Thumb-2, the compare instructions can shift their second 4261 // operand. 4262 CC = ISD::getSetCCSwappedOperands(CC); 4263 std::swap(LHS, RHS); 4264 } 4265 4266 // Thumb1 has very limited immediate modes, so turning an "and" into a 4267 // shift can save multiple instructions. 4268 // 4269 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4270 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4271 // own. If it's the operand to an unsigned comparison with an immediate, 4272 // we can eliminate one of the shifts: we transform 4273 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4274 // 4275 // We avoid transforming cases which aren't profitable due to encoding 4276 // details: 4277 // 4278 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4279 // would not; in that case, we're essentially trading one immediate load for 4280 // another. 4281 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4282 // 3. C2 is zero; we have other code for this special case. 4283 // 4284 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4285 // instruction, since the AND is always one instruction anyway, but we could 4286 // use narrow instructions in some cases. 4287 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4288 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4289 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4290 !isSignedIntSetCC(CC)) { 4291 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4292 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4293 uint64_t RHSV = RHSC->getZExtValue(); 4294 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4295 unsigned ShiftBits = countLeadingZeros(Mask); 4296 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4297 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4298 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4299 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4300 } 4301 } 4302 } 4303 4304 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4305 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4306 // way a cmp would. 4307 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4308 // some tweaks to the heuristics for the previous and->shift transform. 4309 // FIXME: Optimize cases where the LHS isn't a shift. 4310 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4311 isa<ConstantSDNode>(RHS) && 4312 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4313 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4314 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4315 unsigned ShiftAmt = 4316 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4317 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4318 DAG.getVTList(MVT::i32, MVT::i32), 4319 LHS.getOperand(0), 4320 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4321 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4322 Shift.getValue(1), SDValue()); 4323 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4324 return Chain.getValue(1); 4325 } 4326 4327 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4328 4329 // If the RHS is a constant zero then the V (overflow) flag will never be 4330 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4331 // simpler for other passes (like the peephole optimiser) to deal with. 4332 if (isNullConstant(RHS)) { 4333 switch (CondCode) { 4334 default: break; 4335 case ARMCC::GE: 4336 CondCode = ARMCC::PL; 4337 break; 4338 case ARMCC::LT: 4339 CondCode = ARMCC::MI; 4340 break; 4341 } 4342 } 4343 4344 ARMISD::NodeType CompareType; 4345 switch (CondCode) { 4346 default: 4347 CompareType = ARMISD::CMP; 4348 break; 4349 case ARMCC::EQ: 4350 case ARMCC::NE: 4351 // Uses only Z Flag 4352 CompareType = ARMISD::CMPZ; 4353 break; 4354 } 4355 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4356 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4357 } 4358 4359 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4360 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4361 SelectionDAG &DAG, const SDLoc &dl, 4362 bool Signaling) const { 4363 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4364 SDValue Cmp; 4365 if (!isFloatingPointZero(RHS)) 4366 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, 4367 dl, MVT::Glue, LHS, RHS); 4368 else 4369 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, 4370 dl, MVT::Glue, LHS); 4371 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4372 } 4373 4374 /// duplicateCmp - Glue values can have only one use, so this function 4375 /// duplicates a comparison node. 4376 SDValue 4377 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4378 unsigned Opc = Cmp.getOpcode(); 4379 SDLoc DL(Cmp); 4380 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4381 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4382 4383 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4384 Cmp = Cmp.getOperand(0); 4385 Opc = Cmp.getOpcode(); 4386 if (Opc == ARMISD::CMPFP) 4387 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4388 else { 4389 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4390 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 4391 } 4392 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4393 } 4394 4395 // This function returns three things: the arithmetic computation itself 4396 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4397 // comparison and the condition code define the case in which the arithmetic 4398 // computation *does not* overflow. 4399 std::pair<SDValue, SDValue> 4400 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4401 SDValue &ARMcc) const { 4402 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4403 4404 SDValue Value, OverflowCmp; 4405 SDValue LHS = Op.getOperand(0); 4406 SDValue RHS = Op.getOperand(1); 4407 SDLoc dl(Op); 4408 4409 // FIXME: We are currently always generating CMPs because we don't support 4410 // generating CMN through the backend. This is not as good as the natural 4411 // CMP case because it causes a register dependency and cannot be folded 4412 // later. 4413 4414 switch (Op.getOpcode()) { 4415 default: 4416 llvm_unreachable("Unknown overflow instruction!"); 4417 case ISD::SADDO: 4418 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4419 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4420 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4421 break; 4422 case ISD::UADDO: 4423 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4424 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4425 // We do not use it in the USUBO case as Value may not be used. 4426 Value = DAG.getNode(ARMISD::ADDC, dl, 4427 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4428 .getValue(0); 4429 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4430 break; 4431 case ISD::SSUBO: 4432 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4433 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4434 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4435 break; 4436 case ISD::USUBO: 4437 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4438 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4439 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4440 break; 4441 case ISD::UMULO: 4442 // We generate a UMUL_LOHI and then check if the high word is 0. 4443 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4444 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4445 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4446 LHS, RHS); 4447 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4448 DAG.getConstant(0, dl, MVT::i32)); 4449 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4450 break; 4451 case ISD::SMULO: 4452 // We generate a SMUL_LOHI and then check if all the bits of the high word 4453 // are the same as the sign bit of the low word. 4454 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4455 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4456 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4457 LHS, RHS); 4458 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4459 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4460 Value.getValue(0), 4461 DAG.getConstant(31, dl, MVT::i32))); 4462 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4463 break; 4464 } // switch (...) 4465 4466 return std::make_pair(Value, OverflowCmp); 4467 } 4468 4469 SDValue 4470 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4471 // Let legalize expand this if it isn't a legal type yet. 4472 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4473 return SDValue(); 4474 4475 SDValue Value, OverflowCmp; 4476 SDValue ARMcc; 4477 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4478 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4479 SDLoc dl(Op); 4480 // We use 0 and 1 as false and true values. 4481 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4482 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4483 EVT VT = Op.getValueType(); 4484 4485 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4486 ARMcc, CCR, OverflowCmp); 4487 4488 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4489 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4490 } 4491 4492 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4493 SelectionDAG &DAG) { 4494 SDLoc DL(BoolCarry); 4495 EVT CarryVT = BoolCarry.getValueType(); 4496 4497 // This converts the boolean value carry into the carry flag by doing 4498 // ARMISD::SUBC Carry, 1 4499 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4500 DAG.getVTList(CarryVT, MVT::i32), 4501 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4502 return Carry.getValue(1); 4503 } 4504 4505 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4506 SelectionDAG &DAG) { 4507 SDLoc DL(Flags); 4508 4509 // Now convert the carry flag into a boolean carry. We do this 4510 // using ARMISD:ADDE 0, 0, Carry 4511 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4512 DAG.getConstant(0, DL, MVT::i32), 4513 DAG.getConstant(0, DL, MVT::i32), Flags); 4514 } 4515 4516 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4517 SelectionDAG &DAG) const { 4518 // Let legalize expand this if it isn't a legal type yet. 4519 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4520 return SDValue(); 4521 4522 SDValue LHS = Op.getOperand(0); 4523 SDValue RHS = Op.getOperand(1); 4524 SDLoc dl(Op); 4525 4526 EVT VT = Op.getValueType(); 4527 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4528 SDValue Value; 4529 SDValue Overflow; 4530 switch (Op.getOpcode()) { 4531 default: 4532 llvm_unreachable("Unknown overflow instruction!"); 4533 case ISD::UADDO: 4534 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4535 // Convert the carry flag into a boolean value. 4536 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4537 break; 4538 case ISD::USUBO: { 4539 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4540 // Convert the carry flag into a boolean value. 4541 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4542 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4543 // value. So compute 1 - C. 4544 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4545 DAG.getConstant(1, dl, MVT::i32), Overflow); 4546 break; 4547 } 4548 } 4549 4550 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4551 } 4552 4553 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG, 4554 const ARMSubtarget *Subtarget) { 4555 EVT VT = Op.getValueType(); 4556 if (!Subtarget->hasDSP()) 4557 return SDValue(); 4558 if (!VT.isSimple()) 4559 return SDValue(); 4560 4561 unsigned NewOpcode; 4562 bool IsAdd = Op->getOpcode() == ISD::SADDSAT; 4563 switch (VT.getSimpleVT().SimpleTy) { 4564 default: 4565 return SDValue(); 4566 case MVT::i8: 4567 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b; 4568 break; 4569 case MVT::i16: 4570 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b; 4571 break; 4572 } 4573 4574 SDLoc dl(Op); 4575 SDValue Add = 4576 DAG.getNode(NewOpcode, dl, MVT::i32, 4577 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32), 4578 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32)); 4579 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add); 4580 } 4581 4582 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4583 SDValue Cond = Op.getOperand(0); 4584 SDValue SelectTrue = Op.getOperand(1); 4585 SDValue SelectFalse = Op.getOperand(2); 4586 SDLoc dl(Op); 4587 unsigned Opc = Cond.getOpcode(); 4588 4589 if (Cond.getResNo() == 1 && 4590 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4591 Opc == ISD::USUBO)) { 4592 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4593 return SDValue(); 4594 4595 SDValue Value, OverflowCmp; 4596 SDValue ARMcc; 4597 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4598 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4599 EVT VT = Op.getValueType(); 4600 4601 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4602 OverflowCmp, DAG); 4603 } 4604 4605 // Convert: 4606 // 4607 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4608 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4609 // 4610 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4611 const ConstantSDNode *CMOVTrue = 4612 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4613 const ConstantSDNode *CMOVFalse = 4614 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4615 4616 if (CMOVTrue && CMOVFalse) { 4617 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4618 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4619 4620 SDValue True; 4621 SDValue False; 4622 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4623 True = SelectTrue; 4624 False = SelectFalse; 4625 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4626 True = SelectFalse; 4627 False = SelectTrue; 4628 } 4629 4630 if (True.getNode() && False.getNode()) { 4631 EVT VT = Op.getValueType(); 4632 SDValue ARMcc = Cond.getOperand(2); 4633 SDValue CCR = Cond.getOperand(3); 4634 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4635 assert(True.getValueType() == VT); 4636 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4637 } 4638 } 4639 } 4640 4641 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4642 // undefined bits before doing a full-word comparison with zero. 4643 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4644 DAG.getConstant(1, dl, Cond.getValueType())); 4645 4646 return DAG.getSelectCC(dl, Cond, 4647 DAG.getConstant(0, dl, Cond.getValueType()), 4648 SelectTrue, SelectFalse, ISD::SETNE); 4649 } 4650 4651 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4652 bool &swpCmpOps, bool &swpVselOps) { 4653 // Start by selecting the GE condition code for opcodes that return true for 4654 // 'equality' 4655 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4656 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4657 CondCode = ARMCC::GE; 4658 4659 // and GT for opcodes that return false for 'equality'. 4660 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4661 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4662 CondCode = ARMCC::GT; 4663 4664 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4665 // to swap the compare operands. 4666 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4667 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4668 swpCmpOps = true; 4669 4670 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4671 // If we have an unordered opcode, we need to swap the operands to the VSEL 4672 // instruction (effectively negating the condition). 4673 // 4674 // This also has the effect of swapping which one of 'less' or 'greater' 4675 // returns true, so we also swap the compare operands. It also switches 4676 // whether we return true for 'equality', so we compensate by picking the 4677 // opposite condition code to our original choice. 4678 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4679 CC == ISD::SETUGT) { 4680 swpCmpOps = !swpCmpOps; 4681 swpVselOps = !swpVselOps; 4682 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4683 } 4684 4685 // 'ordered' is 'anything but unordered', so use the VS condition code and 4686 // swap the VSEL operands. 4687 if (CC == ISD::SETO) { 4688 CondCode = ARMCC::VS; 4689 swpVselOps = true; 4690 } 4691 4692 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4693 // code and swap the VSEL operands. Also do this if we don't care about the 4694 // unordered case. 4695 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4696 CondCode = ARMCC::EQ; 4697 swpVselOps = true; 4698 } 4699 } 4700 4701 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4702 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4703 SDValue Cmp, SelectionDAG &DAG) const { 4704 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4705 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4706 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4707 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4708 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4709 4710 SDValue TrueLow = TrueVal.getValue(0); 4711 SDValue TrueHigh = TrueVal.getValue(1); 4712 SDValue FalseLow = FalseVal.getValue(0); 4713 SDValue FalseHigh = FalseVal.getValue(1); 4714 4715 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4716 ARMcc, CCR, Cmp); 4717 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4718 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4719 4720 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4721 } else { 4722 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4723 Cmp); 4724 } 4725 } 4726 4727 static bool isGTorGE(ISD::CondCode CC) { 4728 return CC == ISD::SETGT || CC == ISD::SETGE; 4729 } 4730 4731 static bool isLTorLE(ISD::CondCode CC) { 4732 return CC == ISD::SETLT || CC == ISD::SETLE; 4733 } 4734 4735 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4736 // All of these conditions (and their <= and >= counterparts) will do: 4737 // x < k ? k : x 4738 // x > k ? x : k 4739 // k < x ? x : k 4740 // k > x ? k : x 4741 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4742 const SDValue TrueVal, const SDValue FalseVal, 4743 const ISD::CondCode CC, const SDValue K) { 4744 return (isGTorGE(CC) && 4745 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4746 (isLTorLE(CC) && 4747 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4748 } 4749 4750 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4751 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4752 const SDValue TrueVal, const SDValue FalseVal, 4753 const ISD::CondCode CC, const SDValue K) { 4754 return (isGTorGE(CC) && 4755 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4756 (isLTorLE(CC) && 4757 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4758 } 4759 4760 // Check if two chained conditionals could be converted into SSAT or USAT. 4761 // 4762 // SSAT can replace a set of two conditional selectors that bound a number to an 4763 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4764 // 4765 // x < -k ? -k : (x > k ? k : x) 4766 // x < -k ? -k : (x < k ? x : k) 4767 // x > -k ? (x > k ? k : x) : -k 4768 // x < k ? (x < -k ? -k : x) : k 4769 // etc. 4770 // 4771 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4772 // a power of 2. 4773 // 4774 // It returns true if the conversion can be done, false otherwise. 4775 // Additionally, the variable is returned in parameter V, the constant in K and 4776 // usat is set to true if the conditional represents an unsigned saturation 4777 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4778 uint64_t &K, bool &usat) { 4779 SDValue LHS1 = Op.getOperand(0); 4780 SDValue RHS1 = Op.getOperand(1); 4781 SDValue TrueVal1 = Op.getOperand(2); 4782 SDValue FalseVal1 = Op.getOperand(3); 4783 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4784 4785 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4786 if (Op2.getOpcode() != ISD::SELECT_CC) 4787 return false; 4788 4789 SDValue LHS2 = Op2.getOperand(0); 4790 SDValue RHS2 = Op2.getOperand(1); 4791 SDValue TrueVal2 = Op2.getOperand(2); 4792 SDValue FalseVal2 = Op2.getOperand(3); 4793 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4794 4795 // Find out which are the constants and which are the variables 4796 // in each conditional 4797 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4798 ? &RHS1 4799 : nullptr; 4800 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4801 ? &RHS2 4802 : nullptr; 4803 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4804 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4805 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4806 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4807 4808 // We must detect cases where the original operations worked with 16- or 4809 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4810 // must work with sign-extended values but the select operations return 4811 // the original non-extended value. 4812 SDValue V2TmpReg = V2Tmp; 4813 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4814 V2TmpReg = V2Tmp->getOperand(0); 4815 4816 // Check that the registers and the constants have the correct values 4817 // in both conditionals 4818 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4819 V2TmpReg != V2) 4820 return false; 4821 4822 // Figure out which conditional is saturating the lower/upper bound. 4823 const SDValue *LowerCheckOp = 4824 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4825 ? &Op 4826 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4827 ? &Op2 4828 : nullptr; 4829 const SDValue *UpperCheckOp = 4830 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4831 ? &Op 4832 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4833 ? &Op2 4834 : nullptr; 4835 4836 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4837 return false; 4838 4839 // Check that the constant in the lower-bound check is 4840 // the opposite of the constant in the upper-bound check 4841 // in 1's complement. 4842 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4843 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4844 int64_t PosVal = std::max(Val1, Val2); 4845 int64_t NegVal = std::min(Val1, Val2); 4846 4847 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4848 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4849 isPowerOf2_64(PosVal + 1)) { 4850 4851 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4852 if (Val1 == ~Val2) 4853 usat = false; 4854 else if (NegVal == 0) 4855 usat = true; 4856 else 4857 return false; 4858 4859 V = V2; 4860 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4861 4862 return true; 4863 } 4864 4865 return false; 4866 } 4867 4868 // Check if a condition of the type x < k ? k : x can be converted into a 4869 // bit operation instead of conditional moves. 4870 // Currently this is allowed given: 4871 // - The conditions and values match up 4872 // - k is 0 or -1 (all ones) 4873 // This function will not check the last condition, thats up to the caller 4874 // It returns true if the transformation can be made, and in such case 4875 // returns x in V, and k in SatK. 4876 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4877 SDValue &SatK) 4878 { 4879 SDValue LHS = Op.getOperand(0); 4880 SDValue RHS = Op.getOperand(1); 4881 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4882 SDValue TrueVal = Op.getOperand(2); 4883 SDValue FalseVal = Op.getOperand(3); 4884 4885 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4886 ? &RHS 4887 : nullptr; 4888 4889 // No constant operation in comparison, early out 4890 if (!K) 4891 return false; 4892 4893 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4894 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4895 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4896 4897 // If the constant on left and right side, or variable on left and right, 4898 // does not match, early out 4899 if (*K != KTmp || V != VTmp) 4900 return false; 4901 4902 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4903 SatK = *K; 4904 return true; 4905 } 4906 4907 return false; 4908 } 4909 4910 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 4911 if (VT == MVT::f32) 4912 return !Subtarget->hasVFP2Base(); 4913 if (VT == MVT::f64) 4914 return !Subtarget->hasFP64(); 4915 if (VT == MVT::f16) 4916 return !Subtarget->hasFullFP16(); 4917 return false; 4918 } 4919 4920 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4921 EVT VT = Op.getValueType(); 4922 SDLoc dl(Op); 4923 4924 // Try to convert two saturating conditional selects into a single SSAT 4925 SDValue SatValue; 4926 uint64_t SatConstant; 4927 bool SatUSat; 4928 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4929 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4930 if (SatUSat) 4931 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4932 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4933 else 4934 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4935 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4936 } 4937 4938 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4939 // into more efficient bit operations, which is possible when k is 0 or -1 4940 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4941 // single instructions. On Thumb the shift and the bit operation will be two 4942 // instructions. 4943 // Only allow this transformation on full-width (32-bit) operations 4944 SDValue LowerSatConstant; 4945 if (VT == MVT::i32 && 4946 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4947 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4948 DAG.getConstant(31, dl, VT)); 4949 if (isNullConstant(LowerSatConstant)) { 4950 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4951 DAG.getAllOnesConstant(dl, VT)); 4952 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4953 } else if (isAllOnesConstant(LowerSatConstant)) 4954 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4955 } 4956 4957 SDValue LHS = Op.getOperand(0); 4958 SDValue RHS = Op.getOperand(1); 4959 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4960 SDValue TrueVal = Op.getOperand(2); 4961 SDValue FalseVal = Op.getOperand(3); 4962 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal); 4963 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal); 4964 4965 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal && 4966 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) { 4967 unsigned TVal = CTVal->getZExtValue(); 4968 unsigned FVal = CFVal->getZExtValue(); 4969 unsigned Opcode = 0; 4970 4971 if (TVal == ~FVal) { 4972 Opcode = ARMISD::CSINV; 4973 } else if (TVal == ~FVal + 1) { 4974 Opcode = ARMISD::CSNEG; 4975 } else if (TVal + 1 == FVal) { 4976 Opcode = ARMISD::CSINC; 4977 } else if (TVal == FVal + 1) { 4978 Opcode = ARMISD::CSINC; 4979 std::swap(TrueVal, FalseVal); 4980 std::swap(TVal, FVal); 4981 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 4982 } 4983 4984 if (Opcode) { 4985 // If one of the constants is cheaper than another, materialise the 4986 // cheaper one and let the csel generate the other. 4987 if (Opcode != ARMISD::CSINC && 4988 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) { 4989 std::swap(TrueVal, FalseVal); 4990 std::swap(TVal, FVal); 4991 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 4992 } 4993 4994 // Attempt to use ZR checking TVal is 0, possibly inverting the condition 4995 // to get there. CSINC not is invertable like the other two (~(~a) == a, 4996 // -(-a) == a, but (a+1)+1 != a). 4997 if (FVal == 0 && Opcode != ARMISD::CSINC) { 4998 std::swap(TrueVal, FalseVal); 4999 std::swap(TVal, FVal); 5000 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5001 } 5002 if (TVal == 0) 5003 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32); 5004 5005 // Drops F's value because we can get it by inverting/negating TVal. 5006 FalseVal = TrueVal; 5007 5008 SDValue ARMcc; 5009 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5010 EVT VT = TrueVal.getValueType(); 5011 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp); 5012 } 5013 } 5014 5015 if (isUnsupportedFloatingType(LHS.getValueType())) { 5016 DAG.getTargetLoweringInfo().softenSetCCOperands( 5017 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5018 5019 // If softenSetCCOperands only returned one value, we should compare it to 5020 // zero. 5021 if (!RHS.getNode()) { 5022 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5023 CC = ISD::SETNE; 5024 } 5025 } 5026 5027 if (LHS.getValueType() == MVT::i32) { 5028 // Try to generate VSEL on ARMv8. 5029 // The VSEL instruction can't use all the usual ARM condition 5030 // codes: it only has two bits to select the condition code, so it's 5031 // constrained to use only GE, GT, VS and EQ. 5032 // 5033 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 5034 // swap the operands of the previous compare instruction (effectively 5035 // inverting the compare condition, swapping 'less' and 'greater') and 5036 // sometimes need to swap the operands to the VSEL (which inverts the 5037 // condition in the sense of firing whenever the previous condition didn't) 5038 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 5039 TrueVal.getValueType() == MVT::f32 || 5040 TrueVal.getValueType() == MVT::f64)) { 5041 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5042 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 5043 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 5044 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5045 std::swap(TrueVal, FalseVal); 5046 } 5047 } 5048 5049 SDValue ARMcc; 5050 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5051 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5052 // Choose GE over PL, which vsel does now support 5053 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 5054 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 5055 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5056 } 5057 5058 ARMCC::CondCodes CondCode, CondCode2; 5059 FPCCToARMCC(CC, CondCode, CondCode2); 5060 5061 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 5062 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 5063 // must use VSEL (limited condition codes), due to not having conditional f16 5064 // moves. 5065 if (Subtarget->hasFPARMv8Base() && 5066 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 5067 (TrueVal.getValueType() == MVT::f16 || 5068 TrueVal.getValueType() == MVT::f32 || 5069 TrueVal.getValueType() == MVT::f64)) { 5070 bool swpCmpOps = false; 5071 bool swpVselOps = false; 5072 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 5073 5074 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 5075 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 5076 if (swpCmpOps) 5077 std::swap(LHS, RHS); 5078 if (swpVselOps) 5079 std::swap(TrueVal, FalseVal); 5080 } 5081 } 5082 5083 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5084 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5085 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5086 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5087 if (CondCode2 != ARMCC::AL) { 5088 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 5089 // FIXME: Needs another CMP because flag can have but one use. 5090 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 5091 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 5092 } 5093 return Result; 5094 } 5095 5096 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 5097 /// to morph to an integer compare sequence. 5098 static bool canChangeToInt(SDValue Op, bool &SeenZero, 5099 const ARMSubtarget *Subtarget) { 5100 SDNode *N = Op.getNode(); 5101 if (!N->hasOneUse()) 5102 // Otherwise it requires moving the value from fp to integer registers. 5103 return false; 5104 if (!N->getNumValues()) 5105 return false; 5106 EVT VT = Op.getValueType(); 5107 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 5108 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 5109 // vmrs are very slow, e.g. cortex-a8. 5110 return false; 5111 5112 if (isFloatingPointZero(Op)) { 5113 SeenZero = true; 5114 return true; 5115 } 5116 return ISD::isNormalLoad(N); 5117 } 5118 5119 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 5120 if (isFloatingPointZero(Op)) 5121 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 5122 5123 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 5124 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 5125 Ld->getPointerInfo(), Ld->getAlignment(), 5126 Ld->getMemOperand()->getFlags()); 5127 5128 llvm_unreachable("Unknown VFP cmp argument!"); 5129 } 5130 5131 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 5132 SDValue &RetVal1, SDValue &RetVal2) { 5133 SDLoc dl(Op); 5134 5135 if (isFloatingPointZero(Op)) { 5136 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 5137 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 5138 return; 5139 } 5140 5141 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 5142 SDValue Ptr = Ld->getBasePtr(); 5143 RetVal1 = 5144 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 5145 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 5146 5147 EVT PtrType = Ptr.getValueType(); 5148 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 5149 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 5150 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 5151 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 5152 Ld->getPointerInfo().getWithOffset(4), NewAlign, 5153 Ld->getMemOperand()->getFlags()); 5154 return; 5155 } 5156 5157 llvm_unreachable("Unknown VFP cmp argument!"); 5158 } 5159 5160 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 5161 /// f32 and even f64 comparisons to integer ones. 5162 SDValue 5163 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 5164 SDValue Chain = Op.getOperand(0); 5165 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5166 SDValue LHS = Op.getOperand(2); 5167 SDValue RHS = Op.getOperand(3); 5168 SDValue Dest = Op.getOperand(4); 5169 SDLoc dl(Op); 5170 5171 bool LHSSeenZero = false; 5172 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 5173 bool RHSSeenZero = false; 5174 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 5175 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 5176 // If unsafe fp math optimization is enabled and there are no other uses of 5177 // the CMP operands, and the condition code is EQ or NE, we can optimize it 5178 // to an integer comparison. 5179 if (CC == ISD::SETOEQ) 5180 CC = ISD::SETEQ; 5181 else if (CC == ISD::SETUNE) 5182 CC = ISD::SETNE; 5183 5184 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5185 SDValue ARMcc; 5186 if (LHS.getValueType() == MVT::f32) { 5187 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5188 bitcastf32Toi32(LHS, DAG), Mask); 5189 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5190 bitcastf32Toi32(RHS, DAG), Mask); 5191 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5192 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5193 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5194 Chain, Dest, ARMcc, CCR, Cmp); 5195 } 5196 5197 SDValue LHS1, LHS2; 5198 SDValue RHS1, RHS2; 5199 expandf64Toi32(LHS, DAG, LHS1, LHS2); 5200 expandf64Toi32(RHS, DAG, RHS1, RHS2); 5201 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 5202 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 5203 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5204 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5205 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5206 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 5207 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 5208 } 5209 5210 return SDValue(); 5211 } 5212 5213 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 5214 SDValue Chain = Op.getOperand(0); 5215 SDValue Cond = Op.getOperand(1); 5216 SDValue Dest = Op.getOperand(2); 5217 SDLoc dl(Op); 5218 5219 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5220 // instruction. 5221 unsigned Opc = Cond.getOpcode(); 5222 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5223 !Subtarget->isThumb1Only(); 5224 if (Cond.getResNo() == 1 && 5225 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5226 Opc == ISD::USUBO || OptimizeMul)) { 5227 // Only lower legal XALUO ops. 5228 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 5229 return SDValue(); 5230 5231 // The actual operation with overflow check. 5232 SDValue Value, OverflowCmp; 5233 SDValue ARMcc; 5234 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 5235 5236 // Reverse the condition code. 5237 ARMCC::CondCodes CondCode = 5238 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5239 CondCode = ARMCC::getOppositeCondition(CondCode); 5240 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5241 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5242 5243 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5244 OverflowCmp); 5245 } 5246 5247 return SDValue(); 5248 } 5249 5250 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5251 SDValue Chain = Op.getOperand(0); 5252 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5253 SDValue LHS = Op.getOperand(2); 5254 SDValue RHS = Op.getOperand(3); 5255 SDValue Dest = Op.getOperand(4); 5256 SDLoc dl(Op); 5257 5258 if (isUnsupportedFloatingType(LHS.getValueType())) { 5259 DAG.getTargetLoweringInfo().softenSetCCOperands( 5260 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5261 5262 // If softenSetCCOperands only returned one value, we should compare it to 5263 // zero. 5264 if (!RHS.getNode()) { 5265 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5266 CC = ISD::SETNE; 5267 } 5268 } 5269 5270 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5271 // instruction. 5272 unsigned Opc = LHS.getOpcode(); 5273 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5274 !Subtarget->isThumb1Only(); 5275 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5276 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5277 Opc == ISD::USUBO || OptimizeMul) && 5278 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5279 // Only lower legal XALUO ops. 5280 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5281 return SDValue(); 5282 5283 // The actual operation with overflow check. 5284 SDValue Value, OverflowCmp; 5285 SDValue ARMcc; 5286 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5287 5288 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5289 // Reverse the condition code. 5290 ARMCC::CondCodes CondCode = 5291 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5292 CondCode = ARMCC::getOppositeCondition(CondCode); 5293 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5294 } 5295 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5296 5297 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5298 OverflowCmp); 5299 } 5300 5301 if (LHS.getValueType() == MVT::i32) { 5302 SDValue ARMcc; 5303 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5304 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5305 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5306 Chain, Dest, ARMcc, CCR, Cmp); 5307 } 5308 5309 if (getTargetMachine().Options.UnsafeFPMath && 5310 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5311 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5312 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5313 return Result; 5314 } 5315 5316 ARMCC::CondCodes CondCode, CondCode2; 5317 FPCCToARMCC(CC, CondCode, CondCode2); 5318 5319 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5320 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5321 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5322 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5323 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5324 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5325 if (CondCode2 != ARMCC::AL) { 5326 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5327 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5328 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5329 } 5330 return Res; 5331 } 5332 5333 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5334 SDValue Chain = Op.getOperand(0); 5335 SDValue Table = Op.getOperand(1); 5336 SDValue Index = Op.getOperand(2); 5337 SDLoc dl(Op); 5338 5339 EVT PTy = getPointerTy(DAG.getDataLayout()); 5340 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5341 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5342 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5343 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5344 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5345 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5346 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5347 // which does another jump to the destination. This also makes it easier 5348 // to translate it to TBB / TBH later (Thumb2 only). 5349 // FIXME: This might not work if the function is extremely large. 5350 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5351 Addr, Op.getOperand(2), JTI); 5352 } 5353 if (isPositionIndependent() || Subtarget->isROPI()) { 5354 Addr = 5355 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5356 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5357 Chain = Addr.getValue(1); 5358 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5359 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5360 } else { 5361 Addr = 5362 DAG.getLoad(PTy, dl, Chain, Addr, 5363 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5364 Chain = Addr.getValue(1); 5365 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5366 } 5367 } 5368 5369 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5370 EVT VT = Op.getValueType(); 5371 SDLoc dl(Op); 5372 5373 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5374 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5375 return Op; 5376 return DAG.UnrollVectorOp(Op.getNode()); 5377 } 5378 5379 const bool HasFullFP16 = 5380 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5381 5382 EVT NewTy; 5383 const EVT OpTy = Op.getOperand(0).getValueType(); 5384 if (OpTy == MVT::v4f32) 5385 NewTy = MVT::v4i32; 5386 else if (OpTy == MVT::v4f16 && HasFullFP16) 5387 NewTy = MVT::v4i16; 5388 else if (OpTy == MVT::v8f16 && HasFullFP16) 5389 NewTy = MVT::v8i16; 5390 else 5391 llvm_unreachable("Invalid type for custom lowering!"); 5392 5393 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5394 return DAG.UnrollVectorOp(Op.getNode()); 5395 5396 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5397 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5398 } 5399 5400 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5401 EVT VT = Op.getValueType(); 5402 if (VT.isVector()) 5403 return LowerVectorFP_TO_INT(Op, DAG); 5404 5405 bool IsStrict = Op->isStrictFPOpcode(); 5406 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 5407 5408 if (isUnsupportedFloatingType(SrcVal.getValueType())) { 5409 RTLIB::Libcall LC; 5410 if (Op.getOpcode() == ISD::FP_TO_SINT || 5411 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 5412 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), 5413 Op.getValueType()); 5414 else 5415 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), 5416 Op.getValueType()); 5417 SDLoc Loc(Op); 5418 MakeLibCallOptions CallOptions; 5419 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 5420 SDValue Result; 5421 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 5422 CallOptions, Loc, Chain); 5423 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 5424 } 5425 5426 // FIXME: Remove this when we have strict fp instruction selection patterns 5427 if (IsStrict) { 5428 SDLoc Loc(Op); 5429 SDValue Result = 5430 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT 5431 : ISD::FP_TO_UINT, 5432 Loc, Op.getValueType(), SrcVal); 5433 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 5434 } 5435 5436 return Op; 5437 } 5438 5439 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5440 EVT VT = Op.getValueType(); 5441 SDLoc dl(Op); 5442 5443 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5444 if (VT.getVectorElementType() == MVT::f32) 5445 return Op; 5446 return DAG.UnrollVectorOp(Op.getNode()); 5447 } 5448 5449 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5450 Op.getOperand(0).getValueType() == MVT::v8i16) && 5451 "Invalid type for custom lowering!"); 5452 5453 const bool HasFullFP16 = 5454 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5455 5456 EVT DestVecType; 5457 if (VT == MVT::v4f32) 5458 DestVecType = MVT::v4i32; 5459 else if (VT == MVT::v4f16 && HasFullFP16) 5460 DestVecType = MVT::v4i16; 5461 else if (VT == MVT::v8f16 && HasFullFP16) 5462 DestVecType = MVT::v8i16; 5463 else 5464 return DAG.UnrollVectorOp(Op.getNode()); 5465 5466 unsigned CastOpc; 5467 unsigned Opc; 5468 switch (Op.getOpcode()) { 5469 default: llvm_unreachable("Invalid opcode!"); 5470 case ISD::SINT_TO_FP: 5471 CastOpc = ISD::SIGN_EXTEND; 5472 Opc = ISD::SINT_TO_FP; 5473 break; 5474 case ISD::UINT_TO_FP: 5475 CastOpc = ISD::ZERO_EXTEND; 5476 Opc = ISD::UINT_TO_FP; 5477 break; 5478 } 5479 5480 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5481 return DAG.getNode(Opc, dl, VT, Op); 5482 } 5483 5484 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5485 EVT VT = Op.getValueType(); 5486 if (VT.isVector()) 5487 return LowerVectorINT_TO_FP(Op, DAG); 5488 if (isUnsupportedFloatingType(VT)) { 5489 RTLIB::Libcall LC; 5490 if (Op.getOpcode() == ISD::SINT_TO_FP) 5491 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5492 Op.getValueType()); 5493 else 5494 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5495 Op.getValueType()); 5496 MakeLibCallOptions CallOptions; 5497 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5498 CallOptions, SDLoc(Op)).first; 5499 } 5500 5501 return Op; 5502 } 5503 5504 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5505 // Implement fcopysign with a fabs and a conditional fneg. 5506 SDValue Tmp0 = Op.getOperand(0); 5507 SDValue Tmp1 = Op.getOperand(1); 5508 SDLoc dl(Op); 5509 EVT VT = Op.getValueType(); 5510 EVT SrcVT = Tmp1.getValueType(); 5511 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5512 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5513 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5514 5515 if (UseNEON) { 5516 // Use VBSL to copy the sign bit. 5517 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5518 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5519 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5520 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5521 if (VT == MVT::f64) 5522 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5523 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5524 DAG.getConstant(32, dl, MVT::i32)); 5525 else /*if (VT == MVT::f32)*/ 5526 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5527 if (SrcVT == MVT::f32) { 5528 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5529 if (VT == MVT::f64) 5530 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5531 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5532 DAG.getConstant(32, dl, MVT::i32)); 5533 } else if (VT == MVT::f32) 5534 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5535 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5536 DAG.getConstant(32, dl, MVT::i32)); 5537 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5538 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5539 5540 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5541 dl, MVT::i32); 5542 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5543 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5544 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5545 5546 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5547 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5548 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5549 if (VT == MVT::f32) { 5550 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5551 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5552 DAG.getConstant(0, dl, MVT::i32)); 5553 } else { 5554 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5555 } 5556 5557 return Res; 5558 } 5559 5560 // Bitcast operand 1 to i32. 5561 if (SrcVT == MVT::f64) 5562 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5563 Tmp1).getValue(1); 5564 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5565 5566 // Or in the signbit with integer operations. 5567 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5568 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5569 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5570 if (VT == MVT::f32) { 5571 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5572 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5573 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5574 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5575 } 5576 5577 // f64: Or the high part with signbit and then combine two parts. 5578 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5579 Tmp0); 5580 SDValue Lo = Tmp0.getValue(0); 5581 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5582 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5583 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5584 } 5585 5586 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5587 MachineFunction &MF = DAG.getMachineFunction(); 5588 MachineFrameInfo &MFI = MF.getFrameInfo(); 5589 MFI.setReturnAddressIsTaken(true); 5590 5591 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5592 return SDValue(); 5593 5594 EVT VT = Op.getValueType(); 5595 SDLoc dl(Op); 5596 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5597 if (Depth) { 5598 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5599 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5600 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5601 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5602 MachinePointerInfo()); 5603 } 5604 5605 // Return LR, which contains the return address. Mark it an implicit live-in. 5606 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5607 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5608 } 5609 5610 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5611 const ARMBaseRegisterInfo &ARI = 5612 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5613 MachineFunction &MF = DAG.getMachineFunction(); 5614 MachineFrameInfo &MFI = MF.getFrameInfo(); 5615 MFI.setFrameAddressIsTaken(true); 5616 5617 EVT VT = Op.getValueType(); 5618 SDLoc dl(Op); // FIXME probably not meaningful 5619 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5620 Register FrameReg = ARI.getFrameRegister(MF); 5621 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5622 while (Depth--) 5623 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5624 MachinePointerInfo()); 5625 return FrameAddr; 5626 } 5627 5628 // FIXME? Maybe this could be a TableGen attribute on some registers and 5629 // this table could be generated automatically from RegInfo. 5630 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT, 5631 const MachineFunction &MF) const { 5632 Register Reg = StringSwitch<unsigned>(RegName) 5633 .Case("sp", ARM::SP) 5634 .Default(0); 5635 if (Reg) 5636 return Reg; 5637 report_fatal_error(Twine("Invalid register name \"" 5638 + StringRef(RegName) + "\".")); 5639 } 5640 5641 // Result is 64 bit value so split into two 32 bit values and return as a 5642 // pair of values. 5643 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5644 SelectionDAG &DAG) { 5645 SDLoc DL(N); 5646 5647 // This function is only supposed to be called for i64 type destination. 5648 assert(N->getValueType(0) == MVT::i64 5649 && "ExpandREAD_REGISTER called for non-i64 type result."); 5650 5651 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5652 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5653 N->getOperand(0), 5654 N->getOperand(1)); 5655 5656 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5657 Read.getValue(1))); 5658 Results.push_back(Read.getOperand(0)); 5659 } 5660 5661 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5662 /// When \p DstVT, the destination type of \p BC, is on the vector 5663 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5664 /// it might be possible to combine them, such that everything stays on the 5665 /// vector register bank. 5666 /// \p return The node that would replace \p BT, if the combine 5667 /// is possible. 5668 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5669 SelectionDAG &DAG) { 5670 SDValue Op = BC->getOperand(0); 5671 EVT DstVT = BC->getValueType(0); 5672 5673 // The only vector instruction that can produce a scalar (remember, 5674 // since the bitcast was about to be turned into VMOVDRR, the source 5675 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5676 // Moreover, we can do this combine only if there is one use. 5677 // Finally, if the destination type is not a vector, there is not 5678 // much point on forcing everything on the vector bank. 5679 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5680 !Op.hasOneUse()) 5681 return SDValue(); 5682 5683 // If the index is not constant, we will introduce an additional 5684 // multiply that will stick. 5685 // Give up in that case. 5686 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5687 if (!Index) 5688 return SDValue(); 5689 unsigned DstNumElt = DstVT.getVectorNumElements(); 5690 5691 // Compute the new index. 5692 const APInt &APIntIndex = Index->getAPIntValue(); 5693 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5694 NewIndex *= APIntIndex; 5695 // Check if the new constant index fits into i32. 5696 if (NewIndex.getBitWidth() > 32) 5697 return SDValue(); 5698 5699 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5700 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5701 SDLoc dl(Op); 5702 SDValue ExtractSrc = Op.getOperand(0); 5703 EVT VecVT = EVT::getVectorVT( 5704 *DAG.getContext(), DstVT.getScalarType(), 5705 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5706 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5707 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5708 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5709 } 5710 5711 /// ExpandBITCAST - If the target supports VFP, this function is called to 5712 /// expand a bit convert where either the source or destination type is i64 to 5713 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5714 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5715 /// vectors), since the legalizer won't know what to do with that. 5716 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5717 const ARMSubtarget *Subtarget) { 5718 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5719 SDLoc dl(N); 5720 SDValue Op = N->getOperand(0); 5721 5722 // This function is only supposed to be called for i64 types, either as the 5723 // source or destination of the bit convert. 5724 EVT SrcVT = Op.getValueType(); 5725 EVT DstVT = N->getValueType(0); 5726 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5727 5728 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5729 // FullFP16: half values are passed in S-registers, and we don't 5730 // need any of the bitcast and moves: 5731 // 5732 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5733 // t5: i32 = bitcast t2 5734 // t18: f16 = ARMISD::VMOVhr t5 5735 if (Op.getOpcode() != ISD::CopyFromReg || 5736 Op.getValueType() != MVT::f32) 5737 return SDValue(); 5738 5739 auto Move = N->use_begin(); 5740 if (Move->getOpcode() != ARMISD::VMOVhr) 5741 return SDValue(); 5742 5743 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5744 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5745 DAG.ReplaceAllUsesWith(*Move, &Copy); 5746 return Copy; 5747 } 5748 5749 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5750 if (!HasFullFP16) 5751 return SDValue(); 5752 // SoftFP: read half-precision arguments: 5753 // 5754 // t2: i32,ch = ... 5755 // t7: i16 = truncate t2 <~~~~ Op 5756 // t8: f16 = bitcast t7 <~~~~ N 5757 // 5758 if (Op.getOperand(0).getValueType() == MVT::i32) 5759 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5760 MVT::f16, Op.getOperand(0)); 5761 5762 return SDValue(); 5763 } 5764 5765 // Half-precision return values 5766 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5767 if (!HasFullFP16) 5768 return SDValue(); 5769 // 5770 // t11: f16 = fadd t8, t10 5771 // t12: i16 = bitcast t11 <~~~ SDNode N 5772 // t13: i32 = zero_extend t12 5773 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5774 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5775 // 5776 // transform this into: 5777 // 5778 // t20: i32 = ARMISD::VMOVrh t11 5779 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5780 // 5781 auto ZeroExtend = N->use_begin(); 5782 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5783 ZeroExtend->getValueType(0) != MVT::i32) 5784 return SDValue(); 5785 5786 auto Copy = ZeroExtend->use_begin(); 5787 if (Copy->getOpcode() == ISD::CopyToReg && 5788 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5789 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5790 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5791 return Cvt; 5792 } 5793 return SDValue(); 5794 } 5795 5796 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5797 return SDValue(); 5798 5799 // Turn i64->f64 into VMOVDRR. 5800 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5801 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5802 // if we can combine the bitcast with its source. 5803 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5804 return Val; 5805 5806 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5807 DAG.getConstant(0, dl, MVT::i32)); 5808 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5809 DAG.getConstant(1, dl, MVT::i32)); 5810 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5811 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5812 } 5813 5814 // Turn f64->i64 into VMOVRRD. 5815 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5816 SDValue Cvt; 5817 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5818 SrcVT.getVectorNumElements() > 1) 5819 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5820 DAG.getVTList(MVT::i32, MVT::i32), 5821 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5822 else 5823 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5824 DAG.getVTList(MVT::i32, MVT::i32), Op); 5825 // Merge the pieces into a single i64 value. 5826 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5827 } 5828 5829 return SDValue(); 5830 } 5831 5832 /// getZeroVector - Returns a vector of specified type with all zero elements. 5833 /// Zero vectors are used to represent vector negation and in those cases 5834 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5835 /// not support i64 elements, so sometimes the zero vectors will need to be 5836 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5837 /// zero vector. 5838 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5839 assert(VT.isVector() && "Expected a vector type"); 5840 // The canonical modified immediate encoding of a zero vector is....0! 5841 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5842 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5843 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5844 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5845 } 5846 5847 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5848 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5849 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5850 SelectionDAG &DAG) const { 5851 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5852 EVT VT = Op.getValueType(); 5853 unsigned VTBits = VT.getSizeInBits(); 5854 SDLoc dl(Op); 5855 SDValue ShOpLo = Op.getOperand(0); 5856 SDValue ShOpHi = Op.getOperand(1); 5857 SDValue ShAmt = Op.getOperand(2); 5858 SDValue ARMcc; 5859 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5860 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5861 5862 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5863 5864 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5865 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5866 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5867 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5868 DAG.getConstant(VTBits, dl, MVT::i32)); 5869 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5870 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5871 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5872 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5873 ISD::SETGE, ARMcc, DAG, dl); 5874 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5875 ARMcc, CCR, CmpLo); 5876 5877 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5878 SDValue HiBigShift = Opc == ISD::SRA 5879 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5880 DAG.getConstant(VTBits - 1, dl, VT)) 5881 : DAG.getConstant(0, dl, VT); 5882 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5883 ISD::SETGE, ARMcc, DAG, dl); 5884 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5885 ARMcc, CCR, CmpHi); 5886 5887 SDValue Ops[2] = { Lo, Hi }; 5888 return DAG.getMergeValues(Ops, dl); 5889 } 5890 5891 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5892 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5893 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5894 SelectionDAG &DAG) const { 5895 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5896 EVT VT = Op.getValueType(); 5897 unsigned VTBits = VT.getSizeInBits(); 5898 SDLoc dl(Op); 5899 SDValue ShOpLo = Op.getOperand(0); 5900 SDValue ShOpHi = Op.getOperand(1); 5901 SDValue ShAmt = Op.getOperand(2); 5902 SDValue ARMcc; 5903 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5904 5905 assert(Op.getOpcode() == ISD::SHL_PARTS); 5906 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5907 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5908 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5909 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5910 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5911 5912 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5913 DAG.getConstant(VTBits, dl, MVT::i32)); 5914 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5915 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5916 ISD::SETGE, ARMcc, DAG, dl); 5917 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5918 ARMcc, CCR, CmpHi); 5919 5920 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5921 ISD::SETGE, ARMcc, DAG, dl); 5922 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5923 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5924 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5925 5926 SDValue Ops[2] = { Lo, Hi }; 5927 return DAG.getMergeValues(Ops, dl); 5928 } 5929 5930 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5931 SelectionDAG &DAG) const { 5932 // The rounding mode is in bits 23:22 of the FPSCR. 5933 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5934 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5935 // so that the shift + and get folded into a bitfield extract. 5936 SDLoc dl(Op); 5937 SDValue Ops[] = { DAG.getEntryNode(), 5938 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5939 5940 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5941 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5942 DAG.getConstant(1U << 22, dl, MVT::i32)); 5943 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5944 DAG.getConstant(22, dl, MVT::i32)); 5945 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5946 DAG.getConstant(3, dl, MVT::i32)); 5947 } 5948 5949 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5950 const ARMSubtarget *ST) { 5951 SDLoc dl(N); 5952 EVT VT = N->getValueType(0); 5953 if (VT.isVector() && ST->hasNEON()) { 5954 5955 // Compute the least significant set bit: LSB = X & -X 5956 SDValue X = N->getOperand(0); 5957 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5958 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5959 5960 EVT ElemTy = VT.getVectorElementType(); 5961 5962 if (ElemTy == MVT::i8) { 5963 // Compute with: cttz(x) = ctpop(lsb - 1) 5964 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5965 DAG.getTargetConstant(1, dl, ElemTy)); 5966 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5967 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5968 } 5969 5970 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5971 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5972 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5973 unsigned NumBits = ElemTy.getSizeInBits(); 5974 SDValue WidthMinus1 = 5975 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5976 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5977 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5978 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5979 } 5980 5981 // Compute with: cttz(x) = ctpop(lsb - 1) 5982 5983 // Compute LSB - 1. 5984 SDValue Bits; 5985 if (ElemTy == MVT::i64) { 5986 // Load constant 0xffff'ffff'ffff'ffff to register. 5987 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5988 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5989 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5990 } else { 5991 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5992 DAG.getTargetConstant(1, dl, ElemTy)); 5993 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5994 } 5995 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5996 } 5997 5998 if (!ST->hasV6T2Ops()) 5999 return SDValue(); 6000 6001 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 6002 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 6003 } 6004 6005 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 6006 const ARMSubtarget *ST) { 6007 EVT VT = N->getValueType(0); 6008 SDLoc DL(N); 6009 6010 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 6011 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6012 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6013 "Unexpected type for custom ctpop lowering"); 6014 6015 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6016 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6017 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 6018 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 6019 6020 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6021 unsigned EltSize = 8; 6022 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6023 while (EltSize != VT.getScalarSizeInBits()) { 6024 SmallVector<SDValue, 8> Ops; 6025 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 6026 TLI.getPointerTy(DAG.getDataLayout()))); 6027 Ops.push_back(Res); 6028 6029 EltSize *= 2; 6030 NumElts /= 2; 6031 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6032 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 6033 } 6034 6035 return Res; 6036 } 6037 6038 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 6039 /// operand of a vector shift operation, where all the elements of the 6040 /// build_vector must have the same constant integer value. 6041 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6042 // Ignore bit_converts. 6043 while (Op.getOpcode() == ISD::BITCAST) 6044 Op = Op.getOperand(0); 6045 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6046 APInt SplatBits, SplatUndef; 6047 unsigned SplatBitSize; 6048 bool HasAnyUndefs; 6049 if (!BVN || 6050 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 6051 ElementBits) || 6052 SplatBitSize > ElementBits) 6053 return false; 6054 Cnt = SplatBits.getSExtValue(); 6055 return true; 6056 } 6057 6058 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6059 /// operand of a vector shift left operation. That value must be in the range: 6060 /// 0 <= Value < ElementBits for a left shift; or 6061 /// 0 <= Value <= ElementBits for a long left shift. 6062 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6063 assert(VT.isVector() && "vector shift count is not a vector type"); 6064 int64_t ElementBits = VT.getScalarSizeInBits(); 6065 if (!getVShiftImm(Op, ElementBits, Cnt)) 6066 return false; 6067 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6068 } 6069 6070 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6071 /// operand of a vector shift right operation. For a shift opcode, the value 6072 /// is positive, but for an intrinsic the value count must be negative. The 6073 /// absolute value must be in the range: 6074 /// 1 <= |Value| <= ElementBits for a right shift; or 6075 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 6076 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 6077 int64_t &Cnt) { 6078 assert(VT.isVector() && "vector shift count is not a vector type"); 6079 int64_t ElementBits = VT.getScalarSizeInBits(); 6080 if (!getVShiftImm(Op, ElementBits, Cnt)) 6081 return false; 6082 if (!isIntrinsic) 6083 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6084 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 6085 Cnt = -Cnt; 6086 return true; 6087 } 6088 return false; 6089 } 6090 6091 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 6092 const ARMSubtarget *ST) { 6093 EVT VT = N->getValueType(0); 6094 SDLoc dl(N); 6095 int64_t Cnt; 6096 6097 if (!VT.isVector()) 6098 return SDValue(); 6099 6100 // We essentially have two forms here. Shift by an immediate and shift by a 6101 // vector register (there are also shift by a gpr, but that is just handled 6102 // with a tablegen pattern). We cannot easily match shift by an immediate in 6103 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 6104 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 6105 // signed or unsigned, and a negative shift indicates a shift right). 6106 if (N->getOpcode() == ISD::SHL) { 6107 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 6108 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 6109 DAG.getConstant(Cnt, dl, MVT::i32)); 6110 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 6111 N->getOperand(1)); 6112 } 6113 6114 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 6115 "unexpected vector shift opcode"); 6116 6117 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 6118 unsigned VShiftOpc = 6119 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 6120 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 6121 DAG.getConstant(Cnt, dl, MVT::i32)); 6122 } 6123 6124 // Other right shifts we don't have operations for (we use a shift left by a 6125 // negative number). 6126 EVT ShiftVT = N->getOperand(1).getValueType(); 6127 SDValue NegatedCount = DAG.getNode( 6128 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 6129 unsigned VShiftOpc = 6130 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 6131 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 6132 } 6133 6134 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 6135 const ARMSubtarget *ST) { 6136 EVT VT = N->getValueType(0); 6137 SDLoc dl(N); 6138 6139 // We can get here for a node like i32 = ISD::SHL i32, i64 6140 if (VT != MVT::i64) 6141 return SDValue(); 6142 6143 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 6144 N->getOpcode() == ISD::SHL) && 6145 "Unknown shift to lower!"); 6146 6147 unsigned ShOpc = N->getOpcode(); 6148 if (ST->hasMVEIntegerOps()) { 6149 SDValue ShAmt = N->getOperand(1); 6150 unsigned ShPartsOpc = ARMISD::LSLL; 6151 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 6152 6153 // If the shift amount is greater than 32 or has a greater bitwidth than 64 6154 // then do the default optimisation 6155 if (ShAmt->getValueType(0).getSizeInBits() > 64 || 6156 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32))) 6157 return SDValue(); 6158 6159 // Extract the lower 32 bits of the shift amount if it's not an i32 6160 if (ShAmt->getValueType(0) != MVT::i32) 6161 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32); 6162 6163 if (ShOpc == ISD::SRL) { 6164 if (!Con) 6165 // There is no t2LSRLr instruction so negate and perform an lsll if the 6166 // shift amount is in a register, emulating a right shift. 6167 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6168 DAG.getConstant(0, dl, MVT::i32), ShAmt); 6169 else 6170 // Else generate an lsrl on the immediate shift amount 6171 ShPartsOpc = ARMISD::LSRL; 6172 } else if (ShOpc == ISD::SRA) 6173 ShPartsOpc = ARMISD::ASRL; 6174 6175 // Lower 32 bits of the destination/source 6176 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6177 DAG.getConstant(0, dl, MVT::i32)); 6178 // Upper 32 bits of the destination/source 6179 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6180 DAG.getConstant(1, dl, MVT::i32)); 6181 6182 // Generate the shift operation as computed above 6183 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 6184 ShAmt); 6185 // The upper 32 bits come from the second return value of lsll 6186 Hi = SDValue(Lo.getNode(), 1); 6187 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6188 } 6189 6190 // We only lower SRA, SRL of 1 here, all others use generic lowering. 6191 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 6192 return SDValue(); 6193 6194 // If we are in thumb mode, we don't have RRX. 6195 if (ST->isThumb1Only()) 6196 return SDValue(); 6197 6198 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 6199 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6200 DAG.getConstant(0, dl, MVT::i32)); 6201 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6202 DAG.getConstant(1, dl, MVT::i32)); 6203 6204 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 6205 // captures the result into a carry flag. 6206 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 6207 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 6208 6209 // The low part is an ARMISD::RRX operand, which shifts the carry in. 6210 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 6211 6212 // Merge the pieces into a single i64 value. 6213 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6214 } 6215 6216 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 6217 const ARMSubtarget *ST) { 6218 bool Invert = false; 6219 bool Swap = false; 6220 unsigned Opc = ARMCC::AL; 6221 6222 SDValue Op0 = Op.getOperand(0); 6223 SDValue Op1 = Op.getOperand(1); 6224 SDValue CC = Op.getOperand(2); 6225 EVT VT = Op.getValueType(); 6226 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 6227 SDLoc dl(Op); 6228 6229 EVT CmpVT; 6230 if (ST->hasNEON()) 6231 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 6232 else { 6233 assert(ST->hasMVEIntegerOps() && 6234 "No hardware support for integer vector comparison!"); 6235 6236 if (Op.getValueType().getVectorElementType() != MVT::i1) 6237 return SDValue(); 6238 6239 // Make sure we expand floating point setcc to scalar if we do not have 6240 // mve.fp, so that we can handle them from there. 6241 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 6242 return SDValue(); 6243 6244 CmpVT = VT; 6245 } 6246 6247 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 6248 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 6249 // Special-case integer 64-bit equality comparisons. They aren't legal, 6250 // but they can be lowered with a few vector instructions. 6251 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 6252 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 6253 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 6254 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 6255 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 6256 DAG.getCondCode(ISD::SETEQ)); 6257 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 6258 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 6259 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 6260 if (SetCCOpcode == ISD::SETNE) 6261 Merged = DAG.getNOT(dl, Merged, CmpVT); 6262 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6263 return Merged; 6264 } 6265 6266 if (CmpVT.getVectorElementType() == MVT::i64) 6267 // 64-bit comparisons are not legal in general. 6268 return SDValue(); 6269 6270 if (Op1.getValueType().isFloatingPoint()) { 6271 switch (SetCCOpcode) { 6272 default: llvm_unreachable("Illegal FP comparison"); 6273 case ISD::SETUNE: 6274 case ISD::SETNE: 6275 if (ST->hasMVEFloatOps()) { 6276 Opc = ARMCC::NE; break; 6277 } else { 6278 Invert = true; LLVM_FALLTHROUGH; 6279 } 6280 case ISD::SETOEQ: 6281 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6282 case ISD::SETOLT: 6283 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6284 case ISD::SETOGT: 6285 case ISD::SETGT: Opc = ARMCC::GT; break; 6286 case ISD::SETOLE: 6287 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6288 case ISD::SETOGE: 6289 case ISD::SETGE: Opc = ARMCC::GE; break; 6290 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6291 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6292 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6293 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6294 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6295 case ISD::SETONE: { 6296 // Expand this to (OLT | OGT). 6297 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6298 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6299 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6300 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6301 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6302 if (Invert) 6303 Result = DAG.getNOT(dl, Result, VT); 6304 return Result; 6305 } 6306 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6307 case ISD::SETO: { 6308 // Expand this to (OLT | OGE). 6309 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6310 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6311 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6312 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6313 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6314 if (Invert) 6315 Result = DAG.getNOT(dl, Result, VT); 6316 return Result; 6317 } 6318 } 6319 } else { 6320 // Integer comparisons. 6321 switch (SetCCOpcode) { 6322 default: llvm_unreachable("Illegal integer comparison"); 6323 case ISD::SETNE: 6324 if (ST->hasMVEIntegerOps()) { 6325 Opc = ARMCC::NE; break; 6326 } else { 6327 Invert = true; LLVM_FALLTHROUGH; 6328 } 6329 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6330 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6331 case ISD::SETGT: Opc = ARMCC::GT; break; 6332 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6333 case ISD::SETGE: Opc = ARMCC::GE; break; 6334 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6335 case ISD::SETUGT: Opc = ARMCC::HI; break; 6336 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6337 case ISD::SETUGE: Opc = ARMCC::HS; break; 6338 } 6339 6340 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6341 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6342 SDValue AndOp; 6343 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6344 AndOp = Op0; 6345 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6346 AndOp = Op1; 6347 6348 // Ignore bitconvert. 6349 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6350 AndOp = AndOp.getOperand(0); 6351 6352 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6353 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6354 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6355 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6356 if (!Invert) 6357 Result = DAG.getNOT(dl, Result, VT); 6358 return Result; 6359 } 6360 } 6361 } 6362 6363 if (Swap) 6364 std::swap(Op0, Op1); 6365 6366 // If one of the operands is a constant vector zero, attempt to fold the 6367 // comparison to a specialized compare-against-zero form. 6368 SDValue SingleOp; 6369 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6370 SingleOp = Op0; 6371 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6372 if (Opc == ARMCC::GE) 6373 Opc = ARMCC::LE; 6374 else if (Opc == ARMCC::GT) 6375 Opc = ARMCC::LT; 6376 SingleOp = Op1; 6377 } 6378 6379 SDValue Result; 6380 if (SingleOp.getNode()) { 6381 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6382 DAG.getConstant(Opc, dl, MVT::i32)); 6383 } else { 6384 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6385 DAG.getConstant(Opc, dl, MVT::i32)); 6386 } 6387 6388 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6389 6390 if (Invert) 6391 Result = DAG.getNOT(dl, Result, VT); 6392 6393 return Result; 6394 } 6395 6396 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6397 SDValue LHS = Op.getOperand(0); 6398 SDValue RHS = Op.getOperand(1); 6399 SDValue Carry = Op.getOperand(2); 6400 SDValue Cond = Op.getOperand(3); 6401 SDLoc DL(Op); 6402 6403 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6404 6405 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6406 // have to invert the carry first. 6407 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6408 DAG.getConstant(1, DL, MVT::i32), Carry); 6409 // This converts the boolean value carry into the carry flag. 6410 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6411 6412 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6413 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6414 6415 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6416 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6417 SDValue ARMcc = DAG.getConstant( 6418 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6419 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6420 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6421 Cmp.getValue(1), SDValue()); 6422 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6423 CCR, Chain.getValue(1)); 6424 } 6425 6426 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6427 /// valid vector constant for a NEON or MVE instruction with a "modified 6428 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6429 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6430 unsigned SplatBitSize, SelectionDAG &DAG, 6431 const SDLoc &dl, EVT &VT, bool is128Bits, 6432 VMOVModImmType type) { 6433 unsigned OpCmode, Imm; 6434 6435 // SplatBitSize is set to the smallest size that splats the vector, so a 6436 // zero vector will always have SplatBitSize == 8. However, NEON modified 6437 // immediate instructions others than VMOV do not support the 8-bit encoding 6438 // of a zero vector, and the default encoding of zero is supposed to be the 6439 // 32-bit version. 6440 if (SplatBits == 0) 6441 SplatBitSize = 32; 6442 6443 switch (SplatBitSize) { 6444 case 8: 6445 if (type != VMOVModImm) 6446 return SDValue(); 6447 // Any 1-byte value is OK. Op=0, Cmode=1110. 6448 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6449 OpCmode = 0xe; 6450 Imm = SplatBits; 6451 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6452 break; 6453 6454 case 16: 6455 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6456 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6457 if ((SplatBits & ~0xff) == 0) { 6458 // Value = 0x00nn: Op=x, Cmode=100x. 6459 OpCmode = 0x8; 6460 Imm = SplatBits; 6461 break; 6462 } 6463 if ((SplatBits & ~0xff00) == 0) { 6464 // Value = 0xnn00: Op=x, Cmode=101x. 6465 OpCmode = 0xa; 6466 Imm = SplatBits >> 8; 6467 break; 6468 } 6469 return SDValue(); 6470 6471 case 32: 6472 // NEON's 32-bit VMOV supports splat values where: 6473 // * only one byte is nonzero, or 6474 // * the least significant byte is 0xff and the second byte is nonzero, or 6475 // * the least significant 2 bytes are 0xff and the third is nonzero. 6476 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6477 if ((SplatBits & ~0xff) == 0) { 6478 // Value = 0x000000nn: Op=x, Cmode=000x. 6479 OpCmode = 0; 6480 Imm = SplatBits; 6481 break; 6482 } 6483 if ((SplatBits & ~0xff00) == 0) { 6484 // Value = 0x0000nn00: Op=x, Cmode=001x. 6485 OpCmode = 0x2; 6486 Imm = SplatBits >> 8; 6487 break; 6488 } 6489 if ((SplatBits & ~0xff0000) == 0) { 6490 // Value = 0x00nn0000: Op=x, Cmode=010x. 6491 OpCmode = 0x4; 6492 Imm = SplatBits >> 16; 6493 break; 6494 } 6495 if ((SplatBits & ~0xff000000) == 0) { 6496 // Value = 0xnn000000: Op=x, Cmode=011x. 6497 OpCmode = 0x6; 6498 Imm = SplatBits >> 24; 6499 break; 6500 } 6501 6502 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6503 if (type == OtherModImm) return SDValue(); 6504 6505 if ((SplatBits & ~0xffff) == 0 && 6506 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6507 // Value = 0x0000nnff: Op=x, Cmode=1100. 6508 OpCmode = 0xc; 6509 Imm = SplatBits >> 8; 6510 break; 6511 } 6512 6513 // cmode == 0b1101 is not supported for MVE VMVN 6514 if (type == MVEVMVNModImm) 6515 return SDValue(); 6516 6517 if ((SplatBits & ~0xffffff) == 0 && 6518 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6519 // Value = 0x00nnffff: Op=x, Cmode=1101. 6520 OpCmode = 0xd; 6521 Imm = SplatBits >> 16; 6522 break; 6523 } 6524 6525 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6526 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6527 // VMOV.I32. A (very) minor optimization would be to replicate the value 6528 // and fall through here to test for a valid 64-bit splat. But, then the 6529 // caller would also need to check and handle the change in size. 6530 return SDValue(); 6531 6532 case 64: { 6533 if (type != VMOVModImm) 6534 return SDValue(); 6535 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6536 uint64_t BitMask = 0xff; 6537 uint64_t Val = 0; 6538 unsigned ImmMask = 1; 6539 Imm = 0; 6540 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6541 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6542 Val |= BitMask; 6543 Imm |= ImmMask; 6544 } else if ((SplatBits & BitMask) != 0) { 6545 return SDValue(); 6546 } 6547 BitMask <<= 8; 6548 ImmMask <<= 1; 6549 } 6550 6551 if (DAG.getDataLayout().isBigEndian()) 6552 // swap higher and lower 32 bit word 6553 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 6554 6555 // Op=1, Cmode=1110. 6556 OpCmode = 0x1e; 6557 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6558 break; 6559 } 6560 6561 default: 6562 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6563 } 6564 6565 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6566 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6567 } 6568 6569 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6570 const ARMSubtarget *ST) const { 6571 EVT VT = Op.getValueType(); 6572 bool IsDouble = (VT == MVT::f64); 6573 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6574 const APFloat &FPVal = CFP->getValueAPF(); 6575 6576 // Prevent floating-point constants from using literal loads 6577 // when execute-only is enabled. 6578 if (ST->genExecuteOnly()) { 6579 // If we can represent the constant as an immediate, don't lower it 6580 if (isFPImmLegal(FPVal, VT)) 6581 return Op; 6582 // Otherwise, construct as integer, and move to float register 6583 APInt INTVal = FPVal.bitcastToAPInt(); 6584 SDLoc DL(CFP); 6585 switch (VT.getSimpleVT().SimpleTy) { 6586 default: 6587 llvm_unreachable("Unknown floating point type!"); 6588 break; 6589 case MVT::f64: { 6590 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6591 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6592 if (!ST->isLittle()) 6593 std::swap(Lo, Hi); 6594 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6595 } 6596 case MVT::f32: 6597 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6598 DAG.getConstant(INTVal, DL, MVT::i32)); 6599 } 6600 } 6601 6602 if (!ST->hasVFP3Base()) 6603 return SDValue(); 6604 6605 // Use the default (constant pool) lowering for double constants when we have 6606 // an SP-only FPU 6607 if (IsDouble && !Subtarget->hasFP64()) 6608 return SDValue(); 6609 6610 // Try splatting with a VMOV.f32... 6611 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6612 6613 if (ImmVal != -1) { 6614 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6615 // We have code in place to select a valid ConstantFP already, no need to 6616 // do any mangling. 6617 return Op; 6618 } 6619 6620 // It's a float and we are trying to use NEON operations where 6621 // possible. Lower it to a splat followed by an extract. 6622 SDLoc DL(Op); 6623 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6624 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6625 NewVal); 6626 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6627 DAG.getConstant(0, DL, MVT::i32)); 6628 } 6629 6630 // The rest of our options are NEON only, make sure that's allowed before 6631 // proceeding.. 6632 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6633 return SDValue(); 6634 6635 EVT VMovVT; 6636 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6637 6638 // It wouldn't really be worth bothering for doubles except for one very 6639 // important value, which does happen to match: 0.0. So make sure we don't do 6640 // anything stupid. 6641 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6642 return SDValue(); 6643 6644 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6645 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6646 VMovVT, false, VMOVModImm); 6647 if (NewVal != SDValue()) { 6648 SDLoc DL(Op); 6649 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6650 NewVal); 6651 if (IsDouble) 6652 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6653 6654 // It's a float: cast and extract a vector element. 6655 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6656 VecConstant); 6657 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6658 DAG.getConstant(0, DL, MVT::i32)); 6659 } 6660 6661 // Finally, try a VMVN.i32 6662 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6663 false, VMVNModImm); 6664 if (NewVal != SDValue()) { 6665 SDLoc DL(Op); 6666 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6667 6668 if (IsDouble) 6669 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6670 6671 // It's a float: cast and extract a vector element. 6672 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6673 VecConstant); 6674 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6675 DAG.getConstant(0, DL, MVT::i32)); 6676 } 6677 6678 return SDValue(); 6679 } 6680 6681 // check if an VEXT instruction can handle the shuffle mask when the 6682 // vector sources of the shuffle are the same. 6683 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6684 unsigned NumElts = VT.getVectorNumElements(); 6685 6686 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6687 if (M[0] < 0) 6688 return false; 6689 6690 Imm = M[0]; 6691 6692 // If this is a VEXT shuffle, the immediate value is the index of the first 6693 // element. The other shuffle indices must be the successive elements after 6694 // the first one. 6695 unsigned ExpectedElt = Imm; 6696 for (unsigned i = 1; i < NumElts; ++i) { 6697 // Increment the expected index. If it wraps around, just follow it 6698 // back to index zero and keep going. 6699 ++ExpectedElt; 6700 if (ExpectedElt == NumElts) 6701 ExpectedElt = 0; 6702 6703 if (M[i] < 0) continue; // ignore UNDEF indices 6704 if (ExpectedElt != static_cast<unsigned>(M[i])) 6705 return false; 6706 } 6707 6708 return true; 6709 } 6710 6711 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6712 bool &ReverseVEXT, unsigned &Imm) { 6713 unsigned NumElts = VT.getVectorNumElements(); 6714 ReverseVEXT = false; 6715 6716 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6717 if (M[0] < 0) 6718 return false; 6719 6720 Imm = M[0]; 6721 6722 // If this is a VEXT shuffle, the immediate value is the index of the first 6723 // element. The other shuffle indices must be the successive elements after 6724 // the first one. 6725 unsigned ExpectedElt = Imm; 6726 for (unsigned i = 1; i < NumElts; ++i) { 6727 // Increment the expected index. If it wraps around, it may still be 6728 // a VEXT but the source vectors must be swapped. 6729 ExpectedElt += 1; 6730 if (ExpectedElt == NumElts * 2) { 6731 ExpectedElt = 0; 6732 ReverseVEXT = true; 6733 } 6734 6735 if (M[i] < 0) continue; // ignore UNDEF indices 6736 if (ExpectedElt != static_cast<unsigned>(M[i])) 6737 return false; 6738 } 6739 6740 // Adjust the index value if the source operands will be swapped. 6741 if (ReverseVEXT) 6742 Imm -= NumElts; 6743 6744 return true; 6745 } 6746 6747 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6748 /// instruction with the specified blocksize. (The order of the elements 6749 /// within each block of the vector is reversed.) 6750 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6751 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6752 "Only possible block sizes for VREV are: 16, 32, 64"); 6753 6754 unsigned EltSz = VT.getScalarSizeInBits(); 6755 if (EltSz == 64) 6756 return false; 6757 6758 unsigned NumElts = VT.getVectorNumElements(); 6759 unsigned BlockElts = M[0] + 1; 6760 // If the first shuffle index is UNDEF, be optimistic. 6761 if (M[0] < 0) 6762 BlockElts = BlockSize / EltSz; 6763 6764 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6765 return false; 6766 6767 for (unsigned i = 0; i < NumElts; ++i) { 6768 if (M[i] < 0) continue; // ignore UNDEF indices 6769 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6770 return false; 6771 } 6772 6773 return true; 6774 } 6775 6776 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6777 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6778 // range, then 0 is placed into the resulting vector. So pretty much any mask 6779 // of 8 elements can work here. 6780 return VT == MVT::v8i8 && M.size() == 8; 6781 } 6782 6783 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6784 unsigned Index) { 6785 if (Mask.size() == Elements * 2) 6786 return Index / Elements; 6787 return Mask[Index] == 0 ? 0 : 1; 6788 } 6789 6790 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6791 // checking that pairs of elements in the shuffle mask represent the same index 6792 // in each vector, incrementing the expected index by 2 at each step. 6793 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6794 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6795 // v2={e,f,g,h} 6796 // WhichResult gives the offset for each element in the mask based on which 6797 // of the two results it belongs to. 6798 // 6799 // The transpose can be represented either as: 6800 // result1 = shufflevector v1, v2, result1_shuffle_mask 6801 // result2 = shufflevector v1, v2, result2_shuffle_mask 6802 // where v1/v2 and the shuffle masks have the same number of elements 6803 // (here WhichResult (see below) indicates which result is being checked) 6804 // 6805 // or as: 6806 // results = shufflevector v1, v2, shuffle_mask 6807 // where both results are returned in one vector and the shuffle mask has twice 6808 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6809 // want to check the low half and high half of the shuffle mask as if it were 6810 // the other case 6811 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6812 unsigned EltSz = VT.getScalarSizeInBits(); 6813 if (EltSz == 64) 6814 return false; 6815 6816 unsigned NumElts = VT.getVectorNumElements(); 6817 if (M.size() != NumElts && M.size() != NumElts*2) 6818 return false; 6819 6820 // If the mask is twice as long as the input vector then we need to check the 6821 // upper and lower parts of the mask with a matching value for WhichResult 6822 // FIXME: A mask with only even values will be rejected in case the first 6823 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6824 // M[0] is used to determine WhichResult 6825 for (unsigned i = 0; i < M.size(); i += NumElts) { 6826 WhichResult = SelectPairHalf(NumElts, M, i); 6827 for (unsigned j = 0; j < NumElts; j += 2) { 6828 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6829 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6830 return false; 6831 } 6832 } 6833 6834 if (M.size() == NumElts*2) 6835 WhichResult = 0; 6836 6837 return true; 6838 } 6839 6840 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6841 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6842 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6843 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6844 unsigned EltSz = VT.getScalarSizeInBits(); 6845 if (EltSz == 64) 6846 return false; 6847 6848 unsigned NumElts = VT.getVectorNumElements(); 6849 if (M.size() != NumElts && M.size() != NumElts*2) 6850 return false; 6851 6852 for (unsigned i = 0; i < M.size(); i += NumElts) { 6853 WhichResult = SelectPairHalf(NumElts, M, i); 6854 for (unsigned j = 0; j < NumElts; j += 2) { 6855 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6856 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6857 return false; 6858 } 6859 } 6860 6861 if (M.size() == NumElts*2) 6862 WhichResult = 0; 6863 6864 return true; 6865 } 6866 6867 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6868 // that the mask elements are either all even and in steps of size 2 or all odd 6869 // and in steps of size 2. 6870 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6871 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6872 // v2={e,f,g,h} 6873 // Requires similar checks to that of isVTRNMask with 6874 // respect the how results are returned. 6875 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6876 unsigned EltSz = VT.getScalarSizeInBits(); 6877 if (EltSz == 64) 6878 return false; 6879 6880 unsigned NumElts = VT.getVectorNumElements(); 6881 if (M.size() != NumElts && M.size() != NumElts*2) 6882 return false; 6883 6884 for (unsigned i = 0; i < M.size(); i += NumElts) { 6885 WhichResult = SelectPairHalf(NumElts, M, i); 6886 for (unsigned j = 0; j < NumElts; ++j) { 6887 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6888 return false; 6889 } 6890 } 6891 6892 if (M.size() == NumElts*2) 6893 WhichResult = 0; 6894 6895 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6896 if (VT.is64BitVector() && EltSz == 32) 6897 return false; 6898 6899 return true; 6900 } 6901 6902 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6903 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6904 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6905 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6906 unsigned EltSz = VT.getScalarSizeInBits(); 6907 if (EltSz == 64) 6908 return false; 6909 6910 unsigned NumElts = VT.getVectorNumElements(); 6911 if (M.size() != NumElts && M.size() != NumElts*2) 6912 return false; 6913 6914 unsigned Half = NumElts / 2; 6915 for (unsigned i = 0; i < M.size(); i += NumElts) { 6916 WhichResult = SelectPairHalf(NumElts, M, i); 6917 for (unsigned j = 0; j < NumElts; j += Half) { 6918 unsigned Idx = WhichResult; 6919 for (unsigned k = 0; k < Half; ++k) { 6920 int MIdx = M[i + j + k]; 6921 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6922 return false; 6923 Idx += 2; 6924 } 6925 } 6926 } 6927 6928 if (M.size() == NumElts*2) 6929 WhichResult = 0; 6930 6931 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6932 if (VT.is64BitVector() && EltSz == 32) 6933 return false; 6934 6935 return true; 6936 } 6937 6938 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6939 // that pairs of elements of the shufflemask represent the same index in each 6940 // vector incrementing sequentially through the vectors. 6941 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6942 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6943 // v2={e,f,g,h} 6944 // Requires similar checks to that of isVTRNMask with respect the how results 6945 // are returned. 6946 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6947 unsigned EltSz = VT.getScalarSizeInBits(); 6948 if (EltSz == 64) 6949 return false; 6950 6951 unsigned NumElts = VT.getVectorNumElements(); 6952 if (M.size() != NumElts && M.size() != NumElts*2) 6953 return false; 6954 6955 for (unsigned i = 0; i < M.size(); i += NumElts) { 6956 WhichResult = SelectPairHalf(NumElts, M, i); 6957 unsigned Idx = WhichResult * NumElts / 2; 6958 for (unsigned j = 0; j < NumElts; j += 2) { 6959 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6960 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6961 return false; 6962 Idx += 1; 6963 } 6964 } 6965 6966 if (M.size() == NumElts*2) 6967 WhichResult = 0; 6968 6969 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6970 if (VT.is64BitVector() && EltSz == 32) 6971 return false; 6972 6973 return true; 6974 } 6975 6976 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6977 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6978 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6979 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6980 unsigned EltSz = VT.getScalarSizeInBits(); 6981 if (EltSz == 64) 6982 return false; 6983 6984 unsigned NumElts = VT.getVectorNumElements(); 6985 if (M.size() != NumElts && M.size() != NumElts*2) 6986 return false; 6987 6988 for (unsigned i = 0; i < M.size(); i += NumElts) { 6989 WhichResult = SelectPairHalf(NumElts, M, i); 6990 unsigned Idx = WhichResult * NumElts / 2; 6991 for (unsigned j = 0; j < NumElts; j += 2) { 6992 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6993 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6994 return false; 6995 Idx += 1; 6996 } 6997 } 6998 6999 if (M.size() == NumElts*2) 7000 WhichResult = 0; 7001 7002 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7003 if (VT.is64BitVector() && EltSz == 32) 7004 return false; 7005 7006 return true; 7007 } 7008 7009 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 7010 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 7011 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 7012 unsigned &WhichResult, 7013 bool &isV_UNDEF) { 7014 isV_UNDEF = false; 7015 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 7016 return ARMISD::VTRN; 7017 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 7018 return ARMISD::VUZP; 7019 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 7020 return ARMISD::VZIP; 7021 7022 isV_UNDEF = true; 7023 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7024 return ARMISD::VTRN; 7025 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7026 return ARMISD::VUZP; 7027 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7028 return ARMISD::VZIP; 7029 7030 return 0; 7031 } 7032 7033 /// \return true if this is a reverse operation on an vector. 7034 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 7035 unsigned NumElts = VT.getVectorNumElements(); 7036 // Make sure the mask has the right size. 7037 if (NumElts != M.size()) 7038 return false; 7039 7040 // Look for <15, ..., 3, -1, 1, 0>. 7041 for (unsigned i = 0; i != NumElts; ++i) 7042 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 7043 return false; 7044 7045 return true; 7046 } 7047 7048 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) { 7049 unsigned NumElts = VT.getVectorNumElements(); 7050 // Make sure the mask has the right size. 7051 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8)) 7052 return false; 7053 7054 // If Top 7055 // Look for <0, N, 2, N+2, 4, N+4, ..>. 7056 // This inserts Input2 into Input1 7057 // else if not Top 7058 // Look for <0, N+1, 2, N+3, 4, N+5, ..> 7059 // This inserts Input1 into Input2 7060 unsigned Offset = Top ? 0 : 1; 7061 for (unsigned i = 0; i < NumElts; i+=2) { 7062 if (M[i] >= 0 && M[i] != (int)i) 7063 return false; 7064 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset)) 7065 return false; 7066 } 7067 7068 return true; 7069 } 7070 7071 // If N is an integer constant that can be moved into a register in one 7072 // instruction, return an SDValue of such a constant (will become a MOV 7073 // instruction). Otherwise return null. 7074 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 7075 const ARMSubtarget *ST, const SDLoc &dl) { 7076 uint64_t Val; 7077 if (!isa<ConstantSDNode>(N)) 7078 return SDValue(); 7079 Val = cast<ConstantSDNode>(N)->getZExtValue(); 7080 7081 if (ST->isThumb1Only()) { 7082 if (Val <= 255 || ~Val <= 255) 7083 return DAG.getConstant(Val, dl, MVT::i32); 7084 } else { 7085 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 7086 return DAG.getConstant(Val, dl, MVT::i32); 7087 } 7088 return SDValue(); 7089 } 7090 7091 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 7092 const ARMSubtarget *ST) { 7093 SDLoc dl(Op); 7094 EVT VT = Op.getValueType(); 7095 7096 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 7097 7098 unsigned NumElts = VT.getVectorNumElements(); 7099 unsigned BoolMask; 7100 unsigned BitsPerBool; 7101 if (NumElts == 4) { 7102 BitsPerBool = 4; 7103 BoolMask = 0xf; 7104 } else if (NumElts == 8) { 7105 BitsPerBool = 2; 7106 BoolMask = 0x3; 7107 } else if (NumElts == 16) { 7108 BitsPerBool = 1; 7109 BoolMask = 0x1; 7110 } else 7111 return SDValue(); 7112 7113 // If this is a single value copied into all lanes (a splat), we can just sign 7114 // extend that single value 7115 SDValue FirstOp = Op.getOperand(0); 7116 if (!isa<ConstantSDNode>(FirstOp) && 7117 std::all_of(std::next(Op->op_begin()), Op->op_end(), 7118 [&FirstOp](SDUse &U) { 7119 return U.get().isUndef() || U.get() == FirstOp; 7120 })) { 7121 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp, 7122 DAG.getValueType(MVT::i1)); 7123 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext); 7124 } 7125 7126 // First create base with bits set where known 7127 unsigned Bits32 = 0; 7128 for (unsigned i = 0; i < NumElts; ++i) { 7129 SDValue V = Op.getOperand(i); 7130 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 7131 continue; 7132 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 7133 if (BitSet) 7134 Bits32 |= BoolMask << (i * BitsPerBool); 7135 } 7136 7137 // Add in unknown nodes 7138 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 7139 DAG.getConstant(Bits32, dl, MVT::i32)); 7140 for (unsigned i = 0; i < NumElts; ++i) { 7141 SDValue V = Op.getOperand(i); 7142 if (isa<ConstantSDNode>(V) || V.isUndef()) 7143 continue; 7144 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 7145 DAG.getConstant(i, dl, MVT::i32)); 7146 } 7147 7148 return Base; 7149 } 7150 7151 // If this is a case we can't handle, return null and let the default 7152 // expansion code take care of it. 7153 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 7154 const ARMSubtarget *ST) const { 7155 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7156 SDLoc dl(Op); 7157 EVT VT = Op.getValueType(); 7158 7159 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7160 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 7161 7162 APInt SplatBits, SplatUndef; 7163 unsigned SplatBitSize; 7164 bool HasAnyUndefs; 7165 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7166 if (SplatUndef.isAllOnesValue()) 7167 return DAG.getUNDEF(VT); 7168 7169 if ((ST->hasNEON() && SplatBitSize <= 64) || 7170 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) { 7171 // Check if an immediate VMOV works. 7172 EVT VmovVT; 7173 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 7174 SplatUndef.getZExtValue(), SplatBitSize, 7175 DAG, dl, VmovVT, VT.is128BitVector(), 7176 VMOVModImm); 7177 7178 if (Val.getNode()) { 7179 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 7180 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7181 } 7182 7183 // Try an immediate VMVN. 7184 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 7185 Val = isVMOVModifiedImm( 7186 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, 7187 DAG, dl, VmovVT, VT.is128BitVector(), 7188 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 7189 if (Val.getNode()) { 7190 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 7191 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7192 } 7193 7194 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 7195 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 7196 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 7197 if (ImmVal != -1) { 7198 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 7199 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 7200 } 7201 } 7202 } 7203 } 7204 7205 // Scan through the operands to see if only one value is used. 7206 // 7207 // As an optimisation, even if more than one value is used it may be more 7208 // profitable to splat with one value then change some lanes. 7209 // 7210 // Heuristically we decide to do this if the vector has a "dominant" value, 7211 // defined as splatted to more than half of the lanes. 7212 unsigned NumElts = VT.getVectorNumElements(); 7213 bool isOnlyLowElement = true; 7214 bool usesOnlyOneValue = true; 7215 bool hasDominantValue = false; 7216 bool isConstant = true; 7217 7218 // Map of the number of times a particular SDValue appears in the 7219 // element list. 7220 DenseMap<SDValue, unsigned> ValueCounts; 7221 SDValue Value; 7222 for (unsigned i = 0; i < NumElts; ++i) { 7223 SDValue V = Op.getOperand(i); 7224 if (V.isUndef()) 7225 continue; 7226 if (i > 0) 7227 isOnlyLowElement = false; 7228 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7229 isConstant = false; 7230 7231 ValueCounts.insert(std::make_pair(V, 0)); 7232 unsigned &Count = ValueCounts[V]; 7233 7234 // Is this value dominant? (takes up more than half of the lanes) 7235 if (++Count > (NumElts / 2)) { 7236 hasDominantValue = true; 7237 Value = V; 7238 } 7239 } 7240 if (ValueCounts.size() != 1) 7241 usesOnlyOneValue = false; 7242 if (!Value.getNode() && !ValueCounts.empty()) 7243 Value = ValueCounts.begin()->first; 7244 7245 if (ValueCounts.empty()) 7246 return DAG.getUNDEF(VT); 7247 7248 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 7249 // Keep going if we are hitting this case. 7250 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 7251 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7252 7253 unsigned EltSize = VT.getScalarSizeInBits(); 7254 7255 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 7256 // i32 and try again. 7257 if (hasDominantValue && EltSize <= 32) { 7258 if (!isConstant) { 7259 SDValue N; 7260 7261 // If we are VDUPing a value that comes directly from a vector, that will 7262 // cause an unnecessary move to and from a GPR, where instead we could 7263 // just use VDUPLANE. We can only do this if the lane being extracted 7264 // is at a constant index, as the VDUP from lane instructions only have 7265 // constant-index forms. 7266 ConstantSDNode *constIndex; 7267 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7268 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 7269 // We need to create a new undef vector to use for the VDUPLANE if the 7270 // size of the vector from which we get the value is different than the 7271 // size of the vector that we need to create. We will insert the element 7272 // such that the register coalescer will remove unnecessary copies. 7273 if (VT != Value->getOperand(0).getValueType()) { 7274 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 7275 VT.getVectorNumElements(); 7276 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7277 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 7278 Value, DAG.getConstant(index, dl, MVT::i32)), 7279 DAG.getConstant(index, dl, MVT::i32)); 7280 } else 7281 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7282 Value->getOperand(0), Value->getOperand(1)); 7283 } else 7284 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 7285 7286 if (!usesOnlyOneValue) { 7287 // The dominant value was splatted as 'N', but we now have to insert 7288 // all differing elements. 7289 for (unsigned I = 0; I < NumElts; ++I) { 7290 if (Op.getOperand(I) == Value) 7291 continue; 7292 SmallVector<SDValue, 3> Ops; 7293 Ops.push_back(N); 7294 Ops.push_back(Op.getOperand(I)); 7295 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7296 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7297 } 7298 } 7299 return N; 7300 } 7301 if (VT.getVectorElementType().isFloatingPoint()) { 7302 SmallVector<SDValue, 8> Ops; 7303 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7304 assert(FVT == MVT::f32 || FVT == MVT::f16); 7305 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7306 for (unsigned i = 0; i < NumElts; ++i) 7307 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7308 Op.getOperand(i))); 7309 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7310 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7311 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7312 if (Val.getNode()) 7313 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7314 } 7315 if (usesOnlyOneValue) { 7316 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7317 if (isConstant && Val.getNode()) 7318 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7319 } 7320 } 7321 7322 // If all elements are constants and the case above didn't get hit, fall back 7323 // to the default expansion, which will generate a load from the constant 7324 // pool. 7325 if (isConstant) 7326 return SDValue(); 7327 7328 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 7329 if (NumElts >= 4) { 7330 SDValue shuffle = ReconstructShuffle(Op, DAG); 7331 if (shuffle != SDValue()) 7332 return shuffle; 7333 } 7334 7335 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7336 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7337 // into two 64-bit vectors; we might discover a better way to lower it. 7338 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7339 EVT ExtVT = VT.getVectorElementType(); 7340 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7341 SDValue Lower = 7342 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7343 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7344 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7345 SDValue Upper = DAG.getBuildVector( 7346 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7347 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7348 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7349 if (Lower && Upper) 7350 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7351 } 7352 7353 // Vectors with 32- or 64-bit elements can be built by directly assigning 7354 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7355 // will be legalized. 7356 if (EltSize >= 32) { 7357 // Do the expansion with floating-point types, since that is what the VFP 7358 // registers are defined to use, and since i64 is not legal. 7359 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7360 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7361 SmallVector<SDValue, 8> Ops; 7362 for (unsigned i = 0; i < NumElts; ++i) 7363 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7364 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7365 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7366 } 7367 7368 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7369 // know the default expansion would otherwise fall back on something even 7370 // worse. For a vector with one or two non-undef values, that's 7371 // scalar_to_vector for the elements followed by a shuffle (provided the 7372 // shuffle is valid for the target) and materialization element by element 7373 // on the stack followed by a load for everything else. 7374 if (!isConstant && !usesOnlyOneValue) { 7375 SDValue Vec = DAG.getUNDEF(VT); 7376 for (unsigned i = 0 ; i < NumElts; ++i) { 7377 SDValue V = Op.getOperand(i); 7378 if (V.isUndef()) 7379 continue; 7380 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7381 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7382 } 7383 return Vec; 7384 } 7385 7386 return SDValue(); 7387 } 7388 7389 // Gather data to see if the operation can be modelled as a 7390 // shuffle in combination with VEXTs. 7391 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7392 SelectionDAG &DAG) const { 7393 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7394 SDLoc dl(Op); 7395 EVT VT = Op.getValueType(); 7396 unsigned NumElts = VT.getVectorNumElements(); 7397 7398 struct ShuffleSourceInfo { 7399 SDValue Vec; 7400 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7401 unsigned MaxElt = 0; 7402 7403 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7404 // be compatible with the shuffle we intend to construct. As a result 7405 // ShuffleVec will be some sliding window into the original Vec. 7406 SDValue ShuffleVec; 7407 7408 // Code should guarantee that element i in Vec starts at element "WindowBase 7409 // + i * WindowScale in ShuffleVec". 7410 int WindowBase = 0; 7411 int WindowScale = 1; 7412 7413 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7414 7415 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7416 }; 7417 7418 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7419 // node. 7420 SmallVector<ShuffleSourceInfo, 2> Sources; 7421 for (unsigned i = 0; i < NumElts; ++i) { 7422 SDValue V = Op.getOperand(i); 7423 if (V.isUndef()) 7424 continue; 7425 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7426 // A shuffle can only come from building a vector from various 7427 // elements of other vectors. 7428 return SDValue(); 7429 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7430 // Furthermore, shuffles require a constant mask, whereas extractelts 7431 // accept variable indices. 7432 return SDValue(); 7433 } 7434 7435 // Add this element source to the list if it's not already there. 7436 SDValue SourceVec = V.getOperand(0); 7437 auto Source = llvm::find(Sources, SourceVec); 7438 if (Source == Sources.end()) 7439 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7440 7441 // Update the minimum and maximum lane number seen. 7442 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7443 Source->MinElt = std::min(Source->MinElt, EltNo); 7444 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7445 } 7446 7447 // Currently only do something sane when at most two source vectors 7448 // are involved. 7449 if (Sources.size() > 2) 7450 return SDValue(); 7451 7452 // Find out the smallest element size among result and two sources, and use 7453 // it as element size to build the shuffle_vector. 7454 EVT SmallestEltTy = VT.getVectorElementType(); 7455 for (auto &Source : Sources) { 7456 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7457 if (SrcEltTy.bitsLT(SmallestEltTy)) 7458 SmallestEltTy = SrcEltTy; 7459 } 7460 unsigned ResMultiplier = 7461 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7462 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7463 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7464 7465 // If the source vector is too wide or too narrow, we may nevertheless be able 7466 // to construct a compatible shuffle either by concatenating it with UNDEF or 7467 // extracting a suitable range of elements. 7468 for (auto &Src : Sources) { 7469 EVT SrcVT = Src.ShuffleVec.getValueType(); 7470 7471 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 7472 continue; 7473 7474 // This stage of the search produces a source with the same element type as 7475 // the original, but with a total width matching the BUILD_VECTOR output. 7476 EVT EltVT = SrcVT.getVectorElementType(); 7477 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 7478 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7479 7480 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 7481 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 7482 return SDValue(); 7483 // We can pad out the smaller vector for free, so if it's part of a 7484 // shuffle... 7485 Src.ShuffleVec = 7486 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7487 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7488 continue; 7489 } 7490 7491 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 7492 return SDValue(); 7493 7494 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7495 // Span too large for a VEXT to cope 7496 return SDValue(); 7497 } 7498 7499 if (Src.MinElt >= NumSrcElts) { 7500 // The extraction can just take the second half 7501 Src.ShuffleVec = 7502 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7503 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7504 Src.WindowBase = -NumSrcElts; 7505 } else if (Src.MaxElt < NumSrcElts) { 7506 // The extraction can just take the first half 7507 Src.ShuffleVec = 7508 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7509 DAG.getConstant(0, dl, MVT::i32)); 7510 } else { 7511 // An actual VEXT is needed 7512 SDValue VEXTSrc1 = 7513 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7514 DAG.getConstant(0, dl, MVT::i32)); 7515 SDValue VEXTSrc2 = 7516 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7517 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7518 7519 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7520 VEXTSrc2, 7521 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7522 Src.WindowBase = -Src.MinElt; 7523 } 7524 } 7525 7526 // Another possible incompatibility occurs from the vector element types. We 7527 // can fix this by bitcasting the source vectors to the same type we intend 7528 // for the shuffle. 7529 for (auto &Src : Sources) { 7530 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7531 if (SrcEltTy == SmallestEltTy) 7532 continue; 7533 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7534 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec); 7535 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7536 Src.WindowBase *= Src.WindowScale; 7537 } 7538 7539 // Final sanity check before we try to actually produce a shuffle. 7540 LLVM_DEBUG(for (auto Src 7541 : Sources) 7542 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7543 7544 // The stars all align, our next step is to produce the mask for the shuffle. 7545 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7546 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7547 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7548 SDValue Entry = Op.getOperand(i); 7549 if (Entry.isUndef()) 7550 continue; 7551 7552 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7553 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7554 7555 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7556 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7557 // segment. 7558 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7559 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 7560 VT.getScalarSizeInBits()); 7561 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7562 7563 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7564 // starting at the appropriate offset. 7565 int *LaneMask = &Mask[i * ResMultiplier]; 7566 7567 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7568 ExtractBase += NumElts * (Src - Sources.begin()); 7569 for (int j = 0; j < LanesDefined; ++j) 7570 LaneMask[j] = ExtractBase + j; 7571 } 7572 7573 7574 // We can't handle more than two sources. This should have already 7575 // been checked before this point. 7576 assert(Sources.size() <= 2 && "Too many sources!"); 7577 7578 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7579 for (unsigned i = 0; i < Sources.size(); ++i) 7580 ShuffleOps[i] = Sources[i].ShuffleVec; 7581 7582 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7583 ShuffleOps[1], Mask, DAG); 7584 if (!Shuffle) 7585 return SDValue(); 7586 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle); 7587 } 7588 7589 enum ShuffleOpCodes { 7590 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7591 OP_VREV, 7592 OP_VDUP0, 7593 OP_VDUP1, 7594 OP_VDUP2, 7595 OP_VDUP3, 7596 OP_VEXT1, 7597 OP_VEXT2, 7598 OP_VEXT3, 7599 OP_VUZPL, // VUZP, left result 7600 OP_VUZPR, // VUZP, right result 7601 OP_VZIPL, // VZIP, left result 7602 OP_VZIPR, // VZIP, right result 7603 OP_VTRNL, // VTRN, left result 7604 OP_VTRNR // VTRN, right result 7605 }; 7606 7607 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7608 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7609 switch (OpNum) { 7610 case OP_COPY: 7611 case OP_VREV: 7612 case OP_VDUP0: 7613 case OP_VDUP1: 7614 case OP_VDUP2: 7615 case OP_VDUP3: 7616 return true; 7617 } 7618 return false; 7619 } 7620 7621 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7622 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7623 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7624 /// are assumed to be legal. 7625 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7626 if (VT.getVectorNumElements() == 4 && 7627 (VT.is128BitVector() || VT.is64BitVector())) { 7628 unsigned PFIndexes[4]; 7629 for (unsigned i = 0; i != 4; ++i) { 7630 if (M[i] < 0) 7631 PFIndexes[i] = 8; 7632 else 7633 PFIndexes[i] = M[i]; 7634 } 7635 7636 // Compute the index in the perfect shuffle table. 7637 unsigned PFTableIndex = 7638 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7639 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7640 unsigned Cost = (PFEntry >> 30); 7641 7642 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7643 return true; 7644 } 7645 7646 bool ReverseVEXT, isV_UNDEF; 7647 unsigned Imm, WhichResult; 7648 7649 unsigned EltSize = VT.getScalarSizeInBits(); 7650 if (EltSize >= 32 || 7651 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7652 ShuffleVectorInst::isIdentityMask(M) || 7653 isVREVMask(M, VT, 64) || 7654 isVREVMask(M, VT, 32) || 7655 isVREVMask(M, VT, 16)) 7656 return true; 7657 else if (Subtarget->hasNEON() && 7658 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7659 isVTBLMask(M, VT) || 7660 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7661 return true; 7662 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7663 isReverseMask(M, VT)) 7664 return true; 7665 else if (Subtarget->hasMVEIntegerOps() && 7666 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1))) 7667 return true; 7668 else 7669 return false; 7670 } 7671 7672 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7673 /// the specified operations to build the shuffle. 7674 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7675 SDValue RHS, SelectionDAG &DAG, 7676 const SDLoc &dl) { 7677 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7678 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7679 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7680 7681 if (OpNum == OP_COPY) { 7682 if (LHSID == (1*9+2)*9+3) return LHS; 7683 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7684 return RHS; 7685 } 7686 7687 SDValue OpLHS, OpRHS; 7688 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7689 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7690 EVT VT = OpLHS.getValueType(); 7691 7692 switch (OpNum) { 7693 default: llvm_unreachable("Unknown shuffle opcode!"); 7694 case OP_VREV: 7695 // VREV divides the vector in half and swaps within the half. 7696 if (VT.getVectorElementType() == MVT::i32 || 7697 VT.getVectorElementType() == MVT::f32) 7698 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7699 // vrev <4 x i16> -> VREV32 7700 if (VT.getVectorElementType() == MVT::i16) 7701 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7702 // vrev <4 x i8> -> VREV16 7703 assert(VT.getVectorElementType() == MVT::i8); 7704 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 7705 case OP_VDUP0: 7706 case OP_VDUP1: 7707 case OP_VDUP2: 7708 case OP_VDUP3: 7709 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7710 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 7711 case OP_VEXT1: 7712 case OP_VEXT2: 7713 case OP_VEXT3: 7714 return DAG.getNode(ARMISD::VEXT, dl, VT, 7715 OpLHS, OpRHS, 7716 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 7717 case OP_VUZPL: 7718 case OP_VUZPR: 7719 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7720 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7721 case OP_VZIPL: 7722 case OP_VZIPR: 7723 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7724 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7725 case OP_VTRNL: 7726 case OP_VTRNR: 7727 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7728 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7729 } 7730 } 7731 7732 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7733 ArrayRef<int> ShuffleMask, 7734 SelectionDAG &DAG) { 7735 // Check to see if we can use the VTBL instruction. 7736 SDValue V1 = Op.getOperand(0); 7737 SDValue V2 = Op.getOperand(1); 7738 SDLoc DL(Op); 7739 7740 SmallVector<SDValue, 8> VTBLMask; 7741 for (ArrayRef<int>::iterator 7742 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7743 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7744 7745 if (V2.getNode()->isUndef()) 7746 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7747 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7748 7749 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7750 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7751 } 7752 7753 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7754 SelectionDAG &DAG) { 7755 SDLoc DL(Op); 7756 SDValue OpLHS = Op.getOperand(0); 7757 EVT VT = OpLHS.getValueType(); 7758 7759 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7760 "Expect an v8i16/v16i8 type"); 7761 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7762 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7763 // extract the first 8 bytes into the top double word and the last 8 bytes 7764 // into the bottom double word. The v8i16 case is similar. 7765 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7766 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7767 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7768 } 7769 7770 static EVT getVectorTyFromPredicateVector(EVT VT) { 7771 switch (VT.getSimpleVT().SimpleTy) { 7772 case MVT::v4i1: 7773 return MVT::v4i32; 7774 case MVT::v8i1: 7775 return MVT::v8i16; 7776 case MVT::v16i1: 7777 return MVT::v16i8; 7778 default: 7779 llvm_unreachable("Unexpected vector predicate type"); 7780 } 7781 } 7782 7783 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 7784 SelectionDAG &DAG) { 7785 // Converting from boolean predicates to integers involves creating a vector 7786 // of all ones or all zeroes and selecting the lanes based upon the real 7787 // predicate. 7788 SDValue AllOnes = 7789 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 7790 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 7791 7792 SDValue AllZeroes = 7793 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 7794 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 7795 7796 // Get full vector type from predicate type 7797 EVT NewVT = getVectorTyFromPredicateVector(VT); 7798 7799 SDValue RecastV1; 7800 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 7801 // this to a v16i1. This cannot be done with an ordinary bitcast because the 7802 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 7803 // since we know in hardware the sizes are really the same. 7804 if (VT != MVT::v16i1) 7805 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 7806 else 7807 RecastV1 = Pred; 7808 7809 // Select either all ones or zeroes depending upon the real predicate bits. 7810 SDValue PredAsVector = 7811 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 7812 7813 // Recast our new predicate-as-integer v16i8 vector into something 7814 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 7815 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 7816 } 7817 7818 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 7819 const ARMSubtarget *ST) { 7820 EVT VT = Op.getValueType(); 7821 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7822 ArrayRef<int> ShuffleMask = SVN->getMask(); 7823 7824 assert(ST->hasMVEIntegerOps() && 7825 "No support for vector shuffle of boolean predicates"); 7826 7827 SDValue V1 = Op.getOperand(0); 7828 SDLoc dl(Op); 7829 if (isReverseMask(ShuffleMask, VT)) { 7830 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 7831 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 7832 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 7833 DAG.getConstant(16, dl, MVT::i32)); 7834 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 7835 } 7836 7837 // Until we can come up with optimised cases for every single vector 7838 // shuffle in existence we have chosen the least painful strategy. This is 7839 // to essentially promote the boolean predicate to a 8-bit integer, where 7840 // each predicate represents a byte. Then we fall back on a normal integer 7841 // vector shuffle and convert the result back into a predicate vector. In 7842 // many cases the generated code might be even better than scalar code 7843 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 7844 // fields in a register into 8 other arbitrary 2-bit fields! 7845 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 7846 EVT NewVT = PredAsVector.getValueType(); 7847 7848 // Do the shuffle! 7849 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 7850 DAG.getUNDEF(NewVT), ShuffleMask); 7851 7852 // Now return the result of comparing the shuffled vector with zero, 7853 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7854 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 7855 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7856 } 7857 7858 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op, 7859 ArrayRef<int> ShuffleMask, 7860 SelectionDAG &DAG) { 7861 // Attempt to lower the vector shuffle using as many whole register movs as 7862 // possible. This is useful for types smaller than 32bits, which would 7863 // often otherwise become a series for grp movs. 7864 SDLoc dl(Op); 7865 EVT VT = Op.getValueType(); 7866 if (VT.getScalarSizeInBits() >= 32) 7867 return SDValue(); 7868 7869 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && 7870 "Unexpected vector type"); 7871 int NumElts = VT.getVectorNumElements(); 7872 int QuarterSize = NumElts / 4; 7873 // The four final parts of the vector, as i32's 7874 SDValue Parts[4]; 7875 7876 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not 7877 // <u,u,u,u>), returning the vmov lane index 7878 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) { 7879 // Detect which mov lane this would be from the first non-undef element. 7880 int MovIdx = -1; 7881 for (int i = 0; i < Length; i++) { 7882 if (ShuffleMask[Start + i] >= 0) { 7883 if (ShuffleMask[Start + i] % Length != i) 7884 return -1; 7885 MovIdx = ShuffleMask[Start + i] / Length; 7886 break; 7887 } 7888 } 7889 // If all items are undef, leave this for other combines 7890 if (MovIdx == -1) 7891 return -1; 7892 // Check the remaining values are the correct part of the same mov 7893 for (int i = 1; i < Length; i++) { 7894 if (ShuffleMask[Start + i] >= 0 && 7895 (ShuffleMask[Start + i] / Length != MovIdx || 7896 ShuffleMask[Start + i] % Length != i)) 7897 return -1; 7898 } 7899 return MovIdx; 7900 }; 7901 7902 for (int Part = 0; Part < 4; ++Part) { 7903 // Does this part look like a mov 7904 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize); 7905 if (Elt != -1) { 7906 SDValue Input = Op->getOperand(0); 7907 if (Elt >= 4) { 7908 Input = Op->getOperand(1); 7909 Elt -= 4; 7910 } 7911 SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input); 7912 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast, 7913 DAG.getConstant(Elt, dl, MVT::i32)); 7914 } 7915 } 7916 7917 // Nothing interesting found, just return 7918 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3]) 7919 return SDValue(); 7920 7921 // The other parts need to be built with the old shuffle vector, cast to a 7922 // v4i32 and extract_vector_elts 7923 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) { 7924 SmallVector<int, 16> NewShuffleMask; 7925 for (int Part = 0; Part < 4; ++Part) 7926 for (int i = 0; i < QuarterSize; i++) 7927 NewShuffleMask.push_back( 7928 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]); 7929 SDValue NewShuffle = DAG.getVectorShuffle( 7930 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask); 7931 SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle); 7932 7933 for (int Part = 0; Part < 4; ++Part) 7934 if (!Parts[Part]) 7935 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7936 BitCast, DAG.getConstant(Part, dl, MVT::i32)); 7937 } 7938 // Build a vector out of the various parts and bitcast it back to the original 7939 // type. 7940 SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts); 7941 return DAG.getBitcast(VT, NewVec); 7942 } 7943 7944 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 7945 const ARMSubtarget *ST) { 7946 SDValue V1 = Op.getOperand(0); 7947 SDValue V2 = Op.getOperand(1); 7948 SDLoc dl(Op); 7949 EVT VT = Op.getValueType(); 7950 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7951 unsigned EltSize = VT.getScalarSizeInBits(); 7952 7953 if (ST->hasMVEIntegerOps() && EltSize == 1) 7954 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 7955 7956 // Convert shuffles that are directly supported on NEON to target-specific 7957 // DAG nodes, instead of keeping them as shuffles and matching them again 7958 // during code selection. This is more efficient and avoids the possibility 7959 // of inconsistencies between legalization and selection. 7960 // FIXME: floating-point vectors should be canonicalized to integer vectors 7961 // of the same time so that they get CSEd properly. 7962 ArrayRef<int> ShuffleMask = SVN->getMask(); 7963 7964 if (EltSize <= 32) { 7965 if (SVN->isSplat()) { 7966 int Lane = SVN->getSplatIndex(); 7967 // If this is undef splat, generate it via "just" vdup, if possible. 7968 if (Lane == -1) Lane = 0; 7969 7970 // Test if V1 is a SCALAR_TO_VECTOR. 7971 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7972 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7973 } 7974 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7975 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7976 // reaches it). 7977 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7978 !isa<ConstantSDNode>(V1.getOperand(0))) { 7979 bool IsScalarToVector = true; 7980 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7981 if (!V1.getOperand(i).isUndef()) { 7982 IsScalarToVector = false; 7983 break; 7984 } 7985 if (IsScalarToVector) 7986 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7987 } 7988 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7989 DAG.getConstant(Lane, dl, MVT::i32)); 7990 } 7991 7992 bool ReverseVEXT = false; 7993 unsigned Imm = 0; 7994 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7995 if (ReverseVEXT) 7996 std::swap(V1, V2); 7997 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7998 DAG.getConstant(Imm, dl, MVT::i32)); 7999 } 8000 8001 if (isVREVMask(ShuffleMask, VT, 64)) 8002 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 8003 if (isVREVMask(ShuffleMask, VT, 32)) 8004 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 8005 if (isVREVMask(ShuffleMask, VT, 16)) 8006 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 8007 8008 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 8009 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 8010 DAG.getConstant(Imm, dl, MVT::i32)); 8011 } 8012 8013 // Check for Neon shuffles that modify both input vectors in place. 8014 // If both results are used, i.e., if there are two shuffles with the same 8015 // source operands and with masks corresponding to both results of one of 8016 // these operations, DAG memoization will ensure that a single node is 8017 // used for both shuffles. 8018 unsigned WhichResult = 0; 8019 bool isV_UNDEF = false; 8020 if (ST->hasNEON()) { 8021 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8022 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 8023 if (isV_UNDEF) 8024 V2 = V1; 8025 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 8026 .getValue(WhichResult); 8027 } 8028 } 8029 if (ST->hasMVEIntegerOps()) { 8030 if (isVMOVNMask(ShuffleMask, VT, 0)) 8031 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1, 8032 DAG.getConstant(0, dl, MVT::i32)); 8033 if (isVMOVNMask(ShuffleMask, VT, 1)) 8034 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2, 8035 DAG.getConstant(1, dl, MVT::i32)); 8036 } 8037 8038 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 8039 // shuffles that produce a result larger than their operands with: 8040 // shuffle(concat(v1, undef), concat(v2, undef)) 8041 // -> 8042 // shuffle(concat(v1, v2), undef) 8043 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 8044 // 8045 // This is useful in the general case, but there are special cases where 8046 // native shuffles produce larger results: the two-result ops. 8047 // 8048 // Look through the concat when lowering them: 8049 // shuffle(concat(v1, v2), undef) 8050 // -> 8051 // concat(VZIP(v1, v2):0, :1) 8052 // 8053 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 8054 SDValue SubV1 = V1->getOperand(0); 8055 SDValue SubV2 = V1->getOperand(1); 8056 EVT SubVT = SubV1.getValueType(); 8057 8058 // We expect these to have been canonicalized to -1. 8059 assert(llvm::all_of(ShuffleMask, [&](int i) { 8060 return i < (int)VT.getVectorNumElements(); 8061 }) && "Unexpected shuffle index into UNDEF operand!"); 8062 8063 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8064 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 8065 if (isV_UNDEF) 8066 SubV2 = SubV1; 8067 assert((WhichResult == 0) && 8068 "In-place shuffle of concat can only have one result!"); 8069 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 8070 SubV1, SubV2); 8071 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 8072 Res.getValue(1)); 8073 } 8074 } 8075 } 8076 8077 // If the shuffle is not directly supported and it has 4 elements, use 8078 // the PerfectShuffle-generated table to synthesize it from other shuffles. 8079 unsigned NumElts = VT.getVectorNumElements(); 8080 if (NumElts == 4) { 8081 unsigned PFIndexes[4]; 8082 for (unsigned i = 0; i != 4; ++i) { 8083 if (ShuffleMask[i] < 0) 8084 PFIndexes[i] = 8; 8085 else 8086 PFIndexes[i] = ShuffleMask[i]; 8087 } 8088 8089 // Compute the index in the perfect shuffle table. 8090 unsigned PFTableIndex = 8091 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8092 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8093 unsigned Cost = (PFEntry >> 30); 8094 8095 if (Cost <= 4) { 8096 if (ST->hasNEON()) 8097 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8098 else if (isLegalMVEShuffleOp(PFEntry)) { 8099 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8100 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8101 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 8102 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 8103 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 8104 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8105 } 8106 } 8107 } 8108 8109 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 8110 if (EltSize >= 32) { 8111 // Do the expansion with floating-point types, since that is what the VFP 8112 // registers are defined to use, and since i64 is not legal. 8113 EVT EltVT = EVT::getFloatingPointVT(EltSize); 8114 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 8115 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 8116 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 8117 SmallVector<SDValue, 8> Ops; 8118 for (unsigned i = 0; i < NumElts; ++i) { 8119 if (ShuffleMask[i] < 0) 8120 Ops.push_back(DAG.getUNDEF(EltVT)); 8121 else 8122 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 8123 ShuffleMask[i] < (int)NumElts ? V1 : V2, 8124 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 8125 dl, MVT::i32))); 8126 } 8127 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 8128 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8129 } 8130 8131 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 8132 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 8133 8134 if (ST->hasNEON() && VT == MVT::v8i8) 8135 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 8136 return NewOp; 8137 8138 if (ST->hasMVEIntegerOps()) 8139 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG)) 8140 return NewOp; 8141 8142 return SDValue(); 8143 } 8144 8145 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8146 const ARMSubtarget *ST) { 8147 EVT VecVT = Op.getOperand(0).getValueType(); 8148 SDLoc dl(Op); 8149 8150 assert(ST->hasMVEIntegerOps() && 8151 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8152 8153 SDValue Conv = 8154 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8155 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8156 unsigned LaneWidth = 8157 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8158 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 8159 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 8160 Op.getOperand(1), DAG.getValueType(MVT::i1)); 8161 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 8162 DAG.getConstant(~Mask, dl, MVT::i32)); 8163 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 8164 } 8165 8166 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8167 SelectionDAG &DAG) const { 8168 // INSERT_VECTOR_ELT is legal only for immediate indexes. 8169 SDValue Lane = Op.getOperand(2); 8170 if (!isa<ConstantSDNode>(Lane)) 8171 return SDValue(); 8172 8173 SDValue Elt = Op.getOperand(1); 8174 EVT EltVT = Elt.getValueType(); 8175 8176 if (Subtarget->hasMVEIntegerOps() && 8177 Op.getValueType().getScalarSizeInBits() == 1) 8178 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 8179 8180 if (getTypeAction(*DAG.getContext(), EltVT) == 8181 TargetLowering::TypePromoteFloat) { 8182 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 8183 // but the type system will try to do that if we don't intervene. 8184 // Reinterpret any such vector-element insertion as one with the 8185 // corresponding integer types. 8186 8187 SDLoc dl(Op); 8188 8189 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 8190 assert(getTypeAction(*DAG.getContext(), IEltVT) != 8191 TargetLowering::TypePromoteFloat); 8192 8193 SDValue VecIn = Op.getOperand(0); 8194 EVT VecVT = VecIn.getValueType(); 8195 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 8196 VecVT.getVectorNumElements()); 8197 8198 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 8199 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 8200 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 8201 IVecIn, IElt, Lane); 8202 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 8203 } 8204 8205 return Op; 8206 } 8207 8208 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8209 const ARMSubtarget *ST) { 8210 EVT VecVT = Op.getOperand(0).getValueType(); 8211 SDLoc dl(Op); 8212 8213 assert(ST->hasMVEIntegerOps() && 8214 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8215 8216 SDValue Conv = 8217 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8218 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8219 unsigned LaneWidth = 8220 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8221 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 8222 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 8223 return Shift; 8224 } 8225 8226 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 8227 const ARMSubtarget *ST) { 8228 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 8229 SDValue Lane = Op.getOperand(1); 8230 if (!isa<ConstantSDNode>(Lane)) 8231 return SDValue(); 8232 8233 SDValue Vec = Op.getOperand(0); 8234 EVT VT = Vec.getValueType(); 8235 8236 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8237 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 8238 8239 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 8240 SDLoc dl(Op); 8241 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 8242 } 8243 8244 return Op; 8245 } 8246 8247 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 8248 const ARMSubtarget *ST) { 8249 SDValue V1 = Op.getOperand(0); 8250 SDValue V2 = Op.getOperand(1); 8251 SDLoc dl(Op); 8252 EVT VT = Op.getValueType(); 8253 EVT Op1VT = V1.getValueType(); 8254 EVT Op2VT = V2.getValueType(); 8255 unsigned NumElts = VT.getVectorNumElements(); 8256 8257 assert(Op1VT == Op2VT && "Operand types don't match!"); 8258 assert(VT.getScalarSizeInBits() == 1 && 8259 "Unexpected custom CONCAT_VECTORS lowering"); 8260 assert(ST->hasMVEIntegerOps() && 8261 "CONCAT_VECTORS lowering only supported for MVE"); 8262 8263 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8264 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 8265 8266 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 8267 // promoted to v8i16, etc. 8268 8269 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8270 8271 // Extract the vector elements from Op1 and Op2 one by one and truncate them 8272 // to be the right size for the destination. For example, if Op1 is v4i1 then 8273 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 8274 // which when promoted is v8i16. That means each i32 element from Op1 needs 8275 // truncating to i16 and inserting in the result. 8276 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 8277 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 8278 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 8279 EVT NewVT = NewV.getValueType(); 8280 EVT ConcatVT = ConVec.getValueType(); 8281 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 8282 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 8283 DAG.getIntPtrConstant(i, dl)); 8284 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 8285 DAG.getConstant(j, dl, MVT::i32)); 8286 } 8287 return ConVec; 8288 }; 8289 unsigned j = 0; 8290 ConVec = ExractInto(NewV1, ConVec, j); 8291 ConVec = ExractInto(NewV2, ConVec, j); 8292 8293 // Now return the result of comparing the subvector with zero, 8294 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8295 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 8296 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8297 } 8298 8299 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 8300 const ARMSubtarget *ST) { 8301 EVT VT = Op->getValueType(0); 8302 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8303 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 8304 8305 // The only time a CONCAT_VECTORS operation can have legal types is when 8306 // two 64-bit vectors are concatenated to a 128-bit vector. 8307 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 8308 "unexpected CONCAT_VECTORS"); 8309 SDLoc dl(Op); 8310 SDValue Val = DAG.getUNDEF(MVT::v2f64); 8311 SDValue Op0 = Op.getOperand(0); 8312 SDValue Op1 = Op.getOperand(1); 8313 if (!Op0.isUndef()) 8314 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8315 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 8316 DAG.getIntPtrConstant(0, dl)); 8317 if (!Op1.isUndef()) 8318 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8319 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 8320 DAG.getIntPtrConstant(1, dl)); 8321 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 8322 } 8323 8324 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 8325 const ARMSubtarget *ST) { 8326 SDValue V1 = Op.getOperand(0); 8327 SDValue V2 = Op.getOperand(1); 8328 SDLoc dl(Op); 8329 EVT VT = Op.getValueType(); 8330 EVT Op1VT = V1.getValueType(); 8331 unsigned NumElts = VT.getVectorNumElements(); 8332 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 8333 8334 assert(VT.getScalarSizeInBits() == 1 && 8335 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 8336 assert(ST->hasMVEIntegerOps() && 8337 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 8338 8339 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8340 8341 // We now have Op1 promoted to a vector of integers, where v8i1 gets 8342 // promoted to v8i16, etc. 8343 8344 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8345 8346 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 8347 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 8348 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 8349 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 8350 DAG.getIntPtrConstant(i, dl)); 8351 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 8352 DAG.getConstant(j, dl, MVT::i32)); 8353 } 8354 8355 // Now return the result of comparing the subvector with zero, 8356 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8357 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 8358 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8359 } 8360 8361 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 8362 /// element has been zero/sign-extended, depending on the isSigned parameter, 8363 /// from an integer type half its size. 8364 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 8365 bool isSigned) { 8366 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 8367 EVT VT = N->getValueType(0); 8368 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 8369 SDNode *BVN = N->getOperand(0).getNode(); 8370 if (BVN->getValueType(0) != MVT::v4i32 || 8371 BVN->getOpcode() != ISD::BUILD_VECTOR) 8372 return false; 8373 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8374 unsigned HiElt = 1 - LoElt; 8375 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 8376 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 8377 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 8378 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 8379 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 8380 return false; 8381 if (isSigned) { 8382 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 8383 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 8384 return true; 8385 } else { 8386 if (Hi0->isNullValue() && Hi1->isNullValue()) 8387 return true; 8388 } 8389 return false; 8390 } 8391 8392 if (N->getOpcode() != ISD::BUILD_VECTOR) 8393 return false; 8394 8395 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8396 SDNode *Elt = N->getOperand(i).getNode(); 8397 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8398 unsigned EltSize = VT.getScalarSizeInBits(); 8399 unsigned HalfSize = EltSize / 2; 8400 if (isSigned) { 8401 if (!isIntN(HalfSize, C->getSExtValue())) 8402 return false; 8403 } else { 8404 if (!isUIntN(HalfSize, C->getZExtValue())) 8405 return false; 8406 } 8407 continue; 8408 } 8409 return false; 8410 } 8411 8412 return true; 8413 } 8414 8415 /// isSignExtended - Check if a node is a vector value that is sign-extended 8416 /// or a constant BUILD_VECTOR with sign-extended elements. 8417 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8418 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8419 return true; 8420 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8421 return true; 8422 return false; 8423 } 8424 8425 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8426 /// or a constant BUILD_VECTOR with zero-extended elements. 8427 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8428 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8429 return true; 8430 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8431 return true; 8432 return false; 8433 } 8434 8435 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8436 if (OrigVT.getSizeInBits() >= 64) 8437 return OrigVT; 8438 8439 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8440 8441 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8442 switch (OrigSimpleTy) { 8443 default: llvm_unreachable("Unexpected Vector Type"); 8444 case MVT::v2i8: 8445 case MVT::v2i16: 8446 return MVT::v2i32; 8447 case MVT::v4i8: 8448 return MVT::v4i16; 8449 } 8450 } 8451 8452 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8453 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8454 /// We insert the required extension here to get the vector to fill a D register. 8455 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8456 const EVT &OrigTy, 8457 const EVT &ExtTy, 8458 unsigned ExtOpcode) { 8459 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8460 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8461 // 64-bits we need to insert a new extension so that it will be 64-bits. 8462 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8463 if (OrigTy.getSizeInBits() >= 64) 8464 return N; 8465 8466 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8467 EVT NewVT = getExtensionTo64Bits(OrigTy); 8468 8469 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8470 } 8471 8472 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8473 /// does not do any sign/zero extension. If the original vector is less 8474 /// than 64 bits, an appropriate extension will be added after the load to 8475 /// reach a total size of 64 bits. We have to add the extension separately 8476 /// because ARM does not have a sign/zero extending load for vectors. 8477 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8478 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8479 8480 // The load already has the right type. 8481 if (ExtendedTy == LD->getMemoryVT()) 8482 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8483 LD->getBasePtr(), LD->getPointerInfo(), 8484 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8485 8486 // We need to create a zextload/sextload. We cannot just create a load 8487 // followed by a zext/zext node because LowerMUL is also run during normal 8488 // operation legalization where we can't create illegal types. 8489 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8490 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8491 LD->getMemoryVT(), LD->getAlignment(), 8492 LD->getMemOperand()->getFlags()); 8493 } 8494 8495 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8496 /// extending load, or BUILD_VECTOR with extended elements, return the 8497 /// unextended value. The unextended vector should be 64 bits so that it can 8498 /// be used as an operand to a VMULL instruction. If the original vector size 8499 /// before extension is less than 64 bits we add a an extension to resize 8500 /// the vector to 64 bits. 8501 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8502 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8503 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8504 N->getOperand(0)->getValueType(0), 8505 N->getValueType(0), 8506 N->getOpcode()); 8507 8508 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8509 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8510 "Expected extending load"); 8511 8512 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8513 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8514 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8515 SDValue extLoad = 8516 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8517 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8518 8519 return newLoad; 8520 } 8521 8522 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8523 // have been legalized as a BITCAST from v4i32. 8524 if (N->getOpcode() == ISD::BITCAST) { 8525 SDNode *BVN = N->getOperand(0).getNode(); 8526 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8527 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8528 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8529 return DAG.getBuildVector( 8530 MVT::v2i32, SDLoc(N), 8531 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8532 } 8533 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8534 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8535 EVT VT = N->getValueType(0); 8536 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8537 unsigned NumElts = VT.getVectorNumElements(); 8538 MVT TruncVT = MVT::getIntegerVT(EltSize); 8539 SmallVector<SDValue, 8> Ops; 8540 SDLoc dl(N); 8541 for (unsigned i = 0; i != NumElts; ++i) { 8542 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8543 const APInt &CInt = C->getAPIntValue(); 8544 // Element types smaller than 32 bits are not legal, so use i32 elements. 8545 // The values are implicitly truncated so sext vs. zext doesn't matter. 8546 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8547 } 8548 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8549 } 8550 8551 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8552 unsigned Opcode = N->getOpcode(); 8553 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8554 SDNode *N0 = N->getOperand(0).getNode(); 8555 SDNode *N1 = N->getOperand(1).getNode(); 8556 return N0->hasOneUse() && N1->hasOneUse() && 8557 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8558 } 8559 return false; 8560 } 8561 8562 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8563 unsigned Opcode = N->getOpcode(); 8564 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8565 SDNode *N0 = N->getOperand(0).getNode(); 8566 SDNode *N1 = N->getOperand(1).getNode(); 8567 return N0->hasOneUse() && N1->hasOneUse() && 8568 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8569 } 8570 return false; 8571 } 8572 8573 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8574 // Multiplications are only custom-lowered for 128-bit vectors so that 8575 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8576 EVT VT = Op.getValueType(); 8577 assert(VT.is128BitVector() && VT.isInteger() && 8578 "unexpected type for custom-lowering ISD::MUL"); 8579 SDNode *N0 = Op.getOperand(0).getNode(); 8580 SDNode *N1 = Op.getOperand(1).getNode(); 8581 unsigned NewOpc = 0; 8582 bool isMLA = false; 8583 bool isN0SExt = isSignExtended(N0, DAG); 8584 bool isN1SExt = isSignExtended(N1, DAG); 8585 if (isN0SExt && isN1SExt) 8586 NewOpc = ARMISD::VMULLs; 8587 else { 8588 bool isN0ZExt = isZeroExtended(N0, DAG); 8589 bool isN1ZExt = isZeroExtended(N1, DAG); 8590 if (isN0ZExt && isN1ZExt) 8591 NewOpc = ARMISD::VMULLu; 8592 else if (isN1SExt || isN1ZExt) { 8593 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8594 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8595 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8596 NewOpc = ARMISD::VMULLs; 8597 isMLA = true; 8598 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8599 NewOpc = ARMISD::VMULLu; 8600 isMLA = true; 8601 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8602 std::swap(N0, N1); 8603 NewOpc = ARMISD::VMULLu; 8604 isMLA = true; 8605 } 8606 } 8607 8608 if (!NewOpc) { 8609 if (VT == MVT::v2i64) 8610 // Fall through to expand this. It is not legal. 8611 return SDValue(); 8612 else 8613 // Other vector multiplications are legal. 8614 return Op; 8615 } 8616 } 8617 8618 // Legalize to a VMULL instruction. 8619 SDLoc DL(Op); 8620 SDValue Op0; 8621 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8622 if (!isMLA) { 8623 Op0 = SkipExtensionForVMULL(N0, DAG); 8624 assert(Op0.getValueType().is64BitVector() && 8625 Op1.getValueType().is64BitVector() && 8626 "unexpected types for extended operands to VMULL"); 8627 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8628 } 8629 8630 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8631 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8632 // vmull q0, d4, d6 8633 // vmlal q0, d5, d6 8634 // is faster than 8635 // vaddl q0, d4, d5 8636 // vmovl q1, d6 8637 // vmul q0, q0, q1 8638 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8639 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8640 EVT Op1VT = Op1.getValueType(); 8641 return DAG.getNode(N0->getOpcode(), DL, VT, 8642 DAG.getNode(NewOpc, DL, VT, 8643 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8644 DAG.getNode(NewOpc, DL, VT, 8645 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8646 } 8647 8648 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8649 SelectionDAG &DAG) { 8650 // TODO: Should this propagate fast-math-flags? 8651 8652 // Convert to float 8653 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8654 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8655 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8656 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8657 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8658 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8659 // Get reciprocal estimate. 8660 // float4 recip = vrecpeq_f32(yf); 8661 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8662 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8663 Y); 8664 // Because char has a smaller range than uchar, we can actually get away 8665 // without any newton steps. This requires that we use a weird bias 8666 // of 0xb000, however (again, this has been exhaustively tested). 8667 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8668 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8669 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8670 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8671 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8672 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8673 // Convert back to short. 8674 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8675 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8676 return X; 8677 } 8678 8679 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8680 SelectionDAG &DAG) { 8681 // TODO: Should this propagate fast-math-flags? 8682 8683 SDValue N2; 8684 // Convert to float. 8685 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8686 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8687 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8688 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8689 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8690 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8691 8692 // Use reciprocal estimate and one refinement step. 8693 // float4 recip = vrecpeq_f32(yf); 8694 // recip *= vrecpsq_f32(yf, recip); 8695 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8696 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8697 N1); 8698 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8699 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8700 N1, N2); 8701 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8702 // Because short has a smaller range than ushort, we can actually get away 8703 // with only a single newton step. This requires that we use a weird bias 8704 // of 89, however (again, this has been exhaustively tested). 8705 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 8706 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8707 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8708 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 8709 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8710 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8711 // Convert back to integer and return. 8712 // return vmovn_s32(vcvt_s32_f32(result)); 8713 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8714 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8715 return N0; 8716 } 8717 8718 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 8719 const ARMSubtarget *ST) { 8720 EVT VT = Op.getValueType(); 8721 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8722 "unexpected type for custom-lowering ISD::SDIV"); 8723 8724 SDLoc dl(Op); 8725 SDValue N0 = Op.getOperand(0); 8726 SDValue N1 = Op.getOperand(1); 8727 SDValue N2, N3; 8728 8729 if (VT == MVT::v8i8) { 8730 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 8731 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 8732 8733 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8734 DAG.getIntPtrConstant(4, dl)); 8735 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8736 DAG.getIntPtrConstant(4, dl)); 8737 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8738 DAG.getIntPtrConstant(0, dl)); 8739 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8740 DAG.getIntPtrConstant(0, dl)); 8741 8742 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 8743 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 8744 8745 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8746 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8747 8748 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 8749 return N0; 8750 } 8751 return LowerSDIV_v4i16(N0, N1, dl, DAG); 8752 } 8753 8754 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 8755 const ARMSubtarget *ST) { 8756 // TODO: Should this propagate fast-math-flags? 8757 EVT VT = Op.getValueType(); 8758 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8759 "unexpected type for custom-lowering ISD::UDIV"); 8760 8761 SDLoc dl(Op); 8762 SDValue N0 = Op.getOperand(0); 8763 SDValue N1 = Op.getOperand(1); 8764 SDValue N2, N3; 8765 8766 if (VT == MVT::v8i8) { 8767 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 8768 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 8769 8770 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8771 DAG.getIntPtrConstant(4, dl)); 8772 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8773 DAG.getIntPtrConstant(4, dl)); 8774 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8775 DAG.getIntPtrConstant(0, dl)); 8776 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8777 DAG.getIntPtrConstant(0, dl)); 8778 8779 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 8780 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 8781 8782 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8783 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8784 8785 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 8786 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 8787 MVT::i32), 8788 N0); 8789 return N0; 8790 } 8791 8792 // v4i16 sdiv ... Convert to float. 8793 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 8794 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 8795 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 8796 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 8797 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8798 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8799 8800 // Use reciprocal estimate and two refinement steps. 8801 // float4 recip = vrecpeq_f32(yf); 8802 // recip *= vrecpsq_f32(yf, recip); 8803 // recip *= vrecpsq_f32(yf, recip); 8804 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8805 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8806 BN1); 8807 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8808 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8809 BN1, N2); 8810 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8811 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8812 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8813 BN1, N2); 8814 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8815 // Simply multiplying by the reciprocal estimate can leave us a few ulps 8816 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 8817 // and that it will never cause us to return an answer too large). 8818 // float4 result = as_float4(as_int4(xf*recip) + 2); 8819 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8820 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8821 N1 = DAG.getConstant(2, dl, MVT::v4i32); 8822 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8823 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8824 // Convert back to integer and return. 8825 // return vmovn_u32(vcvt_s32_f32(result)); 8826 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8827 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8828 return N0; 8829 } 8830 8831 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 8832 SDNode *N = Op.getNode(); 8833 EVT VT = N->getValueType(0); 8834 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 8835 8836 SDValue Carry = Op.getOperand(2); 8837 8838 SDLoc DL(Op); 8839 8840 SDValue Result; 8841 if (Op.getOpcode() == ISD::ADDCARRY) { 8842 // This converts the boolean value carry into the carry flag. 8843 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8844 8845 // Do the addition proper using the carry flag we wanted. 8846 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 8847 Op.getOperand(1), Carry); 8848 8849 // Now convert the carry flag into a boolean value. 8850 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8851 } else { 8852 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 8853 // have to invert the carry first. 8854 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8855 DAG.getConstant(1, DL, MVT::i32), Carry); 8856 // This converts the boolean value carry into the carry flag. 8857 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8858 8859 // Do the subtraction proper using the carry flag we wanted. 8860 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 8861 Op.getOperand(1), Carry); 8862 8863 // Now convert the carry flag into a boolean value. 8864 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8865 // But the carry returned by ARMISD::SUBE is not a borrow as expected 8866 // by ISD::SUBCARRY, so compute 1 - C. 8867 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8868 DAG.getConstant(1, DL, MVT::i32), Carry); 8869 } 8870 8871 // Return both values. 8872 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 8873 } 8874 8875 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 8876 assert(Subtarget->isTargetDarwin()); 8877 8878 // For iOS, we want to call an alternative entry point: __sincos_stret, 8879 // return values are passed via sret. 8880 SDLoc dl(Op); 8881 SDValue Arg = Op.getOperand(0); 8882 EVT ArgVT = Arg.getValueType(); 8883 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 8884 auto PtrVT = getPointerTy(DAG.getDataLayout()); 8885 8886 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8887 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8888 8889 // Pair of floats / doubles used to pass the result. 8890 Type *RetTy = StructType::get(ArgTy, ArgTy); 8891 auto &DL = DAG.getDataLayout(); 8892 8893 ArgListTy Args; 8894 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 8895 SDValue SRet; 8896 if (ShouldUseSRet) { 8897 // Create stack object for sret. 8898 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 8899 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 8900 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 8901 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 8902 8903 ArgListEntry Entry; 8904 Entry.Node = SRet; 8905 Entry.Ty = RetTy->getPointerTo(); 8906 Entry.IsSExt = false; 8907 Entry.IsZExt = false; 8908 Entry.IsSRet = true; 8909 Args.push_back(Entry); 8910 RetTy = Type::getVoidTy(*DAG.getContext()); 8911 } 8912 8913 ArgListEntry Entry; 8914 Entry.Node = Arg; 8915 Entry.Ty = ArgTy; 8916 Entry.IsSExt = false; 8917 Entry.IsZExt = false; 8918 Args.push_back(Entry); 8919 8920 RTLIB::Libcall LC = 8921 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 8922 const char *LibcallName = getLibcallName(LC); 8923 CallingConv::ID CC = getLibcallCallingConv(LC); 8924 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 8925 8926 TargetLowering::CallLoweringInfo CLI(DAG); 8927 CLI.setDebugLoc(dl) 8928 .setChain(DAG.getEntryNode()) 8929 .setCallee(CC, RetTy, Callee, std::move(Args)) 8930 .setDiscardResult(ShouldUseSRet); 8931 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8932 8933 if (!ShouldUseSRet) 8934 return CallResult.first; 8935 8936 SDValue LoadSin = 8937 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 8938 8939 // Address of cos field. 8940 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 8941 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 8942 SDValue LoadCos = 8943 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 8944 8945 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 8946 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 8947 LoadSin.getValue(0), LoadCos.getValue(0)); 8948 } 8949 8950 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 8951 bool Signed, 8952 SDValue &Chain) const { 8953 EVT VT = Op.getValueType(); 8954 assert((VT == MVT::i32 || VT == MVT::i64) && 8955 "unexpected type for custom lowering DIV"); 8956 SDLoc dl(Op); 8957 8958 const auto &DL = DAG.getDataLayout(); 8959 const auto &TLI = DAG.getTargetLoweringInfo(); 8960 8961 const char *Name = nullptr; 8962 if (Signed) 8963 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 8964 else 8965 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 8966 8967 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 8968 8969 ARMTargetLowering::ArgListTy Args; 8970 8971 for (auto AI : {1, 0}) { 8972 ArgListEntry Arg; 8973 Arg.Node = Op.getOperand(AI); 8974 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 8975 Args.push_back(Arg); 8976 } 8977 8978 CallLoweringInfo CLI(DAG); 8979 CLI.setDebugLoc(dl) 8980 .setChain(Chain) 8981 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 8982 ES, std::move(Args)); 8983 8984 return LowerCallTo(CLI).first; 8985 } 8986 8987 // This is a code size optimisation: return the original SDIV node to 8988 // DAGCombiner when we don't want to expand SDIV into a sequence of 8989 // instructions, and an empty node otherwise which will cause the 8990 // SDIV to be expanded in DAGCombine. 8991 SDValue 8992 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8993 SelectionDAG &DAG, 8994 SmallVectorImpl<SDNode *> &Created) const { 8995 // TODO: Support SREM 8996 if (N->getOpcode() != ISD::SDIV) 8997 return SDValue(); 8998 8999 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 9000 const bool MinSize = ST.hasMinSize(); 9001 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 9002 : ST.hasDivideInARMMode(); 9003 9004 // Don't touch vector types; rewriting this may lead to scalarizing 9005 // the int divs. 9006 if (N->getOperand(0).getValueType().isVector()) 9007 return SDValue(); 9008 9009 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 9010 // hwdiv support for this to be really profitable. 9011 if (!(MinSize && HasDivide)) 9012 return SDValue(); 9013 9014 // ARM mode is a bit simpler than Thumb: we can handle large power 9015 // of 2 immediates with 1 mov instruction; no further checks required, 9016 // just return the sdiv node. 9017 if (!ST.isThumb()) 9018 return SDValue(N, 0); 9019 9020 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 9021 // and thus lose the code size benefits of a MOVS that requires only 2. 9022 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 9023 // but as it's doing exactly this, it's not worth the trouble to get TTI. 9024 if (Divisor.sgt(128)) 9025 return SDValue(); 9026 9027 return SDValue(N, 0); 9028 } 9029 9030 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 9031 bool Signed) const { 9032 assert(Op.getValueType() == MVT::i32 && 9033 "unexpected type for custom lowering DIV"); 9034 SDLoc dl(Op); 9035 9036 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 9037 DAG.getEntryNode(), Op.getOperand(1)); 9038 9039 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9040 } 9041 9042 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 9043 SDLoc DL(N); 9044 SDValue Op = N->getOperand(1); 9045 if (N->getValueType(0) == MVT::i32) 9046 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 9047 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9048 DAG.getConstant(0, DL, MVT::i32)); 9049 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9050 DAG.getConstant(1, DL, MVT::i32)); 9051 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 9052 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 9053 } 9054 9055 void ARMTargetLowering::ExpandDIV_Windows( 9056 SDValue Op, SelectionDAG &DAG, bool Signed, 9057 SmallVectorImpl<SDValue> &Results) const { 9058 const auto &DL = DAG.getDataLayout(); 9059 const auto &TLI = DAG.getTargetLoweringInfo(); 9060 9061 assert(Op.getValueType() == MVT::i64 && 9062 "unexpected type for custom lowering DIV"); 9063 SDLoc dl(Op); 9064 9065 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 9066 9067 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9068 9069 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 9070 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 9071 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 9072 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 9073 9074 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper)); 9075 } 9076 9077 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) { 9078 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode()); 9079 EVT MemVT = LD->getMemoryVT(); 9080 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9081 "Expected a predicate type!"); 9082 assert(MemVT == Op.getValueType()); 9083 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && 9084 "Expected a non-extending load"); 9085 assert(LD->isUnindexed() && "Expected a unindexed load"); 9086 9087 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit 9088 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We 9089 // need to make sure that 8/4 bits are actually loaded into the correct 9090 // place, which means loading the value and then shuffling the values into 9091 // the bottom bits of the predicate. 9092 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect 9093 // for BE). 9094 9095 SDLoc dl(Op); 9096 SDValue Load = DAG.getExtLoad( 9097 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(), 9098 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9099 LD->getMemOperand()); 9100 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load); 9101 if (MemVT != MVT::v16i1) 9102 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred, 9103 DAG.getConstant(0, dl, MVT::i32)); 9104 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl); 9105 } 9106 9107 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) { 9108 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9109 EVT MemVT = ST->getMemoryVT(); 9110 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9111 "Expected a predicate type!"); 9112 assert(MemVT == ST->getValue().getValueType()); 9113 assert(!ST->isTruncatingStore() && "Expected a non-extending store"); 9114 assert(ST->isUnindexed() && "Expected a unindexed store"); 9115 9116 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits 9117 // unset and a scalar store. 9118 SDLoc dl(Op); 9119 SDValue Build = ST->getValue(); 9120 if (MemVT != MVT::v16i1) { 9121 SmallVector<SDValue, 16> Ops; 9122 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) 9123 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build, 9124 DAG.getConstant(I, dl, MVT::i32))); 9125 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++) 9126 Ops.push_back(DAG.getUNDEF(MVT::i32)); 9127 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops); 9128 } 9129 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build); 9130 return DAG.getTruncStore( 9131 ST->getChain(), dl, GRP, ST->getBasePtr(), 9132 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9133 ST->getMemOperand()); 9134 } 9135 9136 static bool isZeroVector(SDValue N) { 9137 return (ISD::isBuildVectorAllZeros(N.getNode()) || 9138 (N->getOpcode() == ARMISD::VMOVIMM && 9139 isNullConstant(N->getOperand(0)))); 9140 } 9141 9142 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) { 9143 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode()); 9144 MVT VT = Op.getSimpleValueType(); 9145 SDValue Mask = N->getMask(); 9146 SDValue PassThru = N->getPassThru(); 9147 SDLoc dl(Op); 9148 9149 if (isZeroVector(PassThru)) 9150 return Op; 9151 9152 // MVE Masked loads use zero as the passthru value. Here we convert undef to 9153 // zero too, and other values are lowered to a select. 9154 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 9155 DAG.getTargetConstant(0, dl, MVT::i32)); 9156 SDValue NewLoad = DAG.getMaskedLoad( 9157 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec, 9158 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(), 9159 N->getExtensionType(), N->isExpandingLoad()); 9160 SDValue Combo = NewLoad; 9161 if (!PassThru.isUndef() && 9162 (PassThru.getOpcode() != ISD::BITCAST || 9163 !isZeroVector(PassThru->getOperand(0)))) 9164 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru); 9165 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl); 9166 } 9167 9168 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 9169 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 9170 // Acquire/Release load/store is not legal for targets without a dmb or 9171 // equivalent available. 9172 return SDValue(); 9173 9174 // Monotonic load/store is legal for all targets. 9175 return Op; 9176 } 9177 9178 static void ReplaceREADCYCLECOUNTER(SDNode *N, 9179 SmallVectorImpl<SDValue> &Results, 9180 SelectionDAG &DAG, 9181 const ARMSubtarget *Subtarget) { 9182 SDLoc DL(N); 9183 // Under Power Management extensions, the cycle-count is: 9184 // mrc p15, #0, <Rt>, c9, c13, #0 9185 SDValue Ops[] = { N->getOperand(0), // Chain 9186 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 9187 DAG.getTargetConstant(15, DL, MVT::i32), 9188 DAG.getTargetConstant(0, DL, MVT::i32), 9189 DAG.getTargetConstant(9, DL, MVT::i32), 9190 DAG.getTargetConstant(13, DL, MVT::i32), 9191 DAG.getTargetConstant(0, DL, MVT::i32) 9192 }; 9193 9194 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 9195 DAG.getVTList(MVT::i32, MVT::Other), Ops); 9196 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 9197 DAG.getConstant(0, DL, MVT::i32))); 9198 Results.push_back(Cycles32.getValue(1)); 9199 } 9200 9201 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 9202 SDLoc dl(V.getNode()); 9203 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 9204 SDValue VHi = DAG.getAnyExtOrTrunc( 9205 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 9206 dl, MVT::i32); 9207 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9208 if (isBigEndian) 9209 std::swap (VLo, VHi); 9210 SDValue RegClass = 9211 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 9212 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 9213 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 9214 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 9215 return SDValue( 9216 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 9217 } 9218 9219 static void ReplaceCMP_SWAP_64Results(SDNode *N, 9220 SmallVectorImpl<SDValue> & Results, 9221 SelectionDAG &DAG) { 9222 assert(N->getValueType(0) == MVT::i64 && 9223 "AtomicCmpSwap on types less than 64 should be legal"); 9224 SDValue Ops[] = {N->getOperand(1), 9225 createGPRPairNode(DAG, N->getOperand(2)), 9226 createGPRPairNode(DAG, N->getOperand(3)), 9227 N->getOperand(0)}; 9228 SDNode *CmpSwap = DAG.getMachineNode( 9229 ARM::CMP_SWAP_64, SDLoc(N), 9230 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 9231 9232 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 9233 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 9234 9235 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9236 9237 SDValue Lo = 9238 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 9239 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9240 SDValue Hi = 9241 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 9242 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9243 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi)); 9244 Results.push_back(SDValue(CmpSwap, 2)); 9245 } 9246 9247 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const { 9248 SDLoc dl(Op); 9249 EVT VT = Op.getValueType(); 9250 SDValue Chain = Op.getOperand(0); 9251 SDValue LHS = Op.getOperand(1); 9252 SDValue RHS = Op.getOperand(2); 9253 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get(); 9254 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 9255 9256 // If we don't have instructions of this float type then soften to a libcall 9257 // and use SETCC instead. 9258 if (isUnsupportedFloatingType(LHS.getValueType())) { 9259 DAG.getTargetLoweringInfo().softenSetCCOperands( 9260 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling); 9261 if (!RHS.getNode()) { 9262 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 9263 CC = ISD::SETNE; 9264 } 9265 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS, 9266 DAG.getCondCode(CC)); 9267 return DAG.getMergeValues({Result, Chain}, dl); 9268 } 9269 9270 ARMCC::CondCodes CondCode, CondCode2; 9271 FPCCToARMCC(CC, CondCode, CondCode2); 9272 9273 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit 9274 // in CMPFP and CMPFPE, but instead it should be made explicit by these 9275 // instructions using a chain instead of glue. This would also fix the problem 9276 // here (and also in LowerSELECT_CC) where we generate two comparisons when 9277 // CondCode2 != AL. 9278 SDValue True = DAG.getConstant(1, dl, VT); 9279 SDValue False = DAG.getConstant(0, dl, VT); 9280 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 9281 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 9282 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9283 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG); 9284 if (CondCode2 != ARMCC::AL) { 9285 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 9286 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9287 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG); 9288 } 9289 return DAG.getMergeValues({Result, Chain}, dl); 9290 } 9291 9292 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9293 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 9294 switch (Op.getOpcode()) { 9295 default: llvm_unreachable("Don't know how to custom lower this!"); 9296 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 9297 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9298 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9299 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9300 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9301 case ISD::SELECT: return LowerSELECT(Op, DAG); 9302 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9303 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9304 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 9305 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 9306 case ISD::VASTART: return LowerVASTART(Op, DAG); 9307 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 9308 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 9309 case ISD::SINT_TO_FP: 9310 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9311 case ISD::STRICT_FP_TO_SINT: 9312 case ISD::STRICT_FP_TO_UINT: 9313 case ISD::FP_TO_SINT: 9314 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 9315 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9316 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9317 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9318 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 9319 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 9320 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 9321 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget); 9322 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 9323 Subtarget); 9324 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 9325 case ISD::SHL: 9326 case ISD::SRL: 9327 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 9328 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 9329 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 9330 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 9331 case ISD::SRL_PARTS: 9332 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 9333 case ISD::CTTZ: 9334 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 9335 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 9336 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 9337 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 9338 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 9339 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 9340 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 9341 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 9342 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9343 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 9344 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 9345 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9346 case ISD::MUL: return LowerMUL(Op, DAG); 9347 case ISD::SDIV: 9348 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9349 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 9350 return LowerSDIV(Op, DAG, Subtarget); 9351 case ISD::UDIV: 9352 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9353 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 9354 return LowerUDIV(Op, DAG, Subtarget); 9355 case ISD::ADDCARRY: 9356 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 9357 case ISD::SADDO: 9358 case ISD::SSUBO: 9359 return LowerSignedALUO(Op, DAG); 9360 case ISD::UADDO: 9361 case ISD::USUBO: 9362 return LowerUnsignedALUO(Op, DAG); 9363 case ISD::SADDSAT: 9364 case ISD::SSUBSAT: 9365 return LowerSADDSUBSAT(Op, DAG, Subtarget); 9366 case ISD::LOAD: 9367 return LowerPredicateLoad(Op, DAG); 9368 case ISD::STORE: 9369 return LowerPredicateStore(Op, DAG); 9370 case ISD::MLOAD: 9371 return LowerMLOAD(Op, DAG); 9372 case ISD::ATOMIC_LOAD: 9373 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 9374 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 9375 case ISD::SDIVREM: 9376 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 9377 case ISD::DYNAMIC_STACKALLOC: 9378 if (Subtarget->isTargetWindows()) 9379 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9380 llvm_unreachable("Don't know how to custom lower this!"); 9381 case ISD::STRICT_FP_ROUND: 9382 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 9383 case ISD::STRICT_FP_EXTEND: 9384 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9385 case ISD::STRICT_FSETCC: 9386 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG); 9387 case ARMISD::WIN__DBZCHK: return SDValue(); 9388 } 9389 } 9390 9391 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 9392 SelectionDAG &DAG) { 9393 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9394 unsigned Opc = 0; 9395 if (IntNo == Intrinsic::arm_smlald) 9396 Opc = ARMISD::SMLALD; 9397 else if (IntNo == Intrinsic::arm_smlaldx) 9398 Opc = ARMISD::SMLALDX; 9399 else if (IntNo == Intrinsic::arm_smlsld) 9400 Opc = ARMISD::SMLSLD; 9401 else if (IntNo == Intrinsic::arm_smlsldx) 9402 Opc = ARMISD::SMLSLDX; 9403 else 9404 return; 9405 9406 SDLoc dl(N); 9407 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9408 N->getOperand(3), 9409 DAG.getConstant(0, dl, MVT::i32)); 9410 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9411 N->getOperand(3), 9412 DAG.getConstant(1, dl, MVT::i32)); 9413 9414 SDValue LongMul = DAG.getNode(Opc, dl, 9415 DAG.getVTList(MVT::i32, MVT::i32), 9416 N->getOperand(1), N->getOperand(2), 9417 Lo, Hi); 9418 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, 9419 LongMul.getValue(0), LongMul.getValue(1))); 9420 } 9421 9422 /// ReplaceNodeResults - Replace the results of node with an illegal result 9423 /// type with new values built out of custom code. 9424 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 9425 SmallVectorImpl<SDValue> &Results, 9426 SelectionDAG &DAG) const { 9427 SDValue Res; 9428 switch (N->getOpcode()) { 9429 default: 9430 llvm_unreachable("Don't know how to custom expand this!"); 9431 case ISD::READ_REGISTER: 9432 ExpandREAD_REGISTER(N, Results, DAG); 9433 break; 9434 case ISD::BITCAST: 9435 Res = ExpandBITCAST(N, DAG, Subtarget); 9436 break; 9437 case ISD::SRL: 9438 case ISD::SRA: 9439 case ISD::SHL: 9440 Res = Expand64BitShift(N, DAG, Subtarget); 9441 break; 9442 case ISD::SREM: 9443 case ISD::UREM: 9444 Res = LowerREM(N, DAG); 9445 break; 9446 case ISD::SDIVREM: 9447 case ISD::UDIVREM: 9448 Res = LowerDivRem(SDValue(N, 0), DAG); 9449 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 9450 Results.push_back(Res.getValue(0)); 9451 Results.push_back(Res.getValue(1)); 9452 return; 9453 case ISD::SADDSAT: 9454 case ISD::SSUBSAT: 9455 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget); 9456 break; 9457 case ISD::READCYCLECOUNTER: 9458 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 9459 return; 9460 case ISD::UDIV: 9461 case ISD::SDIV: 9462 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 9463 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 9464 Results); 9465 case ISD::ATOMIC_CMP_SWAP: 9466 ReplaceCMP_SWAP_64Results(N, Results, DAG); 9467 return; 9468 case ISD::INTRINSIC_WO_CHAIN: 9469 return ReplaceLongIntrinsic(N, Results, DAG); 9470 case ISD::ABS: 9471 lowerABS(N, Results, DAG); 9472 return ; 9473 9474 } 9475 if (Res.getNode()) 9476 Results.push_back(Res); 9477 } 9478 9479 //===----------------------------------------------------------------------===// 9480 // ARM Scheduler Hooks 9481 //===----------------------------------------------------------------------===// 9482 9483 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 9484 /// registers the function context. 9485 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 9486 MachineBasicBlock *MBB, 9487 MachineBasicBlock *DispatchBB, 9488 int FI) const { 9489 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 9490 "ROPI/RWPI not currently supported with SjLj"); 9491 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9492 DebugLoc dl = MI.getDebugLoc(); 9493 MachineFunction *MF = MBB->getParent(); 9494 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9495 MachineConstantPool *MCP = MF->getConstantPool(); 9496 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 9497 const Function &F = MF->getFunction(); 9498 9499 bool isThumb = Subtarget->isThumb(); 9500 bool isThumb2 = Subtarget->isThumb2(); 9501 9502 unsigned PCLabelId = AFI->createPICLabelUId(); 9503 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 9504 ARMConstantPoolValue *CPV = 9505 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 9506 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 9507 9508 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 9509 : &ARM::GPRRegClass; 9510 9511 // Grab constant pool and fixed stack memory operands. 9512 MachineMemOperand *CPMMO = 9513 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9514 MachineMemOperand::MOLoad, 4, 4); 9515 9516 MachineMemOperand *FIMMOSt = 9517 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 9518 MachineMemOperand::MOStore, 4, 4); 9519 9520 // Load the address of the dispatch MBB into the jump buffer. 9521 if (isThumb2) { 9522 // Incoming value: jbuf 9523 // ldr.n r5, LCPI1_1 9524 // orr r5, r5, #1 9525 // add r5, pc 9526 // str r5, [$jbuf, #+4] ; &jbuf[1] 9527 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9528 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9529 .addConstantPoolIndex(CPI) 9530 .addMemOperand(CPMMO) 9531 .add(predOps(ARMCC::AL)); 9532 // Set the low bit because of thumb mode. 9533 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9534 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9535 .addReg(NewVReg1, RegState::Kill) 9536 .addImm(0x01) 9537 .add(predOps(ARMCC::AL)) 9538 .add(condCodeOp()); 9539 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9540 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9541 .addReg(NewVReg2, RegState::Kill) 9542 .addImm(PCLabelId); 9543 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9544 .addReg(NewVReg3, RegState::Kill) 9545 .addFrameIndex(FI) 9546 .addImm(36) // &jbuf[1] :: pc 9547 .addMemOperand(FIMMOSt) 9548 .add(predOps(ARMCC::AL)); 9549 } else if (isThumb) { 9550 // Incoming value: jbuf 9551 // ldr.n r1, LCPI1_4 9552 // add r1, pc 9553 // mov r2, #1 9554 // orrs r1, r2 9555 // add r2, $jbuf, #+4 ; &jbuf[1] 9556 // str r1, [r2] 9557 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9558 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 9559 .addConstantPoolIndex(CPI) 9560 .addMemOperand(CPMMO) 9561 .add(predOps(ARMCC::AL)); 9562 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9563 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 9564 .addReg(NewVReg1, RegState::Kill) 9565 .addImm(PCLabelId); 9566 // Set the low bit because of thumb mode. 9567 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9568 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 9569 .addReg(ARM::CPSR, RegState::Define) 9570 .addImm(1) 9571 .add(predOps(ARMCC::AL)); 9572 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9573 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 9574 .addReg(ARM::CPSR, RegState::Define) 9575 .addReg(NewVReg2, RegState::Kill) 9576 .addReg(NewVReg3, RegState::Kill) 9577 .add(predOps(ARMCC::AL)); 9578 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9579 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 9580 .addFrameIndex(FI) 9581 .addImm(36); // &jbuf[1] :: pc 9582 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 9583 .addReg(NewVReg4, RegState::Kill) 9584 .addReg(NewVReg5, RegState::Kill) 9585 .addImm(0) 9586 .addMemOperand(FIMMOSt) 9587 .add(predOps(ARMCC::AL)); 9588 } else { 9589 // Incoming value: jbuf 9590 // ldr r1, LCPI1_1 9591 // add r1, pc, r1 9592 // str r1, [$jbuf, #+4] ; &jbuf[1] 9593 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9594 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 9595 .addConstantPoolIndex(CPI) 9596 .addImm(0) 9597 .addMemOperand(CPMMO) 9598 .add(predOps(ARMCC::AL)); 9599 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9600 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 9601 .addReg(NewVReg1, RegState::Kill) 9602 .addImm(PCLabelId) 9603 .add(predOps(ARMCC::AL)); 9604 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 9605 .addReg(NewVReg2, RegState::Kill) 9606 .addFrameIndex(FI) 9607 .addImm(36) // &jbuf[1] :: pc 9608 .addMemOperand(FIMMOSt) 9609 .add(predOps(ARMCC::AL)); 9610 } 9611 } 9612 9613 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 9614 MachineBasicBlock *MBB) const { 9615 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9616 DebugLoc dl = MI.getDebugLoc(); 9617 MachineFunction *MF = MBB->getParent(); 9618 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9619 MachineFrameInfo &MFI = MF->getFrameInfo(); 9620 int FI = MFI.getFunctionContextIndex(); 9621 9622 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 9623 : &ARM::GPRnopcRegClass; 9624 9625 // Get a mapping of the call site numbers to all of the landing pads they're 9626 // associated with. 9627 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 9628 unsigned MaxCSNum = 0; 9629 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 9630 ++BB) { 9631 if (!BB->isEHPad()) continue; 9632 9633 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 9634 // pad. 9635 for (MachineBasicBlock::iterator 9636 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 9637 if (!II->isEHLabel()) continue; 9638 9639 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 9640 if (!MF->hasCallSiteLandingPad(Sym)) continue; 9641 9642 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 9643 for (SmallVectorImpl<unsigned>::iterator 9644 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 9645 CSI != CSE; ++CSI) { 9646 CallSiteNumToLPad[*CSI].push_back(&*BB); 9647 MaxCSNum = std::max(MaxCSNum, *CSI); 9648 } 9649 break; 9650 } 9651 } 9652 9653 // Get an ordered list of the machine basic blocks for the jump table. 9654 std::vector<MachineBasicBlock*> LPadList; 9655 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 9656 LPadList.reserve(CallSiteNumToLPad.size()); 9657 for (unsigned I = 1; I <= MaxCSNum; ++I) { 9658 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 9659 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9660 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 9661 LPadList.push_back(*II); 9662 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 9663 } 9664 } 9665 9666 assert(!LPadList.empty() && 9667 "No landing pad destinations for the dispatch jump table!"); 9668 9669 // Create the jump table and associated information. 9670 MachineJumpTableInfo *JTI = 9671 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 9672 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 9673 9674 // Create the MBBs for the dispatch code. 9675 9676 // Shove the dispatch's address into the return slot in the function context. 9677 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 9678 DispatchBB->setIsEHPad(); 9679 9680 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9681 unsigned trap_opcode; 9682 if (Subtarget->isThumb()) 9683 trap_opcode = ARM::tTRAP; 9684 else 9685 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 9686 9687 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 9688 DispatchBB->addSuccessor(TrapBB); 9689 9690 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 9691 DispatchBB->addSuccessor(DispContBB); 9692 9693 // Insert and MBBs. 9694 MF->insert(MF->end(), DispatchBB); 9695 MF->insert(MF->end(), DispContBB); 9696 MF->insert(MF->end(), TrapBB); 9697 9698 // Insert code into the entry block that creates and registers the function 9699 // context. 9700 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 9701 9702 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 9703 MachinePointerInfo::getFixedStack(*MF, FI), 9704 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 9705 9706 MachineInstrBuilder MIB; 9707 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 9708 9709 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 9710 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 9711 9712 // Add a register mask with no preserved registers. This results in all 9713 // registers being marked as clobbered. This can't work if the dispatch block 9714 // is in a Thumb1 function and is linked with ARM code which uses the FP 9715 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 9716 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 9717 9718 bool IsPositionIndependent = isPositionIndependent(); 9719 unsigned NumLPads = LPadList.size(); 9720 if (Subtarget->isThumb2()) { 9721 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9722 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 9723 .addFrameIndex(FI) 9724 .addImm(4) 9725 .addMemOperand(FIMMOLd) 9726 .add(predOps(ARMCC::AL)); 9727 9728 if (NumLPads < 256) { 9729 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 9730 .addReg(NewVReg1) 9731 .addImm(LPadList.size()) 9732 .add(predOps(ARMCC::AL)); 9733 } else { 9734 Register VReg1 = MRI->createVirtualRegister(TRC); 9735 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 9736 .addImm(NumLPads & 0xFFFF) 9737 .add(predOps(ARMCC::AL)); 9738 9739 unsigned VReg2 = VReg1; 9740 if ((NumLPads & 0xFFFF0000) != 0) { 9741 VReg2 = MRI->createVirtualRegister(TRC); 9742 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 9743 .addReg(VReg1) 9744 .addImm(NumLPads >> 16) 9745 .add(predOps(ARMCC::AL)); 9746 } 9747 9748 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 9749 .addReg(NewVReg1) 9750 .addReg(VReg2) 9751 .add(predOps(ARMCC::AL)); 9752 } 9753 9754 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 9755 .addMBB(TrapBB) 9756 .addImm(ARMCC::HI) 9757 .addReg(ARM::CPSR); 9758 9759 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9760 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 9761 .addJumpTableIndex(MJTI) 9762 .add(predOps(ARMCC::AL)); 9763 9764 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9765 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 9766 .addReg(NewVReg3, RegState::Kill) 9767 .addReg(NewVReg1) 9768 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9769 .add(predOps(ARMCC::AL)) 9770 .add(condCodeOp()); 9771 9772 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 9773 .addReg(NewVReg4, RegState::Kill) 9774 .addReg(NewVReg1) 9775 .addJumpTableIndex(MJTI); 9776 } else if (Subtarget->isThumb()) { 9777 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9778 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 9779 .addFrameIndex(FI) 9780 .addImm(1) 9781 .addMemOperand(FIMMOLd) 9782 .add(predOps(ARMCC::AL)); 9783 9784 if (NumLPads < 256) { 9785 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 9786 .addReg(NewVReg1) 9787 .addImm(NumLPads) 9788 .add(predOps(ARMCC::AL)); 9789 } else { 9790 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9791 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9792 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9793 9794 // MachineConstantPool wants an explicit alignment. 9795 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9796 if (Align == 0) 9797 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9798 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9799 9800 Register VReg1 = MRI->createVirtualRegister(TRC); 9801 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 9802 .addReg(VReg1, RegState::Define) 9803 .addConstantPoolIndex(Idx) 9804 .add(predOps(ARMCC::AL)); 9805 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 9806 .addReg(NewVReg1) 9807 .addReg(VReg1) 9808 .add(predOps(ARMCC::AL)); 9809 } 9810 9811 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 9812 .addMBB(TrapBB) 9813 .addImm(ARMCC::HI) 9814 .addReg(ARM::CPSR); 9815 9816 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9817 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 9818 .addReg(ARM::CPSR, RegState::Define) 9819 .addReg(NewVReg1) 9820 .addImm(2) 9821 .add(predOps(ARMCC::AL)); 9822 9823 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9824 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 9825 .addJumpTableIndex(MJTI) 9826 .add(predOps(ARMCC::AL)); 9827 9828 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9829 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 9830 .addReg(ARM::CPSR, RegState::Define) 9831 .addReg(NewVReg2, RegState::Kill) 9832 .addReg(NewVReg3) 9833 .add(predOps(ARMCC::AL)); 9834 9835 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9836 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9837 9838 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9839 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 9840 .addReg(NewVReg4, RegState::Kill) 9841 .addImm(0) 9842 .addMemOperand(JTMMOLd) 9843 .add(predOps(ARMCC::AL)); 9844 9845 unsigned NewVReg6 = NewVReg5; 9846 if (IsPositionIndependent) { 9847 NewVReg6 = MRI->createVirtualRegister(TRC); 9848 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 9849 .addReg(ARM::CPSR, RegState::Define) 9850 .addReg(NewVReg5, RegState::Kill) 9851 .addReg(NewVReg3) 9852 .add(predOps(ARMCC::AL)); 9853 } 9854 9855 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 9856 .addReg(NewVReg6, RegState::Kill) 9857 .addJumpTableIndex(MJTI); 9858 } else { 9859 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9860 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 9861 .addFrameIndex(FI) 9862 .addImm(4) 9863 .addMemOperand(FIMMOLd) 9864 .add(predOps(ARMCC::AL)); 9865 9866 if (NumLPads < 256) { 9867 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 9868 .addReg(NewVReg1) 9869 .addImm(NumLPads) 9870 .add(predOps(ARMCC::AL)); 9871 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 9872 Register VReg1 = MRI->createVirtualRegister(TRC); 9873 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 9874 .addImm(NumLPads & 0xFFFF) 9875 .add(predOps(ARMCC::AL)); 9876 9877 unsigned VReg2 = VReg1; 9878 if ((NumLPads & 0xFFFF0000) != 0) { 9879 VReg2 = MRI->createVirtualRegister(TRC); 9880 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 9881 .addReg(VReg1) 9882 .addImm(NumLPads >> 16) 9883 .add(predOps(ARMCC::AL)); 9884 } 9885 9886 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9887 .addReg(NewVReg1) 9888 .addReg(VReg2) 9889 .add(predOps(ARMCC::AL)); 9890 } else { 9891 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9892 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9893 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9894 9895 // MachineConstantPool wants an explicit alignment. 9896 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9897 if (Align == 0) 9898 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9899 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9900 9901 Register VReg1 = MRI->createVirtualRegister(TRC); 9902 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 9903 .addReg(VReg1, RegState::Define) 9904 .addConstantPoolIndex(Idx) 9905 .addImm(0) 9906 .add(predOps(ARMCC::AL)); 9907 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9908 .addReg(NewVReg1) 9909 .addReg(VReg1, RegState::Kill) 9910 .add(predOps(ARMCC::AL)); 9911 } 9912 9913 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 9914 .addMBB(TrapBB) 9915 .addImm(ARMCC::HI) 9916 .addReg(ARM::CPSR); 9917 9918 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9919 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 9920 .addReg(NewVReg1) 9921 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9922 .add(predOps(ARMCC::AL)) 9923 .add(condCodeOp()); 9924 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9925 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 9926 .addJumpTableIndex(MJTI) 9927 .add(predOps(ARMCC::AL)); 9928 9929 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9930 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9931 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9932 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 9933 .addReg(NewVReg3, RegState::Kill) 9934 .addReg(NewVReg4) 9935 .addImm(0) 9936 .addMemOperand(JTMMOLd) 9937 .add(predOps(ARMCC::AL)); 9938 9939 if (IsPositionIndependent) { 9940 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 9941 .addReg(NewVReg5, RegState::Kill) 9942 .addReg(NewVReg4) 9943 .addJumpTableIndex(MJTI); 9944 } else { 9945 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 9946 .addReg(NewVReg5, RegState::Kill) 9947 .addJumpTableIndex(MJTI); 9948 } 9949 } 9950 9951 // Add the jump table entries as successors to the MBB. 9952 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 9953 for (std::vector<MachineBasicBlock*>::iterator 9954 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 9955 MachineBasicBlock *CurMBB = *I; 9956 if (SeenMBBs.insert(CurMBB).second) 9957 DispContBB->addSuccessor(CurMBB); 9958 } 9959 9960 // N.B. the order the invoke BBs are processed in doesn't matter here. 9961 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 9962 SmallVector<MachineBasicBlock*, 64> MBBLPads; 9963 for (MachineBasicBlock *BB : InvokeBBs) { 9964 9965 // Remove the landing pad successor from the invoke block and replace it 9966 // with the new dispatch block. 9967 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 9968 BB->succ_end()); 9969 while (!Successors.empty()) { 9970 MachineBasicBlock *SMBB = Successors.pop_back_val(); 9971 if (SMBB->isEHPad()) { 9972 BB->removeSuccessor(SMBB); 9973 MBBLPads.push_back(SMBB); 9974 } 9975 } 9976 9977 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 9978 BB->normalizeSuccProbs(); 9979 9980 // Find the invoke call and mark all of the callee-saved registers as 9981 // 'implicit defined' so that they're spilled. This prevents code from 9982 // moving instructions to before the EH block, where they will never be 9983 // executed. 9984 for (MachineBasicBlock::reverse_iterator 9985 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 9986 if (!II->isCall()) continue; 9987 9988 DenseMap<unsigned, bool> DefRegs; 9989 for (MachineInstr::mop_iterator 9990 OI = II->operands_begin(), OE = II->operands_end(); 9991 OI != OE; ++OI) { 9992 if (!OI->isReg()) continue; 9993 DefRegs[OI->getReg()] = true; 9994 } 9995 9996 MachineInstrBuilder MIB(*MF, &*II); 9997 9998 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 9999 unsigned Reg = SavedRegs[i]; 10000 if (Subtarget->isThumb2() && 10001 !ARM::tGPRRegClass.contains(Reg) && 10002 !ARM::hGPRRegClass.contains(Reg)) 10003 continue; 10004 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 10005 continue; 10006 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 10007 continue; 10008 if (!DefRegs[Reg]) 10009 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 10010 } 10011 10012 break; 10013 } 10014 } 10015 10016 // Mark all former landing pads as non-landing pads. The dispatch is the only 10017 // landing pad now. 10018 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10019 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 10020 (*I)->setIsEHPad(false); 10021 10022 // The instruction is gone now. 10023 MI.eraseFromParent(); 10024 } 10025 10026 static 10027 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 10028 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 10029 E = MBB->succ_end(); I != E; ++I) 10030 if (*I != Succ) 10031 return *I; 10032 llvm_unreachable("Expecting a BB with two successors!"); 10033 } 10034 10035 /// Return the load opcode for a given load size. If load size >= 8, 10036 /// neon opcode will be returned. 10037 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 10038 if (LdSize >= 8) 10039 return LdSize == 16 ? ARM::VLD1q32wb_fixed 10040 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 10041 if (IsThumb1) 10042 return LdSize == 4 ? ARM::tLDRi 10043 : LdSize == 2 ? ARM::tLDRHi 10044 : LdSize == 1 ? ARM::tLDRBi : 0; 10045 if (IsThumb2) 10046 return LdSize == 4 ? ARM::t2LDR_POST 10047 : LdSize == 2 ? ARM::t2LDRH_POST 10048 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 10049 return LdSize == 4 ? ARM::LDR_POST_IMM 10050 : LdSize == 2 ? ARM::LDRH_POST 10051 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 10052 } 10053 10054 /// Return the store opcode for a given store size. If store size >= 8, 10055 /// neon opcode will be returned. 10056 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 10057 if (StSize >= 8) 10058 return StSize == 16 ? ARM::VST1q32wb_fixed 10059 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 10060 if (IsThumb1) 10061 return StSize == 4 ? ARM::tSTRi 10062 : StSize == 2 ? ARM::tSTRHi 10063 : StSize == 1 ? ARM::tSTRBi : 0; 10064 if (IsThumb2) 10065 return StSize == 4 ? ARM::t2STR_POST 10066 : StSize == 2 ? ARM::t2STRH_POST 10067 : StSize == 1 ? ARM::t2STRB_POST : 0; 10068 return StSize == 4 ? ARM::STR_POST_IMM 10069 : StSize == 2 ? ARM::STRH_POST 10070 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 10071 } 10072 10073 /// Emit a post-increment load operation with given size. The instructions 10074 /// will be added to BB at Pos. 10075 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10076 const TargetInstrInfo *TII, const DebugLoc &dl, 10077 unsigned LdSize, unsigned Data, unsigned AddrIn, 10078 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10079 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 10080 assert(LdOpc != 0 && "Should have a load opcode"); 10081 if (LdSize >= 8) { 10082 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10083 .addReg(AddrOut, RegState::Define) 10084 .addReg(AddrIn) 10085 .addImm(0) 10086 .add(predOps(ARMCC::AL)); 10087 } else if (IsThumb1) { 10088 // load + update AddrIn 10089 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10090 .addReg(AddrIn) 10091 .addImm(0) 10092 .add(predOps(ARMCC::AL)); 10093 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10094 .add(t1CondCodeOp()) 10095 .addReg(AddrIn) 10096 .addImm(LdSize) 10097 .add(predOps(ARMCC::AL)); 10098 } else if (IsThumb2) { 10099 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10100 .addReg(AddrOut, RegState::Define) 10101 .addReg(AddrIn) 10102 .addImm(LdSize) 10103 .add(predOps(ARMCC::AL)); 10104 } else { // arm 10105 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10106 .addReg(AddrOut, RegState::Define) 10107 .addReg(AddrIn) 10108 .addReg(0) 10109 .addImm(LdSize) 10110 .add(predOps(ARMCC::AL)); 10111 } 10112 } 10113 10114 /// Emit a post-increment store operation with given size. The instructions 10115 /// will be added to BB at Pos. 10116 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10117 const TargetInstrInfo *TII, const DebugLoc &dl, 10118 unsigned StSize, unsigned Data, unsigned AddrIn, 10119 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10120 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 10121 assert(StOpc != 0 && "Should have a store opcode"); 10122 if (StSize >= 8) { 10123 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10124 .addReg(AddrIn) 10125 .addImm(0) 10126 .addReg(Data) 10127 .add(predOps(ARMCC::AL)); 10128 } else if (IsThumb1) { 10129 // store + update AddrIn 10130 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 10131 .addReg(Data) 10132 .addReg(AddrIn) 10133 .addImm(0) 10134 .add(predOps(ARMCC::AL)); 10135 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10136 .add(t1CondCodeOp()) 10137 .addReg(AddrIn) 10138 .addImm(StSize) 10139 .add(predOps(ARMCC::AL)); 10140 } else if (IsThumb2) { 10141 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10142 .addReg(Data) 10143 .addReg(AddrIn) 10144 .addImm(StSize) 10145 .add(predOps(ARMCC::AL)); 10146 } else { // arm 10147 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10148 .addReg(Data) 10149 .addReg(AddrIn) 10150 .addReg(0) 10151 .addImm(StSize) 10152 .add(predOps(ARMCC::AL)); 10153 } 10154 } 10155 10156 MachineBasicBlock * 10157 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 10158 MachineBasicBlock *BB) const { 10159 // This pseudo instruction has 3 operands: dst, src, size 10160 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 10161 // Otherwise, we will generate unrolled scalar copies. 10162 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10163 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10164 MachineFunction::iterator It = ++BB->getIterator(); 10165 10166 Register dest = MI.getOperand(0).getReg(); 10167 Register src = MI.getOperand(1).getReg(); 10168 unsigned SizeVal = MI.getOperand(2).getImm(); 10169 unsigned Align = MI.getOperand(3).getImm(); 10170 DebugLoc dl = MI.getDebugLoc(); 10171 10172 MachineFunction *MF = BB->getParent(); 10173 MachineRegisterInfo &MRI = MF->getRegInfo(); 10174 unsigned UnitSize = 0; 10175 const TargetRegisterClass *TRC = nullptr; 10176 const TargetRegisterClass *VecTRC = nullptr; 10177 10178 bool IsThumb1 = Subtarget->isThumb1Only(); 10179 bool IsThumb2 = Subtarget->isThumb2(); 10180 bool IsThumb = Subtarget->isThumb(); 10181 10182 if (Align & 1) { 10183 UnitSize = 1; 10184 } else if (Align & 2) { 10185 UnitSize = 2; 10186 } else { 10187 // Check whether we can use NEON instructions. 10188 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 10189 Subtarget->hasNEON()) { 10190 if ((Align % 16 == 0) && SizeVal >= 16) 10191 UnitSize = 16; 10192 else if ((Align % 8 == 0) && SizeVal >= 8) 10193 UnitSize = 8; 10194 } 10195 // Can't use NEON instructions. 10196 if (UnitSize == 0) 10197 UnitSize = 4; 10198 } 10199 10200 // Select the correct opcode and register class for unit size load/store 10201 bool IsNeon = UnitSize >= 8; 10202 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 10203 if (IsNeon) 10204 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 10205 : UnitSize == 8 ? &ARM::DPRRegClass 10206 : nullptr; 10207 10208 unsigned BytesLeft = SizeVal % UnitSize; 10209 unsigned LoopSize = SizeVal - BytesLeft; 10210 10211 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 10212 // Use LDR and STR to copy. 10213 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 10214 // [destOut] = STR_POST(scratch, destIn, UnitSize) 10215 unsigned srcIn = src; 10216 unsigned destIn = dest; 10217 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 10218 Register srcOut = MRI.createVirtualRegister(TRC); 10219 Register destOut = MRI.createVirtualRegister(TRC); 10220 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10221 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 10222 IsThumb1, IsThumb2); 10223 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 10224 IsThumb1, IsThumb2); 10225 srcIn = srcOut; 10226 destIn = destOut; 10227 } 10228 10229 // Handle the leftover bytes with LDRB and STRB. 10230 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 10231 // [destOut] = STRB_POST(scratch, destIn, 1) 10232 for (unsigned i = 0; i < BytesLeft; i++) { 10233 Register srcOut = MRI.createVirtualRegister(TRC); 10234 Register destOut = MRI.createVirtualRegister(TRC); 10235 Register scratch = MRI.createVirtualRegister(TRC); 10236 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 10237 IsThumb1, IsThumb2); 10238 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 10239 IsThumb1, IsThumb2); 10240 srcIn = srcOut; 10241 destIn = destOut; 10242 } 10243 MI.eraseFromParent(); // The instruction is gone now. 10244 return BB; 10245 } 10246 10247 // Expand the pseudo op to a loop. 10248 // thisMBB: 10249 // ... 10250 // movw varEnd, # --> with thumb2 10251 // movt varEnd, # 10252 // ldrcp varEnd, idx --> without thumb2 10253 // fallthrough --> loopMBB 10254 // loopMBB: 10255 // PHI varPhi, varEnd, varLoop 10256 // PHI srcPhi, src, srcLoop 10257 // PHI destPhi, dst, destLoop 10258 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10259 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 10260 // subs varLoop, varPhi, #UnitSize 10261 // bne loopMBB 10262 // fallthrough --> exitMBB 10263 // exitMBB: 10264 // epilogue to handle left-over bytes 10265 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10266 // [destOut] = STRB_POST(scratch, destLoop, 1) 10267 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10268 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10269 MF->insert(It, loopMBB); 10270 MF->insert(It, exitMBB); 10271 10272 // Transfer the remainder of BB and its successor edges to exitMBB. 10273 exitMBB->splice(exitMBB->begin(), BB, 10274 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10275 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10276 10277 // Load an immediate to varEnd. 10278 Register varEnd = MRI.createVirtualRegister(TRC); 10279 if (Subtarget->useMovt()) { 10280 unsigned Vtmp = varEnd; 10281 if ((LoopSize & 0xFFFF0000) != 0) 10282 Vtmp = MRI.createVirtualRegister(TRC); 10283 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 10284 .addImm(LoopSize & 0xFFFF) 10285 .add(predOps(ARMCC::AL)); 10286 10287 if ((LoopSize & 0xFFFF0000) != 0) 10288 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 10289 .addReg(Vtmp) 10290 .addImm(LoopSize >> 16) 10291 .add(predOps(ARMCC::AL)); 10292 } else { 10293 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10294 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10295 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 10296 10297 // MachineConstantPool wants an explicit alignment. 10298 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 10299 if (Align == 0) 10300 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 10301 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 10302 MachineMemOperand *CPMMO = 10303 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 10304 MachineMemOperand::MOLoad, 4, 4); 10305 10306 if (IsThumb) 10307 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 10308 .addReg(varEnd, RegState::Define) 10309 .addConstantPoolIndex(Idx) 10310 .add(predOps(ARMCC::AL)) 10311 .addMemOperand(CPMMO); 10312 else 10313 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 10314 .addReg(varEnd, RegState::Define) 10315 .addConstantPoolIndex(Idx) 10316 .addImm(0) 10317 .add(predOps(ARMCC::AL)) 10318 .addMemOperand(CPMMO); 10319 } 10320 BB->addSuccessor(loopMBB); 10321 10322 // Generate the loop body: 10323 // varPhi = PHI(varLoop, varEnd) 10324 // srcPhi = PHI(srcLoop, src) 10325 // destPhi = PHI(destLoop, dst) 10326 MachineBasicBlock *entryBB = BB; 10327 BB = loopMBB; 10328 Register varLoop = MRI.createVirtualRegister(TRC); 10329 Register varPhi = MRI.createVirtualRegister(TRC); 10330 Register srcLoop = MRI.createVirtualRegister(TRC); 10331 Register srcPhi = MRI.createVirtualRegister(TRC); 10332 Register destLoop = MRI.createVirtualRegister(TRC); 10333 Register destPhi = MRI.createVirtualRegister(TRC); 10334 10335 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 10336 .addReg(varLoop).addMBB(loopMBB) 10337 .addReg(varEnd).addMBB(entryBB); 10338 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 10339 .addReg(srcLoop).addMBB(loopMBB) 10340 .addReg(src).addMBB(entryBB); 10341 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 10342 .addReg(destLoop).addMBB(loopMBB) 10343 .addReg(dest).addMBB(entryBB); 10344 10345 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10346 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 10347 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10348 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 10349 IsThumb1, IsThumb2); 10350 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 10351 IsThumb1, IsThumb2); 10352 10353 // Decrement loop variable by UnitSize. 10354 if (IsThumb1) { 10355 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 10356 .add(t1CondCodeOp()) 10357 .addReg(varPhi) 10358 .addImm(UnitSize) 10359 .add(predOps(ARMCC::AL)); 10360 } else { 10361 MachineInstrBuilder MIB = 10362 BuildMI(*BB, BB->end(), dl, 10363 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 10364 MIB.addReg(varPhi) 10365 .addImm(UnitSize) 10366 .add(predOps(ARMCC::AL)) 10367 .add(condCodeOp()); 10368 MIB->getOperand(5).setReg(ARM::CPSR); 10369 MIB->getOperand(5).setIsDef(true); 10370 } 10371 BuildMI(*BB, BB->end(), dl, 10372 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10373 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 10374 10375 // loopMBB can loop back to loopMBB or fall through to exitMBB. 10376 BB->addSuccessor(loopMBB); 10377 BB->addSuccessor(exitMBB); 10378 10379 // Add epilogue to handle BytesLeft. 10380 BB = exitMBB; 10381 auto StartOfExit = exitMBB->begin(); 10382 10383 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10384 // [destOut] = STRB_POST(scratch, destLoop, 1) 10385 unsigned srcIn = srcLoop; 10386 unsigned destIn = destLoop; 10387 for (unsigned i = 0; i < BytesLeft; i++) { 10388 Register srcOut = MRI.createVirtualRegister(TRC); 10389 Register destOut = MRI.createVirtualRegister(TRC); 10390 Register scratch = MRI.createVirtualRegister(TRC); 10391 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 10392 IsThumb1, IsThumb2); 10393 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 10394 IsThumb1, IsThumb2); 10395 srcIn = srcOut; 10396 destIn = destOut; 10397 } 10398 10399 MI.eraseFromParent(); // The instruction is gone now. 10400 return BB; 10401 } 10402 10403 MachineBasicBlock * 10404 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 10405 MachineBasicBlock *MBB) const { 10406 const TargetMachine &TM = getTargetMachine(); 10407 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 10408 DebugLoc DL = MI.getDebugLoc(); 10409 10410 assert(Subtarget->isTargetWindows() && 10411 "__chkstk is only supported on Windows"); 10412 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 10413 10414 // __chkstk takes the number of words to allocate on the stack in R4, and 10415 // returns the stack adjustment in number of bytes in R4. This will not 10416 // clober any other registers (other than the obvious lr). 10417 // 10418 // Although, technically, IP should be considered a register which may be 10419 // clobbered, the call itself will not touch it. Windows on ARM is a pure 10420 // thumb-2 environment, so there is no interworking required. As a result, we 10421 // do not expect a veneer to be emitted by the linker, clobbering IP. 10422 // 10423 // Each module receives its own copy of __chkstk, so no import thunk is 10424 // required, again, ensuring that IP is not clobbered. 10425 // 10426 // Finally, although some linkers may theoretically provide a trampoline for 10427 // out of range calls (which is quite common due to a 32M range limitation of 10428 // branches for Thumb), we can generate the long-call version via 10429 // -mcmodel=large, alleviating the need for the trampoline which may clobber 10430 // IP. 10431 10432 switch (TM.getCodeModel()) { 10433 case CodeModel::Tiny: 10434 llvm_unreachable("Tiny code model not available on ARM."); 10435 case CodeModel::Small: 10436 case CodeModel::Medium: 10437 case CodeModel::Kernel: 10438 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 10439 .add(predOps(ARMCC::AL)) 10440 .addExternalSymbol("__chkstk") 10441 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10442 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10443 .addReg(ARM::R12, 10444 RegState::Implicit | RegState::Define | RegState::Dead) 10445 .addReg(ARM::CPSR, 10446 RegState::Implicit | RegState::Define | RegState::Dead); 10447 break; 10448 case CodeModel::Large: { 10449 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10450 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 10451 10452 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 10453 .addExternalSymbol("__chkstk"); 10454 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 10455 .add(predOps(ARMCC::AL)) 10456 .addReg(Reg, RegState::Kill) 10457 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10458 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10459 .addReg(ARM::R12, 10460 RegState::Implicit | RegState::Define | RegState::Dead) 10461 .addReg(ARM::CPSR, 10462 RegState::Implicit | RegState::Define | RegState::Dead); 10463 break; 10464 } 10465 } 10466 10467 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 10468 .addReg(ARM::SP, RegState::Kill) 10469 .addReg(ARM::R4, RegState::Kill) 10470 .setMIFlags(MachineInstr::FrameSetup) 10471 .add(predOps(ARMCC::AL)) 10472 .add(condCodeOp()); 10473 10474 MI.eraseFromParent(); 10475 return MBB; 10476 } 10477 10478 MachineBasicBlock * 10479 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 10480 MachineBasicBlock *MBB) const { 10481 DebugLoc DL = MI.getDebugLoc(); 10482 MachineFunction *MF = MBB->getParent(); 10483 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10484 10485 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 10486 MF->insert(++MBB->getIterator(), ContBB); 10487 ContBB->splice(ContBB->begin(), MBB, 10488 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10489 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 10490 MBB->addSuccessor(ContBB); 10491 10492 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10493 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 10494 MF->push_back(TrapBB); 10495 MBB->addSuccessor(TrapBB); 10496 10497 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 10498 .addReg(MI.getOperand(0).getReg()) 10499 .addImm(0) 10500 .add(predOps(ARMCC::AL)); 10501 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 10502 .addMBB(TrapBB) 10503 .addImm(ARMCC::EQ) 10504 .addReg(ARM::CPSR); 10505 10506 MI.eraseFromParent(); 10507 return ContBB; 10508 } 10509 10510 // The CPSR operand of SelectItr might be missing a kill marker 10511 // because there were multiple uses of CPSR, and ISel didn't know 10512 // which to mark. Figure out whether SelectItr should have had a 10513 // kill marker, and set it if it should. Returns the correct kill 10514 // marker value. 10515 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 10516 MachineBasicBlock* BB, 10517 const TargetRegisterInfo* TRI) { 10518 // Scan forward through BB for a use/def of CPSR. 10519 MachineBasicBlock::iterator miI(std::next(SelectItr)); 10520 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 10521 const MachineInstr& mi = *miI; 10522 if (mi.readsRegister(ARM::CPSR)) 10523 return false; 10524 if (mi.definesRegister(ARM::CPSR)) 10525 break; // Should have kill-flag - update below. 10526 } 10527 10528 // If we hit the end of the block, check whether CPSR is live into a 10529 // successor. 10530 if (miI == BB->end()) { 10531 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10532 sEnd = BB->succ_end(); 10533 sItr != sEnd; ++sItr) { 10534 MachineBasicBlock* succ = *sItr; 10535 if (succ->isLiveIn(ARM::CPSR)) 10536 return false; 10537 } 10538 } 10539 10540 // We found a def, or hit the end of the basic block and CPSR wasn't live 10541 // out. SelectMI should have a kill flag on CPSR. 10542 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10543 return true; 10544 } 10545 10546 MachineBasicBlock * 10547 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10548 MachineBasicBlock *BB) const { 10549 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10550 DebugLoc dl = MI.getDebugLoc(); 10551 bool isThumb2 = Subtarget->isThumb2(); 10552 switch (MI.getOpcode()) { 10553 default: { 10554 MI.print(errs()); 10555 llvm_unreachable("Unexpected instr type to insert"); 10556 } 10557 10558 // Thumb1 post-indexed loads are really just single-register LDMs. 10559 case ARM::tLDR_postidx: { 10560 MachineOperand Def(MI.getOperand(1)); 10561 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 10562 .add(Def) // Rn_wb 10563 .add(MI.getOperand(2)) // Rn 10564 .add(MI.getOperand(3)) // PredImm 10565 .add(MI.getOperand(4)) // PredReg 10566 .add(MI.getOperand(0)) // Rt 10567 .cloneMemRefs(MI); 10568 MI.eraseFromParent(); 10569 return BB; 10570 } 10571 10572 // The Thumb2 pre-indexed stores have the same MI operands, they just 10573 // define them differently in the .td files from the isel patterns, so 10574 // they need pseudos. 10575 case ARM::t2STR_preidx: 10576 MI.setDesc(TII->get(ARM::t2STR_PRE)); 10577 return BB; 10578 case ARM::t2STRB_preidx: 10579 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 10580 return BB; 10581 case ARM::t2STRH_preidx: 10582 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 10583 return BB; 10584 10585 case ARM::STRi_preidx: 10586 case ARM::STRBi_preidx: { 10587 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 10588 : ARM::STRB_PRE_IMM; 10589 // Decode the offset. 10590 unsigned Offset = MI.getOperand(4).getImm(); 10591 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 10592 Offset = ARM_AM::getAM2Offset(Offset); 10593 if (isSub) 10594 Offset = -Offset; 10595 10596 MachineMemOperand *MMO = *MI.memoperands_begin(); 10597 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 10598 .add(MI.getOperand(0)) // Rn_wb 10599 .add(MI.getOperand(1)) // Rt 10600 .add(MI.getOperand(2)) // Rn 10601 .addImm(Offset) // offset (skip GPR==zero_reg) 10602 .add(MI.getOperand(5)) // pred 10603 .add(MI.getOperand(6)) 10604 .addMemOperand(MMO); 10605 MI.eraseFromParent(); 10606 return BB; 10607 } 10608 case ARM::STRr_preidx: 10609 case ARM::STRBr_preidx: 10610 case ARM::STRH_preidx: { 10611 unsigned NewOpc; 10612 switch (MI.getOpcode()) { 10613 default: llvm_unreachable("unexpected opcode!"); 10614 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 10615 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 10616 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 10617 } 10618 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 10619 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 10620 MIB.add(MI.getOperand(i)); 10621 MI.eraseFromParent(); 10622 return BB; 10623 } 10624 10625 case ARM::tMOVCCr_pseudo: { 10626 // To "insert" a SELECT_CC instruction, we actually have to insert the 10627 // diamond control-flow pattern. The incoming instruction knows the 10628 // destination vreg to set, the condition code register to branch on, the 10629 // true/false values to select between, and a branch opcode to use. 10630 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10631 MachineFunction::iterator It = ++BB->getIterator(); 10632 10633 // thisMBB: 10634 // ... 10635 // TrueVal = ... 10636 // cmpTY ccX, r1, r2 10637 // bCC copy1MBB 10638 // fallthrough --> copy0MBB 10639 MachineBasicBlock *thisMBB = BB; 10640 MachineFunction *F = BB->getParent(); 10641 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10642 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10643 F->insert(It, copy0MBB); 10644 F->insert(It, sinkMBB); 10645 10646 // Check whether CPSR is live past the tMOVCCr_pseudo. 10647 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10648 if (!MI.killsRegister(ARM::CPSR) && 10649 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 10650 copy0MBB->addLiveIn(ARM::CPSR); 10651 sinkMBB->addLiveIn(ARM::CPSR); 10652 } 10653 10654 // Transfer the remainder of BB and its successor edges to sinkMBB. 10655 sinkMBB->splice(sinkMBB->begin(), BB, 10656 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10657 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10658 10659 BB->addSuccessor(copy0MBB); 10660 BB->addSuccessor(sinkMBB); 10661 10662 BuildMI(BB, dl, TII->get(ARM::tBcc)) 10663 .addMBB(sinkMBB) 10664 .addImm(MI.getOperand(3).getImm()) 10665 .addReg(MI.getOperand(4).getReg()); 10666 10667 // copy0MBB: 10668 // %FalseValue = ... 10669 // # fallthrough to sinkMBB 10670 BB = copy0MBB; 10671 10672 // Update machine-CFG edges 10673 BB->addSuccessor(sinkMBB); 10674 10675 // sinkMBB: 10676 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10677 // ... 10678 BB = sinkMBB; 10679 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 10680 .addReg(MI.getOperand(1).getReg()) 10681 .addMBB(copy0MBB) 10682 .addReg(MI.getOperand(2).getReg()) 10683 .addMBB(thisMBB); 10684 10685 MI.eraseFromParent(); // The pseudo instruction is gone now. 10686 return BB; 10687 } 10688 10689 case ARM::BCCi64: 10690 case ARM::BCCZi64: { 10691 // If there is an unconditional branch to the other successor, remove it. 10692 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10693 10694 // Compare both parts that make up the double comparison separately for 10695 // equality. 10696 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 10697 10698 Register LHS1 = MI.getOperand(1).getReg(); 10699 Register LHS2 = MI.getOperand(2).getReg(); 10700 if (RHSisZero) { 10701 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10702 .addReg(LHS1) 10703 .addImm(0) 10704 .add(predOps(ARMCC::AL)); 10705 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10706 .addReg(LHS2).addImm(0) 10707 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10708 } else { 10709 Register RHS1 = MI.getOperand(3).getReg(); 10710 Register RHS2 = MI.getOperand(4).getReg(); 10711 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10712 .addReg(LHS1) 10713 .addReg(RHS1) 10714 .add(predOps(ARMCC::AL)); 10715 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10716 .addReg(LHS2).addReg(RHS2) 10717 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10718 } 10719 10720 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 10721 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 10722 if (MI.getOperand(0).getImm() == ARMCC::NE) 10723 std::swap(destMBB, exitMBB); 10724 10725 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10726 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 10727 if (isThumb2) 10728 BuildMI(BB, dl, TII->get(ARM::t2B)) 10729 .addMBB(exitMBB) 10730 .add(predOps(ARMCC::AL)); 10731 else 10732 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 10733 10734 MI.eraseFromParent(); // The pseudo instruction is gone now. 10735 return BB; 10736 } 10737 10738 case ARM::Int_eh_sjlj_setjmp: 10739 case ARM::Int_eh_sjlj_setjmp_nofp: 10740 case ARM::tInt_eh_sjlj_setjmp: 10741 case ARM::t2Int_eh_sjlj_setjmp: 10742 case ARM::t2Int_eh_sjlj_setjmp_nofp: 10743 return BB; 10744 10745 case ARM::Int_eh_sjlj_setup_dispatch: 10746 EmitSjLjDispatchBlock(MI, BB); 10747 return BB; 10748 10749 case ARM::ABS: 10750 case ARM::t2ABS: { 10751 // To insert an ABS instruction, we have to insert the 10752 // diamond control-flow pattern. The incoming instruction knows the 10753 // source vreg to test against 0, the destination vreg to set, 10754 // the condition code register to branch on, the 10755 // true/false values to select between, and a branch opcode to use. 10756 // It transforms 10757 // V1 = ABS V0 10758 // into 10759 // V2 = MOVS V0 10760 // BCC (branch to SinkBB if V0 >= 0) 10761 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 10762 // SinkBB: V1 = PHI(V2, V3) 10763 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10764 MachineFunction::iterator BBI = ++BB->getIterator(); 10765 MachineFunction *Fn = BB->getParent(); 10766 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10767 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10768 Fn->insert(BBI, RSBBB); 10769 Fn->insert(BBI, SinkBB); 10770 10771 Register ABSSrcReg = MI.getOperand(1).getReg(); 10772 Register ABSDstReg = MI.getOperand(0).getReg(); 10773 bool ABSSrcKIll = MI.getOperand(1).isKill(); 10774 bool isThumb2 = Subtarget->isThumb2(); 10775 MachineRegisterInfo &MRI = Fn->getRegInfo(); 10776 // In Thumb mode S must not be specified if source register is the SP or 10777 // PC and if destination register is the SP, so restrict register class 10778 Register NewRsbDstReg = MRI.createVirtualRegister( 10779 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 10780 10781 // Transfer the remainder of BB and its successor edges to sinkMBB. 10782 SinkBB->splice(SinkBB->begin(), BB, 10783 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10784 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 10785 10786 BB->addSuccessor(RSBBB); 10787 BB->addSuccessor(SinkBB); 10788 10789 // fall through to SinkMBB 10790 RSBBB->addSuccessor(SinkBB); 10791 10792 // insert a cmp at the end of BB 10793 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10794 .addReg(ABSSrcReg) 10795 .addImm(0) 10796 .add(predOps(ARMCC::AL)); 10797 10798 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 10799 BuildMI(BB, dl, 10800 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 10801 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 10802 10803 // insert rsbri in RSBBB 10804 // Note: BCC and rsbri will be converted into predicated rsbmi 10805 // by if-conversion pass 10806 BuildMI(*RSBBB, RSBBB->begin(), dl, 10807 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 10808 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 10809 .addImm(0) 10810 .add(predOps(ARMCC::AL)) 10811 .add(condCodeOp()); 10812 10813 // insert PHI in SinkBB, 10814 // reuse ABSDstReg to not change uses of ABS instruction 10815 BuildMI(*SinkBB, SinkBB->begin(), dl, 10816 TII->get(ARM::PHI), ABSDstReg) 10817 .addReg(NewRsbDstReg).addMBB(RSBBB) 10818 .addReg(ABSSrcReg).addMBB(BB); 10819 10820 // remove ABS instruction 10821 MI.eraseFromParent(); 10822 10823 // return last added BB 10824 return SinkBB; 10825 } 10826 case ARM::COPY_STRUCT_BYVAL_I32: 10827 ++NumLoopByVals; 10828 return EmitStructByval(MI, BB); 10829 case ARM::WIN__CHKSTK: 10830 return EmitLowered__chkstk(MI, BB); 10831 case ARM::WIN__DBZCHK: 10832 return EmitLowered__dbzchk(MI, BB); 10833 } 10834 } 10835 10836 /// Attaches vregs to MEMCPY that it will use as scratch registers 10837 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 10838 /// instead of as a custom inserter because we need the use list from the SDNode. 10839 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 10840 MachineInstr &MI, const SDNode *Node) { 10841 bool isThumb1 = Subtarget->isThumb1Only(); 10842 10843 DebugLoc DL = MI.getDebugLoc(); 10844 MachineFunction *MF = MI.getParent()->getParent(); 10845 MachineRegisterInfo &MRI = MF->getRegInfo(); 10846 MachineInstrBuilder MIB(*MF, MI); 10847 10848 // If the new dst/src is unused mark it as dead. 10849 if (!Node->hasAnyUseOfValue(0)) { 10850 MI.getOperand(0).setIsDead(true); 10851 } 10852 if (!Node->hasAnyUseOfValue(1)) { 10853 MI.getOperand(1).setIsDead(true); 10854 } 10855 10856 // The MEMCPY both defines and kills the scratch registers. 10857 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 10858 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 10859 : &ARM::GPRRegClass); 10860 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 10861 } 10862 } 10863 10864 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10865 SDNode *Node) const { 10866 if (MI.getOpcode() == ARM::MEMCPY) { 10867 attachMEMCPYScratchRegs(Subtarget, MI, Node); 10868 return; 10869 } 10870 10871 const MCInstrDesc *MCID = &MI.getDesc(); 10872 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 10873 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 10874 // operand is still set to noreg. If needed, set the optional operand's 10875 // register to CPSR, and remove the redundant implicit def. 10876 // 10877 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 10878 10879 // Rename pseudo opcodes. 10880 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 10881 unsigned ccOutIdx; 10882 if (NewOpc) { 10883 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 10884 MCID = &TII->get(NewOpc); 10885 10886 assert(MCID->getNumOperands() == 10887 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 10888 && "converted opcode should be the same except for cc_out" 10889 " (and, on Thumb1, pred)"); 10890 10891 MI.setDesc(*MCID); 10892 10893 // Add the optional cc_out operand 10894 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 10895 10896 // On Thumb1, move all input operands to the end, then add the predicate 10897 if (Subtarget->isThumb1Only()) { 10898 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 10899 MI.addOperand(MI.getOperand(1)); 10900 MI.RemoveOperand(1); 10901 } 10902 10903 // Restore the ties 10904 for (unsigned i = MI.getNumOperands(); i--;) { 10905 const MachineOperand& op = MI.getOperand(i); 10906 if (op.isReg() && op.isUse()) { 10907 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 10908 if (DefIdx != -1) 10909 MI.tieOperands(DefIdx, i); 10910 } 10911 } 10912 10913 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 10914 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 10915 ccOutIdx = 1; 10916 } else 10917 ccOutIdx = MCID->getNumOperands() - 1; 10918 } else 10919 ccOutIdx = MCID->getNumOperands() - 1; 10920 10921 // Any ARM instruction that sets the 's' bit should specify an optional 10922 // "cc_out" operand in the last operand position. 10923 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 10924 assert(!NewOpc && "Optional cc_out operand required"); 10925 return; 10926 } 10927 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 10928 // since we already have an optional CPSR def. 10929 bool definesCPSR = false; 10930 bool deadCPSR = false; 10931 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 10932 ++i) { 10933 const MachineOperand &MO = MI.getOperand(i); 10934 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 10935 definesCPSR = true; 10936 if (MO.isDead()) 10937 deadCPSR = true; 10938 MI.RemoveOperand(i); 10939 break; 10940 } 10941 } 10942 if (!definesCPSR) { 10943 assert(!NewOpc && "Optional cc_out operand required"); 10944 return; 10945 } 10946 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 10947 if (deadCPSR) { 10948 assert(!MI.getOperand(ccOutIdx).getReg() && 10949 "expect uninitialized optional cc_out operand"); 10950 // Thumb1 instructions must have the S bit even if the CPSR is dead. 10951 if (!Subtarget->isThumb1Only()) 10952 return; 10953 } 10954 10955 // If this instruction was defined with an optional CPSR def and its dag node 10956 // had a live implicit CPSR def, then activate the optional CPSR def. 10957 MachineOperand &MO = MI.getOperand(ccOutIdx); 10958 MO.setReg(ARM::CPSR); 10959 MO.setIsDef(true); 10960 } 10961 10962 //===----------------------------------------------------------------------===// 10963 // ARM Optimization Hooks 10964 //===----------------------------------------------------------------------===// 10965 10966 // Helper function that checks if N is a null or all ones constant. 10967 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 10968 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 10969 } 10970 10971 // Return true if N is conditionally 0 or all ones. 10972 // Detects these expressions where cc is an i1 value: 10973 // 10974 // (select cc 0, y) [AllOnes=0] 10975 // (select cc y, 0) [AllOnes=0] 10976 // (zext cc) [AllOnes=0] 10977 // (sext cc) [AllOnes=0/1] 10978 // (select cc -1, y) [AllOnes=1] 10979 // (select cc y, -1) [AllOnes=1] 10980 // 10981 // Invert is set when N is the null/all ones constant when CC is false. 10982 // OtherOp is set to the alternative value of N. 10983 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 10984 SDValue &CC, bool &Invert, 10985 SDValue &OtherOp, 10986 SelectionDAG &DAG) { 10987 switch (N->getOpcode()) { 10988 default: return false; 10989 case ISD::SELECT: { 10990 CC = N->getOperand(0); 10991 SDValue N1 = N->getOperand(1); 10992 SDValue N2 = N->getOperand(2); 10993 if (isZeroOrAllOnes(N1, AllOnes)) { 10994 Invert = false; 10995 OtherOp = N2; 10996 return true; 10997 } 10998 if (isZeroOrAllOnes(N2, AllOnes)) { 10999 Invert = true; 11000 OtherOp = N1; 11001 return true; 11002 } 11003 return false; 11004 } 11005 case ISD::ZERO_EXTEND: 11006 // (zext cc) can never be the all ones value. 11007 if (AllOnes) 11008 return false; 11009 LLVM_FALLTHROUGH; 11010 case ISD::SIGN_EXTEND: { 11011 SDLoc dl(N); 11012 EVT VT = N->getValueType(0); 11013 CC = N->getOperand(0); 11014 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 11015 return false; 11016 Invert = !AllOnes; 11017 if (AllOnes) 11018 // When looking for an AllOnes constant, N is an sext, and the 'other' 11019 // value is 0. 11020 OtherOp = DAG.getConstant(0, dl, VT); 11021 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11022 // When looking for a 0 constant, N can be zext or sext. 11023 OtherOp = DAG.getConstant(1, dl, VT); 11024 else 11025 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 11026 VT); 11027 return true; 11028 } 11029 } 11030 } 11031 11032 // Combine a constant select operand into its use: 11033 // 11034 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11035 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11036 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 11037 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11038 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11039 // 11040 // The transform is rejected if the select doesn't have a constant operand that 11041 // is null, or all ones when AllOnes is set. 11042 // 11043 // Also recognize sext/zext from i1: 11044 // 11045 // (add (zext cc), x) -> (select cc (add x, 1), x) 11046 // (add (sext cc), x) -> (select cc (add x, -1), x) 11047 // 11048 // These transformations eventually create predicated instructions. 11049 // 11050 // @param N The node to transform. 11051 // @param Slct The N operand that is a select. 11052 // @param OtherOp The other N operand (x above). 11053 // @param DCI Context. 11054 // @param AllOnes Require the select constant to be all ones instead of null. 11055 // @returns The new node, or SDValue() on failure. 11056 static 11057 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 11058 TargetLowering::DAGCombinerInfo &DCI, 11059 bool AllOnes = false) { 11060 SelectionDAG &DAG = DCI.DAG; 11061 EVT VT = N->getValueType(0); 11062 SDValue NonConstantVal; 11063 SDValue CCOp; 11064 bool SwapSelectOps; 11065 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 11066 NonConstantVal, DAG)) 11067 return SDValue(); 11068 11069 // Slct is now know to be the desired identity constant when CC is true. 11070 SDValue TrueVal = OtherOp; 11071 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 11072 OtherOp, NonConstantVal); 11073 // Unless SwapSelectOps says CC should be false. 11074 if (SwapSelectOps) 11075 std::swap(TrueVal, FalseVal); 11076 11077 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 11078 CCOp, TrueVal, FalseVal); 11079 } 11080 11081 // Attempt combineSelectAndUse on each operand of a commutative operator N. 11082 static 11083 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 11084 TargetLowering::DAGCombinerInfo &DCI) { 11085 SDValue N0 = N->getOperand(0); 11086 SDValue N1 = N->getOperand(1); 11087 if (N0.getNode()->hasOneUse()) 11088 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 11089 return Result; 11090 if (N1.getNode()->hasOneUse()) 11091 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 11092 return Result; 11093 return SDValue(); 11094 } 11095 11096 static bool IsVUZPShuffleNode(SDNode *N) { 11097 // VUZP shuffle node. 11098 if (N->getOpcode() == ARMISD::VUZP) 11099 return true; 11100 11101 // "VUZP" on i32 is an alias for VTRN. 11102 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 11103 return true; 11104 11105 return false; 11106 } 11107 11108 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 11109 TargetLowering::DAGCombinerInfo &DCI, 11110 const ARMSubtarget *Subtarget) { 11111 // Look for ADD(VUZP.0, VUZP.1). 11112 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 11113 N0 == N1) 11114 return SDValue(); 11115 11116 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 11117 if (!N->getValueType(0).is64BitVector()) 11118 return SDValue(); 11119 11120 // Generate vpadd. 11121 SelectionDAG &DAG = DCI.DAG; 11122 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11123 SDLoc dl(N); 11124 SDNode *Unzip = N0.getNode(); 11125 EVT VT = N->getValueType(0); 11126 11127 SmallVector<SDValue, 8> Ops; 11128 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 11129 TLI.getPointerTy(DAG.getDataLayout()))); 11130 Ops.push_back(Unzip->getOperand(0)); 11131 Ops.push_back(Unzip->getOperand(1)); 11132 11133 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11134 } 11135 11136 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11137 TargetLowering::DAGCombinerInfo &DCI, 11138 const ARMSubtarget *Subtarget) { 11139 // Check for two extended operands. 11140 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 11141 N1.getOpcode() == ISD::SIGN_EXTEND) && 11142 !(N0.getOpcode() == ISD::ZERO_EXTEND && 11143 N1.getOpcode() == ISD::ZERO_EXTEND)) 11144 return SDValue(); 11145 11146 SDValue N00 = N0.getOperand(0); 11147 SDValue N10 = N1.getOperand(0); 11148 11149 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 11150 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 11151 N00 == N10) 11152 return SDValue(); 11153 11154 // We only recognize Q register paddl here; this can't be reached until 11155 // after type legalization. 11156 if (!N00.getValueType().is64BitVector() || 11157 !N0.getValueType().is128BitVector()) 11158 return SDValue(); 11159 11160 // Generate vpaddl. 11161 SelectionDAG &DAG = DCI.DAG; 11162 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11163 SDLoc dl(N); 11164 EVT VT = N->getValueType(0); 11165 11166 SmallVector<SDValue, 8> Ops; 11167 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 11168 unsigned Opcode; 11169 if (N0.getOpcode() == ISD::SIGN_EXTEND) 11170 Opcode = Intrinsic::arm_neon_vpaddls; 11171 else 11172 Opcode = Intrinsic::arm_neon_vpaddlu; 11173 Ops.push_back(DAG.getConstant(Opcode, dl, 11174 TLI.getPointerTy(DAG.getDataLayout()))); 11175 EVT ElemTy = N00.getValueType().getVectorElementType(); 11176 unsigned NumElts = VT.getVectorNumElements(); 11177 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 11178 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 11179 N00.getOperand(0), N00.getOperand(1)); 11180 Ops.push_back(Concat); 11181 11182 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11183 } 11184 11185 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 11186 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 11187 // much easier to match. 11188 static SDValue 11189 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11190 TargetLowering::DAGCombinerInfo &DCI, 11191 const ARMSubtarget *Subtarget) { 11192 // Only perform optimization if after legalize, and if NEON is available. We 11193 // also expected both operands to be BUILD_VECTORs. 11194 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 11195 || N0.getOpcode() != ISD::BUILD_VECTOR 11196 || N1.getOpcode() != ISD::BUILD_VECTOR) 11197 return SDValue(); 11198 11199 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 11200 EVT VT = N->getValueType(0); 11201 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 11202 return SDValue(); 11203 11204 // Check that the vector operands are of the right form. 11205 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 11206 // operands, where N is the size of the formed vector. 11207 // Each EXTRACT_VECTOR should have the same input vector and odd or even 11208 // index such that we have a pair wise add pattern. 11209 11210 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 11211 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11212 return SDValue(); 11213 SDValue Vec = N0->getOperand(0)->getOperand(0); 11214 SDNode *V = Vec.getNode(); 11215 unsigned nextIndex = 0; 11216 11217 // For each operands to the ADD which are BUILD_VECTORs, 11218 // check to see if each of their operands are an EXTRACT_VECTOR with 11219 // the same vector and appropriate index. 11220 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 11221 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 11222 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11223 11224 SDValue ExtVec0 = N0->getOperand(i); 11225 SDValue ExtVec1 = N1->getOperand(i); 11226 11227 // First operand is the vector, verify its the same. 11228 if (V != ExtVec0->getOperand(0).getNode() || 11229 V != ExtVec1->getOperand(0).getNode()) 11230 return SDValue(); 11231 11232 // Second is the constant, verify its correct. 11233 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 11234 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 11235 11236 // For the constant, we want to see all the even or all the odd. 11237 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 11238 || C1->getZExtValue() != nextIndex+1) 11239 return SDValue(); 11240 11241 // Increment index. 11242 nextIndex+=2; 11243 } else 11244 return SDValue(); 11245 } 11246 11247 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 11248 // we're using the entire input vector, otherwise there's a size/legality 11249 // mismatch somewhere. 11250 if (nextIndex != Vec.getValueType().getVectorNumElements() || 11251 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 11252 return SDValue(); 11253 11254 // Create VPADDL node. 11255 SelectionDAG &DAG = DCI.DAG; 11256 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11257 11258 SDLoc dl(N); 11259 11260 // Build operand list. 11261 SmallVector<SDValue, 8> Ops; 11262 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 11263 TLI.getPointerTy(DAG.getDataLayout()))); 11264 11265 // Input is the vector. 11266 Ops.push_back(Vec); 11267 11268 // Get widened type and narrowed type. 11269 MVT widenType; 11270 unsigned numElem = VT.getVectorNumElements(); 11271 11272 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 11273 switch (inputLaneType.getSimpleVT().SimpleTy) { 11274 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 11275 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 11276 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 11277 default: 11278 llvm_unreachable("Invalid vector element type for padd optimization."); 11279 } 11280 11281 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 11282 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 11283 return DAG.getNode(ExtOp, dl, VT, tmp); 11284 } 11285 11286 static SDValue findMUL_LOHI(SDValue V) { 11287 if (V->getOpcode() == ISD::UMUL_LOHI || 11288 V->getOpcode() == ISD::SMUL_LOHI) 11289 return V; 11290 return SDValue(); 11291 } 11292 11293 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 11294 TargetLowering::DAGCombinerInfo &DCI, 11295 const ARMSubtarget *Subtarget) { 11296 if (!Subtarget->hasBaseDSP()) 11297 return SDValue(); 11298 11299 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 11300 // accumulates the product into a 64-bit value. The 16-bit values will 11301 // be sign extended somehow or SRA'd into 32-bit values 11302 // (addc (adde (mul 16bit, 16bit), lo), hi) 11303 SDValue Mul = AddcNode->getOperand(0); 11304 SDValue Lo = AddcNode->getOperand(1); 11305 if (Mul.getOpcode() != ISD::MUL) { 11306 Lo = AddcNode->getOperand(0); 11307 Mul = AddcNode->getOperand(1); 11308 if (Mul.getOpcode() != ISD::MUL) 11309 return SDValue(); 11310 } 11311 11312 SDValue SRA = AddeNode->getOperand(0); 11313 SDValue Hi = AddeNode->getOperand(1); 11314 if (SRA.getOpcode() != ISD::SRA) { 11315 SRA = AddeNode->getOperand(1); 11316 Hi = AddeNode->getOperand(0); 11317 if (SRA.getOpcode() != ISD::SRA) 11318 return SDValue(); 11319 } 11320 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 11321 if (Const->getZExtValue() != 31) 11322 return SDValue(); 11323 } else 11324 return SDValue(); 11325 11326 if (SRA.getOperand(0) != Mul) 11327 return SDValue(); 11328 11329 SelectionDAG &DAG = DCI.DAG; 11330 SDLoc dl(AddcNode); 11331 unsigned Opcode = 0; 11332 SDValue Op0; 11333 SDValue Op1; 11334 11335 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 11336 Opcode = ARMISD::SMLALBB; 11337 Op0 = Mul.getOperand(0); 11338 Op1 = Mul.getOperand(1); 11339 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 11340 Opcode = ARMISD::SMLALBT; 11341 Op0 = Mul.getOperand(0); 11342 Op1 = Mul.getOperand(1).getOperand(0); 11343 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 11344 Opcode = ARMISD::SMLALTB; 11345 Op0 = Mul.getOperand(0).getOperand(0); 11346 Op1 = Mul.getOperand(1); 11347 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 11348 Opcode = ARMISD::SMLALTT; 11349 Op0 = Mul->getOperand(0).getOperand(0); 11350 Op1 = Mul->getOperand(1).getOperand(0); 11351 } 11352 11353 if (!Op0 || !Op1) 11354 return SDValue(); 11355 11356 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 11357 Op0, Op1, Lo, Hi); 11358 // Replace the ADDs' nodes uses by the MLA node's values. 11359 SDValue HiMLALResult(SMLAL.getNode(), 1); 11360 SDValue LoMLALResult(SMLAL.getNode(), 0); 11361 11362 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 11363 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 11364 11365 // Return original node to notify the driver to stop replacing. 11366 SDValue resNode(AddcNode, 0); 11367 return resNode; 11368 } 11369 11370 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 11371 TargetLowering::DAGCombinerInfo &DCI, 11372 const ARMSubtarget *Subtarget) { 11373 // Look for multiply add opportunities. 11374 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 11375 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 11376 // a glue link from the first add to the second add. 11377 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 11378 // a S/UMLAL instruction. 11379 // UMUL_LOHI 11380 // / :lo \ :hi 11381 // V \ [no multiline comment] 11382 // loAdd -> ADDC | 11383 // \ :carry / 11384 // V V 11385 // ADDE <- hiAdd 11386 // 11387 // In the special case where only the higher part of a signed result is used 11388 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 11389 // a constant with the exact value of 0x80000000, we recognize we are dealing 11390 // with a "rounded multiply and add" (or subtract) and transform it into 11391 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 11392 11393 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 11394 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 11395 "Expect an ADDE or SUBE"); 11396 11397 assert(AddeSubeNode->getNumOperands() == 3 && 11398 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 11399 "ADDE node has the wrong inputs"); 11400 11401 // Check that we are chained to the right ADDC or SUBC node. 11402 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 11403 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 11404 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 11405 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 11406 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 11407 return SDValue(); 11408 11409 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 11410 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 11411 11412 // Check if the two operands are from the same mul_lohi node. 11413 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 11414 return SDValue(); 11415 11416 assert(AddcSubcNode->getNumValues() == 2 && 11417 AddcSubcNode->getValueType(0) == MVT::i32 && 11418 "Expect ADDC with two result values. First: i32"); 11419 11420 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 11421 // maybe a SMLAL which multiplies two 16-bit values. 11422 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 11423 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 11424 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 11425 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 11426 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 11427 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 11428 11429 // Check for the triangle shape. 11430 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 11431 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 11432 11433 // Make sure that the ADDE/SUBE operands are not coming from the same node. 11434 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 11435 return SDValue(); 11436 11437 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 11438 bool IsLeftOperandMUL = false; 11439 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 11440 if (MULOp == SDValue()) 11441 MULOp = findMUL_LOHI(AddeSubeOp1); 11442 else 11443 IsLeftOperandMUL = true; 11444 if (MULOp == SDValue()) 11445 return SDValue(); 11446 11447 // Figure out the right opcode. 11448 unsigned Opc = MULOp->getOpcode(); 11449 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 11450 11451 // Figure out the high and low input values to the MLAL node. 11452 SDValue *HiAddSub = nullptr; 11453 SDValue *LoMul = nullptr; 11454 SDValue *LowAddSub = nullptr; 11455 11456 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 11457 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 11458 return SDValue(); 11459 11460 if (IsLeftOperandMUL) 11461 HiAddSub = &AddeSubeOp1; 11462 else 11463 HiAddSub = &AddeSubeOp0; 11464 11465 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 11466 // whose low result is fed to the ADDC/SUBC we are checking. 11467 11468 if (AddcSubcOp0 == MULOp.getValue(0)) { 11469 LoMul = &AddcSubcOp0; 11470 LowAddSub = &AddcSubcOp1; 11471 } 11472 if (AddcSubcOp1 == MULOp.getValue(0)) { 11473 LoMul = &AddcSubcOp1; 11474 LowAddSub = &AddcSubcOp0; 11475 } 11476 11477 if (!LoMul) 11478 return SDValue(); 11479 11480 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 11481 // the replacement below will create a cycle. 11482 if (AddcSubcNode == HiAddSub->getNode() || 11483 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 11484 return SDValue(); 11485 11486 // Create the merged node. 11487 SelectionDAG &DAG = DCI.DAG; 11488 11489 // Start building operand list. 11490 SmallVector<SDValue, 8> Ops; 11491 Ops.push_back(LoMul->getOperand(0)); 11492 Ops.push_back(LoMul->getOperand(1)); 11493 11494 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 11495 // the case, we must be doing signed multiplication and only use the higher 11496 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 11497 // addition or subtraction with the value of 0x800000. 11498 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 11499 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 11500 LowAddSub->getNode()->getOpcode() == ISD::Constant && 11501 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 11502 0x80000000) { 11503 Ops.push_back(*HiAddSub); 11504 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 11505 FinalOpc = ARMISD::SMMLSR; 11506 } else { 11507 FinalOpc = ARMISD::SMMLAR; 11508 } 11509 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 11510 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 11511 11512 return SDValue(AddeSubeNode, 0); 11513 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 11514 // SMMLS is generated during instruction selection and the rest of this 11515 // function can not handle the case where AddcSubcNode is a SUBC. 11516 return SDValue(); 11517 11518 // Finish building the operand list for {U/S}MLAL 11519 Ops.push_back(*LowAddSub); 11520 Ops.push_back(*HiAddSub); 11521 11522 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11523 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11524 11525 // Replace the ADDs' nodes uses by the MLA node's values. 11526 SDValue HiMLALResult(MLALNode.getNode(), 1); 11527 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11528 11529 SDValue LoMLALResult(MLALNode.getNode(), 0); 11530 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11531 11532 // Return original node to notify the driver to stop replacing. 11533 return SDValue(AddeSubeNode, 0); 11534 } 11535 11536 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11537 TargetLowering::DAGCombinerInfo &DCI, 11538 const ARMSubtarget *Subtarget) { 11539 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11540 // While trying to combine for the other MLAL nodes, first search for the 11541 // chance to use UMAAL. Check if Addc uses a node which has already 11542 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11543 // as the addend, and it's handled in PerformUMLALCombine. 11544 11545 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11546 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11547 11548 // Check that we have a glued ADDC node. 11549 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11550 if (AddcNode->getOpcode() != ARMISD::ADDC) 11551 return SDValue(); 11552 11553 // Find the converted UMAAL or quit if it doesn't exist. 11554 SDNode *UmlalNode = nullptr; 11555 SDValue AddHi; 11556 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11557 UmlalNode = AddcNode->getOperand(0).getNode(); 11558 AddHi = AddcNode->getOperand(1); 11559 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 11560 UmlalNode = AddcNode->getOperand(1).getNode(); 11561 AddHi = AddcNode->getOperand(0); 11562 } else { 11563 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11564 } 11565 11566 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 11567 // the ADDC as well as Zero. 11568 if (!isNullConstant(UmlalNode->getOperand(3))) 11569 return SDValue(); 11570 11571 if ((isNullConstant(AddeNode->getOperand(0)) && 11572 AddeNode->getOperand(1).getNode() == UmlalNode) || 11573 (AddeNode->getOperand(0).getNode() == UmlalNode && 11574 isNullConstant(AddeNode->getOperand(1)))) { 11575 SelectionDAG &DAG = DCI.DAG; 11576 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 11577 UmlalNode->getOperand(2), AddHi }; 11578 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 11579 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11580 11581 // Replace the ADDs' nodes uses by the UMAAL node's values. 11582 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 11583 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 11584 11585 // Return original node to notify the driver to stop replacing. 11586 return SDValue(AddeNode, 0); 11587 } 11588 return SDValue(); 11589 } 11590 11591 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 11592 const ARMSubtarget *Subtarget) { 11593 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11594 return SDValue(); 11595 11596 // Check that we have a pair of ADDC and ADDE as operands. 11597 // Both addends of the ADDE must be zero. 11598 SDNode* AddcNode = N->getOperand(2).getNode(); 11599 SDNode* AddeNode = N->getOperand(3).getNode(); 11600 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 11601 (AddeNode->getOpcode() == ARMISD::ADDE) && 11602 isNullConstant(AddeNode->getOperand(0)) && 11603 isNullConstant(AddeNode->getOperand(1)) && 11604 (AddeNode->getOperand(2).getNode() == AddcNode)) 11605 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 11606 DAG.getVTList(MVT::i32, MVT::i32), 11607 {N->getOperand(0), N->getOperand(1), 11608 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 11609 else 11610 return SDValue(); 11611 } 11612 11613 static SDValue PerformAddcSubcCombine(SDNode *N, 11614 TargetLowering::DAGCombinerInfo &DCI, 11615 const ARMSubtarget *Subtarget) { 11616 SelectionDAG &DAG(DCI.DAG); 11617 11618 if (N->getOpcode() == ARMISD::SUBC) { 11619 // (SUBC (ADDE 0, 0, C), 1) -> C 11620 SDValue LHS = N->getOperand(0); 11621 SDValue RHS = N->getOperand(1); 11622 if (LHS->getOpcode() == ARMISD::ADDE && 11623 isNullConstant(LHS->getOperand(0)) && 11624 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 11625 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 11626 } 11627 } 11628 11629 if (Subtarget->isThumb1Only()) { 11630 SDValue RHS = N->getOperand(1); 11631 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11632 int32_t imm = C->getSExtValue(); 11633 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 11634 SDLoc DL(N); 11635 RHS = DAG.getConstant(-imm, DL, MVT::i32); 11636 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 11637 : ARMISD::ADDC; 11638 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 11639 } 11640 } 11641 } 11642 11643 return SDValue(); 11644 } 11645 11646 static SDValue PerformAddeSubeCombine(SDNode *N, 11647 TargetLowering::DAGCombinerInfo &DCI, 11648 const ARMSubtarget *Subtarget) { 11649 if (Subtarget->isThumb1Only()) { 11650 SelectionDAG &DAG = DCI.DAG; 11651 SDValue RHS = N->getOperand(1); 11652 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11653 int64_t imm = C->getSExtValue(); 11654 if (imm < 0) { 11655 SDLoc DL(N); 11656 11657 // The with-carry-in form matches bitwise not instead of the negation. 11658 // Effectively, the inverse interpretation of the carry flag already 11659 // accounts for part of the negation. 11660 RHS = DAG.getConstant(~imm, DL, MVT::i32); 11661 11662 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 11663 : ARMISD::ADDE; 11664 return DAG.getNode(Opcode, DL, N->getVTList(), 11665 N->getOperand(0), RHS, N->getOperand(2)); 11666 } 11667 } 11668 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 11669 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 11670 } 11671 return SDValue(); 11672 } 11673 11674 static SDValue PerformABSCombine(SDNode *N, 11675 TargetLowering::DAGCombinerInfo &DCI, 11676 const ARMSubtarget *Subtarget) { 11677 SDValue res; 11678 SelectionDAG &DAG = DCI.DAG; 11679 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11680 11681 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 11682 return SDValue(); 11683 11684 if (!TLI.expandABS(N, res, DAG)) 11685 return SDValue(); 11686 11687 return res; 11688 } 11689 11690 /// PerformADDECombine - Target-specific dag combine transform from 11691 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 11692 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 11693 static SDValue PerformADDECombine(SDNode *N, 11694 TargetLowering::DAGCombinerInfo &DCI, 11695 const ARMSubtarget *Subtarget) { 11696 // Only ARM and Thumb2 support UMLAL/SMLAL. 11697 if (Subtarget->isThumb1Only()) 11698 return PerformAddeSubeCombine(N, DCI, Subtarget); 11699 11700 // Only perform the checks after legalize when the pattern is available. 11701 if (DCI.isBeforeLegalize()) return SDValue(); 11702 11703 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 11704 } 11705 11706 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 11707 /// operands N0 and N1. This is a helper for PerformADDCombine that is 11708 /// called with the default operands, and if that fails, with commuted 11709 /// operands. 11710 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 11711 TargetLowering::DAGCombinerInfo &DCI, 11712 const ARMSubtarget *Subtarget){ 11713 // Attempt to create vpadd for this add. 11714 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 11715 return Result; 11716 11717 // Attempt to create vpaddl for this add. 11718 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 11719 return Result; 11720 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 11721 Subtarget)) 11722 return Result; 11723 11724 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11725 if (N0.getNode()->hasOneUse()) 11726 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 11727 return Result; 11728 return SDValue(); 11729 } 11730 11731 bool 11732 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 11733 CombineLevel Level) const { 11734 if (Level == BeforeLegalizeTypes) 11735 return true; 11736 11737 if (N->getOpcode() != ISD::SHL) 11738 return true; 11739 11740 if (Subtarget->isThumb1Only()) { 11741 // Avoid making expensive immediates by commuting shifts. (This logic 11742 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 11743 // for free.) 11744 if (N->getOpcode() != ISD::SHL) 11745 return true; 11746 SDValue N1 = N->getOperand(0); 11747 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 11748 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 11749 return true; 11750 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 11751 if (Const->getAPIntValue().ult(256)) 11752 return false; 11753 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 11754 Const->getAPIntValue().sgt(-256)) 11755 return false; 11756 } 11757 return true; 11758 } 11759 11760 // Turn off commute-with-shift transform after legalization, so it doesn't 11761 // conflict with PerformSHLSimplify. (We could try to detect when 11762 // PerformSHLSimplify would trigger more precisely, but it isn't 11763 // really necessary.) 11764 return false; 11765 } 11766 11767 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 11768 const SDNode *N, CombineLevel Level) const { 11769 if (!Subtarget->isThumb1Only()) 11770 return true; 11771 11772 if (Level == BeforeLegalizeTypes) 11773 return true; 11774 11775 return false; 11776 } 11777 11778 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 11779 if (!Subtarget->hasNEON()) { 11780 if (Subtarget->isThumb1Only()) 11781 return VT.getScalarSizeInBits() <= 32; 11782 return true; 11783 } 11784 return VT.isScalarInteger(); 11785 } 11786 11787 static SDValue PerformSHLSimplify(SDNode *N, 11788 TargetLowering::DAGCombinerInfo &DCI, 11789 const ARMSubtarget *ST) { 11790 // Allow the generic combiner to identify potential bswaps. 11791 if (DCI.isBeforeLegalize()) 11792 return SDValue(); 11793 11794 // DAG combiner will fold: 11795 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 11796 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 11797 // Other code patterns that can be also be modified have the following form: 11798 // b + ((a << 1) | 510) 11799 // b + ((a << 1) & 510) 11800 // b + ((a << 1) ^ 510) 11801 // b + ((a << 1) + 510) 11802 11803 // Many instructions can perform the shift for free, but it requires both 11804 // the operands to be registers. If c1 << c2 is too large, a mov immediate 11805 // instruction will needed. So, unfold back to the original pattern if: 11806 // - if c1 and c2 are small enough that they don't require mov imms. 11807 // - the user(s) of the node can perform an shl 11808 11809 // No shifted operands for 16-bit instructions. 11810 if (ST->isThumb() && ST->isThumb1Only()) 11811 return SDValue(); 11812 11813 // Check that all the users could perform the shl themselves. 11814 for (auto U : N->uses()) { 11815 switch(U->getOpcode()) { 11816 default: 11817 return SDValue(); 11818 case ISD::SUB: 11819 case ISD::ADD: 11820 case ISD::AND: 11821 case ISD::OR: 11822 case ISD::XOR: 11823 case ISD::SETCC: 11824 case ARMISD::CMP: 11825 // Check that the user isn't already using a constant because there 11826 // aren't any instructions that support an immediate operand and a 11827 // shifted operand. 11828 if (isa<ConstantSDNode>(U->getOperand(0)) || 11829 isa<ConstantSDNode>(U->getOperand(1))) 11830 return SDValue(); 11831 11832 // Check that it's not already using a shift. 11833 if (U->getOperand(0).getOpcode() == ISD::SHL || 11834 U->getOperand(1).getOpcode() == ISD::SHL) 11835 return SDValue(); 11836 break; 11837 } 11838 } 11839 11840 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 11841 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 11842 return SDValue(); 11843 11844 if (N->getOperand(0).getOpcode() != ISD::SHL) 11845 return SDValue(); 11846 11847 SDValue SHL = N->getOperand(0); 11848 11849 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11850 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 11851 if (!C1ShlC2 || !C2) 11852 return SDValue(); 11853 11854 APInt C2Int = C2->getAPIntValue(); 11855 APInt C1Int = C1ShlC2->getAPIntValue(); 11856 11857 // Check that performing a lshr will not lose any information. 11858 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 11859 C2Int.getBitWidth() - C2->getZExtValue()); 11860 if ((C1Int & Mask) != C1Int) 11861 return SDValue(); 11862 11863 // Shift the first constant. 11864 C1Int.lshrInPlace(C2Int); 11865 11866 // The immediates are encoded as an 8-bit value that can be rotated. 11867 auto LargeImm = [](const APInt &Imm) { 11868 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 11869 return Imm.getBitWidth() - Zeros > 8; 11870 }; 11871 11872 if (LargeImm(C1Int) || LargeImm(C2Int)) 11873 return SDValue(); 11874 11875 SelectionDAG &DAG = DCI.DAG; 11876 SDLoc dl(N); 11877 SDValue X = SHL.getOperand(0); 11878 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 11879 DAG.getConstant(C1Int, dl, MVT::i32)); 11880 // Shift left to compensate for the lshr of C1Int. 11881 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 11882 11883 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 11884 SHL.dump(); N->dump()); 11885 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 11886 return Res; 11887 } 11888 11889 11890 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 11891 /// 11892 static SDValue PerformADDCombine(SDNode *N, 11893 TargetLowering::DAGCombinerInfo &DCI, 11894 const ARMSubtarget *Subtarget) { 11895 SDValue N0 = N->getOperand(0); 11896 SDValue N1 = N->getOperand(1); 11897 11898 // Only works one way, because it needs an immediate operand. 11899 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11900 return Result; 11901 11902 // First try with the default operand order. 11903 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 11904 return Result; 11905 11906 // If that didn't work, try again with the operands commuted. 11907 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 11908 } 11909 11910 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 11911 /// 11912 static SDValue PerformSUBCombine(SDNode *N, 11913 TargetLowering::DAGCombinerInfo &DCI, 11914 const ARMSubtarget *Subtarget) { 11915 SDValue N0 = N->getOperand(0); 11916 SDValue N1 = N->getOperand(1); 11917 11918 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11919 if (N1.getNode()->hasOneUse()) 11920 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 11921 return Result; 11922 11923 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector()) 11924 return SDValue(); 11925 11926 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x)) 11927 // so that we can readily pattern match more mve instructions which can use 11928 // a scalar operand. 11929 SDValue VDup = N->getOperand(1); 11930 if (VDup->getOpcode() != ARMISD::VDUP) 11931 return SDValue(); 11932 11933 SDValue VMov = N->getOperand(0); 11934 if (VMov->getOpcode() == ISD::BITCAST) 11935 VMov = VMov->getOperand(0); 11936 11937 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov)) 11938 return SDValue(); 11939 11940 SDLoc dl(N); 11941 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32, 11942 DCI.DAG.getConstant(0, dl, MVT::i32), 11943 VDup->getOperand(0)); 11944 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate); 11945 } 11946 11947 /// PerformVMULCombine 11948 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 11949 /// special multiplier accumulator forwarding. 11950 /// vmul d3, d0, d2 11951 /// vmla d3, d1, d2 11952 /// is faster than 11953 /// vadd d3, d0, d1 11954 /// vmul d3, d3, d2 11955 // However, for (A + B) * (A + B), 11956 // vadd d2, d0, d1 11957 // vmul d3, d0, d2 11958 // vmla d3, d1, d2 11959 // is slower than 11960 // vadd d2, d0, d1 11961 // vmul d3, d2, d2 11962 static SDValue PerformVMULCombine(SDNode *N, 11963 TargetLowering::DAGCombinerInfo &DCI, 11964 const ARMSubtarget *Subtarget) { 11965 if (!Subtarget->hasVMLxForwarding()) 11966 return SDValue(); 11967 11968 SelectionDAG &DAG = DCI.DAG; 11969 SDValue N0 = N->getOperand(0); 11970 SDValue N1 = N->getOperand(1); 11971 unsigned Opcode = N0.getOpcode(); 11972 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11973 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 11974 Opcode = N1.getOpcode(); 11975 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11976 Opcode != ISD::FADD && Opcode != ISD::FSUB) 11977 return SDValue(); 11978 std::swap(N0, N1); 11979 } 11980 11981 if (N0 == N1) 11982 return SDValue(); 11983 11984 EVT VT = N->getValueType(0); 11985 SDLoc DL(N); 11986 SDValue N00 = N0->getOperand(0); 11987 SDValue N01 = N0->getOperand(1); 11988 return DAG.getNode(Opcode, DL, VT, 11989 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 11990 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 11991 } 11992 11993 static SDValue PerformMULCombine(SDNode *N, 11994 TargetLowering::DAGCombinerInfo &DCI, 11995 const ARMSubtarget *Subtarget) { 11996 SelectionDAG &DAG = DCI.DAG; 11997 11998 if (Subtarget->isThumb1Only()) 11999 return SDValue(); 12000 12001 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12002 return SDValue(); 12003 12004 EVT VT = N->getValueType(0); 12005 if (VT.is64BitVector() || VT.is128BitVector()) 12006 return PerformVMULCombine(N, DCI, Subtarget); 12007 if (VT != MVT::i32) 12008 return SDValue(); 12009 12010 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12011 if (!C) 12012 return SDValue(); 12013 12014 int64_t MulAmt = C->getSExtValue(); 12015 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 12016 12017 ShiftAmt = ShiftAmt & (32 - 1); 12018 SDValue V = N->getOperand(0); 12019 SDLoc DL(N); 12020 12021 SDValue Res; 12022 MulAmt >>= ShiftAmt; 12023 12024 if (MulAmt >= 0) { 12025 if (isPowerOf2_32(MulAmt - 1)) { 12026 // (mul x, 2^N + 1) => (add (shl x, N), x) 12027 Res = DAG.getNode(ISD::ADD, DL, VT, 12028 V, 12029 DAG.getNode(ISD::SHL, DL, VT, 12030 V, 12031 DAG.getConstant(Log2_32(MulAmt - 1), DL, 12032 MVT::i32))); 12033 } else if (isPowerOf2_32(MulAmt + 1)) { 12034 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12035 Res = DAG.getNode(ISD::SUB, DL, VT, 12036 DAG.getNode(ISD::SHL, DL, VT, 12037 V, 12038 DAG.getConstant(Log2_32(MulAmt + 1), DL, 12039 MVT::i32)), 12040 V); 12041 } else 12042 return SDValue(); 12043 } else { 12044 uint64_t MulAmtAbs = -MulAmt; 12045 if (isPowerOf2_32(MulAmtAbs + 1)) { 12046 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12047 Res = DAG.getNode(ISD::SUB, DL, VT, 12048 V, 12049 DAG.getNode(ISD::SHL, DL, VT, 12050 V, 12051 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 12052 MVT::i32))); 12053 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 12054 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12055 Res = DAG.getNode(ISD::ADD, DL, VT, 12056 V, 12057 DAG.getNode(ISD::SHL, DL, VT, 12058 V, 12059 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 12060 MVT::i32))); 12061 Res = DAG.getNode(ISD::SUB, DL, VT, 12062 DAG.getConstant(0, DL, MVT::i32), Res); 12063 } else 12064 return SDValue(); 12065 } 12066 12067 if (ShiftAmt != 0) 12068 Res = DAG.getNode(ISD::SHL, DL, VT, 12069 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 12070 12071 // Do not add new nodes to DAG combiner worklist. 12072 DCI.CombineTo(N, Res, false); 12073 return SDValue(); 12074 } 12075 12076 static SDValue CombineANDShift(SDNode *N, 12077 TargetLowering::DAGCombinerInfo &DCI, 12078 const ARMSubtarget *Subtarget) { 12079 // Allow DAGCombine to pattern-match before we touch the canonical form. 12080 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12081 return SDValue(); 12082 12083 if (N->getValueType(0) != MVT::i32) 12084 return SDValue(); 12085 12086 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12087 if (!N1C) 12088 return SDValue(); 12089 12090 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 12091 // Don't transform uxtb/uxth. 12092 if (C1 == 255 || C1 == 65535) 12093 return SDValue(); 12094 12095 SDNode *N0 = N->getOperand(0).getNode(); 12096 if (!N0->hasOneUse()) 12097 return SDValue(); 12098 12099 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 12100 return SDValue(); 12101 12102 bool LeftShift = N0->getOpcode() == ISD::SHL; 12103 12104 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12105 if (!N01C) 12106 return SDValue(); 12107 12108 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 12109 if (!C2 || C2 >= 32) 12110 return SDValue(); 12111 12112 // Clear irrelevant bits in the mask. 12113 if (LeftShift) 12114 C1 &= (-1U << C2); 12115 else 12116 C1 &= (-1U >> C2); 12117 12118 SelectionDAG &DAG = DCI.DAG; 12119 SDLoc DL(N); 12120 12121 // We have a pattern of the form "(and (shl x, c2) c1)" or 12122 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 12123 // transform to a pair of shifts, to save materializing c1. 12124 12125 // First pattern: right shift, then mask off leading bits. 12126 // FIXME: Use demanded bits? 12127 if (!LeftShift && isMask_32(C1)) { 12128 uint32_t C3 = countLeadingZeros(C1); 12129 if (C2 < C3) { 12130 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12131 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12132 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12133 DAG.getConstant(C3, DL, MVT::i32)); 12134 } 12135 } 12136 12137 // First pattern, reversed: left shift, then mask off trailing bits. 12138 if (LeftShift && isMask_32(~C1)) { 12139 uint32_t C3 = countTrailingZeros(C1); 12140 if (C2 < C3) { 12141 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12142 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12143 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12144 DAG.getConstant(C3, DL, MVT::i32)); 12145 } 12146 } 12147 12148 // Second pattern: left shift, then mask off leading bits. 12149 // FIXME: Use demanded bits? 12150 if (LeftShift && isShiftedMask_32(C1)) { 12151 uint32_t Trailing = countTrailingZeros(C1); 12152 uint32_t C3 = countLeadingZeros(C1); 12153 if (Trailing == C2 && C2 + C3 < 32) { 12154 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12155 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12156 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12157 DAG.getConstant(C3, DL, MVT::i32)); 12158 } 12159 } 12160 12161 // Second pattern, reversed: right shift, then mask off trailing bits. 12162 // FIXME: Handle other patterns of known/demanded bits. 12163 if (!LeftShift && isShiftedMask_32(C1)) { 12164 uint32_t Leading = countLeadingZeros(C1); 12165 uint32_t C3 = countTrailingZeros(C1); 12166 if (Leading == C2 && C2 + C3 < 32) { 12167 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12168 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12169 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12170 DAG.getConstant(C3, DL, MVT::i32)); 12171 } 12172 } 12173 12174 // FIXME: Transform "(and (shl x, c2) c1)" -> 12175 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 12176 // c1. 12177 return SDValue(); 12178 } 12179 12180 static SDValue PerformANDCombine(SDNode *N, 12181 TargetLowering::DAGCombinerInfo &DCI, 12182 const ARMSubtarget *Subtarget) { 12183 // Attempt to use immediate-form VBIC 12184 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12185 SDLoc dl(N); 12186 EVT VT = N->getValueType(0); 12187 SelectionDAG &DAG = DCI.DAG; 12188 12189 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12190 return SDValue(); 12191 12192 APInt SplatBits, SplatUndef; 12193 unsigned SplatBitSize; 12194 bool HasAnyUndefs; 12195 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 12196 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12197 if (SplatBitSize <= 64) { 12198 EVT VbicVT; 12199 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 12200 SplatUndef.getZExtValue(), SplatBitSize, 12201 DAG, dl, VbicVT, VT.is128BitVector(), 12202 OtherModImm); 12203 if (Val.getNode()) { 12204 SDValue Input = 12205 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 12206 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 12207 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 12208 } 12209 } 12210 } 12211 12212 if (!Subtarget->isThumb1Only()) { 12213 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 12214 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 12215 return Result; 12216 12217 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12218 return Result; 12219 } 12220 12221 if (Subtarget->isThumb1Only()) 12222 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 12223 return Result; 12224 12225 return SDValue(); 12226 } 12227 12228 // Try combining OR nodes to SMULWB, SMULWT. 12229 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 12230 TargetLowering::DAGCombinerInfo &DCI, 12231 const ARMSubtarget *Subtarget) { 12232 if (!Subtarget->hasV6Ops() || 12233 (Subtarget->isThumb() && 12234 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 12235 return SDValue(); 12236 12237 SDValue SRL = OR->getOperand(0); 12238 SDValue SHL = OR->getOperand(1); 12239 12240 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 12241 SRL = OR->getOperand(1); 12242 SHL = OR->getOperand(0); 12243 } 12244 if (!isSRL16(SRL) || !isSHL16(SHL)) 12245 return SDValue(); 12246 12247 // The first operands to the shifts need to be the two results from the 12248 // same smul_lohi node. 12249 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 12250 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 12251 return SDValue(); 12252 12253 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 12254 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 12255 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 12256 return SDValue(); 12257 12258 // Now we have: 12259 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 12260 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 12261 // For SMUWB the 16-bit value will signed extended somehow. 12262 // For SMULWT only the SRA is required. 12263 // Check both sides of SMUL_LOHI 12264 SDValue OpS16 = SMULLOHI->getOperand(0); 12265 SDValue OpS32 = SMULLOHI->getOperand(1); 12266 12267 SelectionDAG &DAG = DCI.DAG; 12268 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 12269 OpS16 = OpS32; 12270 OpS32 = SMULLOHI->getOperand(0); 12271 } 12272 12273 SDLoc dl(OR); 12274 unsigned Opcode = 0; 12275 if (isS16(OpS16, DAG)) 12276 Opcode = ARMISD::SMULWB; 12277 else if (isSRA16(OpS16)) { 12278 Opcode = ARMISD::SMULWT; 12279 OpS16 = OpS16->getOperand(0); 12280 } 12281 else 12282 return SDValue(); 12283 12284 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 12285 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 12286 return SDValue(OR, 0); 12287 } 12288 12289 static SDValue PerformORCombineToBFI(SDNode *N, 12290 TargetLowering::DAGCombinerInfo &DCI, 12291 const ARMSubtarget *Subtarget) { 12292 // BFI is only available on V6T2+ 12293 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 12294 return SDValue(); 12295 12296 EVT VT = N->getValueType(0); 12297 SDValue N0 = N->getOperand(0); 12298 SDValue N1 = N->getOperand(1); 12299 SelectionDAG &DAG = DCI.DAG; 12300 SDLoc DL(N); 12301 // 1) or (and A, mask), val => ARMbfi A, val, mask 12302 // iff (val & mask) == val 12303 // 12304 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 12305 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 12306 // && mask == ~mask2 12307 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 12308 // && ~mask == mask2 12309 // (i.e., copy a bitfield value into another bitfield of the same width) 12310 12311 if (VT != MVT::i32) 12312 return SDValue(); 12313 12314 SDValue N00 = N0.getOperand(0); 12315 12316 // The value and the mask need to be constants so we can verify this is 12317 // actually a bitfield set. If the mask is 0xffff, we can do better 12318 // via a movt instruction, so don't use BFI in that case. 12319 SDValue MaskOp = N0.getOperand(1); 12320 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 12321 if (!MaskC) 12322 return SDValue(); 12323 unsigned Mask = MaskC->getZExtValue(); 12324 if (Mask == 0xffff) 12325 return SDValue(); 12326 SDValue Res; 12327 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 12328 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 12329 if (N1C) { 12330 unsigned Val = N1C->getZExtValue(); 12331 if ((Val & ~Mask) != Val) 12332 return SDValue(); 12333 12334 if (ARM::isBitFieldInvertedMask(Mask)) { 12335 Val >>= countTrailingZeros(~Mask); 12336 12337 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 12338 DAG.getConstant(Val, DL, MVT::i32), 12339 DAG.getConstant(Mask, DL, MVT::i32)); 12340 12341 DCI.CombineTo(N, Res, false); 12342 // Return value from the original node to inform the combiner than N is 12343 // now dead. 12344 return SDValue(N, 0); 12345 } 12346 } else if (N1.getOpcode() == ISD::AND) { 12347 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 12348 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12349 if (!N11C) 12350 return SDValue(); 12351 unsigned Mask2 = N11C->getZExtValue(); 12352 12353 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 12354 // as is to match. 12355 if (ARM::isBitFieldInvertedMask(Mask) && 12356 (Mask == ~Mask2)) { 12357 // The pack halfword instruction works better for masks that fit it, 12358 // so use that when it's available. 12359 if (Subtarget->hasDSP() && 12360 (Mask == 0xffff || Mask == 0xffff0000)) 12361 return SDValue(); 12362 // 2a 12363 unsigned amt = countTrailingZeros(Mask2); 12364 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 12365 DAG.getConstant(amt, DL, MVT::i32)); 12366 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 12367 DAG.getConstant(Mask, DL, MVT::i32)); 12368 DCI.CombineTo(N, Res, false); 12369 // Return value from the original node to inform the combiner than N is 12370 // now dead. 12371 return SDValue(N, 0); 12372 } else if (ARM::isBitFieldInvertedMask(~Mask) && 12373 (~Mask == Mask2)) { 12374 // The pack halfword instruction works better for masks that fit it, 12375 // so use that when it's available. 12376 if (Subtarget->hasDSP() && 12377 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 12378 return SDValue(); 12379 // 2b 12380 unsigned lsb = countTrailingZeros(Mask); 12381 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 12382 DAG.getConstant(lsb, DL, MVT::i32)); 12383 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 12384 DAG.getConstant(Mask2, DL, MVT::i32)); 12385 DCI.CombineTo(N, Res, false); 12386 // Return value from the original node to inform the combiner than N is 12387 // now dead. 12388 return SDValue(N, 0); 12389 } 12390 } 12391 12392 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 12393 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 12394 ARM::isBitFieldInvertedMask(~Mask)) { 12395 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 12396 // where lsb(mask) == #shamt and masked bits of B are known zero. 12397 SDValue ShAmt = N00.getOperand(1); 12398 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 12399 unsigned LSB = countTrailingZeros(Mask); 12400 if (ShAmtC != LSB) 12401 return SDValue(); 12402 12403 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 12404 DAG.getConstant(~Mask, DL, MVT::i32)); 12405 12406 DCI.CombineTo(N, Res, false); 12407 // Return value from the original node to inform the combiner than N is 12408 // now dead. 12409 return SDValue(N, 0); 12410 } 12411 12412 return SDValue(); 12413 } 12414 12415 static bool isValidMVECond(unsigned CC, bool IsFloat) { 12416 switch (CC) { 12417 case ARMCC::EQ: 12418 case ARMCC::NE: 12419 case ARMCC::LE: 12420 case ARMCC::GT: 12421 case ARMCC::GE: 12422 case ARMCC::LT: 12423 return true; 12424 case ARMCC::HS: 12425 case ARMCC::HI: 12426 return !IsFloat; 12427 default: 12428 return false; 12429 }; 12430 } 12431 12432 static SDValue PerformORCombine_i1(SDNode *N, 12433 TargetLowering::DAGCombinerInfo &DCI, 12434 const ARMSubtarget *Subtarget) { 12435 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 12436 // together with predicates 12437 EVT VT = N->getValueType(0); 12438 SDValue N0 = N->getOperand(0); 12439 SDValue N1 = N->getOperand(1); 12440 12441 ARMCC::CondCodes CondCode0 = ARMCC::AL; 12442 ARMCC::CondCodes CondCode1 = ARMCC::AL; 12443 if (N0->getOpcode() == ARMISD::VCMP) 12444 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2)) 12445 ->getZExtValue(); 12446 else if (N0->getOpcode() == ARMISD::VCMPZ) 12447 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1)) 12448 ->getZExtValue(); 12449 if (N1->getOpcode() == ARMISD::VCMP) 12450 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2)) 12451 ->getZExtValue(); 12452 else if (N1->getOpcode() == ARMISD::VCMPZ) 12453 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1)) 12454 ->getZExtValue(); 12455 12456 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL) 12457 return SDValue(); 12458 12459 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0); 12460 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1); 12461 12462 if (!isValidMVECond(Opposite0, 12463 N0->getOperand(0)->getValueType(0).isFloatingPoint()) || 12464 !isValidMVECond(Opposite1, 12465 N1->getOperand(0)->getValueType(0).isFloatingPoint())) 12466 return SDValue(); 12467 12468 SmallVector<SDValue, 4> Ops0; 12469 Ops0.push_back(N0->getOperand(0)); 12470 if (N0->getOpcode() == ARMISD::VCMP) 12471 Ops0.push_back(N0->getOperand(1)); 12472 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32)); 12473 SmallVector<SDValue, 4> Ops1; 12474 Ops1.push_back(N1->getOperand(0)); 12475 if (N1->getOpcode() == ARMISD::VCMP) 12476 Ops1.push_back(N1->getOperand(1)); 12477 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32)); 12478 12479 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0); 12480 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1); 12481 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1); 12482 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And, 12483 DCI.DAG.getAllOnesConstant(SDLoc(N), VT)); 12484 } 12485 12486 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 12487 static SDValue PerformORCombine(SDNode *N, 12488 TargetLowering::DAGCombinerInfo &DCI, 12489 const ARMSubtarget *Subtarget) { 12490 // Attempt to use immediate-form VORR 12491 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12492 SDLoc dl(N); 12493 EVT VT = N->getValueType(0); 12494 SelectionDAG &DAG = DCI.DAG; 12495 12496 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12497 return SDValue(); 12498 12499 APInt SplatBits, SplatUndef; 12500 unsigned SplatBitSize; 12501 bool HasAnyUndefs; 12502 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 12503 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12504 if (SplatBitSize <= 64) { 12505 EVT VorrVT; 12506 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 12507 SplatUndef.getZExtValue(), SplatBitSize, 12508 DAG, dl, VorrVT, VT.is128BitVector(), 12509 OtherModImm); 12510 if (Val.getNode()) { 12511 SDValue Input = 12512 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 12513 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 12514 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 12515 } 12516 } 12517 } 12518 12519 if (!Subtarget->isThumb1Only()) { 12520 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 12521 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12522 return Result; 12523 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 12524 return Result; 12525 } 12526 12527 SDValue N0 = N->getOperand(0); 12528 SDValue N1 = N->getOperand(1); 12529 12530 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 12531 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 12532 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 12533 12534 // The code below optimizes (or (and X, Y), Z). 12535 // The AND operand needs to have a single user to make these optimizations 12536 // profitable. 12537 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 12538 return SDValue(); 12539 12540 APInt SplatUndef; 12541 unsigned SplatBitSize; 12542 bool HasAnyUndefs; 12543 12544 APInt SplatBits0, SplatBits1; 12545 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 12546 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 12547 // Ensure that the second operand of both ands are constants 12548 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 12549 HasAnyUndefs) && !HasAnyUndefs) { 12550 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 12551 HasAnyUndefs) && !HasAnyUndefs) { 12552 // Ensure that the bit width of the constants are the same and that 12553 // the splat arguments are logical inverses as per the pattern we 12554 // are trying to simplify. 12555 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 12556 SplatBits0 == ~SplatBits1) { 12557 // Canonicalize the vector type to make instruction selection 12558 // simpler. 12559 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 12560 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 12561 N0->getOperand(1), 12562 N0->getOperand(0), 12563 N1->getOperand(0)); 12564 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 12565 } 12566 } 12567 } 12568 } 12569 12570 if (Subtarget->hasMVEIntegerOps() && 12571 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 12572 return PerformORCombine_i1(N, DCI, Subtarget); 12573 12574 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 12575 // reasonable. 12576 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 12577 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 12578 return Res; 12579 } 12580 12581 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12582 return Result; 12583 12584 return SDValue(); 12585 } 12586 12587 static SDValue PerformXORCombine(SDNode *N, 12588 TargetLowering::DAGCombinerInfo &DCI, 12589 const ARMSubtarget *Subtarget) { 12590 EVT VT = N->getValueType(0); 12591 SelectionDAG &DAG = DCI.DAG; 12592 12593 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12594 return SDValue(); 12595 12596 if (!Subtarget->isThumb1Only()) { 12597 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 12598 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12599 return Result; 12600 12601 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12602 return Result; 12603 } 12604 12605 return SDValue(); 12606 } 12607 12608 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 12609 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 12610 // their position in "to" (Rd). 12611 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 12612 assert(N->getOpcode() == ARMISD::BFI); 12613 12614 SDValue From = N->getOperand(1); 12615 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 12616 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 12617 12618 // If the Base came from a SHR #C, we can deduce that it is really testing bit 12619 // #C in the base of the SHR. 12620 if (From->getOpcode() == ISD::SRL && 12621 isa<ConstantSDNode>(From->getOperand(1))) { 12622 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 12623 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 12624 FromMask <<= Shift.getLimitedValue(31); 12625 From = From->getOperand(0); 12626 } 12627 12628 return From; 12629 } 12630 12631 // If A and B contain one contiguous set of bits, does A | B == A . B? 12632 // 12633 // Neither A nor B must be zero. 12634 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 12635 unsigned LastActiveBitInA = A.countTrailingZeros(); 12636 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 12637 return LastActiveBitInA - 1 == FirstActiveBitInB; 12638 } 12639 12640 static SDValue FindBFIToCombineWith(SDNode *N) { 12641 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 12642 // if one exists. 12643 APInt ToMask, FromMask; 12644 SDValue From = ParseBFI(N, ToMask, FromMask); 12645 SDValue To = N->getOperand(0); 12646 12647 // Now check for a compatible BFI to merge with. We can pass through BFIs that 12648 // aren't compatible, but not if they set the same bit in their destination as 12649 // we do (or that of any BFI we're going to combine with). 12650 SDValue V = To; 12651 APInt CombinedToMask = ToMask; 12652 while (V.getOpcode() == ARMISD::BFI) { 12653 APInt NewToMask, NewFromMask; 12654 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 12655 if (NewFrom != From) { 12656 // This BFI has a different base. Keep going. 12657 CombinedToMask |= NewToMask; 12658 V = V.getOperand(0); 12659 continue; 12660 } 12661 12662 // Do the written bits conflict with any we've seen so far? 12663 if ((NewToMask & CombinedToMask).getBoolValue()) 12664 // Conflicting bits - bail out because going further is unsafe. 12665 return SDValue(); 12666 12667 // Are the new bits contiguous when combined with the old bits? 12668 if (BitsProperlyConcatenate(ToMask, NewToMask) && 12669 BitsProperlyConcatenate(FromMask, NewFromMask)) 12670 return V; 12671 if (BitsProperlyConcatenate(NewToMask, ToMask) && 12672 BitsProperlyConcatenate(NewFromMask, FromMask)) 12673 return V; 12674 12675 // We've seen a write to some bits, so track it. 12676 CombinedToMask |= NewToMask; 12677 // Keep going... 12678 V = V.getOperand(0); 12679 } 12680 12681 return SDValue(); 12682 } 12683 12684 static SDValue PerformBFICombine(SDNode *N, 12685 TargetLowering::DAGCombinerInfo &DCI) { 12686 SDValue N1 = N->getOperand(1); 12687 if (N1.getOpcode() == ISD::AND) { 12688 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 12689 // the bits being cleared by the AND are not demanded by the BFI. 12690 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12691 if (!N11C) 12692 return SDValue(); 12693 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12694 unsigned LSB = countTrailingZeros(~InvMask); 12695 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 12696 assert(Width < 12697 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 12698 "undefined behavior"); 12699 unsigned Mask = (1u << Width) - 1; 12700 unsigned Mask2 = N11C->getZExtValue(); 12701 if ((Mask & (~Mask2)) == 0) 12702 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 12703 N->getOperand(0), N1.getOperand(0), 12704 N->getOperand(2)); 12705 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 12706 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 12707 // Keep track of any consecutive bits set that all come from the same base 12708 // value. We can combine these together into a single BFI. 12709 SDValue CombineBFI = FindBFIToCombineWith(N); 12710 if (CombineBFI == SDValue()) 12711 return SDValue(); 12712 12713 // We've found a BFI. 12714 APInt ToMask1, FromMask1; 12715 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 12716 12717 APInt ToMask2, FromMask2; 12718 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 12719 assert(From1 == From2); 12720 (void)From2; 12721 12722 // First, unlink CombineBFI. 12723 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 12724 // Then create a new BFI, combining the two together. 12725 APInt NewFromMask = FromMask1 | FromMask2; 12726 APInt NewToMask = ToMask1 | ToMask2; 12727 12728 EVT VT = N->getValueType(0); 12729 SDLoc dl(N); 12730 12731 if (NewFromMask[0] == 0) 12732 From1 = DCI.DAG.getNode( 12733 ISD::SRL, dl, VT, From1, 12734 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 12735 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 12736 DCI.DAG.getConstant(~NewToMask, dl, VT)); 12737 } 12738 return SDValue(); 12739 } 12740 12741 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 12742 /// ARMISD::VMOVRRD. 12743 static SDValue PerformVMOVRRDCombine(SDNode *N, 12744 TargetLowering::DAGCombinerInfo &DCI, 12745 const ARMSubtarget *Subtarget) { 12746 // vmovrrd(vmovdrr x, y) -> x,y 12747 SDValue InDouble = N->getOperand(0); 12748 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 12749 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 12750 12751 // vmovrrd(load f64) -> (load i32), (load i32) 12752 SDNode *InNode = InDouble.getNode(); 12753 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 12754 InNode->getValueType(0) == MVT::f64 && 12755 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 12756 !cast<LoadSDNode>(InNode)->isVolatile()) { 12757 // TODO: Should this be done for non-FrameIndex operands? 12758 LoadSDNode *LD = cast<LoadSDNode>(InNode); 12759 12760 SelectionDAG &DAG = DCI.DAG; 12761 SDLoc DL(LD); 12762 SDValue BasePtr = LD->getBasePtr(); 12763 SDValue NewLD1 = 12764 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 12765 LD->getAlignment(), LD->getMemOperand()->getFlags()); 12766 12767 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12768 DAG.getConstant(4, DL, MVT::i32)); 12769 12770 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 12771 LD->getPointerInfo().getWithOffset(4), 12772 std::min(4U, LD->getAlignment()), 12773 LD->getMemOperand()->getFlags()); 12774 12775 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 12776 if (DCI.DAG.getDataLayout().isBigEndian()) 12777 std::swap (NewLD1, NewLD2); 12778 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 12779 return Result; 12780 } 12781 12782 return SDValue(); 12783 } 12784 12785 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 12786 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 12787 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 12788 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 12789 SDValue Op0 = N->getOperand(0); 12790 SDValue Op1 = N->getOperand(1); 12791 if (Op0.getOpcode() == ISD::BITCAST) 12792 Op0 = Op0.getOperand(0); 12793 if (Op1.getOpcode() == ISD::BITCAST) 12794 Op1 = Op1.getOperand(0); 12795 if (Op0.getOpcode() == ARMISD::VMOVRRD && 12796 Op0.getNode() == Op1.getNode() && 12797 Op0.getResNo() == 0 && Op1.getResNo() == 1) 12798 return DAG.getNode(ISD::BITCAST, SDLoc(N), 12799 N->getValueType(0), Op0.getOperand(0)); 12800 return SDValue(); 12801 } 12802 12803 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 12804 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 12805 /// i64 vector to have f64 elements, since the value can then be loaded 12806 /// directly into a VFP register. 12807 static bool hasNormalLoadOperand(SDNode *N) { 12808 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 12809 for (unsigned i = 0; i < NumElts; ++i) { 12810 SDNode *Elt = N->getOperand(i).getNode(); 12811 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 12812 return true; 12813 } 12814 return false; 12815 } 12816 12817 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 12818 /// ISD::BUILD_VECTOR. 12819 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 12820 TargetLowering::DAGCombinerInfo &DCI, 12821 const ARMSubtarget *Subtarget) { 12822 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 12823 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 12824 // into a pair of GPRs, which is fine when the value is used as a scalar, 12825 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 12826 SelectionDAG &DAG = DCI.DAG; 12827 if (N->getNumOperands() == 2) 12828 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 12829 return RV; 12830 12831 // Load i64 elements as f64 values so that type legalization does not split 12832 // them up into i32 values. 12833 EVT VT = N->getValueType(0); 12834 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 12835 return SDValue(); 12836 SDLoc dl(N); 12837 SmallVector<SDValue, 8> Ops; 12838 unsigned NumElts = VT.getVectorNumElements(); 12839 for (unsigned i = 0; i < NumElts; ++i) { 12840 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 12841 Ops.push_back(V); 12842 // Make the DAGCombiner fold the bitcast. 12843 DCI.AddToWorklist(V.getNode()); 12844 } 12845 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 12846 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 12847 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12848 } 12849 12850 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 12851 static SDValue 12852 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12853 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 12854 // At that time, we may have inserted bitcasts from integer to float. 12855 // If these bitcasts have survived DAGCombine, change the lowering of this 12856 // BUILD_VECTOR in something more vector friendly, i.e., that does not 12857 // force to use floating point types. 12858 12859 // Make sure we can change the type of the vector. 12860 // This is possible iff: 12861 // 1. The vector is only used in a bitcast to a integer type. I.e., 12862 // 1.1. Vector is used only once. 12863 // 1.2. Use is a bit convert to an integer type. 12864 // 2. The size of its operands are 32-bits (64-bits are not legal). 12865 EVT VT = N->getValueType(0); 12866 EVT EltVT = VT.getVectorElementType(); 12867 12868 // Check 1.1. and 2. 12869 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 12870 return SDValue(); 12871 12872 // By construction, the input type must be float. 12873 assert(EltVT == MVT::f32 && "Unexpected type!"); 12874 12875 // Check 1.2. 12876 SDNode *Use = *N->use_begin(); 12877 if (Use->getOpcode() != ISD::BITCAST || 12878 Use->getValueType(0).isFloatingPoint()) 12879 return SDValue(); 12880 12881 // Check profitability. 12882 // Model is, if more than half of the relevant operands are bitcast from 12883 // i32, turn the build_vector into a sequence of insert_vector_elt. 12884 // Relevant operands are everything that is not statically 12885 // (i.e., at compile time) bitcasted. 12886 unsigned NumOfBitCastedElts = 0; 12887 unsigned NumElts = VT.getVectorNumElements(); 12888 unsigned NumOfRelevantElts = NumElts; 12889 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 12890 SDValue Elt = N->getOperand(Idx); 12891 if (Elt->getOpcode() == ISD::BITCAST) { 12892 // Assume only bit cast to i32 will go away. 12893 if (Elt->getOperand(0).getValueType() == MVT::i32) 12894 ++NumOfBitCastedElts; 12895 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 12896 // Constants are statically casted, thus do not count them as 12897 // relevant operands. 12898 --NumOfRelevantElts; 12899 } 12900 12901 // Check if more than half of the elements require a non-free bitcast. 12902 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 12903 return SDValue(); 12904 12905 SelectionDAG &DAG = DCI.DAG; 12906 // Create the new vector type. 12907 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 12908 // Check if the type is legal. 12909 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12910 if (!TLI.isTypeLegal(VecVT)) 12911 return SDValue(); 12912 12913 // Combine: 12914 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 12915 // => BITCAST INSERT_VECTOR_ELT 12916 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 12917 // (BITCAST EN), N. 12918 SDValue Vec = DAG.getUNDEF(VecVT); 12919 SDLoc dl(N); 12920 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 12921 SDValue V = N->getOperand(Idx); 12922 if (V.isUndef()) 12923 continue; 12924 if (V.getOpcode() == ISD::BITCAST && 12925 V->getOperand(0).getValueType() == MVT::i32) 12926 // Fold obvious case. 12927 V = V.getOperand(0); 12928 else { 12929 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 12930 // Make the DAGCombiner fold the bitcasts. 12931 DCI.AddToWorklist(V.getNode()); 12932 } 12933 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 12934 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 12935 } 12936 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 12937 // Make the DAGCombiner fold the bitcasts. 12938 DCI.AddToWorklist(Vec.getNode()); 12939 return Vec; 12940 } 12941 12942 static SDValue 12943 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12944 EVT VT = N->getValueType(0); 12945 SDValue Op = N->getOperand(0); 12946 SDLoc dl(N); 12947 12948 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x) 12949 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) { 12950 // If the valuetypes are the same, we can remove the cast entirely. 12951 if (Op->getOperand(0).getValueType() == VT) 12952 return Op->getOperand(0); 12953 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, 12954 Op->getOperand(0).getValueType(), Op->getOperand(0)); 12955 } 12956 12957 return SDValue(); 12958 } 12959 12960 static SDValue 12961 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12962 const ARMSubtarget *ST) { 12963 EVT VT = N->getValueType(0); 12964 SDValue Op = N->getOperand(0); 12965 SDLoc dl(N); 12966 12967 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST 12968 if (ST->isLittle()) 12969 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op); 12970 12971 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x) 12972 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) { 12973 // If the valuetypes are the same, we can remove the cast entirely. 12974 if (Op->getOperand(0).getValueType() == VT) 12975 return Op->getOperand(0); 12976 return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0)); 12977 } 12978 12979 return SDValue(); 12980 } 12981 12982 static SDValue PerformVCMPCombine(SDNode *N, 12983 TargetLowering::DAGCombinerInfo &DCI, 12984 const ARMSubtarget *Subtarget) { 12985 if (!Subtarget->hasMVEIntegerOps()) 12986 return SDValue(); 12987 12988 EVT VT = N->getValueType(0); 12989 SDValue Op0 = N->getOperand(0); 12990 SDValue Op1 = N->getOperand(1); 12991 ARMCC::CondCodes Cond = 12992 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12993 SDLoc dl(N); 12994 12995 // vcmp X, 0, cc -> vcmpz X, cc 12996 if (isZeroVector(Op1)) 12997 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, 12998 N->getOperand(2)); 12999 13000 unsigned SwappedCond = getSwappedCondition(Cond); 13001 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) { 13002 // vcmp 0, X, cc -> vcmpz X, reversed(cc) 13003 if (isZeroVector(Op0)) 13004 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1, 13005 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13006 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc) 13007 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP) 13008 return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0, 13009 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13010 } 13011 13012 return SDValue(); 13013 } 13014 13015 /// PerformInsertEltCombine - Target-specific dag combine xforms for 13016 /// ISD::INSERT_VECTOR_ELT. 13017 static SDValue PerformInsertEltCombine(SDNode *N, 13018 TargetLowering::DAGCombinerInfo &DCI) { 13019 // Bitcast an i64 load inserted into a vector to f64. 13020 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13021 EVT VT = N->getValueType(0); 13022 SDNode *Elt = N->getOperand(1).getNode(); 13023 if (VT.getVectorElementType() != MVT::i64 || 13024 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 13025 return SDValue(); 13026 13027 SelectionDAG &DAG = DCI.DAG; 13028 SDLoc dl(N); 13029 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13030 VT.getVectorNumElements()); 13031 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 13032 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 13033 // Make the DAGCombiner fold the bitcasts. 13034 DCI.AddToWorklist(Vec.getNode()); 13035 DCI.AddToWorklist(V.getNode()); 13036 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 13037 Vec, V, N->getOperand(2)); 13038 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 13039 } 13040 13041 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 13042 /// ISD::VECTOR_SHUFFLE. 13043 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 13044 // The LLVM shufflevector instruction does not require the shuffle mask 13045 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 13046 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 13047 // operands do not match the mask length, they are extended by concatenating 13048 // them with undef vectors. That is probably the right thing for other 13049 // targets, but for NEON it is better to concatenate two double-register 13050 // size vector operands into a single quad-register size vector. Do that 13051 // transformation here: 13052 // shuffle(concat(v1, undef), concat(v2, undef)) -> 13053 // shuffle(concat(v1, v2), undef) 13054 SDValue Op0 = N->getOperand(0); 13055 SDValue Op1 = N->getOperand(1); 13056 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 13057 Op1.getOpcode() != ISD::CONCAT_VECTORS || 13058 Op0.getNumOperands() != 2 || 13059 Op1.getNumOperands() != 2) 13060 return SDValue(); 13061 SDValue Concat0Op1 = Op0.getOperand(1); 13062 SDValue Concat1Op1 = Op1.getOperand(1); 13063 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 13064 return SDValue(); 13065 // Skip the transformation if any of the types are illegal. 13066 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13067 EVT VT = N->getValueType(0); 13068 if (!TLI.isTypeLegal(VT) || 13069 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 13070 !TLI.isTypeLegal(Concat1Op1.getValueType())) 13071 return SDValue(); 13072 13073 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13074 Op0.getOperand(0), Op1.getOperand(0)); 13075 // Translate the shuffle mask. 13076 SmallVector<int, 16> NewMask; 13077 unsigned NumElts = VT.getVectorNumElements(); 13078 unsigned HalfElts = NumElts/2; 13079 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13080 for (unsigned n = 0; n < NumElts; ++n) { 13081 int MaskElt = SVN->getMaskElt(n); 13082 int NewElt = -1; 13083 if (MaskElt < (int)HalfElts) 13084 NewElt = MaskElt; 13085 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 13086 NewElt = HalfElts + MaskElt - NumElts; 13087 NewMask.push_back(NewElt); 13088 } 13089 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 13090 DAG.getUNDEF(VT), NewMask); 13091 } 13092 13093 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 13094 /// NEON load/store intrinsics, and generic vector load/stores, to merge 13095 /// base address updates. 13096 /// For generic load/stores, the memory type is assumed to be a vector. 13097 /// The caller is assumed to have checked legality. 13098 static SDValue CombineBaseUpdate(SDNode *N, 13099 TargetLowering::DAGCombinerInfo &DCI) { 13100 SelectionDAG &DAG = DCI.DAG; 13101 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 13102 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 13103 const bool isStore = N->getOpcode() == ISD::STORE; 13104 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 13105 SDValue Addr = N->getOperand(AddrOpIdx); 13106 MemSDNode *MemN = cast<MemSDNode>(N); 13107 SDLoc dl(N); 13108 13109 // Search for a use of the address operand that is an increment. 13110 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 13111 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 13112 SDNode *User = *UI; 13113 if (User->getOpcode() != ISD::ADD || 13114 UI.getUse().getResNo() != Addr.getResNo()) 13115 continue; 13116 13117 // Check that the add is independent of the load/store. Otherwise, folding 13118 // it would create a cycle. We can avoid searching through Addr as it's a 13119 // predecessor to both. 13120 SmallPtrSet<const SDNode *, 32> Visited; 13121 SmallVector<const SDNode *, 16> Worklist; 13122 Visited.insert(Addr.getNode()); 13123 Worklist.push_back(N); 13124 Worklist.push_back(User); 13125 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 13126 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 13127 continue; 13128 13129 // Find the new opcode for the updating load/store. 13130 bool isLoadOp = true; 13131 bool isLaneOp = false; 13132 unsigned NewOpc = 0; 13133 unsigned NumVecs = 0; 13134 if (isIntrinsic) { 13135 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 13136 switch (IntNo) { 13137 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 13138 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 13139 NumVecs = 1; break; 13140 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 13141 NumVecs = 2; break; 13142 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 13143 NumVecs = 3; break; 13144 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 13145 NumVecs = 4; break; 13146 case Intrinsic::arm_neon_vld2dup: 13147 case Intrinsic::arm_neon_vld3dup: 13148 case Intrinsic::arm_neon_vld4dup: 13149 // TODO: Support updating VLDxDUP nodes. For now, we just skip 13150 // combining base updates for such intrinsics. 13151 continue; 13152 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 13153 NumVecs = 2; isLaneOp = true; break; 13154 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 13155 NumVecs = 3; isLaneOp = true; break; 13156 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 13157 NumVecs = 4; isLaneOp = true; break; 13158 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 13159 NumVecs = 1; isLoadOp = false; break; 13160 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 13161 NumVecs = 2; isLoadOp = false; break; 13162 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 13163 NumVecs = 3; isLoadOp = false; break; 13164 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 13165 NumVecs = 4; isLoadOp = false; break; 13166 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 13167 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 13168 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 13169 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 13170 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 13171 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 13172 } 13173 } else { 13174 isLaneOp = true; 13175 switch (N->getOpcode()) { 13176 default: llvm_unreachable("unexpected opcode for Neon base update"); 13177 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 13178 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 13179 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 13180 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 13181 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 13182 NumVecs = 1; isLaneOp = false; break; 13183 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 13184 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 13185 } 13186 } 13187 13188 // Find the size of memory referenced by the load/store. 13189 EVT VecTy; 13190 if (isLoadOp) { 13191 VecTy = N->getValueType(0); 13192 } else if (isIntrinsic) { 13193 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 13194 } else { 13195 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 13196 VecTy = N->getOperand(1).getValueType(); 13197 } 13198 13199 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 13200 if (isLaneOp) 13201 NumBytes /= VecTy.getVectorNumElements(); 13202 13203 // If the increment is a constant, it must match the memory ref size. 13204 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 13205 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 13206 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 13207 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 13208 // separate instructions that make it harder to use a non-constant update. 13209 continue; 13210 } 13211 13212 // OK, we found an ADD we can fold into the base update. 13213 // Now, create a _UPD node, taking care of not breaking alignment. 13214 13215 EVT AlignedVecTy = VecTy; 13216 unsigned Alignment = MemN->getAlignment(); 13217 13218 // If this is a less-than-standard-aligned load/store, change the type to 13219 // match the standard alignment. 13220 // The alignment is overlooked when selecting _UPD variants; and it's 13221 // easier to introduce bitcasts here than fix that. 13222 // There are 3 ways to get to this base-update combine: 13223 // - intrinsics: they are assumed to be properly aligned (to the standard 13224 // alignment of the memory type), so we don't need to do anything. 13225 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 13226 // intrinsics, so, likewise, there's nothing to do. 13227 // - generic load/store instructions: the alignment is specified as an 13228 // explicit operand, rather than implicitly as the standard alignment 13229 // of the memory type (like the intrisics). We need to change the 13230 // memory type to match the explicit alignment. That way, we don't 13231 // generate non-standard-aligned ARMISD::VLDx nodes. 13232 if (isa<LSBaseSDNode>(N)) { 13233 if (Alignment == 0) 13234 Alignment = 1; 13235 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 13236 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 13237 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 13238 assert(!isLaneOp && "Unexpected generic load/store lane."); 13239 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 13240 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 13241 } 13242 // Don't set an explicit alignment on regular load/stores that we want 13243 // to transform to VLD/VST 1_UPD nodes. 13244 // This matches the behavior of regular load/stores, which only get an 13245 // explicit alignment if the MMO alignment is larger than the standard 13246 // alignment of the memory type. 13247 // Intrinsics, however, always get an explicit alignment, set to the 13248 // alignment of the MMO. 13249 Alignment = 1; 13250 } 13251 13252 // Create the new updating load/store node. 13253 // First, create an SDVTList for the new updating node's results. 13254 EVT Tys[6]; 13255 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 13256 unsigned n; 13257 for (n = 0; n < NumResultVecs; ++n) 13258 Tys[n] = AlignedVecTy; 13259 Tys[n++] = MVT::i32; 13260 Tys[n] = MVT::Other; 13261 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 13262 13263 // Then, gather the new node's operands. 13264 SmallVector<SDValue, 8> Ops; 13265 Ops.push_back(N->getOperand(0)); // incoming chain 13266 Ops.push_back(N->getOperand(AddrOpIdx)); 13267 Ops.push_back(Inc); 13268 13269 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 13270 // Try to match the intrinsic's signature 13271 Ops.push_back(StN->getValue()); 13272 } else { 13273 // Loads (and of course intrinsics) match the intrinsics' signature, 13274 // so just add all but the alignment operand. 13275 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 13276 Ops.push_back(N->getOperand(i)); 13277 } 13278 13279 // For all node types, the alignment operand is always the last one. 13280 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 13281 13282 // If this is a non-standard-aligned STORE, the penultimate operand is the 13283 // stored value. Bitcast it to the aligned type. 13284 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 13285 SDValue &StVal = Ops[Ops.size()-2]; 13286 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 13287 } 13288 13289 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 13290 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 13291 MemN->getMemOperand()); 13292 13293 // Update the uses. 13294 SmallVector<SDValue, 5> NewResults; 13295 for (unsigned i = 0; i < NumResultVecs; ++i) 13296 NewResults.push_back(SDValue(UpdN.getNode(), i)); 13297 13298 // If this is an non-standard-aligned LOAD, the first result is the loaded 13299 // value. Bitcast it to the expected result type. 13300 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 13301 SDValue &LdVal = NewResults[0]; 13302 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 13303 } 13304 13305 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 13306 DCI.CombineTo(N, NewResults); 13307 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 13308 13309 break; 13310 } 13311 return SDValue(); 13312 } 13313 13314 static SDValue PerformVLDCombine(SDNode *N, 13315 TargetLowering::DAGCombinerInfo &DCI) { 13316 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13317 return SDValue(); 13318 13319 return CombineBaseUpdate(N, DCI); 13320 } 13321 13322 static SDValue PerformMVEVLDCombine(SDNode *N, 13323 TargetLowering::DAGCombinerInfo &DCI) { 13324 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13325 return SDValue(); 13326 13327 SelectionDAG &DAG = DCI.DAG; 13328 SDValue Addr = N->getOperand(2); 13329 MemSDNode *MemN = cast<MemSDNode>(N); 13330 SDLoc dl(N); 13331 13332 // For the stores, where there are multiple intrinsics we only actually want 13333 // to post-inc the last of the them. 13334 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 13335 if (IntNo == Intrinsic::arm_mve_vst2q && 13336 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1) 13337 return SDValue(); 13338 if (IntNo == Intrinsic::arm_mve_vst4q && 13339 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3) 13340 return SDValue(); 13341 13342 // Search for a use of the address operand that is an increment. 13343 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 13344 UE = Addr.getNode()->use_end(); 13345 UI != UE; ++UI) { 13346 SDNode *User = *UI; 13347 if (User->getOpcode() != ISD::ADD || 13348 UI.getUse().getResNo() != Addr.getResNo()) 13349 continue; 13350 13351 // Check that the add is independent of the load/store. Otherwise, folding 13352 // it would create a cycle. We can avoid searching through Addr as it's a 13353 // predecessor to both. 13354 SmallPtrSet<const SDNode *, 32> Visited; 13355 SmallVector<const SDNode *, 16> Worklist; 13356 Visited.insert(Addr.getNode()); 13357 Worklist.push_back(N); 13358 Worklist.push_back(User); 13359 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 13360 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 13361 continue; 13362 13363 // Find the new opcode for the updating load/store. 13364 bool isLoadOp = true; 13365 unsigned NewOpc = 0; 13366 unsigned NumVecs = 0; 13367 switch (IntNo) { 13368 default: 13369 llvm_unreachable("unexpected intrinsic for MVE VLDn combine"); 13370 case Intrinsic::arm_mve_vld2q: 13371 NewOpc = ARMISD::VLD2_UPD; 13372 NumVecs = 2; 13373 break; 13374 case Intrinsic::arm_mve_vld4q: 13375 NewOpc = ARMISD::VLD4_UPD; 13376 NumVecs = 4; 13377 break; 13378 case Intrinsic::arm_mve_vst2q: 13379 NewOpc = ARMISD::VST2_UPD; 13380 NumVecs = 2; 13381 isLoadOp = false; 13382 break; 13383 case Intrinsic::arm_mve_vst4q: 13384 NewOpc = ARMISD::VST4_UPD; 13385 NumVecs = 4; 13386 isLoadOp = false; 13387 break; 13388 } 13389 13390 // Find the size of memory referenced by the load/store. 13391 EVT VecTy; 13392 if (isLoadOp) { 13393 VecTy = N->getValueType(0); 13394 } else { 13395 VecTy = N->getOperand(3).getValueType(); 13396 } 13397 13398 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 13399 13400 // If the increment is a constant, it must match the memory ref size. 13401 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 13402 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 13403 if (!CInc || CInc->getZExtValue() != NumBytes) 13404 continue; 13405 13406 // Create the new updating load/store node. 13407 // First, create an SDVTList for the new updating node's results. 13408 EVT Tys[6]; 13409 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 13410 unsigned n; 13411 for (n = 0; n < NumResultVecs; ++n) 13412 Tys[n] = VecTy; 13413 Tys[n++] = MVT::i32; 13414 Tys[n] = MVT::Other; 13415 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 13416 13417 // Then, gather the new node's operands. 13418 SmallVector<SDValue, 8> Ops; 13419 Ops.push_back(N->getOperand(0)); // incoming chain 13420 Ops.push_back(N->getOperand(2)); // ptr 13421 Ops.push_back(Inc); 13422 13423 for (unsigned i = 3; i < N->getNumOperands(); ++i) 13424 Ops.push_back(N->getOperand(i)); 13425 13426 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy, 13427 MemN->getMemOperand()); 13428 13429 // Update the uses. 13430 SmallVector<SDValue, 5> NewResults; 13431 for (unsigned i = 0; i < NumResultVecs; ++i) 13432 NewResults.push_back(SDValue(UpdN.getNode(), i)); 13433 13434 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain 13435 DCI.CombineTo(N, NewResults); 13436 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 13437 13438 break; 13439 } 13440 13441 return SDValue(); 13442 } 13443 13444 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 13445 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 13446 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 13447 /// return true. 13448 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13449 SelectionDAG &DAG = DCI.DAG; 13450 EVT VT = N->getValueType(0); 13451 // vldN-dup instructions only support 64-bit vectors for N > 1. 13452 if (!VT.is64BitVector()) 13453 return false; 13454 13455 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 13456 SDNode *VLD = N->getOperand(0).getNode(); 13457 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 13458 return false; 13459 unsigned NumVecs = 0; 13460 unsigned NewOpc = 0; 13461 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 13462 if (IntNo == Intrinsic::arm_neon_vld2lane) { 13463 NumVecs = 2; 13464 NewOpc = ARMISD::VLD2DUP; 13465 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 13466 NumVecs = 3; 13467 NewOpc = ARMISD::VLD3DUP; 13468 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 13469 NumVecs = 4; 13470 NewOpc = ARMISD::VLD4DUP; 13471 } else { 13472 return false; 13473 } 13474 13475 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 13476 // numbers match the load. 13477 unsigned VLDLaneNo = 13478 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 13479 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 13480 UI != UE; ++UI) { 13481 // Ignore uses of the chain result. 13482 if (UI.getUse().getResNo() == NumVecs) 13483 continue; 13484 SDNode *User = *UI; 13485 if (User->getOpcode() != ARMISD::VDUPLANE || 13486 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 13487 return false; 13488 } 13489 13490 // Create the vldN-dup node. 13491 EVT Tys[5]; 13492 unsigned n; 13493 for (n = 0; n < NumVecs; ++n) 13494 Tys[n] = VT; 13495 Tys[n] = MVT::Other; 13496 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 13497 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 13498 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 13499 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 13500 Ops, VLDMemInt->getMemoryVT(), 13501 VLDMemInt->getMemOperand()); 13502 13503 // Update the uses. 13504 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 13505 UI != UE; ++UI) { 13506 unsigned ResNo = UI.getUse().getResNo(); 13507 // Ignore uses of the chain result. 13508 if (ResNo == NumVecs) 13509 continue; 13510 SDNode *User = *UI; 13511 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 13512 } 13513 13514 // Now the vldN-lane intrinsic is dead except for its chain result. 13515 // Update uses of the chain. 13516 std::vector<SDValue> VLDDupResults; 13517 for (unsigned n = 0; n < NumVecs; ++n) 13518 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 13519 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 13520 DCI.CombineTo(VLD, VLDDupResults); 13521 13522 return true; 13523 } 13524 13525 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 13526 /// ARMISD::VDUPLANE. 13527 static SDValue PerformVDUPLANECombine(SDNode *N, 13528 TargetLowering::DAGCombinerInfo &DCI) { 13529 SDValue Op = N->getOperand(0); 13530 13531 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 13532 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 13533 if (CombineVLDDUP(N, DCI)) 13534 return SDValue(N, 0); 13535 13536 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 13537 // redundant. Ignore bit_converts for now; element sizes are checked below. 13538 while (Op.getOpcode() == ISD::BITCAST) 13539 Op = Op.getOperand(0); 13540 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 13541 return SDValue(); 13542 13543 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 13544 unsigned EltSize = Op.getScalarValueSizeInBits(); 13545 // The canonical VMOV for a zero vector uses a 32-bit element size. 13546 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13547 unsigned EltBits; 13548 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 13549 EltSize = 8; 13550 EVT VT = N->getValueType(0); 13551 if (EltSize > VT.getScalarSizeInBits()) 13552 return SDValue(); 13553 13554 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 13555 } 13556 13557 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 13558 static SDValue PerformVDUPCombine(SDNode *N, 13559 TargetLowering::DAGCombinerInfo &DCI, 13560 const ARMSubtarget *Subtarget) { 13561 SelectionDAG &DAG = DCI.DAG; 13562 SDValue Op = N->getOperand(0); 13563 13564 if (!Subtarget->hasNEON()) 13565 return SDValue(); 13566 13567 // Match VDUP(LOAD) -> VLD1DUP. 13568 // We match this pattern here rather than waiting for isel because the 13569 // transform is only legal for unindexed loads. 13570 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 13571 if (LD && Op.hasOneUse() && LD->isUnindexed() && 13572 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 13573 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 13574 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 13575 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 13576 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 13577 Ops, LD->getMemoryVT(), 13578 LD->getMemOperand()); 13579 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 13580 return VLDDup; 13581 } 13582 13583 return SDValue(); 13584 } 13585 13586 static SDValue PerformLOADCombine(SDNode *N, 13587 TargetLowering::DAGCombinerInfo &DCI) { 13588 EVT VT = N->getValueType(0); 13589 13590 // If this is a legal vector load, try to combine it into a VLD1_UPD. 13591 if (ISD::isNormalLoad(N) && VT.isVector() && 13592 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13593 return CombineBaseUpdate(N, DCI); 13594 13595 return SDValue(); 13596 } 13597 13598 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 13599 // pack all of the elements in one place. Next, store to memory in fewer 13600 // chunks. 13601 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St, 13602 SelectionDAG &DAG) { 13603 SDValue StVal = St->getValue(); 13604 EVT VT = StVal.getValueType(); 13605 if (!St->isTruncatingStore() || !VT.isVector()) 13606 return SDValue(); 13607 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13608 EVT StVT = St->getMemoryVT(); 13609 unsigned NumElems = VT.getVectorNumElements(); 13610 assert(StVT != VT && "Cannot truncate to the same type"); 13611 unsigned FromEltSz = VT.getScalarSizeInBits(); 13612 unsigned ToEltSz = StVT.getScalarSizeInBits(); 13613 13614 // From, To sizes and ElemCount must be pow of two 13615 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) 13616 return SDValue(); 13617 13618 // We are going to use the original vector elt for storing. 13619 // Accumulated smaller vector elements must be a multiple of the store size. 13620 if (0 != (NumElems * FromEltSz) % ToEltSz) 13621 return SDValue(); 13622 13623 unsigned SizeRatio = FromEltSz / ToEltSz; 13624 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 13625 13626 // Create a type on which we perform the shuffle. 13627 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 13628 NumElems * SizeRatio); 13629 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 13630 13631 SDLoc DL(St); 13632 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 13633 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 13634 for (unsigned i = 0; i < NumElems; ++i) 13635 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1 13636 : i * SizeRatio; 13637 13638 // Can't shuffle using an illegal type. 13639 if (!TLI.isTypeLegal(WideVecVT)) 13640 return SDValue(); 13641 13642 SDValue Shuff = DAG.getVectorShuffle( 13643 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec); 13644 // At this point all of the data is stored at the bottom of the 13645 // register. We now need to save it to mem. 13646 13647 // Find the largest store unit 13648 MVT StoreType = MVT::i8; 13649 for (MVT Tp : MVT::integer_valuetypes()) { 13650 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 13651 StoreType = Tp; 13652 } 13653 // Didn't find a legal store type. 13654 if (!TLI.isTypeLegal(StoreType)) 13655 return SDValue(); 13656 13657 // Bitcast the original vector into a vector of store-size units 13658 EVT StoreVecVT = 13659 EVT::getVectorVT(*DAG.getContext(), StoreType, 13660 VT.getSizeInBits() / EVT(StoreType).getSizeInBits()); 13661 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 13662 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 13663 SmallVector<SDValue, 8> Chains; 13664 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 13665 TLI.getPointerTy(DAG.getDataLayout())); 13666 SDValue BasePtr = St->getBasePtr(); 13667 13668 // Perform one or more big stores into memory. 13669 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits(); 13670 for (unsigned I = 0; I < E; I++) { 13671 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType, 13672 ShuffWide, DAG.getIntPtrConstant(I, DL)); 13673 SDValue Ch = 13674 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(), 13675 St->getAlignment(), St->getMemOperand()->getFlags()); 13676 BasePtr = 13677 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment); 13678 Chains.push_back(Ch); 13679 } 13680 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 13681 } 13682 13683 // Try taking a single vector store from an truncate (which would otherwise turn 13684 // into an expensive buildvector) and splitting it into a series of narrowing 13685 // stores. 13686 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, 13687 SelectionDAG &DAG) { 13688 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed()) 13689 return SDValue(); 13690 SDValue Trunc = St->getValue(); 13691 if (Trunc->getOpcode() != ISD::TRUNCATE) 13692 return SDValue(); 13693 EVT FromVT = Trunc->getOperand(0).getValueType(); 13694 EVT ToVT = Trunc.getValueType(); 13695 if (!ToVT.isVector()) 13696 return SDValue(); 13697 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 13698 EVT ToEltVT = ToVT.getVectorElementType(); 13699 EVT FromEltVT = FromVT.getVectorElementType(); 13700 13701 unsigned NumElements = 0; 13702 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8)) 13703 NumElements = 4; 13704 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8) 13705 NumElements = 8; 13706 if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements || 13707 FromVT.getVectorNumElements() % NumElements != 0) 13708 return SDValue(); 13709 13710 SDLoc DL(St); 13711 // Details about the old store 13712 SDValue Ch = St->getChain(); 13713 SDValue BasePtr = St->getBasePtr(); 13714 unsigned Alignment = St->getOriginalAlignment(); 13715 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags(); 13716 AAMDNodes AAInfo = St->getAAInfo(); 13717 13718 EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements); 13719 EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements); 13720 13721 SmallVector<SDValue, 4> Stores; 13722 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 13723 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8; 13724 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset); 13725 13726 SDValue Extract = 13727 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0), 13728 DAG.getConstant(i * NumElements, DL, MVT::i32)); 13729 SDValue Store = DAG.getTruncStore( 13730 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset), 13731 NewToVT, Alignment, MMOFlags, AAInfo); 13732 Stores.push_back(Store); 13733 } 13734 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores); 13735 } 13736 13737 /// PerformSTORECombine - Target-specific dag combine xforms for 13738 /// ISD::STORE. 13739 static SDValue PerformSTORECombine(SDNode *N, 13740 TargetLowering::DAGCombinerInfo &DCI, 13741 const ARMSubtarget *Subtarget) { 13742 StoreSDNode *St = cast<StoreSDNode>(N); 13743 if (St->isVolatile()) 13744 return SDValue(); 13745 SDValue StVal = St->getValue(); 13746 EVT VT = StVal.getValueType(); 13747 13748 if (Subtarget->hasNEON()) 13749 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG)) 13750 return Store; 13751 13752 if (Subtarget->hasMVEIntegerOps()) 13753 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG)) 13754 return NewToken; 13755 13756 if (!ISD::isNormalStore(St)) 13757 return SDValue(); 13758 13759 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 13760 // ARM stores of arguments in the same cache line. 13761 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 13762 StVal.getNode()->hasOneUse()) { 13763 SelectionDAG &DAG = DCI.DAG; 13764 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 13765 SDLoc DL(St); 13766 SDValue BasePtr = St->getBasePtr(); 13767 SDValue NewST1 = DAG.getStore( 13768 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 13769 BasePtr, St->getPointerInfo(), St->getAlignment(), 13770 St->getMemOperand()->getFlags()); 13771 13772 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 13773 DAG.getConstant(4, DL, MVT::i32)); 13774 return DAG.getStore(NewST1.getValue(0), DL, 13775 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 13776 OffsetPtr, St->getPointerInfo(), 13777 std::min(4U, St->getAlignment() / 2), 13778 St->getMemOperand()->getFlags()); 13779 } 13780 13781 if (StVal.getValueType() == MVT::i64 && 13782 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13783 13784 // Bitcast an i64 store extracted from a vector to f64. 13785 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13786 SelectionDAG &DAG = DCI.DAG; 13787 SDLoc dl(StVal); 13788 SDValue IntVec = StVal.getOperand(0); 13789 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13790 IntVec.getValueType().getVectorNumElements()); 13791 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 13792 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 13793 Vec, StVal.getOperand(1)); 13794 dl = SDLoc(N); 13795 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 13796 // Make the DAGCombiner fold the bitcasts. 13797 DCI.AddToWorklist(Vec.getNode()); 13798 DCI.AddToWorklist(ExtElt.getNode()); 13799 DCI.AddToWorklist(V.getNode()); 13800 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 13801 St->getPointerInfo(), St->getAlignment(), 13802 St->getMemOperand()->getFlags(), St->getAAInfo()); 13803 } 13804 13805 // If this is a legal vector store, try to combine it into a VST1_UPD. 13806 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() && 13807 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13808 return CombineBaseUpdate(N, DCI); 13809 13810 return SDValue(); 13811 } 13812 13813 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 13814 /// can replace combinations of VMUL and VCVT (floating-point to integer) 13815 /// when the VMUL has a constant operand that is a power of 2. 13816 /// 13817 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13818 /// vmul.f32 d16, d17, d16 13819 /// vcvt.s32.f32 d16, d16 13820 /// becomes: 13821 /// vcvt.s32.f32 d16, d16, #3 13822 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 13823 const ARMSubtarget *Subtarget) { 13824 if (!Subtarget->hasNEON()) 13825 return SDValue(); 13826 13827 SDValue Op = N->getOperand(0); 13828 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 13829 Op.getOpcode() != ISD::FMUL) 13830 return SDValue(); 13831 13832 SDValue ConstVec = Op->getOperand(1); 13833 if (!isa<BuildVectorSDNode>(ConstVec)) 13834 return SDValue(); 13835 13836 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 13837 uint32_t FloatBits = FloatTy.getSizeInBits(); 13838 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 13839 uint32_t IntBits = IntTy.getSizeInBits(); 13840 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13841 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13842 // These instructions only exist converting from f32 to i32. We can handle 13843 // smaller integers by generating an extra truncate, but larger ones would 13844 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13845 // these intructions only support v2i32/v4i32 types. 13846 return SDValue(); 13847 } 13848 13849 BitVector UndefElements; 13850 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13851 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13852 if (C == -1 || C == 0 || C > 32) 13853 return SDValue(); 13854 13855 SDLoc dl(N); 13856 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 13857 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 13858 Intrinsic::arm_neon_vcvtfp2fxu; 13859 SDValue FixConv = DAG.getNode( 13860 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13861 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 13862 DAG.getConstant(C, dl, MVT::i32)); 13863 13864 if (IntBits < FloatBits) 13865 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 13866 13867 return FixConv; 13868 } 13869 13870 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 13871 /// can replace combinations of VCVT (integer to floating-point) and VDIV 13872 /// when the VDIV has a constant operand that is a power of 2. 13873 /// 13874 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13875 /// vcvt.f32.s32 d16, d16 13876 /// vdiv.f32 d16, d17, d16 13877 /// becomes: 13878 /// vcvt.f32.s32 d16, d16, #3 13879 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 13880 const ARMSubtarget *Subtarget) { 13881 if (!Subtarget->hasNEON()) 13882 return SDValue(); 13883 13884 SDValue Op = N->getOperand(0); 13885 unsigned OpOpcode = Op.getNode()->getOpcode(); 13886 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 13887 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 13888 return SDValue(); 13889 13890 SDValue ConstVec = N->getOperand(1); 13891 if (!isa<BuildVectorSDNode>(ConstVec)) 13892 return SDValue(); 13893 13894 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 13895 uint32_t FloatBits = FloatTy.getSizeInBits(); 13896 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 13897 uint32_t IntBits = IntTy.getSizeInBits(); 13898 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13899 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13900 // These instructions only exist converting from i32 to f32. We can handle 13901 // smaller integers by generating an extra extend, but larger ones would 13902 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13903 // these intructions only support v2i32/v4i32 types. 13904 return SDValue(); 13905 } 13906 13907 BitVector UndefElements; 13908 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13909 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13910 if (C == -1 || C == 0 || C > 32) 13911 return SDValue(); 13912 13913 SDLoc dl(N); 13914 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 13915 SDValue ConvInput = Op.getOperand(0); 13916 if (IntBits < FloatBits) 13917 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 13918 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13919 ConvInput); 13920 13921 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 13922 Intrinsic::arm_neon_vcvtfxu2fp; 13923 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 13924 Op.getValueType(), 13925 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 13926 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 13927 } 13928 13929 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 13930 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 13931 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13932 switch (IntNo) { 13933 default: 13934 // Don't do anything for most intrinsics. 13935 break; 13936 13937 // Vector shifts: check for immediate versions and lower them. 13938 // Note: This is done during DAG combining instead of DAG legalizing because 13939 // the build_vectors for 64-bit vector element shift counts are generally 13940 // not legal, and it is hard to see their values after they get legalized to 13941 // loads from a constant pool. 13942 case Intrinsic::arm_neon_vshifts: 13943 case Intrinsic::arm_neon_vshiftu: 13944 case Intrinsic::arm_neon_vrshifts: 13945 case Intrinsic::arm_neon_vrshiftu: 13946 case Intrinsic::arm_neon_vrshiftn: 13947 case Intrinsic::arm_neon_vqshifts: 13948 case Intrinsic::arm_neon_vqshiftu: 13949 case Intrinsic::arm_neon_vqshiftsu: 13950 case Intrinsic::arm_neon_vqshiftns: 13951 case Intrinsic::arm_neon_vqshiftnu: 13952 case Intrinsic::arm_neon_vqshiftnsu: 13953 case Intrinsic::arm_neon_vqrshiftns: 13954 case Intrinsic::arm_neon_vqrshiftnu: 13955 case Intrinsic::arm_neon_vqrshiftnsu: { 13956 EVT VT = N->getOperand(1).getValueType(); 13957 int64_t Cnt; 13958 unsigned VShiftOpc = 0; 13959 13960 switch (IntNo) { 13961 case Intrinsic::arm_neon_vshifts: 13962 case Intrinsic::arm_neon_vshiftu: 13963 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 13964 VShiftOpc = ARMISD::VSHLIMM; 13965 break; 13966 } 13967 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 13968 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 13969 : ARMISD::VSHRuIMM); 13970 break; 13971 } 13972 return SDValue(); 13973 13974 case Intrinsic::arm_neon_vrshifts: 13975 case Intrinsic::arm_neon_vrshiftu: 13976 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 13977 break; 13978 return SDValue(); 13979 13980 case Intrinsic::arm_neon_vqshifts: 13981 case Intrinsic::arm_neon_vqshiftu: 13982 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13983 break; 13984 return SDValue(); 13985 13986 case Intrinsic::arm_neon_vqshiftsu: 13987 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13988 break; 13989 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 13990 13991 case Intrinsic::arm_neon_vrshiftn: 13992 case Intrinsic::arm_neon_vqshiftns: 13993 case Intrinsic::arm_neon_vqshiftnu: 13994 case Intrinsic::arm_neon_vqshiftnsu: 13995 case Intrinsic::arm_neon_vqrshiftns: 13996 case Intrinsic::arm_neon_vqrshiftnu: 13997 case Intrinsic::arm_neon_vqrshiftnsu: 13998 // Narrowing shifts require an immediate right shift. 13999 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 14000 break; 14001 llvm_unreachable("invalid shift count for narrowing vector shift " 14002 "intrinsic"); 14003 14004 default: 14005 llvm_unreachable("unhandled vector shift"); 14006 } 14007 14008 switch (IntNo) { 14009 case Intrinsic::arm_neon_vshifts: 14010 case Intrinsic::arm_neon_vshiftu: 14011 // Opcode already set above. 14012 break; 14013 case Intrinsic::arm_neon_vrshifts: 14014 VShiftOpc = ARMISD::VRSHRsIMM; 14015 break; 14016 case Intrinsic::arm_neon_vrshiftu: 14017 VShiftOpc = ARMISD::VRSHRuIMM; 14018 break; 14019 case Intrinsic::arm_neon_vrshiftn: 14020 VShiftOpc = ARMISD::VRSHRNIMM; 14021 break; 14022 case Intrinsic::arm_neon_vqshifts: 14023 VShiftOpc = ARMISD::VQSHLsIMM; 14024 break; 14025 case Intrinsic::arm_neon_vqshiftu: 14026 VShiftOpc = ARMISD::VQSHLuIMM; 14027 break; 14028 case Intrinsic::arm_neon_vqshiftsu: 14029 VShiftOpc = ARMISD::VQSHLsuIMM; 14030 break; 14031 case Intrinsic::arm_neon_vqshiftns: 14032 VShiftOpc = ARMISD::VQSHRNsIMM; 14033 break; 14034 case Intrinsic::arm_neon_vqshiftnu: 14035 VShiftOpc = ARMISD::VQSHRNuIMM; 14036 break; 14037 case Intrinsic::arm_neon_vqshiftnsu: 14038 VShiftOpc = ARMISD::VQSHRNsuIMM; 14039 break; 14040 case Intrinsic::arm_neon_vqrshiftns: 14041 VShiftOpc = ARMISD::VQRSHRNsIMM; 14042 break; 14043 case Intrinsic::arm_neon_vqrshiftnu: 14044 VShiftOpc = ARMISD::VQRSHRNuIMM; 14045 break; 14046 case Intrinsic::arm_neon_vqrshiftnsu: 14047 VShiftOpc = ARMISD::VQRSHRNsuIMM; 14048 break; 14049 } 14050 14051 SDLoc dl(N); 14052 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 14053 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 14054 } 14055 14056 case Intrinsic::arm_neon_vshiftins: { 14057 EVT VT = N->getOperand(1).getValueType(); 14058 int64_t Cnt; 14059 unsigned VShiftOpc = 0; 14060 14061 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 14062 VShiftOpc = ARMISD::VSLIIMM; 14063 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 14064 VShiftOpc = ARMISD::VSRIIMM; 14065 else { 14066 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 14067 } 14068 14069 SDLoc dl(N); 14070 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 14071 N->getOperand(1), N->getOperand(2), 14072 DAG.getConstant(Cnt, dl, MVT::i32)); 14073 } 14074 14075 case Intrinsic::arm_neon_vqrshifts: 14076 case Intrinsic::arm_neon_vqrshiftu: 14077 // No immediate versions of these to check for. 14078 break; 14079 } 14080 14081 return SDValue(); 14082 } 14083 14084 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 14085 /// lowers them. As with the vector shift intrinsics, this is done during DAG 14086 /// combining instead of DAG legalizing because the build_vectors for 64-bit 14087 /// vector element shift counts are generally not legal, and it is hard to see 14088 /// their values after they get legalized to loads from a constant pool. 14089 static SDValue PerformShiftCombine(SDNode *N, 14090 TargetLowering::DAGCombinerInfo &DCI, 14091 const ARMSubtarget *ST) { 14092 SelectionDAG &DAG = DCI.DAG; 14093 EVT VT = N->getValueType(0); 14094 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 14095 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 14096 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 14097 SDValue N1 = N->getOperand(1); 14098 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 14099 SDValue N0 = N->getOperand(0); 14100 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 14101 DAG.MaskedValueIsZero(N0.getOperand(0), 14102 APInt::getHighBitsSet(32, 16))) 14103 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 14104 } 14105 } 14106 14107 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 14108 N->getOperand(0)->getOpcode() == ISD::AND && 14109 N->getOperand(0)->hasOneUse()) { 14110 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14111 return SDValue(); 14112 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 14113 // usually show up because instcombine prefers to canonicalize it to 14114 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 14115 // out of GEP lowering in some cases. 14116 SDValue N0 = N->getOperand(0); 14117 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14118 if (!ShiftAmtNode) 14119 return SDValue(); 14120 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 14121 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14122 if (!AndMaskNode) 14123 return SDValue(); 14124 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 14125 // Don't transform uxtb/uxth. 14126 if (AndMask == 255 || AndMask == 65535) 14127 return SDValue(); 14128 if (isMask_32(AndMask)) { 14129 uint32_t MaskedBits = countLeadingZeros(AndMask); 14130 if (MaskedBits > ShiftAmt) { 14131 SDLoc DL(N); 14132 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 14133 DAG.getConstant(MaskedBits, DL, MVT::i32)); 14134 return DAG.getNode( 14135 ISD::SRL, DL, MVT::i32, SHL, 14136 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 14137 } 14138 } 14139 } 14140 14141 // Nothing to be done for scalar shifts. 14142 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14143 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 14144 return SDValue(); 14145 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 14146 return SDValue(); 14147 14148 int64_t Cnt; 14149 14150 switch (N->getOpcode()) { 14151 default: llvm_unreachable("unexpected shift opcode"); 14152 14153 case ISD::SHL: 14154 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 14155 SDLoc dl(N); 14156 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 14157 DAG.getConstant(Cnt, dl, MVT::i32)); 14158 } 14159 break; 14160 14161 case ISD::SRA: 14162 case ISD::SRL: 14163 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 14164 unsigned VShiftOpc = 14165 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 14166 SDLoc dl(N); 14167 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 14168 DAG.getConstant(Cnt, dl, MVT::i32)); 14169 } 14170 } 14171 return SDValue(); 14172 } 14173 14174 // Look for a sign/zero extend of a larger than legal load. This can be split 14175 // into two extending loads, which are simpler to deal with than an arbitrary 14176 // sign extend. 14177 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) { 14178 SDValue N0 = N->getOperand(0); 14179 if (N0.getOpcode() != ISD::LOAD) 14180 return SDValue(); 14181 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode()); 14182 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() || 14183 LD->getExtensionType() != ISD::NON_EXTLOAD) 14184 return SDValue(); 14185 EVT FromVT = LD->getValueType(0); 14186 EVT ToVT = N->getValueType(0); 14187 if (!ToVT.isVector()) 14188 return SDValue(); 14189 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 14190 EVT ToEltVT = ToVT.getVectorElementType(); 14191 EVT FromEltVT = FromVT.getVectorElementType(); 14192 14193 unsigned NumElements = 0; 14194 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8)) 14195 NumElements = 4; 14196 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8) 14197 NumElements = 8; 14198 if (NumElements == 0 || 14199 FromVT.getVectorNumElements() == NumElements || 14200 FromVT.getVectorNumElements() % NumElements != 0 || 14201 !isPowerOf2_32(NumElements)) 14202 return SDValue(); 14203 14204 SDLoc DL(LD); 14205 // Details about the old load 14206 SDValue Ch = LD->getChain(); 14207 SDValue BasePtr = LD->getBasePtr(); 14208 unsigned Alignment = LD->getOriginalAlignment(); 14209 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 14210 AAMDNodes AAInfo = LD->getAAInfo(); 14211 14212 ISD::LoadExtType NewExtType = 14213 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 14214 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType()); 14215 EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext()); 14216 EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext()); 14217 unsigned NewOffset = NewFromVT.getSizeInBits() / 8; 14218 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset); 14219 14220 // Split the load in half, each side of which is extended separately. This 14221 // is good enough, as legalisation will take it from there. They are either 14222 // already legal or they will be split further into something that is 14223 // legal. 14224 SDValue NewLoad1 = 14225 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset, 14226 LD->getPointerInfo(), NewFromVT, Alignment, MMOFlags, AAInfo); 14227 SDValue NewLoad2 = 14228 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset, 14229 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT, 14230 Alignment, MMOFlags, AAInfo); 14231 14232 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 14233 SDValue(NewLoad1.getNode(), 1), 14234 SDValue(NewLoad2.getNode(), 1)); 14235 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain); 14236 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2); 14237 } 14238 14239 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 14240 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 14241 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 14242 const ARMSubtarget *ST) { 14243 SDValue N0 = N->getOperand(0); 14244 14245 // Check for sign- and zero-extensions of vector extract operations of 8- and 14246 // 16-bit vector elements. NEON and MVE support these directly. They are 14247 // handled during DAG combining because type legalization will promote them 14248 // to 32-bit types and it is messy to recognize the operations after that. 14249 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) && 14250 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14251 SDValue Vec = N0.getOperand(0); 14252 SDValue Lane = N0.getOperand(1); 14253 EVT VT = N->getValueType(0); 14254 EVT EltVT = N0.getValueType(); 14255 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14256 14257 if (VT == MVT::i32 && 14258 (EltVT == MVT::i8 || EltVT == MVT::i16) && 14259 TLI.isTypeLegal(Vec.getValueType()) && 14260 isa<ConstantSDNode>(Lane)) { 14261 14262 unsigned Opc = 0; 14263 switch (N->getOpcode()) { 14264 default: llvm_unreachable("unexpected opcode"); 14265 case ISD::SIGN_EXTEND: 14266 Opc = ARMISD::VGETLANEs; 14267 break; 14268 case ISD::ZERO_EXTEND: 14269 case ISD::ANY_EXTEND: 14270 Opc = ARMISD::VGETLANEu; 14271 break; 14272 } 14273 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 14274 } 14275 } 14276 14277 if (ST->hasMVEIntegerOps()) 14278 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 14279 return NewLoad; 14280 14281 return SDValue(); 14282 } 14283 14284 static const APInt *isPowerOf2Constant(SDValue V) { 14285 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 14286 if (!C) 14287 return nullptr; 14288 const APInt *CV = &C->getAPIntValue(); 14289 return CV->isPowerOf2() ? CV : nullptr; 14290 } 14291 14292 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 14293 // If we have a CMOV, OR and AND combination such as: 14294 // if (x & CN) 14295 // y |= CM; 14296 // 14297 // And: 14298 // * CN is a single bit; 14299 // * All bits covered by CM are known zero in y 14300 // 14301 // Then we can convert this into a sequence of BFI instructions. This will 14302 // always be a win if CM is a single bit, will always be no worse than the 14303 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 14304 // three bits (due to the extra IT instruction). 14305 14306 SDValue Op0 = CMOV->getOperand(0); 14307 SDValue Op1 = CMOV->getOperand(1); 14308 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 14309 auto CC = CCNode->getAPIntValue().getLimitedValue(); 14310 SDValue CmpZ = CMOV->getOperand(4); 14311 14312 // The compare must be against zero. 14313 if (!isNullConstant(CmpZ->getOperand(1))) 14314 return SDValue(); 14315 14316 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 14317 SDValue And = CmpZ->getOperand(0); 14318 if (And->getOpcode() != ISD::AND) 14319 return SDValue(); 14320 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 14321 if (!AndC) 14322 return SDValue(); 14323 SDValue X = And->getOperand(0); 14324 14325 if (CC == ARMCC::EQ) { 14326 // We're performing an "equal to zero" compare. Swap the operands so we 14327 // canonicalize on a "not equal to zero" compare. 14328 std::swap(Op0, Op1); 14329 } else { 14330 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 14331 } 14332 14333 if (Op1->getOpcode() != ISD::OR) 14334 return SDValue(); 14335 14336 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 14337 if (!OrC) 14338 return SDValue(); 14339 SDValue Y = Op1->getOperand(0); 14340 14341 if (Op0 != Y) 14342 return SDValue(); 14343 14344 // Now, is it profitable to continue? 14345 APInt OrCI = OrC->getAPIntValue(); 14346 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 14347 if (OrCI.countPopulation() > Heuristic) 14348 return SDValue(); 14349 14350 // Lastly, can we determine that the bits defined by OrCI 14351 // are zero in Y? 14352 KnownBits Known = DAG.computeKnownBits(Y); 14353 if ((OrCI & Known.Zero) != OrCI) 14354 return SDValue(); 14355 14356 // OK, we can do the combine. 14357 SDValue V = Y; 14358 SDLoc dl(X); 14359 EVT VT = X.getValueType(); 14360 unsigned BitInX = AndC->logBase2(); 14361 14362 if (BitInX != 0) { 14363 // We must shift X first. 14364 X = DAG.getNode(ISD::SRL, dl, VT, X, 14365 DAG.getConstant(BitInX, dl, VT)); 14366 } 14367 14368 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 14369 BitInY < NumActiveBits; ++BitInY) { 14370 if (OrCI[BitInY] == 0) 14371 continue; 14372 APInt Mask(VT.getSizeInBits(), 0); 14373 Mask.setBit(BitInY); 14374 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 14375 // Confusingly, the operand is an *inverted* mask. 14376 DAG.getConstant(~Mask, dl, VT)); 14377 } 14378 14379 return V; 14380 } 14381 14382 // Given N, the value controlling the conditional branch, search for the loop 14383 // intrinsic, returning it, along with how the value is used. We need to handle 14384 // patterns such as the following: 14385 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 14386 // (brcond (setcc (loop.decrement), 0, eq), exit) 14387 // (brcond (setcc (loop.decrement), 0, ne), header) 14388 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 14389 bool &Negate) { 14390 switch (N->getOpcode()) { 14391 default: 14392 break; 14393 case ISD::XOR: { 14394 if (!isa<ConstantSDNode>(N.getOperand(1))) 14395 return SDValue(); 14396 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 14397 return SDValue(); 14398 Negate = !Negate; 14399 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 14400 } 14401 case ISD::SETCC: { 14402 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 14403 if (!Const) 14404 return SDValue(); 14405 if (Const->isNullValue()) 14406 Imm = 0; 14407 else if (Const->isOne()) 14408 Imm = 1; 14409 else 14410 return SDValue(); 14411 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 14412 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 14413 } 14414 case ISD::INTRINSIC_W_CHAIN: { 14415 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 14416 if (IntOp != Intrinsic::test_set_loop_iterations && 14417 IntOp != Intrinsic::loop_decrement_reg) 14418 return SDValue(); 14419 return N; 14420 } 14421 } 14422 return SDValue(); 14423 } 14424 14425 static SDValue PerformHWLoopCombine(SDNode *N, 14426 TargetLowering::DAGCombinerInfo &DCI, 14427 const ARMSubtarget *ST) { 14428 14429 // The hwloop intrinsics that we're interested are used for control-flow, 14430 // either for entering or exiting the loop: 14431 // - test.set.loop.iterations will test whether its operand is zero. If it 14432 // is zero, the proceeding branch should not enter the loop. 14433 // - loop.decrement.reg also tests whether its operand is zero. If it is 14434 // zero, the proceeding branch should not branch back to the beginning of 14435 // the loop. 14436 // So here, we need to check that how the brcond is using the result of each 14437 // of the intrinsics to ensure that we're branching to the right place at the 14438 // right time. 14439 14440 ISD::CondCode CC; 14441 SDValue Cond; 14442 int Imm = 1; 14443 bool Negate = false; 14444 SDValue Chain = N->getOperand(0); 14445 SDValue Dest; 14446 14447 if (N->getOpcode() == ISD::BRCOND) { 14448 CC = ISD::SETEQ; 14449 Cond = N->getOperand(1); 14450 Dest = N->getOperand(2); 14451 } else { 14452 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 14453 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14454 Cond = N->getOperand(2); 14455 Dest = N->getOperand(4); 14456 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 14457 if (!Const->isOne() && !Const->isNullValue()) 14458 return SDValue(); 14459 Imm = Const->getZExtValue(); 14460 } else 14461 return SDValue(); 14462 } 14463 14464 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 14465 if (!Int) 14466 return SDValue(); 14467 14468 if (Negate) 14469 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32); 14470 14471 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 14472 return (CC == ISD::SETEQ && Imm == 0) || 14473 (CC == ISD::SETNE && Imm == 1) || 14474 (CC == ISD::SETLT && Imm == 1) || 14475 (CC == ISD::SETULT && Imm == 1); 14476 }; 14477 14478 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 14479 return (CC == ISD::SETEQ && Imm == 1) || 14480 (CC == ISD::SETNE && Imm == 0) || 14481 (CC == ISD::SETGT && Imm == 0) || 14482 (CC == ISD::SETUGT && Imm == 0) || 14483 (CC == ISD::SETGE && Imm == 1) || 14484 (CC == ISD::SETUGE && Imm == 1); 14485 }; 14486 14487 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 14488 "unsupported condition"); 14489 14490 SDLoc dl(Int); 14491 SelectionDAG &DAG = DCI.DAG; 14492 SDValue Elements = Int.getOperand(2); 14493 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 14494 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 14495 && "expected single br user"); 14496 SDNode *Br = *N->use_begin(); 14497 SDValue OtherTarget = Br->getOperand(1); 14498 14499 // Update the unconditional branch to branch to the given Dest. 14500 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 14501 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 14502 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 14503 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 14504 }; 14505 14506 if (IntOp == Intrinsic::test_set_loop_iterations) { 14507 SDValue Res; 14508 // We expect this 'instruction' to branch when the counter is zero. 14509 if (IsTrueIfZero(CC, Imm)) { 14510 SDValue Ops[] = { Chain, Elements, Dest }; 14511 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 14512 } else { 14513 // The logic is the reverse of what we need for WLS, so find the other 14514 // basic block target: the target of the proceeding br. 14515 UpdateUncondBr(Br, Dest, DAG); 14516 14517 SDValue Ops[] = { Chain, Elements, OtherTarget }; 14518 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 14519 } 14520 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 14521 return Res; 14522 } else { 14523 SDValue Size = DAG.getTargetConstant( 14524 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 14525 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 14526 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 14527 DAG.getVTList(MVT::i32, MVT::Other), Args); 14528 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 14529 14530 // We expect this instruction to branch when the count is not zero. 14531 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 14532 14533 // Update the unconditional branch to target the loop preheader if we've 14534 // found the condition has been reversed. 14535 if (Target == OtherTarget) 14536 UpdateUncondBr(Br, Dest, DAG); 14537 14538 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14539 SDValue(LoopDec.getNode(), 1), Chain); 14540 14541 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 14542 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 14543 } 14544 return SDValue(); 14545 } 14546 14547 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 14548 SDValue 14549 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 14550 SDValue Cmp = N->getOperand(4); 14551 if (Cmp.getOpcode() != ARMISD::CMPZ) 14552 // Only looking at NE cases. 14553 return SDValue(); 14554 14555 EVT VT = N->getValueType(0); 14556 SDLoc dl(N); 14557 SDValue LHS = Cmp.getOperand(0); 14558 SDValue RHS = Cmp.getOperand(1); 14559 SDValue Chain = N->getOperand(0); 14560 SDValue BB = N->getOperand(1); 14561 SDValue ARMcc = N->getOperand(2); 14562 ARMCC::CondCodes CC = 14563 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 14564 14565 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 14566 // -> (brcond Chain BB CC CPSR Cmp) 14567 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 14568 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 14569 LHS->getOperand(0)->hasOneUse()) { 14570 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 14571 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 14572 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 14573 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 14574 if ((LHS00C && LHS00C->getZExtValue() == 0) && 14575 (LHS01C && LHS01C->getZExtValue() == 1) && 14576 (LHS1C && LHS1C->getZExtValue() == 1) && 14577 (RHSC && RHSC->getZExtValue() == 0)) { 14578 return DAG.getNode( 14579 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 14580 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 14581 } 14582 } 14583 14584 return SDValue(); 14585 } 14586 14587 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 14588 SDValue 14589 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 14590 SDValue Cmp = N->getOperand(4); 14591 if (Cmp.getOpcode() != ARMISD::CMPZ) 14592 // Only looking at EQ and NE cases. 14593 return SDValue(); 14594 14595 EVT VT = N->getValueType(0); 14596 SDLoc dl(N); 14597 SDValue LHS = Cmp.getOperand(0); 14598 SDValue RHS = Cmp.getOperand(1); 14599 SDValue FalseVal = N->getOperand(0); 14600 SDValue TrueVal = N->getOperand(1); 14601 SDValue ARMcc = N->getOperand(2); 14602 ARMCC::CondCodes CC = 14603 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 14604 14605 // BFI is only available on V6T2+. 14606 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 14607 SDValue R = PerformCMOVToBFICombine(N, DAG); 14608 if (R) 14609 return R; 14610 } 14611 14612 // Simplify 14613 // mov r1, r0 14614 // cmp r1, x 14615 // mov r0, y 14616 // moveq r0, x 14617 // to 14618 // cmp r0, x 14619 // movne r0, y 14620 // 14621 // mov r1, r0 14622 // cmp r1, x 14623 // mov r0, x 14624 // movne r0, y 14625 // to 14626 // cmp r0, x 14627 // movne r0, y 14628 /// FIXME: Turn this into a target neutral optimization? 14629 SDValue Res; 14630 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 14631 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 14632 N->getOperand(3), Cmp); 14633 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 14634 SDValue ARMcc; 14635 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 14636 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 14637 N->getOperand(3), NewCmp); 14638 } 14639 14640 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 14641 // -> (cmov F T CC CPSR Cmp) 14642 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 14643 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 14644 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 14645 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 14646 if ((LHS0C && LHS0C->getZExtValue() == 0) && 14647 (LHS1C && LHS1C->getZExtValue() == 1) && 14648 (RHSC && RHSC->getZExtValue() == 0)) { 14649 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 14650 LHS->getOperand(2), LHS->getOperand(3), 14651 LHS->getOperand(4)); 14652 } 14653 } 14654 14655 if (!VT.isInteger()) 14656 return SDValue(); 14657 14658 // Materialize a boolean comparison for integers so we can avoid branching. 14659 if (isNullConstant(FalseVal)) { 14660 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 14661 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 14662 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 14663 // right 5 bits will make that 32 be 1, otherwise it will be 0. 14664 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 14665 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 14666 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 14667 DAG.getConstant(5, dl, MVT::i32)); 14668 } else { 14669 // CMOV 0, 1, ==, (CMPZ x, y) -> 14670 // (ADDCARRY (SUB x, y), t:0, t:1) 14671 // where t = (SUBCARRY 0, (SUB x, y), 0) 14672 // 14673 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 14674 // x != y. In other words, a carry C == 1 when x == y, C == 0 14675 // otherwise. 14676 // The final ADDCARRY computes 14677 // x - y + (0 - (x - y)) + C == C 14678 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 14679 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 14680 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 14681 // ISD::SUBCARRY returns a borrow but we want the carry here 14682 // actually. 14683 SDValue Carry = 14684 DAG.getNode(ISD::SUB, dl, MVT::i32, 14685 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 14686 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 14687 } 14688 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 14689 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 14690 // This seems pointless but will allow us to combine it further below. 14691 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 14692 SDValue Sub = 14693 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 14694 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 14695 Sub.getValue(1), SDValue()); 14696 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 14697 N->getOperand(3), CPSRGlue.getValue(1)); 14698 FalseVal = Sub; 14699 } 14700 } else if (isNullConstant(TrueVal)) { 14701 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 14702 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 14703 // This seems pointless but will allow us to combine it further below 14704 // Note that we change == for != as this is the dual for the case above. 14705 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 14706 SDValue Sub = 14707 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 14708 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 14709 Sub.getValue(1), SDValue()); 14710 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 14711 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 14712 N->getOperand(3), CPSRGlue.getValue(1)); 14713 FalseVal = Sub; 14714 } 14715 } 14716 14717 // On Thumb1, the DAG above may be further combined if z is a power of 2 14718 // (z == 2 ^ K). 14719 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 14720 // t1 = (USUBO (SUB x, y), 1) 14721 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 14722 // Result = if K != 0 then (SHL t2:0, K) else t2:0 14723 // 14724 // This also handles the special case of comparing against zero; it's 14725 // essentially, the same pattern, except there's no SUBS: 14726 // CMOV x, z, !=, (CMPZ x, 0) -> 14727 // t1 = (USUBO x, 1) 14728 // t2 = (SUBCARRY x, t1:0, t1:1) 14729 // Result = if K != 0 then (SHL t2:0, K) else t2:0 14730 const APInt *TrueConst; 14731 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 14732 ((FalseVal.getOpcode() == ARMISD::SUBS && 14733 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 14734 (FalseVal == LHS && isNullConstant(RHS))) && 14735 (TrueConst = isPowerOf2Constant(TrueVal))) { 14736 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 14737 unsigned ShiftAmount = TrueConst->logBase2(); 14738 if (ShiftAmount) 14739 TrueVal = DAG.getConstant(1, dl, VT); 14740 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 14741 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 14742 14743 if (ShiftAmount) 14744 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 14745 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 14746 } 14747 14748 if (Res.getNode()) { 14749 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 14750 // Capture demanded bits information that would be otherwise lost. 14751 if (Known.Zero == 0xfffffffe) 14752 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 14753 DAG.getValueType(MVT::i1)); 14754 else if (Known.Zero == 0xffffff00) 14755 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 14756 DAG.getValueType(MVT::i8)); 14757 else if (Known.Zero == 0xffff0000) 14758 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 14759 DAG.getValueType(MVT::i16)); 14760 } 14761 14762 return Res; 14763 } 14764 14765 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 14766 DAGCombinerInfo &DCI) const { 14767 switch (N->getOpcode()) { 14768 default: break; 14769 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 14770 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 14771 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 14772 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 14773 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget); 14774 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 14775 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 14776 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 14777 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 14778 case ISD::BRCOND: 14779 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 14780 case ARMISD::ADDC: 14781 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 14782 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 14783 case ARMISD::BFI: return PerformBFICombine(N, DCI); 14784 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 14785 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 14786 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget); 14787 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 14788 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 14789 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 14790 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 14791 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 14792 case ISD::FP_TO_SINT: 14793 case ISD::FP_TO_UINT: 14794 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 14795 case ISD::FDIV: 14796 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 14797 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 14798 case ISD::SHL: 14799 case ISD::SRA: 14800 case ISD::SRL: 14801 return PerformShiftCombine(N, DCI, Subtarget); 14802 case ISD::SIGN_EXTEND: 14803 case ISD::ZERO_EXTEND: 14804 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 14805 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 14806 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 14807 case ISD::LOAD: return PerformLOADCombine(N, DCI); 14808 case ARMISD::VLD1DUP: 14809 case ARMISD::VLD2DUP: 14810 case ARMISD::VLD3DUP: 14811 case ARMISD::VLD4DUP: 14812 return PerformVLDCombine(N, DCI); 14813 case ARMISD::BUILD_VECTOR: 14814 return PerformARMBUILD_VECTORCombine(N, DCI); 14815 case ARMISD::PREDICATE_CAST: 14816 return PerformPREDICATE_CASTCombine(N, DCI); 14817 case ARMISD::VECTOR_REG_CAST: 14818 return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget); 14819 case ARMISD::VCMP: 14820 return PerformVCMPCombine(N, DCI, Subtarget); 14821 case ARMISD::SMULWB: { 14822 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14823 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 14824 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 14825 return SDValue(); 14826 break; 14827 } 14828 case ARMISD::SMULWT: { 14829 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14830 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 14831 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 14832 return SDValue(); 14833 break; 14834 } 14835 case ARMISD::SMLALBB: 14836 case ARMISD::QADD16b: 14837 case ARMISD::QSUB16b: { 14838 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14839 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 14840 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 14841 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 14842 return SDValue(); 14843 break; 14844 } 14845 case ARMISD::SMLALBT: { 14846 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 14847 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 14848 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 14849 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 14850 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 14851 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 14852 return SDValue(); 14853 break; 14854 } 14855 case ARMISD::SMLALTB: { 14856 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 14857 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 14858 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 14859 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 14860 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 14861 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 14862 return SDValue(); 14863 break; 14864 } 14865 case ARMISD::SMLALTT: { 14866 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14867 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 14868 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 14869 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 14870 return SDValue(); 14871 break; 14872 } 14873 case ARMISD::QADD8b: 14874 case ARMISD::QSUB8b: { 14875 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14876 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8); 14877 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 14878 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 14879 return SDValue(); 14880 break; 14881 } 14882 case ISD::INTRINSIC_VOID: 14883 case ISD::INTRINSIC_W_CHAIN: 14884 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14885 case Intrinsic::arm_neon_vld1: 14886 case Intrinsic::arm_neon_vld1x2: 14887 case Intrinsic::arm_neon_vld1x3: 14888 case Intrinsic::arm_neon_vld1x4: 14889 case Intrinsic::arm_neon_vld2: 14890 case Intrinsic::arm_neon_vld3: 14891 case Intrinsic::arm_neon_vld4: 14892 case Intrinsic::arm_neon_vld2lane: 14893 case Intrinsic::arm_neon_vld3lane: 14894 case Intrinsic::arm_neon_vld4lane: 14895 case Intrinsic::arm_neon_vld2dup: 14896 case Intrinsic::arm_neon_vld3dup: 14897 case Intrinsic::arm_neon_vld4dup: 14898 case Intrinsic::arm_neon_vst1: 14899 case Intrinsic::arm_neon_vst1x2: 14900 case Intrinsic::arm_neon_vst1x3: 14901 case Intrinsic::arm_neon_vst1x4: 14902 case Intrinsic::arm_neon_vst2: 14903 case Intrinsic::arm_neon_vst3: 14904 case Intrinsic::arm_neon_vst4: 14905 case Intrinsic::arm_neon_vst2lane: 14906 case Intrinsic::arm_neon_vst3lane: 14907 case Intrinsic::arm_neon_vst4lane: 14908 return PerformVLDCombine(N, DCI); 14909 case Intrinsic::arm_mve_vld2q: 14910 case Intrinsic::arm_mve_vld4q: 14911 case Intrinsic::arm_mve_vst2q: 14912 case Intrinsic::arm_mve_vst4q: 14913 return PerformMVEVLDCombine(N, DCI); 14914 default: break; 14915 } 14916 break; 14917 } 14918 return SDValue(); 14919 } 14920 14921 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 14922 EVT VT) const { 14923 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 14924 } 14925 14926 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 14927 unsigned Alignment, 14928 MachineMemOperand::Flags, 14929 bool *Fast) const { 14930 // Depends what it gets converted into if the type is weird. 14931 if (!VT.isSimple()) 14932 return false; 14933 14934 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus 14935 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 14936 auto Ty = VT.getSimpleVT().SimpleTy; 14937 14938 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 14939 // Unaligned access can use (for example) LRDB, LRDH, LDR 14940 if (AllowsUnaligned) { 14941 if (Fast) 14942 *Fast = Subtarget->hasV7Ops(); 14943 return true; 14944 } 14945 } 14946 14947 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 14948 // For any little-endian targets with neon, we can support unaligned ld/st 14949 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 14950 // A big-endian target may also explicitly support unaligned accesses 14951 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 14952 if (Fast) 14953 *Fast = true; 14954 return true; 14955 } 14956 } 14957 14958 if (!Subtarget->hasMVEIntegerOps()) 14959 return false; 14960 14961 // These are for predicates 14962 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 14963 if (Fast) 14964 *Fast = true; 14965 return true; 14966 } 14967 14968 // These are for truncated stores/narrowing loads. They are fine so long as 14969 // the alignment is at least the size of the item being loaded 14970 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 14971 Alignment >= VT.getScalarSizeInBits() / 8) { 14972 if (Fast) 14973 *Fast = true; 14974 return true; 14975 } 14976 14977 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 14978 // VSTRW.U32 all store the vector register in exactly the same format, and 14979 // differ only in the range of their immediate offset field and the required 14980 // alignment. So there is always a store that can be used, regardless of 14981 // actual type. 14982 // 14983 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 14984 // VREV64.8) pair and get the same effect. This will likely be better than 14985 // aligning the vector through the stack. 14986 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 14987 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 14988 Ty == MVT::v2f64) { 14989 if (Fast) 14990 *Fast = true; 14991 return true; 14992 } 14993 14994 return false; 14995 } 14996 14997 14998 EVT ARMTargetLowering::getOptimalMemOpType( 14999 const MemOp &Op, const AttributeList &FuncAttributes) const { 15000 // See if we can use NEON instructions for this... 15001 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() && 15002 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15003 bool Fast; 15004 if (Op.size() >= 16 && 15005 (Op.isAligned(Align(16)) || 15006 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 15007 MachineMemOperand::MONone, &Fast) && 15008 Fast))) { 15009 return MVT::v2f64; 15010 } else if (Op.size() >= 8 && 15011 (Op.isAligned(Align(8)) || 15012 (allowsMisalignedMemoryAccesses( 15013 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 15014 Fast))) { 15015 return MVT::f64; 15016 } 15017 } 15018 15019 // Let the target-independent logic figure it out. 15020 return MVT::Other; 15021 } 15022 15023 // 64-bit integers are split into their high and low parts and held in two 15024 // different registers, so the trunc is free since the low register can just 15025 // be used. 15026 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 15027 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 15028 return false; 15029 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 15030 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 15031 return (SrcBits == 64 && DestBits == 32); 15032 } 15033 15034 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 15035 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 15036 !DstVT.isInteger()) 15037 return false; 15038 unsigned SrcBits = SrcVT.getSizeInBits(); 15039 unsigned DestBits = DstVT.getSizeInBits(); 15040 return (SrcBits == 64 && DestBits == 32); 15041 } 15042 15043 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15044 if (Val.getOpcode() != ISD::LOAD) 15045 return false; 15046 15047 EVT VT1 = Val.getValueType(); 15048 if (!VT1.isSimple() || !VT1.isInteger() || 15049 !VT2.isSimple() || !VT2.isInteger()) 15050 return false; 15051 15052 switch (VT1.getSimpleVT().SimpleTy) { 15053 default: break; 15054 case MVT::i1: 15055 case MVT::i8: 15056 case MVT::i16: 15057 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 15058 return true; 15059 } 15060 15061 return false; 15062 } 15063 15064 bool ARMTargetLowering::isFNegFree(EVT VT) const { 15065 if (!VT.isSimple()) 15066 return false; 15067 15068 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 15069 // negate values directly (fneg is free). So, we don't want to let the DAG 15070 // combiner rewrite fneg into xors and some other instructions. For f16 and 15071 // FullFP16 argument passing, some bitcast nodes may be introduced, 15072 // triggering this DAG combine rewrite, so we are avoiding that with this. 15073 switch (VT.getSimpleVT().SimpleTy) { 15074 default: break; 15075 case MVT::f16: 15076 return Subtarget->hasFullFP16(); 15077 } 15078 15079 return false; 15080 } 15081 15082 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 15083 /// of the vector elements. 15084 static bool areExtractExts(Value *Ext1, Value *Ext2) { 15085 auto areExtDoubled = [](Instruction *Ext) { 15086 return Ext->getType()->getScalarSizeInBits() == 15087 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 15088 }; 15089 15090 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 15091 !match(Ext2, m_ZExtOrSExt(m_Value())) || 15092 !areExtDoubled(cast<Instruction>(Ext1)) || 15093 !areExtDoubled(cast<Instruction>(Ext2))) 15094 return false; 15095 15096 return true; 15097 } 15098 15099 /// Check if sinking \p I's operands to I's basic block is profitable, because 15100 /// the operands can be folded into a target instruction, e.g. 15101 /// sext/zext can be folded into vsubl. 15102 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 15103 SmallVectorImpl<Use *> &Ops) const { 15104 if (!I->getType()->isVectorTy()) 15105 return false; 15106 15107 if (Subtarget->hasNEON()) { 15108 switch (I->getOpcode()) { 15109 case Instruction::Sub: 15110 case Instruction::Add: { 15111 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 15112 return false; 15113 Ops.push_back(&I->getOperandUse(0)); 15114 Ops.push_back(&I->getOperandUse(1)); 15115 return true; 15116 } 15117 default: 15118 return false; 15119 } 15120 } 15121 15122 if (!Subtarget->hasMVEIntegerOps()) 15123 return false; 15124 15125 auto IsSinker = [](Instruction *I, int Operand) { 15126 switch (I->getOpcode()) { 15127 case Instruction::Add: 15128 case Instruction::Mul: 15129 case Instruction::ICmp: 15130 return true; 15131 case Instruction::Sub: 15132 case Instruction::Shl: 15133 case Instruction::LShr: 15134 case Instruction::AShr: 15135 return Operand == 1; 15136 default: 15137 return false; 15138 } 15139 }; 15140 15141 int Op = 0; 15142 if (!isa<ShuffleVectorInst>(I->getOperand(Op))) 15143 Op = 1; 15144 if (!IsSinker(I, Op)) 15145 return false; 15146 if (!match(I->getOperand(Op), 15147 m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()), 15148 m_Undef(), m_Zero()))) { 15149 return false; 15150 } 15151 Instruction *Shuffle = cast<Instruction>(I->getOperand(Op)); 15152 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 15153 // and vector registers 15154 for (Use &U : Shuffle->uses()) { 15155 Instruction *Insn = cast<Instruction>(U.getUser()); 15156 if (!IsSinker(Insn, U.getOperandNo())) 15157 return false; 15158 } 15159 Ops.push_back(&Shuffle->getOperandUse(0)); 15160 Ops.push_back(&I->getOperandUse(Op)); 15161 return true; 15162 } 15163 15164 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 15165 EVT VT = ExtVal.getValueType(); 15166 15167 if (!isTypeLegal(VT)) 15168 return false; 15169 15170 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) { 15171 if (Ld->isExpandingLoad()) 15172 return false; 15173 } 15174 15175 // Don't create a loadext if we can fold the extension into a wide/long 15176 // instruction. 15177 // If there's more than one user instruction, the loadext is desirable no 15178 // matter what. There can be two uses by the same instruction. 15179 if (ExtVal->use_empty() || 15180 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 15181 return true; 15182 15183 SDNode *U = *ExtVal->use_begin(); 15184 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 15185 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 15186 return false; 15187 15188 return true; 15189 } 15190 15191 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 15192 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15193 return false; 15194 15195 if (!isTypeLegal(EVT::getEVT(Ty1))) 15196 return false; 15197 15198 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 15199 15200 // Assuming the caller doesn't have a zeroext or signext return parameter, 15201 // truncation all the way down to i1 is valid. 15202 return true; 15203 } 15204 15205 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 15206 const AddrMode &AM, Type *Ty, 15207 unsigned AS) const { 15208 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 15209 if (Subtarget->hasFPAO()) 15210 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 15211 return 0; 15212 } 15213 return -1; 15214 } 15215 15216 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster 15217 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be 15218 /// expanded to FMAs when this method returns true, otherwise fmuladd is 15219 /// expanded to fmul + fadd. 15220 /// 15221 /// ARM supports both fused and unfused multiply-add operations; we already 15222 /// lower a pair of fmul and fadd to the latter so it's not clear that there 15223 /// would be a gain or that the gain would be worthwhile enough to risk 15224 /// correctness bugs. 15225 /// 15226 /// For MVE, we set this to true as it helps simplify the need for some 15227 /// patterns (and we don't have the non-fused floating point instruction). 15228 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15229 EVT VT) const { 15230 if (!VT.isSimple()) 15231 return false; 15232 15233 switch (VT.getSimpleVT().SimpleTy) { 15234 case MVT::v4f32: 15235 case MVT::v8f16: 15236 return Subtarget->hasMVEFloatOps(); 15237 case MVT::f16: 15238 return Subtarget->useFPVFMx16(); 15239 case MVT::f32: 15240 return Subtarget->useFPVFMx(); 15241 case MVT::f64: 15242 return Subtarget->useFPVFMx64(); 15243 default: 15244 break; 15245 } 15246 15247 return false; 15248 } 15249 15250 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 15251 if (V < 0) 15252 return false; 15253 15254 unsigned Scale = 1; 15255 switch (VT.getSimpleVT().SimpleTy) { 15256 case MVT::i1: 15257 case MVT::i8: 15258 // Scale == 1; 15259 break; 15260 case MVT::i16: 15261 // Scale == 2; 15262 Scale = 2; 15263 break; 15264 default: 15265 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 15266 // Scale == 4; 15267 Scale = 4; 15268 break; 15269 } 15270 15271 if ((V & (Scale - 1)) != 0) 15272 return false; 15273 return isUInt<5>(V / Scale); 15274 } 15275 15276 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 15277 const ARMSubtarget *Subtarget) { 15278 if (!VT.isInteger() && !VT.isFloatingPoint()) 15279 return false; 15280 if (VT.isVector() && Subtarget->hasNEON()) 15281 return false; 15282 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 15283 !Subtarget->hasMVEFloatOps()) 15284 return false; 15285 15286 bool IsNeg = false; 15287 if (V < 0) { 15288 IsNeg = true; 15289 V = -V; 15290 } 15291 15292 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U); 15293 15294 // MVE: size * imm7 15295 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 15296 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 15297 case MVT::i32: 15298 case MVT::f32: 15299 return isShiftedUInt<7,2>(V); 15300 case MVT::i16: 15301 case MVT::f16: 15302 return isShiftedUInt<7,1>(V); 15303 case MVT::i8: 15304 return isUInt<7>(V); 15305 default: 15306 return false; 15307 } 15308 } 15309 15310 // half VLDR: 2 * imm8 15311 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 15312 return isShiftedUInt<8, 1>(V); 15313 // VLDR and LDRD: 4 * imm8 15314 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 15315 return isShiftedUInt<8, 2>(V); 15316 15317 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 15318 // + imm12 or - imm8 15319 if (IsNeg) 15320 return isUInt<8>(V); 15321 return isUInt<12>(V); 15322 } 15323 15324 return false; 15325 } 15326 15327 /// isLegalAddressImmediate - Return true if the integer value can be used 15328 /// as the offset of the target addressing mode for load / store of the 15329 /// given type. 15330 static bool isLegalAddressImmediate(int64_t V, EVT VT, 15331 const ARMSubtarget *Subtarget) { 15332 if (V == 0) 15333 return true; 15334 15335 if (!VT.isSimple()) 15336 return false; 15337 15338 if (Subtarget->isThumb1Only()) 15339 return isLegalT1AddressImmediate(V, VT); 15340 else if (Subtarget->isThumb2()) 15341 return isLegalT2AddressImmediate(V, VT, Subtarget); 15342 15343 // ARM mode. 15344 if (V < 0) 15345 V = - V; 15346 switch (VT.getSimpleVT().SimpleTy) { 15347 default: return false; 15348 case MVT::i1: 15349 case MVT::i8: 15350 case MVT::i32: 15351 // +- imm12 15352 return isUInt<12>(V); 15353 case MVT::i16: 15354 // +- imm8 15355 return isUInt<8>(V); 15356 case MVT::f32: 15357 case MVT::f64: 15358 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 15359 return false; 15360 return isShiftedUInt<8, 2>(V); 15361 } 15362 } 15363 15364 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 15365 EVT VT) const { 15366 int Scale = AM.Scale; 15367 if (Scale < 0) 15368 return false; 15369 15370 switch (VT.getSimpleVT().SimpleTy) { 15371 default: return false; 15372 case MVT::i1: 15373 case MVT::i8: 15374 case MVT::i16: 15375 case MVT::i32: 15376 if (Scale == 1) 15377 return true; 15378 // r + r << imm 15379 Scale = Scale & ~1; 15380 return Scale == 2 || Scale == 4 || Scale == 8; 15381 case MVT::i64: 15382 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 15383 // version in Thumb mode. 15384 // r + r 15385 if (Scale == 1) 15386 return true; 15387 // r * 2 (this can be lowered to r + r). 15388 if (!AM.HasBaseReg && Scale == 2) 15389 return true; 15390 return false; 15391 case MVT::isVoid: 15392 // Note, we allow "void" uses (basically, uses that aren't loads or 15393 // stores), because arm allows folding a scale into many arithmetic 15394 // operations. This should be made more precise and revisited later. 15395 15396 // Allow r << imm, but the imm has to be a multiple of two. 15397 if (Scale & 1) return false; 15398 return isPowerOf2_32(Scale); 15399 } 15400 } 15401 15402 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 15403 EVT VT) const { 15404 const int Scale = AM.Scale; 15405 15406 // Negative scales are not supported in Thumb1. 15407 if (Scale < 0) 15408 return false; 15409 15410 // Thumb1 addressing modes do not support register scaling excepting the 15411 // following cases: 15412 // 1. Scale == 1 means no scaling. 15413 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 15414 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 15415 } 15416 15417 /// isLegalAddressingMode - Return true if the addressing mode represented 15418 /// by AM is legal for this target, for a load/store of the specified type. 15419 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15420 const AddrMode &AM, Type *Ty, 15421 unsigned AS, Instruction *I) const { 15422 EVT VT = getValueType(DL, Ty, true); 15423 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 15424 return false; 15425 15426 // Can never fold addr of global into load/store. 15427 if (AM.BaseGV) 15428 return false; 15429 15430 switch (AM.Scale) { 15431 case 0: // no scale reg, must be "r+i" or "r", or "i". 15432 break; 15433 default: 15434 // ARM doesn't support any R+R*scale+imm addr modes. 15435 if (AM.BaseOffs) 15436 return false; 15437 15438 if (!VT.isSimple()) 15439 return false; 15440 15441 if (Subtarget->isThumb1Only()) 15442 return isLegalT1ScaledAddressingMode(AM, VT); 15443 15444 if (Subtarget->isThumb2()) 15445 return isLegalT2ScaledAddressingMode(AM, VT); 15446 15447 int Scale = AM.Scale; 15448 switch (VT.getSimpleVT().SimpleTy) { 15449 default: return false; 15450 case MVT::i1: 15451 case MVT::i8: 15452 case MVT::i32: 15453 if (Scale < 0) Scale = -Scale; 15454 if (Scale == 1) 15455 return true; 15456 // r + r << imm 15457 return isPowerOf2_32(Scale & ~1); 15458 case MVT::i16: 15459 case MVT::i64: 15460 // r +/- r 15461 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 15462 return true; 15463 // r * 2 (this can be lowered to r + r). 15464 if (!AM.HasBaseReg && Scale == 2) 15465 return true; 15466 return false; 15467 15468 case MVT::isVoid: 15469 // Note, we allow "void" uses (basically, uses that aren't loads or 15470 // stores), because arm allows folding a scale into many arithmetic 15471 // operations. This should be made more precise and revisited later. 15472 15473 // Allow r << imm, but the imm has to be a multiple of two. 15474 if (Scale & 1) return false; 15475 return isPowerOf2_32(Scale); 15476 } 15477 } 15478 return true; 15479 } 15480 15481 /// isLegalICmpImmediate - Return true if the specified immediate is legal 15482 /// icmp immediate, that is the target has icmp instructions which can compare 15483 /// a register against the immediate without having to materialize the 15484 /// immediate into a register. 15485 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15486 // Thumb2 and ARM modes can use cmn for negative immediates. 15487 if (!Subtarget->isThumb()) 15488 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 15489 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 15490 if (Subtarget->isThumb2()) 15491 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 15492 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 15493 // Thumb1 doesn't have cmn, and only 8-bit immediates. 15494 return Imm >= 0 && Imm <= 255; 15495 } 15496 15497 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 15498 /// *or sub* immediate, that is the target has add or sub instructions which can 15499 /// add a register with the immediate without having to materialize the 15500 /// immediate into a register. 15501 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15502 // Same encoding for add/sub, just flip the sign. 15503 int64_t AbsImm = std::abs(Imm); 15504 if (!Subtarget->isThumb()) 15505 return ARM_AM::getSOImmVal(AbsImm) != -1; 15506 if (Subtarget->isThumb2()) 15507 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 15508 // Thumb1 only has 8-bit unsigned immediate. 15509 return AbsImm >= 0 && AbsImm <= 255; 15510 } 15511 15512 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 15513 bool isSEXTLoad, SDValue &Base, 15514 SDValue &Offset, bool &isInc, 15515 SelectionDAG &DAG) { 15516 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 15517 return false; 15518 15519 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 15520 // AddressingMode 3 15521 Base = Ptr->getOperand(0); 15522 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 15523 int RHSC = (int)RHS->getZExtValue(); 15524 if (RHSC < 0 && RHSC > -256) { 15525 assert(Ptr->getOpcode() == ISD::ADD); 15526 isInc = false; 15527 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15528 return true; 15529 } 15530 } 15531 isInc = (Ptr->getOpcode() == ISD::ADD); 15532 Offset = Ptr->getOperand(1); 15533 return true; 15534 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 15535 // AddressingMode 2 15536 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 15537 int RHSC = (int)RHS->getZExtValue(); 15538 if (RHSC < 0 && RHSC > -0x1000) { 15539 assert(Ptr->getOpcode() == ISD::ADD); 15540 isInc = false; 15541 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15542 Base = Ptr->getOperand(0); 15543 return true; 15544 } 15545 } 15546 15547 if (Ptr->getOpcode() == ISD::ADD) { 15548 isInc = true; 15549 ARM_AM::ShiftOpc ShOpcVal= 15550 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 15551 if (ShOpcVal != ARM_AM::no_shift) { 15552 Base = Ptr->getOperand(1); 15553 Offset = Ptr->getOperand(0); 15554 } else { 15555 Base = Ptr->getOperand(0); 15556 Offset = Ptr->getOperand(1); 15557 } 15558 return true; 15559 } 15560 15561 isInc = (Ptr->getOpcode() == ISD::ADD); 15562 Base = Ptr->getOperand(0); 15563 Offset = Ptr->getOperand(1); 15564 return true; 15565 } 15566 15567 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 15568 return false; 15569 } 15570 15571 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 15572 bool isSEXTLoad, SDValue &Base, 15573 SDValue &Offset, bool &isInc, 15574 SelectionDAG &DAG) { 15575 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 15576 return false; 15577 15578 Base = Ptr->getOperand(0); 15579 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 15580 int RHSC = (int)RHS->getZExtValue(); 15581 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 15582 assert(Ptr->getOpcode() == ISD::ADD); 15583 isInc = false; 15584 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15585 return true; 15586 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 15587 isInc = Ptr->getOpcode() == ISD::ADD; 15588 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15589 return true; 15590 } 15591 } 15592 15593 return false; 15594 } 15595 15596 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align, 15597 bool isSEXTLoad, bool IsMasked, bool isLE, 15598 SDValue &Base, SDValue &Offset, 15599 bool &isInc, SelectionDAG &DAG) { 15600 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 15601 return false; 15602 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 15603 return false; 15604 15605 // We allow LE non-masked loads to change the type (for example use a vldrb.8 15606 // as opposed to a vldrw.32). This can allow extra addressing modes or 15607 // alignments for what is otherwise an equivalent instruction. 15608 bool CanChangeType = isLE && !IsMasked; 15609 15610 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 15611 int RHSC = (int)RHS->getZExtValue(); 15612 15613 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 15614 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 15615 assert(Ptr->getOpcode() == ISD::ADD); 15616 isInc = false; 15617 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15618 return true; 15619 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 15620 isInc = Ptr->getOpcode() == ISD::ADD; 15621 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 15622 return true; 15623 } 15624 return false; 15625 }; 15626 15627 // Try to find a matching instruction based on s/zext, Alignment, Offset and 15628 // (in BE/masked) type. 15629 Base = Ptr->getOperand(0); 15630 if (VT == MVT::v4i16) { 15631 if (Align >= 2 && IsInRange(RHSC, 0x80, 2)) 15632 return true; 15633 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 15634 if (IsInRange(RHSC, 0x80, 1)) 15635 return true; 15636 } else if (Align >= 4 && 15637 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) && 15638 IsInRange(RHSC, 0x80, 4)) 15639 return true; 15640 else if (Align >= 2 && 15641 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) && 15642 IsInRange(RHSC, 0x80, 2)) 15643 return true; 15644 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 15645 return true; 15646 return false; 15647 } 15648 15649 /// getPreIndexedAddressParts - returns true by value, base pointer and 15650 /// offset pointer and addressing mode by reference if the node's address 15651 /// can be legally represented as pre-indexed load / store address. 15652 bool 15653 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 15654 SDValue &Offset, 15655 ISD::MemIndexedMode &AM, 15656 SelectionDAG &DAG) const { 15657 if (Subtarget->isThumb1Only()) 15658 return false; 15659 15660 EVT VT; 15661 SDValue Ptr; 15662 unsigned Align; 15663 bool isSEXTLoad = false; 15664 bool IsMasked = false; 15665 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 15666 Ptr = LD->getBasePtr(); 15667 VT = LD->getMemoryVT(); 15668 Align = LD->getAlignment(); 15669 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 15670 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 15671 Ptr = ST->getBasePtr(); 15672 VT = ST->getMemoryVT(); 15673 Align = ST->getAlignment(); 15674 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 15675 Ptr = LD->getBasePtr(); 15676 VT = LD->getMemoryVT(); 15677 Align = LD->getAlignment(); 15678 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 15679 IsMasked = true; 15680 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 15681 Ptr = ST->getBasePtr(); 15682 VT = ST->getMemoryVT(); 15683 Align = ST->getAlignment(); 15684 IsMasked = true; 15685 } else 15686 return false; 15687 15688 bool isInc; 15689 bool isLegal = false; 15690 if (VT.isVector()) 15691 isLegal = Subtarget->hasMVEIntegerOps() && 15692 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad, 15693 IsMasked, Subtarget->isLittle(), Base, 15694 Offset, isInc, DAG); 15695 else { 15696 if (Subtarget->isThumb2()) 15697 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 15698 Offset, isInc, DAG); 15699 else 15700 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 15701 Offset, isInc, DAG); 15702 } 15703 if (!isLegal) 15704 return false; 15705 15706 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 15707 return true; 15708 } 15709 15710 /// getPostIndexedAddressParts - returns true by value, base pointer and 15711 /// offset pointer and addressing mode by reference if this node can be 15712 /// combined with a load / store to form a post-indexed load / store. 15713 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 15714 SDValue &Base, 15715 SDValue &Offset, 15716 ISD::MemIndexedMode &AM, 15717 SelectionDAG &DAG) const { 15718 EVT VT; 15719 SDValue Ptr; 15720 unsigned Align; 15721 bool isSEXTLoad = false, isNonExt; 15722 bool IsMasked = false; 15723 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 15724 VT = LD->getMemoryVT(); 15725 Ptr = LD->getBasePtr(); 15726 Align = LD->getAlignment(); 15727 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 15728 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 15729 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 15730 VT = ST->getMemoryVT(); 15731 Ptr = ST->getBasePtr(); 15732 Align = ST->getAlignment(); 15733 isNonExt = !ST->isTruncatingStore(); 15734 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 15735 VT = LD->getMemoryVT(); 15736 Ptr = LD->getBasePtr(); 15737 Align = LD->getAlignment(); 15738 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 15739 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 15740 IsMasked = true; 15741 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 15742 VT = ST->getMemoryVT(); 15743 Ptr = ST->getBasePtr(); 15744 Align = ST->getAlignment(); 15745 isNonExt = !ST->isTruncatingStore(); 15746 IsMasked = true; 15747 } else 15748 return false; 15749 15750 if (Subtarget->isThumb1Only()) { 15751 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 15752 // must be non-extending/truncating, i32, with an offset of 4. 15753 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 15754 if (Op->getOpcode() != ISD::ADD || !isNonExt) 15755 return false; 15756 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 15757 if (!RHS || RHS->getZExtValue() != 4) 15758 return false; 15759 15760 Offset = Op->getOperand(1); 15761 Base = Op->getOperand(0); 15762 AM = ISD::POST_INC; 15763 return true; 15764 } 15765 15766 bool isInc; 15767 bool isLegal = false; 15768 if (VT.isVector()) 15769 isLegal = Subtarget->hasMVEIntegerOps() && 15770 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad, IsMasked, 15771 Subtarget->isLittle(), Base, Offset, 15772 isInc, DAG); 15773 else { 15774 if (Subtarget->isThumb2()) 15775 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 15776 isInc, DAG); 15777 else 15778 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 15779 isInc, DAG); 15780 } 15781 if (!isLegal) 15782 return false; 15783 15784 if (Ptr != Base) { 15785 // Swap base ptr and offset to catch more post-index load / store when 15786 // it's legal. In Thumb2 mode, offset must be an immediate. 15787 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 15788 !Subtarget->isThumb2()) 15789 std::swap(Base, Offset); 15790 15791 // Post-indexed load / store update the base pointer. 15792 if (Ptr != Base) 15793 return false; 15794 } 15795 15796 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 15797 return true; 15798 } 15799 15800 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15801 KnownBits &Known, 15802 const APInt &DemandedElts, 15803 const SelectionDAG &DAG, 15804 unsigned Depth) const { 15805 unsigned BitWidth = Known.getBitWidth(); 15806 Known.resetAll(); 15807 switch (Op.getOpcode()) { 15808 default: break; 15809 case ARMISD::ADDC: 15810 case ARMISD::ADDE: 15811 case ARMISD::SUBC: 15812 case ARMISD::SUBE: 15813 // Special cases when we convert a carry to a boolean. 15814 if (Op.getResNo() == 0) { 15815 SDValue LHS = Op.getOperand(0); 15816 SDValue RHS = Op.getOperand(1); 15817 // (ADDE 0, 0, C) will give us a single bit. 15818 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 15819 isNullConstant(RHS)) { 15820 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 15821 return; 15822 } 15823 } 15824 break; 15825 case ARMISD::CMOV: { 15826 // Bits are known zero/one if known on the LHS and RHS. 15827 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 15828 if (Known.isUnknown()) 15829 return; 15830 15831 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 15832 Known.Zero &= KnownRHS.Zero; 15833 Known.One &= KnownRHS.One; 15834 return; 15835 } 15836 case ISD::INTRINSIC_W_CHAIN: { 15837 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 15838 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 15839 switch (IntID) { 15840 default: return; 15841 case Intrinsic::arm_ldaex: 15842 case Intrinsic::arm_ldrex: { 15843 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 15844 unsigned MemBits = VT.getScalarSizeInBits(); 15845 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 15846 return; 15847 } 15848 } 15849 } 15850 case ARMISD::BFI: { 15851 // Conservatively, we can recurse down the first operand 15852 // and just mask out all affected bits. 15853 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 15854 15855 // The operand to BFI is already a mask suitable for removing the bits it 15856 // sets. 15857 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 15858 const APInt &Mask = CI->getAPIntValue(); 15859 Known.Zero &= Mask; 15860 Known.One &= Mask; 15861 return; 15862 } 15863 case ARMISD::VGETLANEs: 15864 case ARMISD::VGETLANEu: { 15865 const SDValue &SrcSV = Op.getOperand(0); 15866 EVT VecVT = SrcSV.getValueType(); 15867 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 15868 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 15869 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 15870 assert(Pos->getAPIntValue().ult(NumSrcElts) && 15871 "VGETLANE index out of bounds"); 15872 unsigned Idx = Pos->getZExtValue(); 15873 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 15874 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 15875 15876 EVT VT = Op.getValueType(); 15877 const unsigned DstSz = VT.getScalarSizeInBits(); 15878 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 15879 (void)SrcSz; 15880 assert(SrcSz == Known.getBitWidth()); 15881 assert(DstSz > SrcSz); 15882 if (Op.getOpcode() == ARMISD::VGETLANEs) 15883 Known = Known.sext(DstSz); 15884 else { 15885 Known = Known.zext(DstSz); 15886 } 15887 assert(DstSz == Known.getBitWidth()); 15888 break; 15889 } 15890 } 15891 } 15892 15893 bool 15894 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 15895 const APInt &DemandedAPInt, 15896 TargetLoweringOpt &TLO) const { 15897 // Delay optimization, so we don't have to deal with illegal types, or block 15898 // optimizations. 15899 if (!TLO.LegalOps) 15900 return false; 15901 15902 // Only optimize AND for now. 15903 if (Op.getOpcode() != ISD::AND) 15904 return false; 15905 15906 EVT VT = Op.getValueType(); 15907 15908 // Ignore vectors. 15909 if (VT.isVector()) 15910 return false; 15911 15912 assert(VT == MVT::i32 && "Unexpected integer type"); 15913 15914 // Make sure the RHS really is a constant. 15915 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 15916 if (!C) 15917 return false; 15918 15919 unsigned Mask = C->getZExtValue(); 15920 15921 unsigned Demanded = DemandedAPInt.getZExtValue(); 15922 unsigned ShrunkMask = Mask & Demanded; 15923 unsigned ExpandedMask = Mask | ~Demanded; 15924 15925 // If the mask is all zeros, let the target-independent code replace the 15926 // result with zero. 15927 if (ShrunkMask == 0) 15928 return false; 15929 15930 // If the mask is all ones, erase the AND. (Currently, the target-independent 15931 // code won't do this, so we have to do it explicitly to avoid an infinite 15932 // loop in obscure cases.) 15933 if (ExpandedMask == ~0U) 15934 return TLO.CombineTo(Op, Op.getOperand(0)); 15935 15936 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 15937 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 15938 }; 15939 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 15940 if (NewMask == Mask) 15941 return true; 15942 SDLoc DL(Op); 15943 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 15944 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 15945 return TLO.CombineTo(Op, NewOp); 15946 }; 15947 15948 // Prefer uxtb mask. 15949 if (IsLegalMask(0xFF)) 15950 return UseMask(0xFF); 15951 15952 // Prefer uxth mask. 15953 if (IsLegalMask(0xFFFF)) 15954 return UseMask(0xFFFF); 15955 15956 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 15957 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 15958 if (ShrunkMask < 256) 15959 return UseMask(ShrunkMask); 15960 15961 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 15962 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 15963 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 15964 return UseMask(ExpandedMask); 15965 15966 // Potential improvements: 15967 // 15968 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 15969 // We could try to prefer Thumb1 immediates which can be lowered to a 15970 // two-instruction sequence. 15971 // We could try to recognize more legal ARM/Thumb2 immediates here. 15972 15973 return false; 15974 } 15975 15976 15977 //===----------------------------------------------------------------------===// 15978 // ARM Inline Assembly Support 15979 //===----------------------------------------------------------------------===// 15980 15981 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 15982 // Looking for "rev" which is V6+. 15983 if (!Subtarget->hasV6Ops()) 15984 return false; 15985 15986 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 15987 std::string AsmStr = IA->getAsmString(); 15988 SmallVector<StringRef, 4> AsmPieces; 15989 SplitString(AsmStr, AsmPieces, ";\n"); 15990 15991 switch (AsmPieces.size()) { 15992 default: return false; 15993 case 1: 15994 AsmStr = std::string(AsmPieces[0]); 15995 AsmPieces.clear(); 15996 SplitString(AsmStr, AsmPieces, " \t,"); 15997 15998 // rev $0, $1 15999 if (AsmPieces.size() == 3 && 16000 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 16001 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 16002 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 16003 if (Ty && Ty->getBitWidth() == 32) 16004 return IntrinsicLowering::LowerToByteSwap(CI); 16005 } 16006 break; 16007 } 16008 16009 return false; 16010 } 16011 16012 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 16013 // At this point, we have to lower this constraint to something else, so we 16014 // lower it to an "r" or "w". However, by doing this we will force the result 16015 // to be in register, while the X constraint is much more permissive. 16016 // 16017 // Although we are correct (we are free to emit anything, without 16018 // constraints), we might break use cases that would expect us to be more 16019 // efficient and emit something else. 16020 if (!Subtarget->hasVFP2Base()) 16021 return "r"; 16022 if (ConstraintVT.isFloatingPoint()) 16023 return "w"; 16024 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 16025 (ConstraintVT.getSizeInBits() == 64 || 16026 ConstraintVT.getSizeInBits() == 128)) 16027 return "w"; 16028 16029 return "r"; 16030 } 16031 16032 /// getConstraintType - Given a constraint letter, return the type of 16033 /// constraint it is for this target. 16034 ARMTargetLowering::ConstraintType 16035 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 16036 unsigned S = Constraint.size(); 16037 if (S == 1) { 16038 switch (Constraint[0]) { 16039 default: break; 16040 case 'l': return C_RegisterClass; 16041 case 'w': return C_RegisterClass; 16042 case 'h': return C_RegisterClass; 16043 case 'x': return C_RegisterClass; 16044 case 't': return C_RegisterClass; 16045 case 'j': return C_Immediate; // Constant for movw. 16046 // An address with a single base register. Due to the way we 16047 // currently handle addresses it is the same as an 'r' memory constraint. 16048 case 'Q': return C_Memory; 16049 } 16050 } else if (S == 2) { 16051 switch (Constraint[0]) { 16052 default: break; 16053 case 'T': return C_RegisterClass; 16054 // All 'U+' constraints are addresses. 16055 case 'U': return C_Memory; 16056 } 16057 } 16058 return TargetLowering::getConstraintType(Constraint); 16059 } 16060 16061 /// Examine constraint type and operand type and determine a weight value. 16062 /// This object must already have been set up with the operand type 16063 /// and the current alternative constraint selected. 16064 TargetLowering::ConstraintWeight 16065 ARMTargetLowering::getSingleConstraintMatchWeight( 16066 AsmOperandInfo &info, const char *constraint) const { 16067 ConstraintWeight weight = CW_Invalid; 16068 Value *CallOperandVal = info.CallOperandVal; 16069 // If we don't have a value, we can't do a match, 16070 // but allow it at the lowest weight. 16071 if (!CallOperandVal) 16072 return CW_Default; 16073 Type *type = CallOperandVal->getType(); 16074 // Look at the constraint type. 16075 switch (*constraint) { 16076 default: 16077 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 16078 break; 16079 case 'l': 16080 if (type->isIntegerTy()) { 16081 if (Subtarget->isThumb()) 16082 weight = CW_SpecificReg; 16083 else 16084 weight = CW_Register; 16085 } 16086 break; 16087 case 'w': 16088 if (type->isFloatingPointTy()) 16089 weight = CW_Register; 16090 break; 16091 } 16092 return weight; 16093 } 16094 16095 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 16096 16097 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 16098 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 16099 switch (Constraint.size()) { 16100 case 1: 16101 // GCC ARM Constraint Letters 16102 switch (Constraint[0]) { 16103 case 'l': // Low regs or general regs. 16104 if (Subtarget->isThumb()) 16105 return RCPair(0U, &ARM::tGPRRegClass); 16106 return RCPair(0U, &ARM::GPRRegClass); 16107 case 'h': // High regs or no regs. 16108 if (Subtarget->isThumb()) 16109 return RCPair(0U, &ARM::hGPRRegClass); 16110 break; 16111 case 'r': 16112 if (Subtarget->isThumb1Only()) 16113 return RCPair(0U, &ARM::tGPRRegClass); 16114 return RCPair(0U, &ARM::GPRRegClass); 16115 case 'w': 16116 if (VT == MVT::Other) 16117 break; 16118 if (VT == MVT::f32) 16119 return RCPair(0U, &ARM::SPRRegClass); 16120 if (VT.getSizeInBits() == 64) 16121 return RCPair(0U, &ARM::DPRRegClass); 16122 if (VT.getSizeInBits() == 128) 16123 return RCPair(0U, &ARM::QPRRegClass); 16124 break; 16125 case 'x': 16126 if (VT == MVT::Other) 16127 break; 16128 if (VT == MVT::f32) 16129 return RCPair(0U, &ARM::SPR_8RegClass); 16130 if (VT.getSizeInBits() == 64) 16131 return RCPair(0U, &ARM::DPR_8RegClass); 16132 if (VT.getSizeInBits() == 128) 16133 return RCPair(0U, &ARM::QPR_8RegClass); 16134 break; 16135 case 't': 16136 if (VT == MVT::Other) 16137 break; 16138 if (VT == MVT::f32 || VT == MVT::i32) 16139 return RCPair(0U, &ARM::SPRRegClass); 16140 if (VT.getSizeInBits() == 64) 16141 return RCPair(0U, &ARM::DPR_VFP2RegClass); 16142 if (VT.getSizeInBits() == 128) 16143 return RCPair(0U, &ARM::QPR_VFP2RegClass); 16144 break; 16145 } 16146 break; 16147 16148 case 2: 16149 if (Constraint[0] == 'T') { 16150 switch (Constraint[1]) { 16151 default: 16152 break; 16153 case 'e': 16154 return RCPair(0U, &ARM::tGPREvenRegClass); 16155 case 'o': 16156 return RCPair(0U, &ARM::tGPROddRegClass); 16157 } 16158 } 16159 break; 16160 16161 default: 16162 break; 16163 } 16164 16165 if (StringRef("{cc}").equals_lower(Constraint)) 16166 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 16167 16168 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 16169 } 16170 16171 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 16172 /// vector. If it is invalid, don't add anything to Ops. 16173 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 16174 std::string &Constraint, 16175 std::vector<SDValue>&Ops, 16176 SelectionDAG &DAG) const { 16177 SDValue Result; 16178 16179 // Currently only support length 1 constraints. 16180 if (Constraint.length() != 1) return; 16181 16182 char ConstraintLetter = Constraint[0]; 16183 switch (ConstraintLetter) { 16184 default: break; 16185 case 'j': 16186 case 'I': case 'J': case 'K': case 'L': 16187 case 'M': case 'N': case 'O': 16188 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 16189 if (!C) 16190 return; 16191 16192 int64_t CVal64 = C->getSExtValue(); 16193 int CVal = (int) CVal64; 16194 // None of these constraints allow values larger than 32 bits. Check 16195 // that the value fits in an int. 16196 if (CVal != CVal64) 16197 return; 16198 16199 switch (ConstraintLetter) { 16200 case 'j': 16201 // Constant suitable for movw, must be between 0 and 16202 // 65535. 16203 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps())) 16204 if (CVal >= 0 && CVal <= 65535) 16205 break; 16206 return; 16207 case 'I': 16208 if (Subtarget->isThumb1Only()) { 16209 // This must be a constant between 0 and 255, for ADD 16210 // immediates. 16211 if (CVal >= 0 && CVal <= 255) 16212 break; 16213 } else if (Subtarget->isThumb2()) { 16214 // A constant that can be used as an immediate value in a 16215 // data-processing instruction. 16216 if (ARM_AM::getT2SOImmVal(CVal) != -1) 16217 break; 16218 } else { 16219 // A constant that can be used as an immediate value in a 16220 // data-processing instruction. 16221 if (ARM_AM::getSOImmVal(CVal) != -1) 16222 break; 16223 } 16224 return; 16225 16226 case 'J': 16227 if (Subtarget->isThumb1Only()) { 16228 // This must be a constant between -255 and -1, for negated ADD 16229 // immediates. This can be used in GCC with an "n" modifier that 16230 // prints the negated value, for use with SUB instructions. It is 16231 // not useful otherwise but is implemented for compatibility. 16232 if (CVal >= -255 && CVal <= -1) 16233 break; 16234 } else { 16235 // This must be a constant between -4095 and 4095. It is not clear 16236 // what this constraint is intended for. Implemented for 16237 // compatibility with GCC. 16238 if (CVal >= -4095 && CVal <= 4095) 16239 break; 16240 } 16241 return; 16242 16243 case 'K': 16244 if (Subtarget->isThumb1Only()) { 16245 // A 32-bit value where only one byte has a nonzero value. Exclude 16246 // zero to match GCC. This constraint is used by GCC internally for 16247 // constants that can be loaded with a move/shift combination. 16248 // It is not useful otherwise but is implemented for compatibility. 16249 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 16250 break; 16251 } else if (Subtarget->isThumb2()) { 16252 // A constant whose bitwise inverse can be used as an immediate 16253 // value in a data-processing instruction. This can be used in GCC 16254 // with a "B" modifier that prints the inverted value, for use with 16255 // BIC and MVN instructions. It is not useful otherwise but is 16256 // implemented for compatibility. 16257 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 16258 break; 16259 } else { 16260 // A constant whose bitwise inverse can be used as an immediate 16261 // value in a data-processing instruction. This can be used in GCC 16262 // with a "B" modifier that prints the inverted value, for use with 16263 // BIC and MVN instructions. It is not useful otherwise but is 16264 // implemented for compatibility. 16265 if (ARM_AM::getSOImmVal(~CVal) != -1) 16266 break; 16267 } 16268 return; 16269 16270 case 'L': 16271 if (Subtarget->isThumb1Only()) { 16272 // This must be a constant between -7 and 7, 16273 // for 3-operand ADD/SUB immediate instructions. 16274 if (CVal >= -7 && CVal < 7) 16275 break; 16276 } else if (Subtarget->isThumb2()) { 16277 // A constant whose negation can be used as an immediate value in a 16278 // data-processing instruction. This can be used in GCC with an "n" 16279 // modifier that prints the negated value, for use with SUB 16280 // instructions. It is not useful otherwise but is implemented for 16281 // compatibility. 16282 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 16283 break; 16284 } else { 16285 // A constant whose negation can be used as an immediate value in a 16286 // data-processing instruction. This can be used in GCC with an "n" 16287 // modifier that prints the negated value, for use with SUB 16288 // instructions. It is not useful otherwise but is implemented for 16289 // compatibility. 16290 if (ARM_AM::getSOImmVal(-CVal) != -1) 16291 break; 16292 } 16293 return; 16294 16295 case 'M': 16296 if (Subtarget->isThumb1Only()) { 16297 // This must be a multiple of 4 between 0 and 1020, for 16298 // ADD sp + immediate. 16299 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 16300 break; 16301 } else { 16302 // A power of two or a constant between 0 and 32. This is used in 16303 // GCC for the shift amount on shifted register operands, but it is 16304 // useful in general for any shift amounts. 16305 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 16306 break; 16307 } 16308 return; 16309 16310 case 'N': 16311 if (Subtarget->isThumb1Only()) { 16312 // This must be a constant between 0 and 31, for shift amounts. 16313 if (CVal >= 0 && CVal <= 31) 16314 break; 16315 } 16316 return; 16317 16318 case 'O': 16319 if (Subtarget->isThumb1Only()) { 16320 // This must be a multiple of 4 between -508 and 508, for 16321 // ADD/SUB sp = sp + immediate. 16322 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 16323 break; 16324 } 16325 return; 16326 } 16327 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 16328 break; 16329 } 16330 16331 if (Result.getNode()) { 16332 Ops.push_back(Result); 16333 return; 16334 } 16335 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16336 } 16337 16338 static RTLIB::Libcall getDivRemLibcall( 16339 const SDNode *N, MVT::SimpleValueType SVT) { 16340 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 16341 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 16342 "Unhandled Opcode in getDivRemLibcall"); 16343 bool isSigned = N->getOpcode() == ISD::SDIVREM || 16344 N->getOpcode() == ISD::SREM; 16345 RTLIB::Libcall LC; 16346 switch (SVT) { 16347 default: llvm_unreachable("Unexpected request for libcall!"); 16348 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 16349 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 16350 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 16351 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 16352 } 16353 return LC; 16354 } 16355 16356 static TargetLowering::ArgListTy getDivRemArgList( 16357 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 16358 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 16359 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 16360 "Unhandled Opcode in getDivRemArgList"); 16361 bool isSigned = N->getOpcode() == ISD::SDIVREM || 16362 N->getOpcode() == ISD::SREM; 16363 TargetLowering::ArgListTy Args; 16364 TargetLowering::ArgListEntry Entry; 16365 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 16366 EVT ArgVT = N->getOperand(i).getValueType(); 16367 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 16368 Entry.Node = N->getOperand(i); 16369 Entry.Ty = ArgTy; 16370 Entry.IsSExt = isSigned; 16371 Entry.IsZExt = !isSigned; 16372 Args.push_back(Entry); 16373 } 16374 if (Subtarget->isTargetWindows() && Args.size() >= 2) 16375 std::swap(Args[0], Args[1]); 16376 return Args; 16377 } 16378 16379 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 16380 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 16381 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 16382 Subtarget->isTargetWindows()) && 16383 "Register-based DivRem lowering only"); 16384 unsigned Opcode = Op->getOpcode(); 16385 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 16386 "Invalid opcode for Div/Rem lowering"); 16387 bool isSigned = (Opcode == ISD::SDIVREM); 16388 EVT VT = Op->getValueType(0); 16389 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 16390 SDLoc dl(Op); 16391 16392 // If the target has hardware divide, use divide + multiply + subtract: 16393 // div = a / b 16394 // rem = a - b * div 16395 // return {div, rem} 16396 // This should be lowered into UDIV/SDIV + MLS later on. 16397 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 16398 : Subtarget->hasDivideInARMMode(); 16399 if (hasDivide && Op->getValueType(0).isSimple() && 16400 Op->getSimpleValueType(0) == MVT::i32) { 16401 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 16402 const SDValue Dividend = Op->getOperand(0); 16403 const SDValue Divisor = Op->getOperand(1); 16404 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 16405 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 16406 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 16407 16408 SDValue Values[2] = {Div, Rem}; 16409 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 16410 } 16411 16412 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 16413 VT.getSimpleVT().SimpleTy); 16414 SDValue InChain = DAG.getEntryNode(); 16415 16416 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 16417 DAG.getContext(), 16418 Subtarget); 16419 16420 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 16421 getPointerTy(DAG.getDataLayout())); 16422 16423 Type *RetTy = StructType::get(Ty, Ty); 16424 16425 if (Subtarget->isTargetWindows()) 16426 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 16427 16428 TargetLowering::CallLoweringInfo CLI(DAG); 16429 CLI.setDebugLoc(dl).setChain(InChain) 16430 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 16431 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 16432 16433 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 16434 return CallInfo.first; 16435 } 16436 16437 // Lowers REM using divmod helpers 16438 // see RTABI section 4.2/4.3 16439 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 16440 // Build return types (div and rem) 16441 std::vector<Type*> RetTyParams; 16442 Type *RetTyElement; 16443 16444 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 16445 default: llvm_unreachable("Unexpected request for libcall!"); 16446 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 16447 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 16448 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 16449 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 16450 } 16451 16452 RetTyParams.push_back(RetTyElement); 16453 RetTyParams.push_back(RetTyElement); 16454 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 16455 Type *RetTy = StructType::get(*DAG.getContext(), ret); 16456 16457 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 16458 SimpleTy); 16459 SDValue InChain = DAG.getEntryNode(); 16460 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 16461 Subtarget); 16462 bool isSigned = N->getOpcode() == ISD::SREM; 16463 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 16464 getPointerTy(DAG.getDataLayout())); 16465 16466 if (Subtarget->isTargetWindows()) 16467 InChain = WinDBZCheckDenominator(DAG, N, InChain); 16468 16469 // Lower call 16470 CallLoweringInfo CLI(DAG); 16471 CLI.setChain(InChain) 16472 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 16473 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 16474 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 16475 16476 // Return second (rem) result operand (first contains div) 16477 SDNode *ResNode = CallResult.first.getNode(); 16478 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 16479 return ResNode->getOperand(1); 16480 } 16481 16482 SDValue 16483 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 16484 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 16485 SDLoc DL(Op); 16486 16487 // Get the inputs. 16488 SDValue Chain = Op.getOperand(0); 16489 SDValue Size = Op.getOperand(1); 16490 16491 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 16492 "no-stack-arg-probe")) { 16493 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 16494 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 16495 Chain = SP.getValue(1); 16496 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 16497 if (Align) 16498 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 16499 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 16500 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 16501 SDValue Ops[2] = { SP, Chain }; 16502 return DAG.getMergeValues(Ops, DL); 16503 } 16504 16505 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 16506 DAG.getConstant(2, DL, MVT::i32)); 16507 16508 SDValue Flag; 16509 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 16510 Flag = Chain.getValue(1); 16511 16512 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 16513 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 16514 16515 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 16516 Chain = NewSP.getValue(1); 16517 16518 SDValue Ops[2] = { NewSP, Chain }; 16519 return DAG.getMergeValues(Ops, DL); 16520 } 16521 16522 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 16523 bool IsStrict = Op->isStrictFPOpcode(); 16524 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 16525 const unsigned DstSz = Op.getValueType().getSizeInBits(); 16526 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 16527 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 16528 "Unexpected type for custom-lowering FP_EXTEND"); 16529 16530 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 16531 "With both FP DP and 16, any FP conversion is legal!"); 16532 16533 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 16534 "With FP16, 16 to 32 conversion is legal!"); 16535 16536 // Converting from 32 -> 64 is valid if we have FP64. 16537 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) { 16538 // FIXME: Remove this when we have strict fp instruction selection patterns 16539 if (IsStrict) { 16540 SDLoc Loc(Op); 16541 SDValue Result = DAG.getNode(ISD::FP_EXTEND, 16542 Loc, Op.getValueType(), SrcVal); 16543 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 16544 } 16545 return Op; 16546 } 16547 16548 // Either we are converting from 16 -> 64, without FP16 and/or 16549 // FP.double-precision or without Armv8-fp. So we must do it in two 16550 // steps. 16551 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 16552 // without FP16. So we must do a function call. 16553 SDLoc Loc(Op); 16554 RTLIB::Libcall LC; 16555 MakeLibCallOptions CallOptions; 16556 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 16557 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) { 16558 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64()); 16559 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32); 16560 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64); 16561 if (Supported) { 16562 if (IsStrict) { 16563 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc, 16564 {DstVT, MVT::Other}, {Chain, SrcVal}); 16565 Chain = SrcVal.getValue(1); 16566 } else { 16567 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal); 16568 } 16569 } else { 16570 LC = RTLIB::getFPEXT(SrcVT, DstVT); 16571 assert(LC != RTLIB::UNKNOWN_LIBCALL && 16572 "Unexpected type for custom-lowering FP_EXTEND"); 16573 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 16574 Loc, Chain); 16575 } 16576 } 16577 16578 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal; 16579 } 16580 16581 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 16582 bool IsStrict = Op->isStrictFPOpcode(); 16583 16584 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 16585 EVT SrcVT = SrcVal.getValueType(); 16586 EVT DstVT = Op.getValueType(); 16587 const unsigned DstSz = Op.getValueType().getSizeInBits(); 16588 const unsigned SrcSz = SrcVT.getSizeInBits(); 16589 (void)DstSz; 16590 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 16591 "Unexpected type for custom-lowering FP_ROUND"); 16592 16593 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 16594 "With both FP DP and 16, any FP conversion is legal!"); 16595 16596 SDLoc Loc(Op); 16597 16598 // Instruction from 32 -> 16 if hasFP16 is valid 16599 if (SrcSz == 32 && Subtarget->hasFP16()) 16600 return Op; 16601 16602 // Lib call from 32 -> 16 / 64 -> [32, 16] 16603 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 16604 assert(LC != RTLIB::UNKNOWN_LIBCALL && 16605 "Unexpected type for custom-lowering FP_ROUND"); 16606 MakeLibCallOptions CallOptions; 16607 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 16608 SDValue Result; 16609 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 16610 Loc, Chain); 16611 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 16612 } 16613 16614 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 16615 SelectionDAG &DAG) const { 16616 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 16617 MVT HalfT = MVT::i32; 16618 SDLoc dl(N); 16619 SDValue Hi, Lo, Tmp; 16620 16621 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 16622 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 16623 return ; 16624 16625 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 16626 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 16627 16628 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 16629 DAG.getConstant(0, dl, HalfT)); 16630 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 16631 DAG.getConstant(1, dl, HalfT)); 16632 16633 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 16634 DAG.getConstant(OpTypeBits - 1, dl, 16635 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 16636 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 16637 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 16638 SDValue(Lo.getNode(), 1)); 16639 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 16640 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 16641 16642 Results.push_back(Lo); 16643 Results.push_back(Hi); 16644 } 16645 16646 bool 16647 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 16648 // The ARM target isn't yet aware of offsets. 16649 return false; 16650 } 16651 16652 bool ARM::isBitFieldInvertedMask(unsigned v) { 16653 if (v == 0xffffffff) 16654 return false; 16655 16656 // there can be 1's on either or both "outsides", all the "inside" 16657 // bits must be 0's 16658 return isShiftedMask_32(~v); 16659 } 16660 16661 /// isFPImmLegal - Returns true if the target can instruction select the 16662 /// specified FP immediate natively. If false, the legalizer will 16663 /// materialize the FP immediate as a load from a constant pool. 16664 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16665 bool ForCodeSize) const { 16666 if (!Subtarget->hasVFP3Base()) 16667 return false; 16668 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 16669 return ARM_AM::getFP16Imm(Imm) != -1; 16670 if (VT == MVT::f32) 16671 return ARM_AM::getFP32Imm(Imm) != -1; 16672 if (VT == MVT::f64 && Subtarget->hasFP64()) 16673 return ARM_AM::getFP64Imm(Imm) != -1; 16674 return false; 16675 } 16676 16677 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 16678 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 16679 /// specified in the intrinsic calls. 16680 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16681 const CallInst &I, 16682 MachineFunction &MF, 16683 unsigned Intrinsic) const { 16684 switch (Intrinsic) { 16685 case Intrinsic::arm_neon_vld1: 16686 case Intrinsic::arm_neon_vld2: 16687 case Intrinsic::arm_neon_vld3: 16688 case Intrinsic::arm_neon_vld4: 16689 case Intrinsic::arm_neon_vld2lane: 16690 case Intrinsic::arm_neon_vld3lane: 16691 case Intrinsic::arm_neon_vld4lane: 16692 case Intrinsic::arm_neon_vld2dup: 16693 case Intrinsic::arm_neon_vld3dup: 16694 case Intrinsic::arm_neon_vld4dup: { 16695 Info.opc = ISD::INTRINSIC_W_CHAIN; 16696 // Conservatively set memVT to the entire set of vectors loaded. 16697 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16698 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 16699 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 16700 Info.ptrVal = I.getArgOperand(0); 16701 Info.offset = 0; 16702 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 16703 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 16704 // volatile loads with NEON intrinsics not supported 16705 Info.flags = MachineMemOperand::MOLoad; 16706 return true; 16707 } 16708 case Intrinsic::arm_neon_vld1x2: 16709 case Intrinsic::arm_neon_vld1x3: 16710 case Intrinsic::arm_neon_vld1x4: { 16711 Info.opc = ISD::INTRINSIC_W_CHAIN; 16712 // Conservatively set memVT to the entire set of vectors loaded. 16713 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16714 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 16715 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 16716 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 16717 Info.offset = 0; 16718 Info.align.reset(); 16719 // volatile loads with NEON intrinsics not supported 16720 Info.flags = MachineMemOperand::MOLoad; 16721 return true; 16722 } 16723 case Intrinsic::arm_neon_vst1: 16724 case Intrinsic::arm_neon_vst2: 16725 case Intrinsic::arm_neon_vst3: 16726 case Intrinsic::arm_neon_vst4: 16727 case Intrinsic::arm_neon_vst2lane: 16728 case Intrinsic::arm_neon_vst3lane: 16729 case Intrinsic::arm_neon_vst4lane: { 16730 Info.opc = ISD::INTRINSIC_VOID; 16731 // Conservatively set memVT to the entire set of vectors stored. 16732 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16733 unsigned NumElts = 0; 16734 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 16735 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 16736 if (!ArgTy->isVectorTy()) 16737 break; 16738 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 16739 } 16740 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 16741 Info.ptrVal = I.getArgOperand(0); 16742 Info.offset = 0; 16743 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 16744 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 16745 // volatile stores with NEON intrinsics not supported 16746 Info.flags = MachineMemOperand::MOStore; 16747 return true; 16748 } 16749 case Intrinsic::arm_neon_vst1x2: 16750 case Intrinsic::arm_neon_vst1x3: 16751 case Intrinsic::arm_neon_vst1x4: { 16752 Info.opc = ISD::INTRINSIC_VOID; 16753 // Conservatively set memVT to the entire set of vectors stored. 16754 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16755 unsigned NumElts = 0; 16756 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 16757 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 16758 if (!ArgTy->isVectorTy()) 16759 break; 16760 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 16761 } 16762 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 16763 Info.ptrVal = I.getArgOperand(0); 16764 Info.offset = 0; 16765 Info.align.reset(); 16766 // volatile stores with NEON intrinsics not supported 16767 Info.flags = MachineMemOperand::MOStore; 16768 return true; 16769 } 16770 case Intrinsic::arm_mve_vld2q: 16771 case Intrinsic::arm_mve_vld4q: { 16772 Info.opc = ISD::INTRINSIC_W_CHAIN; 16773 // Conservatively set memVT to the entire set of vectors loaded. 16774 Type *VecTy = cast<CompositeType>(I.getType())->getTypeAtIndex(1); 16775 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4; 16776 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 16777 Info.ptrVal = I.getArgOperand(0); 16778 Info.offset = 0; 16779 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 16780 // volatile loads with MVE intrinsics not supported 16781 Info.flags = MachineMemOperand::MOLoad; 16782 return true; 16783 } 16784 case Intrinsic::arm_mve_vst2q: 16785 case Intrinsic::arm_mve_vst4q: { 16786 Info.opc = ISD::INTRINSIC_VOID; 16787 // Conservatively set memVT to the entire set of vectors stored. 16788 Type *VecTy = I.getArgOperand(1)->getType(); 16789 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4; 16790 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 16791 Info.ptrVal = I.getArgOperand(0); 16792 Info.offset = 0; 16793 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 16794 // volatile stores with MVE intrinsics not supported 16795 Info.flags = MachineMemOperand::MOStore; 16796 return true; 16797 } 16798 case Intrinsic::arm_ldaex: 16799 case Intrinsic::arm_ldrex: { 16800 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16801 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 16802 Info.opc = ISD::INTRINSIC_W_CHAIN; 16803 Info.memVT = MVT::getVT(PtrTy->getElementType()); 16804 Info.ptrVal = I.getArgOperand(0); 16805 Info.offset = 0; 16806 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 16807 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16808 return true; 16809 } 16810 case Intrinsic::arm_stlex: 16811 case Intrinsic::arm_strex: { 16812 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 16813 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 16814 Info.opc = ISD::INTRINSIC_W_CHAIN; 16815 Info.memVT = MVT::getVT(PtrTy->getElementType()); 16816 Info.ptrVal = I.getArgOperand(1); 16817 Info.offset = 0; 16818 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 16819 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16820 return true; 16821 } 16822 case Intrinsic::arm_stlexd: 16823 case Intrinsic::arm_strexd: 16824 Info.opc = ISD::INTRINSIC_W_CHAIN; 16825 Info.memVT = MVT::i64; 16826 Info.ptrVal = I.getArgOperand(2); 16827 Info.offset = 0; 16828 Info.align = Align(8); 16829 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16830 return true; 16831 16832 case Intrinsic::arm_ldaexd: 16833 case Intrinsic::arm_ldrexd: 16834 Info.opc = ISD::INTRINSIC_W_CHAIN; 16835 Info.memVT = MVT::i64; 16836 Info.ptrVal = I.getArgOperand(0); 16837 Info.offset = 0; 16838 Info.align = Align(8); 16839 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16840 return true; 16841 16842 default: 16843 break; 16844 } 16845 16846 return false; 16847 } 16848 16849 /// Returns true if it is beneficial to convert a load of a constant 16850 /// to just the constant itself. 16851 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16852 Type *Ty) const { 16853 assert(Ty->isIntegerTy()); 16854 16855 unsigned Bits = Ty->getPrimitiveSizeInBits(); 16856 if (Bits == 0 || Bits > 32) 16857 return false; 16858 return true; 16859 } 16860 16861 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 16862 unsigned Index) const { 16863 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 16864 return false; 16865 16866 return (Index == 0 || Index == ResVT.getVectorNumElements()); 16867 } 16868 16869 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 16870 ARM_MB::MemBOpt Domain) const { 16871 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16872 16873 // First, if the target has no DMB, see what fallback we can use. 16874 if (!Subtarget->hasDataBarrier()) { 16875 // Some ARMv6 cpus can support data barriers with an mcr instruction. 16876 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 16877 // here. 16878 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 16879 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 16880 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 16881 Builder.getInt32(0), Builder.getInt32(7), 16882 Builder.getInt32(10), Builder.getInt32(5)}; 16883 return Builder.CreateCall(MCR, args); 16884 } else { 16885 // Instead of using barriers, atomic accesses on these subtargets use 16886 // libcalls. 16887 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 16888 } 16889 } else { 16890 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 16891 // Only a full system barrier exists in the M-class architectures. 16892 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 16893 Constant *CDomain = Builder.getInt32(Domain); 16894 return Builder.CreateCall(DMB, CDomain); 16895 } 16896 } 16897 16898 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 16899 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 16900 Instruction *Inst, 16901 AtomicOrdering Ord) const { 16902 switch (Ord) { 16903 case AtomicOrdering::NotAtomic: 16904 case AtomicOrdering::Unordered: 16905 llvm_unreachable("Invalid fence: unordered/non-atomic"); 16906 case AtomicOrdering::Monotonic: 16907 case AtomicOrdering::Acquire: 16908 return nullptr; // Nothing to do 16909 case AtomicOrdering::SequentiallyConsistent: 16910 if (!Inst->hasAtomicStore()) 16911 return nullptr; // Nothing to do 16912 LLVM_FALLTHROUGH; 16913 case AtomicOrdering::Release: 16914 case AtomicOrdering::AcquireRelease: 16915 if (Subtarget->preferISHSTBarriers()) 16916 return makeDMB(Builder, ARM_MB::ISHST); 16917 // FIXME: add a comment with a link to documentation justifying this. 16918 else 16919 return makeDMB(Builder, ARM_MB::ISH); 16920 } 16921 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 16922 } 16923 16924 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 16925 Instruction *Inst, 16926 AtomicOrdering Ord) const { 16927 switch (Ord) { 16928 case AtomicOrdering::NotAtomic: 16929 case AtomicOrdering::Unordered: 16930 llvm_unreachable("Invalid fence: unordered/not-atomic"); 16931 case AtomicOrdering::Monotonic: 16932 case AtomicOrdering::Release: 16933 return nullptr; // Nothing to do 16934 case AtomicOrdering::Acquire: 16935 case AtomicOrdering::AcquireRelease: 16936 case AtomicOrdering::SequentiallyConsistent: 16937 return makeDMB(Builder, ARM_MB::ISH); 16938 } 16939 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 16940 } 16941 16942 // Loads and stores less than 64-bits are already atomic; ones above that 16943 // are doomed anyway, so defer to the default libcall and blame the OS when 16944 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 16945 // anything for those. 16946 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 16947 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 16948 return (Size == 64) && !Subtarget->isMClass(); 16949 } 16950 16951 // Loads and stores less than 64-bits are already atomic; ones above that 16952 // are doomed anyway, so defer to the default libcall and blame the OS when 16953 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 16954 // anything for those. 16955 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 16956 // guarantee, see DDI0406C ARM architecture reference manual, 16957 // sections A8.8.72-74 LDRD) 16958 TargetLowering::AtomicExpansionKind 16959 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 16960 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 16961 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 16962 : AtomicExpansionKind::None; 16963 } 16964 16965 // For the real atomic operations, we have ldrex/strex up to 32 bits, 16966 // and up to 64 bits on the non-M profiles 16967 TargetLowering::AtomicExpansionKind 16968 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 16969 if (AI->isFloatingPointOperation()) 16970 return AtomicExpansionKind::CmpXChg; 16971 16972 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 16973 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 16974 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 16975 ? AtomicExpansionKind::LLSC 16976 : AtomicExpansionKind::None; 16977 } 16978 16979 TargetLowering::AtomicExpansionKind 16980 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 16981 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 16982 // implement cmpxchg without spilling. If the address being exchanged is also 16983 // on the stack and close enough to the spill slot, this can lead to a 16984 // situation where the monitor always gets cleared and the atomic operation 16985 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 16986 bool HasAtomicCmpXchg = 16987 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 16988 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 16989 return AtomicExpansionKind::LLSC; 16990 return AtomicExpansionKind::None; 16991 } 16992 16993 bool ARMTargetLowering::shouldInsertFencesForAtomic( 16994 const Instruction *I) const { 16995 return InsertFencesForAtomic; 16996 } 16997 16998 // This has so far only been implemented for MachO. 16999 bool ARMTargetLowering::useLoadStackGuardNode() const { 17000 return Subtarget->isTargetMachO(); 17001 } 17002 17003 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 17004 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 17005 return TargetLowering::insertSSPDeclarations(M); 17006 17007 // MSVC CRT has a global variable holding security cookie. 17008 M.getOrInsertGlobal("__security_cookie", 17009 Type::getInt8PtrTy(M.getContext())); 17010 17011 // MSVC CRT has a function to validate security cookie. 17012 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 17013 "__security_check_cookie", Type::getVoidTy(M.getContext()), 17014 Type::getInt8PtrTy(M.getContext())); 17015 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 17016 F->addAttribute(1, Attribute::AttrKind::InReg); 17017 } 17018 17019 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 17020 // MSVC CRT has a global variable holding security cookie. 17021 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 17022 return M.getGlobalVariable("__security_cookie"); 17023 return TargetLowering::getSDagStackGuard(M); 17024 } 17025 17026 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 17027 // MSVC CRT has a function to validate security cookie. 17028 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 17029 return M.getFunction("__security_check_cookie"); 17030 return TargetLowering::getSSPStackGuardCheck(M); 17031 } 17032 17033 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 17034 unsigned &Cost) const { 17035 // If we do not have NEON, vector types are not natively supported. 17036 if (!Subtarget->hasNEON()) 17037 return false; 17038 17039 // Floating point values and vector values map to the same register file. 17040 // Therefore, although we could do a store extract of a vector type, this is 17041 // better to leave at float as we have more freedom in the addressing mode for 17042 // those. 17043 if (VectorTy->isFPOrFPVectorTy()) 17044 return false; 17045 17046 // If the index is unknown at compile time, this is very expensive to lower 17047 // and it is not possible to combine the store with the extract. 17048 if (!isa<ConstantInt>(Idx)) 17049 return false; 17050 17051 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 17052 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 17053 // We can do a store + vector extract on any vector that fits perfectly in a D 17054 // or Q register. 17055 if (BitWidth == 64 || BitWidth == 128) { 17056 Cost = 0; 17057 return true; 17058 } 17059 return false; 17060 } 17061 17062 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 17063 return Subtarget->hasV6T2Ops(); 17064 } 17065 17066 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 17067 return Subtarget->hasV6T2Ops(); 17068 } 17069 17070 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 17071 return !Subtarget->hasMinSize(); 17072 } 17073 17074 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 17075 AtomicOrdering Ord) const { 17076 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 17077 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 17078 bool IsAcquire = isAcquireOrStronger(Ord); 17079 17080 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 17081 // intrinsic must return {i32, i32} and we have to recombine them into a 17082 // single i64 here. 17083 if (ValTy->getPrimitiveSizeInBits() == 64) { 17084 Intrinsic::ID Int = 17085 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 17086 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 17087 17088 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 17089 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 17090 17091 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 17092 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 17093 if (!Subtarget->isLittle()) 17094 std::swap (Lo, Hi); 17095 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 17096 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 17097 return Builder.CreateOr( 17098 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 17099 } 17100 17101 Type *Tys[] = { Addr->getType() }; 17102 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 17103 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 17104 17105 return Builder.CreateTruncOrBitCast( 17106 Builder.CreateCall(Ldrex, Addr), 17107 cast<PointerType>(Addr->getType())->getElementType()); 17108 } 17109 17110 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 17111 IRBuilder<> &Builder) const { 17112 if (!Subtarget->hasV7Ops()) 17113 return; 17114 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 17115 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 17116 } 17117 17118 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 17119 Value *Addr, 17120 AtomicOrdering Ord) const { 17121 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 17122 bool IsRelease = isReleaseOrStronger(Ord); 17123 17124 // Since the intrinsics must have legal type, the i64 intrinsics take two 17125 // parameters: "i32, i32". We must marshal Val into the appropriate form 17126 // before the call. 17127 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 17128 Intrinsic::ID Int = 17129 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 17130 Function *Strex = Intrinsic::getDeclaration(M, Int); 17131 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 17132 17133 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 17134 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 17135 if (!Subtarget->isLittle()) 17136 std::swap(Lo, Hi); 17137 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 17138 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 17139 } 17140 17141 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 17142 Type *Tys[] = { Addr->getType() }; 17143 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 17144 17145 return Builder.CreateCall( 17146 Strex, {Builder.CreateZExtOrBitCast( 17147 Val, Strex->getFunctionType()->getParamType(0)), 17148 Addr}); 17149 } 17150 17151 17152 bool ARMTargetLowering::alignLoopsWithOptSize() const { 17153 return Subtarget->isMClass(); 17154 } 17155 17156 /// A helper function for determining the number of interleaved accesses we 17157 /// will generate when lowering accesses of the given type. 17158 unsigned 17159 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 17160 const DataLayout &DL) const { 17161 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 17162 } 17163 17164 bool ARMTargetLowering::isLegalInterleavedAccessType( 17165 unsigned Factor, VectorType *VecTy, const DataLayout &DL) const { 17166 17167 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 17168 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 17169 17170 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) 17171 return false; 17172 17173 // Ensure the vector doesn't have f16 elements. Even though we could do an 17174 // i16 vldN, we can't hold the f16 vectors and will end up converting via 17175 // f32. 17176 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy()) 17177 return false; 17178 if (Subtarget->hasMVEIntegerOps() && Factor == 3) 17179 return false; 17180 17181 // Ensure the number of vector elements is greater than 1. 17182 if (VecTy->getNumElements() < 2) 17183 return false; 17184 17185 // Ensure the element type is legal. 17186 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 17187 return false; 17188 17189 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 17190 // 128 will be split into multiple interleaved accesses. 17191 if (Subtarget->hasNEON() && VecSize == 64) 17192 return true; 17193 return VecSize % 128 == 0; 17194 } 17195 17196 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const { 17197 if (Subtarget->hasNEON()) 17198 return 4; 17199 if (Subtarget->hasMVEIntegerOps()) 17200 return MVEMaxSupportedInterleaveFactor; 17201 return TargetLoweringBase::getMaxSupportedInterleaveFactor(); 17202 } 17203 17204 /// Lower an interleaved load into a vldN intrinsic. 17205 /// 17206 /// E.g. Lower an interleaved load (Factor = 2): 17207 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 17208 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 17209 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 17210 /// 17211 /// Into: 17212 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 17213 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 17214 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 17215 bool ARMTargetLowering::lowerInterleavedLoad( 17216 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 17217 ArrayRef<unsigned> Indices, unsigned Factor) const { 17218 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 17219 "Invalid interleave factor"); 17220 assert(!Shuffles.empty() && "Empty shufflevector input"); 17221 assert(Shuffles.size() == Indices.size() && 17222 "Unmatched number of shufflevectors and indices"); 17223 17224 VectorType *VecTy = Shuffles[0]->getType(); 17225 Type *EltTy = VecTy->getVectorElementType(); 17226 17227 const DataLayout &DL = LI->getModule()->getDataLayout(); 17228 17229 // Skip if we do not have NEON and skip illegal vector types. We can 17230 // "legalize" wide vector types into multiple interleaved accesses as long as 17231 // the vector types are divisible by 128. 17232 if (!isLegalInterleavedAccessType(Factor, VecTy, DL)) 17233 return false; 17234 17235 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 17236 17237 // A pointer vector can not be the return type of the ldN intrinsics. Need to 17238 // load integer vectors first and then convert to pointer vectors. 17239 if (EltTy->isPointerTy()) 17240 VecTy = 17241 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 17242 17243 IRBuilder<> Builder(LI); 17244 17245 // The base address of the load. 17246 Value *BaseAddr = LI->getPointerOperand(); 17247 17248 if (NumLoads > 1) { 17249 // If we're going to generate more than one load, reset the sub-vector type 17250 // to something legal. 17251 VecTy = VectorType::get(VecTy->getVectorElementType(), 17252 VecTy->getVectorNumElements() / NumLoads); 17253 17254 // We will compute the pointer operand of each load from the original base 17255 // address using GEPs. Cast the base address to a pointer to the scalar 17256 // element type. 17257 BaseAddr = Builder.CreateBitCast( 17258 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 17259 LI->getPointerAddressSpace())); 17260 } 17261 17262 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 17263 17264 auto createLoadIntrinsic = [&](Value *BaseAddr) { 17265 if (Subtarget->hasNEON()) { 17266 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 17267 Type *Tys[] = {VecTy, Int8Ptr}; 17268 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 17269 Intrinsic::arm_neon_vld3, 17270 Intrinsic::arm_neon_vld4}; 17271 Function *VldnFunc = 17272 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 17273 17274 SmallVector<Value *, 2> Ops; 17275 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 17276 Ops.push_back(Builder.getInt32(LI->getAlignment())); 17277 17278 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 17279 } else { 17280 assert((Factor == 2 || Factor == 4) && 17281 "expected interleave factor of 2 or 4 for MVE"); 17282 Intrinsic::ID LoadInts = 17283 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q; 17284 Type *VecEltTy = VecTy->getVectorElementType()->getPointerTo( 17285 LI->getPointerAddressSpace()); 17286 Type *Tys[] = {VecTy, VecEltTy}; 17287 Function *VldnFunc = 17288 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys); 17289 17290 SmallVector<Value *, 2> Ops; 17291 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy)); 17292 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 17293 } 17294 }; 17295 17296 // Holds sub-vectors extracted from the load intrinsic return values. The 17297 // sub-vectors are associated with the shufflevector instructions they will 17298 // replace. 17299 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 17300 17301 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 17302 // If we're generating more than one load, compute the base address of 17303 // subsequent loads as an offset from the previous. 17304 if (LoadCount > 0) 17305 BaseAddr = 17306 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 17307 VecTy->getVectorNumElements() * Factor); 17308 17309 CallInst *VldN = createLoadIntrinsic(BaseAddr); 17310 17311 // Replace uses of each shufflevector with the corresponding vector loaded 17312 // by ldN. 17313 for (unsigned i = 0; i < Shuffles.size(); i++) { 17314 ShuffleVectorInst *SV = Shuffles[i]; 17315 unsigned Index = Indices[i]; 17316 17317 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 17318 17319 // Convert the integer vector to pointer vector if the element is pointer. 17320 if (EltTy->isPointerTy()) 17321 SubVec = Builder.CreateIntToPtr( 17322 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 17323 VecTy->getVectorNumElements())); 17324 17325 SubVecs[SV].push_back(SubVec); 17326 } 17327 } 17328 17329 // Replace uses of the shufflevector instructions with the sub-vectors 17330 // returned by the load intrinsic. If a shufflevector instruction is 17331 // associated with more than one sub-vector, those sub-vectors will be 17332 // concatenated into a single wide vector. 17333 for (ShuffleVectorInst *SVI : Shuffles) { 17334 auto &SubVec = SubVecs[SVI]; 17335 auto *WideVec = 17336 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 17337 SVI->replaceAllUsesWith(WideVec); 17338 } 17339 17340 return true; 17341 } 17342 17343 /// Lower an interleaved store into a vstN intrinsic. 17344 /// 17345 /// E.g. Lower an interleaved store (Factor = 3): 17346 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 17347 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 17348 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 17349 /// 17350 /// Into: 17351 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 17352 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 17353 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 17354 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 17355 /// 17356 /// Note that the new shufflevectors will be removed and we'll only generate one 17357 /// vst3 instruction in CodeGen. 17358 /// 17359 /// Example for a more general valid mask (Factor 3). Lower: 17360 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 17361 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 17362 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 17363 /// 17364 /// Into: 17365 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 17366 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 17367 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 17368 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 17369 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 17370 ShuffleVectorInst *SVI, 17371 unsigned Factor) const { 17372 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 17373 "Invalid interleave factor"); 17374 17375 VectorType *VecTy = SVI->getType(); 17376 assert(VecTy->getVectorNumElements() % Factor == 0 && 17377 "Invalid interleaved store"); 17378 17379 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 17380 Type *EltTy = VecTy->getVectorElementType(); 17381 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 17382 17383 const DataLayout &DL = SI->getModule()->getDataLayout(); 17384 17385 // Skip if we do not have NEON and skip illegal vector types. We can 17386 // "legalize" wide vector types into multiple interleaved accesses as long as 17387 // the vector types are divisible by 128. 17388 if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL)) 17389 return false; 17390 17391 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 17392 17393 Value *Op0 = SVI->getOperand(0); 17394 Value *Op1 = SVI->getOperand(1); 17395 IRBuilder<> Builder(SI); 17396 17397 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 17398 // vectors to integer vectors. 17399 if (EltTy->isPointerTy()) { 17400 Type *IntTy = DL.getIntPtrType(EltTy); 17401 17402 // Convert to the corresponding integer vector. 17403 Type *IntVecTy = 17404 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 17405 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 17406 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 17407 17408 SubVecTy = VectorType::get(IntTy, LaneLen); 17409 } 17410 17411 // The base address of the store. 17412 Value *BaseAddr = SI->getPointerOperand(); 17413 17414 if (NumStores > 1) { 17415 // If we're going to generate more than one store, reset the lane length 17416 // and sub-vector type to something legal. 17417 LaneLen /= NumStores; 17418 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 17419 17420 // We will compute the pointer operand of each store from the original base 17421 // address using GEPs. Cast the base address to a pointer to the scalar 17422 // element type. 17423 BaseAddr = Builder.CreateBitCast( 17424 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 17425 SI->getPointerAddressSpace())); 17426 } 17427 17428 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 17429 17430 auto Mask = SVI->getShuffleMask(); 17431 17432 auto createStoreIntrinsic = [&](Value *BaseAddr, 17433 SmallVectorImpl<Value *> &Shuffles) { 17434 if (Subtarget->hasNEON()) { 17435 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 17436 Intrinsic::arm_neon_vst3, 17437 Intrinsic::arm_neon_vst4}; 17438 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 17439 Type *Tys[] = {Int8Ptr, SubVecTy}; 17440 17441 Function *VstNFunc = Intrinsic::getDeclaration( 17442 SI->getModule(), StoreInts[Factor - 2], Tys); 17443 17444 SmallVector<Value *, 6> Ops; 17445 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 17446 for (auto S : Shuffles) 17447 Ops.push_back(S); 17448 Ops.push_back(Builder.getInt32(SI->getAlignment())); 17449 Builder.CreateCall(VstNFunc, Ops); 17450 } else { 17451 assert((Factor == 2 || Factor == 4) && 17452 "expected interleave factor of 2 or 4 for MVE"); 17453 Intrinsic::ID StoreInts = 17454 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q; 17455 Type *EltPtrTy = SubVecTy->getVectorElementType()->getPointerTo( 17456 SI->getPointerAddressSpace()); 17457 Type *Tys[] = {EltPtrTy, SubVecTy}; 17458 Function *VstNFunc = 17459 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys); 17460 17461 SmallVector<Value *, 6> Ops; 17462 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy)); 17463 for (auto S : Shuffles) 17464 Ops.push_back(S); 17465 for (unsigned F = 0; F < Factor; F++) { 17466 Ops.push_back(Builder.getInt32(F)); 17467 Builder.CreateCall(VstNFunc, Ops); 17468 Ops.pop_back(); 17469 } 17470 } 17471 }; 17472 17473 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 17474 // If we generating more than one store, we compute the base address of 17475 // subsequent stores as an offset from the previous. 17476 if (StoreCount > 0) 17477 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 17478 BaseAddr, LaneLen * Factor); 17479 17480 SmallVector<Value *, 4> Shuffles; 17481 17482 // Split the shufflevector operands into sub vectors for the new vstN call. 17483 for (unsigned i = 0; i < Factor; i++) { 17484 unsigned IdxI = StoreCount * LaneLen * Factor + i; 17485 if (Mask[IdxI] >= 0) { 17486 Shuffles.push_back(Builder.CreateShuffleVector( 17487 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 17488 } else { 17489 unsigned StartMask = 0; 17490 for (unsigned j = 1; j < LaneLen; j++) { 17491 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 17492 if (Mask[IdxJ * Factor + IdxI] >= 0) { 17493 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 17494 break; 17495 } 17496 } 17497 // Note: If all elements in a chunk are undefs, StartMask=0! 17498 // Note: Filling undef gaps with random elements is ok, since 17499 // those elements were being written anyway (with undefs). 17500 // In the case of all undefs we're defaulting to using elems from 0 17501 // Note: StartMask cannot be negative, it's checked in 17502 // isReInterleaveMask 17503 Shuffles.push_back(Builder.CreateShuffleVector( 17504 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 17505 } 17506 } 17507 17508 createStoreIntrinsic(BaseAddr, Shuffles); 17509 } 17510 return true; 17511 } 17512 17513 enum HABaseType { 17514 HA_UNKNOWN = 0, 17515 HA_FLOAT, 17516 HA_DOUBLE, 17517 HA_VECT64, 17518 HA_VECT128 17519 }; 17520 17521 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 17522 uint64_t &Members) { 17523 if (auto *ST = dyn_cast<StructType>(Ty)) { 17524 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 17525 uint64_t SubMembers = 0; 17526 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 17527 return false; 17528 Members += SubMembers; 17529 } 17530 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 17531 uint64_t SubMembers = 0; 17532 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 17533 return false; 17534 Members += SubMembers * AT->getNumElements(); 17535 } else if (Ty->isFloatTy()) { 17536 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 17537 return false; 17538 Members = 1; 17539 Base = HA_FLOAT; 17540 } else if (Ty->isDoubleTy()) { 17541 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 17542 return false; 17543 Members = 1; 17544 Base = HA_DOUBLE; 17545 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 17546 Members = 1; 17547 switch (Base) { 17548 case HA_FLOAT: 17549 case HA_DOUBLE: 17550 return false; 17551 case HA_VECT64: 17552 return VT->getBitWidth() == 64; 17553 case HA_VECT128: 17554 return VT->getBitWidth() == 128; 17555 case HA_UNKNOWN: 17556 switch (VT->getBitWidth()) { 17557 case 64: 17558 Base = HA_VECT64; 17559 return true; 17560 case 128: 17561 Base = HA_VECT128; 17562 return true; 17563 default: 17564 return false; 17565 } 17566 } 17567 } 17568 17569 return (Members > 0 && Members <= 4); 17570 } 17571 17572 /// Return the correct alignment for the current calling convention. 17573 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 17574 DataLayout DL) const { 17575 const Align ABITypeAlign(DL.getABITypeAlignment(ArgTy)); 17576 if (!ArgTy->isVectorTy()) 17577 return ABITypeAlign; 17578 17579 // Avoid over-aligning vector parameters. It would require realigning the 17580 // stack and waste space for no real benefit. 17581 return std::min(ABITypeAlign, DL.getStackAlignment()); 17582 } 17583 17584 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 17585 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 17586 /// passing according to AAPCS rules. 17587 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 17588 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 17589 if (getEffectiveCallingConv(CallConv, isVarArg) != 17590 CallingConv::ARM_AAPCS_VFP) 17591 return false; 17592 17593 HABaseType Base = HA_UNKNOWN; 17594 uint64_t Members = 0; 17595 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 17596 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 17597 17598 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 17599 return IsHA || IsIntArray; 17600 } 17601 17602 unsigned ARMTargetLowering::getExceptionPointerRegister( 17603 const Constant *PersonalityFn) const { 17604 // Platforms which do not use SjLj EH may return values in these registers 17605 // via the personality function. 17606 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 17607 } 17608 17609 unsigned ARMTargetLowering::getExceptionSelectorRegister( 17610 const Constant *PersonalityFn) const { 17611 // Platforms which do not use SjLj EH may return values in these registers 17612 // via the personality function. 17613 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 17614 } 17615 17616 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 17617 // Update IsSplitCSR in ARMFunctionInfo. 17618 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 17619 AFI->setIsSplitCSR(true); 17620 } 17621 17622 void ARMTargetLowering::insertCopiesSplitCSR( 17623 MachineBasicBlock *Entry, 17624 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 17625 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 17626 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 17627 if (!IStart) 17628 return; 17629 17630 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 17631 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 17632 MachineBasicBlock::iterator MBBI = Entry->begin(); 17633 for (const MCPhysReg *I = IStart; *I; ++I) { 17634 const TargetRegisterClass *RC = nullptr; 17635 if (ARM::GPRRegClass.contains(*I)) 17636 RC = &ARM::GPRRegClass; 17637 else if (ARM::DPRRegClass.contains(*I)) 17638 RC = &ARM::DPRRegClass; 17639 else 17640 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 17641 17642 Register NewVR = MRI->createVirtualRegister(RC); 17643 // Create copy from CSR to a virtual register. 17644 // FIXME: this currently does not emit CFI pseudo-instructions, it works 17645 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 17646 // nounwind. If we want to generalize this later, we may need to emit 17647 // CFI pseudo-instructions. 17648 assert(Entry->getParent()->getFunction().hasFnAttribute( 17649 Attribute::NoUnwind) && 17650 "Function should be nounwind in insertCopiesSplitCSR!"); 17651 Entry->addLiveIn(*I); 17652 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 17653 .addReg(*I); 17654 17655 // Insert the copy-back instructions right before the terminator. 17656 for (auto *Exit : Exits) 17657 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 17658 TII->get(TargetOpcode::COPY), *I) 17659 .addReg(NewVR); 17660 } 17661 } 17662 17663 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 17664 MF.getFrameInfo().computeMaxCallFrameSize(MF); 17665 TargetLoweringBase::finalizeLowering(MF); 17666 } 17667