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 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 setOperationAction(ISD::SDIVREM, VT, Expand); 214 setOperationAction(ISD::UDIVREM, VT, Expand); 215 216 if (!VT.isFloatingPoint() && 217 VT != MVT::v2i64 && VT != MVT::v1i64) 218 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 219 setOperationAction(Opcode, VT, Legal); 220 if (!VT.isFloatingPoint()) 221 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}) 222 setOperationAction(Opcode, VT, Legal); 223 } 224 225 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 226 addRegisterClass(VT, &ARM::DPRRegClass); 227 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 228 } 229 230 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 231 addRegisterClass(VT, &ARM::DPairRegClass); 232 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 233 } 234 235 void ARMTargetLowering::setAllExpand(MVT VT) { 236 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc) 237 setOperationAction(Opc, VT, Expand); 238 239 // We support these really simple operations even on types where all 240 // the actual arithmetic has to be broken down into simpler 241 // operations or turned into library calls. 242 setOperationAction(ISD::BITCAST, VT, Legal); 243 setOperationAction(ISD::LOAD, VT, Legal); 244 setOperationAction(ISD::STORE, VT, Legal); 245 setOperationAction(ISD::UNDEF, VT, Legal); 246 } 247 248 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To, 249 LegalizeAction Action) { 250 setLoadExtAction(ISD::EXTLOAD, From, To, Action); 251 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action); 252 setLoadExtAction(ISD::SEXTLOAD, From, To, Action); 253 } 254 255 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) { 256 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 }; 257 258 for (auto VT : IntTypes) { 259 addRegisterClass(VT, &ARM::MQPRRegClass); 260 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 261 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 262 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 263 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 264 setOperationAction(ISD::SHL, VT, Custom); 265 setOperationAction(ISD::SRA, VT, Custom); 266 setOperationAction(ISD::SRL, VT, Custom); 267 setOperationAction(ISD::SMIN, VT, Legal); 268 setOperationAction(ISD::SMAX, VT, Legal); 269 setOperationAction(ISD::UMIN, VT, Legal); 270 setOperationAction(ISD::UMAX, VT, Legal); 271 setOperationAction(ISD::ABS, VT, Legal); 272 setOperationAction(ISD::SETCC, VT, Custom); 273 setOperationAction(ISD::MLOAD, VT, Custom); 274 setOperationAction(ISD::MSTORE, VT, Legal); 275 setOperationAction(ISD::CTLZ, VT, Legal); 276 setOperationAction(ISD::CTTZ, VT, Custom); 277 setOperationAction(ISD::BITREVERSE, VT, Legal); 278 setOperationAction(ISD::BSWAP, VT, Legal); 279 setOperationAction(ISD::SADDSAT, VT, Legal); 280 setOperationAction(ISD::UADDSAT, VT, Legal); 281 setOperationAction(ISD::SSUBSAT, VT, Legal); 282 setOperationAction(ISD::USUBSAT, VT, Legal); 283 284 // No native support for these. 285 setOperationAction(ISD::UDIV, VT, Expand); 286 setOperationAction(ISD::SDIV, VT, Expand); 287 setOperationAction(ISD::UREM, VT, Expand); 288 setOperationAction(ISD::SREM, VT, Expand); 289 setOperationAction(ISD::UDIVREM, VT, Expand); 290 setOperationAction(ISD::SDIVREM, VT, Expand); 291 setOperationAction(ISD::CTPOP, VT, Expand); 292 293 // Vector reductions 294 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal); 295 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal); 296 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal); 297 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal); 298 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal); 299 setOperationAction(ISD::VECREDUCE_MUL, VT, Custom); 300 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 301 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 302 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 303 304 if (!HasMVEFP) { 305 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 306 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 307 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 308 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 309 } 310 311 // Pre and Post inc are supported on loads and stores 312 for (unsigned im = (unsigned)ISD::PRE_INC; 313 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 314 setIndexedLoadAction(im, VT, Legal); 315 setIndexedStoreAction(im, VT, Legal); 316 setIndexedMaskedLoadAction(im, VT, Legal); 317 setIndexedMaskedStoreAction(im, VT, Legal); 318 } 319 } 320 321 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 322 for (auto VT : FloatTypes) { 323 addRegisterClass(VT, &ARM::MQPRRegClass); 324 if (!HasMVEFP) 325 setAllExpand(VT); 326 327 // These are legal or custom whether we have MVE.fp or not 328 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 329 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 330 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 331 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 332 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 333 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 334 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 335 setOperationAction(ISD::SETCC, VT, Custom); 336 setOperationAction(ISD::MLOAD, VT, Custom); 337 setOperationAction(ISD::MSTORE, VT, Legal); 338 339 // Pre and Post inc are supported on loads and stores 340 for (unsigned im = (unsigned)ISD::PRE_INC; 341 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 342 setIndexedLoadAction(im, VT, Legal); 343 setIndexedStoreAction(im, VT, Legal); 344 setIndexedMaskedLoadAction(im, VT, Legal); 345 setIndexedMaskedStoreAction(im, VT, Legal); 346 } 347 348 if (HasMVEFP) { 349 setOperationAction(ISD::FMINNUM, VT, Legal); 350 setOperationAction(ISD::FMAXNUM, VT, Legal); 351 setOperationAction(ISD::FROUND, VT, Legal); 352 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 353 setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom); 354 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 355 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 356 357 // No native support for these. 358 setOperationAction(ISD::FDIV, VT, Expand); 359 setOperationAction(ISD::FREM, VT, Expand); 360 setOperationAction(ISD::FSQRT, VT, Expand); 361 setOperationAction(ISD::FSIN, VT, Expand); 362 setOperationAction(ISD::FCOS, VT, Expand); 363 setOperationAction(ISD::FPOW, VT, Expand); 364 setOperationAction(ISD::FLOG, VT, Expand); 365 setOperationAction(ISD::FLOG2, VT, Expand); 366 setOperationAction(ISD::FLOG10, VT, Expand); 367 setOperationAction(ISD::FEXP, VT, Expand); 368 setOperationAction(ISD::FEXP2, VT, Expand); 369 setOperationAction(ISD::FNEARBYINT, VT, Expand); 370 } 371 } 372 373 // Custom Expand smaller than legal vector reductions to prevent false zero 374 // items being added. 375 setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom); 376 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom); 377 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom); 378 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom); 379 setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom); 380 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom); 381 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom); 382 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom); 383 384 // We 'support' these types up to bitcast/load/store level, regardless of 385 // MVE integer-only / float support. Only doing FP data processing on the FP 386 // vector types is inhibited at integer-only level. 387 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 388 for (auto VT : LongTypes) { 389 addRegisterClass(VT, &ARM::MQPRRegClass); 390 setAllExpand(VT); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 393 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 394 } 395 // We can do bitwise operations on v2i64 vectors 396 setOperationAction(ISD::AND, MVT::v2i64, Legal); 397 setOperationAction(ISD::OR, MVT::v2i64, Legal); 398 setOperationAction(ISD::XOR, MVT::v2i64, Legal); 399 400 // It is legal to extload from v4i8 to v4i16 or v4i32. 401 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 402 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 403 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 404 405 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16. 406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 408 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 409 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Legal); 410 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal); 411 412 // Some truncating stores are legal too. 413 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 414 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 415 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 416 417 // Pre and Post inc on these are legal, given the correct extends 418 for (unsigned im = (unsigned)ISD::PRE_INC; 419 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 420 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) { 421 setIndexedLoadAction(im, VT, Legal); 422 setIndexedStoreAction(im, VT, Legal); 423 setIndexedMaskedLoadAction(im, VT, Legal); 424 setIndexedMaskedStoreAction(im, VT, Legal); 425 } 426 } 427 428 // Predicate types 429 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1}; 430 for (auto VT : pTypes) { 431 addRegisterClass(VT, &ARM::VCCRRegClass); 432 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 433 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 434 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 435 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 436 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 437 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 438 setOperationAction(ISD::SETCC, VT, Custom); 439 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 440 setOperationAction(ISD::LOAD, VT, Custom); 441 setOperationAction(ISD::STORE, VT, Custom); 442 } 443 } 444 445 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 446 const ARMSubtarget &STI) 447 : TargetLowering(TM), Subtarget(&STI) { 448 RegInfo = Subtarget->getRegisterInfo(); 449 Itins = Subtarget->getInstrItineraryData(); 450 451 setBooleanContents(ZeroOrOneBooleanContent); 452 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 453 454 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 455 !Subtarget->isTargetWatchOS()) { 456 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 457 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 458 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 459 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 460 : CallingConv::ARM_AAPCS); 461 } 462 463 if (Subtarget->isTargetMachO()) { 464 // Uses VFP for Thumb libfuncs if available. 465 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 466 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 467 static const struct { 468 const RTLIB::Libcall Op; 469 const char * const Name; 470 const ISD::CondCode Cond; 471 } LibraryCalls[] = { 472 // Single-precision floating-point arithmetic. 473 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 474 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 475 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 476 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 477 478 // Double-precision floating-point arithmetic. 479 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 480 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 481 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 482 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 483 484 // Single-precision comparisons. 485 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 486 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 487 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 488 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 489 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 490 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 491 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 492 493 // Double-precision comparisons. 494 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 495 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 496 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 497 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 498 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 499 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 500 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 501 502 // Floating-point to integer conversions. 503 // i64 conversions are done via library routines even when generating VFP 504 // instructions, so use the same ones. 505 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 506 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 507 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 508 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 509 510 // Conversions between floating types. 511 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 512 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 513 514 // Integer to floating-point conversions. 515 // i64 conversions are done via library routines even when generating VFP 516 // instructions, so use the same ones. 517 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 518 // e.g., __floatunsidf vs. __floatunssidfvfp. 519 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 520 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 521 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 522 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 523 }; 524 525 for (const auto &LC : LibraryCalls) { 526 setLibcallName(LC.Op, LC.Name); 527 if (LC.Cond != ISD::SETCC_INVALID) 528 setCmpLibcallCC(LC.Op, LC.Cond); 529 } 530 } 531 } 532 533 // These libcalls are not available in 32-bit. 534 setLibcallName(RTLIB::SHL_I128, nullptr); 535 setLibcallName(RTLIB::SRL_I128, nullptr); 536 setLibcallName(RTLIB::SRA_I128, nullptr); 537 538 // RTLIB 539 if (Subtarget->isAAPCS_ABI() && 540 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 541 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 542 static const struct { 543 const RTLIB::Libcall Op; 544 const char * const Name; 545 const CallingConv::ID CC; 546 const ISD::CondCode Cond; 547 } LibraryCalls[] = { 548 // Double-precision floating-point arithmetic helper functions 549 // RTABI chapter 4.1.2, Table 2 550 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 551 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 552 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 553 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 554 555 // Double-precision floating-point comparison helper functions 556 // RTABI chapter 4.1.2, Table 3 557 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 558 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 559 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 560 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 561 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 562 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 563 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 564 565 // Single-precision floating-point arithmetic helper functions 566 // RTABI chapter 4.1.2, Table 4 567 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 568 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 569 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 570 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 571 572 // Single-precision floating-point comparison helper functions 573 // RTABI chapter 4.1.2, Table 5 574 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 575 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 576 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 577 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 578 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 579 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 580 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 581 582 // Floating-point to integer conversions. 583 // RTABI chapter 4.1.2, Table 6 584 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 585 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 586 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 587 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 588 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 589 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 590 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 591 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 592 593 // Conversions between floating types. 594 // RTABI chapter 4.1.2, Table 7 595 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 596 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 597 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 598 599 // Integer to floating-point conversions. 600 // RTABI chapter 4.1.2, Table 8 601 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 602 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 603 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 604 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 605 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 606 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 607 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 608 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 609 610 // Long long helper functions 611 // RTABI chapter 4.2, Table 9 612 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 613 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 614 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 615 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 616 617 // Integer division functions 618 // RTABI chapter 4.3.1 619 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 620 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 621 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 622 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 623 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 624 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 625 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 626 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 627 }; 628 629 for (const auto &LC : LibraryCalls) { 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 // EABI dependent RTLIB 637 if (TM.Options.EABIVersion == EABI::EABI4 || 638 TM.Options.EABIVersion == EABI::EABI5) { 639 static const struct { 640 const RTLIB::Libcall Op; 641 const char *const Name; 642 const CallingConv::ID CC; 643 const ISD::CondCode Cond; 644 } MemOpsLibraryCalls[] = { 645 // Memory operations 646 // RTABI chapter 4.3.4 647 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 648 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 649 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 650 }; 651 652 for (const auto &LC : MemOpsLibraryCalls) { 653 setLibcallName(LC.Op, LC.Name); 654 setLibcallCallingConv(LC.Op, LC.CC); 655 if (LC.Cond != ISD::SETCC_INVALID) 656 setCmpLibcallCC(LC.Op, LC.Cond); 657 } 658 } 659 } 660 661 if (Subtarget->isTargetWindows()) { 662 static const struct { 663 const RTLIB::Libcall Op; 664 const char * const Name; 665 const CallingConv::ID CC; 666 } LibraryCalls[] = { 667 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 668 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 669 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 670 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 671 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 672 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 673 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 674 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 675 }; 676 677 for (const auto &LC : LibraryCalls) { 678 setLibcallName(LC.Op, LC.Name); 679 setLibcallCallingConv(LC.Op, LC.CC); 680 } 681 } 682 683 // Use divmod compiler-rt calls for iOS 5.0 and later. 684 if (Subtarget->isTargetMachO() && 685 !(Subtarget->isTargetIOS() && 686 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 687 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 688 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 689 } 690 691 // The half <-> float conversion functions are always soft-float on 692 // non-watchos platforms, but are needed for some targets which use a 693 // hard-float calling convention by default. 694 if (!Subtarget->isTargetWatchABI()) { 695 if (Subtarget->isAAPCS_ABI()) { 696 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 697 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 698 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 699 } else { 700 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 701 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 702 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 703 } 704 } 705 706 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 707 // a __gnu_ prefix (which is the default). 708 if (Subtarget->isTargetAEABI()) { 709 static const struct { 710 const RTLIB::Libcall Op; 711 const char * const Name; 712 const CallingConv::ID CC; 713 } LibraryCalls[] = { 714 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 715 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 716 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 717 }; 718 719 for (const auto &LC : LibraryCalls) { 720 setLibcallName(LC.Op, LC.Name); 721 setLibcallCallingConv(LC.Op, LC.CC); 722 } 723 } 724 725 if (Subtarget->isThumb1Only()) 726 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 727 else 728 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 729 730 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 731 Subtarget->hasFPRegs()) { 732 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 733 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 734 if (!Subtarget->hasVFP2Base()) 735 setAllExpand(MVT::f32); 736 if (!Subtarget->hasFP64()) 737 setAllExpand(MVT::f64); 738 } 739 740 if (Subtarget->hasFullFP16()) { 741 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 742 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 743 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 744 745 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 746 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 747 } 748 749 if (Subtarget->hasBF16()) { 750 addRegisterClass(MVT::bf16, &ARM::HPRRegClass); 751 setAllExpand(MVT::bf16); 752 if (!Subtarget->hasFullFP16()) 753 setOperationAction(ISD::BITCAST, MVT::bf16, Custom); 754 } 755 756 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 757 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 758 setTruncStoreAction(VT, InnerVT, Expand); 759 addAllExtLoads(VT, InnerVT, Expand); 760 } 761 762 setOperationAction(ISD::MULHS, VT, Expand); 763 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 764 setOperationAction(ISD::MULHU, VT, Expand); 765 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 766 767 setOperationAction(ISD::BSWAP, VT, Expand); 768 } 769 770 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 771 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 772 773 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 774 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 775 776 if (Subtarget->hasMVEIntegerOps()) 777 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 778 779 // Combine low-overhead loop intrinsics so that we can lower i1 types. 780 if (Subtarget->hasLOB()) { 781 setTargetDAGCombine(ISD::BRCOND); 782 setTargetDAGCombine(ISD::BR_CC); 783 } 784 785 if (Subtarget->hasNEON()) { 786 addDRTypeForNEON(MVT::v2f32); 787 addDRTypeForNEON(MVT::v8i8); 788 addDRTypeForNEON(MVT::v4i16); 789 addDRTypeForNEON(MVT::v2i32); 790 addDRTypeForNEON(MVT::v1i64); 791 792 addQRTypeForNEON(MVT::v4f32); 793 addQRTypeForNEON(MVT::v2f64); 794 addQRTypeForNEON(MVT::v16i8); 795 addQRTypeForNEON(MVT::v8i16); 796 addQRTypeForNEON(MVT::v4i32); 797 addQRTypeForNEON(MVT::v2i64); 798 799 if (Subtarget->hasFullFP16()) { 800 addQRTypeForNEON(MVT::v8f16); 801 addDRTypeForNEON(MVT::v4f16); 802 } 803 804 if (Subtarget->hasBF16()) { 805 addQRTypeForNEON(MVT::v8bf16); 806 addDRTypeForNEON(MVT::v4bf16); 807 } 808 } 809 810 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 811 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 812 // none of Neon, MVE or VFP supports any arithmetic operations on it. 813 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 814 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 815 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 816 // FIXME: Code duplication: FDIV and FREM are expanded always, see 817 // ARMTargetLowering::addTypeForNEON method for details. 818 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 819 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 820 // FIXME: Create unittest. 821 // In another words, find a way when "copysign" appears in DAG with vector 822 // operands. 823 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 824 // FIXME: Code duplication: SETCC has custom operation action, see 825 // ARMTargetLowering::addTypeForNEON method for details. 826 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 827 // FIXME: Create unittest for FNEG and for FABS. 828 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 829 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 830 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 831 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 832 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 833 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 834 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 835 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 836 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 837 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 838 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 839 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 840 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 841 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 842 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 843 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 844 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 845 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 846 } 847 848 if (Subtarget->hasNEON()) { 849 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 850 // supported for v4f32. 851 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 852 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 853 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 854 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 855 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 856 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 857 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 858 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 859 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 860 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 861 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 862 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 863 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 864 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 865 866 // Mark v2f32 intrinsics. 867 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 868 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 869 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 870 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 871 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 872 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 873 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 874 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 875 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 876 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 877 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 878 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 879 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 880 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 881 882 // Neon does not support some operations on v1i64 and v2i64 types. 883 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 884 // Custom handling for some quad-vector types to detect VMULL. 885 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 886 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 887 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 888 // Custom handling for some vector types to avoid expensive expansions 889 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 890 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 891 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 892 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 893 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 894 // a destination type that is wider than the source, and nor does 895 // it have a FP_TO_[SU]INT instruction with a narrower destination than 896 // source. 897 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 898 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 899 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 900 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 901 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 902 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 903 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 904 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 905 906 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 907 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 908 909 // NEON does not have single instruction CTPOP for vectors with element 910 // types wider than 8-bits. However, custom lowering can leverage the 911 // v8i8/v16i8 vcnt instruction. 912 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 913 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 914 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 915 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 916 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 917 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 918 919 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 920 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 921 922 // NEON does not have single instruction CTTZ for vectors. 923 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 924 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 925 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 926 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 927 928 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 929 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 930 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 931 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 932 933 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 934 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 935 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 936 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 937 938 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 939 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 940 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 941 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 942 943 // NEON only has FMA instructions as of VFP4. 944 if (!Subtarget->hasVFP4Base()) { 945 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 946 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 947 } 948 949 setTargetDAGCombine(ISD::SHL); 950 setTargetDAGCombine(ISD::SRL); 951 setTargetDAGCombine(ISD::SRA); 952 setTargetDAGCombine(ISD::FP_TO_SINT); 953 setTargetDAGCombine(ISD::FP_TO_UINT); 954 setTargetDAGCombine(ISD::FDIV); 955 setTargetDAGCombine(ISD::LOAD); 956 957 // It is legal to extload from v4i8 to v4i16 or v4i32. 958 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 959 MVT::v2i32}) { 960 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 961 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 962 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 963 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 964 } 965 } 966 } 967 968 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 969 setTargetDAGCombine(ISD::BUILD_VECTOR); 970 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 971 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 972 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 973 setTargetDAGCombine(ISD::STORE); 974 setTargetDAGCombine(ISD::SIGN_EXTEND); 975 setTargetDAGCombine(ISD::ZERO_EXTEND); 976 setTargetDAGCombine(ISD::ANY_EXTEND); 977 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 978 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 979 setTargetDAGCombine(ISD::INTRINSIC_VOID); 980 setTargetDAGCombine(ISD::VECREDUCE_ADD); 981 setTargetDAGCombine(ISD::ADD); 982 setTargetDAGCombine(ISD::BITCAST); 983 } 984 if (Subtarget->hasMVEIntegerOps()) { 985 setTargetDAGCombine(ISD::SMIN); 986 setTargetDAGCombine(ISD::UMIN); 987 setTargetDAGCombine(ISD::SMAX); 988 setTargetDAGCombine(ISD::UMAX); 989 setTargetDAGCombine(ISD::FP_EXTEND); 990 setTargetDAGCombine(ISD::SELECT); 991 setTargetDAGCombine(ISD::SELECT_CC); 992 } 993 994 if (!Subtarget->hasFP64()) { 995 // When targeting a floating-point unit with only single-precision 996 // operations, f64 is legal for the few double-precision instructions which 997 // are present However, no double-precision operations other than moves, 998 // loads and stores are provided by the hardware. 999 setOperationAction(ISD::FADD, MVT::f64, Expand); 1000 setOperationAction(ISD::FSUB, MVT::f64, Expand); 1001 setOperationAction(ISD::FMUL, MVT::f64, Expand); 1002 setOperationAction(ISD::FMA, MVT::f64, Expand); 1003 setOperationAction(ISD::FDIV, MVT::f64, Expand); 1004 setOperationAction(ISD::FREM, MVT::f64, Expand); 1005 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 1006 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 1007 setOperationAction(ISD::FNEG, MVT::f64, Expand); 1008 setOperationAction(ISD::FABS, MVT::f64, Expand); 1009 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 1010 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1011 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1012 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1013 setOperationAction(ISD::FLOG, MVT::f64, Expand); 1014 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 1015 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 1016 setOperationAction(ISD::FEXP, MVT::f64, Expand); 1017 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 1018 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 1019 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 1020 setOperationAction(ISD::FRINT, MVT::f64, Expand); 1021 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 1022 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 1023 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 1024 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 1025 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 1026 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 1027 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 1028 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 1029 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 1030 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 1031 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 1032 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom); 1033 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom); 1034 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 1035 } 1036 1037 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 1038 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 1039 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom); 1040 if (Subtarget->hasFullFP16()) { 1041 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 1042 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom); 1043 } 1044 } 1045 1046 if (!Subtarget->hasFP16()) { 1047 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 1048 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom); 1049 } 1050 1051 computeRegisterProperties(Subtarget->getRegisterInfo()); 1052 1053 // ARM does not have floating-point extending loads. 1054 for (MVT VT : MVT::fp_valuetypes()) { 1055 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 1056 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 1057 } 1058 1059 // ... or truncating stores 1060 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 1061 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 1062 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 1063 1064 // ARM does not have i1 sign extending load. 1065 for (MVT VT : MVT::integer_valuetypes()) 1066 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 1067 1068 // ARM supports all 4 flavors of integer indexed load / store. 1069 if (!Subtarget->isThumb1Only()) { 1070 for (unsigned im = (unsigned)ISD::PRE_INC; 1071 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1072 setIndexedLoadAction(im, MVT::i1, Legal); 1073 setIndexedLoadAction(im, MVT::i8, Legal); 1074 setIndexedLoadAction(im, MVT::i16, Legal); 1075 setIndexedLoadAction(im, MVT::i32, Legal); 1076 setIndexedStoreAction(im, MVT::i1, Legal); 1077 setIndexedStoreAction(im, MVT::i8, Legal); 1078 setIndexedStoreAction(im, MVT::i16, Legal); 1079 setIndexedStoreAction(im, MVT::i32, Legal); 1080 } 1081 } else { 1082 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 1083 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 1084 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 1085 } 1086 1087 setOperationAction(ISD::SADDO, MVT::i32, Custom); 1088 setOperationAction(ISD::UADDO, MVT::i32, Custom); 1089 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 1090 setOperationAction(ISD::USUBO, MVT::i32, Custom); 1091 1092 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 1093 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 1094 if (Subtarget->hasDSP()) { 1095 setOperationAction(ISD::SADDSAT, MVT::i8, Custom); 1096 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom); 1097 setOperationAction(ISD::SADDSAT, MVT::i16, Custom); 1098 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom); 1099 } 1100 if (Subtarget->hasBaseDSP()) { 1101 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 1102 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 1103 } 1104 1105 // i64 operation support. 1106 setOperationAction(ISD::MUL, MVT::i64, Expand); 1107 setOperationAction(ISD::MULHU, MVT::i32, Expand); 1108 if (Subtarget->isThumb1Only()) { 1109 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 1110 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 1111 } 1112 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 1113 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 1114 setOperationAction(ISD::MULHS, MVT::i32, Expand); 1115 1116 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 1117 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 1118 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 1119 setOperationAction(ISD::SRL, MVT::i64, Custom); 1120 setOperationAction(ISD::SRA, MVT::i64, Custom); 1121 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 1122 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 1123 setOperationAction(ISD::LOAD, MVT::i64, Custom); 1124 setOperationAction(ISD::STORE, MVT::i64, Custom); 1125 1126 // MVE lowers 64 bit shifts to lsll and lsrl 1127 // assuming that ISD::SRL and SRA of i64 are already marked custom 1128 if (Subtarget->hasMVEIntegerOps()) 1129 setOperationAction(ISD::SHL, MVT::i64, Custom); 1130 1131 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1132 if (Subtarget->isThumb1Only()) { 1133 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1134 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1135 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1136 } 1137 1138 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1139 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1140 1141 // ARM does not have ROTL. 1142 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1143 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1144 setOperationAction(ISD::ROTL, VT, Expand); 1145 setOperationAction(ISD::ROTR, VT, Expand); 1146 } 1147 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1148 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1149 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1150 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1151 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1152 } 1153 1154 // @llvm.readcyclecounter requires the Performance Monitors extension. 1155 // Default to the 0 expansion on unsupported platforms. 1156 // FIXME: Technically there are older ARM CPUs that have 1157 // implementation-specific ways of obtaining this information. 1158 if (Subtarget->hasPerfMon()) 1159 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1160 1161 // Only ARMv6 has BSWAP. 1162 if (!Subtarget->hasV6Ops()) 1163 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1164 1165 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1166 : Subtarget->hasDivideInARMMode(); 1167 if (!hasDivide) { 1168 // These are expanded into libcalls if the cpu doesn't have HW divider. 1169 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1170 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1171 } 1172 1173 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1174 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1175 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1176 1177 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1178 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1179 } 1180 1181 setOperationAction(ISD::SREM, MVT::i32, Expand); 1182 setOperationAction(ISD::UREM, MVT::i32, Expand); 1183 1184 // Register based DivRem for AEABI (RTABI 4.2) 1185 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1186 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1187 Subtarget->isTargetWindows()) { 1188 setOperationAction(ISD::SREM, MVT::i64, Custom); 1189 setOperationAction(ISD::UREM, MVT::i64, Custom); 1190 HasStandaloneRem = false; 1191 1192 if (Subtarget->isTargetWindows()) { 1193 const struct { 1194 const RTLIB::Libcall Op; 1195 const char * const Name; 1196 const CallingConv::ID CC; 1197 } LibraryCalls[] = { 1198 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1199 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1200 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1201 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1202 1203 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1204 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1205 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1206 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1207 }; 1208 1209 for (const auto &LC : LibraryCalls) { 1210 setLibcallName(LC.Op, LC.Name); 1211 setLibcallCallingConv(LC.Op, LC.CC); 1212 } 1213 } else { 1214 const struct { 1215 const RTLIB::Libcall Op; 1216 const char * const Name; 1217 const CallingConv::ID CC; 1218 } LibraryCalls[] = { 1219 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1220 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1221 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1222 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1223 1224 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1225 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1226 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1227 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1228 }; 1229 1230 for (const auto &LC : LibraryCalls) { 1231 setLibcallName(LC.Op, LC.Name); 1232 setLibcallCallingConv(LC.Op, LC.CC); 1233 } 1234 } 1235 1236 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1237 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1238 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1239 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1240 } else { 1241 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1242 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1243 } 1244 1245 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 1246 // MSVCRT doesn't have powi; fall back to pow 1247 setLibcallName(RTLIB::POWI_F32, nullptr); 1248 setLibcallName(RTLIB::POWI_F64, nullptr); 1249 } 1250 1251 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1252 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1253 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1254 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1255 1256 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1257 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1258 1259 // Use the default implementation. 1260 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1261 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1262 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1263 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1264 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1265 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1266 1267 if (Subtarget->isTargetWindows()) 1268 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1269 else 1270 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1271 1272 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1273 // the default expansion. 1274 InsertFencesForAtomic = false; 1275 if (Subtarget->hasAnyDataBarrier() && 1276 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1277 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1278 // to ldrex/strex loops already. 1279 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1280 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1281 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1282 1283 // On v8, we have particularly efficient implementations of atomic fences 1284 // if they can be combined with nearby atomic loads and stores. 1285 if (!Subtarget->hasAcquireRelease() || 1286 getTargetMachine().getOptLevel() == 0) { 1287 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1288 InsertFencesForAtomic = true; 1289 } 1290 } else { 1291 // If there's anything we can use as a barrier, go through custom lowering 1292 // for ATOMIC_FENCE. 1293 // If target has DMB in thumb, Fences can be inserted. 1294 if (Subtarget->hasDataBarrier()) 1295 InsertFencesForAtomic = true; 1296 1297 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1298 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1299 1300 // Set them all for expansion, which will force libcalls. 1301 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1302 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1303 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1304 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1305 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1306 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1307 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1308 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1309 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1310 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1311 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1312 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1313 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1314 // Unordered/Monotonic case. 1315 if (!InsertFencesForAtomic) { 1316 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1317 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1318 } 1319 } 1320 1321 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1322 1323 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1324 if (!Subtarget->hasV6Ops()) { 1325 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1326 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1327 } 1328 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1329 1330 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1331 !Subtarget->isThumb1Only()) { 1332 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1333 // iff target supports vfp2. 1334 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1335 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1336 } 1337 1338 // We want to custom lower some of our intrinsics. 1339 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1340 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1341 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1342 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1343 if (Subtarget->useSjLjEH()) 1344 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1345 1346 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1347 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1348 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1349 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1350 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1351 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1352 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1353 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1354 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1355 if (Subtarget->hasFullFP16()) { 1356 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1357 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1358 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1359 } 1360 1361 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1362 1363 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1364 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1365 if (Subtarget->hasFullFP16()) 1366 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1367 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1368 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1369 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1370 1371 // We don't support sin/cos/fmod/copysign/pow 1372 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1373 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1374 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1375 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1376 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1377 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1378 setOperationAction(ISD::FREM, MVT::f64, Expand); 1379 setOperationAction(ISD::FREM, MVT::f32, Expand); 1380 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1381 !Subtarget->isThumb1Only()) { 1382 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1383 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1384 } 1385 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1386 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1387 1388 if (!Subtarget->hasVFP4Base()) { 1389 setOperationAction(ISD::FMA, MVT::f64, Expand); 1390 setOperationAction(ISD::FMA, MVT::f32, Expand); 1391 } 1392 1393 // Various VFP goodness 1394 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1395 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1396 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1397 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1398 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1399 } 1400 1401 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1402 if (!Subtarget->hasFP16()) { 1403 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1404 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1405 } 1406 1407 // Strict floating-point comparisons need custom lowering. 1408 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 1409 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 1410 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 1411 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 1412 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 1413 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 1414 } 1415 1416 // Use __sincos_stret if available. 1417 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1418 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1419 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1420 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1421 } 1422 1423 // FP-ARMv8 implements a lot of rounding-like FP operations. 1424 if (Subtarget->hasFPARMv8Base()) { 1425 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1426 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1427 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1428 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1429 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1430 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1431 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1432 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1433 if (Subtarget->hasNEON()) { 1434 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1435 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1436 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1437 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1438 } 1439 1440 if (Subtarget->hasFP64()) { 1441 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1442 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1443 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1444 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1445 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1446 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1447 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1448 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1449 } 1450 } 1451 1452 // FP16 often need to be promoted to call lib functions 1453 if (Subtarget->hasFullFP16()) { 1454 setOperationAction(ISD::FREM, MVT::f16, Promote); 1455 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1456 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1457 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1458 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1459 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1460 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1461 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1462 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1463 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1464 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1465 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1466 1467 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1468 } 1469 1470 if (Subtarget->hasNEON()) { 1471 // vmin and vmax aren't available in a scalar form, so we can use 1472 // a NEON instruction with an undef lane instead. This has a performance 1473 // penalty on some cores, so we don't do this unless we have been 1474 // asked to by the core tuning model. 1475 if (Subtarget->useNEONForSinglePrecisionFP()) { 1476 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1477 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1478 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1479 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1480 } 1481 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1482 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1483 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1484 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1485 1486 if (Subtarget->hasFullFP16()) { 1487 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1488 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1489 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1490 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1491 1492 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1493 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1494 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1495 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1496 } 1497 } 1498 1499 // We have target-specific dag combine patterns for the following nodes: 1500 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1501 setTargetDAGCombine(ISD::ADD); 1502 setTargetDAGCombine(ISD::SUB); 1503 setTargetDAGCombine(ISD::MUL); 1504 setTargetDAGCombine(ISD::AND); 1505 setTargetDAGCombine(ISD::OR); 1506 setTargetDAGCombine(ISD::XOR); 1507 1508 if (Subtarget->hasMVEIntegerOps()) 1509 setTargetDAGCombine(ISD::VSELECT); 1510 1511 if (Subtarget->hasV6Ops()) 1512 setTargetDAGCombine(ISD::SRL); 1513 if (Subtarget->isThumb1Only()) 1514 setTargetDAGCombine(ISD::SHL); 1515 1516 setStackPointerRegisterToSaveRestore(ARM::SP); 1517 1518 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1519 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1520 setSchedulingPreference(Sched::RegPressure); 1521 else 1522 setSchedulingPreference(Sched::Hybrid); 1523 1524 //// temporary - rewrite interface to use type 1525 MaxStoresPerMemset = 8; 1526 MaxStoresPerMemsetOptSize = 4; 1527 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1528 MaxStoresPerMemcpyOptSize = 2; 1529 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1530 MaxStoresPerMemmoveOptSize = 2; 1531 1532 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1533 // are at least 4 bytes aligned. 1534 setMinStackArgumentAlignment(Align(4)); 1535 1536 // Prefer likely predicted branches to selects on out-of-order cores. 1537 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1538 1539 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment())); 1540 1541 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4)); 1542 1543 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1544 setTargetDAGCombine(ISD::ABS); 1545 } 1546 1547 bool ARMTargetLowering::useSoftFloat() const { 1548 return Subtarget->useSoftFloat(); 1549 } 1550 1551 // FIXME: It might make sense to define the representative register class as the 1552 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1553 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1554 // SPR's representative would be DPR_VFP2. This should work well if register 1555 // pressure tracking were modified such that a register use would increment the 1556 // pressure of the register class's representative and all of it's super 1557 // classes' representatives transitively. We have not implemented this because 1558 // of the difficulty prior to coalescing of modeling operand register classes 1559 // due to the common occurrence of cross class copies and subregister insertions 1560 // and extractions. 1561 std::pair<const TargetRegisterClass *, uint8_t> 1562 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1563 MVT VT) const { 1564 const TargetRegisterClass *RRC = nullptr; 1565 uint8_t Cost = 1; 1566 switch (VT.SimpleTy) { 1567 default: 1568 return TargetLowering::findRepresentativeClass(TRI, VT); 1569 // Use DPR as representative register class for all floating point 1570 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1571 // the cost is 1 for both f32 and f64. 1572 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1573 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1574 RRC = &ARM::DPRRegClass; 1575 // When NEON is used for SP, only half of the register file is available 1576 // because operations that define both SP and DP results will be constrained 1577 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1578 // coalescing by double-counting the SP regs. See the FIXME above. 1579 if (Subtarget->useNEONForSinglePrecisionFP()) 1580 Cost = 2; 1581 break; 1582 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1583 case MVT::v4f32: case MVT::v2f64: 1584 RRC = &ARM::DPRRegClass; 1585 Cost = 2; 1586 break; 1587 case MVT::v4i64: 1588 RRC = &ARM::DPRRegClass; 1589 Cost = 4; 1590 break; 1591 case MVT::v8i64: 1592 RRC = &ARM::DPRRegClass; 1593 Cost = 8; 1594 break; 1595 } 1596 return std::make_pair(RRC, Cost); 1597 } 1598 1599 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1600 switch ((ARMISD::NodeType)Opcode) { 1601 case ARMISD::FIRST_NUMBER: break; 1602 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1603 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1604 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1605 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1606 case ARMISD::CALL: return "ARMISD::CALL"; 1607 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1608 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1609 case ARMISD::tSECALL: return "ARMISD::tSECALL"; 1610 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1611 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1612 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1613 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1614 case ARMISD::SERET_FLAG: return "ARMISD::SERET_FLAG"; 1615 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1616 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1617 case ARMISD::CMP: return "ARMISD::CMP"; 1618 case ARMISD::CMN: return "ARMISD::CMN"; 1619 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1620 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1621 case ARMISD::CMPFPE: return "ARMISD::CMPFPE"; 1622 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1623 case ARMISD::CMPFPEw0: return "ARMISD::CMPFPEw0"; 1624 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1625 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1626 1627 case ARMISD::CMOV: return "ARMISD::CMOV"; 1628 case ARMISD::SUBS: return "ARMISD::SUBS"; 1629 1630 case ARMISD::SSAT: return "ARMISD::SSAT"; 1631 case ARMISD::USAT: return "ARMISD::USAT"; 1632 1633 case ARMISD::ASRL: return "ARMISD::ASRL"; 1634 case ARMISD::LSRL: return "ARMISD::LSRL"; 1635 case ARMISD::LSLL: return "ARMISD::LSLL"; 1636 1637 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1638 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1639 case ARMISD::RRX: return "ARMISD::RRX"; 1640 1641 case ARMISD::ADDC: return "ARMISD::ADDC"; 1642 case ARMISD::ADDE: return "ARMISD::ADDE"; 1643 case ARMISD::SUBC: return "ARMISD::SUBC"; 1644 case ARMISD::SUBE: return "ARMISD::SUBE"; 1645 case ARMISD::LSLS: return "ARMISD::LSLS"; 1646 1647 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1648 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1649 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1650 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1651 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1652 1653 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1654 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1655 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1656 1657 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1658 1659 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1660 1661 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1662 1663 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1664 1665 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1666 1667 case ARMISD::LDRD: return "ARMISD::LDRD"; 1668 case ARMISD::STRD: return "ARMISD::STRD"; 1669 1670 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1671 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1672 1673 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST"; 1674 case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST"; 1675 case ARMISD::VCMP: return "ARMISD::VCMP"; 1676 case ARMISD::VCMPZ: return "ARMISD::VCMPZ"; 1677 case ARMISD::VTST: return "ARMISD::VTST"; 1678 1679 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1680 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1681 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1682 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1683 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1684 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1685 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1686 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1687 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1688 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1689 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1690 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1691 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1692 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1693 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1694 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1695 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1696 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1697 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1698 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1699 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1700 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1701 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1702 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1703 case ARMISD::VDUP: return "ARMISD::VDUP"; 1704 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1705 case ARMISD::VEXT: return "ARMISD::VEXT"; 1706 case ARMISD::VREV64: return "ARMISD::VREV64"; 1707 case ARMISD::VREV32: return "ARMISD::VREV32"; 1708 case ARMISD::VREV16: return "ARMISD::VREV16"; 1709 case ARMISD::VZIP: return "ARMISD::VZIP"; 1710 case ARMISD::VUZP: return "ARMISD::VUZP"; 1711 case ARMISD::VTRN: return "ARMISD::VTRN"; 1712 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1713 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1714 case ARMISD::VMOVN: return "ARMISD::VMOVN"; 1715 case ARMISD::VQMOVNs: return "ARMISD::VQMOVNs"; 1716 case ARMISD::VQMOVNu: return "ARMISD::VQMOVNu"; 1717 case ARMISD::VCVTN: return "ARMISD::VCVTN"; 1718 case ARMISD::VCVTL: return "ARMISD::VCVTL"; 1719 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1720 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1721 case ARMISD::VADDVs: return "ARMISD::VADDVs"; 1722 case ARMISD::VADDVu: return "ARMISD::VADDVu"; 1723 case ARMISD::VADDVps: return "ARMISD::VADDVps"; 1724 case ARMISD::VADDVpu: return "ARMISD::VADDVpu"; 1725 case ARMISD::VADDLVs: return "ARMISD::VADDLVs"; 1726 case ARMISD::VADDLVu: return "ARMISD::VADDLVu"; 1727 case ARMISD::VADDLVAs: return "ARMISD::VADDLVAs"; 1728 case ARMISD::VADDLVAu: return "ARMISD::VADDLVAu"; 1729 case ARMISD::VADDLVps: return "ARMISD::VADDLVps"; 1730 case ARMISD::VADDLVpu: return "ARMISD::VADDLVpu"; 1731 case ARMISD::VADDLVAps: return "ARMISD::VADDLVAps"; 1732 case ARMISD::VADDLVApu: return "ARMISD::VADDLVApu"; 1733 case ARMISD::VMLAVs: return "ARMISD::VMLAVs"; 1734 case ARMISD::VMLAVu: return "ARMISD::VMLAVu"; 1735 case ARMISD::VMLAVps: return "ARMISD::VMLAVps"; 1736 case ARMISD::VMLAVpu: return "ARMISD::VMLAVpu"; 1737 case ARMISD::VMLALVs: return "ARMISD::VMLALVs"; 1738 case ARMISD::VMLALVu: return "ARMISD::VMLALVu"; 1739 case ARMISD::VMLALVps: return "ARMISD::VMLALVps"; 1740 case ARMISD::VMLALVpu: return "ARMISD::VMLALVpu"; 1741 case ARMISD::VMLALVAs: return "ARMISD::VMLALVAs"; 1742 case ARMISD::VMLALVAu: return "ARMISD::VMLALVAu"; 1743 case ARMISD::VMLALVAps: return "ARMISD::VMLALVAps"; 1744 case ARMISD::VMLALVApu: return "ARMISD::VMLALVApu"; 1745 case ARMISD::VMINVu: return "ARMISD::VMINVu"; 1746 case ARMISD::VMINVs: return "ARMISD::VMINVs"; 1747 case ARMISD::VMAXVu: return "ARMISD::VMAXVu"; 1748 case ARMISD::VMAXVs: return "ARMISD::VMAXVs"; 1749 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1750 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1751 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1752 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1753 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1754 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1755 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1756 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1757 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1758 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1759 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1760 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1761 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1762 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1763 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1764 case ARMISD::QADD16b: return "ARMISD::QADD16b"; 1765 case ARMISD::QSUB16b: return "ARMISD::QSUB16b"; 1766 case ARMISD::QADD8b: return "ARMISD::QADD8b"; 1767 case ARMISD::QSUB8b: return "ARMISD::QSUB8b"; 1768 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1769 case ARMISD::BFI: return "ARMISD::BFI"; 1770 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1771 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1772 case ARMISD::VBSP: return "ARMISD::VBSP"; 1773 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1774 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1775 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1776 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1777 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1778 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1779 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1780 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1781 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1782 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1783 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1784 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1785 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1786 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1787 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1788 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1789 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1790 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1791 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1792 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1793 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1794 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1795 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1796 case ARMISD::WLS: return "ARMISD::WLS"; 1797 case ARMISD::LE: return "ARMISD::LE"; 1798 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1799 case ARMISD::CSINV: return "ARMISD::CSINV"; 1800 case ARMISD::CSNEG: return "ARMISD::CSNEG"; 1801 case ARMISD::CSINC: return "ARMISD::CSINC"; 1802 } 1803 return nullptr; 1804 } 1805 1806 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1807 EVT VT) const { 1808 if (!VT.isVector()) 1809 return getPointerTy(DL); 1810 1811 // MVE has a predicate register. 1812 if (Subtarget->hasMVEIntegerOps() && 1813 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1814 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1815 return VT.changeVectorElementTypeToInteger(); 1816 } 1817 1818 /// getRegClassFor - Return the register class that should be used for the 1819 /// specified value type. 1820 const TargetRegisterClass * 1821 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1822 (void)isDivergent; 1823 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1824 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1825 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1826 // MVE Q registers. 1827 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1828 if (VT == MVT::v4i64) 1829 return &ARM::QQPRRegClass; 1830 if (VT == MVT::v8i64) 1831 return &ARM::QQQQPRRegClass; 1832 } 1833 return TargetLowering::getRegClassFor(VT); 1834 } 1835 1836 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1837 // source/dest is aligned and the copy size is large enough. We therefore want 1838 // to align such objects passed to memory intrinsics. 1839 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1840 unsigned &PrefAlign) const { 1841 if (!isa<MemIntrinsic>(CI)) 1842 return false; 1843 MinSize = 8; 1844 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1845 // cycle faster than 4-byte aligned LDM. 1846 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1847 return true; 1848 } 1849 1850 // Create a fast isel object. 1851 FastISel * 1852 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1853 const TargetLibraryInfo *libInfo) const { 1854 return ARM::createFastISel(funcInfo, libInfo); 1855 } 1856 1857 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1858 unsigned NumVals = N->getNumValues(); 1859 if (!NumVals) 1860 return Sched::RegPressure; 1861 1862 for (unsigned i = 0; i != NumVals; ++i) { 1863 EVT VT = N->getValueType(i); 1864 if (VT == MVT::Glue || VT == MVT::Other) 1865 continue; 1866 if (VT.isFloatingPoint() || VT.isVector()) 1867 return Sched::ILP; 1868 } 1869 1870 if (!N->isMachineOpcode()) 1871 return Sched::RegPressure; 1872 1873 // Load are scheduled for latency even if there instruction itinerary 1874 // is not available. 1875 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1876 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1877 1878 if (MCID.getNumDefs() == 0) 1879 return Sched::RegPressure; 1880 if (!Itins->isEmpty() && 1881 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1882 return Sched::ILP; 1883 1884 return Sched::RegPressure; 1885 } 1886 1887 //===----------------------------------------------------------------------===// 1888 // Lowering Code 1889 //===----------------------------------------------------------------------===// 1890 1891 static bool isSRL16(const SDValue &Op) { 1892 if (Op.getOpcode() != ISD::SRL) 1893 return false; 1894 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1895 return Const->getZExtValue() == 16; 1896 return false; 1897 } 1898 1899 static bool isSRA16(const SDValue &Op) { 1900 if (Op.getOpcode() != ISD::SRA) 1901 return false; 1902 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1903 return Const->getZExtValue() == 16; 1904 return false; 1905 } 1906 1907 static bool isSHL16(const SDValue &Op) { 1908 if (Op.getOpcode() != ISD::SHL) 1909 return false; 1910 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1911 return Const->getZExtValue() == 16; 1912 return false; 1913 } 1914 1915 // Check for a signed 16-bit value. We special case SRA because it makes it 1916 // more simple when also looking for SRAs that aren't sign extending a 1917 // smaller value. Without the check, we'd need to take extra care with 1918 // checking order for some operations. 1919 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1920 if (isSRA16(Op)) 1921 return isSHL16(Op.getOperand(0)); 1922 return DAG.ComputeNumSignBits(Op) == 17; 1923 } 1924 1925 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1926 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1927 switch (CC) { 1928 default: llvm_unreachable("Unknown condition code!"); 1929 case ISD::SETNE: return ARMCC::NE; 1930 case ISD::SETEQ: return ARMCC::EQ; 1931 case ISD::SETGT: return ARMCC::GT; 1932 case ISD::SETGE: return ARMCC::GE; 1933 case ISD::SETLT: return ARMCC::LT; 1934 case ISD::SETLE: return ARMCC::LE; 1935 case ISD::SETUGT: return ARMCC::HI; 1936 case ISD::SETUGE: return ARMCC::HS; 1937 case ISD::SETULT: return ARMCC::LO; 1938 case ISD::SETULE: return ARMCC::LS; 1939 } 1940 } 1941 1942 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1943 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1944 ARMCC::CondCodes &CondCode2) { 1945 CondCode2 = ARMCC::AL; 1946 switch (CC) { 1947 default: llvm_unreachable("Unknown FP condition!"); 1948 case ISD::SETEQ: 1949 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1950 case ISD::SETGT: 1951 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1952 case ISD::SETGE: 1953 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1954 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1955 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1956 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1957 case ISD::SETO: CondCode = ARMCC::VC; break; 1958 case ISD::SETUO: CondCode = ARMCC::VS; break; 1959 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1960 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1961 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1962 case ISD::SETLT: 1963 case ISD::SETULT: CondCode = ARMCC::LT; break; 1964 case ISD::SETLE: 1965 case ISD::SETULE: CondCode = ARMCC::LE; break; 1966 case ISD::SETNE: 1967 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1968 } 1969 } 1970 1971 //===----------------------------------------------------------------------===// 1972 // Calling Convention Implementation 1973 //===----------------------------------------------------------------------===// 1974 1975 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1976 /// account presence of floating point hardware and calling convention 1977 /// limitations, such as support for variadic functions. 1978 CallingConv::ID 1979 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1980 bool isVarArg) const { 1981 switch (CC) { 1982 default: 1983 report_fatal_error("Unsupported calling convention"); 1984 case CallingConv::ARM_AAPCS: 1985 case CallingConv::ARM_APCS: 1986 case CallingConv::GHC: 1987 case CallingConv::CFGuard_Check: 1988 return CC; 1989 case CallingConv::PreserveMost: 1990 return CallingConv::PreserveMost; 1991 case CallingConv::ARM_AAPCS_VFP: 1992 case CallingConv::Swift: 1993 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1994 case CallingConv::C: 1995 if (!Subtarget->isAAPCS_ABI()) 1996 return CallingConv::ARM_APCS; 1997 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1998 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1999 !isVarArg) 2000 return CallingConv::ARM_AAPCS_VFP; 2001 else 2002 return CallingConv::ARM_AAPCS; 2003 case CallingConv::Fast: 2004 case CallingConv::CXX_FAST_TLS: 2005 if (!Subtarget->isAAPCS_ABI()) { 2006 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 2007 return CallingConv::Fast; 2008 return CallingConv::ARM_APCS; 2009 } else if (Subtarget->hasVFP2Base() && 2010 !Subtarget->isThumb1Only() && !isVarArg) 2011 return CallingConv::ARM_AAPCS_VFP; 2012 else 2013 return CallingConv::ARM_AAPCS; 2014 } 2015 } 2016 2017 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2018 bool isVarArg) const { 2019 return CCAssignFnForNode(CC, false, isVarArg); 2020 } 2021 2022 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 2023 bool isVarArg) const { 2024 return CCAssignFnForNode(CC, true, isVarArg); 2025 } 2026 2027 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 2028 /// CallingConvention. 2029 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 2030 bool Return, 2031 bool isVarArg) const { 2032 switch (getEffectiveCallingConv(CC, isVarArg)) { 2033 default: 2034 report_fatal_error("Unsupported calling convention"); 2035 case CallingConv::ARM_APCS: 2036 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 2037 case CallingConv::ARM_AAPCS: 2038 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2039 case CallingConv::ARM_AAPCS_VFP: 2040 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 2041 case CallingConv::Fast: 2042 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 2043 case CallingConv::GHC: 2044 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 2045 case CallingConv::PreserveMost: 2046 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 2047 case CallingConv::CFGuard_Check: 2048 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check); 2049 } 2050 } 2051 2052 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG, 2053 MVT LocVT, MVT ValVT, SDValue Val) const { 2054 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()), 2055 Val); 2056 if (Subtarget->hasFullFP16()) { 2057 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val); 2058 } else { 2059 Val = DAG.getNode(ISD::TRUNCATE, dl, 2060 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2061 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val); 2062 } 2063 return Val; 2064 } 2065 2066 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG, 2067 MVT LocVT, MVT ValVT, 2068 SDValue Val) const { 2069 if (Subtarget->hasFullFP16()) { 2070 Val = DAG.getNode(ARMISD::VMOVrh, dl, 2071 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2072 } else { 2073 Val = DAG.getNode(ISD::BITCAST, dl, 2074 MVT::getIntegerVT(ValVT.getSizeInBits()), Val); 2075 Val = DAG.getNode(ISD::ZERO_EXTEND, dl, 2076 MVT::getIntegerVT(LocVT.getSizeInBits()), Val); 2077 } 2078 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val); 2079 } 2080 2081 /// LowerCallResult - Lower the result values of a call into the 2082 /// appropriate copies out of appropriate physical registers. 2083 SDValue ARMTargetLowering::LowerCallResult( 2084 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2085 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 2086 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2087 SDValue ThisVal) const { 2088 // Assign locations to each value returned by this call. 2089 SmallVector<CCValAssign, 16> RVLocs; 2090 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2091 *DAG.getContext()); 2092 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 2093 2094 // Copy all of the result registers out of their specified physreg. 2095 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2096 CCValAssign VA = RVLocs[i]; 2097 2098 // Pass 'this' value directly from the argument to return value, to avoid 2099 // reg unit interference 2100 if (i == 0 && isThisReturn) { 2101 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 2102 "unexpected return calling convention register assignment"); 2103 InVals.push_back(ThisVal); 2104 continue; 2105 } 2106 2107 SDValue Val; 2108 if (VA.needsCustom() && 2109 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) { 2110 // Handle f64 or half of a v2f64. 2111 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2112 InFlag); 2113 Chain = Lo.getValue(1); 2114 InFlag = Lo.getValue(2); 2115 VA = RVLocs[++i]; // skip ahead to next loc 2116 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 2117 InFlag); 2118 Chain = Hi.getValue(1); 2119 InFlag = Hi.getValue(2); 2120 if (!Subtarget->isLittle()) 2121 std::swap (Lo, Hi); 2122 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2123 2124 if (VA.getLocVT() == MVT::v2f64) { 2125 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 2126 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2127 DAG.getConstant(0, dl, MVT::i32)); 2128 2129 VA = RVLocs[++i]; // skip ahead to next loc 2130 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2131 Chain = Lo.getValue(1); 2132 InFlag = Lo.getValue(2); 2133 VA = RVLocs[++i]; // skip ahead to next loc 2134 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 2135 Chain = Hi.getValue(1); 2136 InFlag = Hi.getValue(2); 2137 if (!Subtarget->isLittle()) 2138 std::swap (Lo, Hi); 2139 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 2140 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 2141 DAG.getConstant(1, dl, MVT::i32)); 2142 } 2143 } else { 2144 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 2145 InFlag); 2146 Chain = Val.getValue(1); 2147 InFlag = Val.getValue(2); 2148 } 2149 2150 switch (VA.getLocInfo()) { 2151 default: llvm_unreachable("Unknown loc info!"); 2152 case CCValAssign::Full: break; 2153 case CCValAssign::BCvt: 2154 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 2155 break; 2156 } 2157 2158 // f16 arguments have their size extended to 4 bytes and passed as if they 2159 // had been copied to the LSBs of a 32-bit register. 2160 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2161 if (VA.needsCustom() && 2162 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 2163 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val); 2164 2165 InVals.push_back(Val); 2166 } 2167 2168 return Chain; 2169 } 2170 2171 /// LowerMemOpCallTo - Store the argument to the stack. 2172 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 2173 SDValue Arg, const SDLoc &dl, 2174 SelectionDAG &DAG, 2175 const CCValAssign &VA, 2176 ISD::ArgFlagsTy Flags) const { 2177 unsigned LocMemOffset = VA.getLocMemOffset(); 2178 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2179 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 2180 StackPtr, PtrOff); 2181 return DAG.getStore( 2182 Chain, dl, Arg, PtrOff, 2183 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 2184 } 2185 2186 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 2187 SDValue Chain, SDValue &Arg, 2188 RegsToPassVector &RegsToPass, 2189 CCValAssign &VA, CCValAssign &NextVA, 2190 SDValue &StackPtr, 2191 SmallVectorImpl<SDValue> &MemOpChains, 2192 ISD::ArgFlagsTy Flags) const { 2193 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2194 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2195 unsigned id = Subtarget->isLittle() ? 0 : 1; 2196 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2197 2198 if (NextVA.isRegLoc()) 2199 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2200 else { 2201 assert(NextVA.isMemLoc()); 2202 if (!StackPtr.getNode()) 2203 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2204 getPointerTy(DAG.getDataLayout())); 2205 2206 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2207 dl, DAG, NextVA, 2208 Flags)); 2209 } 2210 } 2211 2212 /// LowerCall - Lowering a call into a callseq_start <- 2213 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2214 /// nodes. 2215 SDValue 2216 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2217 SmallVectorImpl<SDValue> &InVals) const { 2218 SelectionDAG &DAG = CLI.DAG; 2219 SDLoc &dl = CLI.DL; 2220 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2221 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2222 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2223 SDValue Chain = CLI.Chain; 2224 SDValue Callee = CLI.Callee; 2225 bool &isTailCall = CLI.IsTailCall; 2226 CallingConv::ID CallConv = CLI.CallConv; 2227 bool doesNotRet = CLI.DoesNotReturn; 2228 bool isVarArg = CLI.IsVarArg; 2229 2230 MachineFunction &MF = DAG.getMachineFunction(); 2231 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2232 MachineFunction::CallSiteInfo CSInfo; 2233 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2234 bool isThisReturn = false; 2235 bool isCmseNSCall = false; 2236 bool PreferIndirect = false; 2237 2238 // Determine whether this is a non-secure function call. 2239 if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call")) 2240 isCmseNSCall = true; 2241 2242 // Disable tail calls if they're not supported. 2243 if (!Subtarget->supportsTailCall()) 2244 isTailCall = false; 2245 2246 // For both the non-secure calls and the returns from a CMSE entry function, 2247 // the function needs to do some extra work afte r the call, or before the 2248 // return, respectively, thus it cannot end with atail call 2249 if (isCmseNSCall || AFI->isCmseNSEntryFunction()) 2250 isTailCall = false; 2251 2252 if (isa<GlobalAddressSDNode>(Callee)) { 2253 // If we're optimizing for minimum size and the function is called three or 2254 // more times in this block, we can improve codesize by calling indirectly 2255 // as BLXr has a 16-bit encoding. 2256 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2257 if (CLI.CB) { 2258 auto *BB = CLI.CB->getParent(); 2259 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2260 count_if(GV->users(), [&BB](const User *U) { 2261 return isa<Instruction>(U) && 2262 cast<Instruction>(U)->getParent() == BB; 2263 }) > 2; 2264 } 2265 } 2266 if (isTailCall) { 2267 // Check if it's really possible to do a tail call. 2268 isTailCall = IsEligibleForTailCallOptimization( 2269 Callee, CallConv, isVarArg, isStructRet, 2270 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2271 PreferIndirect); 2272 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall()) 2273 report_fatal_error("failed to perform tail call elimination on a call " 2274 "site marked musttail"); 2275 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2276 // detected sibcalls. 2277 if (isTailCall) 2278 ++NumTailCalls; 2279 } 2280 2281 // Analyze operands of the call, assigning locations to each operand. 2282 SmallVector<CCValAssign, 16> ArgLocs; 2283 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2284 *DAG.getContext()); 2285 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2286 2287 // Get a count of how many bytes are to be pushed on the stack. 2288 unsigned NumBytes = CCInfo.getNextStackOffset(); 2289 2290 if (isTailCall) { 2291 // For tail calls, memory operands are available in our caller's stack. 2292 NumBytes = 0; 2293 } else { 2294 // Adjust the stack pointer for the new arguments... 2295 // These operations are automatically eliminated by the prolog/epilog pass 2296 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2297 } 2298 2299 SDValue StackPtr = 2300 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2301 2302 RegsToPassVector RegsToPass; 2303 SmallVector<SDValue, 8> MemOpChains; 2304 2305 // Walk the register/memloc assignments, inserting copies/loads. In the case 2306 // of tail call optimization, arguments are handled later. 2307 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2308 i != e; 2309 ++i, ++realArgIdx) { 2310 CCValAssign &VA = ArgLocs[i]; 2311 SDValue Arg = OutVals[realArgIdx]; 2312 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2313 bool isByVal = Flags.isByVal(); 2314 2315 // Promote the value if needed. 2316 switch (VA.getLocInfo()) { 2317 default: llvm_unreachable("Unknown loc info!"); 2318 case CCValAssign::Full: break; 2319 case CCValAssign::SExt: 2320 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2321 break; 2322 case CCValAssign::ZExt: 2323 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2324 break; 2325 case CCValAssign::AExt: 2326 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2327 break; 2328 case CCValAssign::BCvt: 2329 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2330 break; 2331 } 2332 2333 // f16 arguments have their size extended to 4 bytes and passed as if they 2334 // had been copied to the LSBs of a 32-bit register. 2335 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 2336 if (VA.needsCustom() && 2337 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) { 2338 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 2339 } else { 2340 // f16 arguments could have been extended prior to argument lowering. 2341 // Mask them arguments if this is a CMSE nonsecure call. 2342 auto ArgVT = Outs[realArgIdx].ArgVT; 2343 if (isCmseNSCall && (ArgVT == MVT::f16)) { 2344 auto LocBits = VA.getLocVT().getSizeInBits(); 2345 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits()); 2346 SDValue Mask = 2347 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 2348 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 2349 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 2350 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2351 } 2352 } 2353 2354 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2355 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 2356 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2357 DAG.getConstant(0, dl, MVT::i32)); 2358 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2359 DAG.getConstant(1, dl, MVT::i32)); 2360 2361 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i], 2362 StackPtr, MemOpChains, Flags); 2363 2364 VA = ArgLocs[++i]; // skip ahead to next loc 2365 if (VA.isRegLoc()) { 2366 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i], 2367 StackPtr, MemOpChains, Flags); 2368 } else { 2369 assert(VA.isMemLoc()); 2370 2371 MemOpChains.push_back( 2372 LowerMemOpCallTo(Chain, StackPtr, Op1, dl, DAG, VA, Flags)); 2373 } 2374 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 2375 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2376 StackPtr, MemOpChains, Flags); 2377 } else if (VA.isRegLoc()) { 2378 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2379 Outs[0].VT == MVT::i32) { 2380 assert(VA.getLocVT() == MVT::i32 && 2381 "unexpected calling convention register assignment"); 2382 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2383 "unexpected use of 'returned'"); 2384 isThisReturn = true; 2385 } 2386 const TargetOptions &Options = DAG.getTarget().Options; 2387 if (Options.EmitCallSiteInfo) 2388 CSInfo.emplace_back(VA.getLocReg(), i); 2389 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2390 } else if (isByVal) { 2391 assert(VA.isMemLoc()); 2392 unsigned offset = 0; 2393 2394 // True if this byval aggregate will be split between registers 2395 // and memory. 2396 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2397 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2398 2399 if (CurByValIdx < ByValArgsCount) { 2400 2401 unsigned RegBegin, RegEnd; 2402 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2403 2404 EVT PtrVT = 2405 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2406 unsigned int i, j; 2407 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2408 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2409 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2410 SDValue Load = 2411 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(), 2412 DAG.InferPtrAlign(AddArg)); 2413 MemOpChains.push_back(Load.getValue(1)); 2414 RegsToPass.push_back(std::make_pair(j, Load)); 2415 } 2416 2417 // If parameter size outsides register area, "offset" value 2418 // helps us to calculate stack slot for remained part properly. 2419 offset = RegEnd - RegBegin; 2420 2421 CCInfo.nextInRegsParam(); 2422 } 2423 2424 if (Flags.getByValSize() > 4*offset) { 2425 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2426 unsigned LocMemOffset = VA.getLocMemOffset(); 2427 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2428 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2429 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2430 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2431 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2432 MVT::i32); 2433 SDValue AlignNode = 2434 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32); 2435 2436 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2437 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2438 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2439 Ops)); 2440 } 2441 } else if (!isTailCall) { 2442 assert(VA.isMemLoc()); 2443 2444 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2445 dl, DAG, VA, Flags)); 2446 } 2447 } 2448 2449 if (!MemOpChains.empty()) 2450 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2451 2452 // Build a sequence of copy-to-reg nodes chained together with token chain 2453 // and flag operands which copy the outgoing args into the appropriate regs. 2454 SDValue InFlag; 2455 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2456 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2457 RegsToPass[i].second, InFlag); 2458 InFlag = Chain.getValue(1); 2459 } 2460 2461 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2462 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2463 // node so that legalize doesn't hack it. 2464 bool isDirect = false; 2465 2466 const TargetMachine &TM = getTargetMachine(); 2467 const Module *Mod = MF.getFunction().getParent(); 2468 const GlobalValue *GV = nullptr; 2469 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2470 GV = G->getGlobal(); 2471 bool isStub = 2472 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2473 2474 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2475 bool isLocalARMFunc = false; 2476 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2477 2478 if (Subtarget->genLongCalls()) { 2479 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2480 "long-calls codegen is not position independent!"); 2481 // Handle a global address or an external symbol. If it's not one of 2482 // those, the target's already in a register, so we don't need to do 2483 // anything extra. 2484 if (isa<GlobalAddressSDNode>(Callee)) { 2485 // Create a constant pool entry for the callee address 2486 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2487 ARMConstantPoolValue *CPV = 2488 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2489 2490 // Get the address of the callee into a register 2491 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2492 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2493 Callee = DAG.getLoad( 2494 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2495 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2496 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2497 const char *Sym = S->getSymbol(); 2498 2499 // Create a constant pool entry for the callee address 2500 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2501 ARMConstantPoolValue *CPV = 2502 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2503 ARMPCLabelIndex, 0); 2504 // Get the address of the callee into a register 2505 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2506 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2507 Callee = DAG.getLoad( 2508 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2509 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2510 } 2511 } else if (isa<GlobalAddressSDNode>(Callee)) { 2512 if (!PreferIndirect) { 2513 isDirect = true; 2514 bool isDef = GV->isStrongDefinitionForLinker(); 2515 2516 // ARM call to a local ARM function is predicable. 2517 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2518 // tBX takes a register source operand. 2519 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2520 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2521 Callee = DAG.getNode( 2522 ARMISD::WrapperPIC, dl, PtrVt, 2523 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2524 Callee = DAG.getLoad( 2525 PtrVt, dl, DAG.getEntryNode(), Callee, 2526 MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(), 2527 MachineMemOperand::MODereferenceable | 2528 MachineMemOperand::MOInvariant); 2529 } else if (Subtarget->isTargetCOFF()) { 2530 assert(Subtarget->isTargetWindows() && 2531 "Windows is the only supported COFF target"); 2532 unsigned TargetFlags = ARMII::MO_NO_FLAG; 2533 if (GV->hasDLLImportStorageClass()) 2534 TargetFlags = ARMII::MO_DLLIMPORT; 2535 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 2536 TargetFlags = ARMII::MO_COFFSTUB; 2537 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2538 TargetFlags); 2539 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 2540 Callee = 2541 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2542 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2543 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2544 } else { 2545 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2546 } 2547 } 2548 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2549 isDirect = true; 2550 // tBX takes a register source operand. 2551 const char *Sym = S->getSymbol(); 2552 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2553 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2554 ARMConstantPoolValue *CPV = 2555 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2556 ARMPCLabelIndex, 4); 2557 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4)); 2558 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2559 Callee = DAG.getLoad( 2560 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2561 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2562 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2563 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2564 } else { 2565 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2566 } 2567 } 2568 2569 if (isCmseNSCall) { 2570 assert(!isARMFunc && !isDirect && 2571 "Cannot handle call to ARM function or direct call"); 2572 if (NumBytes > 0) { 2573 DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(), 2574 "call to non-secure function would " 2575 "require passing arguments on stack", 2576 dl.getDebugLoc()); 2577 DAG.getContext()->diagnose(Diag); 2578 } 2579 if (isStructRet) { 2580 DiagnosticInfoUnsupported Diag( 2581 DAG.getMachineFunction().getFunction(), 2582 "call to non-secure function would return value through pointer", 2583 dl.getDebugLoc()); 2584 DAG.getContext()->diagnose(Diag); 2585 } 2586 } 2587 2588 // FIXME: handle tail calls differently. 2589 unsigned CallOpc; 2590 if (Subtarget->isThumb()) { 2591 if (isCmseNSCall) 2592 CallOpc = ARMISD::tSECALL; 2593 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2594 CallOpc = ARMISD::CALL_NOLINK; 2595 else 2596 CallOpc = ARMISD::CALL; 2597 } else { 2598 if (!isDirect && !Subtarget->hasV5TOps()) 2599 CallOpc = ARMISD::CALL_NOLINK; 2600 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2601 // Emit regular call when code size is the priority 2602 !Subtarget->hasMinSize()) 2603 // "mov lr, pc; b _foo" to avoid confusing the RSP 2604 CallOpc = ARMISD::CALL_NOLINK; 2605 else 2606 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2607 } 2608 2609 std::vector<SDValue> Ops; 2610 Ops.push_back(Chain); 2611 Ops.push_back(Callee); 2612 2613 // Add argument registers to the end of the list so that they are known live 2614 // into the call. 2615 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2616 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2617 RegsToPass[i].second.getValueType())); 2618 2619 // Add a register mask operand representing the call-preserved registers. 2620 if (!isTailCall) { 2621 const uint32_t *Mask; 2622 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2623 if (isThisReturn) { 2624 // For 'this' returns, use the R0-preserving mask if applicable 2625 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2626 if (!Mask) { 2627 // Set isThisReturn to false if the calling convention is not one that 2628 // allows 'returned' to be modeled in this way, so LowerCallResult does 2629 // not try to pass 'this' straight through 2630 isThisReturn = false; 2631 Mask = ARI->getCallPreservedMask(MF, CallConv); 2632 } 2633 } else 2634 Mask = ARI->getCallPreservedMask(MF, CallConv); 2635 2636 assert(Mask && "Missing call preserved mask for calling convention"); 2637 Ops.push_back(DAG.getRegisterMask(Mask)); 2638 } 2639 2640 if (InFlag.getNode()) 2641 Ops.push_back(InFlag); 2642 2643 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2644 if (isTailCall) { 2645 MF.getFrameInfo().setHasTailCall(); 2646 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2647 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 2648 return Ret; 2649 } 2650 2651 // Returns a chain and a flag for retval copy to use. 2652 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2653 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 2654 InFlag = Chain.getValue(1); 2655 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 2656 2657 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2658 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2659 if (!Ins.empty()) 2660 InFlag = Chain.getValue(1); 2661 2662 // Handle result values, copying them out of physregs into vregs that we 2663 // return. 2664 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2665 InVals, isThisReturn, 2666 isThisReturn ? OutVals[0] : SDValue()); 2667 } 2668 2669 /// HandleByVal - Every parameter *after* a byval parameter is passed 2670 /// on the stack. Remember the next parameter register to allocate, 2671 /// and then confiscate the rest of the parameter registers to insure 2672 /// this. 2673 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2674 Align Alignment) const { 2675 // Byval (as with any stack) slots are always at least 4 byte aligned. 2676 Alignment = std::max(Alignment, Align(4)); 2677 2678 unsigned Reg = State->AllocateReg(GPRArgRegs); 2679 if (!Reg) 2680 return; 2681 2682 unsigned AlignInRegs = Alignment.value() / 4; 2683 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2684 for (unsigned i = 0; i < Waste; ++i) 2685 Reg = State->AllocateReg(GPRArgRegs); 2686 2687 if (!Reg) 2688 return; 2689 2690 unsigned Excess = 4 * (ARM::R4 - Reg); 2691 2692 // Special case when NSAA != SP and parameter size greater than size of 2693 // all remained GPR regs. In that case we can't split parameter, we must 2694 // send it to stack. We also must set NCRN to R4, so waste all 2695 // remained registers. 2696 const unsigned NSAAOffset = State->getNextStackOffset(); 2697 if (NSAAOffset != 0 && Size > Excess) { 2698 while (State->AllocateReg(GPRArgRegs)) 2699 ; 2700 return; 2701 } 2702 2703 // First register for byval parameter is the first register that wasn't 2704 // allocated before this method call, so it would be "reg". 2705 // If parameter is small enough to be saved in range [reg, r4), then 2706 // the end (first after last) register would be reg + param-size-in-regs, 2707 // else parameter would be splitted between registers and stack, 2708 // end register would be r4 in this case. 2709 unsigned ByValRegBegin = Reg; 2710 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2711 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2712 // Note, first register is allocated in the beginning of function already, 2713 // allocate remained amount of registers we need. 2714 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2715 State->AllocateReg(GPRArgRegs); 2716 // A byval parameter that is split between registers and memory needs its 2717 // size truncated here. 2718 // In the case where the entire structure fits in registers, we set the 2719 // size in memory to zero. 2720 Size = std::max<int>(Size - Excess, 0); 2721 } 2722 2723 /// MatchingStackOffset - Return true if the given stack call argument is 2724 /// already available in the same position (relatively) of the caller's 2725 /// incoming argument stack. 2726 static 2727 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2728 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2729 const TargetInstrInfo *TII) { 2730 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2731 int FI = std::numeric_limits<int>::max(); 2732 if (Arg.getOpcode() == ISD::CopyFromReg) { 2733 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2734 if (!Register::isVirtualRegister(VR)) 2735 return false; 2736 MachineInstr *Def = MRI->getVRegDef(VR); 2737 if (!Def) 2738 return false; 2739 if (!Flags.isByVal()) { 2740 if (!TII->isLoadFromStackSlot(*Def, FI)) 2741 return false; 2742 } else { 2743 return false; 2744 } 2745 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2746 if (Flags.isByVal()) 2747 // ByVal argument is passed in as a pointer but it's now being 2748 // dereferenced. e.g. 2749 // define @foo(%struct.X* %A) { 2750 // tail call @bar(%struct.X* byval %A) 2751 // } 2752 return false; 2753 SDValue Ptr = Ld->getBasePtr(); 2754 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2755 if (!FINode) 2756 return false; 2757 FI = FINode->getIndex(); 2758 } else 2759 return false; 2760 2761 assert(FI != std::numeric_limits<int>::max()); 2762 if (!MFI.isFixedObjectIndex(FI)) 2763 return false; 2764 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2765 } 2766 2767 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2768 /// for tail call optimization. Targets which want to do tail call 2769 /// optimization should implement this function. 2770 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2771 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2772 bool isCalleeStructRet, bool isCallerStructRet, 2773 const SmallVectorImpl<ISD::OutputArg> &Outs, 2774 const SmallVectorImpl<SDValue> &OutVals, 2775 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2776 const bool isIndirect) const { 2777 MachineFunction &MF = DAG.getMachineFunction(); 2778 const Function &CallerF = MF.getFunction(); 2779 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2780 2781 assert(Subtarget->supportsTailCall()); 2782 2783 // Indirect tail calls cannot be optimized for Thumb1 if the args 2784 // to the call take up r0-r3. The reason is that there are no legal registers 2785 // left to hold the pointer to the function to be called. 2786 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2787 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2788 return false; 2789 2790 // Look for obvious safe cases to perform tail call optimization that do not 2791 // require ABI changes. This is what gcc calls sibcall. 2792 2793 // Exception-handling functions need a special set of instructions to indicate 2794 // a return to the hardware. Tail-calling another function would probably 2795 // break this. 2796 if (CallerF.hasFnAttribute("interrupt")) 2797 return false; 2798 2799 // Also avoid sibcall optimization if either caller or callee uses struct 2800 // return semantics. 2801 if (isCalleeStructRet || isCallerStructRet) 2802 return false; 2803 2804 // Externally-defined functions with weak linkage should not be 2805 // tail-called on ARM when the OS does not support dynamic 2806 // pre-emption of symbols, as the AAELF spec requires normal calls 2807 // to undefined weak functions to be replaced with a NOP or jump to the 2808 // next instruction. The behaviour of branch instructions in this 2809 // situation (as used for tail calls) is implementation-defined, so we 2810 // cannot rely on the linker replacing the tail call with a return. 2811 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2812 const GlobalValue *GV = G->getGlobal(); 2813 const Triple &TT = getTargetMachine().getTargetTriple(); 2814 if (GV->hasExternalWeakLinkage() && 2815 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2816 return false; 2817 } 2818 2819 // Check that the call results are passed in the same way. 2820 LLVMContext &C = *DAG.getContext(); 2821 if (!CCState::resultsCompatible( 2822 getEffectiveCallingConv(CalleeCC, isVarArg), 2823 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins, 2824 CCAssignFnForReturn(CalleeCC, isVarArg), 2825 CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) 2826 return false; 2827 // The callee has to preserve all registers the caller needs to preserve. 2828 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2829 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2830 if (CalleeCC != CallerCC) { 2831 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2832 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2833 return false; 2834 } 2835 2836 // If Caller's vararg or byval argument has been split between registers and 2837 // stack, do not perform tail call, since part of the argument is in caller's 2838 // local frame. 2839 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2840 if (AFI_Caller->getArgRegsSaveSize()) 2841 return false; 2842 2843 // If the callee takes no arguments then go on to check the results of the 2844 // call. 2845 if (!Outs.empty()) { 2846 // Check if stack adjustment is needed. For now, do not do this if any 2847 // argument is passed on the stack. 2848 SmallVector<CCValAssign, 16> ArgLocs; 2849 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2850 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2851 if (CCInfo.getNextStackOffset()) { 2852 // Check if the arguments are already laid out in the right way as 2853 // the caller's fixed stack objects. 2854 MachineFrameInfo &MFI = MF.getFrameInfo(); 2855 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2856 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2857 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2858 i != e; 2859 ++i, ++realArgIdx) { 2860 CCValAssign &VA = ArgLocs[i]; 2861 EVT RegVT = VA.getLocVT(); 2862 SDValue Arg = OutVals[realArgIdx]; 2863 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2864 if (VA.getLocInfo() == CCValAssign::Indirect) 2865 return false; 2866 if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) { 2867 // f64 and vector types are split into multiple registers or 2868 // register/stack-slot combinations. The types will not match 2869 // the registers; give up on memory f64 refs until we figure 2870 // out what to do about this. 2871 if (!VA.isRegLoc()) 2872 return false; 2873 if (!ArgLocs[++i].isRegLoc()) 2874 return false; 2875 if (RegVT == MVT::v2f64) { 2876 if (!ArgLocs[++i].isRegLoc()) 2877 return false; 2878 if (!ArgLocs[++i].isRegLoc()) 2879 return false; 2880 } 2881 } else if (!VA.isRegLoc()) { 2882 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2883 MFI, MRI, TII)) 2884 return false; 2885 } 2886 } 2887 } 2888 2889 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2890 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2891 return false; 2892 } 2893 2894 return true; 2895 } 2896 2897 bool 2898 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2899 MachineFunction &MF, bool isVarArg, 2900 const SmallVectorImpl<ISD::OutputArg> &Outs, 2901 LLVMContext &Context) const { 2902 SmallVector<CCValAssign, 16> RVLocs; 2903 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2904 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2905 } 2906 2907 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2908 const SDLoc &DL, SelectionDAG &DAG) { 2909 const MachineFunction &MF = DAG.getMachineFunction(); 2910 const Function &F = MF.getFunction(); 2911 2912 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2913 2914 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2915 // version of the "preferred return address". These offsets affect the return 2916 // instruction if this is a return from PL1 without hypervisor extensions. 2917 // IRQ/FIQ: +4 "subs pc, lr, #4" 2918 // SWI: 0 "subs pc, lr, #0" 2919 // ABORT: +4 "subs pc, lr, #4" 2920 // UNDEF: +4/+2 "subs pc, lr, #0" 2921 // UNDEF varies depending on where the exception came from ARM or Thumb 2922 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2923 2924 int64_t LROffset; 2925 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2926 IntKind == "ABORT") 2927 LROffset = 4; 2928 else if (IntKind == "SWI" || IntKind == "UNDEF") 2929 LROffset = 0; 2930 else 2931 report_fatal_error("Unsupported interrupt attribute. If present, value " 2932 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2933 2934 RetOps.insert(RetOps.begin() + 1, 2935 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2936 2937 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2938 } 2939 2940 SDValue 2941 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2942 bool isVarArg, 2943 const SmallVectorImpl<ISD::OutputArg> &Outs, 2944 const SmallVectorImpl<SDValue> &OutVals, 2945 const SDLoc &dl, SelectionDAG &DAG) const { 2946 // CCValAssign - represent the assignment of the return value to a location. 2947 SmallVector<CCValAssign, 16> RVLocs; 2948 2949 // CCState - Info about the registers and stack slots. 2950 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2951 *DAG.getContext()); 2952 2953 // Analyze outgoing return values. 2954 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2955 2956 SDValue Flag; 2957 SmallVector<SDValue, 4> RetOps; 2958 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2959 bool isLittleEndian = Subtarget->isLittle(); 2960 2961 MachineFunction &MF = DAG.getMachineFunction(); 2962 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2963 AFI->setReturnRegsCount(RVLocs.size()); 2964 2965 // Report error if cmse entry function returns structure through first ptr arg. 2966 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) { 2967 // Note: using an empty SDLoc(), as the first line of the function is a 2968 // better place to report than the last line. 2969 DiagnosticInfoUnsupported Diag( 2970 DAG.getMachineFunction().getFunction(), 2971 "secure entry function would return value through pointer", 2972 SDLoc().getDebugLoc()); 2973 DAG.getContext()->diagnose(Diag); 2974 } 2975 2976 // Copy the result values into the output registers. 2977 for (unsigned i = 0, realRVLocIdx = 0; 2978 i != RVLocs.size(); 2979 ++i, ++realRVLocIdx) { 2980 CCValAssign &VA = RVLocs[i]; 2981 assert(VA.isRegLoc() && "Can only return in registers!"); 2982 2983 SDValue Arg = OutVals[realRVLocIdx]; 2984 bool ReturnF16 = false; 2985 2986 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2987 // Half-precision return values can be returned like this: 2988 // 2989 // t11 f16 = fadd ... 2990 // t12: i16 = bitcast t11 2991 // t13: i32 = zero_extend t12 2992 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2993 // 2994 // to avoid code generation for bitcasts, we simply set Arg to the node 2995 // that produces the f16 value, t11 in this case. 2996 // 2997 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2998 SDValue ZE = Arg.getOperand(0); 2999 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 3000 SDValue BC = ZE.getOperand(0); 3001 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 3002 Arg = BC.getOperand(0); 3003 ReturnF16 = true; 3004 } 3005 } 3006 } 3007 } 3008 3009 switch (VA.getLocInfo()) { 3010 default: llvm_unreachable("Unknown loc info!"); 3011 case CCValAssign::Full: break; 3012 case CCValAssign::BCvt: 3013 if (!ReturnF16) 3014 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3015 break; 3016 } 3017 3018 // Mask f16 arguments if this is a CMSE nonsecure entry. 3019 auto RetVT = Outs[realRVLocIdx].ArgVT; 3020 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) { 3021 if (VA.needsCustom() && VA.getValVT() == MVT::f16) { 3022 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg); 3023 } else { 3024 auto LocBits = VA.getLocVT().getSizeInBits(); 3025 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits()); 3026 SDValue Mask = 3027 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits)); 3028 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg); 3029 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask); 3030 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 3031 } 3032 } 3033 3034 if (VA.needsCustom() && 3035 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) { 3036 if (VA.getLocVT() == MVT::v2f64) { 3037 // Extract the first half and return it in two registers. 3038 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3039 DAG.getConstant(0, dl, MVT::i32)); 3040 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 3041 DAG.getVTList(MVT::i32, MVT::i32), Half); 3042 3043 Chain = 3044 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3045 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag); 3046 Flag = Chain.getValue(1); 3047 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3048 VA = RVLocs[++i]; // skip ahead to next loc 3049 Chain = 3050 DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3051 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag); 3052 Flag = Chain.getValue(1); 3053 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3054 VA = RVLocs[++i]; // skip ahead to next loc 3055 3056 // Extract the 2nd half and fall through to handle it as an f64 value. 3057 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 3058 DAG.getConstant(1, dl, MVT::i32)); 3059 } 3060 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 3061 // available. 3062 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 3063 DAG.getVTList(MVT::i32, MVT::i32), Arg); 3064 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3065 fmrrd.getValue(isLittleEndian ? 0 : 1), Flag); 3066 Flag = Chain.getValue(1); 3067 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3068 VA = RVLocs[++i]; // skip ahead to next loc 3069 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3070 fmrrd.getValue(isLittleEndian ? 1 : 0), Flag); 3071 } else 3072 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 3073 3074 // Guarantee that all emitted copies are 3075 // stuck together, avoiding something bad. 3076 Flag = Chain.getValue(1); 3077 RetOps.push_back(DAG.getRegister( 3078 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT())); 3079 } 3080 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 3081 const MCPhysReg *I = 3082 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3083 if (I) { 3084 for (; *I; ++I) { 3085 if (ARM::GPRRegClass.contains(*I)) 3086 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 3087 else if (ARM::DPRRegClass.contains(*I)) 3088 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3089 else 3090 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3091 } 3092 } 3093 3094 // Update chain and glue. 3095 RetOps[0] = Chain; 3096 if (Flag.getNode()) 3097 RetOps.push_back(Flag); 3098 3099 // CPUs which aren't M-class use a special sequence to return from 3100 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 3101 // though we use "subs pc, lr, #N"). 3102 // 3103 // M-class CPUs actually use a normal return sequence with a special 3104 // (hardware-provided) value in LR, so the normal code path works. 3105 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 3106 !Subtarget->isMClass()) { 3107 if (Subtarget->isThumb1Only()) 3108 report_fatal_error("interrupt attribute is not supported in Thumb1"); 3109 return LowerInterruptReturn(RetOps, dl, DAG); 3110 } 3111 3112 ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG : 3113 ARMISD::RET_FLAG; 3114 return DAG.getNode(RetNode, dl, MVT::Other, RetOps); 3115 } 3116 3117 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 3118 if (N->getNumValues() != 1) 3119 return false; 3120 if (!N->hasNUsesOfValue(1, 0)) 3121 return false; 3122 3123 SDValue TCChain = Chain; 3124 SDNode *Copy = *N->use_begin(); 3125 if (Copy->getOpcode() == ISD::CopyToReg) { 3126 // If the copy has a glue operand, we conservatively assume it isn't safe to 3127 // perform a tail call. 3128 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3129 return false; 3130 TCChain = Copy->getOperand(0); 3131 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 3132 SDNode *VMov = Copy; 3133 // f64 returned in a pair of GPRs. 3134 SmallPtrSet<SDNode*, 2> Copies; 3135 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3136 UI != UE; ++UI) { 3137 if (UI->getOpcode() != ISD::CopyToReg) 3138 return false; 3139 Copies.insert(*UI); 3140 } 3141 if (Copies.size() > 2) 3142 return false; 3143 3144 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 3145 UI != UE; ++UI) { 3146 SDValue UseChain = UI->getOperand(0); 3147 if (Copies.count(UseChain.getNode())) 3148 // Second CopyToReg 3149 Copy = *UI; 3150 else { 3151 // We are at the top of this chain. 3152 // If the copy has a glue operand, we conservatively assume it 3153 // isn't safe to perform a tail call. 3154 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 3155 return false; 3156 // First CopyToReg 3157 TCChain = UseChain; 3158 } 3159 } 3160 } else if (Copy->getOpcode() == ISD::BITCAST) { 3161 // f32 returned in a single GPR. 3162 if (!Copy->hasOneUse()) 3163 return false; 3164 Copy = *Copy->use_begin(); 3165 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 3166 return false; 3167 // If the copy has a glue operand, we conservatively assume it isn't safe to 3168 // perform a tail call. 3169 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 3170 return false; 3171 TCChain = Copy->getOperand(0); 3172 } else { 3173 return false; 3174 } 3175 3176 bool HasRet = false; 3177 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 3178 UI != UE; ++UI) { 3179 if (UI->getOpcode() != ARMISD::RET_FLAG && 3180 UI->getOpcode() != ARMISD::INTRET_FLAG) 3181 return false; 3182 HasRet = true; 3183 } 3184 3185 if (!HasRet) 3186 return false; 3187 3188 Chain = TCChain; 3189 return true; 3190 } 3191 3192 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3193 if (!Subtarget->supportsTailCall()) 3194 return false; 3195 3196 if (!CI->isTailCall()) 3197 return false; 3198 3199 return true; 3200 } 3201 3202 // Trying to write a 64 bit value so need to split into two 32 bit values first, 3203 // and pass the lower and high parts through. 3204 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 3205 SDLoc DL(Op); 3206 SDValue WriteValue = Op->getOperand(2); 3207 3208 // This function is only supposed to be called for i64 type argument. 3209 assert(WriteValue.getValueType() == MVT::i64 3210 && "LowerWRITE_REGISTER called for non-i64 type argument."); 3211 3212 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3213 DAG.getConstant(0, DL, MVT::i32)); 3214 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 3215 DAG.getConstant(1, DL, MVT::i32)); 3216 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 3217 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 3218 } 3219 3220 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 3221 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 3222 // one of the above mentioned nodes. It has to be wrapped because otherwise 3223 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 3224 // be used to form addressing mode. These wrapped nodes will be selected 3225 // into MOVi. 3226 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 3227 SelectionDAG &DAG) const { 3228 EVT PtrVT = Op.getValueType(); 3229 // FIXME there is no actual debug info here 3230 SDLoc dl(Op); 3231 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3232 SDValue Res; 3233 3234 // When generating execute-only code Constant Pools must be promoted to the 3235 // global data section. It's a bit ugly that we can't share them across basic 3236 // blocks, but this way we guarantee that execute-only behaves correct with 3237 // position-independent addressing modes. 3238 if (Subtarget->genExecuteOnly()) { 3239 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3240 auto T = const_cast<Type*>(CP->getType()); 3241 auto C = const_cast<Constant*>(CP->getConstVal()); 3242 auto M = const_cast<Module*>(DAG.getMachineFunction(). 3243 getFunction().getParent()); 3244 auto GV = new GlobalVariable( 3245 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 3246 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 3247 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 3248 Twine(AFI->createPICLabelUId()) 3249 ); 3250 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 3251 dl, PtrVT); 3252 return LowerGlobalAddress(GA, DAG); 3253 } 3254 3255 if (CP->isMachineConstantPoolEntry()) 3256 Res = 3257 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign()); 3258 else 3259 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign()); 3260 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 3261 } 3262 3263 unsigned ARMTargetLowering::getJumpTableEncoding() const { 3264 return MachineJumpTableInfo::EK_Inline; 3265 } 3266 3267 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 3268 SelectionDAG &DAG) const { 3269 MachineFunction &MF = DAG.getMachineFunction(); 3270 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3271 unsigned ARMPCLabelIndex = 0; 3272 SDLoc DL(Op); 3273 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3274 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 3275 SDValue CPAddr; 3276 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 3277 if (!IsPositionIndependent) { 3278 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4)); 3279 } else { 3280 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3281 ARMPCLabelIndex = AFI->createPICLabelUId(); 3282 ARMConstantPoolValue *CPV = 3283 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3284 ARMCP::CPBlockAddress, PCAdj); 3285 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3286 } 3287 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3288 SDValue Result = DAG.getLoad( 3289 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3290 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3291 if (!IsPositionIndependent) 3292 return Result; 3293 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3294 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3295 } 3296 3297 /// Convert a TLS address reference into the correct sequence of loads 3298 /// and calls to compute the variable's address for Darwin, and return an 3299 /// SDValue containing the final node. 3300 3301 /// Darwin only has one TLS scheme which must be capable of dealing with the 3302 /// fully general situation, in the worst case. This means: 3303 /// + "extern __thread" declaration. 3304 /// + Defined in a possibly unknown dynamic library. 3305 /// 3306 /// The general system is that each __thread variable has a [3 x i32] descriptor 3307 /// which contains information used by the runtime to calculate the address. The 3308 /// only part of this the compiler needs to know about is the first word, which 3309 /// contains a function pointer that must be called with the address of the 3310 /// entire descriptor in "r0". 3311 /// 3312 /// Since this descriptor may be in a different unit, in general access must 3313 /// proceed along the usual ARM rules. A common sequence to produce is: 3314 /// 3315 /// movw rT1, :lower16:_var$non_lazy_ptr 3316 /// movt rT1, :upper16:_var$non_lazy_ptr 3317 /// ldr r0, [rT1] 3318 /// ldr rT2, [r0] 3319 /// blx rT2 3320 /// [...address now in r0...] 3321 SDValue 3322 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3323 SelectionDAG &DAG) const { 3324 assert(Subtarget->isTargetDarwin() && 3325 "This function expects a Darwin target"); 3326 SDLoc DL(Op); 3327 3328 // First step is to get the address of the actua global symbol. This is where 3329 // the TLS descriptor lives. 3330 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3331 3332 // The first entry in the descriptor is a function pointer that we must call 3333 // to obtain the address of the variable. 3334 SDValue Chain = DAG.getEntryNode(); 3335 SDValue FuncTLVGet = DAG.getLoad( 3336 MVT::i32, DL, Chain, DescAddr, 3337 MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4), 3338 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3339 MachineMemOperand::MOInvariant); 3340 Chain = FuncTLVGet.getValue(1); 3341 3342 MachineFunction &F = DAG.getMachineFunction(); 3343 MachineFrameInfo &MFI = F.getFrameInfo(); 3344 MFI.setAdjustsStack(true); 3345 3346 // TLS calls preserve all registers except those that absolutely must be 3347 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3348 // silly). 3349 auto TRI = 3350 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3351 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3352 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3353 3354 // Finally, we can make the call. This is just a degenerate version of a 3355 // normal AArch64 call node: r0 takes the address of the descriptor, and 3356 // returns the address of the variable in this thread. 3357 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3358 Chain = 3359 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3360 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3361 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3362 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3363 } 3364 3365 SDValue 3366 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3367 SelectionDAG &DAG) const { 3368 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3369 3370 SDValue Chain = DAG.getEntryNode(); 3371 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3372 SDLoc DL(Op); 3373 3374 // Load the current TEB (thread environment block) 3375 SDValue Ops[] = {Chain, 3376 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3377 DAG.getTargetConstant(15, DL, MVT::i32), 3378 DAG.getTargetConstant(0, DL, MVT::i32), 3379 DAG.getTargetConstant(13, DL, MVT::i32), 3380 DAG.getTargetConstant(0, DL, MVT::i32), 3381 DAG.getTargetConstant(2, DL, MVT::i32)}; 3382 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3383 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3384 3385 SDValue TEB = CurrentTEB.getValue(0); 3386 Chain = CurrentTEB.getValue(1); 3387 3388 // Load the ThreadLocalStoragePointer from the TEB 3389 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3390 SDValue TLSArray = 3391 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3392 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3393 3394 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3395 // offset into the TLSArray. 3396 3397 // Load the TLS index from the C runtime 3398 SDValue TLSIndex = 3399 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3400 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3401 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3402 3403 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3404 DAG.getConstant(2, DL, MVT::i32)); 3405 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3406 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3407 MachinePointerInfo()); 3408 3409 // Get the offset of the start of the .tls section (section base) 3410 const auto *GA = cast<GlobalAddressSDNode>(Op); 3411 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3412 SDValue Offset = DAG.getLoad( 3413 PtrVT, DL, Chain, 3414 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3415 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))), 3416 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3417 3418 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3419 } 3420 3421 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3422 SDValue 3423 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3424 SelectionDAG &DAG) const { 3425 SDLoc dl(GA); 3426 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3427 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3428 MachineFunction &MF = DAG.getMachineFunction(); 3429 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3430 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3431 ARMConstantPoolValue *CPV = 3432 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3433 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3434 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3435 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3436 Argument = DAG.getLoad( 3437 PtrVT, dl, DAG.getEntryNode(), Argument, 3438 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3439 SDValue Chain = Argument.getValue(1); 3440 3441 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3442 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3443 3444 // call __tls_get_addr. 3445 ArgListTy Args; 3446 ArgListEntry Entry; 3447 Entry.Node = Argument; 3448 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3449 Args.push_back(Entry); 3450 3451 // FIXME: is there useful debug info available here? 3452 TargetLowering::CallLoweringInfo CLI(DAG); 3453 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3454 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3455 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3456 3457 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3458 return CallResult.first; 3459 } 3460 3461 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3462 // "local exec" model. 3463 SDValue 3464 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3465 SelectionDAG &DAG, 3466 TLSModel::Model model) const { 3467 const GlobalValue *GV = GA->getGlobal(); 3468 SDLoc dl(GA); 3469 SDValue Offset; 3470 SDValue Chain = DAG.getEntryNode(); 3471 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3472 // Get the Thread Pointer 3473 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3474 3475 if (model == TLSModel::InitialExec) { 3476 MachineFunction &MF = DAG.getMachineFunction(); 3477 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3478 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3479 // Initial exec model. 3480 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3481 ARMConstantPoolValue *CPV = 3482 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3483 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3484 true); 3485 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3486 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3487 Offset = DAG.getLoad( 3488 PtrVT, dl, Chain, Offset, 3489 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3490 Chain = Offset.getValue(1); 3491 3492 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3493 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3494 3495 Offset = DAG.getLoad( 3496 PtrVT, dl, Chain, Offset, 3497 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3498 } else { 3499 // local exec model 3500 assert(model == TLSModel::LocalExec); 3501 ARMConstantPoolValue *CPV = 3502 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3503 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3504 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3505 Offset = DAG.getLoad( 3506 PtrVT, dl, Chain, Offset, 3507 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3508 } 3509 3510 // The address of the thread local variable is the add of the thread 3511 // pointer with the offset of the variable. 3512 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3513 } 3514 3515 SDValue 3516 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3517 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3518 if (DAG.getTarget().useEmulatedTLS()) 3519 return LowerToTLSEmulatedModel(GA, DAG); 3520 3521 if (Subtarget->isTargetDarwin()) 3522 return LowerGlobalTLSAddressDarwin(Op, DAG); 3523 3524 if (Subtarget->isTargetWindows()) 3525 return LowerGlobalTLSAddressWindows(Op, DAG); 3526 3527 // TODO: implement the "local dynamic" model 3528 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3529 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3530 3531 switch (model) { 3532 case TLSModel::GeneralDynamic: 3533 case TLSModel::LocalDynamic: 3534 return LowerToTLSGeneralDynamicModel(GA, DAG); 3535 case TLSModel::InitialExec: 3536 case TLSModel::LocalExec: 3537 return LowerToTLSExecModels(GA, DAG, model); 3538 } 3539 llvm_unreachable("bogus TLS model"); 3540 } 3541 3542 /// Return true if all users of V are within function F, looking through 3543 /// ConstantExprs. 3544 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3545 SmallVector<const User*,4> Worklist; 3546 for (auto *U : V->users()) 3547 Worklist.push_back(U); 3548 while (!Worklist.empty()) { 3549 auto *U = Worklist.pop_back_val(); 3550 if (isa<ConstantExpr>(U)) { 3551 for (auto *UU : U->users()) 3552 Worklist.push_back(UU); 3553 continue; 3554 } 3555 3556 auto *I = dyn_cast<Instruction>(U); 3557 if (!I || I->getParent()->getParent() != F) 3558 return false; 3559 } 3560 return true; 3561 } 3562 3563 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3564 const GlobalValue *GV, SelectionDAG &DAG, 3565 EVT PtrVT, const SDLoc &dl) { 3566 // If we're creating a pool entry for a constant global with unnamed address, 3567 // and the global is small enough, we can emit it inline into the constant pool 3568 // to save ourselves an indirection. 3569 // 3570 // This is a win if the constant is only used in one function (so it doesn't 3571 // need to be duplicated) or duplicating the constant wouldn't increase code 3572 // size (implying the constant is no larger than 4 bytes). 3573 const Function &F = DAG.getMachineFunction().getFunction(); 3574 3575 // We rely on this decision to inline being idemopotent and unrelated to the 3576 // use-site. We know that if we inline a variable at one use site, we'll 3577 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3578 // doesn't know about this optimization, so bail out if it's enabled else 3579 // we could decide to inline here (and thus never emit the GV) but require 3580 // the GV from fast-isel generated code. 3581 if (!EnableConstpoolPromotion || 3582 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3583 return SDValue(); 3584 3585 auto *GVar = dyn_cast<GlobalVariable>(GV); 3586 if (!GVar || !GVar->hasInitializer() || 3587 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3588 !GVar->hasLocalLinkage()) 3589 return SDValue(); 3590 3591 // If we inline a value that contains relocations, we move the relocations 3592 // from .data to .text. This is not allowed in position-independent code. 3593 auto *Init = GVar->getInitializer(); 3594 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3595 Init->needsRelocation()) 3596 return SDValue(); 3597 3598 // The constant islands pass can only really deal with alignment requests 3599 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3600 // any type wanting greater alignment requirements than 4 bytes. We also 3601 // can only promote constants that are multiples of 4 bytes in size or 3602 // are paddable to a multiple of 4. Currently we only try and pad constants 3603 // that are strings for simplicity. 3604 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3605 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3606 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar); 3607 unsigned RequiredPadding = 4 - (Size % 4); 3608 bool PaddingPossible = 3609 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3610 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize || 3611 Size == 0) 3612 return SDValue(); 3613 3614 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3615 MachineFunction &MF = DAG.getMachineFunction(); 3616 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3617 3618 // We can't bloat the constant pool too much, else the ConstantIslands pass 3619 // may fail to converge. If we haven't promoted this global yet (it may have 3620 // multiple uses), and promoting it would increase the constant pool size (Sz 3621 // > 4), ensure we have space to do so up to MaxTotal. 3622 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3623 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3624 ConstpoolPromotionMaxTotal) 3625 return SDValue(); 3626 3627 // This is only valid if all users are in a single function; we can't clone 3628 // the constant in general. The LLVM IR unnamed_addr allows merging 3629 // constants, but not cloning them. 3630 // 3631 // We could potentially allow cloning if we could prove all uses of the 3632 // constant in the current function don't care about the address, like 3633 // printf format strings. But that isn't implemented for now. 3634 if (!allUsersAreInFunction(GVar, &F)) 3635 return SDValue(); 3636 3637 // We're going to inline this global. Pad it out if needed. 3638 if (RequiredPadding != 4) { 3639 StringRef S = CDAInit->getAsString(); 3640 3641 SmallVector<uint8_t,16> V(S.size()); 3642 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3643 while (RequiredPadding--) 3644 V.push_back(0); 3645 Init = ConstantDataArray::get(*DAG.getContext(), V); 3646 } 3647 3648 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3649 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4)); 3650 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3651 AFI->markGlobalAsPromotedToConstantPool(GVar); 3652 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3653 PaddedSize - 4); 3654 } 3655 ++NumConstpoolPromoted; 3656 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3657 } 3658 3659 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3660 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3661 if (!(GV = GA->getBaseObject())) 3662 return false; 3663 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3664 return V->isConstant(); 3665 return isa<Function>(GV); 3666 } 3667 3668 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3669 SelectionDAG &DAG) const { 3670 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3671 default: llvm_unreachable("unknown object format"); 3672 case Triple::COFF: 3673 return LowerGlobalAddressWindows(Op, DAG); 3674 case Triple::ELF: 3675 return LowerGlobalAddressELF(Op, DAG); 3676 case Triple::MachO: 3677 return LowerGlobalAddressDarwin(Op, DAG); 3678 } 3679 } 3680 3681 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3682 SelectionDAG &DAG) const { 3683 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3684 SDLoc dl(Op); 3685 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3686 const TargetMachine &TM = getTargetMachine(); 3687 bool IsRO = isReadOnly(GV); 3688 3689 // promoteToConstantPool only if not generating XO text section 3690 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3691 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3692 return V; 3693 3694 if (isPositionIndependent()) { 3695 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3696 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3697 UseGOT_PREL ? ARMII::MO_GOT : 0); 3698 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3699 if (UseGOT_PREL) 3700 Result = 3701 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3702 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3703 return Result; 3704 } else if (Subtarget->isROPI() && IsRO) { 3705 // PC-relative. 3706 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3707 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3708 return Result; 3709 } else if (Subtarget->isRWPI() && !IsRO) { 3710 // SB-relative. 3711 SDValue RelAddr; 3712 if (Subtarget->useMovt()) { 3713 ++NumMovwMovt; 3714 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3715 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3716 } else { // use literal pool for address constant 3717 ARMConstantPoolValue *CPV = 3718 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3719 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3720 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3721 RelAddr = DAG.getLoad( 3722 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3723 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3724 } 3725 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3726 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3727 return Result; 3728 } 3729 3730 // If we have T2 ops, we can materialize the address directly via movt/movw 3731 // pair. This is always cheaper. 3732 if (Subtarget->useMovt()) { 3733 ++NumMovwMovt; 3734 // FIXME: Once remat is capable of dealing with instructions with register 3735 // operands, expand this into two nodes. 3736 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3737 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3738 } else { 3739 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4)); 3740 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3741 return DAG.getLoad( 3742 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3743 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3744 } 3745 } 3746 3747 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3748 SelectionDAG &DAG) const { 3749 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3750 "ROPI/RWPI not currently supported for Darwin"); 3751 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3752 SDLoc dl(Op); 3753 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3754 3755 if (Subtarget->useMovt()) 3756 ++NumMovwMovt; 3757 3758 // FIXME: Once remat is capable of dealing with instructions with register 3759 // operands, expand this into multiple nodes 3760 unsigned Wrapper = 3761 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3762 3763 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3764 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3765 3766 if (Subtarget->isGVIndirectSymbol(GV)) 3767 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3768 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3769 return Result; 3770 } 3771 3772 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3773 SelectionDAG &DAG) const { 3774 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3775 assert(Subtarget->useMovt() && 3776 "Windows on ARM expects to use movw/movt"); 3777 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3778 "ROPI/RWPI not currently supported for Windows"); 3779 3780 const TargetMachine &TM = getTargetMachine(); 3781 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3782 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3783 if (GV->hasDLLImportStorageClass()) 3784 TargetFlags = ARMII::MO_DLLIMPORT; 3785 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3786 TargetFlags = ARMII::MO_COFFSTUB; 3787 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3788 SDValue Result; 3789 SDLoc DL(Op); 3790 3791 ++NumMovwMovt; 3792 3793 // FIXME: Once remat is capable of dealing with instructions with register 3794 // operands, expand this into two nodes. 3795 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3796 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3797 TargetFlags)); 3798 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3799 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3800 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3801 return Result; 3802 } 3803 3804 SDValue 3805 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3806 SDLoc dl(Op); 3807 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3808 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3809 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3810 Op.getOperand(1), Val); 3811 } 3812 3813 SDValue 3814 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3815 SDLoc dl(Op); 3816 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3817 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3818 } 3819 3820 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3821 SelectionDAG &DAG) const { 3822 SDLoc dl(Op); 3823 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3824 Op.getOperand(0)); 3825 } 3826 3827 SDValue ARMTargetLowering::LowerINTRINSIC_VOID( 3828 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const { 3829 unsigned IntNo = 3830 cast<ConstantSDNode>( 3831 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other)) 3832 ->getZExtValue(); 3833 switch (IntNo) { 3834 default: 3835 return SDValue(); // Don't custom lower most intrinsics. 3836 case Intrinsic::arm_gnu_eabi_mcount: { 3837 MachineFunction &MF = DAG.getMachineFunction(); 3838 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3839 SDLoc dl(Op); 3840 SDValue Chain = Op.getOperand(0); 3841 // call "\01__gnu_mcount_nc" 3842 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 3843 const uint32_t *Mask = 3844 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3845 assert(Mask && "Missing call preserved mask for calling convention"); 3846 // Mark LR an implicit live-in. 3847 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3848 SDValue ReturnAddress = 3849 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT); 3850 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue}; 3851 SDValue Callee = 3852 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0); 3853 SDValue RegisterMask = DAG.getRegisterMask(Mask); 3854 if (Subtarget->isThumb()) 3855 return SDValue( 3856 DAG.getMachineNode( 3857 ARM::tBL_PUSHLR, dl, ResultTys, 3858 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT), 3859 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}), 3860 0); 3861 return SDValue( 3862 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys, 3863 {ReturnAddress, Callee, RegisterMask, Chain}), 3864 0); 3865 } 3866 } 3867 } 3868 3869 SDValue 3870 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3871 const ARMSubtarget *Subtarget) const { 3872 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3873 SDLoc dl(Op); 3874 switch (IntNo) { 3875 default: return SDValue(); // Don't custom lower most intrinsics. 3876 case Intrinsic::thread_pointer: { 3877 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3878 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3879 } 3880 case Intrinsic::arm_cls: { 3881 const SDValue &Operand = Op.getOperand(1); 3882 const EVT VTy = Op.getValueType(); 3883 SDValue SRA = 3884 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy)); 3885 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand); 3886 SDValue SHL = 3887 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy)); 3888 SDValue OR = 3889 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy)); 3890 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR); 3891 return Result; 3892 } 3893 case Intrinsic::arm_cls64: { 3894 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x)) 3895 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x))) 3896 const SDValue &Operand = Op.getOperand(1); 3897 const EVT VTy = Op.getValueType(); 3898 3899 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3900 DAG.getConstant(1, dl, VTy)); 3901 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand, 3902 DAG.getConstant(0, dl, VTy)); 3903 SDValue Constant0 = DAG.getConstant(0, dl, VTy); 3904 SDValue Constant1 = DAG.getConstant(1, dl, VTy); 3905 SDValue Constant31 = DAG.getConstant(31, dl, VTy); 3906 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31); 3907 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi); 3908 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1); 3909 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1); 3910 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi); 3911 SDValue CheckLo = 3912 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ); 3913 SDValue HiIsZero = 3914 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ); 3915 SDValue AdjustedLo = 3916 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy)); 3917 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo); 3918 SDValue Result = 3919 DAG.getSelect(dl, VTy, CheckLo, 3920 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi); 3921 return Result; 3922 } 3923 case Intrinsic::eh_sjlj_lsda: { 3924 MachineFunction &MF = DAG.getMachineFunction(); 3925 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3926 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3927 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3928 SDValue CPAddr; 3929 bool IsPositionIndependent = isPositionIndependent(); 3930 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3931 ARMConstantPoolValue *CPV = 3932 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3933 ARMCP::CPLSDA, PCAdj); 3934 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4)); 3935 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3936 SDValue Result = DAG.getLoad( 3937 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3938 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3939 3940 if (IsPositionIndependent) { 3941 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3942 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3943 } 3944 return Result; 3945 } 3946 case Intrinsic::arm_neon_vabs: 3947 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3948 Op.getOperand(1)); 3949 case Intrinsic::arm_neon_vmulls: 3950 case Intrinsic::arm_neon_vmullu: { 3951 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3952 ? ARMISD::VMULLs : ARMISD::VMULLu; 3953 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3954 Op.getOperand(1), Op.getOperand(2)); 3955 } 3956 case Intrinsic::arm_neon_vminnm: 3957 case Intrinsic::arm_neon_vmaxnm: { 3958 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3959 ? ISD::FMINNUM : ISD::FMAXNUM; 3960 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3961 Op.getOperand(1), Op.getOperand(2)); 3962 } 3963 case Intrinsic::arm_neon_vminu: 3964 case Intrinsic::arm_neon_vmaxu: { 3965 if (Op.getValueType().isFloatingPoint()) 3966 return SDValue(); 3967 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3968 ? ISD::UMIN : ISD::UMAX; 3969 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3970 Op.getOperand(1), Op.getOperand(2)); 3971 } 3972 case Intrinsic::arm_neon_vmins: 3973 case Intrinsic::arm_neon_vmaxs: { 3974 // v{min,max}s is overloaded between signed integers and floats. 3975 if (!Op.getValueType().isFloatingPoint()) { 3976 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3977 ? ISD::SMIN : ISD::SMAX; 3978 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3979 Op.getOperand(1), Op.getOperand(2)); 3980 } 3981 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3982 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3983 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3984 Op.getOperand(1), Op.getOperand(2)); 3985 } 3986 case Intrinsic::arm_neon_vtbl1: 3987 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3988 Op.getOperand(1), Op.getOperand(2)); 3989 case Intrinsic::arm_neon_vtbl2: 3990 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3991 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3992 case Intrinsic::arm_mve_pred_i2v: 3993 case Intrinsic::arm_mve_pred_v2i: 3994 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(), 3995 Op.getOperand(1)); 3996 case Intrinsic::arm_mve_vreinterpretq: 3997 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(), 3998 Op.getOperand(1)); 3999 case Intrinsic::arm_mve_lsll: 4000 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(), 4001 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4002 case Intrinsic::arm_mve_asrl: 4003 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(), 4004 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4005 } 4006 } 4007 4008 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 4009 const ARMSubtarget *Subtarget) { 4010 SDLoc dl(Op); 4011 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 4012 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 4013 if (SSID == SyncScope::SingleThread) 4014 return Op; 4015 4016 if (!Subtarget->hasDataBarrier()) { 4017 // Some ARMv6 cpus can support data barriers with an mcr instruction. 4018 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 4019 // here. 4020 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 4021 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 4022 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 4023 DAG.getConstant(0, dl, MVT::i32)); 4024 } 4025 4026 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 4027 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 4028 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 4029 if (Subtarget->isMClass()) { 4030 // Only a full system barrier exists in the M-class architectures. 4031 Domain = ARM_MB::SY; 4032 } else if (Subtarget->preferISHSTBarriers() && 4033 Ord == AtomicOrdering::Release) { 4034 // Swift happens to implement ISHST barriers in a way that's compatible with 4035 // Release semantics but weaker than ISH so we'd be fools not to use 4036 // it. Beware: other processors probably don't! 4037 Domain = ARM_MB::ISHST; 4038 } 4039 4040 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 4041 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 4042 DAG.getConstant(Domain, dl, MVT::i32)); 4043 } 4044 4045 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 4046 const ARMSubtarget *Subtarget) { 4047 // ARM pre v5TE and Thumb1 does not have preload instructions. 4048 if (!(Subtarget->isThumb2() || 4049 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 4050 // Just preserve the chain. 4051 return Op.getOperand(0); 4052 4053 SDLoc dl(Op); 4054 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 4055 if (!isRead && 4056 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 4057 // ARMv7 with MP extension has PLDW. 4058 return Op.getOperand(0); 4059 4060 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 4061 if (Subtarget->isThumb()) { 4062 // Invert the bits. 4063 isRead = ~isRead & 1; 4064 isData = ~isData & 1; 4065 } 4066 4067 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 4068 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 4069 DAG.getConstant(isData, dl, MVT::i32)); 4070 } 4071 4072 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 4073 MachineFunction &MF = DAG.getMachineFunction(); 4074 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 4075 4076 // vastart just stores the address of the VarArgsFrameIndex slot into the 4077 // memory location argument. 4078 SDLoc dl(Op); 4079 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4080 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4081 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4082 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 4083 MachinePointerInfo(SV)); 4084 } 4085 4086 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 4087 CCValAssign &NextVA, 4088 SDValue &Root, 4089 SelectionDAG &DAG, 4090 const SDLoc &dl) const { 4091 MachineFunction &MF = DAG.getMachineFunction(); 4092 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4093 4094 const TargetRegisterClass *RC; 4095 if (AFI->isThumb1OnlyFunction()) 4096 RC = &ARM::tGPRRegClass; 4097 else 4098 RC = &ARM::GPRRegClass; 4099 4100 // Transform the arguments stored in physical registers into virtual ones. 4101 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4102 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4103 4104 SDValue ArgValue2; 4105 if (NextVA.isMemLoc()) { 4106 MachineFrameInfo &MFI = MF.getFrameInfo(); 4107 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 4108 4109 // Create load node to retrieve arguments from the stack. 4110 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4111 ArgValue2 = DAG.getLoad( 4112 MVT::i32, dl, Root, FIN, 4113 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4114 } else { 4115 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 4116 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 4117 } 4118 if (!Subtarget->isLittle()) 4119 std::swap (ArgValue, ArgValue2); 4120 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 4121 } 4122 4123 // The remaining GPRs hold either the beginning of variable-argument 4124 // data, or the beginning of an aggregate passed by value (usually 4125 // byval). Either way, we allocate stack slots adjacent to the data 4126 // provided by our caller, and store the unallocated registers there. 4127 // If this is a variadic function, the va_list pointer will begin with 4128 // these values; otherwise, this reassembles a (byval) structure that 4129 // was split between registers and memory. 4130 // Return: The frame index registers were stored into. 4131 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 4132 const SDLoc &dl, SDValue &Chain, 4133 const Value *OrigArg, 4134 unsigned InRegsParamRecordIdx, 4135 int ArgOffset, unsigned ArgSize) const { 4136 // Currently, two use-cases possible: 4137 // Case #1. Non-var-args function, and we meet first byval parameter. 4138 // Setup first unallocated register as first byval register; 4139 // eat all remained registers 4140 // (these two actions are performed by HandleByVal method). 4141 // Then, here, we initialize stack frame with 4142 // "store-reg" instructions. 4143 // Case #2. Var-args function, that doesn't contain byval parameters. 4144 // The same: eat all remained unallocated registers, 4145 // initialize stack frame. 4146 4147 MachineFunction &MF = DAG.getMachineFunction(); 4148 MachineFrameInfo &MFI = MF.getFrameInfo(); 4149 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4150 unsigned RBegin, REnd; 4151 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 4152 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 4153 } else { 4154 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4155 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 4156 REnd = ARM::R4; 4157 } 4158 4159 if (REnd != RBegin) 4160 ArgOffset = -4 * (ARM::R4 - RBegin); 4161 4162 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4163 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 4164 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 4165 4166 SmallVector<SDValue, 4> MemOps; 4167 const TargetRegisterClass *RC = 4168 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 4169 4170 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 4171 unsigned VReg = MF.addLiveIn(Reg, RC); 4172 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4173 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4174 MachinePointerInfo(OrigArg, 4 * i)); 4175 MemOps.push_back(Store); 4176 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 4177 } 4178 4179 if (!MemOps.empty()) 4180 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4181 return FrameIndex; 4182 } 4183 4184 // Setup stack frame, the va_list pointer will start from. 4185 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 4186 const SDLoc &dl, SDValue &Chain, 4187 unsigned ArgOffset, 4188 unsigned TotalArgRegsSaveSize, 4189 bool ForceMutable) const { 4190 MachineFunction &MF = DAG.getMachineFunction(); 4191 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4192 4193 // Try to store any remaining integer argument regs 4194 // to their spots on the stack so that they may be loaded by dereferencing 4195 // the result of va_next. 4196 // If there is no regs to be stored, just point address after last 4197 // argument passed via stack. 4198 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 4199 CCInfo.getInRegsParamsCount(), 4200 CCInfo.getNextStackOffset(), 4201 std::max(4U, TotalArgRegsSaveSize)); 4202 AFI->setVarArgsFrameIndex(FrameIndex); 4203 } 4204 4205 bool ARMTargetLowering::splitValueIntoRegisterParts( 4206 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 4207 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 4208 bool IsABIRegCopy = CC.hasValue(); 4209 EVT ValueVT = Val.getValueType(); 4210 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4211 PartVT == MVT::f32) { 4212 unsigned ValueBits = ValueVT.getSizeInBits(); 4213 unsigned PartBits = PartVT.getSizeInBits(); 4214 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val); 4215 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val); 4216 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 4217 Parts[0] = Val; 4218 return true; 4219 } 4220 return false; 4221 } 4222 4223 SDValue ARMTargetLowering::joinRegisterPartsIntoValue( 4224 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 4225 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 4226 bool IsABIRegCopy = CC.hasValue(); 4227 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) && 4228 PartVT == MVT::f32) { 4229 unsigned ValueBits = ValueVT.getSizeInBits(); 4230 unsigned PartBits = PartVT.getSizeInBits(); 4231 SDValue Val = Parts[0]; 4232 4233 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val); 4234 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val); 4235 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 4236 return Val; 4237 } 4238 return SDValue(); 4239 } 4240 4241 SDValue ARMTargetLowering::LowerFormalArguments( 4242 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4243 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4244 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4245 MachineFunction &MF = DAG.getMachineFunction(); 4246 MachineFrameInfo &MFI = MF.getFrameInfo(); 4247 4248 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 4249 4250 // Assign locations to all of the incoming arguments. 4251 SmallVector<CCValAssign, 16> ArgLocs; 4252 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4253 *DAG.getContext()); 4254 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 4255 4256 SmallVector<SDValue, 16> ArgValues; 4257 SDValue ArgValue; 4258 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4259 unsigned CurArgIdx = 0; 4260 4261 // Initially ArgRegsSaveSize is zero. 4262 // Then we increase this value each time we meet byval parameter. 4263 // We also increase this value in case of varargs function. 4264 AFI->setArgRegsSaveSize(0); 4265 4266 // Calculate the amount of stack space that we need to allocate to store 4267 // byval and variadic arguments that are passed in registers. 4268 // We need to know this before we allocate the first byval or variadic 4269 // argument, as they will be allocated a stack slot below the CFA (Canonical 4270 // Frame Address, the stack pointer at entry to the function). 4271 unsigned ArgRegBegin = ARM::R4; 4272 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4273 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 4274 break; 4275 4276 CCValAssign &VA = ArgLocs[i]; 4277 unsigned Index = VA.getValNo(); 4278 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 4279 if (!Flags.isByVal()) 4280 continue; 4281 4282 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 4283 unsigned RBegin, REnd; 4284 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 4285 ArgRegBegin = std::min(ArgRegBegin, RBegin); 4286 4287 CCInfo.nextInRegsParam(); 4288 } 4289 CCInfo.rewindByValRegsInfo(); 4290 4291 int lastInsIndex = -1; 4292 if (isVarArg && MFI.hasVAStart()) { 4293 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 4294 if (RegIdx != array_lengthof(GPRArgRegs)) 4295 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 4296 } 4297 4298 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 4299 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 4300 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4301 4302 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4303 CCValAssign &VA = ArgLocs[i]; 4304 if (Ins[VA.getValNo()].isOrigArg()) { 4305 std::advance(CurOrigArg, 4306 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 4307 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 4308 } 4309 // Arguments stored in registers. 4310 if (VA.isRegLoc()) { 4311 EVT RegVT = VA.getLocVT(); 4312 4313 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) { 4314 // f64 and vector types are split up into multiple registers or 4315 // combinations of registers and stack slots. 4316 SDValue ArgValue1 = 4317 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4318 VA = ArgLocs[++i]; // skip ahead to next loc 4319 SDValue ArgValue2; 4320 if (VA.isMemLoc()) { 4321 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 4322 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4323 ArgValue2 = DAG.getLoad( 4324 MVT::f64, dl, Chain, FIN, 4325 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4326 } else { 4327 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4328 } 4329 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 4330 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4331 ArgValue1, DAG.getIntPtrConstant(0, dl)); 4332 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue, 4333 ArgValue2, DAG.getIntPtrConstant(1, dl)); 4334 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) { 4335 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 4336 } else { 4337 const TargetRegisterClass *RC; 4338 4339 if (RegVT == MVT::f16 || RegVT == MVT::bf16) 4340 RC = &ARM::HPRRegClass; 4341 else if (RegVT == MVT::f32) 4342 RC = &ARM::SPRRegClass; 4343 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 || 4344 RegVT == MVT::v4bf16) 4345 RC = &ARM::DPRRegClass; 4346 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 || 4347 RegVT == MVT::v8bf16) 4348 RC = &ARM::QPRRegClass; 4349 else if (RegVT == MVT::i32) 4350 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 4351 : &ARM::GPRRegClass; 4352 else 4353 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4354 4355 // Transform the arguments in physical registers into virtual ones. 4356 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4357 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 4358 4359 // If this value is passed in r0 and has the returned attribute (e.g. 4360 // C++ 'structors), record this fact for later use. 4361 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 4362 AFI->setPreservesR0(); 4363 } 4364 } 4365 4366 // If this is an 8 or 16-bit value, it is really passed promoted 4367 // to 32 bits. Insert an assert[sz]ext to capture this, then 4368 // truncate to the right size. 4369 switch (VA.getLocInfo()) { 4370 default: llvm_unreachable("Unknown loc info!"); 4371 case CCValAssign::Full: break; 4372 case CCValAssign::BCvt: 4373 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 4374 break; 4375 case CCValAssign::SExt: 4376 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 4377 DAG.getValueType(VA.getValVT())); 4378 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4379 break; 4380 case CCValAssign::ZExt: 4381 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 4382 DAG.getValueType(VA.getValVT())); 4383 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4384 break; 4385 } 4386 4387 // f16 arguments have their size extended to 4 bytes and passed as if they 4388 // had been copied to the LSBs of a 32-bit register. 4389 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI) 4390 if (VA.needsCustom() && 4391 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) 4392 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue); 4393 4394 InVals.push_back(ArgValue); 4395 } else { // VA.isRegLoc() 4396 // sanity check 4397 assert(VA.isMemLoc()); 4398 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 4399 4400 int index = VA.getValNo(); 4401 4402 // Some Ins[] entries become multiple ArgLoc[] entries. 4403 // Process them only once. 4404 if (index != lastInsIndex) 4405 { 4406 ISD::ArgFlagsTy Flags = Ins[index].Flags; 4407 // FIXME: For now, all byval parameter objects are marked mutable. 4408 // This can be changed with more analysis. 4409 // In case of tail call optimization mark all arguments mutable. 4410 // Since they could be overwritten by lowering of arguments in case of 4411 // a tail call. 4412 if (Flags.isByVal()) { 4413 assert(Ins[index].isOrigArg() && 4414 "Byval arguments cannot be implicit"); 4415 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 4416 4417 int FrameIndex = StoreByValRegs( 4418 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4419 VA.getLocMemOffset(), Flags.getByValSize()); 4420 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4421 CCInfo.nextInRegsParam(); 4422 } else { 4423 unsigned FIOffset = VA.getLocMemOffset(); 4424 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4425 FIOffset, true); 4426 4427 // Create load nodes to retrieve arguments from the stack. 4428 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4429 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4430 MachinePointerInfo::getFixedStack( 4431 DAG.getMachineFunction(), FI))); 4432 } 4433 lastInsIndex = index; 4434 } 4435 } 4436 } 4437 4438 // varargs 4439 if (isVarArg && MFI.hasVAStart()) { 4440 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(), 4441 TotalArgRegsSaveSize); 4442 if (AFI->isCmseNSEntryFunction()) { 4443 DiagnosticInfoUnsupported Diag( 4444 DAG.getMachineFunction().getFunction(), 4445 "secure entry function must not be variadic", dl.getDebugLoc()); 4446 DAG.getContext()->diagnose(Diag); 4447 } 4448 } 4449 4450 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4451 4452 if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) { 4453 DiagnosticInfoUnsupported Diag( 4454 DAG.getMachineFunction().getFunction(), 4455 "secure entry function requires arguments on stack", dl.getDebugLoc()); 4456 DAG.getContext()->diagnose(Diag); 4457 } 4458 4459 return Chain; 4460 } 4461 4462 /// isFloatingPointZero - Return true if this is +0.0. 4463 static bool isFloatingPointZero(SDValue Op) { 4464 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4465 return CFP->getValueAPF().isPosZero(); 4466 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4467 // Maybe this has already been legalized into the constant pool? 4468 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4469 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4470 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4471 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4472 return CFP->getValueAPF().isPosZero(); 4473 } 4474 } else if (Op->getOpcode() == ISD::BITCAST && 4475 Op->getValueType(0) == MVT::f64) { 4476 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4477 // created by LowerConstantFP(). 4478 SDValue BitcastOp = Op->getOperand(0); 4479 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4480 isNullConstant(BitcastOp->getOperand(0))) 4481 return true; 4482 } 4483 return false; 4484 } 4485 4486 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4487 /// the given operands. 4488 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4489 SDValue &ARMcc, SelectionDAG &DAG, 4490 const SDLoc &dl) const { 4491 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4492 unsigned C = RHSC->getZExtValue(); 4493 if (!isLegalICmpImmediate((int32_t)C)) { 4494 // Constant does not fit, try adjusting it by one. 4495 switch (CC) { 4496 default: break; 4497 case ISD::SETLT: 4498 case ISD::SETGE: 4499 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4500 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4501 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4502 } 4503 break; 4504 case ISD::SETULT: 4505 case ISD::SETUGE: 4506 if (C != 0 && isLegalICmpImmediate(C-1)) { 4507 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4508 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4509 } 4510 break; 4511 case ISD::SETLE: 4512 case ISD::SETGT: 4513 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4514 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4515 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4516 } 4517 break; 4518 case ISD::SETULE: 4519 case ISD::SETUGT: 4520 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4521 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4522 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4523 } 4524 break; 4525 } 4526 } 4527 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4528 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4529 // In ARM and Thumb-2, the compare instructions can shift their second 4530 // operand. 4531 CC = ISD::getSetCCSwappedOperands(CC); 4532 std::swap(LHS, RHS); 4533 } 4534 4535 // Thumb1 has very limited immediate modes, so turning an "and" into a 4536 // shift can save multiple instructions. 4537 // 4538 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4539 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4540 // own. If it's the operand to an unsigned comparison with an immediate, 4541 // we can eliminate one of the shifts: we transform 4542 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4543 // 4544 // We avoid transforming cases which aren't profitable due to encoding 4545 // details: 4546 // 4547 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4548 // would not; in that case, we're essentially trading one immediate load for 4549 // another. 4550 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4551 // 3. C2 is zero; we have other code for this special case. 4552 // 4553 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4554 // instruction, since the AND is always one instruction anyway, but we could 4555 // use narrow instructions in some cases. 4556 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4557 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4558 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4559 !isSignedIntSetCC(CC)) { 4560 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4561 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4562 uint64_t RHSV = RHSC->getZExtValue(); 4563 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4564 unsigned ShiftBits = countLeadingZeros(Mask); 4565 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4566 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4567 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4568 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4569 } 4570 } 4571 } 4572 4573 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4574 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4575 // way a cmp would. 4576 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4577 // some tweaks to the heuristics for the previous and->shift transform. 4578 // FIXME: Optimize cases where the LHS isn't a shift. 4579 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4580 isa<ConstantSDNode>(RHS) && 4581 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4582 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4583 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4584 unsigned ShiftAmt = 4585 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4586 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4587 DAG.getVTList(MVT::i32, MVT::i32), 4588 LHS.getOperand(0), 4589 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4590 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4591 Shift.getValue(1), SDValue()); 4592 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4593 return Chain.getValue(1); 4594 } 4595 4596 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4597 4598 // If the RHS is a constant zero then the V (overflow) flag will never be 4599 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4600 // simpler for other passes (like the peephole optimiser) to deal with. 4601 if (isNullConstant(RHS)) { 4602 switch (CondCode) { 4603 default: break; 4604 case ARMCC::GE: 4605 CondCode = ARMCC::PL; 4606 break; 4607 case ARMCC::LT: 4608 CondCode = ARMCC::MI; 4609 break; 4610 } 4611 } 4612 4613 ARMISD::NodeType CompareType; 4614 switch (CondCode) { 4615 default: 4616 CompareType = ARMISD::CMP; 4617 break; 4618 case ARMCC::EQ: 4619 case ARMCC::NE: 4620 // Uses only Z Flag 4621 CompareType = ARMISD::CMPZ; 4622 break; 4623 } 4624 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4625 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4626 } 4627 4628 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4629 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4630 SelectionDAG &DAG, const SDLoc &dl, 4631 bool Signaling) const { 4632 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4633 SDValue Cmp; 4634 if (!isFloatingPointZero(RHS)) 4635 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, 4636 dl, MVT::Glue, LHS, RHS); 4637 else 4638 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, 4639 dl, MVT::Glue, LHS); 4640 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4641 } 4642 4643 /// duplicateCmp - Glue values can have only one use, so this function 4644 /// duplicates a comparison node. 4645 SDValue 4646 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4647 unsigned Opc = Cmp.getOpcode(); 4648 SDLoc DL(Cmp); 4649 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4650 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4651 4652 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4653 Cmp = Cmp.getOperand(0); 4654 Opc = Cmp.getOpcode(); 4655 if (Opc == ARMISD::CMPFP) 4656 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4657 else { 4658 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4659 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 4660 } 4661 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4662 } 4663 4664 // This function returns three things: the arithmetic computation itself 4665 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4666 // comparison and the condition code define the case in which the arithmetic 4667 // computation *does not* overflow. 4668 std::pair<SDValue, SDValue> 4669 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4670 SDValue &ARMcc) const { 4671 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4672 4673 SDValue Value, OverflowCmp; 4674 SDValue LHS = Op.getOperand(0); 4675 SDValue RHS = Op.getOperand(1); 4676 SDLoc dl(Op); 4677 4678 // FIXME: We are currently always generating CMPs because we don't support 4679 // generating CMN through the backend. This is not as good as the natural 4680 // CMP case because it causes a register dependency and cannot be folded 4681 // later. 4682 4683 switch (Op.getOpcode()) { 4684 default: 4685 llvm_unreachable("Unknown overflow instruction!"); 4686 case ISD::SADDO: 4687 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4688 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4689 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4690 break; 4691 case ISD::UADDO: 4692 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4693 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4694 // We do not use it in the USUBO case as Value may not be used. 4695 Value = DAG.getNode(ARMISD::ADDC, dl, 4696 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4697 .getValue(0); 4698 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4699 break; 4700 case ISD::SSUBO: 4701 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4702 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4703 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4704 break; 4705 case ISD::USUBO: 4706 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4707 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4708 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4709 break; 4710 case ISD::UMULO: 4711 // We generate a UMUL_LOHI and then check if the high word is 0. 4712 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4713 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4714 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4715 LHS, RHS); 4716 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4717 DAG.getConstant(0, dl, MVT::i32)); 4718 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4719 break; 4720 case ISD::SMULO: 4721 // We generate a SMUL_LOHI and then check if all the bits of the high word 4722 // are the same as the sign bit of the low word. 4723 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4724 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4725 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4726 LHS, RHS); 4727 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4728 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4729 Value.getValue(0), 4730 DAG.getConstant(31, dl, MVT::i32))); 4731 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4732 break; 4733 } // switch (...) 4734 4735 return std::make_pair(Value, OverflowCmp); 4736 } 4737 4738 SDValue 4739 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4740 // Let legalize expand this if it isn't a legal type yet. 4741 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4742 return SDValue(); 4743 4744 SDValue Value, OverflowCmp; 4745 SDValue ARMcc; 4746 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4747 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4748 SDLoc dl(Op); 4749 // We use 0 and 1 as false and true values. 4750 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4751 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4752 EVT VT = Op.getValueType(); 4753 4754 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4755 ARMcc, CCR, OverflowCmp); 4756 4757 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4758 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4759 } 4760 4761 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4762 SelectionDAG &DAG) { 4763 SDLoc DL(BoolCarry); 4764 EVT CarryVT = BoolCarry.getValueType(); 4765 4766 // This converts the boolean value carry into the carry flag by doing 4767 // ARMISD::SUBC Carry, 1 4768 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4769 DAG.getVTList(CarryVT, MVT::i32), 4770 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4771 return Carry.getValue(1); 4772 } 4773 4774 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4775 SelectionDAG &DAG) { 4776 SDLoc DL(Flags); 4777 4778 // Now convert the carry flag into a boolean carry. We do this 4779 // using ARMISD:ADDE 0, 0, Carry 4780 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4781 DAG.getConstant(0, DL, MVT::i32), 4782 DAG.getConstant(0, DL, MVT::i32), Flags); 4783 } 4784 4785 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4786 SelectionDAG &DAG) const { 4787 // Let legalize expand this if it isn't a legal type yet. 4788 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4789 return SDValue(); 4790 4791 SDValue LHS = Op.getOperand(0); 4792 SDValue RHS = Op.getOperand(1); 4793 SDLoc dl(Op); 4794 4795 EVT VT = Op.getValueType(); 4796 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4797 SDValue Value; 4798 SDValue Overflow; 4799 switch (Op.getOpcode()) { 4800 default: 4801 llvm_unreachable("Unknown overflow instruction!"); 4802 case ISD::UADDO: 4803 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4804 // Convert the carry flag into a boolean value. 4805 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4806 break; 4807 case ISD::USUBO: { 4808 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4809 // Convert the carry flag into a boolean value. 4810 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4811 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4812 // value. So compute 1 - C. 4813 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4814 DAG.getConstant(1, dl, MVT::i32), Overflow); 4815 break; 4816 } 4817 } 4818 4819 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4820 } 4821 4822 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG, 4823 const ARMSubtarget *Subtarget) { 4824 EVT VT = Op.getValueType(); 4825 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 4826 return SDValue(); 4827 if (!VT.isSimple()) 4828 return SDValue(); 4829 4830 unsigned NewOpcode; 4831 bool IsAdd = Op->getOpcode() == ISD::SADDSAT; 4832 switch (VT.getSimpleVT().SimpleTy) { 4833 default: 4834 return SDValue(); 4835 case MVT::i8: 4836 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b; 4837 break; 4838 case MVT::i16: 4839 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b; 4840 break; 4841 } 4842 4843 SDLoc dl(Op); 4844 SDValue Add = 4845 DAG.getNode(NewOpcode, dl, MVT::i32, 4846 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32), 4847 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32)); 4848 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add); 4849 } 4850 4851 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4852 SDValue Cond = Op.getOperand(0); 4853 SDValue SelectTrue = Op.getOperand(1); 4854 SDValue SelectFalse = Op.getOperand(2); 4855 SDLoc dl(Op); 4856 unsigned Opc = Cond.getOpcode(); 4857 4858 if (Cond.getResNo() == 1 && 4859 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4860 Opc == ISD::USUBO)) { 4861 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4862 return SDValue(); 4863 4864 SDValue Value, OverflowCmp; 4865 SDValue ARMcc; 4866 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4867 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4868 EVT VT = Op.getValueType(); 4869 4870 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4871 OverflowCmp, DAG); 4872 } 4873 4874 // Convert: 4875 // 4876 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4877 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4878 // 4879 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4880 const ConstantSDNode *CMOVTrue = 4881 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4882 const ConstantSDNode *CMOVFalse = 4883 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4884 4885 if (CMOVTrue && CMOVFalse) { 4886 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4887 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4888 4889 SDValue True; 4890 SDValue False; 4891 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4892 True = SelectTrue; 4893 False = SelectFalse; 4894 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4895 True = SelectFalse; 4896 False = SelectTrue; 4897 } 4898 4899 if (True.getNode() && False.getNode()) { 4900 EVT VT = Op.getValueType(); 4901 SDValue ARMcc = Cond.getOperand(2); 4902 SDValue CCR = Cond.getOperand(3); 4903 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4904 assert(True.getValueType() == VT); 4905 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4906 } 4907 } 4908 } 4909 4910 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4911 // undefined bits before doing a full-word comparison with zero. 4912 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4913 DAG.getConstant(1, dl, Cond.getValueType())); 4914 4915 return DAG.getSelectCC(dl, Cond, 4916 DAG.getConstant(0, dl, Cond.getValueType()), 4917 SelectTrue, SelectFalse, ISD::SETNE); 4918 } 4919 4920 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4921 bool &swpCmpOps, bool &swpVselOps) { 4922 // Start by selecting the GE condition code for opcodes that return true for 4923 // 'equality' 4924 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4925 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4926 CondCode = ARMCC::GE; 4927 4928 // and GT for opcodes that return false for 'equality'. 4929 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4930 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4931 CondCode = ARMCC::GT; 4932 4933 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4934 // to swap the compare operands. 4935 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4936 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4937 swpCmpOps = true; 4938 4939 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4940 // If we have an unordered opcode, we need to swap the operands to the VSEL 4941 // instruction (effectively negating the condition). 4942 // 4943 // This also has the effect of swapping which one of 'less' or 'greater' 4944 // returns true, so we also swap the compare operands. It also switches 4945 // whether we return true for 'equality', so we compensate by picking the 4946 // opposite condition code to our original choice. 4947 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4948 CC == ISD::SETUGT) { 4949 swpCmpOps = !swpCmpOps; 4950 swpVselOps = !swpVselOps; 4951 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4952 } 4953 4954 // 'ordered' is 'anything but unordered', so use the VS condition code and 4955 // swap the VSEL operands. 4956 if (CC == ISD::SETO) { 4957 CondCode = ARMCC::VS; 4958 swpVselOps = true; 4959 } 4960 4961 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4962 // code and swap the VSEL operands. Also do this if we don't care about the 4963 // unordered case. 4964 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4965 CondCode = ARMCC::EQ; 4966 swpVselOps = true; 4967 } 4968 } 4969 4970 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4971 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4972 SDValue Cmp, SelectionDAG &DAG) const { 4973 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4974 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4975 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4976 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4977 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4978 4979 SDValue TrueLow = TrueVal.getValue(0); 4980 SDValue TrueHigh = TrueVal.getValue(1); 4981 SDValue FalseLow = FalseVal.getValue(0); 4982 SDValue FalseHigh = FalseVal.getValue(1); 4983 4984 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4985 ARMcc, CCR, Cmp); 4986 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4987 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4988 4989 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4990 } else { 4991 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4992 Cmp); 4993 } 4994 } 4995 4996 static bool isGTorGE(ISD::CondCode CC) { 4997 return CC == ISD::SETGT || CC == ISD::SETGE; 4998 } 4999 5000 static bool isLTorLE(ISD::CondCode CC) { 5001 return CC == ISD::SETLT || CC == ISD::SETLE; 5002 } 5003 5004 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 5005 // All of these conditions (and their <= and >= counterparts) will do: 5006 // x < k ? k : x 5007 // x > k ? x : k 5008 // k < x ? x : k 5009 // k > x ? k : x 5010 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 5011 const SDValue TrueVal, const SDValue FalseVal, 5012 const ISD::CondCode CC, const SDValue K) { 5013 return (isGTorGE(CC) && 5014 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 5015 (isLTorLE(CC) && 5016 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 5017 } 5018 5019 // Check if two chained conditionals could be converted into SSAT or USAT. 5020 // 5021 // SSAT can replace a set of two conditional selectors that bound a number to an 5022 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 5023 // 5024 // x < -k ? -k : (x > k ? k : x) 5025 // x < -k ? -k : (x < k ? x : k) 5026 // x > -k ? (x > k ? k : x) : -k 5027 // x < k ? (x < -k ? -k : x) : k 5028 // etc. 5029 // 5030 // LLVM canonicalizes these to either a min(max()) or a max(min()) 5031 // pattern. This function tries to match one of these and will return true 5032 // if successful. 5033 // 5034 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 5035 // a power of 2. 5036 // 5037 // It returns true if the conversion can be done, false otherwise. 5038 // Additionally, the variable is returned in parameter V, the constant in K and 5039 // usat is set to true if the conditional represents an unsigned saturation 5040 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 5041 uint64_t &K, bool &Usat) { 5042 SDValue V1 = Op.getOperand(0); 5043 SDValue K1 = Op.getOperand(1); 5044 SDValue TrueVal1 = Op.getOperand(2); 5045 SDValue FalseVal1 = Op.getOperand(3); 5046 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5047 5048 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 5049 if (Op2.getOpcode() != ISD::SELECT_CC) 5050 return false; 5051 5052 SDValue V2 = Op2.getOperand(0); 5053 SDValue K2 = Op2.getOperand(1); 5054 SDValue TrueVal2 = Op2.getOperand(2); 5055 SDValue FalseVal2 = Op2.getOperand(3); 5056 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 5057 5058 SDValue V1Tmp = V1; 5059 SDValue V2Tmp = V2; 5060 5061 if (V1.getOpcode() == ISD::SIGN_EXTEND_INREG && 5062 V2.getOpcode() == ISD::SIGN_EXTEND_INREG) { 5063 V1Tmp = V1.getOperand(0); 5064 V2Tmp = V2.getOperand(0); 5065 } 5066 5067 // Check that the registers and the constants match a max(min()) or min(max()) 5068 // pattern 5069 if (V1Tmp == TrueVal1 && V2Tmp == TrueVal2 && K1 == FalseVal1 && 5070 K2 == FalseVal2 && 5071 ((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2)))) { 5072 5073 // Check that the constant in the lower-bound check is 5074 // the opposite of the constant in the upper-bound check 5075 // in 1's complement. 5076 if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2)) 5077 return false; 5078 5079 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue(); 5080 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue(); 5081 int64_t PosVal = std::max(Val1, Val2); 5082 int64_t NegVal = std::min(Val1, Val2); 5083 5084 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) || 5085 !isPowerOf2_64(PosVal + 1)) 5086 return false; 5087 5088 // Handle the difference between USAT (unsigned) and SSAT (signed) 5089 // saturation 5090 if (Val1 == ~Val2) 5091 Usat = false; 5092 else if (NegVal == 0) 5093 Usat = true; 5094 else 5095 return false; 5096 5097 V = V2Tmp; 5098 // At this point, PosVal is guaranteed to be positive 5099 K = (uint64_t) PosVal; 5100 5101 return true; 5102 } 5103 return false; 5104 } 5105 5106 // Check if a condition of the type x < k ? k : x can be converted into a 5107 // bit operation instead of conditional moves. 5108 // Currently this is allowed given: 5109 // - The conditions and values match up 5110 // - k is 0 or -1 (all ones) 5111 // This function will not check the last condition, thats up to the caller 5112 // It returns true if the transformation can be made, and in such case 5113 // returns x in V, and k in SatK. 5114 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 5115 SDValue &SatK) 5116 { 5117 SDValue LHS = Op.getOperand(0); 5118 SDValue RHS = Op.getOperand(1); 5119 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5120 SDValue TrueVal = Op.getOperand(2); 5121 SDValue FalseVal = Op.getOperand(3); 5122 5123 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 5124 ? &RHS 5125 : nullptr; 5126 5127 // No constant operation in comparison, early out 5128 if (!K) 5129 return false; 5130 5131 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 5132 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 5133 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 5134 5135 // If the constant on left and right side, or variable on left and right, 5136 // does not match, early out 5137 if (*K != KTmp || V != VTmp) 5138 return false; 5139 5140 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 5141 SatK = *K; 5142 return true; 5143 } 5144 5145 return false; 5146 } 5147 5148 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 5149 if (VT == MVT::f32) 5150 return !Subtarget->hasVFP2Base(); 5151 if (VT == MVT::f64) 5152 return !Subtarget->hasFP64(); 5153 if (VT == MVT::f16) 5154 return !Subtarget->hasFullFP16(); 5155 return false; 5156 } 5157 5158 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 5159 EVT VT = Op.getValueType(); 5160 SDLoc dl(Op); 5161 5162 // Try to convert two saturating conditional selects into a single SSAT 5163 SDValue SatValue; 5164 uint64_t SatConstant; 5165 bool SatUSat; 5166 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 5167 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 5168 if (SatUSat) 5169 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 5170 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 5171 else 5172 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 5173 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 5174 } 5175 5176 // Try to convert expressions of the form x < k ? k : x (and similar forms) 5177 // into more efficient bit operations, which is possible when k is 0 or -1 5178 // On ARM and Thumb-2 which have flexible operand 2 this will result in 5179 // single instructions. On Thumb the shift and the bit operation will be two 5180 // instructions. 5181 // Only allow this transformation on full-width (32-bit) operations 5182 SDValue LowerSatConstant; 5183 if (VT == MVT::i32 && 5184 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 5185 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 5186 DAG.getConstant(31, dl, VT)); 5187 if (isNullConstant(LowerSatConstant)) { 5188 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 5189 DAG.getAllOnesConstant(dl, VT)); 5190 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 5191 } else if (isAllOnesConstant(LowerSatConstant)) 5192 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 5193 } 5194 5195 SDValue LHS = Op.getOperand(0); 5196 SDValue RHS = Op.getOperand(1); 5197 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5198 SDValue TrueVal = Op.getOperand(2); 5199 SDValue FalseVal = Op.getOperand(3); 5200 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal); 5201 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal); 5202 5203 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal && 5204 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) { 5205 unsigned TVal = CTVal->getZExtValue(); 5206 unsigned FVal = CFVal->getZExtValue(); 5207 unsigned Opcode = 0; 5208 5209 if (TVal == ~FVal) { 5210 Opcode = ARMISD::CSINV; 5211 } else if (TVal == ~FVal + 1) { 5212 Opcode = ARMISD::CSNEG; 5213 } else if (TVal + 1 == FVal) { 5214 Opcode = ARMISD::CSINC; 5215 } else if (TVal == FVal + 1) { 5216 Opcode = ARMISD::CSINC; 5217 std::swap(TrueVal, FalseVal); 5218 std::swap(TVal, FVal); 5219 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5220 } 5221 5222 if (Opcode) { 5223 // If one of the constants is cheaper than another, materialise the 5224 // cheaper one and let the csel generate the other. 5225 if (Opcode != ARMISD::CSINC && 5226 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) { 5227 std::swap(TrueVal, FalseVal); 5228 std::swap(TVal, FVal); 5229 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5230 } 5231 5232 // Attempt to use ZR checking TVal is 0, possibly inverting the condition 5233 // to get there. CSINC not is invertable like the other two (~(~a) == a, 5234 // -(-a) == a, but (a+1)+1 != a). 5235 if (FVal == 0 && Opcode != ARMISD::CSINC) { 5236 std::swap(TrueVal, FalseVal); 5237 std::swap(TVal, FVal); 5238 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5239 } 5240 if (TVal == 0) 5241 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32); 5242 5243 // Drops F's value because we can get it by inverting/negating TVal. 5244 FalseVal = TrueVal; 5245 5246 SDValue ARMcc; 5247 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5248 EVT VT = TrueVal.getValueType(); 5249 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp); 5250 } 5251 } 5252 5253 if (isUnsupportedFloatingType(LHS.getValueType())) { 5254 DAG.getTargetLoweringInfo().softenSetCCOperands( 5255 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5256 5257 // If softenSetCCOperands only returned one value, we should compare it to 5258 // zero. 5259 if (!RHS.getNode()) { 5260 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5261 CC = ISD::SETNE; 5262 } 5263 } 5264 5265 if (LHS.getValueType() == MVT::i32) { 5266 // Try to generate VSEL on ARMv8. 5267 // The VSEL instruction can't use all the usual ARM condition 5268 // codes: it only has two bits to select the condition code, so it's 5269 // constrained to use only GE, GT, VS and EQ. 5270 // 5271 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 5272 // swap the operands of the previous compare instruction (effectively 5273 // inverting the compare condition, swapping 'less' and 'greater') and 5274 // sometimes need to swap the operands to the VSEL (which inverts the 5275 // condition in the sense of firing whenever the previous condition didn't) 5276 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 5277 TrueVal.getValueType() == MVT::f32 || 5278 TrueVal.getValueType() == MVT::f64)) { 5279 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5280 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 5281 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 5282 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5283 std::swap(TrueVal, FalseVal); 5284 } 5285 } 5286 5287 SDValue ARMcc; 5288 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5289 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5290 // Choose GE over PL, which vsel does now support 5291 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 5292 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 5293 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5294 } 5295 5296 ARMCC::CondCodes CondCode, CondCode2; 5297 FPCCToARMCC(CC, CondCode, CondCode2); 5298 5299 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 5300 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 5301 // must use VSEL (limited condition codes), due to not having conditional f16 5302 // moves. 5303 if (Subtarget->hasFPARMv8Base() && 5304 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 5305 (TrueVal.getValueType() == MVT::f16 || 5306 TrueVal.getValueType() == MVT::f32 || 5307 TrueVal.getValueType() == MVT::f64)) { 5308 bool swpCmpOps = false; 5309 bool swpVselOps = false; 5310 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 5311 5312 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 5313 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 5314 if (swpCmpOps) 5315 std::swap(LHS, RHS); 5316 if (swpVselOps) 5317 std::swap(TrueVal, FalseVal); 5318 } 5319 } 5320 5321 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5322 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5323 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5324 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 5325 if (CondCode2 != ARMCC::AL) { 5326 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 5327 // FIXME: Needs another CMP because flag can have but one use. 5328 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 5329 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 5330 } 5331 return Result; 5332 } 5333 5334 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 5335 /// to morph to an integer compare sequence. 5336 static bool canChangeToInt(SDValue Op, bool &SeenZero, 5337 const ARMSubtarget *Subtarget) { 5338 SDNode *N = Op.getNode(); 5339 if (!N->hasOneUse()) 5340 // Otherwise it requires moving the value from fp to integer registers. 5341 return false; 5342 if (!N->getNumValues()) 5343 return false; 5344 EVT VT = Op.getValueType(); 5345 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 5346 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 5347 // vmrs are very slow, e.g. cortex-a8. 5348 return false; 5349 5350 if (isFloatingPointZero(Op)) { 5351 SeenZero = true; 5352 return true; 5353 } 5354 return ISD::isNormalLoad(N); 5355 } 5356 5357 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 5358 if (isFloatingPointZero(Op)) 5359 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 5360 5361 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 5362 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 5363 Ld->getPointerInfo(), Ld->getAlignment(), 5364 Ld->getMemOperand()->getFlags()); 5365 5366 llvm_unreachable("Unknown VFP cmp argument!"); 5367 } 5368 5369 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 5370 SDValue &RetVal1, SDValue &RetVal2) { 5371 SDLoc dl(Op); 5372 5373 if (isFloatingPointZero(Op)) { 5374 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 5375 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 5376 return; 5377 } 5378 5379 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 5380 SDValue Ptr = Ld->getBasePtr(); 5381 RetVal1 = 5382 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 5383 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 5384 5385 EVT PtrType = Ptr.getValueType(); 5386 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 5387 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 5388 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 5389 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 5390 Ld->getPointerInfo().getWithOffset(4), NewAlign, 5391 Ld->getMemOperand()->getFlags()); 5392 return; 5393 } 5394 5395 llvm_unreachable("Unknown VFP cmp argument!"); 5396 } 5397 5398 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 5399 /// f32 and even f64 comparisons to integer ones. 5400 SDValue 5401 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 5402 SDValue Chain = Op.getOperand(0); 5403 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5404 SDValue LHS = Op.getOperand(2); 5405 SDValue RHS = Op.getOperand(3); 5406 SDValue Dest = Op.getOperand(4); 5407 SDLoc dl(Op); 5408 5409 bool LHSSeenZero = false; 5410 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 5411 bool RHSSeenZero = false; 5412 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 5413 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 5414 // If unsafe fp math optimization is enabled and there are no other uses of 5415 // the CMP operands, and the condition code is EQ or NE, we can optimize it 5416 // to an integer comparison. 5417 if (CC == ISD::SETOEQ) 5418 CC = ISD::SETEQ; 5419 else if (CC == ISD::SETUNE) 5420 CC = ISD::SETNE; 5421 5422 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5423 SDValue ARMcc; 5424 if (LHS.getValueType() == MVT::f32) { 5425 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5426 bitcastf32Toi32(LHS, DAG), Mask); 5427 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 5428 bitcastf32Toi32(RHS, DAG), Mask); 5429 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5430 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5431 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5432 Chain, Dest, ARMcc, CCR, Cmp); 5433 } 5434 5435 SDValue LHS1, LHS2; 5436 SDValue RHS1, RHS2; 5437 expandf64Toi32(LHS, DAG, LHS1, LHS2); 5438 expandf64Toi32(RHS, DAG, RHS1, RHS2); 5439 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 5440 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 5441 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5442 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5443 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5444 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 5445 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 5446 } 5447 5448 return SDValue(); 5449 } 5450 5451 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 5452 SDValue Chain = Op.getOperand(0); 5453 SDValue Cond = Op.getOperand(1); 5454 SDValue Dest = Op.getOperand(2); 5455 SDLoc dl(Op); 5456 5457 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5458 // instruction. 5459 unsigned Opc = Cond.getOpcode(); 5460 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5461 !Subtarget->isThumb1Only(); 5462 if (Cond.getResNo() == 1 && 5463 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5464 Opc == ISD::USUBO || OptimizeMul)) { 5465 // Only lower legal XALUO ops. 5466 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 5467 return SDValue(); 5468 5469 // The actual operation with overflow check. 5470 SDValue Value, OverflowCmp; 5471 SDValue ARMcc; 5472 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 5473 5474 // Reverse the condition code. 5475 ARMCC::CondCodes CondCode = 5476 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5477 CondCode = ARMCC::getOppositeCondition(CondCode); 5478 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5479 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5480 5481 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5482 OverflowCmp); 5483 } 5484 5485 return SDValue(); 5486 } 5487 5488 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5489 SDValue Chain = Op.getOperand(0); 5490 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5491 SDValue LHS = Op.getOperand(2); 5492 SDValue RHS = Op.getOperand(3); 5493 SDValue Dest = Op.getOperand(4); 5494 SDLoc dl(Op); 5495 5496 if (isUnsupportedFloatingType(LHS.getValueType())) { 5497 DAG.getTargetLoweringInfo().softenSetCCOperands( 5498 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS); 5499 5500 // If softenSetCCOperands only returned one value, we should compare it to 5501 // zero. 5502 if (!RHS.getNode()) { 5503 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5504 CC = ISD::SETNE; 5505 } 5506 } 5507 5508 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5509 // instruction. 5510 unsigned Opc = LHS.getOpcode(); 5511 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5512 !Subtarget->isThumb1Only(); 5513 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5514 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5515 Opc == ISD::USUBO || OptimizeMul) && 5516 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5517 // Only lower legal XALUO ops. 5518 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5519 return SDValue(); 5520 5521 // The actual operation with overflow check. 5522 SDValue Value, OverflowCmp; 5523 SDValue ARMcc; 5524 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5525 5526 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5527 // Reverse the condition code. 5528 ARMCC::CondCodes CondCode = 5529 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5530 CondCode = ARMCC::getOppositeCondition(CondCode); 5531 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5532 } 5533 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5534 5535 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5536 OverflowCmp); 5537 } 5538 5539 if (LHS.getValueType() == MVT::i32) { 5540 SDValue ARMcc; 5541 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5542 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5543 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5544 Chain, Dest, ARMcc, CCR, Cmp); 5545 } 5546 5547 if (getTargetMachine().Options.UnsafeFPMath && 5548 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5549 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5550 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5551 return Result; 5552 } 5553 5554 ARMCC::CondCodes CondCode, CondCode2; 5555 FPCCToARMCC(CC, CondCode, CondCode2); 5556 5557 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5558 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 5559 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5560 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5561 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5562 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5563 if (CondCode2 != ARMCC::AL) { 5564 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5565 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5566 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5567 } 5568 return Res; 5569 } 5570 5571 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5572 SDValue Chain = Op.getOperand(0); 5573 SDValue Table = Op.getOperand(1); 5574 SDValue Index = Op.getOperand(2); 5575 SDLoc dl(Op); 5576 5577 EVT PTy = getPointerTy(DAG.getDataLayout()); 5578 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5579 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5580 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5581 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5582 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5583 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5584 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5585 // which does another jump to the destination. This also makes it easier 5586 // to translate it to TBB / TBH later (Thumb2 only). 5587 // FIXME: This might not work if the function is extremely large. 5588 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5589 Addr, Op.getOperand(2), JTI); 5590 } 5591 if (isPositionIndependent() || Subtarget->isROPI()) { 5592 Addr = 5593 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5594 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5595 Chain = Addr.getValue(1); 5596 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5597 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5598 } else { 5599 Addr = 5600 DAG.getLoad(PTy, dl, Chain, Addr, 5601 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5602 Chain = Addr.getValue(1); 5603 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5604 } 5605 } 5606 5607 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5608 EVT VT = Op.getValueType(); 5609 SDLoc dl(Op); 5610 5611 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5612 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5613 return Op; 5614 return DAG.UnrollVectorOp(Op.getNode()); 5615 } 5616 5617 const bool HasFullFP16 = 5618 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5619 5620 EVT NewTy; 5621 const EVT OpTy = Op.getOperand(0).getValueType(); 5622 if (OpTy == MVT::v4f32) 5623 NewTy = MVT::v4i32; 5624 else if (OpTy == MVT::v4f16 && HasFullFP16) 5625 NewTy = MVT::v4i16; 5626 else if (OpTy == MVT::v8f16 && HasFullFP16) 5627 NewTy = MVT::v8i16; 5628 else 5629 llvm_unreachable("Invalid type for custom lowering!"); 5630 5631 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5632 return DAG.UnrollVectorOp(Op.getNode()); 5633 5634 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5635 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5636 } 5637 5638 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5639 EVT VT = Op.getValueType(); 5640 if (VT.isVector()) 5641 return LowerVectorFP_TO_INT(Op, DAG); 5642 5643 bool IsStrict = Op->isStrictFPOpcode(); 5644 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 5645 5646 if (isUnsupportedFloatingType(SrcVal.getValueType())) { 5647 RTLIB::Libcall LC; 5648 if (Op.getOpcode() == ISD::FP_TO_SINT || 5649 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 5650 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), 5651 Op.getValueType()); 5652 else 5653 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), 5654 Op.getValueType()); 5655 SDLoc Loc(Op); 5656 MakeLibCallOptions CallOptions; 5657 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 5658 SDValue Result; 5659 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 5660 CallOptions, Loc, Chain); 5661 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 5662 } 5663 5664 // FIXME: Remove this when we have strict fp instruction selection patterns 5665 if (IsStrict) { 5666 SDLoc Loc(Op); 5667 SDValue Result = 5668 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT 5669 : ISD::FP_TO_UINT, 5670 Loc, Op.getValueType(), SrcVal); 5671 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 5672 } 5673 5674 return Op; 5675 } 5676 5677 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5678 EVT VT = Op.getValueType(); 5679 SDLoc dl(Op); 5680 5681 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5682 if (VT.getVectorElementType() == MVT::f32) 5683 return Op; 5684 return DAG.UnrollVectorOp(Op.getNode()); 5685 } 5686 5687 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5688 Op.getOperand(0).getValueType() == MVT::v8i16) && 5689 "Invalid type for custom lowering!"); 5690 5691 const bool HasFullFP16 = 5692 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5693 5694 EVT DestVecType; 5695 if (VT == MVT::v4f32) 5696 DestVecType = MVT::v4i32; 5697 else if (VT == MVT::v4f16 && HasFullFP16) 5698 DestVecType = MVT::v4i16; 5699 else if (VT == MVT::v8f16 && HasFullFP16) 5700 DestVecType = MVT::v8i16; 5701 else 5702 return DAG.UnrollVectorOp(Op.getNode()); 5703 5704 unsigned CastOpc; 5705 unsigned Opc; 5706 switch (Op.getOpcode()) { 5707 default: llvm_unreachable("Invalid opcode!"); 5708 case ISD::SINT_TO_FP: 5709 CastOpc = ISD::SIGN_EXTEND; 5710 Opc = ISD::SINT_TO_FP; 5711 break; 5712 case ISD::UINT_TO_FP: 5713 CastOpc = ISD::ZERO_EXTEND; 5714 Opc = ISD::UINT_TO_FP; 5715 break; 5716 } 5717 5718 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5719 return DAG.getNode(Opc, dl, VT, Op); 5720 } 5721 5722 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5723 EVT VT = Op.getValueType(); 5724 if (VT.isVector()) 5725 return LowerVectorINT_TO_FP(Op, DAG); 5726 if (isUnsupportedFloatingType(VT)) { 5727 RTLIB::Libcall LC; 5728 if (Op.getOpcode() == ISD::SINT_TO_FP) 5729 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5730 Op.getValueType()); 5731 else 5732 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5733 Op.getValueType()); 5734 MakeLibCallOptions CallOptions; 5735 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5736 CallOptions, SDLoc(Op)).first; 5737 } 5738 5739 return Op; 5740 } 5741 5742 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5743 // Implement fcopysign with a fabs and a conditional fneg. 5744 SDValue Tmp0 = Op.getOperand(0); 5745 SDValue Tmp1 = Op.getOperand(1); 5746 SDLoc dl(Op); 5747 EVT VT = Op.getValueType(); 5748 EVT SrcVT = Tmp1.getValueType(); 5749 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5750 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5751 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5752 5753 if (UseNEON) { 5754 // Use VBSL to copy the sign bit. 5755 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5756 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5757 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5758 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5759 if (VT == MVT::f64) 5760 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5761 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5762 DAG.getConstant(32, dl, MVT::i32)); 5763 else /*if (VT == MVT::f32)*/ 5764 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5765 if (SrcVT == MVT::f32) { 5766 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5767 if (VT == MVT::f64) 5768 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5769 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5770 DAG.getConstant(32, dl, MVT::i32)); 5771 } else if (VT == MVT::f32) 5772 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5773 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5774 DAG.getConstant(32, dl, MVT::i32)); 5775 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5776 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5777 5778 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5779 dl, MVT::i32); 5780 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5781 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5782 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5783 5784 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5785 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5786 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5787 if (VT == MVT::f32) { 5788 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5789 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5790 DAG.getConstant(0, dl, MVT::i32)); 5791 } else { 5792 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5793 } 5794 5795 return Res; 5796 } 5797 5798 // Bitcast operand 1 to i32. 5799 if (SrcVT == MVT::f64) 5800 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5801 Tmp1).getValue(1); 5802 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5803 5804 // Or in the signbit with integer operations. 5805 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5806 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5807 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5808 if (VT == MVT::f32) { 5809 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5810 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5811 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5812 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5813 } 5814 5815 // f64: Or the high part with signbit and then combine two parts. 5816 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5817 Tmp0); 5818 SDValue Lo = Tmp0.getValue(0); 5819 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5820 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5821 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5822 } 5823 5824 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5825 MachineFunction &MF = DAG.getMachineFunction(); 5826 MachineFrameInfo &MFI = MF.getFrameInfo(); 5827 MFI.setReturnAddressIsTaken(true); 5828 5829 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5830 return SDValue(); 5831 5832 EVT VT = Op.getValueType(); 5833 SDLoc dl(Op); 5834 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5835 if (Depth) { 5836 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5837 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5838 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5839 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5840 MachinePointerInfo()); 5841 } 5842 5843 // Return LR, which contains the return address. Mark it an implicit live-in. 5844 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5845 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5846 } 5847 5848 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5849 const ARMBaseRegisterInfo &ARI = 5850 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5851 MachineFunction &MF = DAG.getMachineFunction(); 5852 MachineFrameInfo &MFI = MF.getFrameInfo(); 5853 MFI.setFrameAddressIsTaken(true); 5854 5855 EVT VT = Op.getValueType(); 5856 SDLoc dl(Op); // FIXME probably not meaningful 5857 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5858 Register FrameReg = ARI.getFrameRegister(MF); 5859 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5860 while (Depth--) 5861 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5862 MachinePointerInfo()); 5863 return FrameAddr; 5864 } 5865 5866 // FIXME? Maybe this could be a TableGen attribute on some registers and 5867 // this table could be generated automatically from RegInfo. 5868 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT, 5869 const MachineFunction &MF) const { 5870 Register Reg = StringSwitch<unsigned>(RegName) 5871 .Case("sp", ARM::SP) 5872 .Default(0); 5873 if (Reg) 5874 return Reg; 5875 report_fatal_error(Twine("Invalid register name \"" 5876 + StringRef(RegName) + "\".")); 5877 } 5878 5879 // Result is 64 bit value so split into two 32 bit values and return as a 5880 // pair of values. 5881 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5882 SelectionDAG &DAG) { 5883 SDLoc DL(N); 5884 5885 // This function is only supposed to be called for i64 type destination. 5886 assert(N->getValueType(0) == MVT::i64 5887 && "ExpandREAD_REGISTER called for non-i64 type result."); 5888 5889 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5890 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5891 N->getOperand(0), 5892 N->getOperand(1)); 5893 5894 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5895 Read.getValue(1))); 5896 Results.push_back(Read.getOperand(0)); 5897 } 5898 5899 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5900 /// When \p DstVT, the destination type of \p BC, is on the vector 5901 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5902 /// it might be possible to combine them, such that everything stays on the 5903 /// vector register bank. 5904 /// \p return The node that would replace \p BT, if the combine 5905 /// is possible. 5906 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5907 SelectionDAG &DAG) { 5908 SDValue Op = BC->getOperand(0); 5909 EVT DstVT = BC->getValueType(0); 5910 5911 // The only vector instruction that can produce a scalar (remember, 5912 // since the bitcast was about to be turned into VMOVDRR, the source 5913 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5914 // Moreover, we can do this combine only if there is one use. 5915 // Finally, if the destination type is not a vector, there is not 5916 // much point on forcing everything on the vector bank. 5917 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5918 !Op.hasOneUse()) 5919 return SDValue(); 5920 5921 // If the index is not constant, we will introduce an additional 5922 // multiply that will stick. 5923 // Give up in that case. 5924 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5925 if (!Index) 5926 return SDValue(); 5927 unsigned DstNumElt = DstVT.getVectorNumElements(); 5928 5929 // Compute the new index. 5930 const APInt &APIntIndex = Index->getAPIntValue(); 5931 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5932 NewIndex *= APIntIndex; 5933 // Check if the new constant index fits into i32. 5934 if (NewIndex.getBitWidth() > 32) 5935 return SDValue(); 5936 5937 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5938 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5939 SDLoc dl(Op); 5940 SDValue ExtractSrc = Op.getOperand(0); 5941 EVT VecVT = EVT::getVectorVT( 5942 *DAG.getContext(), DstVT.getScalarType(), 5943 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5944 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5945 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5946 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5947 } 5948 5949 /// ExpandBITCAST - If the target supports VFP, this function is called to 5950 /// expand a bit convert where either the source or destination type is i64 to 5951 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5952 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5953 /// vectors), since the legalizer won't know what to do with that. 5954 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5955 const ARMSubtarget *Subtarget) const { 5956 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5957 SDLoc dl(N); 5958 SDValue Op = N->getOperand(0); 5959 5960 // This function is only supposed to be called for i16 and i64 types, either 5961 // as the source or destination of the bit convert. 5962 EVT SrcVT = Op.getValueType(); 5963 EVT DstVT = N->getValueType(0); 5964 5965 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) && 5966 (DstVT == MVT::f16 || DstVT == MVT::bf16)) 5967 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(), 5968 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op)); 5969 5970 if ((DstVT == MVT::i16 || DstVT == MVT::i32) && 5971 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) 5972 return DAG.getNode( 5973 ISD::TRUNCATE, SDLoc(N), DstVT, 5974 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op)); 5975 5976 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5977 return SDValue(); 5978 5979 // Turn i64->f64 into VMOVDRR. 5980 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5981 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5982 // if we can combine the bitcast with its source. 5983 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5984 return Val; 5985 5986 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5987 DAG.getConstant(0, dl, MVT::i32)); 5988 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5989 DAG.getConstant(1, dl, MVT::i32)); 5990 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5991 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5992 } 5993 5994 // Turn f64->i64 into VMOVRRD. 5995 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5996 SDValue Cvt; 5997 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5998 SrcVT.getVectorNumElements() > 1) 5999 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 6000 DAG.getVTList(MVT::i32, MVT::i32), 6001 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 6002 else 6003 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 6004 DAG.getVTList(MVT::i32, MVT::i32), Op); 6005 // Merge the pieces into a single i64 value. 6006 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 6007 } 6008 6009 return SDValue(); 6010 } 6011 6012 /// getZeroVector - Returns a vector of specified type with all zero elements. 6013 /// Zero vectors are used to represent vector negation and in those cases 6014 /// will be implemented with the NEON VNEG instruction. However, VNEG does 6015 /// not support i64 elements, so sometimes the zero vectors will need to be 6016 /// explicitly constructed. Regardless, use a canonical VMOV to create the 6017 /// zero vector. 6018 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 6019 assert(VT.isVector() && "Expected a vector type"); 6020 // The canonical modified immediate encoding of a zero vector is....0! 6021 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 6022 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 6023 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 6024 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6025 } 6026 6027 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 6028 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6029 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 6030 SelectionDAG &DAG) const { 6031 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6032 EVT VT = Op.getValueType(); 6033 unsigned VTBits = VT.getSizeInBits(); 6034 SDLoc dl(Op); 6035 SDValue ShOpLo = Op.getOperand(0); 6036 SDValue ShOpHi = Op.getOperand(1); 6037 SDValue ShAmt = Op.getOperand(2); 6038 SDValue ARMcc; 6039 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6040 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 6041 6042 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 6043 6044 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6045 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6046 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 6047 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6048 DAG.getConstant(VTBits, dl, MVT::i32)); 6049 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 6050 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6051 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 6052 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6053 ISD::SETGE, ARMcc, DAG, dl); 6054 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 6055 ARMcc, CCR, CmpLo); 6056 6057 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 6058 SDValue HiBigShift = Opc == ISD::SRA 6059 ? DAG.getNode(Opc, dl, VT, ShOpHi, 6060 DAG.getConstant(VTBits - 1, dl, VT)) 6061 : DAG.getConstant(0, dl, VT); 6062 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6063 ISD::SETGE, ARMcc, DAG, dl); 6064 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6065 ARMcc, CCR, CmpHi); 6066 6067 SDValue Ops[2] = { Lo, Hi }; 6068 return DAG.getMergeValues(Ops, dl); 6069 } 6070 6071 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 6072 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 6073 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 6074 SelectionDAG &DAG) const { 6075 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6076 EVT VT = Op.getValueType(); 6077 unsigned VTBits = VT.getSizeInBits(); 6078 SDLoc dl(Op); 6079 SDValue ShOpLo = Op.getOperand(0); 6080 SDValue ShOpHi = Op.getOperand(1); 6081 SDValue ShAmt = Op.getOperand(2); 6082 SDValue ARMcc; 6083 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6084 6085 assert(Op.getOpcode() == ISD::SHL_PARTS); 6086 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6087 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 6088 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 6089 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 6090 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 6091 6092 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 6093 DAG.getConstant(VTBits, dl, MVT::i32)); 6094 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 6095 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6096 ISD::SETGE, ARMcc, DAG, dl); 6097 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 6098 ARMcc, CCR, CmpHi); 6099 6100 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 6101 ISD::SETGE, ARMcc, DAG, dl); 6102 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6103 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 6104 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 6105 6106 SDValue Ops[2] = { Lo, Hi }; 6107 return DAG.getMergeValues(Ops, dl); 6108 } 6109 6110 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 6111 SelectionDAG &DAG) const { 6112 // The rounding mode is in bits 23:22 of the FPSCR. 6113 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 6114 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 6115 // so that the shift + and get folded into a bitfield extract. 6116 SDLoc dl(Op); 6117 SDValue Chain = Op.getOperand(0); 6118 SDValue Ops[] = {Chain, 6119 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)}; 6120 6121 SDValue FPSCR = 6122 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops); 6123 Chain = FPSCR.getValue(1); 6124 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 6125 DAG.getConstant(1U << 22, dl, MVT::i32)); 6126 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 6127 DAG.getConstant(22, dl, MVT::i32)); 6128 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 6129 DAG.getConstant(3, dl, MVT::i32)); 6130 return DAG.getMergeValues({And, Chain}, dl); 6131 } 6132 6133 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 6134 const ARMSubtarget *ST) { 6135 SDLoc dl(N); 6136 EVT VT = N->getValueType(0); 6137 if (VT.isVector() && ST->hasNEON()) { 6138 6139 // Compute the least significant set bit: LSB = X & -X 6140 SDValue X = N->getOperand(0); 6141 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 6142 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 6143 6144 EVT ElemTy = VT.getVectorElementType(); 6145 6146 if (ElemTy == MVT::i8) { 6147 // Compute with: cttz(x) = ctpop(lsb - 1) 6148 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6149 DAG.getTargetConstant(1, dl, ElemTy)); 6150 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6151 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6152 } 6153 6154 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 6155 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 6156 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 6157 unsigned NumBits = ElemTy.getSizeInBits(); 6158 SDValue WidthMinus1 = 6159 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6160 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 6161 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 6162 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 6163 } 6164 6165 // Compute with: cttz(x) = ctpop(lsb - 1) 6166 6167 // Compute LSB - 1. 6168 SDValue Bits; 6169 if (ElemTy == MVT::i64) { 6170 // Load constant 0xffff'ffff'ffff'ffff to register. 6171 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6172 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 6173 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 6174 } else { 6175 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 6176 DAG.getTargetConstant(1, dl, ElemTy)); 6177 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 6178 } 6179 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 6180 } 6181 6182 if (!ST->hasV6T2Ops()) 6183 return SDValue(); 6184 6185 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 6186 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 6187 } 6188 6189 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 6190 const ARMSubtarget *ST) { 6191 EVT VT = N->getValueType(0); 6192 SDLoc DL(N); 6193 6194 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 6195 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6196 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6197 "Unexpected type for custom ctpop lowering"); 6198 6199 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6200 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6201 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 6202 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 6203 6204 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6205 unsigned EltSize = 8; 6206 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6207 while (EltSize != VT.getScalarSizeInBits()) { 6208 SmallVector<SDValue, 8> Ops; 6209 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 6210 TLI.getPointerTy(DAG.getDataLayout()))); 6211 Ops.push_back(Res); 6212 6213 EltSize *= 2; 6214 NumElts /= 2; 6215 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6216 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 6217 } 6218 6219 return Res; 6220 } 6221 6222 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 6223 /// operand of a vector shift operation, where all the elements of the 6224 /// build_vector must have the same constant integer value. 6225 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6226 // Ignore bit_converts. 6227 while (Op.getOpcode() == ISD::BITCAST) 6228 Op = Op.getOperand(0); 6229 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6230 APInt SplatBits, SplatUndef; 6231 unsigned SplatBitSize; 6232 bool HasAnyUndefs; 6233 if (!BVN || 6234 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 6235 ElementBits) || 6236 SplatBitSize > ElementBits) 6237 return false; 6238 Cnt = SplatBits.getSExtValue(); 6239 return true; 6240 } 6241 6242 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6243 /// operand of a vector shift left operation. That value must be in the range: 6244 /// 0 <= Value < ElementBits for a left shift; or 6245 /// 0 <= Value <= ElementBits for a long left shift. 6246 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6247 assert(VT.isVector() && "vector shift count is not a vector type"); 6248 int64_t ElementBits = VT.getScalarSizeInBits(); 6249 if (!getVShiftImm(Op, ElementBits, Cnt)) 6250 return false; 6251 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6252 } 6253 6254 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6255 /// operand of a vector shift right operation. For a shift opcode, the value 6256 /// is positive, but for an intrinsic the value count must be negative. The 6257 /// absolute value must be in the range: 6258 /// 1 <= |Value| <= ElementBits for a right shift; or 6259 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 6260 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 6261 int64_t &Cnt) { 6262 assert(VT.isVector() && "vector shift count is not a vector type"); 6263 int64_t ElementBits = VT.getScalarSizeInBits(); 6264 if (!getVShiftImm(Op, ElementBits, Cnt)) 6265 return false; 6266 if (!isIntrinsic) 6267 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6268 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 6269 Cnt = -Cnt; 6270 return true; 6271 } 6272 return false; 6273 } 6274 6275 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 6276 const ARMSubtarget *ST) { 6277 EVT VT = N->getValueType(0); 6278 SDLoc dl(N); 6279 int64_t Cnt; 6280 6281 if (!VT.isVector()) 6282 return SDValue(); 6283 6284 // We essentially have two forms here. Shift by an immediate and shift by a 6285 // vector register (there are also shift by a gpr, but that is just handled 6286 // with a tablegen pattern). We cannot easily match shift by an immediate in 6287 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 6288 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 6289 // signed or unsigned, and a negative shift indicates a shift right). 6290 if (N->getOpcode() == ISD::SHL) { 6291 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 6292 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 6293 DAG.getConstant(Cnt, dl, MVT::i32)); 6294 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 6295 N->getOperand(1)); 6296 } 6297 6298 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 6299 "unexpected vector shift opcode"); 6300 6301 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 6302 unsigned VShiftOpc = 6303 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 6304 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 6305 DAG.getConstant(Cnt, dl, MVT::i32)); 6306 } 6307 6308 // Other right shifts we don't have operations for (we use a shift left by a 6309 // negative number). 6310 EVT ShiftVT = N->getOperand(1).getValueType(); 6311 SDValue NegatedCount = DAG.getNode( 6312 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 6313 unsigned VShiftOpc = 6314 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 6315 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 6316 } 6317 6318 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 6319 const ARMSubtarget *ST) { 6320 EVT VT = N->getValueType(0); 6321 SDLoc dl(N); 6322 6323 // We can get here for a node like i32 = ISD::SHL i32, i64 6324 if (VT != MVT::i64) 6325 return SDValue(); 6326 6327 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 6328 N->getOpcode() == ISD::SHL) && 6329 "Unknown shift to lower!"); 6330 6331 unsigned ShOpc = N->getOpcode(); 6332 if (ST->hasMVEIntegerOps()) { 6333 SDValue ShAmt = N->getOperand(1); 6334 unsigned ShPartsOpc = ARMISD::LSLL; 6335 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 6336 6337 // If the shift amount is greater than 32 or has a greater bitwidth than 64 6338 // then do the default optimisation 6339 if (ShAmt->getValueType(0).getSizeInBits() > 64 || 6340 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32))) 6341 return SDValue(); 6342 6343 // Extract the lower 32 bits of the shift amount if it's not an i32 6344 if (ShAmt->getValueType(0) != MVT::i32) 6345 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32); 6346 6347 if (ShOpc == ISD::SRL) { 6348 if (!Con) 6349 // There is no t2LSRLr instruction so negate and perform an lsll if the 6350 // shift amount is in a register, emulating a right shift. 6351 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 6352 DAG.getConstant(0, dl, MVT::i32), ShAmt); 6353 else 6354 // Else generate an lsrl on the immediate shift amount 6355 ShPartsOpc = ARMISD::LSRL; 6356 } else if (ShOpc == ISD::SRA) 6357 ShPartsOpc = ARMISD::ASRL; 6358 6359 // Lower 32 bits of the destination/source 6360 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6361 DAG.getConstant(0, dl, MVT::i32)); 6362 // Upper 32 bits of the destination/source 6363 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6364 DAG.getConstant(1, dl, MVT::i32)); 6365 6366 // Generate the shift operation as computed above 6367 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 6368 ShAmt); 6369 // The upper 32 bits come from the second return value of lsll 6370 Hi = SDValue(Lo.getNode(), 1); 6371 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6372 } 6373 6374 // We only lower SRA, SRL of 1 here, all others use generic lowering. 6375 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 6376 return SDValue(); 6377 6378 // If we are in thumb mode, we don't have RRX. 6379 if (ST->isThumb1Only()) 6380 return SDValue(); 6381 6382 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 6383 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6384 DAG.getConstant(0, dl, MVT::i32)); 6385 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 6386 DAG.getConstant(1, dl, MVT::i32)); 6387 6388 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 6389 // captures the result into a carry flag. 6390 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 6391 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 6392 6393 // The low part is an ARMISD::RRX operand, which shifts the carry in. 6394 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 6395 6396 // Merge the pieces into a single i64 value. 6397 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6398 } 6399 6400 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 6401 const ARMSubtarget *ST) { 6402 bool Invert = false; 6403 bool Swap = false; 6404 unsigned Opc = ARMCC::AL; 6405 6406 SDValue Op0 = Op.getOperand(0); 6407 SDValue Op1 = Op.getOperand(1); 6408 SDValue CC = Op.getOperand(2); 6409 EVT VT = Op.getValueType(); 6410 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 6411 SDLoc dl(Op); 6412 6413 EVT CmpVT; 6414 if (ST->hasNEON()) 6415 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 6416 else { 6417 assert(ST->hasMVEIntegerOps() && 6418 "No hardware support for integer vector comparison!"); 6419 6420 if (Op.getValueType().getVectorElementType() != MVT::i1) 6421 return SDValue(); 6422 6423 // Make sure we expand floating point setcc to scalar if we do not have 6424 // mve.fp, so that we can handle them from there. 6425 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 6426 return SDValue(); 6427 6428 CmpVT = VT; 6429 } 6430 6431 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 6432 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 6433 // Special-case integer 64-bit equality comparisons. They aren't legal, 6434 // but they can be lowered with a few vector instructions. 6435 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 6436 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 6437 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 6438 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 6439 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 6440 DAG.getCondCode(ISD::SETEQ)); 6441 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 6442 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 6443 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 6444 if (SetCCOpcode == ISD::SETNE) 6445 Merged = DAG.getNOT(dl, Merged, CmpVT); 6446 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6447 return Merged; 6448 } 6449 6450 if (CmpVT.getVectorElementType() == MVT::i64) 6451 // 64-bit comparisons are not legal in general. 6452 return SDValue(); 6453 6454 if (Op1.getValueType().isFloatingPoint()) { 6455 switch (SetCCOpcode) { 6456 default: llvm_unreachable("Illegal FP comparison"); 6457 case ISD::SETUNE: 6458 case ISD::SETNE: 6459 if (ST->hasMVEFloatOps()) { 6460 Opc = ARMCC::NE; break; 6461 } else { 6462 Invert = true; LLVM_FALLTHROUGH; 6463 } 6464 case ISD::SETOEQ: 6465 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6466 case ISD::SETOLT: 6467 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6468 case ISD::SETOGT: 6469 case ISD::SETGT: Opc = ARMCC::GT; break; 6470 case ISD::SETOLE: 6471 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6472 case ISD::SETOGE: 6473 case ISD::SETGE: Opc = ARMCC::GE; break; 6474 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6475 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6476 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6477 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6478 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6479 case ISD::SETONE: { 6480 // Expand this to (OLT | OGT). 6481 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6482 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6483 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6484 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6485 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6486 if (Invert) 6487 Result = DAG.getNOT(dl, Result, VT); 6488 return Result; 6489 } 6490 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6491 case ISD::SETO: { 6492 // Expand this to (OLT | OGE). 6493 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6494 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6495 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6496 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6497 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6498 if (Invert) 6499 Result = DAG.getNOT(dl, Result, VT); 6500 return Result; 6501 } 6502 } 6503 } else { 6504 // Integer comparisons. 6505 switch (SetCCOpcode) { 6506 default: llvm_unreachable("Illegal integer comparison"); 6507 case ISD::SETNE: 6508 if (ST->hasMVEIntegerOps()) { 6509 Opc = ARMCC::NE; break; 6510 } else { 6511 Invert = true; LLVM_FALLTHROUGH; 6512 } 6513 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6514 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6515 case ISD::SETGT: Opc = ARMCC::GT; break; 6516 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6517 case ISD::SETGE: Opc = ARMCC::GE; break; 6518 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6519 case ISD::SETUGT: Opc = ARMCC::HI; break; 6520 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6521 case ISD::SETUGE: Opc = ARMCC::HS; break; 6522 } 6523 6524 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6525 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6526 SDValue AndOp; 6527 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6528 AndOp = Op0; 6529 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6530 AndOp = Op1; 6531 6532 // Ignore bitconvert. 6533 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6534 AndOp = AndOp.getOperand(0); 6535 6536 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6537 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6538 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6539 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6540 if (!Invert) 6541 Result = DAG.getNOT(dl, Result, VT); 6542 return Result; 6543 } 6544 } 6545 } 6546 6547 if (Swap) 6548 std::swap(Op0, Op1); 6549 6550 // If one of the operands is a constant vector zero, attempt to fold the 6551 // comparison to a specialized compare-against-zero form. 6552 SDValue SingleOp; 6553 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6554 SingleOp = Op0; 6555 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6556 if (Opc == ARMCC::GE) 6557 Opc = ARMCC::LE; 6558 else if (Opc == ARMCC::GT) 6559 Opc = ARMCC::LT; 6560 SingleOp = Op1; 6561 } 6562 6563 SDValue Result; 6564 if (SingleOp.getNode()) { 6565 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6566 DAG.getConstant(Opc, dl, MVT::i32)); 6567 } else { 6568 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6569 DAG.getConstant(Opc, dl, MVT::i32)); 6570 } 6571 6572 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6573 6574 if (Invert) 6575 Result = DAG.getNOT(dl, Result, VT); 6576 6577 return Result; 6578 } 6579 6580 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6581 SDValue LHS = Op.getOperand(0); 6582 SDValue RHS = Op.getOperand(1); 6583 SDValue Carry = Op.getOperand(2); 6584 SDValue Cond = Op.getOperand(3); 6585 SDLoc DL(Op); 6586 6587 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6588 6589 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6590 // have to invert the carry first. 6591 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6592 DAG.getConstant(1, DL, MVT::i32), Carry); 6593 // This converts the boolean value carry into the carry flag. 6594 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6595 6596 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6597 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6598 6599 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6600 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6601 SDValue ARMcc = DAG.getConstant( 6602 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6603 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6604 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6605 Cmp.getValue(1), SDValue()); 6606 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6607 CCR, Chain.getValue(1)); 6608 } 6609 6610 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6611 /// valid vector constant for a NEON or MVE instruction with a "modified 6612 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6613 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6614 unsigned SplatBitSize, SelectionDAG &DAG, 6615 const SDLoc &dl, EVT &VT, EVT VectorVT, 6616 VMOVModImmType type) { 6617 unsigned OpCmode, Imm; 6618 bool is128Bits = VectorVT.is128BitVector(); 6619 6620 // SplatBitSize is set to the smallest size that splats the vector, so a 6621 // zero vector will always have SplatBitSize == 8. However, NEON modified 6622 // immediate instructions others than VMOV do not support the 8-bit encoding 6623 // of a zero vector, and the default encoding of zero is supposed to be the 6624 // 32-bit version. 6625 if (SplatBits == 0) 6626 SplatBitSize = 32; 6627 6628 switch (SplatBitSize) { 6629 case 8: 6630 if (type != VMOVModImm) 6631 return SDValue(); 6632 // Any 1-byte value is OK. Op=0, Cmode=1110. 6633 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6634 OpCmode = 0xe; 6635 Imm = SplatBits; 6636 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6637 break; 6638 6639 case 16: 6640 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6641 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6642 if ((SplatBits & ~0xff) == 0) { 6643 // Value = 0x00nn: Op=x, Cmode=100x. 6644 OpCmode = 0x8; 6645 Imm = SplatBits; 6646 break; 6647 } 6648 if ((SplatBits & ~0xff00) == 0) { 6649 // Value = 0xnn00: Op=x, Cmode=101x. 6650 OpCmode = 0xa; 6651 Imm = SplatBits >> 8; 6652 break; 6653 } 6654 return SDValue(); 6655 6656 case 32: 6657 // NEON's 32-bit VMOV supports splat values where: 6658 // * only one byte is nonzero, or 6659 // * the least significant byte is 0xff and the second byte is nonzero, or 6660 // * the least significant 2 bytes are 0xff and the third is nonzero. 6661 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6662 if ((SplatBits & ~0xff) == 0) { 6663 // Value = 0x000000nn: Op=x, Cmode=000x. 6664 OpCmode = 0; 6665 Imm = SplatBits; 6666 break; 6667 } 6668 if ((SplatBits & ~0xff00) == 0) { 6669 // Value = 0x0000nn00: Op=x, Cmode=001x. 6670 OpCmode = 0x2; 6671 Imm = SplatBits >> 8; 6672 break; 6673 } 6674 if ((SplatBits & ~0xff0000) == 0) { 6675 // Value = 0x00nn0000: Op=x, Cmode=010x. 6676 OpCmode = 0x4; 6677 Imm = SplatBits >> 16; 6678 break; 6679 } 6680 if ((SplatBits & ~0xff000000) == 0) { 6681 // Value = 0xnn000000: Op=x, Cmode=011x. 6682 OpCmode = 0x6; 6683 Imm = SplatBits >> 24; 6684 break; 6685 } 6686 6687 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6688 if (type == OtherModImm) return SDValue(); 6689 6690 if ((SplatBits & ~0xffff) == 0 && 6691 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6692 // Value = 0x0000nnff: Op=x, Cmode=1100. 6693 OpCmode = 0xc; 6694 Imm = SplatBits >> 8; 6695 break; 6696 } 6697 6698 // cmode == 0b1101 is not supported for MVE VMVN 6699 if (type == MVEVMVNModImm) 6700 return SDValue(); 6701 6702 if ((SplatBits & ~0xffffff) == 0 && 6703 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6704 // Value = 0x00nnffff: Op=x, Cmode=1101. 6705 OpCmode = 0xd; 6706 Imm = SplatBits >> 16; 6707 break; 6708 } 6709 6710 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6711 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6712 // VMOV.I32. A (very) minor optimization would be to replicate the value 6713 // and fall through here to test for a valid 64-bit splat. But, then the 6714 // caller would also need to check and handle the change in size. 6715 return SDValue(); 6716 6717 case 64: { 6718 if (type != VMOVModImm) 6719 return SDValue(); 6720 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6721 uint64_t BitMask = 0xff; 6722 uint64_t Val = 0; 6723 unsigned ImmMask = 1; 6724 Imm = 0; 6725 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6726 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6727 Val |= BitMask; 6728 Imm |= ImmMask; 6729 } else if ((SplatBits & BitMask) != 0) { 6730 return SDValue(); 6731 } 6732 BitMask <<= 8; 6733 ImmMask <<= 1; 6734 } 6735 6736 if (DAG.getDataLayout().isBigEndian()) { 6737 // Reverse the order of elements within the vector. 6738 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8; 6739 unsigned Mask = (1 << BytesPerElem) - 1; 6740 unsigned NumElems = 8 / BytesPerElem; 6741 unsigned NewImm = 0; 6742 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) { 6743 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask); 6744 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem; 6745 } 6746 Imm = NewImm; 6747 } 6748 6749 // Op=1, Cmode=1110. 6750 OpCmode = 0x1e; 6751 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6752 break; 6753 } 6754 6755 default: 6756 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6757 } 6758 6759 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6760 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6761 } 6762 6763 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6764 const ARMSubtarget *ST) const { 6765 EVT VT = Op.getValueType(); 6766 bool IsDouble = (VT == MVT::f64); 6767 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6768 const APFloat &FPVal = CFP->getValueAPF(); 6769 6770 // Prevent floating-point constants from using literal loads 6771 // when execute-only is enabled. 6772 if (ST->genExecuteOnly()) { 6773 // If we can represent the constant as an immediate, don't lower it 6774 if (isFPImmLegal(FPVal, VT)) 6775 return Op; 6776 // Otherwise, construct as integer, and move to float register 6777 APInt INTVal = FPVal.bitcastToAPInt(); 6778 SDLoc DL(CFP); 6779 switch (VT.getSimpleVT().SimpleTy) { 6780 default: 6781 llvm_unreachable("Unknown floating point type!"); 6782 break; 6783 case MVT::f64: { 6784 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6785 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6786 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6787 } 6788 case MVT::f32: 6789 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6790 DAG.getConstant(INTVal, DL, MVT::i32)); 6791 } 6792 } 6793 6794 if (!ST->hasVFP3Base()) 6795 return SDValue(); 6796 6797 // Use the default (constant pool) lowering for double constants when we have 6798 // an SP-only FPU 6799 if (IsDouble && !Subtarget->hasFP64()) 6800 return SDValue(); 6801 6802 // Try splatting with a VMOV.f32... 6803 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6804 6805 if (ImmVal != -1) { 6806 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6807 // We have code in place to select a valid ConstantFP already, no need to 6808 // do any mangling. 6809 return Op; 6810 } 6811 6812 // It's a float and we are trying to use NEON operations where 6813 // possible. Lower it to a splat followed by an extract. 6814 SDLoc DL(Op); 6815 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6816 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6817 NewVal); 6818 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6819 DAG.getConstant(0, DL, MVT::i32)); 6820 } 6821 6822 // The rest of our options are NEON only, make sure that's allowed before 6823 // proceeding.. 6824 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6825 return SDValue(); 6826 6827 EVT VMovVT; 6828 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6829 6830 // It wouldn't really be worth bothering for doubles except for one very 6831 // important value, which does happen to match: 0.0. So make sure we don't do 6832 // anything stupid. 6833 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6834 return SDValue(); 6835 6836 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6837 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6838 VMovVT, VT, VMOVModImm); 6839 if (NewVal != SDValue()) { 6840 SDLoc DL(Op); 6841 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6842 NewVal); 6843 if (IsDouble) 6844 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6845 6846 // It's a float: cast and extract a vector element. 6847 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6848 VecConstant); 6849 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6850 DAG.getConstant(0, DL, MVT::i32)); 6851 } 6852 6853 // Finally, try a VMVN.i32 6854 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6855 VT, VMVNModImm); 6856 if (NewVal != SDValue()) { 6857 SDLoc DL(Op); 6858 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6859 6860 if (IsDouble) 6861 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6862 6863 // It's a float: cast and extract a vector element. 6864 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6865 VecConstant); 6866 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6867 DAG.getConstant(0, DL, MVT::i32)); 6868 } 6869 6870 return SDValue(); 6871 } 6872 6873 // check if an VEXT instruction can handle the shuffle mask when the 6874 // vector sources of the shuffle are the same. 6875 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6876 unsigned NumElts = VT.getVectorNumElements(); 6877 6878 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6879 if (M[0] < 0) 6880 return false; 6881 6882 Imm = M[0]; 6883 6884 // If this is a VEXT shuffle, the immediate value is the index of the first 6885 // element. The other shuffle indices must be the successive elements after 6886 // the first one. 6887 unsigned ExpectedElt = Imm; 6888 for (unsigned i = 1; i < NumElts; ++i) { 6889 // Increment the expected index. If it wraps around, just follow it 6890 // back to index zero and keep going. 6891 ++ExpectedElt; 6892 if (ExpectedElt == NumElts) 6893 ExpectedElt = 0; 6894 6895 if (M[i] < 0) continue; // ignore UNDEF indices 6896 if (ExpectedElt != static_cast<unsigned>(M[i])) 6897 return false; 6898 } 6899 6900 return true; 6901 } 6902 6903 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6904 bool &ReverseVEXT, unsigned &Imm) { 6905 unsigned NumElts = VT.getVectorNumElements(); 6906 ReverseVEXT = false; 6907 6908 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6909 if (M[0] < 0) 6910 return false; 6911 6912 Imm = M[0]; 6913 6914 // If this is a VEXT shuffle, the immediate value is the index of the first 6915 // element. The other shuffle indices must be the successive elements after 6916 // the first one. 6917 unsigned ExpectedElt = Imm; 6918 for (unsigned i = 1; i < NumElts; ++i) { 6919 // Increment the expected index. If it wraps around, it may still be 6920 // a VEXT but the source vectors must be swapped. 6921 ExpectedElt += 1; 6922 if (ExpectedElt == NumElts * 2) { 6923 ExpectedElt = 0; 6924 ReverseVEXT = true; 6925 } 6926 6927 if (M[i] < 0) continue; // ignore UNDEF indices 6928 if (ExpectedElt != static_cast<unsigned>(M[i])) 6929 return false; 6930 } 6931 6932 // Adjust the index value if the source operands will be swapped. 6933 if (ReverseVEXT) 6934 Imm -= NumElts; 6935 6936 return true; 6937 } 6938 6939 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6940 /// instruction with the specified blocksize. (The order of the elements 6941 /// within each block of the vector is reversed.) 6942 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6943 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6944 "Only possible block sizes for VREV are: 16, 32, 64"); 6945 6946 unsigned EltSz = VT.getScalarSizeInBits(); 6947 if (EltSz == 64) 6948 return false; 6949 6950 unsigned NumElts = VT.getVectorNumElements(); 6951 unsigned BlockElts = M[0] + 1; 6952 // If the first shuffle index is UNDEF, be optimistic. 6953 if (M[0] < 0) 6954 BlockElts = BlockSize / EltSz; 6955 6956 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6957 return false; 6958 6959 for (unsigned i = 0; i < NumElts; ++i) { 6960 if (M[i] < 0) continue; // ignore UNDEF indices 6961 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6962 return false; 6963 } 6964 6965 return true; 6966 } 6967 6968 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6969 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6970 // range, then 0 is placed into the resulting vector. So pretty much any mask 6971 // of 8 elements can work here. 6972 return VT == MVT::v8i8 && M.size() == 8; 6973 } 6974 6975 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6976 unsigned Index) { 6977 if (Mask.size() == Elements * 2) 6978 return Index / Elements; 6979 return Mask[Index] == 0 ? 0 : 1; 6980 } 6981 6982 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6983 // checking that pairs of elements in the shuffle mask represent the same index 6984 // in each vector, incrementing the expected index by 2 at each step. 6985 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6986 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6987 // v2={e,f,g,h} 6988 // WhichResult gives the offset for each element in the mask based on which 6989 // of the two results it belongs to. 6990 // 6991 // The transpose can be represented either as: 6992 // result1 = shufflevector v1, v2, result1_shuffle_mask 6993 // result2 = shufflevector v1, v2, result2_shuffle_mask 6994 // where v1/v2 and the shuffle masks have the same number of elements 6995 // (here WhichResult (see below) indicates which result is being checked) 6996 // 6997 // or as: 6998 // results = shufflevector v1, v2, shuffle_mask 6999 // where both results are returned in one vector and the shuffle mask has twice 7000 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 7001 // want to check the low half and high half of the shuffle mask as if it were 7002 // the other case 7003 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7004 unsigned EltSz = VT.getScalarSizeInBits(); 7005 if (EltSz == 64) 7006 return false; 7007 7008 unsigned NumElts = VT.getVectorNumElements(); 7009 if (M.size() != NumElts && M.size() != NumElts*2) 7010 return false; 7011 7012 // If the mask is twice as long as the input vector then we need to check the 7013 // upper and lower parts of the mask with a matching value for WhichResult 7014 // FIXME: A mask with only even values will be rejected in case the first 7015 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 7016 // M[0] is used to determine WhichResult 7017 for (unsigned i = 0; i < M.size(); i += NumElts) { 7018 WhichResult = SelectPairHalf(NumElts, M, i); 7019 for (unsigned j = 0; j < NumElts; j += 2) { 7020 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7021 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 7022 return false; 7023 } 7024 } 7025 7026 if (M.size() == NumElts*2) 7027 WhichResult = 0; 7028 7029 return true; 7030 } 7031 7032 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 7033 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7034 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 7035 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7036 unsigned EltSz = VT.getScalarSizeInBits(); 7037 if (EltSz == 64) 7038 return false; 7039 7040 unsigned NumElts = VT.getVectorNumElements(); 7041 if (M.size() != NumElts && M.size() != NumElts*2) 7042 return false; 7043 7044 for (unsigned i = 0; i < M.size(); i += NumElts) { 7045 WhichResult = SelectPairHalf(NumElts, M, i); 7046 for (unsigned j = 0; j < NumElts; j += 2) { 7047 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 7048 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 7049 return false; 7050 } 7051 } 7052 7053 if (M.size() == NumElts*2) 7054 WhichResult = 0; 7055 7056 return true; 7057 } 7058 7059 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 7060 // that the mask elements are either all even and in steps of size 2 or all odd 7061 // and in steps of size 2. 7062 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 7063 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 7064 // v2={e,f,g,h} 7065 // Requires similar checks to that of isVTRNMask with 7066 // respect the how results are returned. 7067 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7068 unsigned EltSz = VT.getScalarSizeInBits(); 7069 if (EltSz == 64) 7070 return false; 7071 7072 unsigned NumElts = VT.getVectorNumElements(); 7073 if (M.size() != NumElts && M.size() != NumElts*2) 7074 return false; 7075 7076 for (unsigned i = 0; i < M.size(); i += NumElts) { 7077 WhichResult = SelectPairHalf(NumElts, M, i); 7078 for (unsigned j = 0; j < NumElts; ++j) { 7079 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 7080 return false; 7081 } 7082 } 7083 7084 if (M.size() == NumElts*2) 7085 WhichResult = 0; 7086 7087 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7088 if (VT.is64BitVector() && EltSz == 32) 7089 return false; 7090 7091 return true; 7092 } 7093 7094 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 7095 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7096 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 7097 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7098 unsigned EltSz = VT.getScalarSizeInBits(); 7099 if (EltSz == 64) 7100 return false; 7101 7102 unsigned NumElts = VT.getVectorNumElements(); 7103 if (M.size() != NumElts && M.size() != NumElts*2) 7104 return false; 7105 7106 unsigned Half = NumElts / 2; 7107 for (unsigned i = 0; i < M.size(); i += NumElts) { 7108 WhichResult = SelectPairHalf(NumElts, M, i); 7109 for (unsigned j = 0; j < NumElts; j += Half) { 7110 unsigned Idx = WhichResult; 7111 for (unsigned k = 0; k < Half; ++k) { 7112 int MIdx = M[i + j + k]; 7113 if (MIdx >= 0 && (unsigned) MIdx != Idx) 7114 return false; 7115 Idx += 2; 7116 } 7117 } 7118 } 7119 7120 if (M.size() == NumElts*2) 7121 WhichResult = 0; 7122 7123 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7124 if (VT.is64BitVector() && EltSz == 32) 7125 return false; 7126 7127 return true; 7128 } 7129 7130 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 7131 // that pairs of elements of the shufflemask represent the same index in each 7132 // vector incrementing sequentially through the vectors. 7133 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 7134 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 7135 // v2={e,f,g,h} 7136 // Requires similar checks to that of isVTRNMask with respect the how results 7137 // are returned. 7138 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7139 unsigned EltSz = VT.getScalarSizeInBits(); 7140 if (EltSz == 64) 7141 return false; 7142 7143 unsigned NumElts = VT.getVectorNumElements(); 7144 if (M.size() != NumElts && M.size() != NumElts*2) 7145 return false; 7146 7147 for (unsigned i = 0; i < M.size(); i += NumElts) { 7148 WhichResult = SelectPairHalf(NumElts, M, i); 7149 unsigned Idx = WhichResult * NumElts / 2; 7150 for (unsigned j = 0; j < NumElts; j += 2) { 7151 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7152 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 7153 return false; 7154 Idx += 1; 7155 } 7156 } 7157 7158 if (M.size() == NumElts*2) 7159 WhichResult = 0; 7160 7161 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7162 if (VT.is64BitVector() && EltSz == 32) 7163 return false; 7164 7165 return true; 7166 } 7167 7168 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 7169 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7170 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 7171 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 7172 unsigned EltSz = VT.getScalarSizeInBits(); 7173 if (EltSz == 64) 7174 return false; 7175 7176 unsigned NumElts = VT.getVectorNumElements(); 7177 if (M.size() != NumElts && M.size() != NumElts*2) 7178 return false; 7179 7180 for (unsigned i = 0; i < M.size(); i += NumElts) { 7181 WhichResult = SelectPairHalf(NumElts, M, i); 7182 unsigned Idx = WhichResult * NumElts / 2; 7183 for (unsigned j = 0; j < NumElts; j += 2) { 7184 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 7185 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 7186 return false; 7187 Idx += 1; 7188 } 7189 } 7190 7191 if (M.size() == NumElts*2) 7192 WhichResult = 0; 7193 7194 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 7195 if (VT.is64BitVector() && EltSz == 32) 7196 return false; 7197 7198 return true; 7199 } 7200 7201 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 7202 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 7203 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 7204 unsigned &WhichResult, 7205 bool &isV_UNDEF) { 7206 isV_UNDEF = false; 7207 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 7208 return ARMISD::VTRN; 7209 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 7210 return ARMISD::VUZP; 7211 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 7212 return ARMISD::VZIP; 7213 7214 isV_UNDEF = true; 7215 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7216 return ARMISD::VTRN; 7217 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7218 return ARMISD::VUZP; 7219 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 7220 return ARMISD::VZIP; 7221 7222 return 0; 7223 } 7224 7225 /// \return true if this is a reverse operation on an vector. 7226 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 7227 unsigned NumElts = VT.getVectorNumElements(); 7228 // Make sure the mask has the right size. 7229 if (NumElts != M.size()) 7230 return false; 7231 7232 // Look for <15, ..., 3, -1, 1, 0>. 7233 for (unsigned i = 0; i != NumElts; ++i) 7234 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 7235 return false; 7236 7237 return true; 7238 } 7239 7240 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) { 7241 unsigned NumElts = VT.getVectorNumElements(); 7242 // Make sure the mask has the right size. 7243 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8)) 7244 return false; 7245 7246 // If Top 7247 // Look for <0, N, 2, N+2, 4, N+4, ..>. 7248 // This inserts Input2 into Input1 7249 // else if not Top 7250 // Look for <0, N+1, 2, N+3, 4, N+5, ..> 7251 // This inserts Input1 into Input2 7252 unsigned Offset = Top ? 0 : 1; 7253 for (unsigned i = 0; i < NumElts; i+=2) { 7254 if (M[i] >= 0 && M[i] != (int)i) 7255 return false; 7256 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset)) 7257 return false; 7258 } 7259 7260 return true; 7261 } 7262 7263 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted 7264 // from a pair of inputs. For example: 7265 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7266 // FP_ROUND(EXTRACT_ELT(Y, 0), 7267 // FP_ROUND(EXTRACT_ELT(X, 1), 7268 // FP_ROUND(EXTRACT_ELT(Y, 1), ...) 7269 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG, 7270 const ARMSubtarget *ST) { 7271 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7272 if (!ST->hasMVEFloatOps()) 7273 return SDValue(); 7274 7275 SDLoc dl(BV); 7276 EVT VT = BV.getValueType(); 7277 if (VT != MVT::v8f16) 7278 return SDValue(); 7279 7280 // We are looking for a buildvector of fptrunc elements, where all the 7281 // elements are interleavingly extracted from two sources. Check the first two 7282 // items are valid enough and extract some info from them (they are checked 7283 // properly in the loop below). 7284 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND || 7285 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7286 BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0) 7287 return SDValue(); 7288 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND || 7289 BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7290 BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0) 7291 return SDValue(); 7292 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7293 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0); 7294 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32) 7295 return SDValue(); 7296 7297 // Check all the values in the BuildVector line up with our expectations. 7298 for (unsigned i = 1; i < 4; i++) { 7299 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7300 return Trunc.getOpcode() == ISD::FP_ROUND && 7301 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7302 Trunc.getOperand(0).getOperand(0) == Op && 7303 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7304 }; 7305 if (!Check(BV.getOperand(i * 2 + 0), Op0, i)) 7306 return SDValue(); 7307 if (!Check(BV.getOperand(i * 2 + 1), Op1, i)) 7308 return SDValue(); 7309 } 7310 7311 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0, 7312 DAG.getConstant(0, dl, MVT::i32)); 7313 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1, 7314 DAG.getConstant(1, dl, MVT::i32)); 7315 } 7316 7317 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted 7318 // from a single input on alternating lanes. For example: 7319 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0), 7320 // FP_ROUND(EXTRACT_ELT(X, 2), 7321 // FP_ROUND(EXTRACT_ELT(X, 4), ...) 7322 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG, 7323 const ARMSubtarget *ST) { 7324 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7325 if (!ST->hasMVEFloatOps()) 7326 return SDValue(); 7327 7328 SDLoc dl(BV); 7329 EVT VT = BV.getValueType(); 7330 if (VT != MVT::v4f32) 7331 return SDValue(); 7332 7333 // We are looking for a buildvector of fptext elements, where all the 7334 // elements are alternating lanes from a single source. For example <0,2,4,6> 7335 // or <1,3,5,7>. Check the first two items are valid enough and extract some 7336 // info from them (they are checked properly in the loop below). 7337 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND || 7338 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7339 return SDValue(); 7340 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0); 7341 int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1); 7342 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1)) 7343 return SDValue(); 7344 7345 // Check all the values in the BuildVector line up with our expectations. 7346 for (unsigned i = 1; i < 4; i++) { 7347 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) { 7348 return Trunc.getOpcode() == ISD::FP_EXTEND && 7349 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7350 Trunc.getOperand(0).getOperand(0) == Op && 7351 Trunc.getOperand(0).getConstantOperandVal(1) == Idx; 7352 }; 7353 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset)) 7354 return SDValue(); 7355 } 7356 7357 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0, 7358 DAG.getConstant(Offset, dl, MVT::i32)); 7359 } 7360 7361 // If N is an integer constant that can be moved into a register in one 7362 // instruction, return an SDValue of such a constant (will become a MOV 7363 // instruction). Otherwise return null. 7364 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 7365 const ARMSubtarget *ST, const SDLoc &dl) { 7366 uint64_t Val; 7367 if (!isa<ConstantSDNode>(N)) 7368 return SDValue(); 7369 Val = cast<ConstantSDNode>(N)->getZExtValue(); 7370 7371 if (ST->isThumb1Only()) { 7372 if (Val <= 255 || ~Val <= 255) 7373 return DAG.getConstant(Val, dl, MVT::i32); 7374 } else { 7375 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 7376 return DAG.getConstant(Val, dl, MVT::i32); 7377 } 7378 return SDValue(); 7379 } 7380 7381 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 7382 const ARMSubtarget *ST) { 7383 SDLoc dl(Op); 7384 EVT VT = Op.getValueType(); 7385 7386 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 7387 7388 unsigned NumElts = VT.getVectorNumElements(); 7389 unsigned BoolMask; 7390 unsigned BitsPerBool; 7391 if (NumElts == 4) { 7392 BitsPerBool = 4; 7393 BoolMask = 0xf; 7394 } else if (NumElts == 8) { 7395 BitsPerBool = 2; 7396 BoolMask = 0x3; 7397 } else if (NumElts == 16) { 7398 BitsPerBool = 1; 7399 BoolMask = 0x1; 7400 } else 7401 return SDValue(); 7402 7403 // If this is a single value copied into all lanes (a splat), we can just sign 7404 // extend that single value 7405 SDValue FirstOp = Op.getOperand(0); 7406 if (!isa<ConstantSDNode>(FirstOp) && 7407 std::all_of(std::next(Op->op_begin()), Op->op_end(), 7408 [&FirstOp](SDUse &U) { 7409 return U.get().isUndef() || U.get() == FirstOp; 7410 })) { 7411 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp, 7412 DAG.getValueType(MVT::i1)); 7413 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext); 7414 } 7415 7416 // First create base with bits set where known 7417 unsigned Bits32 = 0; 7418 for (unsigned i = 0; i < NumElts; ++i) { 7419 SDValue V = Op.getOperand(i); 7420 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 7421 continue; 7422 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 7423 if (BitSet) 7424 Bits32 |= BoolMask << (i * BitsPerBool); 7425 } 7426 7427 // Add in unknown nodes 7428 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 7429 DAG.getConstant(Bits32, dl, MVT::i32)); 7430 for (unsigned i = 0; i < NumElts; ++i) { 7431 SDValue V = Op.getOperand(i); 7432 if (isa<ConstantSDNode>(V) || V.isUndef()) 7433 continue; 7434 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 7435 DAG.getConstant(i, dl, MVT::i32)); 7436 } 7437 7438 return Base; 7439 } 7440 7441 // If this is a case we can't handle, return null and let the default 7442 // expansion code take care of it. 7443 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 7444 const ARMSubtarget *ST) const { 7445 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7446 SDLoc dl(Op); 7447 EVT VT = Op.getValueType(); 7448 7449 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7450 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 7451 7452 APInt SplatBits, SplatUndef; 7453 unsigned SplatBitSize; 7454 bool HasAnyUndefs; 7455 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7456 if (SplatUndef.isAllOnesValue()) 7457 return DAG.getUNDEF(VT); 7458 7459 if ((ST->hasNEON() && SplatBitSize <= 64) || 7460 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) { 7461 // Check if an immediate VMOV works. 7462 EVT VmovVT; 7463 SDValue Val = 7464 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 7465 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm); 7466 7467 if (Val.getNode()) { 7468 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 7469 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7470 } 7471 7472 // Try an immediate VMVN. 7473 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 7474 Val = isVMOVModifiedImm( 7475 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT, 7476 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 7477 if (Val.getNode()) { 7478 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 7479 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 7480 } 7481 7482 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 7483 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 7484 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 7485 if (ImmVal != -1) { 7486 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 7487 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 7488 } 7489 } 7490 } 7491 } 7492 7493 // Scan through the operands to see if only one value is used. 7494 // 7495 // As an optimisation, even if more than one value is used it may be more 7496 // profitable to splat with one value then change some lanes. 7497 // 7498 // Heuristically we decide to do this if the vector has a "dominant" value, 7499 // defined as splatted to more than half of the lanes. 7500 unsigned NumElts = VT.getVectorNumElements(); 7501 bool isOnlyLowElement = true; 7502 bool usesOnlyOneValue = true; 7503 bool hasDominantValue = false; 7504 bool isConstant = true; 7505 7506 // Map of the number of times a particular SDValue appears in the 7507 // element list. 7508 DenseMap<SDValue, unsigned> ValueCounts; 7509 SDValue Value; 7510 for (unsigned i = 0; i < NumElts; ++i) { 7511 SDValue V = Op.getOperand(i); 7512 if (V.isUndef()) 7513 continue; 7514 if (i > 0) 7515 isOnlyLowElement = false; 7516 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7517 isConstant = false; 7518 7519 ValueCounts.insert(std::make_pair(V, 0)); 7520 unsigned &Count = ValueCounts[V]; 7521 7522 // Is this value dominant? (takes up more than half of the lanes) 7523 if (++Count > (NumElts / 2)) { 7524 hasDominantValue = true; 7525 Value = V; 7526 } 7527 } 7528 if (ValueCounts.size() != 1) 7529 usesOnlyOneValue = false; 7530 if (!Value.getNode() && !ValueCounts.empty()) 7531 Value = ValueCounts.begin()->first; 7532 7533 if (ValueCounts.empty()) 7534 return DAG.getUNDEF(VT); 7535 7536 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 7537 // Keep going if we are hitting this case. 7538 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 7539 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7540 7541 unsigned EltSize = VT.getScalarSizeInBits(); 7542 7543 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 7544 // i32 and try again. 7545 if (hasDominantValue && EltSize <= 32) { 7546 if (!isConstant) { 7547 SDValue N; 7548 7549 // If we are VDUPing a value that comes directly from a vector, that will 7550 // cause an unnecessary move to and from a GPR, where instead we could 7551 // just use VDUPLANE. We can only do this if the lane being extracted 7552 // is at a constant index, as the VDUP from lane instructions only have 7553 // constant-index forms. 7554 ConstantSDNode *constIndex; 7555 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7556 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 7557 // We need to create a new undef vector to use for the VDUPLANE if the 7558 // size of the vector from which we get the value is different than the 7559 // size of the vector that we need to create. We will insert the element 7560 // such that the register coalescer will remove unnecessary copies. 7561 if (VT != Value->getOperand(0).getValueType()) { 7562 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 7563 VT.getVectorNumElements(); 7564 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7565 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 7566 Value, DAG.getConstant(index, dl, MVT::i32)), 7567 DAG.getConstant(index, dl, MVT::i32)); 7568 } else 7569 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7570 Value->getOperand(0), Value->getOperand(1)); 7571 } else 7572 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 7573 7574 if (!usesOnlyOneValue) { 7575 // The dominant value was splatted as 'N', but we now have to insert 7576 // all differing elements. 7577 for (unsigned I = 0; I < NumElts; ++I) { 7578 if (Op.getOperand(I) == Value) 7579 continue; 7580 SmallVector<SDValue, 3> Ops; 7581 Ops.push_back(N); 7582 Ops.push_back(Op.getOperand(I)); 7583 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7584 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7585 } 7586 } 7587 return N; 7588 } 7589 if (VT.getVectorElementType().isFloatingPoint()) { 7590 SmallVector<SDValue, 8> Ops; 7591 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7592 assert(FVT == MVT::f32 || FVT == MVT::f16); 7593 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7594 for (unsigned i = 0; i < NumElts; ++i) 7595 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7596 Op.getOperand(i))); 7597 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7598 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7599 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7600 if (Val.getNode()) 7601 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7602 } 7603 if (usesOnlyOneValue) { 7604 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7605 if (isConstant && Val.getNode()) 7606 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7607 } 7608 } 7609 7610 // If all elements are constants and the case above didn't get hit, fall back 7611 // to the default expansion, which will generate a load from the constant 7612 // pool. 7613 if (isConstant) 7614 return SDValue(); 7615 7616 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and 7617 // vmovn). Empirical tests suggest this is rarely worth it for vectors of 7618 // length <= 2. 7619 if (NumElts >= 4) 7620 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 7621 return shuffle; 7622 7623 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into 7624 // VCVT's 7625 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget)) 7626 return VCVT; 7627 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget)) 7628 return VCVT; 7629 7630 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7631 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7632 // into two 64-bit vectors; we might discover a better way to lower it. 7633 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7634 EVT ExtVT = VT.getVectorElementType(); 7635 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7636 SDValue Lower = 7637 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7638 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7639 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7640 SDValue Upper = DAG.getBuildVector( 7641 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7642 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7643 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7644 if (Lower && Upper) 7645 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7646 } 7647 7648 // Vectors with 32- or 64-bit elements can be built by directly assigning 7649 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7650 // will be legalized. 7651 if (EltSize >= 32) { 7652 // Do the expansion with floating-point types, since that is what the VFP 7653 // registers are defined to use, and since i64 is not legal. 7654 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7655 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7656 SmallVector<SDValue, 8> Ops; 7657 for (unsigned i = 0; i < NumElts; ++i) 7658 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7659 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7660 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7661 } 7662 7663 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7664 // know the default expansion would otherwise fall back on something even 7665 // worse. For a vector with one or two non-undef values, that's 7666 // scalar_to_vector for the elements followed by a shuffle (provided the 7667 // shuffle is valid for the target) and materialization element by element 7668 // on the stack followed by a load for everything else. 7669 if (!isConstant && !usesOnlyOneValue) { 7670 SDValue Vec = DAG.getUNDEF(VT); 7671 for (unsigned i = 0 ; i < NumElts; ++i) { 7672 SDValue V = Op.getOperand(i); 7673 if (V.isUndef()) 7674 continue; 7675 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7676 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7677 } 7678 return Vec; 7679 } 7680 7681 return SDValue(); 7682 } 7683 7684 // Gather data to see if the operation can be modelled as a 7685 // shuffle in combination with VEXTs. 7686 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7687 SelectionDAG &DAG) const { 7688 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7689 SDLoc dl(Op); 7690 EVT VT = Op.getValueType(); 7691 unsigned NumElts = VT.getVectorNumElements(); 7692 7693 struct ShuffleSourceInfo { 7694 SDValue Vec; 7695 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7696 unsigned MaxElt = 0; 7697 7698 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7699 // be compatible with the shuffle we intend to construct. As a result 7700 // ShuffleVec will be some sliding window into the original Vec. 7701 SDValue ShuffleVec; 7702 7703 // Code should guarantee that element i in Vec starts at element "WindowBase 7704 // + i * WindowScale in ShuffleVec". 7705 int WindowBase = 0; 7706 int WindowScale = 1; 7707 7708 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7709 7710 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7711 }; 7712 7713 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7714 // node. 7715 SmallVector<ShuffleSourceInfo, 2> Sources; 7716 for (unsigned i = 0; i < NumElts; ++i) { 7717 SDValue V = Op.getOperand(i); 7718 if (V.isUndef()) 7719 continue; 7720 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7721 // A shuffle can only come from building a vector from various 7722 // elements of other vectors. 7723 return SDValue(); 7724 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7725 // Furthermore, shuffles require a constant mask, whereas extractelts 7726 // accept variable indices. 7727 return SDValue(); 7728 } 7729 7730 // Add this element source to the list if it's not already there. 7731 SDValue SourceVec = V.getOperand(0); 7732 auto Source = llvm::find(Sources, SourceVec); 7733 if (Source == Sources.end()) 7734 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7735 7736 // Update the minimum and maximum lane number seen. 7737 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7738 Source->MinElt = std::min(Source->MinElt, EltNo); 7739 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7740 } 7741 7742 // Currently only do something sane when at most two source vectors 7743 // are involved. 7744 if (Sources.size() > 2) 7745 return SDValue(); 7746 7747 // Find out the smallest element size among result and two sources, and use 7748 // it as element size to build the shuffle_vector. 7749 EVT SmallestEltTy = VT.getVectorElementType(); 7750 for (auto &Source : Sources) { 7751 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7752 if (SrcEltTy.bitsLT(SmallestEltTy)) 7753 SmallestEltTy = SrcEltTy; 7754 } 7755 unsigned ResMultiplier = 7756 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7757 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7758 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7759 7760 // If the source vector is too wide or too narrow, we may nevertheless be able 7761 // to construct a compatible shuffle either by concatenating it with UNDEF or 7762 // extracting a suitable range of elements. 7763 for (auto &Src : Sources) { 7764 EVT SrcVT = Src.ShuffleVec.getValueType(); 7765 7766 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits(); 7767 uint64_t VTSize = VT.getFixedSizeInBits(); 7768 if (SrcVTSize == VTSize) 7769 continue; 7770 7771 // This stage of the search produces a source with the same element type as 7772 // the original, but with a total width matching the BUILD_VECTOR output. 7773 EVT EltVT = SrcVT.getVectorElementType(); 7774 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits(); 7775 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7776 7777 if (SrcVTSize < VTSize) { 7778 if (2 * SrcVTSize != VTSize) 7779 return SDValue(); 7780 // We can pad out the smaller vector for free, so if it's part of a 7781 // shuffle... 7782 Src.ShuffleVec = 7783 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7784 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7785 continue; 7786 } 7787 7788 if (SrcVTSize != 2 * VTSize) 7789 return SDValue(); 7790 7791 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7792 // Span too large for a VEXT to cope 7793 return SDValue(); 7794 } 7795 7796 if (Src.MinElt >= NumSrcElts) { 7797 // The extraction can just take the second half 7798 Src.ShuffleVec = 7799 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7800 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7801 Src.WindowBase = -NumSrcElts; 7802 } else if (Src.MaxElt < NumSrcElts) { 7803 // The extraction can just take the first half 7804 Src.ShuffleVec = 7805 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7806 DAG.getConstant(0, dl, MVT::i32)); 7807 } else { 7808 // An actual VEXT is needed 7809 SDValue VEXTSrc1 = 7810 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7811 DAG.getConstant(0, dl, MVT::i32)); 7812 SDValue VEXTSrc2 = 7813 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7814 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7815 7816 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7817 VEXTSrc2, 7818 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7819 Src.WindowBase = -Src.MinElt; 7820 } 7821 } 7822 7823 // Another possible incompatibility occurs from the vector element types. We 7824 // can fix this by bitcasting the source vectors to the same type we intend 7825 // for the shuffle. 7826 for (auto &Src : Sources) { 7827 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7828 if (SrcEltTy == SmallestEltTy) 7829 continue; 7830 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7831 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec); 7832 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7833 Src.WindowBase *= Src.WindowScale; 7834 } 7835 7836 // Final sanity check before we try to actually produce a shuffle. 7837 LLVM_DEBUG(for (auto Src 7838 : Sources) 7839 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7840 7841 // The stars all align, our next step is to produce the mask for the shuffle. 7842 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7843 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7844 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7845 SDValue Entry = Op.getOperand(i); 7846 if (Entry.isUndef()) 7847 continue; 7848 7849 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7850 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7851 7852 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7853 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7854 // segment. 7855 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7856 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(), 7857 VT.getScalarSizeInBits()); 7858 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7859 7860 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7861 // starting at the appropriate offset. 7862 int *LaneMask = &Mask[i * ResMultiplier]; 7863 7864 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7865 ExtractBase += NumElts * (Src - Sources.begin()); 7866 for (int j = 0; j < LanesDefined; ++j) 7867 LaneMask[j] = ExtractBase + j; 7868 } 7869 7870 7871 // We can't handle more than two sources. This should have already 7872 // been checked before this point. 7873 assert(Sources.size() <= 2 && "Too many sources!"); 7874 7875 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7876 for (unsigned i = 0; i < Sources.size(); ++i) 7877 ShuffleOps[i] = Sources[i].ShuffleVec; 7878 7879 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7880 ShuffleOps[1], Mask, DAG); 7881 if (!Shuffle) 7882 return SDValue(); 7883 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle); 7884 } 7885 7886 enum ShuffleOpCodes { 7887 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7888 OP_VREV, 7889 OP_VDUP0, 7890 OP_VDUP1, 7891 OP_VDUP2, 7892 OP_VDUP3, 7893 OP_VEXT1, 7894 OP_VEXT2, 7895 OP_VEXT3, 7896 OP_VUZPL, // VUZP, left result 7897 OP_VUZPR, // VUZP, right result 7898 OP_VZIPL, // VZIP, left result 7899 OP_VZIPR, // VZIP, right result 7900 OP_VTRNL, // VTRN, left result 7901 OP_VTRNR // VTRN, right result 7902 }; 7903 7904 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7905 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7906 switch (OpNum) { 7907 case OP_COPY: 7908 case OP_VREV: 7909 case OP_VDUP0: 7910 case OP_VDUP1: 7911 case OP_VDUP2: 7912 case OP_VDUP3: 7913 return true; 7914 } 7915 return false; 7916 } 7917 7918 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7919 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7920 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7921 /// are assumed to be legal. 7922 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7923 if (VT.getVectorNumElements() == 4 && 7924 (VT.is128BitVector() || VT.is64BitVector())) { 7925 unsigned PFIndexes[4]; 7926 for (unsigned i = 0; i != 4; ++i) { 7927 if (M[i] < 0) 7928 PFIndexes[i] = 8; 7929 else 7930 PFIndexes[i] = M[i]; 7931 } 7932 7933 // Compute the index in the perfect shuffle table. 7934 unsigned PFTableIndex = 7935 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7936 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7937 unsigned Cost = (PFEntry >> 30); 7938 7939 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7940 return true; 7941 } 7942 7943 bool ReverseVEXT, isV_UNDEF; 7944 unsigned Imm, WhichResult; 7945 7946 unsigned EltSize = VT.getScalarSizeInBits(); 7947 if (EltSize >= 32 || 7948 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7949 ShuffleVectorInst::isIdentityMask(M) || 7950 isVREVMask(M, VT, 64) || 7951 isVREVMask(M, VT, 32) || 7952 isVREVMask(M, VT, 16)) 7953 return true; 7954 else if (Subtarget->hasNEON() && 7955 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7956 isVTBLMask(M, VT) || 7957 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7958 return true; 7959 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7960 isReverseMask(M, VT)) 7961 return true; 7962 else if (Subtarget->hasMVEIntegerOps() && 7963 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1))) 7964 return true; 7965 else 7966 return false; 7967 } 7968 7969 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7970 /// the specified operations to build the shuffle. 7971 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7972 SDValue RHS, SelectionDAG &DAG, 7973 const SDLoc &dl) { 7974 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7975 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7976 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7977 7978 if (OpNum == OP_COPY) { 7979 if (LHSID == (1*9+2)*9+3) return LHS; 7980 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7981 return RHS; 7982 } 7983 7984 SDValue OpLHS, OpRHS; 7985 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7986 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7987 EVT VT = OpLHS.getValueType(); 7988 7989 switch (OpNum) { 7990 default: llvm_unreachable("Unknown shuffle opcode!"); 7991 case OP_VREV: 7992 // VREV divides the vector in half and swaps within the half. 7993 if (VT.getVectorElementType() == MVT::i32 || 7994 VT.getVectorElementType() == MVT::f32) 7995 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7996 // vrev <4 x i16> -> VREV32 7997 if (VT.getVectorElementType() == MVT::i16) 7998 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7999 // vrev <4 x i8> -> VREV16 8000 assert(VT.getVectorElementType() == MVT::i8); 8001 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 8002 case OP_VDUP0: 8003 case OP_VDUP1: 8004 case OP_VDUP2: 8005 case OP_VDUP3: 8006 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 8007 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 8008 case OP_VEXT1: 8009 case OP_VEXT2: 8010 case OP_VEXT3: 8011 return DAG.getNode(ARMISD::VEXT, dl, VT, 8012 OpLHS, OpRHS, 8013 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 8014 case OP_VUZPL: 8015 case OP_VUZPR: 8016 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 8017 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 8018 case OP_VZIPL: 8019 case OP_VZIPR: 8020 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 8021 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 8022 case OP_VTRNL: 8023 case OP_VTRNR: 8024 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 8025 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 8026 } 8027 } 8028 8029 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 8030 ArrayRef<int> ShuffleMask, 8031 SelectionDAG &DAG) { 8032 // Check to see if we can use the VTBL instruction. 8033 SDValue V1 = Op.getOperand(0); 8034 SDValue V2 = Op.getOperand(1); 8035 SDLoc DL(Op); 8036 8037 SmallVector<SDValue, 8> VTBLMask; 8038 for (ArrayRef<int>::iterator 8039 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 8040 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 8041 8042 if (V2.getNode()->isUndef()) 8043 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 8044 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8045 8046 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 8047 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 8048 } 8049 8050 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 8051 SelectionDAG &DAG) { 8052 SDLoc DL(Op); 8053 SDValue OpLHS = Op.getOperand(0); 8054 EVT VT = OpLHS.getValueType(); 8055 8056 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 8057 "Expect an v8i16/v16i8 type"); 8058 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 8059 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 8060 // extract the first 8 bytes into the top double word and the last 8 bytes 8061 // into the bottom double word. The v8i16 case is similar. 8062 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 8063 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 8064 DAG.getConstant(ExtractNum, DL, MVT::i32)); 8065 } 8066 8067 static EVT getVectorTyFromPredicateVector(EVT VT) { 8068 switch (VT.getSimpleVT().SimpleTy) { 8069 case MVT::v4i1: 8070 return MVT::v4i32; 8071 case MVT::v8i1: 8072 return MVT::v8i16; 8073 case MVT::v16i1: 8074 return MVT::v16i8; 8075 default: 8076 llvm_unreachable("Unexpected vector predicate type"); 8077 } 8078 } 8079 8080 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 8081 SelectionDAG &DAG) { 8082 // Converting from boolean predicates to integers involves creating a vector 8083 // of all ones or all zeroes and selecting the lanes based upon the real 8084 // predicate. 8085 SDValue AllOnes = 8086 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 8087 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 8088 8089 SDValue AllZeroes = 8090 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 8091 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 8092 8093 // Get full vector type from predicate type 8094 EVT NewVT = getVectorTyFromPredicateVector(VT); 8095 8096 SDValue RecastV1; 8097 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 8098 // this to a v16i1. This cannot be done with an ordinary bitcast because the 8099 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 8100 // since we know in hardware the sizes are really the same. 8101 if (VT != MVT::v16i1) 8102 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 8103 else 8104 RecastV1 = Pred; 8105 8106 // Select either all ones or zeroes depending upon the real predicate bits. 8107 SDValue PredAsVector = 8108 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 8109 8110 // Recast our new predicate-as-integer v16i8 vector into something 8111 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 8112 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 8113 } 8114 8115 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 8116 const ARMSubtarget *ST) { 8117 EVT VT = Op.getValueType(); 8118 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8119 ArrayRef<int> ShuffleMask = SVN->getMask(); 8120 8121 assert(ST->hasMVEIntegerOps() && 8122 "No support for vector shuffle of boolean predicates"); 8123 8124 SDValue V1 = Op.getOperand(0); 8125 SDLoc dl(Op); 8126 if (isReverseMask(ShuffleMask, VT)) { 8127 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 8128 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 8129 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 8130 DAG.getConstant(16, dl, MVT::i32)); 8131 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 8132 } 8133 8134 // Until we can come up with optimised cases for every single vector 8135 // shuffle in existence we have chosen the least painful strategy. This is 8136 // to essentially promote the boolean predicate to a 8-bit integer, where 8137 // each predicate represents a byte. Then we fall back on a normal integer 8138 // vector shuffle and convert the result back into a predicate vector. In 8139 // many cases the generated code might be even better than scalar code 8140 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 8141 // fields in a register into 8 other arbitrary 2-bit fields! 8142 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 8143 EVT NewVT = PredAsVector.getValueType(); 8144 8145 // Do the shuffle! 8146 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 8147 DAG.getUNDEF(NewVT), ShuffleMask); 8148 8149 // Now return the result of comparing the shuffled vector with zero, 8150 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8151 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 8152 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8153 } 8154 8155 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op, 8156 ArrayRef<int> ShuffleMask, 8157 SelectionDAG &DAG) { 8158 // Attempt to lower the vector shuffle using as many whole register movs as 8159 // possible. This is useful for types smaller than 32bits, which would 8160 // often otherwise become a series for grp movs. 8161 SDLoc dl(Op); 8162 EVT VT = Op.getValueType(); 8163 if (VT.getScalarSizeInBits() >= 32) 8164 return SDValue(); 8165 8166 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && 8167 "Unexpected vector type"); 8168 int NumElts = VT.getVectorNumElements(); 8169 int QuarterSize = NumElts / 4; 8170 // The four final parts of the vector, as i32's 8171 SDValue Parts[4]; 8172 8173 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not 8174 // <u,u,u,u>), returning the vmov lane index 8175 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) { 8176 // Detect which mov lane this would be from the first non-undef element. 8177 int MovIdx = -1; 8178 for (int i = 0; i < Length; i++) { 8179 if (ShuffleMask[Start + i] >= 0) { 8180 if (ShuffleMask[Start + i] % Length != i) 8181 return -1; 8182 MovIdx = ShuffleMask[Start + i] / Length; 8183 break; 8184 } 8185 } 8186 // If all items are undef, leave this for other combines 8187 if (MovIdx == -1) 8188 return -1; 8189 // Check the remaining values are the correct part of the same mov 8190 for (int i = 1; i < Length; i++) { 8191 if (ShuffleMask[Start + i] >= 0 && 8192 (ShuffleMask[Start + i] / Length != MovIdx || 8193 ShuffleMask[Start + i] % Length != i)) 8194 return -1; 8195 } 8196 return MovIdx; 8197 }; 8198 8199 for (int Part = 0; Part < 4; ++Part) { 8200 // Does this part look like a mov 8201 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize); 8202 if (Elt != -1) { 8203 SDValue Input = Op->getOperand(0); 8204 if (Elt >= 4) { 8205 Input = Op->getOperand(1); 8206 Elt -= 4; 8207 } 8208 SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input); 8209 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast, 8210 DAG.getConstant(Elt, dl, MVT::i32)); 8211 } 8212 } 8213 8214 // Nothing interesting found, just return 8215 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3]) 8216 return SDValue(); 8217 8218 // The other parts need to be built with the old shuffle vector, cast to a 8219 // v4i32 and extract_vector_elts 8220 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) { 8221 SmallVector<int, 16> NewShuffleMask; 8222 for (int Part = 0; Part < 4; ++Part) 8223 for (int i = 0; i < QuarterSize; i++) 8224 NewShuffleMask.push_back( 8225 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]); 8226 SDValue NewShuffle = DAG.getVectorShuffle( 8227 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask); 8228 SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle); 8229 8230 for (int Part = 0; Part < 4; ++Part) 8231 if (!Parts[Part]) 8232 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 8233 BitCast, DAG.getConstant(Part, dl, MVT::i32)); 8234 } 8235 // Build a vector out of the various parts and bitcast it back to the original 8236 // type. 8237 SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts); 8238 return DAG.getBitcast(VT, NewVec); 8239 } 8240 8241 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 8242 const ARMSubtarget *ST) { 8243 SDValue V1 = Op.getOperand(0); 8244 SDValue V2 = Op.getOperand(1); 8245 SDLoc dl(Op); 8246 EVT VT = Op.getValueType(); 8247 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8248 unsigned EltSize = VT.getScalarSizeInBits(); 8249 8250 if (ST->hasMVEIntegerOps() && EltSize == 1) 8251 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 8252 8253 // Convert shuffles that are directly supported on NEON to target-specific 8254 // DAG nodes, instead of keeping them as shuffles and matching them again 8255 // during code selection. This is more efficient and avoids the possibility 8256 // of inconsistencies between legalization and selection. 8257 // FIXME: floating-point vectors should be canonicalized to integer vectors 8258 // of the same time so that they get CSEd properly. 8259 ArrayRef<int> ShuffleMask = SVN->getMask(); 8260 8261 if (EltSize <= 32) { 8262 if (SVN->isSplat()) { 8263 int Lane = SVN->getSplatIndex(); 8264 // If this is undef splat, generate it via "just" vdup, if possible. 8265 if (Lane == -1) Lane = 0; 8266 8267 // Test if V1 is a SCALAR_TO_VECTOR. 8268 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 8269 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8270 } 8271 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 8272 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 8273 // reaches it). 8274 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 8275 !isa<ConstantSDNode>(V1.getOperand(0))) { 8276 bool IsScalarToVector = true; 8277 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 8278 if (!V1.getOperand(i).isUndef()) { 8279 IsScalarToVector = false; 8280 break; 8281 } 8282 if (IsScalarToVector) 8283 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 8284 } 8285 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 8286 DAG.getConstant(Lane, dl, MVT::i32)); 8287 } 8288 8289 bool ReverseVEXT = false; 8290 unsigned Imm = 0; 8291 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 8292 if (ReverseVEXT) 8293 std::swap(V1, V2); 8294 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 8295 DAG.getConstant(Imm, dl, MVT::i32)); 8296 } 8297 8298 if (isVREVMask(ShuffleMask, VT, 64)) 8299 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 8300 if (isVREVMask(ShuffleMask, VT, 32)) 8301 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 8302 if (isVREVMask(ShuffleMask, VT, 16)) 8303 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 8304 8305 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 8306 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 8307 DAG.getConstant(Imm, dl, MVT::i32)); 8308 } 8309 8310 // Check for Neon shuffles that modify both input vectors in place. 8311 // If both results are used, i.e., if there are two shuffles with the same 8312 // source operands and with masks corresponding to both results of one of 8313 // these operations, DAG memoization will ensure that a single node is 8314 // used for both shuffles. 8315 unsigned WhichResult = 0; 8316 bool isV_UNDEF = false; 8317 if (ST->hasNEON()) { 8318 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8319 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 8320 if (isV_UNDEF) 8321 V2 = V1; 8322 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 8323 .getValue(WhichResult); 8324 } 8325 } 8326 if (ST->hasMVEIntegerOps()) { 8327 if (isVMOVNMask(ShuffleMask, VT, 0)) 8328 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1, 8329 DAG.getConstant(0, dl, MVT::i32)); 8330 if (isVMOVNMask(ShuffleMask, VT, 1)) 8331 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2, 8332 DAG.getConstant(1, dl, MVT::i32)); 8333 } 8334 8335 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 8336 // shuffles that produce a result larger than their operands with: 8337 // shuffle(concat(v1, undef), concat(v2, undef)) 8338 // -> 8339 // shuffle(concat(v1, v2), undef) 8340 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 8341 // 8342 // This is useful in the general case, but there are special cases where 8343 // native shuffles produce larger results: the two-result ops. 8344 // 8345 // Look through the concat when lowering them: 8346 // shuffle(concat(v1, v2), undef) 8347 // -> 8348 // concat(VZIP(v1, v2):0, :1) 8349 // 8350 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 8351 SDValue SubV1 = V1->getOperand(0); 8352 SDValue SubV2 = V1->getOperand(1); 8353 EVT SubVT = SubV1.getValueType(); 8354 8355 // We expect these to have been canonicalized to -1. 8356 assert(llvm::all_of(ShuffleMask, [&](int i) { 8357 return i < (int)VT.getVectorNumElements(); 8358 }) && "Unexpected shuffle index into UNDEF operand!"); 8359 8360 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 8361 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 8362 if (isV_UNDEF) 8363 SubV2 = SubV1; 8364 assert((WhichResult == 0) && 8365 "In-place shuffle of concat can only have one result!"); 8366 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 8367 SubV1, SubV2); 8368 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 8369 Res.getValue(1)); 8370 } 8371 } 8372 } 8373 8374 // If the shuffle is not directly supported and it has 4 elements, use 8375 // the PerfectShuffle-generated table to synthesize it from other shuffles. 8376 unsigned NumElts = VT.getVectorNumElements(); 8377 if (NumElts == 4) { 8378 unsigned PFIndexes[4]; 8379 for (unsigned i = 0; i != 4; ++i) { 8380 if (ShuffleMask[i] < 0) 8381 PFIndexes[i] = 8; 8382 else 8383 PFIndexes[i] = ShuffleMask[i]; 8384 } 8385 8386 // Compute the index in the perfect shuffle table. 8387 unsigned PFTableIndex = 8388 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8389 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8390 unsigned Cost = (PFEntry >> 30); 8391 8392 if (Cost <= 4) { 8393 if (ST->hasNEON()) 8394 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8395 else if (isLegalMVEShuffleOp(PFEntry)) { 8396 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8397 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8398 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 8399 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 8400 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 8401 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8402 } 8403 } 8404 } 8405 8406 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 8407 if (EltSize >= 32) { 8408 // Do the expansion with floating-point types, since that is what the VFP 8409 // registers are defined to use, and since i64 is not legal. 8410 EVT EltVT = EVT::getFloatingPointVT(EltSize); 8411 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 8412 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 8413 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 8414 SmallVector<SDValue, 8> Ops; 8415 for (unsigned i = 0; i < NumElts; ++i) { 8416 if (ShuffleMask[i] < 0) 8417 Ops.push_back(DAG.getUNDEF(EltVT)); 8418 else 8419 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 8420 ShuffleMask[i] < (int)NumElts ? V1 : V2, 8421 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 8422 dl, MVT::i32))); 8423 } 8424 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 8425 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8426 } 8427 8428 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 8429 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 8430 8431 if (ST->hasNEON() && VT == MVT::v8i8) 8432 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 8433 return NewOp; 8434 8435 if (ST->hasMVEIntegerOps()) 8436 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG)) 8437 return NewOp; 8438 8439 return SDValue(); 8440 } 8441 8442 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8443 const ARMSubtarget *ST) { 8444 EVT VecVT = Op.getOperand(0).getValueType(); 8445 SDLoc dl(Op); 8446 8447 assert(ST->hasMVEIntegerOps() && 8448 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8449 8450 SDValue Conv = 8451 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8452 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8453 unsigned LaneWidth = 8454 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8455 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 8456 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 8457 Op.getOperand(1), DAG.getValueType(MVT::i1)); 8458 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 8459 DAG.getConstant(~Mask, dl, MVT::i32)); 8460 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 8461 } 8462 8463 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8464 SelectionDAG &DAG) const { 8465 // INSERT_VECTOR_ELT is legal only for immediate indexes. 8466 SDValue Lane = Op.getOperand(2); 8467 if (!isa<ConstantSDNode>(Lane)) 8468 return SDValue(); 8469 8470 SDValue Elt = Op.getOperand(1); 8471 EVT EltVT = Elt.getValueType(); 8472 8473 if (Subtarget->hasMVEIntegerOps() && 8474 Op.getValueType().getScalarSizeInBits() == 1) 8475 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 8476 8477 if (getTypeAction(*DAG.getContext(), EltVT) == 8478 TargetLowering::TypePromoteFloat) { 8479 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 8480 // but the type system will try to do that if we don't intervene. 8481 // Reinterpret any such vector-element insertion as one with the 8482 // corresponding integer types. 8483 8484 SDLoc dl(Op); 8485 8486 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 8487 assert(getTypeAction(*DAG.getContext(), IEltVT) != 8488 TargetLowering::TypePromoteFloat); 8489 8490 SDValue VecIn = Op.getOperand(0); 8491 EVT VecVT = VecIn.getValueType(); 8492 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 8493 VecVT.getVectorNumElements()); 8494 8495 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 8496 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 8497 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 8498 IVecIn, IElt, Lane); 8499 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 8500 } 8501 8502 return Op; 8503 } 8504 8505 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 8506 const ARMSubtarget *ST) { 8507 EVT VecVT = Op.getOperand(0).getValueType(); 8508 SDLoc dl(Op); 8509 8510 assert(ST->hasMVEIntegerOps() && 8511 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 8512 8513 SDValue Conv = 8514 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 8515 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8516 unsigned LaneWidth = 8517 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 8518 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 8519 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 8520 return Shift; 8521 } 8522 8523 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 8524 const ARMSubtarget *ST) { 8525 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 8526 SDValue Lane = Op.getOperand(1); 8527 if (!isa<ConstantSDNode>(Lane)) 8528 return SDValue(); 8529 8530 SDValue Vec = Op.getOperand(0); 8531 EVT VT = Vec.getValueType(); 8532 8533 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8534 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 8535 8536 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 8537 SDLoc dl(Op); 8538 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 8539 } 8540 8541 return Op; 8542 } 8543 8544 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 8545 const ARMSubtarget *ST) { 8546 SDValue V1 = Op.getOperand(0); 8547 SDValue V2 = Op.getOperand(1); 8548 SDLoc dl(Op); 8549 EVT VT = Op.getValueType(); 8550 EVT Op1VT = V1.getValueType(); 8551 EVT Op2VT = V2.getValueType(); 8552 unsigned NumElts = VT.getVectorNumElements(); 8553 8554 assert(Op1VT == Op2VT && "Operand types don't match!"); 8555 assert(VT.getScalarSizeInBits() == 1 && 8556 "Unexpected custom CONCAT_VECTORS lowering"); 8557 assert(ST->hasMVEIntegerOps() && 8558 "CONCAT_VECTORS lowering only supported for MVE"); 8559 8560 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8561 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 8562 8563 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 8564 // promoted to v8i16, etc. 8565 8566 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8567 8568 // Extract the vector elements from Op1 and Op2 one by one and truncate them 8569 // to be the right size for the destination. For example, if Op1 is v4i1 then 8570 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 8571 // which when promoted is v8i16. That means each i32 element from Op1 needs 8572 // truncating to i16 and inserting in the result. 8573 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 8574 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 8575 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 8576 EVT NewVT = NewV.getValueType(); 8577 EVT ConcatVT = ConVec.getValueType(); 8578 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 8579 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 8580 DAG.getIntPtrConstant(i, dl)); 8581 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 8582 DAG.getConstant(j, dl, MVT::i32)); 8583 } 8584 return ConVec; 8585 }; 8586 unsigned j = 0; 8587 ConVec = ExractInto(NewV1, ConVec, j); 8588 ConVec = ExractInto(NewV2, ConVec, j); 8589 8590 // Now return the result of comparing the subvector with zero, 8591 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8592 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 8593 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8594 } 8595 8596 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 8597 const ARMSubtarget *ST) { 8598 EVT VT = Op->getValueType(0); 8599 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 8600 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 8601 8602 // The only time a CONCAT_VECTORS operation can have legal types is when 8603 // two 64-bit vectors are concatenated to a 128-bit vector. 8604 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 8605 "unexpected CONCAT_VECTORS"); 8606 SDLoc dl(Op); 8607 SDValue Val = DAG.getUNDEF(MVT::v2f64); 8608 SDValue Op0 = Op.getOperand(0); 8609 SDValue Op1 = Op.getOperand(1); 8610 if (!Op0.isUndef()) 8611 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8612 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 8613 DAG.getIntPtrConstant(0, dl)); 8614 if (!Op1.isUndef()) 8615 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 8616 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 8617 DAG.getIntPtrConstant(1, dl)); 8618 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 8619 } 8620 8621 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 8622 const ARMSubtarget *ST) { 8623 SDValue V1 = Op.getOperand(0); 8624 SDValue V2 = Op.getOperand(1); 8625 SDLoc dl(Op); 8626 EVT VT = Op.getValueType(); 8627 EVT Op1VT = V1.getValueType(); 8628 unsigned NumElts = VT.getVectorNumElements(); 8629 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 8630 8631 assert(VT.getScalarSizeInBits() == 1 && 8632 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 8633 assert(ST->hasMVEIntegerOps() && 8634 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 8635 8636 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 8637 8638 // We now have Op1 promoted to a vector of integers, where v8i1 gets 8639 // promoted to v8i16, etc. 8640 8641 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 8642 8643 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 8644 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 8645 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 8646 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 8647 DAG.getIntPtrConstant(i, dl)); 8648 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 8649 DAG.getConstant(j, dl, MVT::i32)); 8650 } 8651 8652 // Now return the result of comparing the subvector with zero, 8653 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8654 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 8655 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8656 } 8657 8658 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 8659 /// element has been zero/sign-extended, depending on the isSigned parameter, 8660 /// from an integer type half its size. 8661 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 8662 bool isSigned) { 8663 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 8664 EVT VT = N->getValueType(0); 8665 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 8666 SDNode *BVN = N->getOperand(0).getNode(); 8667 if (BVN->getValueType(0) != MVT::v4i32 || 8668 BVN->getOpcode() != ISD::BUILD_VECTOR) 8669 return false; 8670 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8671 unsigned HiElt = 1 - LoElt; 8672 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 8673 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 8674 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 8675 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 8676 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 8677 return false; 8678 if (isSigned) { 8679 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 8680 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 8681 return true; 8682 } else { 8683 if (Hi0->isNullValue() && Hi1->isNullValue()) 8684 return true; 8685 } 8686 return false; 8687 } 8688 8689 if (N->getOpcode() != ISD::BUILD_VECTOR) 8690 return false; 8691 8692 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8693 SDNode *Elt = N->getOperand(i).getNode(); 8694 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8695 unsigned EltSize = VT.getScalarSizeInBits(); 8696 unsigned HalfSize = EltSize / 2; 8697 if (isSigned) { 8698 if (!isIntN(HalfSize, C->getSExtValue())) 8699 return false; 8700 } else { 8701 if (!isUIntN(HalfSize, C->getZExtValue())) 8702 return false; 8703 } 8704 continue; 8705 } 8706 return false; 8707 } 8708 8709 return true; 8710 } 8711 8712 /// isSignExtended - Check if a node is a vector value that is sign-extended 8713 /// or a constant BUILD_VECTOR with sign-extended elements. 8714 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8715 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8716 return true; 8717 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8718 return true; 8719 return false; 8720 } 8721 8722 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8723 /// or a constant BUILD_VECTOR with zero-extended elements. 8724 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8725 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8726 return true; 8727 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8728 return true; 8729 return false; 8730 } 8731 8732 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8733 if (OrigVT.getSizeInBits() >= 64) 8734 return OrigVT; 8735 8736 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8737 8738 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8739 switch (OrigSimpleTy) { 8740 default: llvm_unreachable("Unexpected Vector Type"); 8741 case MVT::v2i8: 8742 case MVT::v2i16: 8743 return MVT::v2i32; 8744 case MVT::v4i8: 8745 return MVT::v4i16; 8746 } 8747 } 8748 8749 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8750 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8751 /// We insert the required extension here to get the vector to fill a D register. 8752 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8753 const EVT &OrigTy, 8754 const EVT &ExtTy, 8755 unsigned ExtOpcode) { 8756 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8757 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8758 // 64-bits we need to insert a new extension so that it will be 64-bits. 8759 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8760 if (OrigTy.getSizeInBits() >= 64) 8761 return N; 8762 8763 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8764 EVT NewVT = getExtensionTo64Bits(OrigTy); 8765 8766 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8767 } 8768 8769 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8770 /// does not do any sign/zero extension. If the original vector is less 8771 /// than 64 bits, an appropriate extension will be added after the load to 8772 /// reach a total size of 64 bits. We have to add the extension separately 8773 /// because ARM does not have a sign/zero extending load for vectors. 8774 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8775 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8776 8777 // The load already has the right type. 8778 if (ExtendedTy == LD->getMemoryVT()) 8779 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8780 LD->getBasePtr(), LD->getPointerInfo(), 8781 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8782 8783 // We need to create a zextload/sextload. We cannot just create a load 8784 // followed by a zext/zext node because LowerMUL is also run during normal 8785 // operation legalization where we can't create illegal types. 8786 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8787 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8788 LD->getMemoryVT(), LD->getAlignment(), 8789 LD->getMemOperand()->getFlags()); 8790 } 8791 8792 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8793 /// extending load, or BUILD_VECTOR with extended elements, return the 8794 /// unextended value. The unextended vector should be 64 bits so that it can 8795 /// be used as an operand to a VMULL instruction. If the original vector size 8796 /// before extension is less than 64 bits we add a an extension to resize 8797 /// the vector to 64 bits. 8798 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8799 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8800 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8801 N->getOperand(0)->getValueType(0), 8802 N->getValueType(0), 8803 N->getOpcode()); 8804 8805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8806 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8807 "Expected extending load"); 8808 8809 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8810 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8811 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8812 SDValue extLoad = 8813 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8814 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8815 8816 return newLoad; 8817 } 8818 8819 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8820 // have been legalized as a BITCAST from v4i32. 8821 if (N->getOpcode() == ISD::BITCAST) { 8822 SDNode *BVN = N->getOperand(0).getNode(); 8823 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8824 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8825 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8826 return DAG.getBuildVector( 8827 MVT::v2i32, SDLoc(N), 8828 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8829 } 8830 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8831 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8832 EVT VT = N->getValueType(0); 8833 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8834 unsigned NumElts = VT.getVectorNumElements(); 8835 MVT TruncVT = MVT::getIntegerVT(EltSize); 8836 SmallVector<SDValue, 8> Ops; 8837 SDLoc dl(N); 8838 for (unsigned i = 0; i != NumElts; ++i) { 8839 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8840 const APInt &CInt = C->getAPIntValue(); 8841 // Element types smaller than 32 bits are not legal, so use i32 elements. 8842 // The values are implicitly truncated so sext vs. zext doesn't matter. 8843 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8844 } 8845 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8846 } 8847 8848 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8849 unsigned Opcode = N->getOpcode(); 8850 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8851 SDNode *N0 = N->getOperand(0).getNode(); 8852 SDNode *N1 = N->getOperand(1).getNode(); 8853 return N0->hasOneUse() && N1->hasOneUse() && 8854 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8855 } 8856 return false; 8857 } 8858 8859 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8860 unsigned Opcode = N->getOpcode(); 8861 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8862 SDNode *N0 = N->getOperand(0).getNode(); 8863 SDNode *N1 = N->getOperand(1).getNode(); 8864 return N0->hasOneUse() && N1->hasOneUse() && 8865 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8866 } 8867 return false; 8868 } 8869 8870 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8871 // Multiplications are only custom-lowered for 128-bit vectors so that 8872 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8873 EVT VT = Op.getValueType(); 8874 assert(VT.is128BitVector() && VT.isInteger() && 8875 "unexpected type for custom-lowering ISD::MUL"); 8876 SDNode *N0 = Op.getOperand(0).getNode(); 8877 SDNode *N1 = Op.getOperand(1).getNode(); 8878 unsigned NewOpc = 0; 8879 bool isMLA = false; 8880 bool isN0SExt = isSignExtended(N0, DAG); 8881 bool isN1SExt = isSignExtended(N1, DAG); 8882 if (isN0SExt && isN1SExt) 8883 NewOpc = ARMISD::VMULLs; 8884 else { 8885 bool isN0ZExt = isZeroExtended(N0, DAG); 8886 bool isN1ZExt = isZeroExtended(N1, DAG); 8887 if (isN0ZExt && isN1ZExt) 8888 NewOpc = ARMISD::VMULLu; 8889 else if (isN1SExt || isN1ZExt) { 8890 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8891 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8892 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8893 NewOpc = ARMISD::VMULLs; 8894 isMLA = true; 8895 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8896 NewOpc = ARMISD::VMULLu; 8897 isMLA = true; 8898 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8899 std::swap(N0, N1); 8900 NewOpc = ARMISD::VMULLu; 8901 isMLA = true; 8902 } 8903 } 8904 8905 if (!NewOpc) { 8906 if (VT == MVT::v2i64) 8907 // Fall through to expand this. It is not legal. 8908 return SDValue(); 8909 else 8910 // Other vector multiplications are legal. 8911 return Op; 8912 } 8913 } 8914 8915 // Legalize to a VMULL instruction. 8916 SDLoc DL(Op); 8917 SDValue Op0; 8918 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8919 if (!isMLA) { 8920 Op0 = SkipExtensionForVMULL(N0, DAG); 8921 assert(Op0.getValueType().is64BitVector() && 8922 Op1.getValueType().is64BitVector() && 8923 "unexpected types for extended operands to VMULL"); 8924 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8925 } 8926 8927 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8928 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8929 // vmull q0, d4, d6 8930 // vmlal q0, d5, d6 8931 // is faster than 8932 // vaddl q0, d4, d5 8933 // vmovl q1, d6 8934 // vmul q0, q0, q1 8935 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8936 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8937 EVT Op1VT = Op1.getValueType(); 8938 return DAG.getNode(N0->getOpcode(), DL, VT, 8939 DAG.getNode(NewOpc, DL, VT, 8940 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8941 DAG.getNode(NewOpc, DL, VT, 8942 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8943 } 8944 8945 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8946 SelectionDAG &DAG) { 8947 // TODO: Should this propagate fast-math-flags? 8948 8949 // Convert to float 8950 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8951 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8952 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8953 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8954 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8955 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8956 // Get reciprocal estimate. 8957 // float4 recip = vrecpeq_f32(yf); 8958 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8959 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8960 Y); 8961 // Because char has a smaller range than uchar, we can actually get away 8962 // without any newton steps. This requires that we use a weird bias 8963 // of 0xb000, however (again, this has been exhaustively tested). 8964 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8965 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8966 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8967 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8968 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8969 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8970 // Convert back to short. 8971 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8972 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8973 return X; 8974 } 8975 8976 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8977 SelectionDAG &DAG) { 8978 // TODO: Should this propagate fast-math-flags? 8979 8980 SDValue N2; 8981 // Convert to float. 8982 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8983 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8984 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8985 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8986 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8987 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8988 8989 // Use reciprocal estimate and one refinement step. 8990 // float4 recip = vrecpeq_f32(yf); 8991 // recip *= vrecpsq_f32(yf, recip); 8992 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8993 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8994 N1); 8995 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8996 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8997 N1, N2); 8998 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8999 // Because short has a smaller range than ushort, we can actually get away 9000 // with only a single newton step. This requires that we use a weird bias 9001 // of 89, however (again, this has been exhaustively tested). 9002 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 9003 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9004 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9005 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 9006 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9007 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9008 // Convert back to integer and return. 9009 // return vmovn_s32(vcvt_s32_f32(result)); 9010 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9011 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9012 return N0; 9013 } 9014 9015 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 9016 const ARMSubtarget *ST) { 9017 EVT VT = Op.getValueType(); 9018 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9019 "unexpected type for custom-lowering ISD::SDIV"); 9020 9021 SDLoc dl(Op); 9022 SDValue N0 = Op.getOperand(0); 9023 SDValue N1 = Op.getOperand(1); 9024 SDValue N2, N3; 9025 9026 if (VT == MVT::v8i8) { 9027 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 9028 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 9029 9030 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9031 DAG.getIntPtrConstant(4, dl)); 9032 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9033 DAG.getIntPtrConstant(4, dl)); 9034 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9035 DAG.getIntPtrConstant(0, dl)); 9036 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9037 DAG.getIntPtrConstant(0, dl)); 9038 9039 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 9040 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 9041 9042 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9043 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9044 9045 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 9046 return N0; 9047 } 9048 return LowerSDIV_v4i16(N0, N1, dl, DAG); 9049 } 9050 9051 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 9052 const ARMSubtarget *ST) { 9053 // TODO: Should this propagate fast-math-flags? 9054 EVT VT = Op.getValueType(); 9055 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 9056 "unexpected type for custom-lowering ISD::UDIV"); 9057 9058 SDLoc dl(Op); 9059 SDValue N0 = Op.getOperand(0); 9060 SDValue N1 = Op.getOperand(1); 9061 SDValue N2, N3; 9062 9063 if (VT == MVT::v8i8) { 9064 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 9065 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 9066 9067 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9068 DAG.getIntPtrConstant(4, dl)); 9069 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9070 DAG.getIntPtrConstant(4, dl)); 9071 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 9072 DAG.getIntPtrConstant(0, dl)); 9073 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 9074 DAG.getIntPtrConstant(0, dl)); 9075 9076 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 9077 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 9078 9079 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 9080 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 9081 9082 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 9083 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 9084 MVT::i32), 9085 N0); 9086 return N0; 9087 } 9088 9089 // v4i16 sdiv ... Convert to float. 9090 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 9091 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 9092 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 9093 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 9094 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 9095 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 9096 9097 // Use reciprocal estimate and two refinement steps. 9098 // float4 recip = vrecpeq_f32(yf); 9099 // recip *= vrecpsq_f32(yf, recip); 9100 // recip *= vrecpsq_f32(yf, recip); 9101 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9102 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 9103 BN1); 9104 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9105 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9106 BN1, N2); 9107 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9108 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 9109 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 9110 BN1, N2); 9111 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 9112 // Simply multiplying by the reciprocal estimate can leave us a few ulps 9113 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 9114 // and that it will never cause us to return an answer too large). 9115 // float4 result = as_float4(as_int4(xf*recip) + 2); 9116 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 9117 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 9118 N1 = DAG.getConstant(2, dl, MVT::v4i32); 9119 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 9120 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 9121 // Convert back to integer and return. 9122 // return vmovn_u32(vcvt_s32_f32(result)); 9123 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 9124 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 9125 return N0; 9126 } 9127 9128 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 9129 SDNode *N = Op.getNode(); 9130 EVT VT = N->getValueType(0); 9131 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 9132 9133 SDValue Carry = Op.getOperand(2); 9134 9135 SDLoc DL(Op); 9136 9137 SDValue Result; 9138 if (Op.getOpcode() == ISD::ADDCARRY) { 9139 // This converts the boolean value carry into the carry flag. 9140 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9141 9142 // Do the addition proper using the carry flag we wanted. 9143 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 9144 Op.getOperand(1), Carry); 9145 9146 // Now convert the carry flag into a boolean value. 9147 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9148 } else { 9149 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 9150 // have to invert the carry first. 9151 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9152 DAG.getConstant(1, DL, MVT::i32), Carry); 9153 // This converts the boolean value carry into the carry flag. 9154 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 9155 9156 // Do the subtraction proper using the carry flag we wanted. 9157 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 9158 Op.getOperand(1), Carry); 9159 9160 // Now convert the carry flag into a boolean value. 9161 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 9162 // But the carry returned by ARMISD::SUBE is not a borrow as expected 9163 // by ISD::SUBCARRY, so compute 1 - C. 9164 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 9165 DAG.getConstant(1, DL, MVT::i32), Carry); 9166 } 9167 9168 // Return both values. 9169 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 9170 } 9171 9172 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 9173 assert(Subtarget->isTargetDarwin()); 9174 9175 // For iOS, we want to call an alternative entry point: __sincos_stret, 9176 // return values are passed via sret. 9177 SDLoc dl(Op); 9178 SDValue Arg = Op.getOperand(0); 9179 EVT ArgVT = Arg.getValueType(); 9180 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 9181 auto PtrVT = getPointerTy(DAG.getDataLayout()); 9182 9183 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9184 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9185 9186 // Pair of floats / doubles used to pass the result. 9187 Type *RetTy = StructType::get(ArgTy, ArgTy); 9188 auto &DL = DAG.getDataLayout(); 9189 9190 ArgListTy Args; 9191 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 9192 SDValue SRet; 9193 if (ShouldUseSRet) { 9194 // Create stack object for sret. 9195 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 9196 const Align StackAlign = DL.getPrefTypeAlign(RetTy); 9197 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 9198 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 9199 9200 ArgListEntry Entry; 9201 Entry.Node = SRet; 9202 Entry.Ty = RetTy->getPointerTo(); 9203 Entry.IsSExt = false; 9204 Entry.IsZExt = false; 9205 Entry.IsSRet = true; 9206 Args.push_back(Entry); 9207 RetTy = Type::getVoidTy(*DAG.getContext()); 9208 } 9209 9210 ArgListEntry Entry; 9211 Entry.Node = Arg; 9212 Entry.Ty = ArgTy; 9213 Entry.IsSExt = false; 9214 Entry.IsZExt = false; 9215 Args.push_back(Entry); 9216 9217 RTLIB::Libcall LC = 9218 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 9219 const char *LibcallName = getLibcallName(LC); 9220 CallingConv::ID CC = getLibcallCallingConv(LC); 9221 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 9222 9223 TargetLowering::CallLoweringInfo CLI(DAG); 9224 CLI.setDebugLoc(dl) 9225 .setChain(DAG.getEntryNode()) 9226 .setCallee(CC, RetTy, Callee, std::move(Args)) 9227 .setDiscardResult(ShouldUseSRet); 9228 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 9229 9230 if (!ShouldUseSRet) 9231 return CallResult.first; 9232 9233 SDValue LoadSin = 9234 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 9235 9236 // Address of cos field. 9237 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 9238 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 9239 SDValue LoadCos = 9240 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 9241 9242 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 9243 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 9244 LoadSin.getValue(0), LoadCos.getValue(0)); 9245 } 9246 9247 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 9248 bool Signed, 9249 SDValue &Chain) const { 9250 EVT VT = Op.getValueType(); 9251 assert((VT == MVT::i32 || VT == MVT::i64) && 9252 "unexpected type for custom lowering DIV"); 9253 SDLoc dl(Op); 9254 9255 const auto &DL = DAG.getDataLayout(); 9256 const auto &TLI = DAG.getTargetLoweringInfo(); 9257 9258 const char *Name = nullptr; 9259 if (Signed) 9260 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 9261 else 9262 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 9263 9264 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 9265 9266 ARMTargetLowering::ArgListTy Args; 9267 9268 for (auto AI : {1, 0}) { 9269 ArgListEntry Arg; 9270 Arg.Node = Op.getOperand(AI); 9271 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 9272 Args.push_back(Arg); 9273 } 9274 9275 CallLoweringInfo CLI(DAG); 9276 CLI.setDebugLoc(dl) 9277 .setChain(Chain) 9278 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 9279 ES, std::move(Args)); 9280 9281 return LowerCallTo(CLI).first; 9282 } 9283 9284 // This is a code size optimisation: return the original SDIV node to 9285 // DAGCombiner when we don't want to expand SDIV into a sequence of 9286 // instructions, and an empty node otherwise which will cause the 9287 // SDIV to be expanded in DAGCombine. 9288 SDValue 9289 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 9290 SelectionDAG &DAG, 9291 SmallVectorImpl<SDNode *> &Created) const { 9292 // TODO: Support SREM 9293 if (N->getOpcode() != ISD::SDIV) 9294 return SDValue(); 9295 9296 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 9297 const bool MinSize = ST.hasMinSize(); 9298 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 9299 : ST.hasDivideInARMMode(); 9300 9301 // Don't touch vector types; rewriting this may lead to scalarizing 9302 // the int divs. 9303 if (N->getOperand(0).getValueType().isVector()) 9304 return SDValue(); 9305 9306 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 9307 // hwdiv support for this to be really profitable. 9308 if (!(MinSize && HasDivide)) 9309 return SDValue(); 9310 9311 // ARM mode is a bit simpler than Thumb: we can handle large power 9312 // of 2 immediates with 1 mov instruction; no further checks required, 9313 // just return the sdiv node. 9314 if (!ST.isThumb()) 9315 return SDValue(N, 0); 9316 9317 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 9318 // and thus lose the code size benefits of a MOVS that requires only 2. 9319 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 9320 // but as it's doing exactly this, it's not worth the trouble to get TTI. 9321 if (Divisor.sgt(128)) 9322 return SDValue(); 9323 9324 return SDValue(N, 0); 9325 } 9326 9327 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 9328 bool Signed) const { 9329 assert(Op.getValueType() == MVT::i32 && 9330 "unexpected type for custom lowering DIV"); 9331 SDLoc dl(Op); 9332 9333 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 9334 DAG.getEntryNode(), Op.getOperand(1)); 9335 9336 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9337 } 9338 9339 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 9340 SDLoc DL(N); 9341 SDValue Op = N->getOperand(1); 9342 if (N->getValueType(0) == MVT::i32) 9343 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 9344 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9345 DAG.getConstant(0, DL, MVT::i32)); 9346 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 9347 DAG.getConstant(1, DL, MVT::i32)); 9348 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 9349 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 9350 } 9351 9352 void ARMTargetLowering::ExpandDIV_Windows( 9353 SDValue Op, SelectionDAG &DAG, bool Signed, 9354 SmallVectorImpl<SDValue> &Results) const { 9355 const auto &DL = DAG.getDataLayout(); 9356 const auto &TLI = DAG.getTargetLoweringInfo(); 9357 9358 assert(Op.getValueType() == MVT::i64 && 9359 "unexpected type for custom lowering DIV"); 9360 SDLoc dl(Op); 9361 9362 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 9363 9364 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 9365 9366 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 9367 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 9368 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 9369 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 9370 9371 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper)); 9372 } 9373 9374 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) { 9375 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode()); 9376 EVT MemVT = LD->getMemoryVT(); 9377 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9378 "Expected a predicate type!"); 9379 assert(MemVT == Op.getValueType()); 9380 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && 9381 "Expected a non-extending load"); 9382 assert(LD->isUnindexed() && "Expected a unindexed load"); 9383 9384 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit 9385 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We 9386 // need to make sure that 8/4 bits are actually loaded into the correct 9387 // place, which means loading the value and then shuffling the values into 9388 // the bottom bits of the predicate. 9389 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect 9390 // for BE). 9391 9392 SDLoc dl(Op); 9393 SDValue Load = DAG.getExtLoad( 9394 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(), 9395 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9396 LD->getMemOperand()); 9397 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load); 9398 if (MemVT != MVT::v16i1) 9399 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred, 9400 DAG.getConstant(0, dl, MVT::i32)); 9401 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl); 9402 } 9403 9404 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results, 9405 SelectionDAG &DAG) const { 9406 LoadSDNode *LD = cast<LoadSDNode>(N); 9407 EVT MemVT = LD->getMemoryVT(); 9408 assert(LD->isUnindexed() && "Loads should be unindexed at this point."); 9409 9410 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9411 !Subtarget->isThumb1Only() && LD->isVolatile()) { 9412 SDLoc dl(N); 9413 SDValue Result = DAG.getMemIntrinsicNode( 9414 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}), 9415 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand()); 9416 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1); 9417 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0); 9418 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 9419 Results.append({Pair, Result.getValue(2)}); 9420 } 9421 } 9422 9423 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) { 9424 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9425 EVT MemVT = ST->getMemoryVT(); 9426 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && 9427 "Expected a predicate type!"); 9428 assert(MemVT == ST->getValue().getValueType()); 9429 assert(!ST->isTruncatingStore() && "Expected a non-extending store"); 9430 assert(ST->isUnindexed() && "Expected a unindexed store"); 9431 9432 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits 9433 // unset and a scalar store. 9434 SDLoc dl(Op); 9435 SDValue Build = ST->getValue(); 9436 if (MemVT != MVT::v16i1) { 9437 SmallVector<SDValue, 16> Ops; 9438 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) 9439 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build, 9440 DAG.getConstant(I, dl, MVT::i32))); 9441 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++) 9442 Ops.push_back(DAG.getUNDEF(MVT::i32)); 9443 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops); 9444 } 9445 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build); 9446 return DAG.getTruncStore( 9447 ST->getChain(), dl, GRP, ST->getBasePtr(), 9448 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()), 9449 ST->getMemOperand()); 9450 } 9451 9452 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG, 9453 const ARMSubtarget *Subtarget) { 9454 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 9455 EVT MemVT = ST->getMemoryVT(); 9456 assert(ST->isUnindexed() && "Stores should be unindexed at this point."); 9457 9458 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() && 9459 !Subtarget->isThumb1Only() && ST->isVolatile()) { 9460 SDNode *N = Op.getNode(); 9461 SDLoc dl(N); 9462 9463 SDValue Lo = DAG.getNode( 9464 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9465 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl, 9466 MVT::i32)); 9467 SDValue Hi = DAG.getNode( 9468 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(), 9469 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl, 9470 MVT::i32)); 9471 9472 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other), 9473 {ST->getChain(), Lo, Hi, ST->getBasePtr()}, 9474 MemVT, ST->getMemOperand()); 9475 } else if (Subtarget->hasMVEIntegerOps() && 9476 ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || 9477 MemVT == MVT::v16i1))) { 9478 return LowerPredicateStore(Op, DAG); 9479 } 9480 9481 return SDValue(); 9482 } 9483 9484 static bool isZeroVector(SDValue N) { 9485 return (ISD::isBuildVectorAllZeros(N.getNode()) || 9486 (N->getOpcode() == ARMISD::VMOVIMM && 9487 isNullConstant(N->getOperand(0)))); 9488 } 9489 9490 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) { 9491 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode()); 9492 MVT VT = Op.getSimpleValueType(); 9493 SDValue Mask = N->getMask(); 9494 SDValue PassThru = N->getPassThru(); 9495 SDLoc dl(Op); 9496 9497 if (isZeroVector(PassThru)) 9498 return Op; 9499 9500 // MVE Masked loads use zero as the passthru value. Here we convert undef to 9501 // zero too, and other values are lowered to a select. 9502 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 9503 DAG.getTargetConstant(0, dl, MVT::i32)); 9504 SDValue NewLoad = DAG.getMaskedLoad( 9505 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec, 9506 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(), 9507 N->getExtensionType(), N->isExpandingLoad()); 9508 SDValue Combo = NewLoad; 9509 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST || 9510 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) && 9511 isZeroVector(PassThru->getOperand(0)); 9512 if (!PassThru.isUndef() && !PassThruIsCastZero) 9513 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru); 9514 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl); 9515 } 9516 9517 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG, 9518 const ARMSubtarget *ST) { 9519 if (!ST->hasMVEIntegerOps()) 9520 return SDValue(); 9521 9522 SDLoc dl(Op); 9523 unsigned BaseOpcode = 0; 9524 switch (Op->getOpcode()) { 9525 default: llvm_unreachable("Expected VECREDUCE opcode"); 9526 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break; 9527 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break; 9528 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break; 9529 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break; 9530 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break; 9531 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break; 9532 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break; 9533 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break; 9534 } 9535 9536 SDValue Op0 = Op->getOperand(0); 9537 EVT VT = Op0.getValueType(); 9538 EVT EltVT = VT.getVectorElementType(); 9539 unsigned NumElts = VT.getVectorNumElements(); 9540 unsigned NumActiveLanes = NumElts; 9541 9542 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || 9543 NumActiveLanes == 2) && 9544 "Only expected a power 2 vector size"); 9545 9546 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements 9547 // allows us to easily extract vector elements from the lanes. 9548 while (NumActiveLanes > 4) { 9549 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32; 9550 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0); 9551 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev); 9552 NumActiveLanes /= 2; 9553 } 9554 9555 SDValue Res; 9556 if (NumActiveLanes == 4) { 9557 // The remaining 4 elements are summed sequentially 9558 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9559 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32)); 9560 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9561 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32)); 9562 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9563 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32)); 9564 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9565 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32)); 9566 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9567 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags()); 9568 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags()); 9569 } else { 9570 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9571 DAG.getConstant(0, dl, MVT::i32)); 9572 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 9573 DAG.getConstant(1, dl, MVT::i32)); 9574 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags()); 9575 } 9576 9577 // Result type may be wider than element type. 9578 if (EltVT != Op->getValueType(0)) 9579 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res); 9580 return Res; 9581 } 9582 9583 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG, 9584 const ARMSubtarget *ST) { 9585 if (!ST->hasMVEFloatOps()) 9586 return SDValue(); 9587 return LowerVecReduce(Op, DAG, ST); 9588 } 9589 9590 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 9591 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 9592 // Acquire/Release load/store is not legal for targets without a dmb or 9593 // equivalent available. 9594 return SDValue(); 9595 9596 // Monotonic load/store is legal for all targets. 9597 return Op; 9598 } 9599 9600 static void ReplaceREADCYCLECOUNTER(SDNode *N, 9601 SmallVectorImpl<SDValue> &Results, 9602 SelectionDAG &DAG, 9603 const ARMSubtarget *Subtarget) { 9604 SDLoc DL(N); 9605 // Under Power Management extensions, the cycle-count is: 9606 // mrc p15, #0, <Rt>, c9, c13, #0 9607 SDValue Ops[] = { N->getOperand(0), // Chain 9608 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32), 9609 DAG.getTargetConstant(15, DL, MVT::i32), 9610 DAG.getTargetConstant(0, DL, MVT::i32), 9611 DAG.getTargetConstant(9, DL, MVT::i32), 9612 DAG.getTargetConstant(13, DL, MVT::i32), 9613 DAG.getTargetConstant(0, DL, MVT::i32) 9614 }; 9615 9616 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 9617 DAG.getVTList(MVT::i32, MVT::Other), Ops); 9618 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 9619 DAG.getConstant(0, DL, MVT::i32))); 9620 Results.push_back(Cycles32.getValue(1)); 9621 } 9622 9623 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 9624 SDLoc dl(V.getNode()); 9625 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 9626 SDValue VHi = DAG.getAnyExtOrTrunc( 9627 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 9628 dl, MVT::i32); 9629 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9630 if (isBigEndian) 9631 std::swap (VLo, VHi); 9632 SDValue RegClass = 9633 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 9634 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 9635 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 9636 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 9637 return SDValue( 9638 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 9639 } 9640 9641 static void ReplaceCMP_SWAP_64Results(SDNode *N, 9642 SmallVectorImpl<SDValue> & Results, 9643 SelectionDAG &DAG) { 9644 assert(N->getValueType(0) == MVT::i64 && 9645 "AtomicCmpSwap on types less than 64 should be legal"); 9646 SDValue Ops[] = {N->getOperand(1), 9647 createGPRPairNode(DAG, N->getOperand(2)), 9648 createGPRPairNode(DAG, N->getOperand(3)), 9649 N->getOperand(0)}; 9650 SDNode *CmpSwap = DAG.getMachineNode( 9651 ARM::CMP_SWAP_64, SDLoc(N), 9652 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 9653 9654 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 9655 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 9656 9657 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9658 9659 SDValue Lo = 9660 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 9661 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9662 SDValue Hi = 9663 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 9664 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)); 9665 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi)); 9666 Results.push_back(SDValue(CmpSwap, 2)); 9667 } 9668 9669 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const { 9670 SDLoc dl(Op); 9671 EVT VT = Op.getValueType(); 9672 SDValue Chain = Op.getOperand(0); 9673 SDValue LHS = Op.getOperand(1); 9674 SDValue RHS = Op.getOperand(2); 9675 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get(); 9676 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 9677 9678 // If we don't have instructions of this float type then soften to a libcall 9679 // and use SETCC instead. 9680 if (isUnsupportedFloatingType(LHS.getValueType())) { 9681 DAG.getTargetLoweringInfo().softenSetCCOperands( 9682 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling); 9683 if (!RHS.getNode()) { 9684 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 9685 CC = ISD::SETNE; 9686 } 9687 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS, 9688 DAG.getCondCode(CC)); 9689 return DAG.getMergeValues({Result, Chain}, dl); 9690 } 9691 9692 ARMCC::CondCodes CondCode, CondCode2; 9693 FPCCToARMCC(CC, CondCode, CondCode2); 9694 9695 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit 9696 // in CMPFP and CMPFPE, but instead it should be made explicit by these 9697 // instructions using a chain instead of glue. This would also fix the problem 9698 // here (and also in LowerSELECT_CC) where we generate two comparisons when 9699 // CondCode2 != AL. 9700 SDValue True = DAG.getConstant(1, dl, VT); 9701 SDValue False = DAG.getConstant(0, dl, VT); 9702 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 9703 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 9704 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9705 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG); 9706 if (CondCode2 != ARMCC::AL) { 9707 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 9708 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling); 9709 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG); 9710 } 9711 return DAG.getMergeValues({Result, Chain}, dl); 9712 } 9713 9714 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9715 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 9716 switch (Op.getOpcode()) { 9717 default: llvm_unreachable("Don't know how to custom lower this!"); 9718 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 9719 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9720 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9721 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9722 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9723 case ISD::SELECT: return LowerSELECT(Op, DAG); 9724 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9725 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9726 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 9727 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 9728 case ISD::VASTART: return LowerVASTART(Op, DAG); 9729 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 9730 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 9731 case ISD::SINT_TO_FP: 9732 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9733 case ISD::STRICT_FP_TO_SINT: 9734 case ISD::STRICT_FP_TO_UINT: 9735 case ISD::FP_TO_SINT: 9736 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 9737 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9738 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9739 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9740 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 9741 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 9742 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 9743 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget); 9744 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 9745 Subtarget); 9746 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 9747 case ISD::SHL: 9748 case ISD::SRL: 9749 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 9750 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 9751 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 9752 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 9753 case ISD::SRL_PARTS: 9754 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 9755 case ISD::CTTZ: 9756 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 9757 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 9758 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 9759 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 9760 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 9761 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 9762 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 9763 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 9764 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9765 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 9766 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 9767 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9768 case ISD::MUL: return LowerMUL(Op, DAG); 9769 case ISD::SDIV: 9770 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9771 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 9772 return LowerSDIV(Op, DAG, Subtarget); 9773 case ISD::UDIV: 9774 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 9775 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 9776 return LowerUDIV(Op, DAG, Subtarget); 9777 case ISD::ADDCARRY: 9778 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 9779 case ISD::SADDO: 9780 case ISD::SSUBO: 9781 return LowerSignedALUO(Op, DAG); 9782 case ISD::UADDO: 9783 case ISD::USUBO: 9784 return LowerUnsignedALUO(Op, DAG); 9785 case ISD::SADDSAT: 9786 case ISD::SSUBSAT: 9787 return LowerSADDSUBSAT(Op, DAG, Subtarget); 9788 case ISD::LOAD: 9789 return LowerPredicateLoad(Op, DAG); 9790 case ISD::STORE: 9791 return LowerSTORE(Op, DAG, Subtarget); 9792 case ISD::MLOAD: 9793 return LowerMLOAD(Op, DAG); 9794 case ISD::VECREDUCE_MUL: 9795 case ISD::VECREDUCE_AND: 9796 case ISD::VECREDUCE_OR: 9797 case ISD::VECREDUCE_XOR: 9798 return LowerVecReduce(Op, DAG, Subtarget); 9799 case ISD::VECREDUCE_FADD: 9800 case ISD::VECREDUCE_FMUL: 9801 case ISD::VECREDUCE_FMIN: 9802 case ISD::VECREDUCE_FMAX: 9803 return LowerVecReduceF(Op, DAG, Subtarget); 9804 case ISD::ATOMIC_LOAD: 9805 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 9806 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 9807 case ISD::SDIVREM: 9808 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 9809 case ISD::DYNAMIC_STACKALLOC: 9810 if (Subtarget->isTargetWindows()) 9811 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9812 llvm_unreachable("Don't know how to custom lower this!"); 9813 case ISD::STRICT_FP_ROUND: 9814 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 9815 case ISD::STRICT_FP_EXTEND: 9816 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9817 case ISD::STRICT_FSETCC: 9818 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG); 9819 case ARMISD::WIN__DBZCHK: return SDValue(); 9820 } 9821 } 9822 9823 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 9824 SelectionDAG &DAG) { 9825 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9826 unsigned Opc = 0; 9827 if (IntNo == Intrinsic::arm_smlald) 9828 Opc = ARMISD::SMLALD; 9829 else if (IntNo == Intrinsic::arm_smlaldx) 9830 Opc = ARMISD::SMLALDX; 9831 else if (IntNo == Intrinsic::arm_smlsld) 9832 Opc = ARMISD::SMLSLD; 9833 else if (IntNo == Intrinsic::arm_smlsldx) 9834 Opc = ARMISD::SMLSLDX; 9835 else 9836 return; 9837 9838 SDLoc dl(N); 9839 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9840 N->getOperand(3), 9841 DAG.getConstant(0, dl, MVT::i32)); 9842 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9843 N->getOperand(3), 9844 DAG.getConstant(1, dl, MVT::i32)); 9845 9846 SDValue LongMul = DAG.getNode(Opc, dl, 9847 DAG.getVTList(MVT::i32, MVT::i32), 9848 N->getOperand(1), N->getOperand(2), 9849 Lo, Hi); 9850 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, 9851 LongMul.getValue(0), LongMul.getValue(1))); 9852 } 9853 9854 /// ReplaceNodeResults - Replace the results of node with an illegal result 9855 /// type with new values built out of custom code. 9856 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 9857 SmallVectorImpl<SDValue> &Results, 9858 SelectionDAG &DAG) const { 9859 SDValue Res; 9860 switch (N->getOpcode()) { 9861 default: 9862 llvm_unreachable("Don't know how to custom expand this!"); 9863 case ISD::READ_REGISTER: 9864 ExpandREAD_REGISTER(N, Results, DAG); 9865 break; 9866 case ISD::BITCAST: 9867 Res = ExpandBITCAST(N, DAG, Subtarget); 9868 break; 9869 case ISD::SRL: 9870 case ISD::SRA: 9871 case ISD::SHL: 9872 Res = Expand64BitShift(N, DAG, Subtarget); 9873 break; 9874 case ISD::SREM: 9875 case ISD::UREM: 9876 Res = LowerREM(N, DAG); 9877 break; 9878 case ISD::SDIVREM: 9879 case ISD::UDIVREM: 9880 Res = LowerDivRem(SDValue(N, 0), DAG); 9881 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 9882 Results.push_back(Res.getValue(0)); 9883 Results.push_back(Res.getValue(1)); 9884 return; 9885 case ISD::SADDSAT: 9886 case ISD::SSUBSAT: 9887 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget); 9888 break; 9889 case ISD::READCYCLECOUNTER: 9890 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 9891 return; 9892 case ISD::UDIV: 9893 case ISD::SDIV: 9894 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 9895 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 9896 Results); 9897 case ISD::ATOMIC_CMP_SWAP: 9898 ReplaceCMP_SWAP_64Results(N, Results, DAG); 9899 return; 9900 case ISD::INTRINSIC_WO_CHAIN: 9901 return ReplaceLongIntrinsic(N, Results, DAG); 9902 case ISD::ABS: 9903 lowerABS(N, Results, DAG); 9904 return ; 9905 case ISD::LOAD: 9906 LowerLOAD(N, Results, DAG); 9907 break; 9908 } 9909 if (Res.getNode()) 9910 Results.push_back(Res); 9911 } 9912 9913 //===----------------------------------------------------------------------===// 9914 // ARM Scheduler Hooks 9915 //===----------------------------------------------------------------------===// 9916 9917 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 9918 /// registers the function context. 9919 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 9920 MachineBasicBlock *MBB, 9921 MachineBasicBlock *DispatchBB, 9922 int FI) const { 9923 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 9924 "ROPI/RWPI not currently supported with SjLj"); 9925 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9926 DebugLoc dl = MI.getDebugLoc(); 9927 MachineFunction *MF = MBB->getParent(); 9928 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9929 MachineConstantPool *MCP = MF->getConstantPool(); 9930 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 9931 const Function &F = MF->getFunction(); 9932 9933 bool isThumb = Subtarget->isThumb(); 9934 bool isThumb2 = Subtarget->isThumb2(); 9935 9936 unsigned PCLabelId = AFI->createPICLabelUId(); 9937 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 9938 ARMConstantPoolValue *CPV = 9939 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 9940 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4)); 9941 9942 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 9943 : &ARM::GPRRegClass; 9944 9945 // Grab constant pool and fixed stack memory operands. 9946 MachineMemOperand *CPMMO = 9947 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9948 MachineMemOperand::MOLoad, 4, Align(4)); 9949 9950 MachineMemOperand *FIMMOSt = 9951 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 9952 MachineMemOperand::MOStore, 4, Align(4)); 9953 9954 // Load the address of the dispatch MBB into the jump buffer. 9955 if (isThumb2) { 9956 // Incoming value: jbuf 9957 // ldr.n r5, LCPI1_1 9958 // orr r5, r5, #1 9959 // add r5, pc 9960 // str r5, [$jbuf, #+4] ; &jbuf[1] 9961 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9962 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9963 .addConstantPoolIndex(CPI) 9964 .addMemOperand(CPMMO) 9965 .add(predOps(ARMCC::AL)); 9966 // Set the low bit because of thumb mode. 9967 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9968 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9969 .addReg(NewVReg1, RegState::Kill) 9970 .addImm(0x01) 9971 .add(predOps(ARMCC::AL)) 9972 .add(condCodeOp()); 9973 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9974 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9975 .addReg(NewVReg2, RegState::Kill) 9976 .addImm(PCLabelId); 9977 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9978 .addReg(NewVReg3, RegState::Kill) 9979 .addFrameIndex(FI) 9980 .addImm(36) // &jbuf[1] :: pc 9981 .addMemOperand(FIMMOSt) 9982 .add(predOps(ARMCC::AL)); 9983 } else if (isThumb) { 9984 // Incoming value: jbuf 9985 // ldr.n r1, LCPI1_4 9986 // add r1, pc 9987 // mov r2, #1 9988 // orrs r1, r2 9989 // add r2, $jbuf, #+4 ; &jbuf[1] 9990 // str r1, [r2] 9991 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9992 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 9993 .addConstantPoolIndex(CPI) 9994 .addMemOperand(CPMMO) 9995 .add(predOps(ARMCC::AL)); 9996 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9997 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 9998 .addReg(NewVReg1, RegState::Kill) 9999 .addImm(PCLabelId); 10000 // Set the low bit because of thumb mode. 10001 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10002 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 10003 .addReg(ARM::CPSR, RegState::Define) 10004 .addImm(1) 10005 .add(predOps(ARMCC::AL)); 10006 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10007 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 10008 .addReg(ARM::CPSR, RegState::Define) 10009 .addReg(NewVReg2, RegState::Kill) 10010 .addReg(NewVReg3, RegState::Kill) 10011 .add(predOps(ARMCC::AL)); 10012 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10013 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 10014 .addFrameIndex(FI) 10015 .addImm(36); // &jbuf[1] :: pc 10016 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 10017 .addReg(NewVReg4, RegState::Kill) 10018 .addReg(NewVReg5, RegState::Kill) 10019 .addImm(0) 10020 .addMemOperand(FIMMOSt) 10021 .add(predOps(ARMCC::AL)); 10022 } else { 10023 // Incoming value: jbuf 10024 // ldr r1, LCPI1_1 10025 // add r1, pc, r1 10026 // str r1, [$jbuf, #+4] ; &jbuf[1] 10027 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10028 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 10029 .addConstantPoolIndex(CPI) 10030 .addImm(0) 10031 .addMemOperand(CPMMO) 10032 .add(predOps(ARMCC::AL)); 10033 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10034 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 10035 .addReg(NewVReg1, RegState::Kill) 10036 .addImm(PCLabelId) 10037 .add(predOps(ARMCC::AL)); 10038 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 10039 .addReg(NewVReg2, RegState::Kill) 10040 .addFrameIndex(FI) 10041 .addImm(36) // &jbuf[1] :: pc 10042 .addMemOperand(FIMMOSt) 10043 .add(predOps(ARMCC::AL)); 10044 } 10045 } 10046 10047 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 10048 MachineBasicBlock *MBB) const { 10049 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10050 DebugLoc dl = MI.getDebugLoc(); 10051 MachineFunction *MF = MBB->getParent(); 10052 MachineRegisterInfo *MRI = &MF->getRegInfo(); 10053 MachineFrameInfo &MFI = MF->getFrameInfo(); 10054 int FI = MFI.getFunctionContextIndex(); 10055 10056 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 10057 : &ARM::GPRnopcRegClass; 10058 10059 // Get a mapping of the call site numbers to all of the landing pads they're 10060 // associated with. 10061 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 10062 unsigned MaxCSNum = 0; 10063 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 10064 ++BB) { 10065 if (!BB->isEHPad()) continue; 10066 10067 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 10068 // pad. 10069 for (MachineBasicBlock::iterator 10070 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 10071 if (!II->isEHLabel()) continue; 10072 10073 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 10074 if (!MF->hasCallSiteLandingPad(Sym)) continue; 10075 10076 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 10077 for (SmallVectorImpl<unsigned>::iterator 10078 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 10079 CSI != CSE; ++CSI) { 10080 CallSiteNumToLPad[*CSI].push_back(&*BB); 10081 MaxCSNum = std::max(MaxCSNum, *CSI); 10082 } 10083 break; 10084 } 10085 } 10086 10087 // Get an ordered list of the machine basic blocks for the jump table. 10088 std::vector<MachineBasicBlock*> LPadList; 10089 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 10090 LPadList.reserve(CallSiteNumToLPad.size()); 10091 for (unsigned I = 1; I <= MaxCSNum; ++I) { 10092 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 10093 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10094 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 10095 LPadList.push_back(*II); 10096 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 10097 } 10098 } 10099 10100 assert(!LPadList.empty() && 10101 "No landing pad destinations for the dispatch jump table!"); 10102 10103 // Create the jump table and associated information. 10104 MachineJumpTableInfo *JTI = 10105 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 10106 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 10107 10108 // Create the MBBs for the dispatch code. 10109 10110 // Shove the dispatch's address into the return slot in the function context. 10111 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 10112 DispatchBB->setIsEHPad(); 10113 10114 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10115 unsigned trap_opcode; 10116 if (Subtarget->isThumb()) 10117 trap_opcode = ARM::tTRAP; 10118 else 10119 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 10120 10121 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 10122 DispatchBB->addSuccessor(TrapBB); 10123 10124 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 10125 DispatchBB->addSuccessor(DispContBB); 10126 10127 // Insert and MBBs. 10128 MF->insert(MF->end(), DispatchBB); 10129 MF->insert(MF->end(), DispContBB); 10130 MF->insert(MF->end(), TrapBB); 10131 10132 // Insert code into the entry block that creates and registers the function 10133 // context. 10134 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 10135 10136 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 10137 MachinePointerInfo::getFixedStack(*MF, FI), 10138 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4)); 10139 10140 MachineInstrBuilder MIB; 10141 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 10142 10143 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 10144 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 10145 10146 // Add a register mask with no preserved registers. This results in all 10147 // registers being marked as clobbered. This can't work if the dispatch block 10148 // is in a Thumb1 function and is linked with ARM code which uses the FP 10149 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 10150 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 10151 10152 bool IsPositionIndependent = isPositionIndependent(); 10153 unsigned NumLPads = LPadList.size(); 10154 if (Subtarget->isThumb2()) { 10155 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10156 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 10157 .addFrameIndex(FI) 10158 .addImm(4) 10159 .addMemOperand(FIMMOLd) 10160 .add(predOps(ARMCC::AL)); 10161 10162 if (NumLPads < 256) { 10163 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 10164 .addReg(NewVReg1) 10165 .addImm(LPadList.size()) 10166 .add(predOps(ARMCC::AL)); 10167 } else { 10168 Register VReg1 = MRI->createVirtualRegister(TRC); 10169 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 10170 .addImm(NumLPads & 0xFFFF) 10171 .add(predOps(ARMCC::AL)); 10172 10173 unsigned VReg2 = VReg1; 10174 if ((NumLPads & 0xFFFF0000) != 0) { 10175 VReg2 = MRI->createVirtualRegister(TRC); 10176 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 10177 .addReg(VReg1) 10178 .addImm(NumLPads >> 16) 10179 .add(predOps(ARMCC::AL)); 10180 } 10181 10182 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 10183 .addReg(NewVReg1) 10184 .addReg(VReg2) 10185 .add(predOps(ARMCC::AL)); 10186 } 10187 10188 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 10189 .addMBB(TrapBB) 10190 .addImm(ARMCC::HI) 10191 .addReg(ARM::CPSR); 10192 10193 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10194 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 10195 .addJumpTableIndex(MJTI) 10196 .add(predOps(ARMCC::AL)); 10197 10198 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10199 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 10200 .addReg(NewVReg3, RegState::Kill) 10201 .addReg(NewVReg1) 10202 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10203 .add(predOps(ARMCC::AL)) 10204 .add(condCodeOp()); 10205 10206 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 10207 .addReg(NewVReg4, RegState::Kill) 10208 .addReg(NewVReg1) 10209 .addJumpTableIndex(MJTI); 10210 } else if (Subtarget->isThumb()) { 10211 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10212 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 10213 .addFrameIndex(FI) 10214 .addImm(1) 10215 .addMemOperand(FIMMOLd) 10216 .add(predOps(ARMCC::AL)); 10217 10218 if (NumLPads < 256) { 10219 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 10220 .addReg(NewVReg1) 10221 .addImm(NumLPads) 10222 .add(predOps(ARMCC::AL)); 10223 } else { 10224 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10225 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10226 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10227 10228 // MachineConstantPool wants an explicit alignment. 10229 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10230 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10231 10232 Register VReg1 = MRI->createVirtualRegister(TRC); 10233 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 10234 .addReg(VReg1, RegState::Define) 10235 .addConstantPoolIndex(Idx) 10236 .add(predOps(ARMCC::AL)); 10237 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 10238 .addReg(NewVReg1) 10239 .addReg(VReg1) 10240 .add(predOps(ARMCC::AL)); 10241 } 10242 10243 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 10244 .addMBB(TrapBB) 10245 .addImm(ARMCC::HI) 10246 .addReg(ARM::CPSR); 10247 10248 Register NewVReg2 = MRI->createVirtualRegister(TRC); 10249 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 10250 .addReg(ARM::CPSR, RegState::Define) 10251 .addReg(NewVReg1) 10252 .addImm(2) 10253 .add(predOps(ARMCC::AL)); 10254 10255 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10256 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 10257 .addJumpTableIndex(MJTI) 10258 .add(predOps(ARMCC::AL)); 10259 10260 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10261 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 10262 .addReg(ARM::CPSR, RegState::Define) 10263 .addReg(NewVReg2, RegState::Kill) 10264 .addReg(NewVReg3) 10265 .add(predOps(ARMCC::AL)); 10266 10267 MachineMemOperand *JTMMOLd = 10268 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10269 MachineMemOperand::MOLoad, 4, Align(4)); 10270 10271 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10272 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 10273 .addReg(NewVReg4, RegState::Kill) 10274 .addImm(0) 10275 .addMemOperand(JTMMOLd) 10276 .add(predOps(ARMCC::AL)); 10277 10278 unsigned NewVReg6 = NewVReg5; 10279 if (IsPositionIndependent) { 10280 NewVReg6 = MRI->createVirtualRegister(TRC); 10281 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 10282 .addReg(ARM::CPSR, RegState::Define) 10283 .addReg(NewVReg5, RegState::Kill) 10284 .addReg(NewVReg3) 10285 .add(predOps(ARMCC::AL)); 10286 } 10287 10288 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 10289 .addReg(NewVReg6, RegState::Kill) 10290 .addJumpTableIndex(MJTI); 10291 } else { 10292 Register NewVReg1 = MRI->createVirtualRegister(TRC); 10293 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 10294 .addFrameIndex(FI) 10295 .addImm(4) 10296 .addMemOperand(FIMMOLd) 10297 .add(predOps(ARMCC::AL)); 10298 10299 if (NumLPads < 256) { 10300 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 10301 .addReg(NewVReg1) 10302 .addImm(NumLPads) 10303 .add(predOps(ARMCC::AL)); 10304 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 10305 Register VReg1 = MRI->createVirtualRegister(TRC); 10306 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 10307 .addImm(NumLPads & 0xFFFF) 10308 .add(predOps(ARMCC::AL)); 10309 10310 unsigned VReg2 = VReg1; 10311 if ((NumLPads & 0xFFFF0000) != 0) { 10312 VReg2 = MRI->createVirtualRegister(TRC); 10313 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 10314 .addReg(VReg1) 10315 .addImm(NumLPads >> 16) 10316 .add(predOps(ARMCC::AL)); 10317 } 10318 10319 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10320 .addReg(NewVReg1) 10321 .addReg(VReg2) 10322 .add(predOps(ARMCC::AL)); 10323 } else { 10324 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10325 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10326 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 10327 10328 // MachineConstantPool wants an explicit alignment. 10329 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10330 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10331 10332 Register VReg1 = MRI->createVirtualRegister(TRC); 10333 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 10334 .addReg(VReg1, RegState::Define) 10335 .addConstantPoolIndex(Idx) 10336 .addImm(0) 10337 .add(predOps(ARMCC::AL)); 10338 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 10339 .addReg(NewVReg1) 10340 .addReg(VReg1, RegState::Kill) 10341 .add(predOps(ARMCC::AL)); 10342 } 10343 10344 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 10345 .addMBB(TrapBB) 10346 .addImm(ARMCC::HI) 10347 .addReg(ARM::CPSR); 10348 10349 Register NewVReg3 = MRI->createVirtualRegister(TRC); 10350 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 10351 .addReg(NewVReg1) 10352 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 10353 .add(predOps(ARMCC::AL)) 10354 .add(condCodeOp()); 10355 Register NewVReg4 = MRI->createVirtualRegister(TRC); 10356 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 10357 .addJumpTableIndex(MJTI) 10358 .add(predOps(ARMCC::AL)); 10359 10360 MachineMemOperand *JTMMOLd = 10361 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF), 10362 MachineMemOperand::MOLoad, 4, Align(4)); 10363 Register NewVReg5 = MRI->createVirtualRegister(TRC); 10364 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 10365 .addReg(NewVReg3, RegState::Kill) 10366 .addReg(NewVReg4) 10367 .addImm(0) 10368 .addMemOperand(JTMMOLd) 10369 .add(predOps(ARMCC::AL)); 10370 10371 if (IsPositionIndependent) { 10372 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 10373 .addReg(NewVReg5, RegState::Kill) 10374 .addReg(NewVReg4) 10375 .addJumpTableIndex(MJTI); 10376 } else { 10377 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 10378 .addReg(NewVReg5, RegState::Kill) 10379 .addJumpTableIndex(MJTI); 10380 } 10381 } 10382 10383 // Add the jump table entries as successors to the MBB. 10384 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 10385 for (std::vector<MachineBasicBlock*>::iterator 10386 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 10387 MachineBasicBlock *CurMBB = *I; 10388 if (SeenMBBs.insert(CurMBB).second) 10389 DispContBB->addSuccessor(CurMBB); 10390 } 10391 10392 // N.B. the order the invoke BBs are processed in doesn't matter here. 10393 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 10394 SmallVector<MachineBasicBlock*, 64> MBBLPads; 10395 for (MachineBasicBlock *BB : InvokeBBs) { 10396 10397 // Remove the landing pad successor from the invoke block and replace it 10398 // with the new dispatch block. 10399 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 10400 BB->succ_end()); 10401 while (!Successors.empty()) { 10402 MachineBasicBlock *SMBB = Successors.pop_back_val(); 10403 if (SMBB->isEHPad()) { 10404 BB->removeSuccessor(SMBB); 10405 MBBLPads.push_back(SMBB); 10406 } 10407 } 10408 10409 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 10410 BB->normalizeSuccProbs(); 10411 10412 // Find the invoke call and mark all of the callee-saved registers as 10413 // 'implicit defined' so that they're spilled. This prevents code from 10414 // moving instructions to before the EH block, where they will never be 10415 // executed. 10416 for (MachineBasicBlock::reverse_iterator 10417 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 10418 if (!II->isCall()) continue; 10419 10420 DenseMap<unsigned, bool> DefRegs; 10421 for (MachineInstr::mop_iterator 10422 OI = II->operands_begin(), OE = II->operands_end(); 10423 OI != OE; ++OI) { 10424 if (!OI->isReg()) continue; 10425 DefRegs[OI->getReg()] = true; 10426 } 10427 10428 MachineInstrBuilder MIB(*MF, &*II); 10429 10430 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 10431 unsigned Reg = SavedRegs[i]; 10432 if (Subtarget->isThumb2() && 10433 !ARM::tGPRRegClass.contains(Reg) && 10434 !ARM::hGPRRegClass.contains(Reg)) 10435 continue; 10436 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 10437 continue; 10438 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 10439 continue; 10440 if (!DefRegs[Reg]) 10441 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 10442 } 10443 10444 break; 10445 } 10446 } 10447 10448 // Mark all former landing pads as non-landing pads. The dispatch is the only 10449 // landing pad now. 10450 for (SmallVectorImpl<MachineBasicBlock*>::iterator 10451 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 10452 (*I)->setIsEHPad(false); 10453 10454 // The instruction is gone now. 10455 MI.eraseFromParent(); 10456 } 10457 10458 static 10459 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 10460 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 10461 E = MBB->succ_end(); I != E; ++I) 10462 if (*I != Succ) 10463 return *I; 10464 llvm_unreachable("Expecting a BB with two successors!"); 10465 } 10466 10467 /// Return the load opcode for a given load size. If load size >= 8, 10468 /// neon opcode will be returned. 10469 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 10470 if (LdSize >= 8) 10471 return LdSize == 16 ? ARM::VLD1q32wb_fixed 10472 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 10473 if (IsThumb1) 10474 return LdSize == 4 ? ARM::tLDRi 10475 : LdSize == 2 ? ARM::tLDRHi 10476 : LdSize == 1 ? ARM::tLDRBi : 0; 10477 if (IsThumb2) 10478 return LdSize == 4 ? ARM::t2LDR_POST 10479 : LdSize == 2 ? ARM::t2LDRH_POST 10480 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 10481 return LdSize == 4 ? ARM::LDR_POST_IMM 10482 : LdSize == 2 ? ARM::LDRH_POST 10483 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 10484 } 10485 10486 /// Return the store opcode for a given store size. If store size >= 8, 10487 /// neon opcode will be returned. 10488 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 10489 if (StSize >= 8) 10490 return StSize == 16 ? ARM::VST1q32wb_fixed 10491 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 10492 if (IsThumb1) 10493 return StSize == 4 ? ARM::tSTRi 10494 : StSize == 2 ? ARM::tSTRHi 10495 : StSize == 1 ? ARM::tSTRBi : 0; 10496 if (IsThumb2) 10497 return StSize == 4 ? ARM::t2STR_POST 10498 : StSize == 2 ? ARM::t2STRH_POST 10499 : StSize == 1 ? ARM::t2STRB_POST : 0; 10500 return StSize == 4 ? ARM::STR_POST_IMM 10501 : StSize == 2 ? ARM::STRH_POST 10502 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 10503 } 10504 10505 /// Emit a post-increment load operation with given size. The instructions 10506 /// will be added to BB at Pos. 10507 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10508 const TargetInstrInfo *TII, const DebugLoc &dl, 10509 unsigned LdSize, unsigned Data, unsigned AddrIn, 10510 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10511 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 10512 assert(LdOpc != 0 && "Should have a load opcode"); 10513 if (LdSize >= 8) { 10514 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10515 .addReg(AddrOut, RegState::Define) 10516 .addReg(AddrIn) 10517 .addImm(0) 10518 .add(predOps(ARMCC::AL)); 10519 } else if (IsThumb1) { 10520 // load + update AddrIn 10521 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10522 .addReg(AddrIn) 10523 .addImm(0) 10524 .add(predOps(ARMCC::AL)); 10525 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10526 .add(t1CondCodeOp()) 10527 .addReg(AddrIn) 10528 .addImm(LdSize) 10529 .add(predOps(ARMCC::AL)); 10530 } else if (IsThumb2) { 10531 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10532 .addReg(AddrOut, RegState::Define) 10533 .addReg(AddrIn) 10534 .addImm(LdSize) 10535 .add(predOps(ARMCC::AL)); 10536 } else { // arm 10537 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 10538 .addReg(AddrOut, RegState::Define) 10539 .addReg(AddrIn) 10540 .addReg(0) 10541 .addImm(LdSize) 10542 .add(predOps(ARMCC::AL)); 10543 } 10544 } 10545 10546 /// Emit a post-increment store operation with given size. The instructions 10547 /// will be added to BB at Pos. 10548 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 10549 const TargetInstrInfo *TII, const DebugLoc &dl, 10550 unsigned StSize, unsigned Data, unsigned AddrIn, 10551 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 10552 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 10553 assert(StOpc != 0 && "Should have a store opcode"); 10554 if (StSize >= 8) { 10555 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10556 .addReg(AddrIn) 10557 .addImm(0) 10558 .addReg(Data) 10559 .add(predOps(ARMCC::AL)); 10560 } else if (IsThumb1) { 10561 // store + update AddrIn 10562 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 10563 .addReg(Data) 10564 .addReg(AddrIn) 10565 .addImm(0) 10566 .add(predOps(ARMCC::AL)); 10567 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 10568 .add(t1CondCodeOp()) 10569 .addReg(AddrIn) 10570 .addImm(StSize) 10571 .add(predOps(ARMCC::AL)); 10572 } else if (IsThumb2) { 10573 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10574 .addReg(Data) 10575 .addReg(AddrIn) 10576 .addImm(StSize) 10577 .add(predOps(ARMCC::AL)); 10578 } else { // arm 10579 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 10580 .addReg(Data) 10581 .addReg(AddrIn) 10582 .addReg(0) 10583 .addImm(StSize) 10584 .add(predOps(ARMCC::AL)); 10585 } 10586 } 10587 10588 MachineBasicBlock * 10589 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 10590 MachineBasicBlock *BB) const { 10591 // This pseudo instruction has 3 operands: dst, src, size 10592 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 10593 // Otherwise, we will generate unrolled scalar copies. 10594 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10595 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10596 MachineFunction::iterator It = ++BB->getIterator(); 10597 10598 Register dest = MI.getOperand(0).getReg(); 10599 Register src = MI.getOperand(1).getReg(); 10600 unsigned SizeVal = MI.getOperand(2).getImm(); 10601 unsigned Alignment = MI.getOperand(3).getImm(); 10602 DebugLoc dl = MI.getDebugLoc(); 10603 10604 MachineFunction *MF = BB->getParent(); 10605 MachineRegisterInfo &MRI = MF->getRegInfo(); 10606 unsigned UnitSize = 0; 10607 const TargetRegisterClass *TRC = nullptr; 10608 const TargetRegisterClass *VecTRC = nullptr; 10609 10610 bool IsThumb1 = Subtarget->isThumb1Only(); 10611 bool IsThumb2 = Subtarget->isThumb2(); 10612 bool IsThumb = Subtarget->isThumb(); 10613 10614 if (Alignment & 1) { 10615 UnitSize = 1; 10616 } else if (Alignment & 2) { 10617 UnitSize = 2; 10618 } else { 10619 // Check whether we can use NEON instructions. 10620 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 10621 Subtarget->hasNEON()) { 10622 if ((Alignment % 16 == 0) && SizeVal >= 16) 10623 UnitSize = 16; 10624 else if ((Alignment % 8 == 0) && SizeVal >= 8) 10625 UnitSize = 8; 10626 } 10627 // Can't use NEON instructions. 10628 if (UnitSize == 0) 10629 UnitSize = 4; 10630 } 10631 10632 // Select the correct opcode and register class for unit size load/store 10633 bool IsNeon = UnitSize >= 8; 10634 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 10635 if (IsNeon) 10636 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 10637 : UnitSize == 8 ? &ARM::DPRRegClass 10638 : nullptr; 10639 10640 unsigned BytesLeft = SizeVal % UnitSize; 10641 unsigned LoopSize = SizeVal - BytesLeft; 10642 10643 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 10644 // Use LDR and STR to copy. 10645 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 10646 // [destOut] = STR_POST(scratch, destIn, UnitSize) 10647 unsigned srcIn = src; 10648 unsigned destIn = dest; 10649 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 10650 Register srcOut = MRI.createVirtualRegister(TRC); 10651 Register destOut = MRI.createVirtualRegister(TRC); 10652 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10653 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 10654 IsThumb1, IsThumb2); 10655 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 10656 IsThumb1, IsThumb2); 10657 srcIn = srcOut; 10658 destIn = destOut; 10659 } 10660 10661 // Handle the leftover bytes with LDRB and STRB. 10662 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 10663 // [destOut] = STRB_POST(scratch, destIn, 1) 10664 for (unsigned i = 0; i < BytesLeft; i++) { 10665 Register srcOut = MRI.createVirtualRegister(TRC); 10666 Register destOut = MRI.createVirtualRegister(TRC); 10667 Register scratch = MRI.createVirtualRegister(TRC); 10668 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 10669 IsThumb1, IsThumb2); 10670 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 10671 IsThumb1, IsThumb2); 10672 srcIn = srcOut; 10673 destIn = destOut; 10674 } 10675 MI.eraseFromParent(); // The instruction is gone now. 10676 return BB; 10677 } 10678 10679 // Expand the pseudo op to a loop. 10680 // thisMBB: 10681 // ... 10682 // movw varEnd, # --> with thumb2 10683 // movt varEnd, # 10684 // ldrcp varEnd, idx --> without thumb2 10685 // fallthrough --> loopMBB 10686 // loopMBB: 10687 // PHI varPhi, varEnd, varLoop 10688 // PHI srcPhi, src, srcLoop 10689 // PHI destPhi, dst, destLoop 10690 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10691 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 10692 // subs varLoop, varPhi, #UnitSize 10693 // bne loopMBB 10694 // fallthrough --> exitMBB 10695 // exitMBB: 10696 // epilogue to handle left-over bytes 10697 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10698 // [destOut] = STRB_POST(scratch, destLoop, 1) 10699 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10700 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10701 MF->insert(It, loopMBB); 10702 MF->insert(It, exitMBB); 10703 10704 // Transfer the remainder of BB and its successor edges to exitMBB. 10705 exitMBB->splice(exitMBB->begin(), BB, 10706 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10707 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10708 10709 // Load an immediate to varEnd. 10710 Register varEnd = MRI.createVirtualRegister(TRC); 10711 if (Subtarget->useMovt()) { 10712 unsigned Vtmp = varEnd; 10713 if ((LoopSize & 0xFFFF0000) != 0) 10714 Vtmp = MRI.createVirtualRegister(TRC); 10715 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 10716 .addImm(LoopSize & 0xFFFF) 10717 .add(predOps(ARMCC::AL)); 10718 10719 if ((LoopSize & 0xFFFF0000) != 0) 10720 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 10721 .addReg(Vtmp) 10722 .addImm(LoopSize >> 16) 10723 .add(predOps(ARMCC::AL)); 10724 } else { 10725 MachineConstantPool *ConstantPool = MF->getConstantPool(); 10726 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 10727 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 10728 10729 // MachineConstantPool wants an explicit alignment. 10730 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty); 10731 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment); 10732 MachineMemOperand *CPMMO = 10733 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 10734 MachineMemOperand::MOLoad, 4, Align(4)); 10735 10736 if (IsThumb) 10737 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 10738 .addReg(varEnd, RegState::Define) 10739 .addConstantPoolIndex(Idx) 10740 .add(predOps(ARMCC::AL)) 10741 .addMemOperand(CPMMO); 10742 else 10743 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 10744 .addReg(varEnd, RegState::Define) 10745 .addConstantPoolIndex(Idx) 10746 .addImm(0) 10747 .add(predOps(ARMCC::AL)) 10748 .addMemOperand(CPMMO); 10749 } 10750 BB->addSuccessor(loopMBB); 10751 10752 // Generate the loop body: 10753 // varPhi = PHI(varLoop, varEnd) 10754 // srcPhi = PHI(srcLoop, src) 10755 // destPhi = PHI(destLoop, dst) 10756 MachineBasicBlock *entryBB = BB; 10757 BB = loopMBB; 10758 Register varLoop = MRI.createVirtualRegister(TRC); 10759 Register varPhi = MRI.createVirtualRegister(TRC); 10760 Register srcLoop = MRI.createVirtualRegister(TRC); 10761 Register srcPhi = MRI.createVirtualRegister(TRC); 10762 Register destLoop = MRI.createVirtualRegister(TRC); 10763 Register destPhi = MRI.createVirtualRegister(TRC); 10764 10765 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 10766 .addReg(varLoop).addMBB(loopMBB) 10767 .addReg(varEnd).addMBB(entryBB); 10768 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 10769 .addReg(srcLoop).addMBB(loopMBB) 10770 .addReg(src).addMBB(entryBB); 10771 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 10772 .addReg(destLoop).addMBB(loopMBB) 10773 .addReg(dest).addMBB(entryBB); 10774 10775 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 10776 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 10777 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 10778 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 10779 IsThumb1, IsThumb2); 10780 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 10781 IsThumb1, IsThumb2); 10782 10783 // Decrement loop variable by UnitSize. 10784 if (IsThumb1) { 10785 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 10786 .add(t1CondCodeOp()) 10787 .addReg(varPhi) 10788 .addImm(UnitSize) 10789 .add(predOps(ARMCC::AL)); 10790 } else { 10791 MachineInstrBuilder MIB = 10792 BuildMI(*BB, BB->end(), dl, 10793 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 10794 MIB.addReg(varPhi) 10795 .addImm(UnitSize) 10796 .add(predOps(ARMCC::AL)) 10797 .add(condCodeOp()); 10798 MIB->getOperand(5).setReg(ARM::CPSR); 10799 MIB->getOperand(5).setIsDef(true); 10800 } 10801 BuildMI(*BB, BB->end(), dl, 10802 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10803 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 10804 10805 // loopMBB can loop back to loopMBB or fall through to exitMBB. 10806 BB->addSuccessor(loopMBB); 10807 BB->addSuccessor(exitMBB); 10808 10809 // Add epilogue to handle BytesLeft. 10810 BB = exitMBB; 10811 auto StartOfExit = exitMBB->begin(); 10812 10813 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 10814 // [destOut] = STRB_POST(scratch, destLoop, 1) 10815 unsigned srcIn = srcLoop; 10816 unsigned destIn = destLoop; 10817 for (unsigned i = 0; i < BytesLeft; i++) { 10818 Register srcOut = MRI.createVirtualRegister(TRC); 10819 Register destOut = MRI.createVirtualRegister(TRC); 10820 Register scratch = MRI.createVirtualRegister(TRC); 10821 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 10822 IsThumb1, IsThumb2); 10823 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 10824 IsThumb1, IsThumb2); 10825 srcIn = srcOut; 10826 destIn = destOut; 10827 } 10828 10829 MI.eraseFromParent(); // The instruction is gone now. 10830 return BB; 10831 } 10832 10833 MachineBasicBlock * 10834 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 10835 MachineBasicBlock *MBB) const { 10836 const TargetMachine &TM = getTargetMachine(); 10837 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 10838 DebugLoc DL = MI.getDebugLoc(); 10839 10840 assert(Subtarget->isTargetWindows() && 10841 "__chkstk is only supported on Windows"); 10842 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 10843 10844 // __chkstk takes the number of words to allocate on the stack in R4, and 10845 // returns the stack adjustment in number of bytes in R4. This will not 10846 // clober any other registers (other than the obvious lr). 10847 // 10848 // Although, technically, IP should be considered a register which may be 10849 // clobbered, the call itself will not touch it. Windows on ARM is a pure 10850 // thumb-2 environment, so there is no interworking required. As a result, we 10851 // do not expect a veneer to be emitted by the linker, clobbering IP. 10852 // 10853 // Each module receives its own copy of __chkstk, so no import thunk is 10854 // required, again, ensuring that IP is not clobbered. 10855 // 10856 // Finally, although some linkers may theoretically provide a trampoline for 10857 // out of range calls (which is quite common due to a 32M range limitation of 10858 // branches for Thumb), we can generate the long-call version via 10859 // -mcmodel=large, alleviating the need for the trampoline which may clobber 10860 // IP. 10861 10862 switch (TM.getCodeModel()) { 10863 case CodeModel::Tiny: 10864 llvm_unreachable("Tiny code model not available on ARM."); 10865 case CodeModel::Small: 10866 case CodeModel::Medium: 10867 case CodeModel::Kernel: 10868 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 10869 .add(predOps(ARMCC::AL)) 10870 .addExternalSymbol("__chkstk") 10871 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10872 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10873 .addReg(ARM::R12, 10874 RegState::Implicit | RegState::Define | RegState::Dead) 10875 .addReg(ARM::CPSR, 10876 RegState::Implicit | RegState::Define | RegState::Dead); 10877 break; 10878 case CodeModel::Large: { 10879 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10880 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 10881 10882 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 10883 .addExternalSymbol("__chkstk"); 10884 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 10885 .add(predOps(ARMCC::AL)) 10886 .addReg(Reg, RegState::Kill) 10887 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10888 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10889 .addReg(ARM::R12, 10890 RegState::Implicit | RegState::Define | RegState::Dead) 10891 .addReg(ARM::CPSR, 10892 RegState::Implicit | RegState::Define | RegState::Dead); 10893 break; 10894 } 10895 } 10896 10897 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 10898 .addReg(ARM::SP, RegState::Kill) 10899 .addReg(ARM::R4, RegState::Kill) 10900 .setMIFlags(MachineInstr::FrameSetup) 10901 .add(predOps(ARMCC::AL)) 10902 .add(condCodeOp()); 10903 10904 MI.eraseFromParent(); 10905 return MBB; 10906 } 10907 10908 MachineBasicBlock * 10909 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 10910 MachineBasicBlock *MBB) const { 10911 DebugLoc DL = MI.getDebugLoc(); 10912 MachineFunction *MF = MBB->getParent(); 10913 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10914 10915 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 10916 MF->insert(++MBB->getIterator(), ContBB); 10917 ContBB->splice(ContBB->begin(), MBB, 10918 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10919 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 10920 MBB->addSuccessor(ContBB); 10921 10922 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10923 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 10924 MF->push_back(TrapBB); 10925 MBB->addSuccessor(TrapBB); 10926 10927 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 10928 .addReg(MI.getOperand(0).getReg()) 10929 .addImm(0) 10930 .add(predOps(ARMCC::AL)); 10931 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 10932 .addMBB(TrapBB) 10933 .addImm(ARMCC::EQ) 10934 .addReg(ARM::CPSR); 10935 10936 MI.eraseFromParent(); 10937 return ContBB; 10938 } 10939 10940 // The CPSR operand of SelectItr might be missing a kill marker 10941 // because there were multiple uses of CPSR, and ISel didn't know 10942 // which to mark. Figure out whether SelectItr should have had a 10943 // kill marker, and set it if it should. Returns the correct kill 10944 // marker value. 10945 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 10946 MachineBasicBlock* BB, 10947 const TargetRegisterInfo* TRI) { 10948 // Scan forward through BB for a use/def of CPSR. 10949 MachineBasicBlock::iterator miI(std::next(SelectItr)); 10950 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 10951 const MachineInstr& mi = *miI; 10952 if (mi.readsRegister(ARM::CPSR)) 10953 return false; 10954 if (mi.definesRegister(ARM::CPSR)) 10955 break; // Should have kill-flag - update below. 10956 } 10957 10958 // If we hit the end of the block, check whether CPSR is live into a 10959 // successor. 10960 if (miI == BB->end()) { 10961 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10962 sEnd = BB->succ_end(); 10963 sItr != sEnd; ++sItr) { 10964 MachineBasicBlock* succ = *sItr; 10965 if (succ->isLiveIn(ARM::CPSR)) 10966 return false; 10967 } 10968 } 10969 10970 // We found a def, or hit the end of the basic block and CPSR wasn't live 10971 // out. SelectMI should have a kill flag on CPSR. 10972 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10973 return true; 10974 } 10975 10976 MachineBasicBlock * 10977 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10978 MachineBasicBlock *BB) const { 10979 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10980 DebugLoc dl = MI.getDebugLoc(); 10981 bool isThumb2 = Subtarget->isThumb2(); 10982 switch (MI.getOpcode()) { 10983 default: { 10984 MI.print(errs()); 10985 llvm_unreachable("Unexpected instr type to insert"); 10986 } 10987 10988 // Thumb1 post-indexed loads are really just single-register LDMs. 10989 case ARM::tLDR_postidx: { 10990 MachineOperand Def(MI.getOperand(1)); 10991 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 10992 .add(Def) // Rn_wb 10993 .add(MI.getOperand(2)) // Rn 10994 .add(MI.getOperand(3)) // PredImm 10995 .add(MI.getOperand(4)) // PredReg 10996 .add(MI.getOperand(0)) // Rt 10997 .cloneMemRefs(MI); 10998 MI.eraseFromParent(); 10999 return BB; 11000 } 11001 11002 // The Thumb2 pre-indexed stores have the same MI operands, they just 11003 // define them differently in the .td files from the isel patterns, so 11004 // they need pseudos. 11005 case ARM::t2STR_preidx: 11006 MI.setDesc(TII->get(ARM::t2STR_PRE)); 11007 return BB; 11008 case ARM::t2STRB_preidx: 11009 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 11010 return BB; 11011 case ARM::t2STRH_preidx: 11012 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 11013 return BB; 11014 11015 case ARM::STRi_preidx: 11016 case ARM::STRBi_preidx: { 11017 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 11018 : ARM::STRB_PRE_IMM; 11019 // Decode the offset. 11020 unsigned Offset = MI.getOperand(4).getImm(); 11021 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 11022 Offset = ARM_AM::getAM2Offset(Offset); 11023 if (isSub) 11024 Offset = -Offset; 11025 11026 MachineMemOperand *MMO = *MI.memoperands_begin(); 11027 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 11028 .add(MI.getOperand(0)) // Rn_wb 11029 .add(MI.getOperand(1)) // Rt 11030 .add(MI.getOperand(2)) // Rn 11031 .addImm(Offset) // offset (skip GPR==zero_reg) 11032 .add(MI.getOperand(5)) // pred 11033 .add(MI.getOperand(6)) 11034 .addMemOperand(MMO); 11035 MI.eraseFromParent(); 11036 return BB; 11037 } 11038 case ARM::STRr_preidx: 11039 case ARM::STRBr_preidx: 11040 case ARM::STRH_preidx: { 11041 unsigned NewOpc; 11042 switch (MI.getOpcode()) { 11043 default: llvm_unreachable("unexpected opcode!"); 11044 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 11045 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 11046 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 11047 } 11048 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 11049 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 11050 MIB.add(MI.getOperand(i)); 11051 MI.eraseFromParent(); 11052 return BB; 11053 } 11054 11055 case ARM::tMOVCCr_pseudo: { 11056 // To "insert" a SELECT_CC instruction, we actually have to insert the 11057 // diamond control-flow pattern. The incoming instruction knows the 11058 // destination vreg to set, the condition code register to branch on, the 11059 // true/false values to select between, and a branch opcode to use. 11060 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11061 MachineFunction::iterator It = ++BB->getIterator(); 11062 11063 // thisMBB: 11064 // ... 11065 // TrueVal = ... 11066 // cmpTY ccX, r1, r2 11067 // bCC copy1MBB 11068 // fallthrough --> copy0MBB 11069 MachineBasicBlock *thisMBB = BB; 11070 MachineFunction *F = BB->getParent(); 11071 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11072 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11073 F->insert(It, copy0MBB); 11074 F->insert(It, sinkMBB); 11075 11076 // Check whether CPSR is live past the tMOVCCr_pseudo. 11077 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11078 if (!MI.killsRegister(ARM::CPSR) && 11079 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 11080 copy0MBB->addLiveIn(ARM::CPSR); 11081 sinkMBB->addLiveIn(ARM::CPSR); 11082 } 11083 11084 // Transfer the remainder of BB and its successor edges to sinkMBB. 11085 sinkMBB->splice(sinkMBB->begin(), BB, 11086 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11087 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11088 11089 BB->addSuccessor(copy0MBB); 11090 BB->addSuccessor(sinkMBB); 11091 11092 BuildMI(BB, dl, TII->get(ARM::tBcc)) 11093 .addMBB(sinkMBB) 11094 .addImm(MI.getOperand(3).getImm()) 11095 .addReg(MI.getOperand(4).getReg()); 11096 11097 // copy0MBB: 11098 // %FalseValue = ... 11099 // # fallthrough to sinkMBB 11100 BB = copy0MBB; 11101 11102 // Update machine-CFG edges 11103 BB->addSuccessor(sinkMBB); 11104 11105 // sinkMBB: 11106 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11107 // ... 11108 BB = sinkMBB; 11109 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 11110 .addReg(MI.getOperand(1).getReg()) 11111 .addMBB(copy0MBB) 11112 .addReg(MI.getOperand(2).getReg()) 11113 .addMBB(thisMBB); 11114 11115 MI.eraseFromParent(); // The pseudo instruction is gone now. 11116 return BB; 11117 } 11118 11119 case ARM::BCCi64: 11120 case ARM::BCCZi64: { 11121 // If there is an unconditional branch to the other successor, remove it. 11122 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11123 11124 // Compare both parts that make up the double comparison separately for 11125 // equality. 11126 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 11127 11128 Register LHS1 = MI.getOperand(1).getReg(); 11129 Register LHS2 = MI.getOperand(2).getReg(); 11130 if (RHSisZero) { 11131 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11132 .addReg(LHS1) 11133 .addImm(0) 11134 .add(predOps(ARMCC::AL)); 11135 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11136 .addReg(LHS2).addImm(0) 11137 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11138 } else { 11139 Register RHS1 = MI.getOperand(3).getReg(); 11140 Register RHS2 = MI.getOperand(4).getReg(); 11141 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11142 .addReg(LHS1) 11143 .addReg(RHS1) 11144 .add(predOps(ARMCC::AL)); 11145 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 11146 .addReg(LHS2).addReg(RHS2) 11147 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 11148 } 11149 11150 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 11151 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 11152 if (MI.getOperand(0).getImm() == ARMCC::NE) 11153 std::swap(destMBB, exitMBB); 11154 11155 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 11156 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 11157 if (isThumb2) 11158 BuildMI(BB, dl, TII->get(ARM::t2B)) 11159 .addMBB(exitMBB) 11160 .add(predOps(ARMCC::AL)); 11161 else 11162 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 11163 11164 MI.eraseFromParent(); // The pseudo instruction is gone now. 11165 return BB; 11166 } 11167 11168 case ARM::Int_eh_sjlj_setjmp: 11169 case ARM::Int_eh_sjlj_setjmp_nofp: 11170 case ARM::tInt_eh_sjlj_setjmp: 11171 case ARM::t2Int_eh_sjlj_setjmp: 11172 case ARM::t2Int_eh_sjlj_setjmp_nofp: 11173 return BB; 11174 11175 case ARM::Int_eh_sjlj_setup_dispatch: 11176 EmitSjLjDispatchBlock(MI, BB); 11177 return BB; 11178 11179 case ARM::ABS: 11180 case ARM::t2ABS: { 11181 // To insert an ABS instruction, we have to insert the 11182 // diamond control-flow pattern. The incoming instruction knows the 11183 // source vreg to test against 0, the destination vreg to set, 11184 // the condition code register to branch on, the 11185 // true/false values to select between, and a branch opcode to use. 11186 // It transforms 11187 // V1 = ABS V0 11188 // into 11189 // V2 = MOVS V0 11190 // BCC (branch to SinkBB if V0 >= 0) 11191 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 11192 // SinkBB: V1 = PHI(V2, V3) 11193 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11194 MachineFunction::iterator BBI = ++BB->getIterator(); 11195 MachineFunction *Fn = BB->getParent(); 11196 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11197 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 11198 Fn->insert(BBI, RSBBB); 11199 Fn->insert(BBI, SinkBB); 11200 11201 Register ABSSrcReg = MI.getOperand(1).getReg(); 11202 Register ABSDstReg = MI.getOperand(0).getReg(); 11203 bool ABSSrcKIll = MI.getOperand(1).isKill(); 11204 bool isThumb2 = Subtarget->isThumb2(); 11205 MachineRegisterInfo &MRI = Fn->getRegInfo(); 11206 // In Thumb mode S must not be specified if source register is the SP or 11207 // PC and if destination register is the SP, so restrict register class 11208 Register NewRsbDstReg = MRI.createVirtualRegister( 11209 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 11210 11211 // Transfer the remainder of BB and its successor edges to sinkMBB. 11212 SinkBB->splice(SinkBB->begin(), BB, 11213 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11214 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 11215 11216 BB->addSuccessor(RSBBB); 11217 BB->addSuccessor(SinkBB); 11218 11219 // fall through to SinkMBB 11220 RSBBB->addSuccessor(SinkBB); 11221 11222 // insert a cmp at the end of BB 11223 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 11224 .addReg(ABSSrcReg) 11225 .addImm(0) 11226 .add(predOps(ARMCC::AL)); 11227 11228 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 11229 BuildMI(BB, dl, 11230 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 11231 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 11232 11233 // insert rsbri in RSBBB 11234 // Note: BCC and rsbri will be converted into predicated rsbmi 11235 // by if-conversion pass 11236 BuildMI(*RSBBB, RSBBB->begin(), dl, 11237 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 11238 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 11239 .addImm(0) 11240 .add(predOps(ARMCC::AL)) 11241 .add(condCodeOp()); 11242 11243 // insert PHI in SinkBB, 11244 // reuse ABSDstReg to not change uses of ABS instruction 11245 BuildMI(*SinkBB, SinkBB->begin(), dl, 11246 TII->get(ARM::PHI), ABSDstReg) 11247 .addReg(NewRsbDstReg).addMBB(RSBBB) 11248 .addReg(ABSSrcReg).addMBB(BB); 11249 11250 // remove ABS instruction 11251 MI.eraseFromParent(); 11252 11253 // return last added BB 11254 return SinkBB; 11255 } 11256 case ARM::COPY_STRUCT_BYVAL_I32: 11257 ++NumLoopByVals; 11258 return EmitStructByval(MI, BB); 11259 case ARM::WIN__CHKSTK: 11260 return EmitLowered__chkstk(MI, BB); 11261 case ARM::WIN__DBZCHK: 11262 return EmitLowered__dbzchk(MI, BB); 11263 } 11264 } 11265 11266 /// Attaches vregs to MEMCPY that it will use as scratch registers 11267 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 11268 /// instead of as a custom inserter because we need the use list from the SDNode. 11269 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 11270 MachineInstr &MI, const SDNode *Node) { 11271 bool isThumb1 = Subtarget->isThumb1Only(); 11272 11273 DebugLoc DL = MI.getDebugLoc(); 11274 MachineFunction *MF = MI.getParent()->getParent(); 11275 MachineRegisterInfo &MRI = MF->getRegInfo(); 11276 MachineInstrBuilder MIB(*MF, MI); 11277 11278 // If the new dst/src is unused mark it as dead. 11279 if (!Node->hasAnyUseOfValue(0)) { 11280 MI.getOperand(0).setIsDead(true); 11281 } 11282 if (!Node->hasAnyUseOfValue(1)) { 11283 MI.getOperand(1).setIsDead(true); 11284 } 11285 11286 // The MEMCPY both defines and kills the scratch registers. 11287 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 11288 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 11289 : &ARM::GPRRegClass); 11290 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 11291 } 11292 } 11293 11294 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11295 SDNode *Node) const { 11296 if (MI.getOpcode() == ARM::MEMCPY) { 11297 attachMEMCPYScratchRegs(Subtarget, MI, Node); 11298 return; 11299 } 11300 11301 const MCInstrDesc *MCID = &MI.getDesc(); 11302 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 11303 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 11304 // operand is still set to noreg. If needed, set the optional operand's 11305 // register to CPSR, and remove the redundant implicit def. 11306 // 11307 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 11308 11309 // Rename pseudo opcodes. 11310 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 11311 unsigned ccOutIdx; 11312 if (NewOpc) { 11313 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 11314 MCID = &TII->get(NewOpc); 11315 11316 assert(MCID->getNumOperands() == 11317 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 11318 && "converted opcode should be the same except for cc_out" 11319 " (and, on Thumb1, pred)"); 11320 11321 MI.setDesc(*MCID); 11322 11323 // Add the optional cc_out operand 11324 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 11325 11326 // On Thumb1, move all input operands to the end, then add the predicate 11327 if (Subtarget->isThumb1Only()) { 11328 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 11329 MI.addOperand(MI.getOperand(1)); 11330 MI.RemoveOperand(1); 11331 } 11332 11333 // Restore the ties 11334 for (unsigned i = MI.getNumOperands(); i--;) { 11335 const MachineOperand& op = MI.getOperand(i); 11336 if (op.isReg() && op.isUse()) { 11337 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 11338 if (DefIdx != -1) 11339 MI.tieOperands(DefIdx, i); 11340 } 11341 } 11342 11343 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 11344 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 11345 ccOutIdx = 1; 11346 } else 11347 ccOutIdx = MCID->getNumOperands() - 1; 11348 } else 11349 ccOutIdx = MCID->getNumOperands() - 1; 11350 11351 // Any ARM instruction that sets the 's' bit should specify an optional 11352 // "cc_out" operand in the last operand position. 11353 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 11354 assert(!NewOpc && "Optional cc_out operand required"); 11355 return; 11356 } 11357 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 11358 // since we already have an optional CPSR def. 11359 bool definesCPSR = false; 11360 bool deadCPSR = false; 11361 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 11362 ++i) { 11363 const MachineOperand &MO = MI.getOperand(i); 11364 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 11365 definesCPSR = true; 11366 if (MO.isDead()) 11367 deadCPSR = true; 11368 MI.RemoveOperand(i); 11369 break; 11370 } 11371 } 11372 if (!definesCPSR) { 11373 assert(!NewOpc && "Optional cc_out operand required"); 11374 return; 11375 } 11376 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 11377 if (deadCPSR) { 11378 assert(!MI.getOperand(ccOutIdx).getReg() && 11379 "expect uninitialized optional cc_out operand"); 11380 // Thumb1 instructions must have the S bit even if the CPSR is dead. 11381 if (!Subtarget->isThumb1Only()) 11382 return; 11383 } 11384 11385 // If this instruction was defined with an optional CPSR def and its dag node 11386 // had a live implicit CPSR def, then activate the optional CPSR def. 11387 MachineOperand &MO = MI.getOperand(ccOutIdx); 11388 MO.setReg(ARM::CPSR); 11389 MO.setIsDef(true); 11390 } 11391 11392 //===----------------------------------------------------------------------===// 11393 // ARM Optimization Hooks 11394 //===----------------------------------------------------------------------===// 11395 11396 // Helper function that checks if N is a null or all ones constant. 11397 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 11398 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 11399 } 11400 11401 // Return true if N is conditionally 0 or all ones. 11402 // Detects these expressions where cc is an i1 value: 11403 // 11404 // (select cc 0, y) [AllOnes=0] 11405 // (select cc y, 0) [AllOnes=0] 11406 // (zext cc) [AllOnes=0] 11407 // (sext cc) [AllOnes=0/1] 11408 // (select cc -1, y) [AllOnes=1] 11409 // (select cc y, -1) [AllOnes=1] 11410 // 11411 // Invert is set when N is the null/all ones constant when CC is false. 11412 // OtherOp is set to the alternative value of N. 11413 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 11414 SDValue &CC, bool &Invert, 11415 SDValue &OtherOp, 11416 SelectionDAG &DAG) { 11417 switch (N->getOpcode()) { 11418 default: return false; 11419 case ISD::SELECT: { 11420 CC = N->getOperand(0); 11421 SDValue N1 = N->getOperand(1); 11422 SDValue N2 = N->getOperand(2); 11423 if (isZeroOrAllOnes(N1, AllOnes)) { 11424 Invert = false; 11425 OtherOp = N2; 11426 return true; 11427 } 11428 if (isZeroOrAllOnes(N2, AllOnes)) { 11429 Invert = true; 11430 OtherOp = N1; 11431 return true; 11432 } 11433 return false; 11434 } 11435 case ISD::ZERO_EXTEND: 11436 // (zext cc) can never be the all ones value. 11437 if (AllOnes) 11438 return false; 11439 LLVM_FALLTHROUGH; 11440 case ISD::SIGN_EXTEND: { 11441 SDLoc dl(N); 11442 EVT VT = N->getValueType(0); 11443 CC = N->getOperand(0); 11444 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 11445 return false; 11446 Invert = !AllOnes; 11447 if (AllOnes) 11448 // When looking for an AllOnes constant, N is an sext, and the 'other' 11449 // value is 0. 11450 OtherOp = DAG.getConstant(0, dl, VT); 11451 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11452 // When looking for a 0 constant, N can be zext or sext. 11453 OtherOp = DAG.getConstant(1, dl, VT); 11454 else 11455 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 11456 VT); 11457 return true; 11458 } 11459 } 11460 } 11461 11462 // Combine a constant select operand into its use: 11463 // 11464 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11465 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11466 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 11467 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11468 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11469 // 11470 // The transform is rejected if the select doesn't have a constant operand that 11471 // is null, or all ones when AllOnes is set. 11472 // 11473 // Also recognize sext/zext from i1: 11474 // 11475 // (add (zext cc), x) -> (select cc (add x, 1), x) 11476 // (add (sext cc), x) -> (select cc (add x, -1), x) 11477 // 11478 // These transformations eventually create predicated instructions. 11479 // 11480 // @param N The node to transform. 11481 // @param Slct The N operand that is a select. 11482 // @param OtherOp The other N operand (x above). 11483 // @param DCI Context. 11484 // @param AllOnes Require the select constant to be all ones instead of null. 11485 // @returns The new node, or SDValue() on failure. 11486 static 11487 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 11488 TargetLowering::DAGCombinerInfo &DCI, 11489 bool AllOnes = false) { 11490 SelectionDAG &DAG = DCI.DAG; 11491 EVT VT = N->getValueType(0); 11492 SDValue NonConstantVal; 11493 SDValue CCOp; 11494 bool SwapSelectOps; 11495 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 11496 NonConstantVal, DAG)) 11497 return SDValue(); 11498 11499 // Slct is now know to be the desired identity constant when CC is true. 11500 SDValue TrueVal = OtherOp; 11501 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 11502 OtherOp, NonConstantVal); 11503 // Unless SwapSelectOps says CC should be false. 11504 if (SwapSelectOps) 11505 std::swap(TrueVal, FalseVal); 11506 11507 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 11508 CCOp, TrueVal, FalseVal); 11509 } 11510 11511 // Attempt combineSelectAndUse on each operand of a commutative operator N. 11512 static 11513 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 11514 TargetLowering::DAGCombinerInfo &DCI) { 11515 SDValue N0 = N->getOperand(0); 11516 SDValue N1 = N->getOperand(1); 11517 if (N0.getNode()->hasOneUse()) 11518 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 11519 return Result; 11520 if (N1.getNode()->hasOneUse()) 11521 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 11522 return Result; 11523 return SDValue(); 11524 } 11525 11526 static bool IsVUZPShuffleNode(SDNode *N) { 11527 // VUZP shuffle node. 11528 if (N->getOpcode() == ARMISD::VUZP) 11529 return true; 11530 11531 // "VUZP" on i32 is an alias for VTRN. 11532 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 11533 return true; 11534 11535 return false; 11536 } 11537 11538 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 11539 TargetLowering::DAGCombinerInfo &DCI, 11540 const ARMSubtarget *Subtarget) { 11541 // Look for ADD(VUZP.0, VUZP.1). 11542 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 11543 N0 == N1) 11544 return SDValue(); 11545 11546 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 11547 if (!N->getValueType(0).is64BitVector()) 11548 return SDValue(); 11549 11550 // Generate vpadd. 11551 SelectionDAG &DAG = DCI.DAG; 11552 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11553 SDLoc dl(N); 11554 SDNode *Unzip = N0.getNode(); 11555 EVT VT = N->getValueType(0); 11556 11557 SmallVector<SDValue, 8> Ops; 11558 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 11559 TLI.getPointerTy(DAG.getDataLayout()))); 11560 Ops.push_back(Unzip->getOperand(0)); 11561 Ops.push_back(Unzip->getOperand(1)); 11562 11563 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11564 } 11565 11566 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11567 TargetLowering::DAGCombinerInfo &DCI, 11568 const ARMSubtarget *Subtarget) { 11569 // Check for two extended operands. 11570 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 11571 N1.getOpcode() == ISD::SIGN_EXTEND) && 11572 !(N0.getOpcode() == ISD::ZERO_EXTEND && 11573 N1.getOpcode() == ISD::ZERO_EXTEND)) 11574 return SDValue(); 11575 11576 SDValue N00 = N0.getOperand(0); 11577 SDValue N10 = N1.getOperand(0); 11578 11579 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 11580 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 11581 N00 == N10) 11582 return SDValue(); 11583 11584 // We only recognize Q register paddl here; this can't be reached until 11585 // after type legalization. 11586 if (!N00.getValueType().is64BitVector() || 11587 !N0.getValueType().is128BitVector()) 11588 return SDValue(); 11589 11590 // Generate vpaddl. 11591 SelectionDAG &DAG = DCI.DAG; 11592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11593 SDLoc dl(N); 11594 EVT VT = N->getValueType(0); 11595 11596 SmallVector<SDValue, 8> Ops; 11597 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 11598 unsigned Opcode; 11599 if (N0.getOpcode() == ISD::SIGN_EXTEND) 11600 Opcode = Intrinsic::arm_neon_vpaddls; 11601 else 11602 Opcode = Intrinsic::arm_neon_vpaddlu; 11603 Ops.push_back(DAG.getConstant(Opcode, dl, 11604 TLI.getPointerTy(DAG.getDataLayout()))); 11605 EVT ElemTy = N00.getValueType().getVectorElementType(); 11606 unsigned NumElts = VT.getVectorNumElements(); 11607 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 11608 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 11609 N00.getOperand(0), N00.getOperand(1)); 11610 Ops.push_back(Concat); 11611 11612 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 11613 } 11614 11615 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 11616 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 11617 // much easier to match. 11618 static SDValue 11619 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 11620 TargetLowering::DAGCombinerInfo &DCI, 11621 const ARMSubtarget *Subtarget) { 11622 // Only perform optimization if after legalize, and if NEON is available. We 11623 // also expected both operands to be BUILD_VECTORs. 11624 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 11625 || N0.getOpcode() != ISD::BUILD_VECTOR 11626 || N1.getOpcode() != ISD::BUILD_VECTOR) 11627 return SDValue(); 11628 11629 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 11630 EVT VT = N->getValueType(0); 11631 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 11632 return SDValue(); 11633 11634 // Check that the vector operands are of the right form. 11635 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 11636 // operands, where N is the size of the formed vector. 11637 // Each EXTRACT_VECTOR should have the same input vector and odd or even 11638 // index such that we have a pair wise add pattern. 11639 11640 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 11641 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11642 return SDValue(); 11643 SDValue Vec = N0->getOperand(0)->getOperand(0); 11644 SDNode *V = Vec.getNode(); 11645 unsigned nextIndex = 0; 11646 11647 // For each operands to the ADD which are BUILD_VECTORs, 11648 // check to see if each of their operands are an EXTRACT_VECTOR with 11649 // the same vector and appropriate index. 11650 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 11651 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 11652 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11653 11654 SDValue ExtVec0 = N0->getOperand(i); 11655 SDValue ExtVec1 = N1->getOperand(i); 11656 11657 // First operand is the vector, verify its the same. 11658 if (V != ExtVec0->getOperand(0).getNode() || 11659 V != ExtVec1->getOperand(0).getNode()) 11660 return SDValue(); 11661 11662 // Second is the constant, verify its correct. 11663 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 11664 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 11665 11666 // For the constant, we want to see all the even or all the odd. 11667 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 11668 || C1->getZExtValue() != nextIndex+1) 11669 return SDValue(); 11670 11671 // Increment index. 11672 nextIndex+=2; 11673 } else 11674 return SDValue(); 11675 } 11676 11677 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 11678 // we're using the entire input vector, otherwise there's a size/legality 11679 // mismatch somewhere. 11680 if (nextIndex != Vec.getValueType().getVectorNumElements() || 11681 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 11682 return SDValue(); 11683 11684 // Create VPADDL node. 11685 SelectionDAG &DAG = DCI.DAG; 11686 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11687 11688 SDLoc dl(N); 11689 11690 // Build operand list. 11691 SmallVector<SDValue, 8> Ops; 11692 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 11693 TLI.getPointerTy(DAG.getDataLayout()))); 11694 11695 // Input is the vector. 11696 Ops.push_back(Vec); 11697 11698 // Get widened type and narrowed type. 11699 MVT widenType; 11700 unsigned numElem = VT.getVectorNumElements(); 11701 11702 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 11703 switch (inputLaneType.getSimpleVT().SimpleTy) { 11704 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 11705 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 11706 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 11707 default: 11708 llvm_unreachable("Invalid vector element type for padd optimization."); 11709 } 11710 11711 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 11712 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 11713 return DAG.getNode(ExtOp, dl, VT, tmp); 11714 } 11715 11716 static SDValue findMUL_LOHI(SDValue V) { 11717 if (V->getOpcode() == ISD::UMUL_LOHI || 11718 V->getOpcode() == ISD::SMUL_LOHI) 11719 return V; 11720 return SDValue(); 11721 } 11722 11723 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 11724 TargetLowering::DAGCombinerInfo &DCI, 11725 const ARMSubtarget *Subtarget) { 11726 if (!Subtarget->hasBaseDSP()) 11727 return SDValue(); 11728 11729 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 11730 // accumulates the product into a 64-bit value. The 16-bit values will 11731 // be sign extended somehow or SRA'd into 32-bit values 11732 // (addc (adde (mul 16bit, 16bit), lo), hi) 11733 SDValue Mul = AddcNode->getOperand(0); 11734 SDValue Lo = AddcNode->getOperand(1); 11735 if (Mul.getOpcode() != ISD::MUL) { 11736 Lo = AddcNode->getOperand(0); 11737 Mul = AddcNode->getOperand(1); 11738 if (Mul.getOpcode() != ISD::MUL) 11739 return SDValue(); 11740 } 11741 11742 SDValue SRA = AddeNode->getOperand(0); 11743 SDValue Hi = AddeNode->getOperand(1); 11744 if (SRA.getOpcode() != ISD::SRA) { 11745 SRA = AddeNode->getOperand(1); 11746 Hi = AddeNode->getOperand(0); 11747 if (SRA.getOpcode() != ISD::SRA) 11748 return SDValue(); 11749 } 11750 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 11751 if (Const->getZExtValue() != 31) 11752 return SDValue(); 11753 } else 11754 return SDValue(); 11755 11756 if (SRA.getOperand(0) != Mul) 11757 return SDValue(); 11758 11759 SelectionDAG &DAG = DCI.DAG; 11760 SDLoc dl(AddcNode); 11761 unsigned Opcode = 0; 11762 SDValue Op0; 11763 SDValue Op1; 11764 11765 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 11766 Opcode = ARMISD::SMLALBB; 11767 Op0 = Mul.getOperand(0); 11768 Op1 = Mul.getOperand(1); 11769 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 11770 Opcode = ARMISD::SMLALBT; 11771 Op0 = Mul.getOperand(0); 11772 Op1 = Mul.getOperand(1).getOperand(0); 11773 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 11774 Opcode = ARMISD::SMLALTB; 11775 Op0 = Mul.getOperand(0).getOperand(0); 11776 Op1 = Mul.getOperand(1); 11777 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 11778 Opcode = ARMISD::SMLALTT; 11779 Op0 = Mul->getOperand(0).getOperand(0); 11780 Op1 = Mul->getOperand(1).getOperand(0); 11781 } 11782 11783 if (!Op0 || !Op1) 11784 return SDValue(); 11785 11786 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 11787 Op0, Op1, Lo, Hi); 11788 // Replace the ADDs' nodes uses by the MLA node's values. 11789 SDValue HiMLALResult(SMLAL.getNode(), 1); 11790 SDValue LoMLALResult(SMLAL.getNode(), 0); 11791 11792 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 11793 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 11794 11795 // Return original node to notify the driver to stop replacing. 11796 SDValue resNode(AddcNode, 0); 11797 return resNode; 11798 } 11799 11800 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 11801 TargetLowering::DAGCombinerInfo &DCI, 11802 const ARMSubtarget *Subtarget) { 11803 // Look for multiply add opportunities. 11804 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 11805 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 11806 // a glue link from the first add to the second add. 11807 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 11808 // a S/UMLAL instruction. 11809 // UMUL_LOHI 11810 // / :lo \ :hi 11811 // V \ [no multiline comment] 11812 // loAdd -> ADDC | 11813 // \ :carry / 11814 // V V 11815 // ADDE <- hiAdd 11816 // 11817 // In the special case where only the higher part of a signed result is used 11818 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 11819 // a constant with the exact value of 0x80000000, we recognize we are dealing 11820 // with a "rounded multiply and add" (or subtract) and transform it into 11821 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 11822 11823 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 11824 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 11825 "Expect an ADDE or SUBE"); 11826 11827 assert(AddeSubeNode->getNumOperands() == 3 && 11828 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 11829 "ADDE node has the wrong inputs"); 11830 11831 // Check that we are chained to the right ADDC or SUBC node. 11832 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 11833 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 11834 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 11835 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 11836 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 11837 return SDValue(); 11838 11839 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 11840 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 11841 11842 // Check if the two operands are from the same mul_lohi node. 11843 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 11844 return SDValue(); 11845 11846 assert(AddcSubcNode->getNumValues() == 2 && 11847 AddcSubcNode->getValueType(0) == MVT::i32 && 11848 "Expect ADDC with two result values. First: i32"); 11849 11850 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 11851 // maybe a SMLAL which multiplies two 16-bit values. 11852 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 11853 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 11854 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 11855 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 11856 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 11857 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 11858 11859 // Check for the triangle shape. 11860 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 11861 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 11862 11863 // Make sure that the ADDE/SUBE operands are not coming from the same node. 11864 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 11865 return SDValue(); 11866 11867 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 11868 bool IsLeftOperandMUL = false; 11869 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 11870 if (MULOp == SDValue()) 11871 MULOp = findMUL_LOHI(AddeSubeOp1); 11872 else 11873 IsLeftOperandMUL = true; 11874 if (MULOp == SDValue()) 11875 return SDValue(); 11876 11877 // Figure out the right opcode. 11878 unsigned Opc = MULOp->getOpcode(); 11879 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 11880 11881 // Figure out the high and low input values to the MLAL node. 11882 SDValue *HiAddSub = nullptr; 11883 SDValue *LoMul = nullptr; 11884 SDValue *LowAddSub = nullptr; 11885 11886 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 11887 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 11888 return SDValue(); 11889 11890 if (IsLeftOperandMUL) 11891 HiAddSub = &AddeSubeOp1; 11892 else 11893 HiAddSub = &AddeSubeOp0; 11894 11895 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 11896 // whose low result is fed to the ADDC/SUBC we are checking. 11897 11898 if (AddcSubcOp0 == MULOp.getValue(0)) { 11899 LoMul = &AddcSubcOp0; 11900 LowAddSub = &AddcSubcOp1; 11901 } 11902 if (AddcSubcOp1 == MULOp.getValue(0)) { 11903 LoMul = &AddcSubcOp1; 11904 LowAddSub = &AddcSubcOp0; 11905 } 11906 11907 if (!LoMul) 11908 return SDValue(); 11909 11910 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 11911 // the replacement below will create a cycle. 11912 if (AddcSubcNode == HiAddSub->getNode() || 11913 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 11914 return SDValue(); 11915 11916 // Create the merged node. 11917 SelectionDAG &DAG = DCI.DAG; 11918 11919 // Start building operand list. 11920 SmallVector<SDValue, 8> Ops; 11921 Ops.push_back(LoMul->getOperand(0)); 11922 Ops.push_back(LoMul->getOperand(1)); 11923 11924 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 11925 // the case, we must be doing signed multiplication and only use the higher 11926 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 11927 // addition or subtraction with the value of 0x800000. 11928 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 11929 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 11930 LowAddSub->getNode()->getOpcode() == ISD::Constant && 11931 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 11932 0x80000000) { 11933 Ops.push_back(*HiAddSub); 11934 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 11935 FinalOpc = ARMISD::SMMLSR; 11936 } else { 11937 FinalOpc = ARMISD::SMMLAR; 11938 } 11939 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 11940 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 11941 11942 return SDValue(AddeSubeNode, 0); 11943 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 11944 // SMMLS is generated during instruction selection and the rest of this 11945 // function can not handle the case where AddcSubcNode is a SUBC. 11946 return SDValue(); 11947 11948 // Finish building the operand list for {U/S}MLAL 11949 Ops.push_back(*LowAddSub); 11950 Ops.push_back(*HiAddSub); 11951 11952 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11953 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11954 11955 // Replace the ADDs' nodes uses by the MLA node's values. 11956 SDValue HiMLALResult(MLALNode.getNode(), 1); 11957 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11958 11959 SDValue LoMLALResult(MLALNode.getNode(), 0); 11960 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11961 11962 // Return original node to notify the driver to stop replacing. 11963 return SDValue(AddeSubeNode, 0); 11964 } 11965 11966 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11967 TargetLowering::DAGCombinerInfo &DCI, 11968 const ARMSubtarget *Subtarget) { 11969 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11970 // While trying to combine for the other MLAL nodes, first search for the 11971 // chance to use UMAAL. Check if Addc uses a node which has already 11972 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11973 // as the addend, and it's handled in PerformUMLALCombine. 11974 11975 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11976 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11977 11978 // Check that we have a glued ADDC node. 11979 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11980 if (AddcNode->getOpcode() != ARMISD::ADDC) 11981 return SDValue(); 11982 11983 // Find the converted UMAAL or quit if it doesn't exist. 11984 SDNode *UmlalNode = nullptr; 11985 SDValue AddHi; 11986 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11987 UmlalNode = AddcNode->getOperand(0).getNode(); 11988 AddHi = AddcNode->getOperand(1); 11989 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 11990 UmlalNode = AddcNode->getOperand(1).getNode(); 11991 AddHi = AddcNode->getOperand(0); 11992 } else { 11993 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11994 } 11995 11996 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 11997 // the ADDC as well as Zero. 11998 if (!isNullConstant(UmlalNode->getOperand(3))) 11999 return SDValue(); 12000 12001 if ((isNullConstant(AddeNode->getOperand(0)) && 12002 AddeNode->getOperand(1).getNode() == UmlalNode) || 12003 (AddeNode->getOperand(0).getNode() == UmlalNode && 12004 isNullConstant(AddeNode->getOperand(1)))) { 12005 SelectionDAG &DAG = DCI.DAG; 12006 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 12007 UmlalNode->getOperand(2), AddHi }; 12008 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 12009 DAG.getVTList(MVT::i32, MVT::i32), Ops); 12010 12011 // Replace the ADDs' nodes uses by the UMAAL node's values. 12012 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 12013 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 12014 12015 // Return original node to notify the driver to stop replacing. 12016 return SDValue(AddeNode, 0); 12017 } 12018 return SDValue(); 12019 } 12020 12021 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 12022 const ARMSubtarget *Subtarget) { 12023 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 12024 return SDValue(); 12025 12026 // Check that we have a pair of ADDC and ADDE as operands. 12027 // Both addends of the ADDE must be zero. 12028 SDNode* AddcNode = N->getOperand(2).getNode(); 12029 SDNode* AddeNode = N->getOperand(3).getNode(); 12030 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 12031 (AddeNode->getOpcode() == ARMISD::ADDE) && 12032 isNullConstant(AddeNode->getOperand(0)) && 12033 isNullConstant(AddeNode->getOperand(1)) && 12034 (AddeNode->getOperand(2).getNode() == AddcNode)) 12035 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 12036 DAG.getVTList(MVT::i32, MVT::i32), 12037 {N->getOperand(0), N->getOperand(1), 12038 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 12039 else 12040 return SDValue(); 12041 } 12042 12043 static SDValue PerformAddcSubcCombine(SDNode *N, 12044 TargetLowering::DAGCombinerInfo &DCI, 12045 const ARMSubtarget *Subtarget) { 12046 SelectionDAG &DAG(DCI.DAG); 12047 12048 if (N->getOpcode() == ARMISD::SUBC) { 12049 // (SUBC (ADDE 0, 0, C), 1) -> C 12050 SDValue LHS = N->getOperand(0); 12051 SDValue RHS = N->getOperand(1); 12052 if (LHS->getOpcode() == ARMISD::ADDE && 12053 isNullConstant(LHS->getOperand(0)) && 12054 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 12055 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 12056 } 12057 } 12058 12059 if (Subtarget->isThumb1Only()) { 12060 SDValue RHS = N->getOperand(1); 12061 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12062 int32_t imm = C->getSExtValue(); 12063 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 12064 SDLoc DL(N); 12065 RHS = DAG.getConstant(-imm, DL, MVT::i32); 12066 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 12067 : ARMISD::ADDC; 12068 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 12069 } 12070 } 12071 } 12072 12073 return SDValue(); 12074 } 12075 12076 static SDValue PerformAddeSubeCombine(SDNode *N, 12077 TargetLowering::DAGCombinerInfo &DCI, 12078 const ARMSubtarget *Subtarget) { 12079 if (Subtarget->isThumb1Only()) { 12080 SelectionDAG &DAG = DCI.DAG; 12081 SDValue RHS = N->getOperand(1); 12082 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 12083 int64_t imm = C->getSExtValue(); 12084 if (imm < 0) { 12085 SDLoc DL(N); 12086 12087 // The with-carry-in form matches bitwise not instead of the negation. 12088 // Effectively, the inverse interpretation of the carry flag already 12089 // accounts for part of the negation. 12090 RHS = DAG.getConstant(~imm, DL, MVT::i32); 12091 12092 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 12093 : ARMISD::ADDE; 12094 return DAG.getNode(Opcode, DL, N->getVTList(), 12095 N->getOperand(0), RHS, N->getOperand(2)); 12096 } 12097 } 12098 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 12099 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 12100 } 12101 return SDValue(); 12102 } 12103 12104 static SDValue PerformSELECTCombine(SDNode *N, 12105 TargetLowering::DAGCombinerInfo &DCI, 12106 const ARMSubtarget *Subtarget) { 12107 if (!Subtarget->hasMVEIntegerOps()) 12108 return SDValue(); 12109 12110 SDLoc dl(N); 12111 SDValue SetCC; 12112 SDValue LHS; 12113 SDValue RHS; 12114 ISD::CondCode CC; 12115 SDValue TrueVal; 12116 SDValue FalseVal; 12117 12118 if (N->getOpcode() == ISD::SELECT && 12119 N->getOperand(0)->getOpcode() == ISD::SETCC) { 12120 SetCC = N->getOperand(0); 12121 LHS = SetCC->getOperand(0); 12122 RHS = SetCC->getOperand(1); 12123 CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 12124 TrueVal = N->getOperand(1); 12125 FalseVal = N->getOperand(2); 12126 } else if (N->getOpcode() == ISD::SELECT_CC) { 12127 LHS = N->getOperand(0); 12128 RHS = N->getOperand(1); 12129 CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 12130 TrueVal = N->getOperand(2); 12131 FalseVal = N->getOperand(3); 12132 } else { 12133 return SDValue(); 12134 } 12135 12136 unsigned int Opcode = 0; 12137 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN || 12138 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) && 12139 (CC == ISD::SETULT || CC == ISD::SETUGT)) { 12140 Opcode = ARMISD::VMINVu; 12141 if (CC == ISD::SETUGT) 12142 std::swap(TrueVal, FalseVal); 12143 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN || 12144 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) && 12145 (CC == ISD::SETLT || CC == ISD::SETGT)) { 12146 Opcode = ARMISD::VMINVs; 12147 if (CC == ISD::SETGT) 12148 std::swap(TrueVal, FalseVal); 12149 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX || 12150 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) && 12151 (CC == ISD::SETUGT || CC == ISD::SETULT)) { 12152 Opcode = ARMISD::VMAXVu; 12153 if (CC == ISD::SETULT) 12154 std::swap(TrueVal, FalseVal); 12155 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX || 12156 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) && 12157 (CC == ISD::SETGT || CC == ISD::SETLT)) { 12158 Opcode = ARMISD::VMAXVs; 12159 if (CC == ISD::SETLT) 12160 std::swap(TrueVal, FalseVal); 12161 } else 12162 return SDValue(); 12163 12164 // Normalise to the right hand side being the vector reduction 12165 switch (TrueVal->getOpcode()) { 12166 case ISD::VECREDUCE_UMIN: 12167 case ISD::VECREDUCE_SMIN: 12168 case ISD::VECREDUCE_UMAX: 12169 case ISD::VECREDUCE_SMAX: 12170 std::swap(LHS, RHS); 12171 std::swap(TrueVal, FalseVal); 12172 break; 12173 } 12174 12175 EVT VectorType = FalseVal->getOperand(0).getValueType(); 12176 12177 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 && 12178 VectorType != MVT::v4i32) 12179 return SDValue(); 12180 12181 EVT VectorScalarType = VectorType.getVectorElementType(); 12182 12183 // The values being selected must also be the ones being compared 12184 if (TrueVal != LHS || FalseVal != RHS) 12185 return SDValue(); 12186 12187 EVT LeftType = LHS->getValueType(0); 12188 EVT RightType = RHS->getValueType(0); 12189 12190 // The types must match the reduced type too 12191 if (LeftType != VectorScalarType || RightType != VectorScalarType) 12192 return SDValue(); 12193 12194 // Legalise the scalar to an i32 12195 if (VectorScalarType != MVT::i32) 12196 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 12197 12198 // Generate the reduction as an i32 for legalisation purposes 12199 auto Reduction = 12200 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0)); 12201 12202 // The result isn't actually an i32 so truncate it back to its original type 12203 if (VectorScalarType != MVT::i32) 12204 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction); 12205 12206 return Reduction; 12207 } 12208 12209 static SDValue PerformVSELECTCombine(SDNode *N, 12210 TargetLowering::DAGCombinerInfo &DCI, 12211 const ARMSubtarget *Subtarget) { 12212 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs). 12213 // 12214 // We need to re-implement this optimization here as the implementation in the 12215 // Target-Independent DAGCombiner does not handle the kind of constant we make 12216 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for 12217 // good reason, allowing truncation there would break other targets). 12218 // 12219 // Currently, this is only done for MVE, as it's the only target that benefits 12220 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL). 12221 if (!Subtarget->hasMVEIntegerOps()) 12222 return SDValue(); 12223 12224 if (N->getOperand(0).getOpcode() != ISD::XOR) 12225 return SDValue(); 12226 SDValue XOR = N->getOperand(0); 12227 12228 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s. 12229 // It is important to check with truncation allowed as the BUILD_VECTORs we 12230 // generate in those situations will truncate their operands. 12231 ConstantSDNode *Const = 12232 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false, 12233 /*AllowTruncation*/ true); 12234 if (!Const || !Const->isOne()) 12235 return SDValue(); 12236 12237 // Rewrite into vselect(cond, rhs, lhs). 12238 SDValue Cond = XOR->getOperand(0); 12239 SDValue LHS = N->getOperand(1); 12240 SDValue RHS = N->getOperand(2); 12241 EVT Type = N->getValueType(0); 12242 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS); 12243 } 12244 12245 static SDValue PerformABSCombine(SDNode *N, 12246 TargetLowering::DAGCombinerInfo &DCI, 12247 const ARMSubtarget *Subtarget) { 12248 SDValue res; 12249 SelectionDAG &DAG = DCI.DAG; 12250 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12251 12252 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 12253 return SDValue(); 12254 12255 if (!TLI.expandABS(N, res, DAG)) 12256 return SDValue(); 12257 12258 return res; 12259 } 12260 12261 /// PerformADDECombine - Target-specific dag combine transform from 12262 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 12263 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 12264 static SDValue PerformADDECombine(SDNode *N, 12265 TargetLowering::DAGCombinerInfo &DCI, 12266 const ARMSubtarget *Subtarget) { 12267 // Only ARM and Thumb2 support UMLAL/SMLAL. 12268 if (Subtarget->isThumb1Only()) 12269 return PerformAddeSubeCombine(N, DCI, Subtarget); 12270 12271 // Only perform the checks after legalize when the pattern is available. 12272 if (DCI.isBeforeLegalize()) return SDValue(); 12273 12274 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 12275 } 12276 12277 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 12278 /// operands N0 and N1. This is a helper for PerformADDCombine that is 12279 /// called with the default operands, and if that fails, with commuted 12280 /// operands. 12281 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 12282 TargetLowering::DAGCombinerInfo &DCI, 12283 const ARMSubtarget *Subtarget){ 12284 // Attempt to create vpadd for this add. 12285 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 12286 return Result; 12287 12288 // Attempt to create vpaddl for this add. 12289 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 12290 return Result; 12291 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 12292 Subtarget)) 12293 return Result; 12294 12295 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 12296 if (N0.getNode()->hasOneUse()) 12297 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 12298 return Result; 12299 return SDValue(); 12300 } 12301 12302 static SDValue PerformADDVecReduce(SDNode *N, 12303 TargetLowering::DAGCombinerInfo &DCI, 12304 const ARMSubtarget *Subtarget) { 12305 if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64) 12306 return SDValue(); 12307 12308 SDValue N0 = N->getOperand(0); 12309 SDValue N1 = N->getOperand(1); 12310 12311 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this 12312 // will look like: 12313 // t1: i32,i32 = ARMISD::VADDLVs x 12314 // t2: i64 = build_pair t1, t1:1 12315 // t3: i64 = add t2, y 12316 // We also need to check for sext / zext and commutitive adds. 12317 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA, 12318 SDValue NB) { 12319 if (NB->getOpcode() != ISD::BUILD_PAIR) 12320 return SDValue(); 12321 SDValue VecRed = NB->getOperand(0); 12322 if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 || 12323 NB->getOperand(1) != SDValue(VecRed.getNode(), 1)) 12324 return SDValue(); 12325 12326 SDLoc dl(N); 12327 SmallVector<SDValue, 4> Ops; 12328 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12329 DCI.DAG.getConstant(0, dl, MVT::i32))); 12330 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA, 12331 DCI.DAG.getConstant(1, dl, MVT::i32))); 12332 for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++) 12333 Ops.push_back(VecRed->getOperand(i)); 12334 SDValue Red = DCI.DAG.getNode(OpcodeA, dl, 12335 DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops); 12336 return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red, 12337 SDValue(Red.getNode(), 1)); 12338 }; 12339 12340 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1)) 12341 return M; 12342 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1)) 12343 return M; 12344 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0)) 12345 return M; 12346 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0)) 12347 return M; 12348 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1)) 12349 return M; 12350 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1)) 12351 return M; 12352 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0)) 12353 return M; 12354 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0)) 12355 return M; 12356 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1)) 12357 return M; 12358 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1)) 12359 return M; 12360 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0)) 12361 return M; 12362 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0)) 12363 return M; 12364 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1)) 12365 return M; 12366 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1)) 12367 return M; 12368 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0)) 12369 return M; 12370 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0)) 12371 return M; 12372 return SDValue(); 12373 } 12374 12375 bool 12376 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 12377 CombineLevel Level) const { 12378 if (Level == BeforeLegalizeTypes) 12379 return true; 12380 12381 if (N->getOpcode() != ISD::SHL) 12382 return true; 12383 12384 if (Subtarget->isThumb1Only()) { 12385 // Avoid making expensive immediates by commuting shifts. (This logic 12386 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 12387 // for free.) 12388 if (N->getOpcode() != ISD::SHL) 12389 return true; 12390 SDValue N1 = N->getOperand(0); 12391 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 12392 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 12393 return true; 12394 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 12395 if (Const->getAPIntValue().ult(256)) 12396 return false; 12397 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 12398 Const->getAPIntValue().sgt(-256)) 12399 return false; 12400 } 12401 return true; 12402 } 12403 12404 // Turn off commute-with-shift transform after legalization, so it doesn't 12405 // conflict with PerformSHLSimplify. (We could try to detect when 12406 // PerformSHLSimplify would trigger more precisely, but it isn't 12407 // really necessary.) 12408 return false; 12409 } 12410 12411 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 12412 const SDNode *N, CombineLevel Level) const { 12413 if (!Subtarget->isThumb1Only()) 12414 return true; 12415 12416 if (Level == BeforeLegalizeTypes) 12417 return true; 12418 12419 return false; 12420 } 12421 12422 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 12423 if (!Subtarget->hasNEON()) { 12424 if (Subtarget->isThumb1Only()) 12425 return VT.getScalarSizeInBits() <= 32; 12426 return true; 12427 } 12428 return VT.isScalarInteger(); 12429 } 12430 12431 static SDValue PerformSHLSimplify(SDNode *N, 12432 TargetLowering::DAGCombinerInfo &DCI, 12433 const ARMSubtarget *ST) { 12434 // Allow the generic combiner to identify potential bswaps. 12435 if (DCI.isBeforeLegalize()) 12436 return SDValue(); 12437 12438 // DAG combiner will fold: 12439 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 12440 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 12441 // Other code patterns that can be also be modified have the following form: 12442 // b + ((a << 1) | 510) 12443 // b + ((a << 1) & 510) 12444 // b + ((a << 1) ^ 510) 12445 // b + ((a << 1) + 510) 12446 12447 // Many instructions can perform the shift for free, but it requires both 12448 // the operands to be registers. If c1 << c2 is too large, a mov immediate 12449 // instruction will needed. So, unfold back to the original pattern if: 12450 // - if c1 and c2 are small enough that they don't require mov imms. 12451 // - the user(s) of the node can perform an shl 12452 12453 // No shifted operands for 16-bit instructions. 12454 if (ST->isThumb() && ST->isThumb1Only()) 12455 return SDValue(); 12456 12457 // Check that all the users could perform the shl themselves. 12458 for (auto U : N->uses()) { 12459 switch(U->getOpcode()) { 12460 default: 12461 return SDValue(); 12462 case ISD::SUB: 12463 case ISD::ADD: 12464 case ISD::AND: 12465 case ISD::OR: 12466 case ISD::XOR: 12467 case ISD::SETCC: 12468 case ARMISD::CMP: 12469 // Check that the user isn't already using a constant because there 12470 // aren't any instructions that support an immediate operand and a 12471 // shifted operand. 12472 if (isa<ConstantSDNode>(U->getOperand(0)) || 12473 isa<ConstantSDNode>(U->getOperand(1))) 12474 return SDValue(); 12475 12476 // Check that it's not already using a shift. 12477 if (U->getOperand(0).getOpcode() == ISD::SHL || 12478 U->getOperand(1).getOpcode() == ISD::SHL) 12479 return SDValue(); 12480 break; 12481 } 12482 } 12483 12484 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 12485 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 12486 return SDValue(); 12487 12488 if (N->getOperand(0).getOpcode() != ISD::SHL) 12489 return SDValue(); 12490 12491 SDValue SHL = N->getOperand(0); 12492 12493 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12494 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 12495 if (!C1ShlC2 || !C2) 12496 return SDValue(); 12497 12498 APInt C2Int = C2->getAPIntValue(); 12499 APInt C1Int = C1ShlC2->getAPIntValue(); 12500 12501 // Check that performing a lshr will not lose any information. 12502 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 12503 C2Int.getBitWidth() - C2->getZExtValue()); 12504 if ((C1Int & Mask) != C1Int) 12505 return SDValue(); 12506 12507 // Shift the first constant. 12508 C1Int.lshrInPlace(C2Int); 12509 12510 // The immediates are encoded as an 8-bit value that can be rotated. 12511 auto LargeImm = [](const APInt &Imm) { 12512 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 12513 return Imm.getBitWidth() - Zeros > 8; 12514 }; 12515 12516 if (LargeImm(C1Int) || LargeImm(C2Int)) 12517 return SDValue(); 12518 12519 SelectionDAG &DAG = DCI.DAG; 12520 SDLoc dl(N); 12521 SDValue X = SHL.getOperand(0); 12522 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 12523 DAG.getConstant(C1Int, dl, MVT::i32)); 12524 // Shift left to compensate for the lshr of C1Int. 12525 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 12526 12527 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 12528 SHL.dump(); N->dump()); 12529 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 12530 return Res; 12531 } 12532 12533 12534 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 12535 /// 12536 static SDValue PerformADDCombine(SDNode *N, 12537 TargetLowering::DAGCombinerInfo &DCI, 12538 const ARMSubtarget *Subtarget) { 12539 SDValue N0 = N->getOperand(0); 12540 SDValue N1 = N->getOperand(1); 12541 12542 // Only works one way, because it needs an immediate operand. 12543 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12544 return Result; 12545 12546 if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget)) 12547 return Result; 12548 12549 // First try with the default operand order. 12550 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 12551 return Result; 12552 12553 // If that didn't work, try again with the operands commuted. 12554 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 12555 } 12556 12557 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 12558 /// 12559 static SDValue PerformSUBCombine(SDNode *N, 12560 TargetLowering::DAGCombinerInfo &DCI, 12561 const ARMSubtarget *Subtarget) { 12562 SDValue N0 = N->getOperand(0); 12563 SDValue N1 = N->getOperand(1); 12564 12565 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 12566 if (N1.getNode()->hasOneUse()) 12567 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 12568 return Result; 12569 12570 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector()) 12571 return SDValue(); 12572 12573 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x)) 12574 // so that we can readily pattern match more mve instructions which can use 12575 // a scalar operand. 12576 SDValue VDup = N->getOperand(1); 12577 if (VDup->getOpcode() != ARMISD::VDUP) 12578 return SDValue(); 12579 12580 SDValue VMov = N->getOperand(0); 12581 if (VMov->getOpcode() == ISD::BITCAST) 12582 VMov = VMov->getOperand(0); 12583 12584 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov)) 12585 return SDValue(); 12586 12587 SDLoc dl(N); 12588 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32, 12589 DCI.DAG.getConstant(0, dl, MVT::i32), 12590 VDup->getOperand(0)); 12591 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate); 12592 } 12593 12594 /// PerformVMULCombine 12595 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 12596 /// special multiplier accumulator forwarding. 12597 /// vmul d3, d0, d2 12598 /// vmla d3, d1, d2 12599 /// is faster than 12600 /// vadd d3, d0, d1 12601 /// vmul d3, d3, d2 12602 // However, for (A + B) * (A + B), 12603 // vadd d2, d0, d1 12604 // vmul d3, d0, d2 12605 // vmla d3, d1, d2 12606 // is slower than 12607 // vadd d2, d0, d1 12608 // vmul d3, d2, d2 12609 static SDValue PerformVMULCombine(SDNode *N, 12610 TargetLowering::DAGCombinerInfo &DCI, 12611 const ARMSubtarget *Subtarget) { 12612 if (!Subtarget->hasVMLxForwarding()) 12613 return SDValue(); 12614 12615 SelectionDAG &DAG = DCI.DAG; 12616 SDValue N0 = N->getOperand(0); 12617 SDValue N1 = N->getOperand(1); 12618 unsigned Opcode = N0.getOpcode(); 12619 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12620 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 12621 Opcode = N1.getOpcode(); 12622 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 12623 Opcode != ISD::FADD && Opcode != ISD::FSUB) 12624 return SDValue(); 12625 std::swap(N0, N1); 12626 } 12627 12628 if (N0 == N1) 12629 return SDValue(); 12630 12631 EVT VT = N->getValueType(0); 12632 SDLoc DL(N); 12633 SDValue N00 = N0->getOperand(0); 12634 SDValue N01 = N0->getOperand(1); 12635 return DAG.getNode(Opcode, DL, VT, 12636 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 12637 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 12638 } 12639 12640 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG, 12641 const ARMSubtarget *Subtarget) { 12642 EVT VT = N->getValueType(0); 12643 if (VT != MVT::v2i64) 12644 return SDValue(); 12645 12646 SDValue N0 = N->getOperand(0); 12647 SDValue N1 = N->getOperand(1); 12648 12649 auto IsSignExt = [&](SDValue Op) { 12650 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG) 12651 return SDValue(); 12652 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT(); 12653 if (VT.getScalarSizeInBits() == 32) 12654 return Op->getOperand(0); 12655 return SDValue(); 12656 }; 12657 auto IsZeroExt = [&](SDValue Op) { 12658 // Zero extends are a little more awkward. At the point we are matching 12659 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask. 12660 // That might be before of after a bitcast depending on how the and is 12661 // placed. Because this has to look through bitcasts, it is currently only 12662 // supported on LE. 12663 if (!Subtarget->isLittle()) 12664 return SDValue(); 12665 12666 SDValue And = Op; 12667 if (And->getOpcode() == ISD::BITCAST) 12668 And = And->getOperand(0); 12669 if (And->getOpcode() != ISD::AND) 12670 return SDValue(); 12671 SDValue Mask = And->getOperand(1); 12672 if (Mask->getOpcode() == ISD::BITCAST) 12673 Mask = Mask->getOperand(0); 12674 12675 if (Mask->getOpcode() != ISD::BUILD_VECTOR || 12676 Mask.getValueType() != MVT::v4i32) 12677 return SDValue(); 12678 if (isAllOnesConstant(Mask->getOperand(0)) && 12679 isNullConstant(Mask->getOperand(1)) && 12680 isAllOnesConstant(Mask->getOperand(2)) && 12681 isNullConstant(Mask->getOperand(3))) 12682 return And->getOperand(0); 12683 return SDValue(); 12684 }; 12685 12686 SDLoc dl(N); 12687 if (SDValue Op0 = IsSignExt(N0)) { 12688 if (SDValue Op1 = IsSignExt(N1)) { 12689 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12690 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12691 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a); 12692 } 12693 } 12694 if (SDValue Op0 = IsZeroExt(N0)) { 12695 if (SDValue Op1 = IsZeroExt(N1)) { 12696 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0); 12697 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1); 12698 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a); 12699 } 12700 } 12701 12702 return SDValue(); 12703 } 12704 12705 static SDValue PerformMULCombine(SDNode *N, 12706 TargetLowering::DAGCombinerInfo &DCI, 12707 const ARMSubtarget *Subtarget) { 12708 SelectionDAG &DAG = DCI.DAG; 12709 12710 EVT VT = N->getValueType(0); 12711 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64) 12712 return PerformMVEVMULLCombine(N, DAG, Subtarget); 12713 12714 if (Subtarget->isThumb1Only()) 12715 return SDValue(); 12716 12717 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12718 return SDValue(); 12719 12720 if (VT.is64BitVector() || VT.is128BitVector()) 12721 return PerformVMULCombine(N, DCI, Subtarget); 12722 if (VT != MVT::i32) 12723 return SDValue(); 12724 12725 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12726 if (!C) 12727 return SDValue(); 12728 12729 int64_t MulAmt = C->getSExtValue(); 12730 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 12731 12732 ShiftAmt = ShiftAmt & (32 - 1); 12733 SDValue V = N->getOperand(0); 12734 SDLoc DL(N); 12735 12736 SDValue Res; 12737 MulAmt >>= ShiftAmt; 12738 12739 if (MulAmt >= 0) { 12740 if (isPowerOf2_32(MulAmt - 1)) { 12741 // (mul x, 2^N + 1) => (add (shl x, N), x) 12742 Res = DAG.getNode(ISD::ADD, DL, VT, 12743 V, 12744 DAG.getNode(ISD::SHL, DL, VT, 12745 V, 12746 DAG.getConstant(Log2_32(MulAmt - 1), DL, 12747 MVT::i32))); 12748 } else if (isPowerOf2_32(MulAmt + 1)) { 12749 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12750 Res = DAG.getNode(ISD::SUB, DL, VT, 12751 DAG.getNode(ISD::SHL, DL, VT, 12752 V, 12753 DAG.getConstant(Log2_32(MulAmt + 1), DL, 12754 MVT::i32)), 12755 V); 12756 } else 12757 return SDValue(); 12758 } else { 12759 uint64_t MulAmtAbs = -MulAmt; 12760 if (isPowerOf2_32(MulAmtAbs + 1)) { 12761 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12762 Res = DAG.getNode(ISD::SUB, DL, VT, 12763 V, 12764 DAG.getNode(ISD::SHL, DL, VT, 12765 V, 12766 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 12767 MVT::i32))); 12768 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 12769 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12770 Res = DAG.getNode(ISD::ADD, DL, VT, 12771 V, 12772 DAG.getNode(ISD::SHL, DL, VT, 12773 V, 12774 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 12775 MVT::i32))); 12776 Res = DAG.getNode(ISD::SUB, DL, VT, 12777 DAG.getConstant(0, DL, MVT::i32), Res); 12778 } else 12779 return SDValue(); 12780 } 12781 12782 if (ShiftAmt != 0) 12783 Res = DAG.getNode(ISD::SHL, DL, VT, 12784 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 12785 12786 // Do not add new nodes to DAG combiner worklist. 12787 DCI.CombineTo(N, Res, false); 12788 return SDValue(); 12789 } 12790 12791 static SDValue CombineANDShift(SDNode *N, 12792 TargetLowering::DAGCombinerInfo &DCI, 12793 const ARMSubtarget *Subtarget) { 12794 // Allow DAGCombine to pattern-match before we touch the canonical form. 12795 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12796 return SDValue(); 12797 12798 if (N->getValueType(0) != MVT::i32) 12799 return SDValue(); 12800 12801 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12802 if (!N1C) 12803 return SDValue(); 12804 12805 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 12806 // Don't transform uxtb/uxth. 12807 if (C1 == 255 || C1 == 65535) 12808 return SDValue(); 12809 12810 SDNode *N0 = N->getOperand(0).getNode(); 12811 if (!N0->hasOneUse()) 12812 return SDValue(); 12813 12814 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 12815 return SDValue(); 12816 12817 bool LeftShift = N0->getOpcode() == ISD::SHL; 12818 12819 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12820 if (!N01C) 12821 return SDValue(); 12822 12823 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 12824 if (!C2 || C2 >= 32) 12825 return SDValue(); 12826 12827 // Clear irrelevant bits in the mask. 12828 if (LeftShift) 12829 C1 &= (-1U << C2); 12830 else 12831 C1 &= (-1U >> C2); 12832 12833 SelectionDAG &DAG = DCI.DAG; 12834 SDLoc DL(N); 12835 12836 // We have a pattern of the form "(and (shl x, c2) c1)" or 12837 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 12838 // transform to a pair of shifts, to save materializing c1. 12839 12840 // First pattern: right shift, then mask off leading bits. 12841 // FIXME: Use demanded bits? 12842 if (!LeftShift && isMask_32(C1)) { 12843 uint32_t C3 = countLeadingZeros(C1); 12844 if (C2 < C3) { 12845 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12846 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12847 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12848 DAG.getConstant(C3, DL, MVT::i32)); 12849 } 12850 } 12851 12852 // First pattern, reversed: left shift, then mask off trailing bits. 12853 if (LeftShift && isMask_32(~C1)) { 12854 uint32_t C3 = countTrailingZeros(C1); 12855 if (C2 < C3) { 12856 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12857 DAG.getConstant(C3 - C2, DL, MVT::i32)); 12858 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12859 DAG.getConstant(C3, DL, MVT::i32)); 12860 } 12861 } 12862 12863 // Second pattern: left shift, then mask off leading bits. 12864 // FIXME: Use demanded bits? 12865 if (LeftShift && isShiftedMask_32(C1)) { 12866 uint32_t Trailing = countTrailingZeros(C1); 12867 uint32_t C3 = countLeadingZeros(C1); 12868 if (Trailing == C2 && C2 + C3 < 32) { 12869 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12870 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12871 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 12872 DAG.getConstant(C3, DL, MVT::i32)); 12873 } 12874 } 12875 12876 // Second pattern, reversed: right shift, then mask off trailing bits. 12877 // FIXME: Handle other patterns of known/demanded bits. 12878 if (!LeftShift && isShiftedMask_32(C1)) { 12879 uint32_t Leading = countLeadingZeros(C1); 12880 uint32_t C3 = countTrailingZeros(C1); 12881 if (Leading == C2 && C2 + C3 < 32) { 12882 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 12883 DAG.getConstant(C2 + C3, DL, MVT::i32)); 12884 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 12885 DAG.getConstant(C3, DL, MVT::i32)); 12886 } 12887 } 12888 12889 // FIXME: Transform "(and (shl x, c2) c1)" -> 12890 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 12891 // c1. 12892 return SDValue(); 12893 } 12894 12895 static SDValue PerformANDCombine(SDNode *N, 12896 TargetLowering::DAGCombinerInfo &DCI, 12897 const ARMSubtarget *Subtarget) { 12898 // Attempt to use immediate-form VBIC 12899 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12900 SDLoc dl(N); 12901 EVT VT = N->getValueType(0); 12902 SelectionDAG &DAG = DCI.DAG; 12903 12904 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 || 12905 VT == MVT::v8i1 || VT == MVT::v16i1) 12906 return SDValue(); 12907 12908 APInt SplatBits, SplatUndef; 12909 unsigned SplatBitSize; 12910 bool HasAnyUndefs; 12911 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 12912 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12913 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 12914 SplatBitSize == 64) { 12915 EVT VbicVT; 12916 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 12917 SplatUndef.getZExtValue(), SplatBitSize, 12918 DAG, dl, VbicVT, VT, OtherModImm); 12919 if (Val.getNode()) { 12920 SDValue Input = 12921 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 12922 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 12923 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 12924 } 12925 } 12926 } 12927 12928 if (!Subtarget->isThumb1Only()) { 12929 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 12930 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 12931 return Result; 12932 12933 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12934 return Result; 12935 } 12936 12937 if (Subtarget->isThumb1Only()) 12938 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 12939 return Result; 12940 12941 return SDValue(); 12942 } 12943 12944 // Try combining OR nodes to SMULWB, SMULWT. 12945 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 12946 TargetLowering::DAGCombinerInfo &DCI, 12947 const ARMSubtarget *Subtarget) { 12948 if (!Subtarget->hasV6Ops() || 12949 (Subtarget->isThumb() && 12950 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 12951 return SDValue(); 12952 12953 SDValue SRL = OR->getOperand(0); 12954 SDValue SHL = OR->getOperand(1); 12955 12956 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 12957 SRL = OR->getOperand(1); 12958 SHL = OR->getOperand(0); 12959 } 12960 if (!isSRL16(SRL) || !isSHL16(SHL)) 12961 return SDValue(); 12962 12963 // The first operands to the shifts need to be the two results from the 12964 // same smul_lohi node. 12965 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 12966 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 12967 return SDValue(); 12968 12969 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 12970 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 12971 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 12972 return SDValue(); 12973 12974 // Now we have: 12975 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 12976 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 12977 // For SMUWB the 16-bit value will signed extended somehow. 12978 // For SMULWT only the SRA is required. 12979 // Check both sides of SMUL_LOHI 12980 SDValue OpS16 = SMULLOHI->getOperand(0); 12981 SDValue OpS32 = SMULLOHI->getOperand(1); 12982 12983 SelectionDAG &DAG = DCI.DAG; 12984 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 12985 OpS16 = OpS32; 12986 OpS32 = SMULLOHI->getOperand(0); 12987 } 12988 12989 SDLoc dl(OR); 12990 unsigned Opcode = 0; 12991 if (isS16(OpS16, DAG)) 12992 Opcode = ARMISD::SMULWB; 12993 else if (isSRA16(OpS16)) { 12994 Opcode = ARMISD::SMULWT; 12995 OpS16 = OpS16->getOperand(0); 12996 } 12997 else 12998 return SDValue(); 12999 13000 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 13001 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 13002 return SDValue(OR, 0); 13003 } 13004 13005 static SDValue PerformORCombineToBFI(SDNode *N, 13006 TargetLowering::DAGCombinerInfo &DCI, 13007 const ARMSubtarget *Subtarget) { 13008 // BFI is only available on V6T2+ 13009 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 13010 return SDValue(); 13011 13012 EVT VT = N->getValueType(0); 13013 SDValue N0 = N->getOperand(0); 13014 SDValue N1 = N->getOperand(1); 13015 SelectionDAG &DAG = DCI.DAG; 13016 SDLoc DL(N); 13017 // 1) or (and A, mask), val => ARMbfi A, val, mask 13018 // iff (val & mask) == val 13019 // 13020 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 13021 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 13022 // && mask == ~mask2 13023 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 13024 // && ~mask == mask2 13025 // (i.e., copy a bitfield value into another bitfield of the same width) 13026 13027 if (VT != MVT::i32) 13028 return SDValue(); 13029 13030 SDValue N00 = N0.getOperand(0); 13031 13032 // The value and the mask need to be constants so we can verify this is 13033 // actually a bitfield set. If the mask is 0xffff, we can do better 13034 // via a movt instruction, so don't use BFI in that case. 13035 SDValue MaskOp = N0.getOperand(1); 13036 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 13037 if (!MaskC) 13038 return SDValue(); 13039 unsigned Mask = MaskC->getZExtValue(); 13040 if (Mask == 0xffff) 13041 return SDValue(); 13042 SDValue Res; 13043 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 13044 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 13045 if (N1C) { 13046 unsigned Val = N1C->getZExtValue(); 13047 if ((Val & ~Mask) != Val) 13048 return SDValue(); 13049 13050 if (ARM::isBitFieldInvertedMask(Mask)) { 13051 Val >>= countTrailingZeros(~Mask); 13052 13053 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 13054 DAG.getConstant(Val, DL, MVT::i32), 13055 DAG.getConstant(Mask, DL, MVT::i32)); 13056 13057 DCI.CombineTo(N, Res, false); 13058 // Return value from the original node to inform the combiner than N is 13059 // now dead. 13060 return SDValue(N, 0); 13061 } 13062 } else if (N1.getOpcode() == ISD::AND) { 13063 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 13064 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 13065 if (!N11C) 13066 return SDValue(); 13067 unsigned Mask2 = N11C->getZExtValue(); 13068 13069 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 13070 // as is to match. 13071 if (ARM::isBitFieldInvertedMask(Mask) && 13072 (Mask == ~Mask2)) { 13073 // The pack halfword instruction works better for masks that fit it, 13074 // so use that when it's available. 13075 if (Subtarget->hasDSP() && 13076 (Mask == 0xffff || Mask == 0xffff0000)) 13077 return SDValue(); 13078 // 2a 13079 unsigned amt = countTrailingZeros(Mask2); 13080 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 13081 DAG.getConstant(amt, DL, MVT::i32)); 13082 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 13083 DAG.getConstant(Mask, DL, MVT::i32)); 13084 DCI.CombineTo(N, Res, false); 13085 // Return value from the original node to inform the combiner than N is 13086 // now dead. 13087 return SDValue(N, 0); 13088 } else if (ARM::isBitFieldInvertedMask(~Mask) && 13089 (~Mask == Mask2)) { 13090 // The pack halfword instruction works better for masks that fit it, 13091 // so use that when it's available. 13092 if (Subtarget->hasDSP() && 13093 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 13094 return SDValue(); 13095 // 2b 13096 unsigned lsb = countTrailingZeros(Mask); 13097 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 13098 DAG.getConstant(lsb, DL, MVT::i32)); 13099 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 13100 DAG.getConstant(Mask2, DL, MVT::i32)); 13101 DCI.CombineTo(N, Res, false); 13102 // Return value from the original node to inform the combiner than N is 13103 // now dead. 13104 return SDValue(N, 0); 13105 } 13106 } 13107 13108 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 13109 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 13110 ARM::isBitFieldInvertedMask(~Mask)) { 13111 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 13112 // where lsb(mask) == #shamt and masked bits of B are known zero. 13113 SDValue ShAmt = N00.getOperand(1); 13114 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 13115 unsigned LSB = countTrailingZeros(Mask); 13116 if (ShAmtC != LSB) 13117 return SDValue(); 13118 13119 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 13120 DAG.getConstant(~Mask, DL, MVT::i32)); 13121 13122 DCI.CombineTo(N, Res, false); 13123 // Return value from the original node to inform the combiner than N is 13124 // now dead. 13125 return SDValue(N, 0); 13126 } 13127 13128 return SDValue(); 13129 } 13130 13131 static bool isValidMVECond(unsigned CC, bool IsFloat) { 13132 switch (CC) { 13133 case ARMCC::EQ: 13134 case ARMCC::NE: 13135 case ARMCC::LE: 13136 case ARMCC::GT: 13137 case ARMCC::GE: 13138 case ARMCC::LT: 13139 return true; 13140 case ARMCC::HS: 13141 case ARMCC::HI: 13142 return !IsFloat; 13143 default: 13144 return false; 13145 }; 13146 } 13147 13148 static ARMCC::CondCodes getVCMPCondCode(SDValue N) { 13149 if (N->getOpcode() == ARMISD::VCMP) 13150 return (ARMCC::CondCodes)N->getConstantOperandVal(2); 13151 else if (N->getOpcode() == ARMISD::VCMPZ) 13152 return (ARMCC::CondCodes)N->getConstantOperandVal(1); 13153 else 13154 llvm_unreachable("Not a VCMP/VCMPZ!"); 13155 } 13156 13157 static bool CanInvertMVEVCMP(SDValue N) { 13158 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N)); 13159 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint()); 13160 } 13161 13162 static SDValue PerformORCombine_i1(SDNode *N, 13163 TargetLowering::DAGCombinerInfo &DCI, 13164 const ARMSubtarget *Subtarget) { 13165 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 13166 // together with predicates 13167 EVT VT = N->getValueType(0); 13168 SDLoc DL(N); 13169 SDValue N0 = N->getOperand(0); 13170 SDValue N1 = N->getOperand(1); 13171 13172 auto IsFreelyInvertable = [&](SDValue V) { 13173 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ) 13174 return CanInvertMVEVCMP(V); 13175 return false; 13176 }; 13177 13178 // At least one operand must be freely invertable. 13179 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1))) 13180 return SDValue(); 13181 13182 SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT); 13183 SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT); 13184 SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1); 13185 return DCI.DAG.getLogicalNOT(DL, And, VT); 13186 } 13187 13188 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 13189 static SDValue PerformORCombine(SDNode *N, 13190 TargetLowering::DAGCombinerInfo &DCI, 13191 const ARMSubtarget *Subtarget) { 13192 // Attempt to use immediate-form VORR 13193 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 13194 SDLoc dl(N); 13195 EVT VT = N->getValueType(0); 13196 SelectionDAG &DAG = DCI.DAG; 13197 13198 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13199 return SDValue(); 13200 13201 if (Subtarget->hasMVEIntegerOps() && 13202 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 13203 return PerformORCombine_i1(N, DCI, Subtarget); 13204 13205 APInt SplatBits, SplatUndef; 13206 unsigned SplatBitSize; 13207 bool HasAnyUndefs; 13208 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) && 13209 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 13210 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 || 13211 SplatBitSize == 64) { 13212 EVT VorrVT; 13213 SDValue Val = 13214 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(), 13215 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm); 13216 if (Val.getNode()) { 13217 SDValue Input = 13218 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 13219 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 13220 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 13221 } 13222 } 13223 } 13224 13225 if (!Subtarget->isThumb1Only()) { 13226 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 13227 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13228 return Result; 13229 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 13230 return Result; 13231 } 13232 13233 SDValue N0 = N->getOperand(0); 13234 SDValue N1 = N->getOperand(1); 13235 13236 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 13237 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 13238 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 13239 13240 // The code below optimizes (or (and X, Y), Z). 13241 // The AND operand needs to have a single user to make these optimizations 13242 // profitable. 13243 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 13244 return SDValue(); 13245 13246 APInt SplatUndef; 13247 unsigned SplatBitSize; 13248 bool HasAnyUndefs; 13249 13250 APInt SplatBits0, SplatBits1; 13251 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 13252 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 13253 // Ensure that the second operand of both ands are constants 13254 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 13255 HasAnyUndefs) && !HasAnyUndefs) { 13256 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 13257 HasAnyUndefs) && !HasAnyUndefs) { 13258 // Ensure that the bit width of the constants are the same and that 13259 // the splat arguments are logical inverses as per the pattern we 13260 // are trying to simplify. 13261 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 13262 SplatBits0 == ~SplatBits1) { 13263 // Canonicalize the vector type to make instruction selection 13264 // simpler. 13265 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 13266 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT, 13267 N0->getOperand(1), 13268 N0->getOperand(0), 13269 N1->getOperand(0)); 13270 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 13271 } 13272 } 13273 } 13274 } 13275 13276 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 13277 // reasonable. 13278 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 13279 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 13280 return Res; 13281 } 13282 13283 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13284 return Result; 13285 13286 return SDValue(); 13287 } 13288 13289 static SDValue PerformXORCombine(SDNode *N, 13290 TargetLowering::DAGCombinerInfo &DCI, 13291 const ARMSubtarget *Subtarget) { 13292 EVT VT = N->getValueType(0); 13293 SelectionDAG &DAG = DCI.DAG; 13294 13295 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13296 return SDValue(); 13297 13298 if (!Subtarget->isThumb1Only()) { 13299 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 13300 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 13301 return Result; 13302 13303 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 13304 return Result; 13305 } 13306 13307 if (Subtarget->hasMVEIntegerOps()) { 13308 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition. 13309 SDValue N0 = N->getOperand(0); 13310 SDValue N1 = N->getOperand(1); 13311 const TargetLowering *TLI = Subtarget->getTargetLowering(); 13312 if (TLI->isConstTrueVal(N1.getNode()) && 13313 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) { 13314 if (CanInvertMVEVCMP(N0)) { 13315 SDLoc DL(N0); 13316 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0)); 13317 13318 SmallVector<SDValue, 4> Ops; 13319 Ops.push_back(N0->getOperand(0)); 13320 if (N0->getOpcode() == ARMISD::VCMP) 13321 Ops.push_back(N0->getOperand(1)); 13322 Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32)); 13323 return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops); 13324 } 13325 } 13326 } 13327 13328 return SDValue(); 13329 } 13330 13331 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 13332 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 13333 // their position in "to" (Rd). 13334 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 13335 assert(N->getOpcode() == ARMISD::BFI); 13336 13337 SDValue From = N->getOperand(1); 13338 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 13339 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 13340 13341 // If the Base came from a SHR #C, we can deduce that it is really testing bit 13342 // #C in the base of the SHR. 13343 if (From->getOpcode() == ISD::SRL && 13344 isa<ConstantSDNode>(From->getOperand(1))) { 13345 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 13346 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 13347 FromMask <<= Shift.getLimitedValue(31); 13348 From = From->getOperand(0); 13349 } 13350 13351 return From; 13352 } 13353 13354 // If A and B contain one contiguous set of bits, does A | B == A . B? 13355 // 13356 // Neither A nor B must be zero. 13357 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 13358 unsigned LastActiveBitInA = A.countTrailingZeros(); 13359 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 13360 return LastActiveBitInA - 1 == FirstActiveBitInB; 13361 } 13362 13363 static SDValue FindBFIToCombineWith(SDNode *N) { 13364 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 13365 // if one exists. 13366 APInt ToMask, FromMask; 13367 SDValue From = ParseBFI(N, ToMask, FromMask); 13368 SDValue To = N->getOperand(0); 13369 13370 // Now check for a compatible BFI to merge with. We can pass through BFIs that 13371 // aren't compatible, but not if they set the same bit in their destination as 13372 // we do (or that of any BFI we're going to combine with). 13373 SDValue V = To; 13374 APInt CombinedToMask = ToMask; 13375 while (V.getOpcode() == ARMISD::BFI) { 13376 APInt NewToMask, NewFromMask; 13377 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 13378 if (NewFrom != From) { 13379 // This BFI has a different base. Keep going. 13380 CombinedToMask |= NewToMask; 13381 V = V.getOperand(0); 13382 continue; 13383 } 13384 13385 // Do the written bits conflict with any we've seen so far? 13386 if ((NewToMask & CombinedToMask).getBoolValue()) 13387 // Conflicting bits - bail out because going further is unsafe. 13388 return SDValue(); 13389 13390 // Are the new bits contiguous when combined with the old bits? 13391 if (BitsProperlyConcatenate(ToMask, NewToMask) && 13392 BitsProperlyConcatenate(FromMask, NewFromMask)) 13393 return V; 13394 if (BitsProperlyConcatenate(NewToMask, ToMask) && 13395 BitsProperlyConcatenate(NewFromMask, FromMask)) 13396 return V; 13397 13398 // We've seen a write to some bits, so track it. 13399 CombinedToMask |= NewToMask; 13400 // Keep going... 13401 V = V.getOperand(0); 13402 } 13403 13404 return SDValue(); 13405 } 13406 13407 static SDValue PerformBFICombine(SDNode *N, 13408 TargetLowering::DAGCombinerInfo &DCI) { 13409 SDValue N1 = N->getOperand(1); 13410 if (N1.getOpcode() == ISD::AND) { 13411 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 13412 // the bits being cleared by the AND are not demanded by the BFI. 13413 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 13414 if (!N11C) 13415 return SDValue(); 13416 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13417 unsigned LSB = countTrailingZeros(~InvMask); 13418 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 13419 assert(Width < 13420 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 13421 "undefined behavior"); 13422 unsigned Mask = (1u << Width) - 1; 13423 unsigned Mask2 = N11C->getZExtValue(); 13424 if ((Mask & (~Mask2)) == 0) 13425 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 13426 N->getOperand(0), N1.getOperand(0), 13427 N->getOperand(2)); 13428 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 13429 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 13430 // Keep track of any consecutive bits set that all come from the same base 13431 // value. We can combine these together into a single BFI. 13432 SDValue CombineBFI = FindBFIToCombineWith(N); 13433 if (CombineBFI == SDValue()) 13434 return SDValue(); 13435 13436 // We've found a BFI. 13437 APInt ToMask1, FromMask1; 13438 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 13439 13440 APInt ToMask2, FromMask2; 13441 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 13442 assert(From1 == From2); 13443 (void)From2; 13444 13445 // First, unlink CombineBFI. 13446 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 13447 // Then create a new BFI, combining the two together. 13448 APInt NewFromMask = FromMask1 | FromMask2; 13449 APInt NewToMask = ToMask1 | ToMask2; 13450 13451 EVT VT = N->getValueType(0); 13452 SDLoc dl(N); 13453 13454 if (NewFromMask[0] == 0) 13455 From1 = DCI.DAG.getNode( 13456 ISD::SRL, dl, VT, From1, 13457 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 13458 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 13459 DCI.DAG.getConstant(~NewToMask, dl, VT)); 13460 } 13461 return SDValue(); 13462 } 13463 13464 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 13465 /// ARMISD::VMOVRRD. 13466 static SDValue PerformVMOVRRDCombine(SDNode *N, 13467 TargetLowering::DAGCombinerInfo &DCI, 13468 const ARMSubtarget *Subtarget) { 13469 // vmovrrd(vmovdrr x, y) -> x,y 13470 SDValue InDouble = N->getOperand(0); 13471 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 13472 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 13473 13474 // vmovrrd(load f64) -> (load i32), (load i32) 13475 SDNode *InNode = InDouble.getNode(); 13476 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 13477 InNode->getValueType(0) == MVT::f64 && 13478 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 13479 !cast<LoadSDNode>(InNode)->isVolatile()) { 13480 // TODO: Should this be done for non-FrameIndex operands? 13481 LoadSDNode *LD = cast<LoadSDNode>(InNode); 13482 13483 SelectionDAG &DAG = DCI.DAG; 13484 SDLoc DL(LD); 13485 SDValue BasePtr = LD->getBasePtr(); 13486 SDValue NewLD1 = 13487 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 13488 LD->getAlignment(), LD->getMemOperand()->getFlags()); 13489 13490 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 13491 DAG.getConstant(4, DL, MVT::i32)); 13492 13493 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 13494 LD->getPointerInfo().getWithOffset(4), 13495 std::min(4U, LD->getAlignment()), 13496 LD->getMemOperand()->getFlags()); 13497 13498 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 13499 if (DCI.DAG.getDataLayout().isBigEndian()) 13500 std::swap (NewLD1, NewLD2); 13501 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 13502 return Result; 13503 } 13504 13505 return SDValue(); 13506 } 13507 13508 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 13509 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 13510 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 13511 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 13512 SDValue Op0 = N->getOperand(0); 13513 SDValue Op1 = N->getOperand(1); 13514 if (Op0.getOpcode() == ISD::BITCAST) 13515 Op0 = Op0.getOperand(0); 13516 if (Op1.getOpcode() == ISD::BITCAST) 13517 Op1 = Op1.getOperand(0); 13518 if (Op0.getOpcode() == ARMISD::VMOVRRD && 13519 Op0.getNode() == Op1.getNode() && 13520 Op0.getResNo() == 0 && Op1.getResNo() == 1) 13521 return DAG.getNode(ISD::BITCAST, SDLoc(N), 13522 N->getValueType(0), Op0.getOperand(0)); 13523 return SDValue(); 13524 } 13525 13526 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13527 SDValue Op0 = N->getOperand(0); 13528 13529 // VMOVhr (VMOVrh (X)) -> X 13530 if (Op0->getOpcode() == ARMISD::VMOVrh) 13531 return Op0->getOperand(0); 13532 13533 // FullFP16: half values are passed in S-registers, and we don't 13534 // need any of the bitcast and moves: 13535 // 13536 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 13537 // t5: i32 = bitcast t2 13538 // t18: f16 = ARMISD::VMOVhr t5 13539 if (Op0->getOpcode() == ISD::BITCAST) { 13540 SDValue Copy = Op0->getOperand(0); 13541 if (Copy.getValueType() == MVT::f32 && 13542 Copy->getOpcode() == ISD::CopyFromReg) { 13543 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)}; 13544 SDValue NewCopy = 13545 DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops); 13546 return NewCopy; 13547 } 13548 } 13549 13550 // fold (VMOVhr (load x)) -> (load (f16*)x) 13551 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) { 13552 if (LN0->hasOneUse() && LN0->isUnindexed() && 13553 LN0->getMemoryVT() == MVT::i16) { 13554 SDValue Load = 13555 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(), 13556 LN0->getBasePtr(), LN0->getMemOperand()); 13557 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13558 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1)); 13559 return Load; 13560 } 13561 } 13562 13563 // Only the bottom 16 bits of the source register are used. 13564 APInt DemandedMask = APInt::getLowBitsSet(32, 16); 13565 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 13566 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI)) 13567 return SDValue(N, 0); 13568 13569 return SDValue(); 13570 } 13571 13572 static SDValue PerformVMOVrhCombine(SDNode *N, 13573 TargetLowering::DAGCombinerInfo &DCI) { 13574 SDValue N0 = N->getOperand(0); 13575 EVT VT = N->getValueType(0); 13576 13577 // fold (VMOVrh (fpconst x)) -> const x 13578 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) { 13579 APFloat V = C->getValueAPF(); 13580 return DCI.DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT); 13581 } 13582 13583 // fold (VMOVrh (load x)) -> (zextload (i16*)x) 13584 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) { 13585 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 13586 13587 SDValue Load = 13588 DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(), 13589 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand()); 13590 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0)); 13591 DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 13592 return Load; 13593 } 13594 13595 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n) 13596 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 13597 isa<ConstantSDNode>(N0->getOperand(1))) 13598 return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0), 13599 N0->getOperand(1)); 13600 13601 return SDValue(); 13602 } 13603 13604 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 13605 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 13606 /// i64 vector to have f64 elements, since the value can then be loaded 13607 /// directly into a VFP register. 13608 static bool hasNormalLoadOperand(SDNode *N) { 13609 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 13610 for (unsigned i = 0; i < NumElts; ++i) { 13611 SDNode *Elt = N->getOperand(i).getNode(); 13612 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 13613 return true; 13614 } 13615 return false; 13616 } 13617 13618 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 13619 /// ISD::BUILD_VECTOR. 13620 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 13621 TargetLowering::DAGCombinerInfo &DCI, 13622 const ARMSubtarget *Subtarget) { 13623 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 13624 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 13625 // into a pair of GPRs, which is fine when the value is used as a scalar, 13626 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 13627 SelectionDAG &DAG = DCI.DAG; 13628 if (N->getNumOperands() == 2) 13629 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 13630 return RV; 13631 13632 // Load i64 elements as f64 values so that type legalization does not split 13633 // them up into i32 values. 13634 EVT VT = N->getValueType(0); 13635 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 13636 return SDValue(); 13637 SDLoc dl(N); 13638 SmallVector<SDValue, 8> Ops; 13639 unsigned NumElts = VT.getVectorNumElements(); 13640 for (unsigned i = 0; i < NumElts; ++i) { 13641 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 13642 Ops.push_back(V); 13643 // Make the DAGCombiner fold the bitcast. 13644 DCI.AddToWorklist(V.getNode()); 13645 } 13646 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 13647 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 13648 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 13649 } 13650 13651 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 13652 static SDValue 13653 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13654 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 13655 // At that time, we may have inserted bitcasts from integer to float. 13656 // If these bitcasts have survived DAGCombine, change the lowering of this 13657 // BUILD_VECTOR in something more vector friendly, i.e., that does not 13658 // force to use floating point types. 13659 13660 // Make sure we can change the type of the vector. 13661 // This is possible iff: 13662 // 1. The vector is only used in a bitcast to a integer type. I.e., 13663 // 1.1. Vector is used only once. 13664 // 1.2. Use is a bit convert to an integer type. 13665 // 2. The size of its operands are 32-bits (64-bits are not legal). 13666 EVT VT = N->getValueType(0); 13667 EVT EltVT = VT.getVectorElementType(); 13668 13669 // Check 1.1. and 2. 13670 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 13671 return SDValue(); 13672 13673 // By construction, the input type must be float. 13674 assert(EltVT == MVT::f32 && "Unexpected type!"); 13675 13676 // Check 1.2. 13677 SDNode *Use = *N->use_begin(); 13678 if (Use->getOpcode() != ISD::BITCAST || 13679 Use->getValueType(0).isFloatingPoint()) 13680 return SDValue(); 13681 13682 // Check profitability. 13683 // Model is, if more than half of the relevant operands are bitcast from 13684 // i32, turn the build_vector into a sequence of insert_vector_elt. 13685 // Relevant operands are everything that is not statically 13686 // (i.e., at compile time) bitcasted. 13687 unsigned NumOfBitCastedElts = 0; 13688 unsigned NumElts = VT.getVectorNumElements(); 13689 unsigned NumOfRelevantElts = NumElts; 13690 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 13691 SDValue Elt = N->getOperand(Idx); 13692 if (Elt->getOpcode() == ISD::BITCAST) { 13693 // Assume only bit cast to i32 will go away. 13694 if (Elt->getOperand(0).getValueType() == MVT::i32) 13695 ++NumOfBitCastedElts; 13696 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 13697 // Constants are statically casted, thus do not count them as 13698 // relevant operands. 13699 --NumOfRelevantElts; 13700 } 13701 13702 // Check if more than half of the elements require a non-free bitcast. 13703 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 13704 return SDValue(); 13705 13706 SelectionDAG &DAG = DCI.DAG; 13707 // Create the new vector type. 13708 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 13709 // Check if the type is legal. 13710 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13711 if (!TLI.isTypeLegal(VecVT)) 13712 return SDValue(); 13713 13714 // Combine: 13715 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 13716 // => BITCAST INSERT_VECTOR_ELT 13717 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 13718 // (BITCAST EN), N. 13719 SDValue Vec = DAG.getUNDEF(VecVT); 13720 SDLoc dl(N); 13721 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 13722 SDValue V = N->getOperand(Idx); 13723 if (V.isUndef()) 13724 continue; 13725 if (V.getOpcode() == ISD::BITCAST && 13726 V->getOperand(0).getValueType() == MVT::i32) 13727 // Fold obvious case. 13728 V = V.getOperand(0); 13729 else { 13730 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 13731 // Make the DAGCombiner fold the bitcasts. 13732 DCI.AddToWorklist(V.getNode()); 13733 } 13734 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 13735 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 13736 } 13737 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 13738 // Make the DAGCombiner fold the bitcasts. 13739 DCI.AddToWorklist(Vec.getNode()); 13740 return Vec; 13741 } 13742 13743 static SDValue 13744 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 13745 EVT VT = N->getValueType(0); 13746 SDValue Op = N->getOperand(0); 13747 SDLoc dl(N); 13748 13749 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x) 13750 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) { 13751 // If the valuetypes are the same, we can remove the cast entirely. 13752 if (Op->getOperand(0).getValueType() == VT) 13753 return Op->getOperand(0); 13754 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0)); 13755 } 13756 13757 return SDValue(); 13758 } 13759 13760 static SDValue 13761 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 13762 const ARMSubtarget *ST) { 13763 EVT VT = N->getValueType(0); 13764 SDValue Op = N->getOperand(0); 13765 SDLoc dl(N); 13766 13767 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST 13768 if (ST->isLittle()) 13769 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op); 13770 13771 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x) 13772 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) { 13773 // If the valuetypes are the same, we can remove the cast entirely. 13774 if (Op->getOperand(0).getValueType() == VT) 13775 return Op->getOperand(0); 13776 return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0)); 13777 } 13778 13779 return SDValue(); 13780 } 13781 13782 static SDValue PerformVCMPCombine(SDNode *N, 13783 TargetLowering::DAGCombinerInfo &DCI, 13784 const ARMSubtarget *Subtarget) { 13785 if (!Subtarget->hasMVEIntegerOps()) 13786 return SDValue(); 13787 13788 EVT VT = N->getValueType(0); 13789 SDValue Op0 = N->getOperand(0); 13790 SDValue Op1 = N->getOperand(1); 13791 ARMCC::CondCodes Cond = 13792 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 13793 SDLoc dl(N); 13794 13795 // vcmp X, 0, cc -> vcmpz X, cc 13796 if (isZeroVector(Op1)) 13797 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, 13798 N->getOperand(2)); 13799 13800 unsigned SwappedCond = getSwappedCondition(Cond); 13801 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) { 13802 // vcmp 0, X, cc -> vcmpz X, reversed(cc) 13803 if (isZeroVector(Op0)) 13804 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1, 13805 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13806 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc) 13807 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP) 13808 return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0, 13809 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32)); 13810 } 13811 13812 return SDValue(); 13813 } 13814 13815 /// PerformInsertEltCombine - Target-specific dag combine xforms for 13816 /// ISD::INSERT_VECTOR_ELT. 13817 static SDValue PerformInsertEltCombine(SDNode *N, 13818 TargetLowering::DAGCombinerInfo &DCI) { 13819 // Bitcast an i64 load inserted into a vector to f64. 13820 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13821 EVT VT = N->getValueType(0); 13822 SDNode *Elt = N->getOperand(1).getNode(); 13823 if (VT.getVectorElementType() != MVT::i64 || 13824 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 13825 return SDValue(); 13826 13827 SelectionDAG &DAG = DCI.DAG; 13828 SDLoc dl(N); 13829 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13830 VT.getVectorNumElements()); 13831 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 13832 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 13833 // Make the DAGCombiner fold the bitcasts. 13834 DCI.AddToWorklist(Vec.getNode()); 13835 DCI.AddToWorklist(V.getNode()); 13836 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 13837 Vec, V, N->getOperand(2)); 13838 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 13839 } 13840 13841 static SDValue PerformExtractEltCombine(SDNode *N, 13842 TargetLowering::DAGCombinerInfo &DCI) { 13843 SDValue Op0 = N->getOperand(0); 13844 EVT VT = N->getValueType(0); 13845 SDLoc dl(N); 13846 13847 // extract (vdup x) -> x 13848 if (Op0->getOpcode() == ARMISD::VDUP) { 13849 SDValue X = Op0->getOperand(0); 13850 if (VT == MVT::f16 && X.getValueType() == MVT::i32) 13851 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X); 13852 if (VT == MVT::i32 && X.getValueType() == MVT::f16) 13853 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X); 13854 13855 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST) 13856 X = X->getOperand(0); 13857 if (X.getValueType() == VT) 13858 return X; 13859 } 13860 13861 return SDValue(); 13862 } 13863 13864 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 13865 /// ISD::VECTOR_SHUFFLE. 13866 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 13867 // The LLVM shufflevector instruction does not require the shuffle mask 13868 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 13869 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 13870 // operands do not match the mask length, they are extended by concatenating 13871 // them with undef vectors. That is probably the right thing for other 13872 // targets, but for NEON it is better to concatenate two double-register 13873 // size vector operands into a single quad-register size vector. Do that 13874 // transformation here: 13875 // shuffle(concat(v1, undef), concat(v2, undef)) -> 13876 // shuffle(concat(v1, v2), undef) 13877 SDValue Op0 = N->getOperand(0); 13878 SDValue Op1 = N->getOperand(1); 13879 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 13880 Op1.getOpcode() != ISD::CONCAT_VECTORS || 13881 Op0.getNumOperands() != 2 || 13882 Op1.getNumOperands() != 2) 13883 return SDValue(); 13884 SDValue Concat0Op1 = Op0.getOperand(1); 13885 SDValue Concat1Op1 = Op1.getOperand(1); 13886 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 13887 return SDValue(); 13888 // Skip the transformation if any of the types are illegal. 13889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13890 EVT VT = N->getValueType(0); 13891 if (!TLI.isTypeLegal(VT) || 13892 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 13893 !TLI.isTypeLegal(Concat1Op1.getValueType())) 13894 return SDValue(); 13895 13896 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13897 Op0.getOperand(0), Op1.getOperand(0)); 13898 // Translate the shuffle mask. 13899 SmallVector<int, 16> NewMask; 13900 unsigned NumElts = VT.getVectorNumElements(); 13901 unsigned HalfElts = NumElts/2; 13902 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13903 for (unsigned n = 0; n < NumElts; ++n) { 13904 int MaskElt = SVN->getMaskElt(n); 13905 int NewElt = -1; 13906 if (MaskElt < (int)HalfElts) 13907 NewElt = MaskElt; 13908 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 13909 NewElt = HalfElts + MaskElt - NumElts; 13910 NewMask.push_back(NewElt); 13911 } 13912 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 13913 DAG.getUNDEF(VT), NewMask); 13914 } 13915 13916 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 13917 /// NEON load/store intrinsics, and generic vector load/stores, to merge 13918 /// base address updates. 13919 /// For generic load/stores, the memory type is assumed to be a vector. 13920 /// The caller is assumed to have checked legality. 13921 static SDValue CombineBaseUpdate(SDNode *N, 13922 TargetLowering::DAGCombinerInfo &DCI) { 13923 SelectionDAG &DAG = DCI.DAG; 13924 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 13925 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 13926 const bool isStore = N->getOpcode() == ISD::STORE; 13927 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 13928 SDValue Addr = N->getOperand(AddrOpIdx); 13929 MemSDNode *MemN = cast<MemSDNode>(N); 13930 SDLoc dl(N); 13931 13932 // Search for a use of the address operand that is an increment. 13933 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 13934 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 13935 SDNode *User = *UI; 13936 if (User->getOpcode() != ISD::ADD || 13937 UI.getUse().getResNo() != Addr.getResNo()) 13938 continue; 13939 13940 // Check that the add is independent of the load/store. Otherwise, folding 13941 // it would create a cycle. We can avoid searching through Addr as it's a 13942 // predecessor to both. 13943 SmallPtrSet<const SDNode *, 32> Visited; 13944 SmallVector<const SDNode *, 16> Worklist; 13945 Visited.insert(Addr.getNode()); 13946 Worklist.push_back(N); 13947 Worklist.push_back(User); 13948 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 13949 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 13950 continue; 13951 13952 // Find the new opcode for the updating load/store. 13953 bool isLoadOp = true; 13954 bool isLaneOp = false; 13955 unsigned NewOpc = 0; 13956 unsigned NumVecs = 0; 13957 if (isIntrinsic) { 13958 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 13959 switch (IntNo) { 13960 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 13961 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 13962 NumVecs = 1; break; 13963 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 13964 NumVecs = 2; break; 13965 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 13966 NumVecs = 3; break; 13967 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 13968 NumVecs = 4; break; 13969 case Intrinsic::arm_neon_vld1x2: 13970 case Intrinsic::arm_neon_vld1x3: 13971 case Intrinsic::arm_neon_vld1x4: 13972 case Intrinsic::arm_neon_vld2dup: 13973 case Intrinsic::arm_neon_vld3dup: 13974 case Intrinsic::arm_neon_vld4dup: 13975 // TODO: Support updating VLD1x and VLDxDUP nodes. For now, we just skip 13976 // combining base updates for such intrinsics. 13977 continue; 13978 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 13979 NumVecs = 2; isLaneOp = true; break; 13980 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 13981 NumVecs = 3; isLaneOp = true; break; 13982 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 13983 NumVecs = 4; isLaneOp = true; break; 13984 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 13985 NumVecs = 1; isLoadOp = false; break; 13986 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 13987 NumVecs = 2; isLoadOp = false; break; 13988 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 13989 NumVecs = 3; isLoadOp = false; break; 13990 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 13991 NumVecs = 4; isLoadOp = false; break; 13992 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 13993 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 13994 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 13995 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 13996 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 13997 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 13998 } 13999 } else { 14000 isLaneOp = true; 14001 switch (N->getOpcode()) { 14002 default: llvm_unreachable("unexpected opcode for Neon base update"); 14003 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 14004 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 14005 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 14006 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 14007 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 14008 NumVecs = 1; isLaneOp = false; break; 14009 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 14010 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 14011 } 14012 } 14013 14014 // Find the size of memory referenced by the load/store. 14015 EVT VecTy; 14016 if (isLoadOp) { 14017 VecTy = N->getValueType(0); 14018 } else if (isIntrinsic) { 14019 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 14020 } else { 14021 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 14022 VecTy = N->getOperand(1).getValueType(); 14023 } 14024 14025 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14026 if (isLaneOp) 14027 NumBytes /= VecTy.getVectorNumElements(); 14028 14029 // If the increment is a constant, it must match the memory ref size. 14030 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14031 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 14032 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 14033 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 14034 // separate instructions that make it harder to use a non-constant update. 14035 continue; 14036 } 14037 14038 // OK, we found an ADD we can fold into the base update. 14039 // Now, create a _UPD node, taking care of not breaking alignment. 14040 14041 EVT AlignedVecTy = VecTy; 14042 unsigned Alignment = MemN->getAlignment(); 14043 14044 // If this is a less-than-standard-aligned load/store, change the type to 14045 // match the standard alignment. 14046 // The alignment is overlooked when selecting _UPD variants; and it's 14047 // easier to introduce bitcasts here than fix that. 14048 // There are 3 ways to get to this base-update combine: 14049 // - intrinsics: they are assumed to be properly aligned (to the standard 14050 // alignment of the memory type), so we don't need to do anything. 14051 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 14052 // intrinsics, so, likewise, there's nothing to do. 14053 // - generic load/store instructions: the alignment is specified as an 14054 // explicit operand, rather than implicitly as the standard alignment 14055 // of the memory type (like the intrisics). We need to change the 14056 // memory type to match the explicit alignment. That way, we don't 14057 // generate non-standard-aligned ARMISD::VLDx nodes. 14058 if (isa<LSBaseSDNode>(N)) { 14059 if (Alignment == 0) 14060 Alignment = 1; 14061 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 14062 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 14063 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 14064 assert(!isLaneOp && "Unexpected generic load/store lane."); 14065 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 14066 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 14067 } 14068 // Don't set an explicit alignment on regular load/stores that we want 14069 // to transform to VLD/VST 1_UPD nodes. 14070 // This matches the behavior of regular load/stores, which only get an 14071 // explicit alignment if the MMO alignment is larger than the standard 14072 // alignment of the memory type. 14073 // Intrinsics, however, always get an explicit alignment, set to the 14074 // alignment of the MMO. 14075 Alignment = 1; 14076 } 14077 14078 // Create the new updating load/store node. 14079 // First, create an SDVTList for the new updating node's results. 14080 EVT Tys[6]; 14081 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 14082 unsigned n; 14083 for (n = 0; n < NumResultVecs; ++n) 14084 Tys[n] = AlignedVecTy; 14085 Tys[n++] = MVT::i32; 14086 Tys[n] = MVT::Other; 14087 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 14088 14089 // Then, gather the new node's operands. 14090 SmallVector<SDValue, 8> Ops; 14091 Ops.push_back(N->getOperand(0)); // incoming chain 14092 Ops.push_back(N->getOperand(AddrOpIdx)); 14093 Ops.push_back(Inc); 14094 14095 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 14096 // Try to match the intrinsic's signature 14097 Ops.push_back(StN->getValue()); 14098 } else { 14099 // Loads (and of course intrinsics) match the intrinsics' signature, 14100 // so just add all but the alignment operand. 14101 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 14102 Ops.push_back(N->getOperand(i)); 14103 } 14104 14105 // For all node types, the alignment operand is always the last one. 14106 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 14107 14108 // If this is a non-standard-aligned STORE, the penultimate operand is the 14109 // stored value. Bitcast it to the aligned type. 14110 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 14111 SDValue &StVal = Ops[Ops.size()-2]; 14112 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 14113 } 14114 14115 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 14116 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 14117 MemN->getMemOperand()); 14118 14119 // Update the uses. 14120 SmallVector<SDValue, 5> NewResults; 14121 for (unsigned i = 0; i < NumResultVecs; ++i) 14122 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14123 14124 // If this is an non-standard-aligned LOAD, the first result is the loaded 14125 // value. Bitcast it to the expected result type. 14126 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 14127 SDValue &LdVal = NewResults[0]; 14128 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 14129 } 14130 14131 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 14132 DCI.CombineTo(N, NewResults); 14133 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14134 14135 break; 14136 } 14137 return SDValue(); 14138 } 14139 14140 static SDValue PerformVLDCombine(SDNode *N, 14141 TargetLowering::DAGCombinerInfo &DCI) { 14142 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14143 return SDValue(); 14144 14145 return CombineBaseUpdate(N, DCI); 14146 } 14147 14148 static SDValue PerformMVEVLDCombine(SDNode *N, 14149 TargetLowering::DAGCombinerInfo &DCI) { 14150 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14151 return SDValue(); 14152 14153 SelectionDAG &DAG = DCI.DAG; 14154 SDValue Addr = N->getOperand(2); 14155 MemSDNode *MemN = cast<MemSDNode>(N); 14156 SDLoc dl(N); 14157 14158 // For the stores, where there are multiple intrinsics we only actually want 14159 // to post-inc the last of the them. 14160 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14161 if (IntNo == Intrinsic::arm_mve_vst2q && 14162 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1) 14163 return SDValue(); 14164 if (IntNo == Intrinsic::arm_mve_vst4q && 14165 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3) 14166 return SDValue(); 14167 14168 // Search for a use of the address operand that is an increment. 14169 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14170 UE = Addr.getNode()->use_end(); 14171 UI != UE; ++UI) { 14172 SDNode *User = *UI; 14173 if (User->getOpcode() != ISD::ADD || 14174 UI.getUse().getResNo() != Addr.getResNo()) 14175 continue; 14176 14177 // Check that the add is independent of the load/store. Otherwise, folding 14178 // it would create a cycle. We can avoid searching through Addr as it's a 14179 // predecessor to both. 14180 SmallPtrSet<const SDNode *, 32> Visited; 14181 SmallVector<const SDNode *, 16> Worklist; 14182 Visited.insert(Addr.getNode()); 14183 Worklist.push_back(N); 14184 Worklist.push_back(User); 14185 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14186 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14187 continue; 14188 14189 // Find the new opcode for the updating load/store. 14190 bool isLoadOp = true; 14191 unsigned NewOpc = 0; 14192 unsigned NumVecs = 0; 14193 switch (IntNo) { 14194 default: 14195 llvm_unreachable("unexpected intrinsic for MVE VLDn combine"); 14196 case Intrinsic::arm_mve_vld2q: 14197 NewOpc = ARMISD::VLD2_UPD; 14198 NumVecs = 2; 14199 break; 14200 case Intrinsic::arm_mve_vld4q: 14201 NewOpc = ARMISD::VLD4_UPD; 14202 NumVecs = 4; 14203 break; 14204 case Intrinsic::arm_mve_vst2q: 14205 NewOpc = ARMISD::VST2_UPD; 14206 NumVecs = 2; 14207 isLoadOp = false; 14208 break; 14209 case Intrinsic::arm_mve_vst4q: 14210 NewOpc = ARMISD::VST4_UPD; 14211 NumVecs = 4; 14212 isLoadOp = false; 14213 break; 14214 } 14215 14216 // Find the size of memory referenced by the load/store. 14217 EVT VecTy; 14218 if (isLoadOp) { 14219 VecTy = N->getValueType(0); 14220 } else { 14221 VecTy = N->getOperand(3).getValueType(); 14222 } 14223 14224 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14225 14226 // If the increment is a constant, it must match the memory ref size. 14227 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14228 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 14229 if (!CInc || CInc->getZExtValue() != NumBytes) 14230 continue; 14231 14232 // Create the new updating load/store node. 14233 // First, create an SDVTList for the new updating node's results. 14234 EVT Tys[6]; 14235 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 14236 unsigned n; 14237 for (n = 0; n < NumResultVecs; ++n) 14238 Tys[n] = VecTy; 14239 Tys[n++] = MVT::i32; 14240 Tys[n] = MVT::Other; 14241 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 14242 14243 // Then, gather the new node's operands. 14244 SmallVector<SDValue, 8> Ops; 14245 Ops.push_back(N->getOperand(0)); // incoming chain 14246 Ops.push_back(N->getOperand(2)); // ptr 14247 Ops.push_back(Inc); 14248 14249 for (unsigned i = 3; i < N->getNumOperands(); ++i) 14250 Ops.push_back(N->getOperand(i)); 14251 14252 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy, 14253 MemN->getMemOperand()); 14254 14255 // Update the uses. 14256 SmallVector<SDValue, 5> NewResults; 14257 for (unsigned i = 0; i < NumResultVecs; ++i) 14258 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14259 14260 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain 14261 DCI.CombineTo(N, NewResults); 14262 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14263 14264 break; 14265 } 14266 14267 return SDValue(); 14268 } 14269 14270 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 14271 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 14272 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 14273 /// return true. 14274 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 14275 SelectionDAG &DAG = DCI.DAG; 14276 EVT VT = N->getValueType(0); 14277 // vldN-dup instructions only support 64-bit vectors for N > 1. 14278 if (!VT.is64BitVector()) 14279 return false; 14280 14281 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 14282 SDNode *VLD = N->getOperand(0).getNode(); 14283 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 14284 return false; 14285 unsigned NumVecs = 0; 14286 unsigned NewOpc = 0; 14287 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 14288 if (IntNo == Intrinsic::arm_neon_vld2lane) { 14289 NumVecs = 2; 14290 NewOpc = ARMISD::VLD2DUP; 14291 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 14292 NumVecs = 3; 14293 NewOpc = ARMISD::VLD3DUP; 14294 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 14295 NumVecs = 4; 14296 NewOpc = ARMISD::VLD4DUP; 14297 } else { 14298 return false; 14299 } 14300 14301 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 14302 // numbers match the load. 14303 unsigned VLDLaneNo = 14304 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 14305 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14306 UI != UE; ++UI) { 14307 // Ignore uses of the chain result. 14308 if (UI.getUse().getResNo() == NumVecs) 14309 continue; 14310 SDNode *User = *UI; 14311 if (User->getOpcode() != ARMISD::VDUPLANE || 14312 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 14313 return false; 14314 } 14315 14316 // Create the vldN-dup node. 14317 EVT Tys[5]; 14318 unsigned n; 14319 for (n = 0; n < NumVecs; ++n) 14320 Tys[n] = VT; 14321 Tys[n] = MVT::Other; 14322 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 14323 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 14324 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 14325 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 14326 Ops, VLDMemInt->getMemoryVT(), 14327 VLDMemInt->getMemOperand()); 14328 14329 // Update the uses. 14330 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 14331 UI != UE; ++UI) { 14332 unsigned ResNo = UI.getUse().getResNo(); 14333 // Ignore uses of the chain result. 14334 if (ResNo == NumVecs) 14335 continue; 14336 SDNode *User = *UI; 14337 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 14338 } 14339 14340 // Now the vldN-lane intrinsic is dead except for its chain result. 14341 // Update uses of the chain. 14342 std::vector<SDValue> VLDDupResults; 14343 for (unsigned n = 0; n < NumVecs; ++n) 14344 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 14345 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 14346 DCI.CombineTo(VLD, VLDDupResults); 14347 14348 return true; 14349 } 14350 14351 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 14352 /// ARMISD::VDUPLANE. 14353 static SDValue PerformVDUPLANECombine(SDNode *N, 14354 TargetLowering::DAGCombinerInfo &DCI, 14355 const ARMSubtarget *Subtarget) { 14356 SDValue Op = N->getOperand(0); 14357 EVT VT = N->getValueType(0); 14358 14359 // On MVE, we just convert the VDUPLANE to a VDUP with an extract. 14360 if (Subtarget->hasMVEIntegerOps()) { 14361 EVT ExtractVT = VT.getVectorElementType(); 14362 // We need to ensure we are creating a legal type. 14363 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT)) 14364 ExtractVT = MVT::i32; 14365 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT, 14366 N->getOperand(0), N->getOperand(1)); 14367 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract); 14368 } 14369 14370 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 14371 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 14372 if (CombineVLDDUP(N, DCI)) 14373 return SDValue(N, 0); 14374 14375 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 14376 // redundant. Ignore bit_converts for now; element sizes are checked below. 14377 while (Op.getOpcode() == ISD::BITCAST) 14378 Op = Op.getOperand(0); 14379 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 14380 return SDValue(); 14381 14382 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 14383 unsigned EltSize = Op.getScalarValueSizeInBits(); 14384 // The canonical VMOV for a zero vector uses a 32-bit element size. 14385 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14386 unsigned EltBits; 14387 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 14388 EltSize = 8; 14389 if (EltSize > VT.getScalarSizeInBits()) 14390 return SDValue(); 14391 14392 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 14393 } 14394 14395 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 14396 static SDValue PerformVDUPCombine(SDNode *N, 14397 TargetLowering::DAGCombinerInfo &DCI, 14398 const ARMSubtarget *Subtarget) { 14399 SelectionDAG &DAG = DCI.DAG; 14400 SDValue Op = N->getOperand(0); 14401 SDLoc dl(N); 14402 14403 if (Subtarget->hasMVEIntegerOps()) { 14404 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will 14405 // need to come from a GPR. 14406 if (Op.getValueType() == MVT::f32) 14407 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14408 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op)); 14409 else if (Op.getValueType() == MVT::f16) 14410 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), 14411 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op)); 14412 } 14413 14414 if (!Subtarget->hasNEON()) 14415 return SDValue(); 14416 14417 // Match VDUP(LOAD) -> VLD1DUP. 14418 // We match this pattern here rather than waiting for isel because the 14419 // transform is only legal for unindexed loads. 14420 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 14421 if (LD && Op.hasOneUse() && LD->isUnindexed() && 14422 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 14423 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 14424 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 14425 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 14426 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 14427 Ops, LD->getMemoryVT(), 14428 LD->getMemOperand()); 14429 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 14430 return VLDDup; 14431 } 14432 14433 return SDValue(); 14434 } 14435 14436 static SDValue PerformLOADCombine(SDNode *N, 14437 TargetLowering::DAGCombinerInfo &DCI) { 14438 EVT VT = N->getValueType(0); 14439 14440 // If this is a legal vector load, try to combine it into a VLD1_UPD. 14441 if (ISD::isNormalLoad(N) && VT.isVector() && 14442 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14443 return CombineBaseUpdate(N, DCI); 14444 14445 return SDValue(); 14446 } 14447 14448 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 14449 // pack all of the elements in one place. Next, store to memory in fewer 14450 // chunks. 14451 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St, 14452 SelectionDAG &DAG) { 14453 SDValue StVal = St->getValue(); 14454 EVT VT = StVal.getValueType(); 14455 if (!St->isTruncatingStore() || !VT.isVector()) 14456 return SDValue(); 14457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14458 EVT StVT = St->getMemoryVT(); 14459 unsigned NumElems = VT.getVectorNumElements(); 14460 assert(StVT != VT && "Cannot truncate to the same type"); 14461 unsigned FromEltSz = VT.getScalarSizeInBits(); 14462 unsigned ToEltSz = StVT.getScalarSizeInBits(); 14463 14464 // From, To sizes and ElemCount must be pow of two 14465 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) 14466 return SDValue(); 14467 14468 // We are going to use the original vector elt for storing. 14469 // Accumulated smaller vector elements must be a multiple of the store size. 14470 if (0 != (NumElems * FromEltSz) % ToEltSz) 14471 return SDValue(); 14472 14473 unsigned SizeRatio = FromEltSz / ToEltSz; 14474 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 14475 14476 // Create a type on which we perform the shuffle. 14477 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 14478 NumElems * SizeRatio); 14479 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 14480 14481 SDLoc DL(St); 14482 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 14483 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14484 for (unsigned i = 0; i < NumElems; ++i) 14485 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1 14486 : i * SizeRatio; 14487 14488 // Can't shuffle using an illegal type. 14489 if (!TLI.isTypeLegal(WideVecVT)) 14490 return SDValue(); 14491 14492 SDValue Shuff = DAG.getVectorShuffle( 14493 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec); 14494 // At this point all of the data is stored at the bottom of the 14495 // register. We now need to save it to mem. 14496 14497 // Find the largest store unit 14498 MVT StoreType = MVT::i8; 14499 for (MVT Tp : MVT::integer_valuetypes()) { 14500 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 14501 StoreType = Tp; 14502 } 14503 // Didn't find a legal store type. 14504 if (!TLI.isTypeLegal(StoreType)) 14505 return SDValue(); 14506 14507 // Bitcast the original vector into a vector of store-size units 14508 EVT StoreVecVT = 14509 EVT::getVectorVT(*DAG.getContext(), StoreType, 14510 VT.getSizeInBits() / EVT(StoreType).getSizeInBits()); 14511 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 14512 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 14513 SmallVector<SDValue, 8> Chains; 14514 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 14515 TLI.getPointerTy(DAG.getDataLayout())); 14516 SDValue BasePtr = St->getBasePtr(); 14517 14518 // Perform one or more big stores into memory. 14519 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits(); 14520 for (unsigned I = 0; I < E; I++) { 14521 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType, 14522 ShuffWide, DAG.getIntPtrConstant(I, DL)); 14523 SDValue Ch = 14524 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(), 14525 St->getAlignment(), St->getMemOperand()->getFlags()); 14526 BasePtr = 14527 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment); 14528 Chains.push_back(Ch); 14529 } 14530 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 14531 } 14532 14533 // Try taking a single vector store from an truncate (which would otherwise turn 14534 // into an expensive buildvector) and splitting it into a series of narrowing 14535 // stores. 14536 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, 14537 SelectionDAG &DAG) { 14538 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed()) 14539 return SDValue(); 14540 SDValue Trunc = St->getValue(); 14541 if (Trunc->getOpcode() != ISD::TRUNCATE && Trunc->getOpcode() != ISD::FP_ROUND) 14542 return SDValue(); 14543 EVT FromVT = Trunc->getOperand(0).getValueType(); 14544 EVT ToVT = Trunc.getValueType(); 14545 if (!ToVT.isVector()) 14546 return SDValue(); 14547 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 14548 EVT ToEltVT = ToVT.getVectorElementType(); 14549 EVT FromEltVT = FromVT.getVectorElementType(); 14550 14551 unsigned NumElements = 0; 14552 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8)) 14553 NumElements = 4; 14554 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8) 14555 NumElements = 8; 14556 if (FromEltVT == MVT::f32 && ToEltVT == MVT::f16) 14557 NumElements = 4; 14558 if (NumElements == 0 || 14559 (FromEltVT != MVT::f32 && FromVT.getVectorNumElements() == NumElements) || 14560 FromVT.getVectorNumElements() % NumElements != 0) 14561 return SDValue(); 14562 14563 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so 14564 // use the VMOVN over splitting the store. We are looking for patterns of: 14565 // !rev: 0 N 1 N+1 2 N+2 ... 14566 // rev: N 0 N+1 1 N+2 2 ... 14567 auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) { 14568 unsigned NumElts = ToVT.getVectorNumElements(); 14569 if (NumElts != M.size()) 14570 return false; 14571 14572 unsigned Off0 = rev ? NumElts : 0; 14573 unsigned Off1 = rev ? 0 : NumElts; 14574 14575 for (unsigned i = 0; i < NumElts; i += 2) { 14576 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2)) 14577 return false; 14578 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2)) 14579 return false; 14580 } 14581 14582 return true; 14583 }; 14584 14585 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0))) 14586 if (isVMOVNOriginalMask(Shuffle->getMask(), false) || 14587 isVMOVNOriginalMask(Shuffle->getMask(), true)) 14588 return SDValue(); 14589 14590 LLVMContext &C = *DAG.getContext(); 14591 SDLoc DL(St); 14592 // Details about the old store 14593 SDValue Ch = St->getChain(); 14594 SDValue BasePtr = St->getBasePtr(); 14595 Align Alignment = St->getOriginalAlign(); 14596 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags(); 14597 AAMDNodes AAInfo = St->getAAInfo(); 14598 14599 // We split the store into slices of NumElements. fp16 trunc stores are vcvt 14600 // and then stored as truncating integer stores. 14601 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements); 14602 EVT NewToVT = EVT::getVectorVT( 14603 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements); 14604 14605 SmallVector<SDValue, 4> Stores; 14606 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 14607 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8; 14608 SDValue NewPtr = 14609 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 14610 14611 SDValue Extract = 14612 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0), 14613 DAG.getConstant(i * NumElements, DL, MVT::i32)); 14614 14615 if (ToEltVT == MVT::f16) { 14616 SDValue FPTrunc = 14617 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16), 14618 Extract, DAG.getConstant(0, DL, MVT::i32)); 14619 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc); 14620 } 14621 14622 SDValue Store = DAG.getTruncStore( 14623 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset), 14624 NewToVT, Alignment.value(), MMOFlags, AAInfo); 14625 Stores.push_back(Store); 14626 } 14627 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores); 14628 } 14629 14630 /// PerformSTORECombine - Target-specific dag combine xforms for 14631 /// ISD::STORE. 14632 static SDValue PerformSTORECombine(SDNode *N, 14633 TargetLowering::DAGCombinerInfo &DCI, 14634 const ARMSubtarget *Subtarget) { 14635 StoreSDNode *St = cast<StoreSDNode>(N); 14636 if (St->isVolatile()) 14637 return SDValue(); 14638 SDValue StVal = St->getValue(); 14639 EVT VT = StVal.getValueType(); 14640 14641 if (Subtarget->hasNEON()) 14642 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG)) 14643 return Store; 14644 14645 if (Subtarget->hasMVEIntegerOps()) 14646 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG)) 14647 return NewToken; 14648 14649 if (!ISD::isNormalStore(St)) 14650 return SDValue(); 14651 14652 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 14653 // ARM stores of arguments in the same cache line. 14654 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 14655 StVal.getNode()->hasOneUse()) { 14656 SelectionDAG &DAG = DCI.DAG; 14657 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 14658 SDLoc DL(St); 14659 SDValue BasePtr = St->getBasePtr(); 14660 SDValue NewST1 = DAG.getStore( 14661 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 14662 BasePtr, St->getPointerInfo(), St->getOriginalAlign(), 14663 St->getMemOperand()->getFlags()); 14664 14665 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 14666 DAG.getConstant(4, DL, MVT::i32)); 14667 return DAG.getStore(NewST1.getValue(0), DL, 14668 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 14669 OffsetPtr, St->getPointerInfo().getWithOffset(4), 14670 St->getOriginalAlign(), 14671 St->getMemOperand()->getFlags()); 14672 } 14673 14674 if (StVal.getValueType() == MVT::i64 && 14675 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14676 14677 // Bitcast an i64 store extracted from a vector to f64. 14678 // Otherwise, the i64 value will be legalized to a pair of i32 values. 14679 SelectionDAG &DAG = DCI.DAG; 14680 SDLoc dl(StVal); 14681 SDValue IntVec = StVal.getOperand(0); 14682 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 14683 IntVec.getValueType().getVectorNumElements()); 14684 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 14685 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 14686 Vec, StVal.getOperand(1)); 14687 dl = SDLoc(N); 14688 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 14689 // Make the DAGCombiner fold the bitcasts. 14690 DCI.AddToWorklist(Vec.getNode()); 14691 DCI.AddToWorklist(ExtElt.getNode()); 14692 DCI.AddToWorklist(V.getNode()); 14693 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 14694 St->getPointerInfo(), St->getAlignment(), 14695 St->getMemOperand()->getFlags(), St->getAAInfo()); 14696 } 14697 14698 // If this is a legal vector store, try to combine it into a VST1_UPD. 14699 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() && 14700 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 14701 return CombineBaseUpdate(N, DCI); 14702 14703 return SDValue(); 14704 } 14705 14706 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 14707 /// can replace combinations of VMUL and VCVT (floating-point to integer) 14708 /// when the VMUL has a constant operand that is a power of 2. 14709 /// 14710 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14711 /// vmul.f32 d16, d17, d16 14712 /// vcvt.s32.f32 d16, d16 14713 /// becomes: 14714 /// vcvt.s32.f32 d16, d16, #3 14715 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 14716 const ARMSubtarget *Subtarget) { 14717 if (!Subtarget->hasNEON()) 14718 return SDValue(); 14719 14720 SDValue Op = N->getOperand(0); 14721 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 14722 Op.getOpcode() != ISD::FMUL) 14723 return SDValue(); 14724 14725 SDValue ConstVec = Op->getOperand(1); 14726 if (!isa<BuildVectorSDNode>(ConstVec)) 14727 return SDValue(); 14728 14729 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 14730 uint32_t FloatBits = FloatTy.getSizeInBits(); 14731 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 14732 uint32_t IntBits = IntTy.getSizeInBits(); 14733 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14734 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14735 // These instructions only exist converting from f32 to i32. We can handle 14736 // smaller integers by generating an extra truncate, but larger ones would 14737 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14738 // these intructions only support v2i32/v4i32 types. 14739 return SDValue(); 14740 } 14741 14742 BitVector UndefElements; 14743 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14744 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14745 if (C == -1 || C == 0 || C > 32) 14746 return SDValue(); 14747 14748 SDLoc dl(N); 14749 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 14750 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 14751 Intrinsic::arm_neon_vcvtfp2fxu; 14752 SDValue FixConv = DAG.getNode( 14753 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14754 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 14755 DAG.getConstant(C, dl, MVT::i32)); 14756 14757 if (IntBits < FloatBits) 14758 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 14759 14760 return FixConv; 14761 } 14762 14763 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 14764 /// can replace combinations of VCVT (integer to floating-point) and VDIV 14765 /// when the VDIV has a constant operand that is a power of 2. 14766 /// 14767 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 14768 /// vcvt.f32.s32 d16, d16 14769 /// vdiv.f32 d16, d17, d16 14770 /// becomes: 14771 /// vcvt.f32.s32 d16, d16, #3 14772 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 14773 const ARMSubtarget *Subtarget) { 14774 if (!Subtarget->hasNEON()) 14775 return SDValue(); 14776 14777 SDValue Op = N->getOperand(0); 14778 unsigned OpOpcode = Op.getNode()->getOpcode(); 14779 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 14780 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 14781 return SDValue(); 14782 14783 SDValue ConstVec = N->getOperand(1); 14784 if (!isa<BuildVectorSDNode>(ConstVec)) 14785 return SDValue(); 14786 14787 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 14788 uint32_t FloatBits = FloatTy.getSizeInBits(); 14789 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 14790 uint32_t IntBits = IntTy.getSizeInBits(); 14791 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 14792 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 14793 // These instructions only exist converting from i32 to f32. We can handle 14794 // smaller integers by generating an extra extend, but larger ones would 14795 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 14796 // these intructions only support v2i32/v4i32 types. 14797 return SDValue(); 14798 } 14799 14800 BitVector UndefElements; 14801 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 14802 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 14803 if (C == -1 || C == 0 || C > 32) 14804 return SDValue(); 14805 14806 SDLoc dl(N); 14807 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 14808 SDValue ConvInput = Op.getOperand(0); 14809 if (IntBits < FloatBits) 14810 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 14811 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 14812 ConvInput); 14813 14814 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 14815 Intrinsic::arm_neon_vcvtfxu2fp; 14816 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 14817 Op.getValueType(), 14818 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 14819 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 14820 } 14821 14822 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG, 14823 const ARMSubtarget *ST) { 14824 if (!ST->hasMVEIntegerOps()) 14825 return SDValue(); 14826 14827 assert(N->getOpcode() == ISD::VECREDUCE_ADD); 14828 EVT ResVT = N->getValueType(0); 14829 SDValue N0 = N->getOperand(0); 14830 SDLoc dl(N); 14831 14832 // We are looking for something that will have illegal types if left alone, 14833 // but that we can convert to a single instruction undef MVE. For example 14834 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A 14835 // or 14836 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B 14837 14838 // Cases: 14839 // VADDV u/s 8/16/32 14840 // VMLAV u/s 8/16/32 14841 // VADDLV u/s 32 14842 // VMLALV u/s 16/32 14843 14844 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) { 14845 if (ResVT != RetTy || N0->getOpcode() != ExtendCode) 14846 return SDValue(); 14847 SDValue A = N0->getOperand(0); 14848 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14849 return A; 14850 return SDValue(); 14851 }; 14852 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode, 14853 ArrayRef<MVT> ExtTypes, SDValue &Mask) { 14854 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 14855 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 14856 return SDValue(); 14857 Mask = N0->getOperand(0); 14858 SDValue Ext = N0->getOperand(1); 14859 if (Ext->getOpcode() != ExtendCode) 14860 return SDValue(); 14861 SDValue A = Ext->getOperand(0); 14862 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14863 return A; 14864 return SDValue(); 14865 }; 14866 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 14867 SDValue &A, SDValue &B) { 14868 // For a vmla we are trying to match a larger pattern: 14869 // ExtA = sext/zext A 14870 // ExtB = sext/zext B 14871 // Mul = mul ExtA, ExtB 14872 // vecreduce.add Mul 14873 // There might also be en extra extend between the mul and the addreduce, so 14874 // long as the bitwidth is high enough to make them equivalent (for example 14875 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64). 14876 if (ResVT != RetTy) 14877 return false; 14878 SDValue Mul = N0; 14879 if (Mul->getOpcode() == ExtendCode && 14880 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >= 14881 ResVT.getScalarSizeInBits()) 14882 Mul = Mul->getOperand(0); 14883 if (Mul->getOpcode() != ISD::MUL) 14884 return false; 14885 SDValue ExtA = Mul->getOperand(0); 14886 SDValue ExtB = Mul->getOperand(1); 14887 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 14888 return false; 14889 A = ExtA->getOperand(0); 14890 B = ExtB->getOperand(0); 14891 if (A.getValueType() == B.getValueType() && 14892 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14893 return true; 14894 return false; 14895 }; 14896 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes, 14897 SDValue &A, SDValue &B, SDValue &Mask) { 14898 // Same as the pattern above with a select for the zero predicated lanes 14899 // ExtA = sext/zext A 14900 // ExtB = sext/zext B 14901 // Mul = mul ExtA, ExtB 14902 // N0 = select Mask, Mul, 0 14903 // vecreduce.add N0 14904 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT || 14905 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode())) 14906 return false; 14907 Mask = N0->getOperand(0); 14908 SDValue Mul = N0->getOperand(1); 14909 if (Mul->getOpcode() == ExtendCode && 14910 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >= 14911 ResVT.getScalarSizeInBits()) 14912 Mul = Mul->getOperand(0); 14913 if (Mul->getOpcode() != ISD::MUL) 14914 return false; 14915 SDValue ExtA = Mul->getOperand(0); 14916 SDValue ExtB = Mul->getOperand(1); 14917 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode) 14918 return false; 14919 A = ExtA->getOperand(0); 14920 B = ExtB->getOperand(0); 14921 if (A.getValueType() == B.getValueType() && 14922 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; })) 14923 return true; 14924 return false; 14925 }; 14926 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) { 14927 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops); 14928 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node, 14929 SDValue(Node.getNode(), 1)); 14930 }; 14931 14932 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8})) 14933 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A); 14934 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8})) 14935 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A); 14936 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32})) 14937 return Create64bitNode(ARMISD::VADDLVs, {A}); 14938 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32})) 14939 return Create64bitNode(ARMISD::VADDLVu, {A}); 14940 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8})) 14941 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14942 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A)); 14943 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8})) 14944 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14945 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A)); 14946 14947 SDValue Mask; 14948 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 14949 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask); 14950 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask)) 14951 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask); 14952 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask)) 14953 return Create64bitNode(ARMISD::VADDLVps, {A, Mask}); 14954 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask)) 14955 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask}); 14956 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask)) 14957 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14958 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask)); 14959 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask)) 14960 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14961 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask)); 14962 14963 SDValue A, B; 14964 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 14965 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B); 14966 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B)) 14967 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B); 14968 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 14969 return Create64bitNode(ARMISD::VMLALVs, {A, B}); 14970 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B)) 14971 return Create64bitNode(ARMISD::VMLALVu, {A, B}); 14972 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B)) 14973 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14974 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B)); 14975 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B)) 14976 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14977 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B)); 14978 14979 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 14980 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask); 14981 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask)) 14982 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask); 14983 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask)) 14984 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask}); 14985 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask)) 14986 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask}); 14987 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask)) 14988 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14989 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask)); 14990 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask)) 14991 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, 14992 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask)); 14993 14994 // Some complications. We can get a case where the two inputs of the mul are 14995 // the same, then the output sext will have been helpfully converted to a 14996 // zext. Turn it back. 14997 SDValue Op = N0; 14998 if (Op->getOpcode() == ISD::VSELECT) 14999 Op = Op->getOperand(1); 15000 if (Op->getOpcode() == ISD::ZERO_EXTEND && 15001 Op->getOperand(0)->getOpcode() == ISD::MUL) { 15002 SDValue Mul = Op->getOperand(0); 15003 if (Mul->getOperand(0) == Mul->getOperand(1) && 15004 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) { 15005 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul); 15006 if (Op != N0) 15007 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0), 15008 N0->getOperand(0), Ext, N0->getOperand(2)); 15009 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext); 15010 } 15011 } 15012 15013 return SDValue(); 15014 } 15015 15016 static SDValue PerformVMOVNCombine(SDNode *N, 15017 TargetLowering::DAGCombinerInfo &DCI) { 15018 SDValue Op0 = N->getOperand(0); 15019 SDValue Op1 = N->getOperand(1); 15020 unsigned IsTop = N->getConstantOperandVal(2); 15021 15022 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b) 15023 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b) 15024 if ((Op1->getOpcode() == ARMISD::VQMOVNs || 15025 Op1->getOpcode() == ARMISD::VQMOVNu) && 15026 Op1->getConstantOperandVal(2) == 0) 15027 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0), 15028 Op0, Op1->getOperand(1), N->getOperand(2)); 15029 15030 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from 15031 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting 15032 // into the top or bottom lanes. 15033 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 15034 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1)); 15035 APInt Op0DemandedElts = 15036 IsTop ? Op1DemandedElts 15037 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1)); 15038 15039 APInt KnownUndef, KnownZero; 15040 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 15041 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 15042 KnownZero, DCI)) 15043 return SDValue(N, 0); 15044 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef, 15045 KnownZero, DCI)) 15046 return SDValue(N, 0); 15047 15048 return SDValue(); 15049 } 15050 15051 static SDValue PerformVQMOVNCombine(SDNode *N, 15052 TargetLowering::DAGCombinerInfo &DCI) { 15053 SDValue Op0 = N->getOperand(0); 15054 unsigned IsTop = N->getConstantOperandVal(2); 15055 15056 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 15057 APInt Op0DemandedElts = 15058 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1) 15059 : APInt::getHighBitsSet(2, 1)); 15060 15061 APInt KnownUndef, KnownZero; 15062 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo(); 15063 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef, 15064 KnownZero, DCI)) 15065 return SDValue(N, 0); 15066 return SDValue(); 15067 } 15068 15069 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) { 15070 SDLoc DL(N); 15071 SDValue Op0 = N->getOperand(0); 15072 SDValue Op1 = N->getOperand(1); 15073 15074 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from 15075 // uses of the intrinsics. 15076 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 15077 int ShiftAmt = C->getSExtValue(); 15078 if (ShiftAmt == 0) { 15079 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL); 15080 DAG.ReplaceAllUsesWith(N, Merge.getNode()); 15081 return SDValue(); 15082 } 15083 15084 if (ShiftAmt >= -32 && ShiftAmt < 0) { 15085 unsigned NewOpcode = 15086 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL; 15087 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1, 15088 DAG.getConstant(-ShiftAmt, DL, MVT::i32)); 15089 DAG.ReplaceAllUsesWith(N, NewShift.getNode()); 15090 return NewShift; 15091 } 15092 } 15093 15094 return SDValue(); 15095 } 15096 15097 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 15098 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N, 15099 DAGCombinerInfo &DCI) const { 15100 SelectionDAG &DAG = DCI.DAG; 15101 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15102 switch (IntNo) { 15103 default: 15104 // Don't do anything for most intrinsics. 15105 break; 15106 15107 // Vector shifts: check for immediate versions and lower them. 15108 // Note: This is done during DAG combining instead of DAG legalizing because 15109 // the build_vectors for 64-bit vector element shift counts are generally 15110 // not legal, and it is hard to see their values after they get legalized to 15111 // loads from a constant pool. 15112 case Intrinsic::arm_neon_vshifts: 15113 case Intrinsic::arm_neon_vshiftu: 15114 case Intrinsic::arm_neon_vrshifts: 15115 case Intrinsic::arm_neon_vrshiftu: 15116 case Intrinsic::arm_neon_vrshiftn: 15117 case Intrinsic::arm_neon_vqshifts: 15118 case Intrinsic::arm_neon_vqshiftu: 15119 case Intrinsic::arm_neon_vqshiftsu: 15120 case Intrinsic::arm_neon_vqshiftns: 15121 case Intrinsic::arm_neon_vqshiftnu: 15122 case Intrinsic::arm_neon_vqshiftnsu: 15123 case Intrinsic::arm_neon_vqrshiftns: 15124 case Intrinsic::arm_neon_vqrshiftnu: 15125 case Intrinsic::arm_neon_vqrshiftnsu: { 15126 EVT VT = N->getOperand(1).getValueType(); 15127 int64_t Cnt; 15128 unsigned VShiftOpc = 0; 15129 15130 switch (IntNo) { 15131 case Intrinsic::arm_neon_vshifts: 15132 case Intrinsic::arm_neon_vshiftu: 15133 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 15134 VShiftOpc = ARMISD::VSHLIMM; 15135 break; 15136 } 15137 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 15138 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 15139 : ARMISD::VSHRuIMM); 15140 break; 15141 } 15142 return SDValue(); 15143 15144 case Intrinsic::arm_neon_vrshifts: 15145 case Intrinsic::arm_neon_vrshiftu: 15146 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 15147 break; 15148 return SDValue(); 15149 15150 case Intrinsic::arm_neon_vqshifts: 15151 case Intrinsic::arm_neon_vqshiftu: 15152 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15153 break; 15154 return SDValue(); 15155 15156 case Intrinsic::arm_neon_vqshiftsu: 15157 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 15158 break; 15159 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 15160 15161 case Intrinsic::arm_neon_vrshiftn: 15162 case Intrinsic::arm_neon_vqshiftns: 15163 case Intrinsic::arm_neon_vqshiftnu: 15164 case Intrinsic::arm_neon_vqshiftnsu: 15165 case Intrinsic::arm_neon_vqrshiftns: 15166 case Intrinsic::arm_neon_vqrshiftnu: 15167 case Intrinsic::arm_neon_vqrshiftnsu: 15168 // Narrowing shifts require an immediate right shift. 15169 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 15170 break; 15171 llvm_unreachable("invalid shift count for narrowing vector shift " 15172 "intrinsic"); 15173 15174 default: 15175 llvm_unreachable("unhandled vector shift"); 15176 } 15177 15178 switch (IntNo) { 15179 case Intrinsic::arm_neon_vshifts: 15180 case Intrinsic::arm_neon_vshiftu: 15181 // Opcode already set above. 15182 break; 15183 case Intrinsic::arm_neon_vrshifts: 15184 VShiftOpc = ARMISD::VRSHRsIMM; 15185 break; 15186 case Intrinsic::arm_neon_vrshiftu: 15187 VShiftOpc = ARMISD::VRSHRuIMM; 15188 break; 15189 case Intrinsic::arm_neon_vrshiftn: 15190 VShiftOpc = ARMISD::VRSHRNIMM; 15191 break; 15192 case Intrinsic::arm_neon_vqshifts: 15193 VShiftOpc = ARMISD::VQSHLsIMM; 15194 break; 15195 case Intrinsic::arm_neon_vqshiftu: 15196 VShiftOpc = ARMISD::VQSHLuIMM; 15197 break; 15198 case Intrinsic::arm_neon_vqshiftsu: 15199 VShiftOpc = ARMISD::VQSHLsuIMM; 15200 break; 15201 case Intrinsic::arm_neon_vqshiftns: 15202 VShiftOpc = ARMISD::VQSHRNsIMM; 15203 break; 15204 case Intrinsic::arm_neon_vqshiftnu: 15205 VShiftOpc = ARMISD::VQSHRNuIMM; 15206 break; 15207 case Intrinsic::arm_neon_vqshiftnsu: 15208 VShiftOpc = ARMISD::VQSHRNsuIMM; 15209 break; 15210 case Intrinsic::arm_neon_vqrshiftns: 15211 VShiftOpc = ARMISD::VQRSHRNsIMM; 15212 break; 15213 case Intrinsic::arm_neon_vqrshiftnu: 15214 VShiftOpc = ARMISD::VQRSHRNuIMM; 15215 break; 15216 case Intrinsic::arm_neon_vqrshiftnsu: 15217 VShiftOpc = ARMISD::VQRSHRNsuIMM; 15218 break; 15219 } 15220 15221 SDLoc dl(N); 15222 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15223 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 15224 } 15225 15226 case Intrinsic::arm_neon_vshiftins: { 15227 EVT VT = N->getOperand(1).getValueType(); 15228 int64_t Cnt; 15229 unsigned VShiftOpc = 0; 15230 15231 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 15232 VShiftOpc = ARMISD::VSLIIMM; 15233 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 15234 VShiftOpc = ARMISD::VSRIIMM; 15235 else { 15236 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 15237 } 15238 15239 SDLoc dl(N); 15240 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 15241 N->getOperand(1), N->getOperand(2), 15242 DAG.getConstant(Cnt, dl, MVT::i32)); 15243 } 15244 15245 case Intrinsic::arm_neon_vqrshifts: 15246 case Intrinsic::arm_neon_vqrshiftu: 15247 // No immediate versions of these to check for. 15248 break; 15249 15250 case Intrinsic::arm_mve_vqdmlah: 15251 case Intrinsic::arm_mve_vqdmlash: 15252 case Intrinsic::arm_mve_vqrdmlah: 15253 case Intrinsic::arm_mve_vqrdmlash: 15254 case Intrinsic::arm_mve_vmla_n_predicated: 15255 case Intrinsic::arm_mve_vmlas_n_predicated: 15256 case Intrinsic::arm_mve_vqdmlah_predicated: 15257 case Intrinsic::arm_mve_vqdmlash_predicated: 15258 case Intrinsic::arm_mve_vqrdmlah_predicated: 15259 case Intrinsic::arm_mve_vqrdmlash_predicated: { 15260 // These intrinsics all take an i32 scalar operand which is narrowed to the 15261 // size of a single lane of the vector type they return. So we don't need 15262 // any bits of that operand above that point, which allows us to eliminate 15263 // uxth/sxth. 15264 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits(); 15265 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15266 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI)) 15267 return SDValue(); 15268 break; 15269 } 15270 15271 case Intrinsic::arm_mve_minv: 15272 case Intrinsic::arm_mve_maxv: 15273 case Intrinsic::arm_mve_minav: 15274 case Intrinsic::arm_mve_maxav: 15275 case Intrinsic::arm_mve_minv_predicated: 15276 case Intrinsic::arm_mve_maxv_predicated: 15277 case Intrinsic::arm_mve_minav_predicated: 15278 case Intrinsic::arm_mve_maxav_predicated: { 15279 // These intrinsics all take an i32 scalar operand which is narrowed to the 15280 // size of a single lane of the vector type they take as the other input. 15281 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits(); 15282 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth); 15283 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 15284 return SDValue(); 15285 break; 15286 } 15287 15288 case Intrinsic::arm_mve_addv: { 15289 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node, 15290 // which allow PerformADDVecReduce to turn it into VADDLV when possible. 15291 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15292 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs; 15293 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1)); 15294 } 15295 15296 case Intrinsic::arm_mve_addlv: 15297 case Intrinsic::arm_mve_addlv_predicated: { 15298 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR 15299 // which recombines the two outputs into an i64 15300 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15301 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ? 15302 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) : 15303 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps); 15304 15305 SmallVector<SDValue, 4> Ops; 15306 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++) 15307 if (i != 2) // skip the unsigned flag 15308 Ops.push_back(N->getOperand(i)); 15309 15310 SDLoc dl(N); 15311 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops); 15312 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0), 15313 val.getValue(1)); 15314 } 15315 } 15316 15317 return SDValue(); 15318 } 15319 15320 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 15321 /// lowers them. As with the vector shift intrinsics, this is done during DAG 15322 /// combining instead of DAG legalizing because the build_vectors for 64-bit 15323 /// vector element shift counts are generally not legal, and it is hard to see 15324 /// their values after they get legalized to loads from a constant pool. 15325 static SDValue PerformShiftCombine(SDNode *N, 15326 TargetLowering::DAGCombinerInfo &DCI, 15327 const ARMSubtarget *ST) { 15328 SelectionDAG &DAG = DCI.DAG; 15329 EVT VT = N->getValueType(0); 15330 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 15331 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 15332 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 15333 SDValue N1 = N->getOperand(1); 15334 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 15335 SDValue N0 = N->getOperand(0); 15336 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 15337 DAG.MaskedValueIsZero(N0.getOperand(0), 15338 APInt::getHighBitsSet(32, 16))) 15339 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 15340 } 15341 } 15342 15343 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 15344 N->getOperand(0)->getOpcode() == ISD::AND && 15345 N->getOperand(0)->hasOneUse()) { 15346 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 15347 return SDValue(); 15348 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 15349 // usually show up because instcombine prefers to canonicalize it to 15350 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 15351 // out of GEP lowering in some cases. 15352 SDValue N0 = N->getOperand(0); 15353 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15354 if (!ShiftAmtNode) 15355 return SDValue(); 15356 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 15357 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15358 if (!AndMaskNode) 15359 return SDValue(); 15360 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 15361 // Don't transform uxtb/uxth. 15362 if (AndMask == 255 || AndMask == 65535) 15363 return SDValue(); 15364 if (isMask_32(AndMask)) { 15365 uint32_t MaskedBits = countLeadingZeros(AndMask); 15366 if (MaskedBits > ShiftAmt) { 15367 SDLoc DL(N); 15368 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 15369 DAG.getConstant(MaskedBits, DL, MVT::i32)); 15370 return DAG.getNode( 15371 ISD::SRL, DL, MVT::i32, SHL, 15372 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 15373 } 15374 } 15375 } 15376 15377 // Nothing to be done for scalar shifts. 15378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15379 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 15380 return SDValue(); 15381 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 15382 return SDValue(); 15383 15384 int64_t Cnt; 15385 15386 switch (N->getOpcode()) { 15387 default: llvm_unreachable("unexpected shift opcode"); 15388 15389 case ISD::SHL: 15390 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 15391 SDLoc dl(N); 15392 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 15393 DAG.getConstant(Cnt, dl, MVT::i32)); 15394 } 15395 break; 15396 15397 case ISD::SRA: 15398 case ISD::SRL: 15399 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 15400 unsigned VShiftOpc = 15401 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 15402 SDLoc dl(N); 15403 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 15404 DAG.getConstant(Cnt, dl, MVT::i32)); 15405 } 15406 } 15407 return SDValue(); 15408 } 15409 15410 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be 15411 // split into multiple extending loads, which are simpler to deal with than an 15412 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL 15413 // to convert the type to an f32. 15414 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) { 15415 SDValue N0 = N->getOperand(0); 15416 if (N0.getOpcode() != ISD::LOAD) 15417 return SDValue(); 15418 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode()); 15419 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() || 15420 LD->getExtensionType() != ISD::NON_EXTLOAD) 15421 return SDValue(); 15422 EVT FromVT = LD->getValueType(0); 15423 EVT ToVT = N->getValueType(0); 15424 if (!ToVT.isVector()) 15425 return SDValue(); 15426 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements()); 15427 EVT ToEltVT = ToVT.getVectorElementType(); 15428 EVT FromEltVT = FromVT.getVectorElementType(); 15429 15430 unsigned NumElements = 0; 15431 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8)) 15432 NumElements = 4; 15433 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8) 15434 NumElements = 8; 15435 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16) 15436 NumElements = 4; 15437 if (NumElements == 0 || 15438 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) || 15439 FromVT.getVectorNumElements() % NumElements != 0 || 15440 !isPowerOf2_32(NumElements)) 15441 return SDValue(); 15442 15443 LLVMContext &C = *DAG.getContext(); 15444 SDLoc DL(LD); 15445 // Details about the old load 15446 SDValue Ch = LD->getChain(); 15447 SDValue BasePtr = LD->getBasePtr(); 15448 Align Alignment = LD->getOriginalAlign(); 15449 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 15450 AAMDNodes AAInfo = LD->getAAInfo(); 15451 15452 ISD::LoadExtType NewExtType = 15453 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 15454 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType()); 15455 EVT NewFromVT = EVT::getVectorVT( 15456 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements); 15457 EVT NewToVT = EVT::getVectorVT( 15458 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements); 15459 15460 SmallVector<SDValue, 4> Loads; 15461 SmallVector<SDValue, 4> Chains; 15462 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) { 15463 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8; 15464 SDValue NewPtr = 15465 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset)); 15466 15467 SDValue NewLoad = 15468 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset, 15469 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT, 15470 Alignment, MMOFlags, AAInfo); 15471 Loads.push_back(NewLoad); 15472 Chains.push_back(SDValue(NewLoad.getNode(), 1)); 15473 } 15474 15475 // Float truncs need to extended with VCVTB's into their floating point types. 15476 if (FromEltVT == MVT::f16) { 15477 SmallVector<SDValue, 4> Extends; 15478 15479 for (unsigned i = 0; i < Loads.size(); i++) { 15480 SDValue LoadBC = 15481 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]); 15482 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC, 15483 DAG.getConstant(0, DL, MVT::i32)); 15484 Extends.push_back(FPExt); 15485 } 15486 15487 Loads = Extends; 15488 } 15489 15490 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 15491 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain); 15492 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads); 15493 } 15494 15495 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 15496 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 15497 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 15498 const ARMSubtarget *ST) { 15499 SDValue N0 = N->getOperand(0); 15500 15501 // Check for sign- and zero-extensions of vector extract operations of 8- and 15502 // 16-bit vector elements. NEON and MVE support these directly. They are 15503 // handled during DAG combining because type legalization will promote them 15504 // to 32-bit types and it is messy to recognize the operations after that. 15505 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) && 15506 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15507 SDValue Vec = N0.getOperand(0); 15508 SDValue Lane = N0.getOperand(1); 15509 EVT VT = N->getValueType(0); 15510 EVT EltVT = N0.getValueType(); 15511 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15512 15513 if (VT == MVT::i32 && 15514 (EltVT == MVT::i8 || EltVT == MVT::i16) && 15515 TLI.isTypeLegal(Vec.getValueType()) && 15516 isa<ConstantSDNode>(Lane)) { 15517 15518 unsigned Opc = 0; 15519 switch (N->getOpcode()) { 15520 default: llvm_unreachable("unexpected opcode"); 15521 case ISD::SIGN_EXTEND: 15522 Opc = ARMISD::VGETLANEs; 15523 break; 15524 case ISD::ZERO_EXTEND: 15525 case ISD::ANY_EXTEND: 15526 Opc = ARMISD::VGETLANEu; 15527 break; 15528 } 15529 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 15530 } 15531 } 15532 15533 if (ST->hasMVEIntegerOps()) 15534 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 15535 return NewLoad; 15536 15537 return SDValue(); 15538 } 15539 15540 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG, 15541 const ARMSubtarget *ST) { 15542 if (ST->hasMVEFloatOps()) 15543 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG)) 15544 return NewLoad; 15545 15546 return SDValue(); 15547 } 15548 15549 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating 15550 /// saturates. 15551 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG, 15552 const ARMSubtarget *ST) { 15553 EVT VT = N->getValueType(0); 15554 SDValue N0 = N->getOperand(0); 15555 if (!ST->hasMVEIntegerOps()) 15556 return SDValue(); 15557 15558 if (VT != MVT::v4i32 && VT != MVT::v8i16) 15559 return SDValue(); 15560 15561 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) { 15562 // Check one is a smin and the other is a smax 15563 if (Min->getOpcode() != ISD::SMIN) 15564 std::swap(Min, Max); 15565 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX) 15566 return false; 15567 15568 APInt SaturateC; 15569 if (VT == MVT::v4i32) 15570 SaturateC = APInt(32, (1 << 15) - 1, true); 15571 else //if (VT == MVT::v8i16) 15572 SaturateC = APInt(16, (1 << 7) - 1, true); 15573 15574 APInt MinC, MaxC; 15575 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 15576 MinC != SaturateC) 15577 return false; 15578 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) || 15579 MaxC != ~SaturateC) 15580 return false; 15581 return true; 15582 }; 15583 15584 if (IsSignedSaturate(N, N0.getNode())) { 15585 SDLoc DL(N); 15586 MVT ExtVT, HalfVT; 15587 if (VT == MVT::v4i32) { 15588 HalfVT = MVT::v8i16; 15589 ExtVT = MVT::v4i16; 15590 } else { // if (VT == MVT::v8i16) 15591 HalfVT = MVT::v16i8; 15592 ExtVT = MVT::v8i8; 15593 } 15594 15595 // Create a VQMOVNB with undef top lanes, then signed extended into the top 15596 // half. That extend will hopefully be removed if only the bottom bits are 15597 // demanded (though a truncating store, for example). 15598 SDValue VQMOVN = 15599 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT), 15600 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32)); 15601 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 15602 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast, 15603 DAG.getValueType(ExtVT)); 15604 } 15605 15606 auto IsUnsignedSaturate = [&](SDNode *Min) { 15607 // For unsigned, we just need to check for <= 0xffff 15608 if (Min->getOpcode() != ISD::UMIN) 15609 return false; 15610 15611 APInt SaturateC; 15612 if (VT == MVT::v4i32) 15613 SaturateC = APInt(32, (1 << 16) - 1, true); 15614 else //if (VT == MVT::v8i16) 15615 SaturateC = APInt(16, (1 << 8) - 1, true); 15616 15617 APInt MinC; 15618 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) || 15619 MinC != SaturateC) 15620 return false; 15621 return true; 15622 }; 15623 15624 if (IsUnsignedSaturate(N)) { 15625 SDLoc DL(N); 15626 MVT HalfVT; 15627 unsigned ExtConst; 15628 if (VT == MVT::v4i32) { 15629 HalfVT = MVT::v8i16; 15630 ExtConst = 0x0000FFFF; 15631 } else { //if (VT == MVT::v8i16) 15632 HalfVT = MVT::v16i8; 15633 ExtConst = 0x00FF; 15634 } 15635 15636 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with 15637 // an AND. That extend will hopefully be removed if only the bottom bits are 15638 // demanded (though a truncating store, for example). 15639 SDValue VQMOVN = 15640 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0, 15641 DAG.getConstant(0, DL, MVT::i32)); 15642 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN); 15643 return DAG.getNode(ISD::AND, DL, VT, Bitcast, 15644 DAG.getConstant(ExtConst, DL, VT)); 15645 } 15646 15647 return SDValue(); 15648 } 15649 15650 static const APInt *isPowerOf2Constant(SDValue V) { 15651 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 15652 if (!C) 15653 return nullptr; 15654 const APInt *CV = &C->getAPIntValue(); 15655 return CV->isPowerOf2() ? CV : nullptr; 15656 } 15657 15658 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 15659 // If we have a CMOV, OR and AND combination such as: 15660 // if (x & CN) 15661 // y |= CM; 15662 // 15663 // And: 15664 // * CN is a single bit; 15665 // * All bits covered by CM are known zero in y 15666 // 15667 // Then we can convert this into a sequence of BFI instructions. This will 15668 // always be a win if CM is a single bit, will always be no worse than the 15669 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 15670 // three bits (due to the extra IT instruction). 15671 15672 SDValue Op0 = CMOV->getOperand(0); 15673 SDValue Op1 = CMOV->getOperand(1); 15674 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 15675 auto CC = CCNode->getAPIntValue().getLimitedValue(); 15676 SDValue CmpZ = CMOV->getOperand(4); 15677 15678 // The compare must be against zero. 15679 if (!isNullConstant(CmpZ->getOperand(1))) 15680 return SDValue(); 15681 15682 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 15683 SDValue And = CmpZ->getOperand(0); 15684 if (And->getOpcode() != ISD::AND) 15685 return SDValue(); 15686 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 15687 if (!AndC) 15688 return SDValue(); 15689 SDValue X = And->getOperand(0); 15690 15691 if (CC == ARMCC::EQ) { 15692 // We're performing an "equal to zero" compare. Swap the operands so we 15693 // canonicalize on a "not equal to zero" compare. 15694 std::swap(Op0, Op1); 15695 } else { 15696 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 15697 } 15698 15699 if (Op1->getOpcode() != ISD::OR) 15700 return SDValue(); 15701 15702 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 15703 if (!OrC) 15704 return SDValue(); 15705 SDValue Y = Op1->getOperand(0); 15706 15707 if (Op0 != Y) 15708 return SDValue(); 15709 15710 // Now, is it profitable to continue? 15711 APInt OrCI = OrC->getAPIntValue(); 15712 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 15713 if (OrCI.countPopulation() > Heuristic) 15714 return SDValue(); 15715 15716 // Lastly, can we determine that the bits defined by OrCI 15717 // are zero in Y? 15718 KnownBits Known = DAG.computeKnownBits(Y); 15719 if ((OrCI & Known.Zero) != OrCI) 15720 return SDValue(); 15721 15722 // OK, we can do the combine. 15723 SDValue V = Y; 15724 SDLoc dl(X); 15725 EVT VT = X.getValueType(); 15726 unsigned BitInX = AndC->logBase2(); 15727 15728 if (BitInX != 0) { 15729 // We must shift X first. 15730 X = DAG.getNode(ISD::SRL, dl, VT, X, 15731 DAG.getConstant(BitInX, dl, VT)); 15732 } 15733 15734 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 15735 BitInY < NumActiveBits; ++BitInY) { 15736 if (OrCI[BitInY] == 0) 15737 continue; 15738 APInt Mask(VT.getSizeInBits(), 0); 15739 Mask.setBit(BitInY); 15740 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 15741 // Confusingly, the operand is an *inverted* mask. 15742 DAG.getConstant(~Mask, dl, VT)); 15743 } 15744 15745 return V; 15746 } 15747 15748 // Given N, the value controlling the conditional branch, search for the loop 15749 // intrinsic, returning it, along with how the value is used. We need to handle 15750 // patterns such as the following: 15751 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 15752 // (brcond (setcc (loop.decrement), 0, eq), exit) 15753 // (brcond (setcc (loop.decrement), 0, ne), header) 15754 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 15755 bool &Negate) { 15756 switch (N->getOpcode()) { 15757 default: 15758 break; 15759 case ISD::XOR: { 15760 if (!isa<ConstantSDNode>(N.getOperand(1))) 15761 return SDValue(); 15762 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 15763 return SDValue(); 15764 Negate = !Negate; 15765 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 15766 } 15767 case ISD::SETCC: { 15768 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 15769 if (!Const) 15770 return SDValue(); 15771 if (Const->isNullValue()) 15772 Imm = 0; 15773 else if (Const->isOne()) 15774 Imm = 1; 15775 else 15776 return SDValue(); 15777 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 15778 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 15779 } 15780 case ISD::INTRINSIC_W_CHAIN: { 15781 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 15782 if (IntOp != Intrinsic::test_set_loop_iterations && 15783 IntOp != Intrinsic::loop_decrement_reg) 15784 return SDValue(); 15785 return N; 15786 } 15787 } 15788 return SDValue(); 15789 } 15790 15791 static SDValue PerformHWLoopCombine(SDNode *N, 15792 TargetLowering::DAGCombinerInfo &DCI, 15793 const ARMSubtarget *ST) { 15794 15795 // The hwloop intrinsics that we're interested are used for control-flow, 15796 // either for entering or exiting the loop: 15797 // - test.set.loop.iterations will test whether its operand is zero. If it 15798 // is zero, the proceeding branch should not enter the loop. 15799 // - loop.decrement.reg also tests whether its operand is zero. If it is 15800 // zero, the proceeding branch should not branch back to the beginning of 15801 // the loop. 15802 // So here, we need to check that how the brcond is using the result of each 15803 // of the intrinsics to ensure that we're branching to the right place at the 15804 // right time. 15805 15806 ISD::CondCode CC; 15807 SDValue Cond; 15808 int Imm = 1; 15809 bool Negate = false; 15810 SDValue Chain = N->getOperand(0); 15811 SDValue Dest; 15812 15813 if (N->getOpcode() == ISD::BRCOND) { 15814 CC = ISD::SETEQ; 15815 Cond = N->getOperand(1); 15816 Dest = N->getOperand(2); 15817 } else { 15818 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 15819 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15820 Cond = N->getOperand(2); 15821 Dest = N->getOperand(4); 15822 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 15823 if (!Const->isOne() && !Const->isNullValue()) 15824 return SDValue(); 15825 Imm = Const->getZExtValue(); 15826 } else 15827 return SDValue(); 15828 } 15829 15830 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 15831 if (!Int) 15832 return SDValue(); 15833 15834 if (Negate) 15835 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32); 15836 15837 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 15838 return (CC == ISD::SETEQ && Imm == 0) || 15839 (CC == ISD::SETNE && Imm == 1) || 15840 (CC == ISD::SETLT && Imm == 1) || 15841 (CC == ISD::SETULT && Imm == 1); 15842 }; 15843 15844 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 15845 return (CC == ISD::SETEQ && Imm == 1) || 15846 (CC == ISD::SETNE && Imm == 0) || 15847 (CC == ISD::SETGT && Imm == 0) || 15848 (CC == ISD::SETUGT && Imm == 0) || 15849 (CC == ISD::SETGE && Imm == 1) || 15850 (CC == ISD::SETUGE && Imm == 1); 15851 }; 15852 15853 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 15854 "unsupported condition"); 15855 15856 SDLoc dl(Int); 15857 SelectionDAG &DAG = DCI.DAG; 15858 SDValue Elements = Int.getOperand(2); 15859 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 15860 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 15861 && "expected single br user"); 15862 SDNode *Br = *N->use_begin(); 15863 SDValue OtherTarget = Br->getOperand(1); 15864 15865 // Update the unconditional branch to branch to the given Dest. 15866 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 15867 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 15868 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 15869 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 15870 }; 15871 15872 if (IntOp == Intrinsic::test_set_loop_iterations) { 15873 SDValue Res; 15874 // We expect this 'instruction' to branch when the counter is zero. 15875 if (IsTrueIfZero(CC, Imm)) { 15876 SDValue Ops[] = { Chain, Elements, Dest }; 15877 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 15878 } else { 15879 // The logic is the reverse of what we need for WLS, so find the other 15880 // basic block target: the target of the proceeding br. 15881 UpdateUncondBr(Br, Dest, DAG); 15882 15883 SDValue Ops[] = { Chain, Elements, OtherTarget }; 15884 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 15885 } 15886 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 15887 return Res; 15888 } else { 15889 SDValue Size = DAG.getTargetConstant( 15890 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 15891 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 15892 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 15893 DAG.getVTList(MVT::i32, MVT::Other), Args); 15894 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 15895 15896 // We expect this instruction to branch when the count is not zero. 15897 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 15898 15899 // Update the unconditional branch to target the loop preheader if we've 15900 // found the condition has been reversed. 15901 if (Target == OtherTarget) 15902 UpdateUncondBr(Br, Dest, DAG); 15903 15904 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15905 SDValue(LoopDec.getNode(), 1), Chain); 15906 15907 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 15908 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 15909 } 15910 return SDValue(); 15911 } 15912 15913 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 15914 SDValue 15915 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 15916 SDValue Cmp = N->getOperand(4); 15917 if (Cmp.getOpcode() != ARMISD::CMPZ) 15918 // Only looking at NE cases. 15919 return SDValue(); 15920 15921 EVT VT = N->getValueType(0); 15922 SDLoc dl(N); 15923 SDValue LHS = Cmp.getOperand(0); 15924 SDValue RHS = Cmp.getOperand(1); 15925 SDValue Chain = N->getOperand(0); 15926 SDValue BB = N->getOperand(1); 15927 SDValue ARMcc = N->getOperand(2); 15928 ARMCC::CondCodes CC = 15929 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 15930 15931 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 15932 // -> (brcond Chain BB CC CPSR Cmp) 15933 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 15934 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 15935 LHS->getOperand(0)->hasOneUse()) { 15936 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 15937 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 15938 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 15939 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 15940 if ((LHS00C && LHS00C->getZExtValue() == 0) && 15941 (LHS01C && LHS01C->getZExtValue() == 1) && 15942 (LHS1C && LHS1C->getZExtValue() == 1) && 15943 (RHSC && RHSC->getZExtValue() == 0)) { 15944 return DAG.getNode( 15945 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 15946 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 15947 } 15948 } 15949 15950 return SDValue(); 15951 } 15952 15953 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 15954 SDValue 15955 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 15956 SDValue Cmp = N->getOperand(4); 15957 if (Cmp.getOpcode() != ARMISD::CMPZ) 15958 // Only looking at EQ and NE cases. 15959 return SDValue(); 15960 15961 EVT VT = N->getValueType(0); 15962 SDLoc dl(N); 15963 SDValue LHS = Cmp.getOperand(0); 15964 SDValue RHS = Cmp.getOperand(1); 15965 SDValue FalseVal = N->getOperand(0); 15966 SDValue TrueVal = N->getOperand(1); 15967 SDValue ARMcc = N->getOperand(2); 15968 ARMCC::CondCodes CC = 15969 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 15970 15971 // BFI is only available on V6T2+. 15972 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 15973 SDValue R = PerformCMOVToBFICombine(N, DAG); 15974 if (R) 15975 return R; 15976 } 15977 15978 // Simplify 15979 // mov r1, r0 15980 // cmp r1, x 15981 // mov r0, y 15982 // moveq r0, x 15983 // to 15984 // cmp r0, x 15985 // movne r0, y 15986 // 15987 // mov r1, r0 15988 // cmp r1, x 15989 // mov r0, x 15990 // movne r0, y 15991 // to 15992 // cmp r0, x 15993 // movne r0, y 15994 /// FIXME: Turn this into a target neutral optimization? 15995 SDValue Res; 15996 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 15997 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 15998 N->getOperand(3), Cmp); 15999 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 16000 SDValue ARMcc; 16001 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 16002 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 16003 N->getOperand(3), NewCmp); 16004 } 16005 16006 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 16007 // -> (cmov F T CC CPSR Cmp) 16008 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 16009 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 16010 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 16011 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 16012 if ((LHS0C && LHS0C->getZExtValue() == 0) && 16013 (LHS1C && LHS1C->getZExtValue() == 1) && 16014 (RHSC && RHSC->getZExtValue() == 0)) { 16015 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 16016 LHS->getOperand(2), LHS->getOperand(3), 16017 LHS->getOperand(4)); 16018 } 16019 } 16020 16021 if (!VT.isInteger()) 16022 return SDValue(); 16023 16024 // Materialize a boolean comparison for integers so we can avoid branching. 16025 if (isNullConstant(FalseVal)) { 16026 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 16027 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 16028 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 16029 // right 5 bits will make that 32 be 1, otherwise it will be 0. 16030 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 16031 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 16032 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 16033 DAG.getConstant(5, dl, MVT::i32)); 16034 } else { 16035 // CMOV 0, 1, ==, (CMPZ x, y) -> 16036 // (ADDCARRY (SUB x, y), t:0, t:1) 16037 // where t = (SUBCARRY 0, (SUB x, y), 0) 16038 // 16039 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 16040 // x != y. In other words, a carry C == 1 when x == y, C == 0 16041 // otherwise. 16042 // The final ADDCARRY computes 16043 // x - y + (0 - (x - y)) + C == C 16044 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 16045 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 16046 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 16047 // ISD::SUBCARRY returns a borrow but we want the carry here 16048 // actually. 16049 SDValue Carry = 16050 DAG.getNode(ISD::SUB, dl, MVT::i32, 16051 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 16052 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 16053 } 16054 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 16055 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 16056 // This seems pointless but will allow us to combine it further below. 16057 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 16058 SDValue Sub = 16059 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 16060 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 16061 Sub.getValue(1), SDValue()); 16062 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 16063 N->getOperand(3), CPSRGlue.getValue(1)); 16064 FalseVal = Sub; 16065 } 16066 } else if (isNullConstant(TrueVal)) { 16067 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 16068 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 16069 // This seems pointless but will allow us to combine it further below 16070 // Note that we change == for != as this is the dual for the case above. 16071 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 16072 SDValue Sub = 16073 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 16074 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 16075 Sub.getValue(1), SDValue()); 16076 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 16077 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 16078 N->getOperand(3), CPSRGlue.getValue(1)); 16079 FalseVal = Sub; 16080 } 16081 } 16082 16083 // On Thumb1, the DAG above may be further combined if z is a power of 2 16084 // (z == 2 ^ K). 16085 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 16086 // t1 = (USUBO (SUB x, y), 1) 16087 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 16088 // Result = if K != 0 then (SHL t2:0, K) else t2:0 16089 // 16090 // This also handles the special case of comparing against zero; it's 16091 // essentially, the same pattern, except there's no SUBS: 16092 // CMOV x, z, !=, (CMPZ x, 0) -> 16093 // t1 = (USUBO x, 1) 16094 // t2 = (SUBCARRY x, t1:0, t1:1) 16095 // Result = if K != 0 then (SHL t2:0, K) else t2:0 16096 const APInt *TrueConst; 16097 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 16098 ((FalseVal.getOpcode() == ARMISD::SUBS && 16099 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 16100 (FalseVal == LHS && isNullConstant(RHS))) && 16101 (TrueConst = isPowerOf2Constant(TrueVal))) { 16102 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 16103 unsigned ShiftAmount = TrueConst->logBase2(); 16104 if (ShiftAmount) 16105 TrueVal = DAG.getConstant(1, dl, VT); 16106 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 16107 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 16108 16109 if (ShiftAmount) 16110 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 16111 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 16112 } 16113 16114 if (Res.getNode()) { 16115 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 16116 // Capture demanded bits information that would be otherwise lost. 16117 if (Known.Zero == 0xfffffffe) 16118 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16119 DAG.getValueType(MVT::i1)); 16120 else if (Known.Zero == 0xffffff00) 16121 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16122 DAG.getValueType(MVT::i8)); 16123 else if (Known.Zero == 0xffff0000) 16124 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 16125 DAG.getValueType(MVT::i16)); 16126 } 16127 16128 return Res; 16129 } 16130 16131 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG, 16132 const ARMSubtarget *ST) { 16133 SDValue Src = N->getOperand(0); 16134 EVT DstVT = N->getValueType(0); 16135 16136 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE. 16137 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) { 16138 EVT SrcVT = Src.getValueType(); 16139 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits()) 16140 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0)); 16141 } 16142 16143 // We may have a bitcast of something that has already had this bitcast 16144 // combine performed on it, so skip past any VECTOR_REG_CASTs. 16145 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST) 16146 Src = Src.getOperand(0); 16147 16148 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that 16149 // would be generated is at least the width of the element type. 16150 EVT SrcVT = Src.getValueType(); 16151 if ((Src.getOpcode() == ARMISD::VMOVIMM || 16152 Src.getOpcode() == ARMISD::VMVNIMM || 16153 Src.getOpcode() == ARMISD::VMOVFPIMM) && 16154 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() && 16155 DAG.getDataLayout().isBigEndian()) 16156 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src); 16157 16158 return SDValue(); 16159 } 16160 16161 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 16162 DAGCombinerInfo &DCI) const { 16163 switch (N->getOpcode()) { 16164 default: break; 16165 case ISD::SELECT_CC: 16166 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget); 16167 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget); 16168 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 16169 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 16170 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 16171 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 16172 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget); 16173 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 16174 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 16175 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 16176 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 16177 case ISD::BRCOND: 16178 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 16179 case ARMISD::ADDC: 16180 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 16181 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 16182 case ARMISD::BFI: return PerformBFICombine(N, DCI); 16183 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 16184 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 16185 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI); 16186 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI); 16187 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget); 16188 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 16189 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 16190 case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI); 16191 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 16192 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget); 16193 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 16194 case ISD::FP_TO_SINT: 16195 case ISD::FP_TO_UINT: 16196 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 16197 case ISD::FDIV: 16198 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 16199 case ISD::INTRINSIC_WO_CHAIN: 16200 return PerformIntrinsicCombine(N, DCI); 16201 case ISD::SHL: 16202 case ISD::SRA: 16203 case ISD::SRL: 16204 return PerformShiftCombine(N, DCI, Subtarget); 16205 case ISD::SIGN_EXTEND: 16206 case ISD::ZERO_EXTEND: 16207 case ISD::ANY_EXTEND: 16208 return PerformExtendCombine(N, DCI.DAG, Subtarget); 16209 case ISD::FP_EXTEND: 16210 return PerformFPExtendCombine(N, DCI.DAG, Subtarget); 16211 case ISD::SMIN: 16212 case ISD::UMIN: 16213 case ISD::SMAX: 16214 case ISD::UMAX: 16215 return PerformMinMaxCombine(N, DCI.DAG, Subtarget); 16216 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 16217 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 16218 case ISD::LOAD: return PerformLOADCombine(N, DCI); 16219 case ARMISD::VLD1DUP: 16220 case ARMISD::VLD2DUP: 16221 case ARMISD::VLD3DUP: 16222 case ARMISD::VLD4DUP: 16223 return PerformVLDCombine(N, DCI); 16224 case ARMISD::BUILD_VECTOR: 16225 return PerformARMBUILD_VECTORCombine(N, DCI); 16226 case ISD::BITCAST: 16227 return PerformBITCASTCombine(N, DCI.DAG, Subtarget); 16228 case ARMISD::PREDICATE_CAST: 16229 return PerformPREDICATE_CASTCombine(N, DCI); 16230 case ARMISD::VECTOR_REG_CAST: 16231 return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget); 16232 case ARMISD::VCMP: 16233 return PerformVCMPCombine(N, DCI, Subtarget); 16234 case ISD::VECREDUCE_ADD: 16235 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget); 16236 case ARMISD::VMOVN: 16237 return PerformVMOVNCombine(N, DCI); 16238 case ARMISD::VQMOVNs: 16239 case ARMISD::VQMOVNu: 16240 return PerformVQMOVNCombine(N, DCI); 16241 case ARMISD::ASRL: 16242 case ARMISD::LSRL: 16243 case ARMISD::LSLL: 16244 return PerformLongShiftCombine(N, DCI.DAG); 16245 case ARMISD::SMULWB: { 16246 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16247 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16248 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16249 return SDValue(); 16250 break; 16251 } 16252 case ARMISD::SMULWT: { 16253 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16254 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16255 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 16256 return SDValue(); 16257 break; 16258 } 16259 case ARMISD::SMLALBB: 16260 case ARMISD::QADD16b: 16261 case ARMISD::QSUB16b: { 16262 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16263 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 16264 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16265 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16266 return SDValue(); 16267 break; 16268 } 16269 case ARMISD::SMLALBT: { 16270 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 16271 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16272 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 16273 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16274 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 16275 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 16276 return SDValue(); 16277 break; 16278 } 16279 case ARMISD::SMLALTB: { 16280 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 16281 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 16282 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 16283 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 16284 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 16285 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 16286 return SDValue(); 16287 break; 16288 } 16289 case ARMISD::SMLALTT: { 16290 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16291 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 16292 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16293 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16294 return SDValue(); 16295 break; 16296 } 16297 case ARMISD::QADD8b: 16298 case ARMISD::QSUB8b: { 16299 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 16300 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8); 16301 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 16302 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 16303 return SDValue(); 16304 break; 16305 } 16306 case ISD::INTRINSIC_VOID: 16307 case ISD::INTRINSIC_W_CHAIN: 16308 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 16309 case Intrinsic::arm_neon_vld1: 16310 case Intrinsic::arm_neon_vld1x2: 16311 case Intrinsic::arm_neon_vld1x3: 16312 case Intrinsic::arm_neon_vld1x4: 16313 case Intrinsic::arm_neon_vld2: 16314 case Intrinsic::arm_neon_vld3: 16315 case Intrinsic::arm_neon_vld4: 16316 case Intrinsic::arm_neon_vld2lane: 16317 case Intrinsic::arm_neon_vld3lane: 16318 case Intrinsic::arm_neon_vld4lane: 16319 case Intrinsic::arm_neon_vld2dup: 16320 case Intrinsic::arm_neon_vld3dup: 16321 case Intrinsic::arm_neon_vld4dup: 16322 case Intrinsic::arm_neon_vst1: 16323 case Intrinsic::arm_neon_vst1x2: 16324 case Intrinsic::arm_neon_vst1x3: 16325 case Intrinsic::arm_neon_vst1x4: 16326 case Intrinsic::arm_neon_vst2: 16327 case Intrinsic::arm_neon_vst3: 16328 case Intrinsic::arm_neon_vst4: 16329 case Intrinsic::arm_neon_vst2lane: 16330 case Intrinsic::arm_neon_vst3lane: 16331 case Intrinsic::arm_neon_vst4lane: 16332 return PerformVLDCombine(N, DCI); 16333 case Intrinsic::arm_mve_vld2q: 16334 case Intrinsic::arm_mve_vld4q: 16335 case Intrinsic::arm_mve_vst2q: 16336 case Intrinsic::arm_mve_vst4q: 16337 return PerformMVEVLDCombine(N, DCI); 16338 default: break; 16339 } 16340 break; 16341 } 16342 return SDValue(); 16343 } 16344 16345 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 16346 EVT VT) const { 16347 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 16348 } 16349 16350 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 16351 unsigned Alignment, 16352 MachineMemOperand::Flags, 16353 bool *Fast) const { 16354 // Depends what it gets converted into if the type is weird. 16355 if (!VT.isSimple()) 16356 return false; 16357 16358 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus 16359 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 16360 auto Ty = VT.getSimpleVT().SimpleTy; 16361 16362 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 16363 // Unaligned access can use (for example) LRDB, LRDH, LDR 16364 if (AllowsUnaligned) { 16365 if (Fast) 16366 *Fast = Subtarget->hasV7Ops(); 16367 return true; 16368 } 16369 } 16370 16371 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 16372 // For any little-endian targets with neon, we can support unaligned ld/st 16373 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 16374 // A big-endian target may also explicitly support unaligned accesses 16375 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 16376 if (Fast) 16377 *Fast = true; 16378 return true; 16379 } 16380 } 16381 16382 if (!Subtarget->hasMVEIntegerOps()) 16383 return false; 16384 16385 // These are for predicates 16386 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 16387 if (Fast) 16388 *Fast = true; 16389 return true; 16390 } 16391 16392 // These are for truncated stores/narrowing loads. They are fine so long as 16393 // the alignment is at least the size of the item being loaded 16394 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 16395 Alignment >= VT.getScalarSizeInBits() / 8) { 16396 if (Fast) 16397 *Fast = true; 16398 return true; 16399 } 16400 16401 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 16402 // VSTRW.U32 all store the vector register in exactly the same format, and 16403 // differ only in the range of their immediate offset field and the required 16404 // alignment. So there is always a store that can be used, regardless of 16405 // actual type. 16406 // 16407 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 16408 // VREV64.8) pair and get the same effect. This will likely be better than 16409 // aligning the vector through the stack. 16410 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 16411 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 16412 Ty == MVT::v2f64) { 16413 if (Fast) 16414 *Fast = true; 16415 return true; 16416 } 16417 16418 return false; 16419 } 16420 16421 16422 EVT ARMTargetLowering::getOptimalMemOpType( 16423 const MemOp &Op, const AttributeList &FuncAttributes) const { 16424 // See if we can use NEON instructions for this... 16425 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() && 16426 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 16427 bool Fast; 16428 if (Op.size() >= 16 && 16429 (Op.isAligned(Align(16)) || 16430 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 16431 MachineMemOperand::MONone, &Fast) && 16432 Fast))) { 16433 return MVT::v2f64; 16434 } else if (Op.size() >= 8 && 16435 (Op.isAligned(Align(8)) || 16436 (allowsMisalignedMemoryAccesses( 16437 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 16438 Fast))) { 16439 return MVT::f64; 16440 } 16441 } 16442 16443 // Let the target-independent logic figure it out. 16444 return MVT::Other; 16445 } 16446 16447 // 64-bit integers are split into their high and low parts and held in two 16448 // different registers, so the trunc is free since the low register can just 16449 // be used. 16450 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 16451 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 16452 return false; 16453 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 16454 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 16455 return (SrcBits == 64 && DestBits == 32); 16456 } 16457 16458 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 16459 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 16460 !DstVT.isInteger()) 16461 return false; 16462 unsigned SrcBits = SrcVT.getSizeInBits(); 16463 unsigned DestBits = DstVT.getSizeInBits(); 16464 return (SrcBits == 64 && DestBits == 32); 16465 } 16466 16467 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16468 if (Val.getOpcode() != ISD::LOAD) 16469 return false; 16470 16471 EVT VT1 = Val.getValueType(); 16472 if (!VT1.isSimple() || !VT1.isInteger() || 16473 !VT2.isSimple() || !VT2.isInteger()) 16474 return false; 16475 16476 switch (VT1.getSimpleVT().SimpleTy) { 16477 default: break; 16478 case MVT::i1: 16479 case MVT::i8: 16480 case MVT::i16: 16481 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 16482 return true; 16483 } 16484 16485 return false; 16486 } 16487 16488 bool ARMTargetLowering::isFNegFree(EVT VT) const { 16489 if (!VT.isSimple()) 16490 return false; 16491 16492 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 16493 // negate values directly (fneg is free). So, we don't want to let the DAG 16494 // combiner rewrite fneg into xors and some other instructions. For f16 and 16495 // FullFP16 argument passing, some bitcast nodes may be introduced, 16496 // triggering this DAG combine rewrite, so we are avoiding that with this. 16497 switch (VT.getSimpleVT().SimpleTy) { 16498 default: break; 16499 case MVT::f16: 16500 return Subtarget->hasFullFP16(); 16501 } 16502 16503 return false; 16504 } 16505 16506 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 16507 /// of the vector elements. 16508 static bool areExtractExts(Value *Ext1, Value *Ext2) { 16509 auto areExtDoubled = [](Instruction *Ext) { 16510 return Ext->getType()->getScalarSizeInBits() == 16511 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 16512 }; 16513 16514 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 16515 !match(Ext2, m_ZExtOrSExt(m_Value())) || 16516 !areExtDoubled(cast<Instruction>(Ext1)) || 16517 !areExtDoubled(cast<Instruction>(Ext2))) 16518 return false; 16519 16520 return true; 16521 } 16522 16523 /// Check if sinking \p I's operands to I's basic block is profitable, because 16524 /// the operands can be folded into a target instruction, e.g. 16525 /// sext/zext can be folded into vsubl. 16526 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 16527 SmallVectorImpl<Use *> &Ops) const { 16528 if (!I->getType()->isVectorTy()) 16529 return false; 16530 16531 if (Subtarget->hasNEON()) { 16532 switch (I->getOpcode()) { 16533 case Instruction::Sub: 16534 case Instruction::Add: { 16535 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 16536 return false; 16537 Ops.push_back(&I->getOperandUse(0)); 16538 Ops.push_back(&I->getOperandUse(1)); 16539 return true; 16540 } 16541 default: 16542 return false; 16543 } 16544 } 16545 16546 if (!Subtarget->hasMVEIntegerOps()) 16547 return false; 16548 16549 auto IsFMSMul = [&](Instruction *I) { 16550 if (!I->hasOneUse()) 16551 return false; 16552 auto *Sub = cast<Instruction>(*I->users().begin()); 16553 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I; 16554 }; 16555 auto IsFMS = [&](Instruction *I) { 16556 if (match(I->getOperand(0), m_FNeg(m_Value())) || 16557 match(I->getOperand(1), m_FNeg(m_Value()))) 16558 return true; 16559 return false; 16560 }; 16561 16562 auto IsSinker = [&](Instruction *I, int Operand) { 16563 switch (I->getOpcode()) { 16564 case Instruction::Add: 16565 case Instruction::Mul: 16566 case Instruction::FAdd: 16567 case Instruction::ICmp: 16568 case Instruction::FCmp: 16569 return true; 16570 case Instruction::FMul: 16571 return !IsFMSMul(I); 16572 case Instruction::Sub: 16573 case Instruction::FSub: 16574 case Instruction::Shl: 16575 case Instruction::LShr: 16576 case Instruction::AShr: 16577 return Operand == 1; 16578 case Instruction::Call: 16579 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 16580 switch (II->getIntrinsicID()) { 16581 case Intrinsic::fma: 16582 return !IsFMS(I); 16583 case Intrinsic::arm_mve_add_predicated: 16584 case Intrinsic::arm_mve_mul_predicated: 16585 case Intrinsic::arm_mve_qadd_predicated: 16586 case Intrinsic::arm_mve_hadd_predicated: 16587 case Intrinsic::arm_mve_vqdmull_predicated: 16588 case Intrinsic::arm_mve_qdmulh_predicated: 16589 case Intrinsic::arm_mve_qrdmulh_predicated: 16590 case Intrinsic::arm_mve_fma_predicated: 16591 return true; 16592 case Intrinsic::arm_mve_sub_predicated: 16593 case Intrinsic::arm_mve_qsub_predicated: 16594 case Intrinsic::arm_mve_hsub_predicated: 16595 return Operand == 1; 16596 default: 16597 return false; 16598 } 16599 } 16600 return false; 16601 default: 16602 return false; 16603 } 16604 }; 16605 16606 for (auto OpIdx : enumerate(I->operands())) { 16607 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 16608 // Make sure we are not already sinking this operand 16609 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 16610 continue; 16611 16612 Instruction *Shuffle = Op; 16613 if (Shuffle->getOpcode() == Instruction::BitCast) 16614 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0)); 16615 // We are looking for a splat that can be sunk. 16616 if (!Shuffle || 16617 !match(Shuffle, m_Shuffle( 16618 m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 16619 m_Undef(), m_ZeroMask()))) 16620 continue; 16621 if (!IsSinker(I, OpIdx.index())) 16622 continue; 16623 16624 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 16625 // and vector registers 16626 for (Use &U : Op->uses()) { 16627 Instruction *Insn = cast<Instruction>(U.getUser()); 16628 if (!IsSinker(Insn, U.getOperandNo())) 16629 return false; 16630 } 16631 16632 Ops.push_back(&Shuffle->getOperandUse(0)); 16633 if (Shuffle != Op) 16634 Ops.push_back(&Op->getOperandUse(0)); 16635 Ops.push_back(&OpIdx.value()); 16636 } 16637 return true; 16638 } 16639 16640 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const { 16641 if (!Subtarget->hasMVEIntegerOps()) 16642 return nullptr; 16643 Type *SVIType = SVI->getType(); 16644 Type *ScalarType = SVIType->getScalarType(); 16645 16646 if (ScalarType->isFloatTy()) 16647 return Type::getInt32Ty(SVIType->getContext()); 16648 if (ScalarType->isHalfTy()) 16649 return Type::getInt16Ty(SVIType->getContext()); 16650 return nullptr; 16651 } 16652 16653 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 16654 EVT VT = ExtVal.getValueType(); 16655 16656 if (!isTypeLegal(VT)) 16657 return false; 16658 16659 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) { 16660 if (Ld->isExpandingLoad()) 16661 return false; 16662 } 16663 16664 if (Subtarget->hasMVEIntegerOps()) 16665 return true; 16666 16667 // Don't create a loadext if we can fold the extension into a wide/long 16668 // instruction. 16669 // If there's more than one user instruction, the loadext is desirable no 16670 // matter what. There can be two uses by the same instruction. 16671 if (ExtVal->use_empty() || 16672 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 16673 return true; 16674 16675 SDNode *U = *ExtVal->use_begin(); 16676 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 16677 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 16678 return false; 16679 16680 return true; 16681 } 16682 16683 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 16684 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16685 return false; 16686 16687 if (!isTypeLegal(EVT::getEVT(Ty1))) 16688 return false; 16689 16690 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 16691 16692 // Assuming the caller doesn't have a zeroext or signext return parameter, 16693 // truncation all the way down to i1 is valid. 16694 return true; 16695 } 16696 16697 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 16698 const AddrMode &AM, Type *Ty, 16699 unsigned AS) const { 16700 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 16701 if (Subtarget->hasFPAO()) 16702 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 16703 return 0; 16704 } 16705 return -1; 16706 } 16707 16708 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster 16709 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be 16710 /// expanded to FMAs when this method returns true, otherwise fmuladd is 16711 /// expanded to fmul + fadd. 16712 /// 16713 /// ARM supports both fused and unfused multiply-add operations; we already 16714 /// lower a pair of fmul and fadd to the latter so it's not clear that there 16715 /// would be a gain or that the gain would be worthwhile enough to risk 16716 /// correctness bugs. 16717 /// 16718 /// For MVE, we set this to true as it helps simplify the need for some 16719 /// patterns (and we don't have the non-fused floating point instruction). 16720 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16721 EVT VT) const { 16722 if (!VT.isSimple()) 16723 return false; 16724 16725 switch (VT.getSimpleVT().SimpleTy) { 16726 case MVT::v4f32: 16727 case MVT::v8f16: 16728 return Subtarget->hasMVEFloatOps(); 16729 case MVT::f16: 16730 return Subtarget->useFPVFMx16(); 16731 case MVT::f32: 16732 return Subtarget->useFPVFMx(); 16733 case MVT::f64: 16734 return Subtarget->useFPVFMx64(); 16735 default: 16736 break; 16737 } 16738 16739 return false; 16740 } 16741 16742 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 16743 if (V < 0) 16744 return false; 16745 16746 unsigned Scale = 1; 16747 switch (VT.getSimpleVT().SimpleTy) { 16748 case MVT::i1: 16749 case MVT::i8: 16750 // Scale == 1; 16751 break; 16752 case MVT::i16: 16753 // Scale == 2; 16754 Scale = 2; 16755 break; 16756 default: 16757 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 16758 // Scale == 4; 16759 Scale = 4; 16760 break; 16761 } 16762 16763 if ((V & (Scale - 1)) != 0) 16764 return false; 16765 return isUInt<5>(V / Scale); 16766 } 16767 16768 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 16769 const ARMSubtarget *Subtarget) { 16770 if (!VT.isInteger() && !VT.isFloatingPoint()) 16771 return false; 16772 if (VT.isVector() && Subtarget->hasNEON()) 16773 return false; 16774 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 16775 !Subtarget->hasMVEFloatOps()) 16776 return false; 16777 16778 bool IsNeg = false; 16779 if (V < 0) { 16780 IsNeg = true; 16781 V = -V; 16782 } 16783 16784 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U); 16785 16786 // MVE: size * imm7 16787 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 16788 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 16789 case MVT::i32: 16790 case MVT::f32: 16791 return isShiftedUInt<7,2>(V); 16792 case MVT::i16: 16793 case MVT::f16: 16794 return isShiftedUInt<7,1>(V); 16795 case MVT::i8: 16796 return isUInt<7>(V); 16797 default: 16798 return false; 16799 } 16800 } 16801 16802 // half VLDR: 2 * imm8 16803 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 16804 return isShiftedUInt<8, 1>(V); 16805 // VLDR and LDRD: 4 * imm8 16806 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 16807 return isShiftedUInt<8, 2>(V); 16808 16809 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 16810 // + imm12 or - imm8 16811 if (IsNeg) 16812 return isUInt<8>(V); 16813 return isUInt<12>(V); 16814 } 16815 16816 return false; 16817 } 16818 16819 /// isLegalAddressImmediate - Return true if the integer value can be used 16820 /// as the offset of the target addressing mode for load / store of the 16821 /// given type. 16822 static bool isLegalAddressImmediate(int64_t V, EVT VT, 16823 const ARMSubtarget *Subtarget) { 16824 if (V == 0) 16825 return true; 16826 16827 if (!VT.isSimple()) 16828 return false; 16829 16830 if (Subtarget->isThumb1Only()) 16831 return isLegalT1AddressImmediate(V, VT); 16832 else if (Subtarget->isThumb2()) 16833 return isLegalT2AddressImmediate(V, VT, Subtarget); 16834 16835 // ARM mode. 16836 if (V < 0) 16837 V = - V; 16838 switch (VT.getSimpleVT().SimpleTy) { 16839 default: return false; 16840 case MVT::i1: 16841 case MVT::i8: 16842 case MVT::i32: 16843 // +- imm12 16844 return isUInt<12>(V); 16845 case MVT::i16: 16846 // +- imm8 16847 return isUInt<8>(V); 16848 case MVT::f32: 16849 case MVT::f64: 16850 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 16851 return false; 16852 return isShiftedUInt<8, 2>(V); 16853 } 16854 } 16855 16856 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 16857 EVT VT) const { 16858 int Scale = AM.Scale; 16859 if (Scale < 0) 16860 return false; 16861 16862 switch (VT.getSimpleVT().SimpleTy) { 16863 default: return false; 16864 case MVT::i1: 16865 case MVT::i8: 16866 case MVT::i16: 16867 case MVT::i32: 16868 if (Scale == 1) 16869 return true; 16870 // r + r << imm 16871 Scale = Scale & ~1; 16872 return Scale == 2 || Scale == 4 || Scale == 8; 16873 case MVT::i64: 16874 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 16875 // version in Thumb mode. 16876 // r + r 16877 if (Scale == 1) 16878 return true; 16879 // r * 2 (this can be lowered to r + r). 16880 if (!AM.HasBaseReg && Scale == 2) 16881 return true; 16882 return false; 16883 case MVT::isVoid: 16884 // Note, we allow "void" uses (basically, uses that aren't loads or 16885 // stores), because arm allows folding a scale into many arithmetic 16886 // operations. This should be made more precise and revisited later. 16887 16888 // Allow r << imm, but the imm has to be a multiple of two. 16889 if (Scale & 1) return false; 16890 return isPowerOf2_32(Scale); 16891 } 16892 } 16893 16894 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 16895 EVT VT) const { 16896 const int Scale = AM.Scale; 16897 16898 // Negative scales are not supported in Thumb1. 16899 if (Scale < 0) 16900 return false; 16901 16902 // Thumb1 addressing modes do not support register scaling excepting the 16903 // following cases: 16904 // 1. Scale == 1 means no scaling. 16905 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 16906 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 16907 } 16908 16909 /// isLegalAddressingMode - Return true if the addressing mode represented 16910 /// by AM is legal for this target, for a load/store of the specified type. 16911 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 16912 const AddrMode &AM, Type *Ty, 16913 unsigned AS, Instruction *I) const { 16914 EVT VT = getValueType(DL, Ty, true); 16915 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 16916 return false; 16917 16918 // Can never fold addr of global into load/store. 16919 if (AM.BaseGV) 16920 return false; 16921 16922 switch (AM.Scale) { 16923 case 0: // no scale reg, must be "r+i" or "r", or "i". 16924 break; 16925 default: 16926 // ARM doesn't support any R+R*scale+imm addr modes. 16927 if (AM.BaseOffs) 16928 return false; 16929 16930 if (!VT.isSimple()) 16931 return false; 16932 16933 if (Subtarget->isThumb1Only()) 16934 return isLegalT1ScaledAddressingMode(AM, VT); 16935 16936 if (Subtarget->isThumb2()) 16937 return isLegalT2ScaledAddressingMode(AM, VT); 16938 16939 int Scale = AM.Scale; 16940 switch (VT.getSimpleVT().SimpleTy) { 16941 default: return false; 16942 case MVT::i1: 16943 case MVT::i8: 16944 case MVT::i32: 16945 if (Scale < 0) Scale = -Scale; 16946 if (Scale == 1) 16947 return true; 16948 // r + r << imm 16949 return isPowerOf2_32(Scale & ~1); 16950 case MVT::i16: 16951 case MVT::i64: 16952 // r +/- r 16953 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 16954 return true; 16955 // r * 2 (this can be lowered to r + r). 16956 if (!AM.HasBaseReg && Scale == 2) 16957 return true; 16958 return false; 16959 16960 case MVT::isVoid: 16961 // Note, we allow "void" uses (basically, uses that aren't loads or 16962 // stores), because arm allows folding a scale into many arithmetic 16963 // operations. This should be made more precise and revisited later. 16964 16965 // Allow r << imm, but the imm has to be a multiple of two. 16966 if (Scale & 1) return false; 16967 return isPowerOf2_32(Scale); 16968 } 16969 } 16970 return true; 16971 } 16972 16973 /// isLegalICmpImmediate - Return true if the specified immediate is legal 16974 /// icmp immediate, that is the target has icmp instructions which can compare 16975 /// a register against the immediate without having to materialize the 16976 /// immediate into a register. 16977 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16978 // Thumb2 and ARM modes can use cmn for negative immediates. 16979 if (!Subtarget->isThumb()) 16980 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 16981 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 16982 if (Subtarget->isThumb2()) 16983 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 16984 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 16985 // Thumb1 doesn't have cmn, and only 8-bit immediates. 16986 return Imm >= 0 && Imm <= 255; 16987 } 16988 16989 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 16990 /// *or sub* immediate, that is the target has add or sub instructions which can 16991 /// add a register with the immediate without having to materialize the 16992 /// immediate into a register. 16993 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16994 // Same encoding for add/sub, just flip the sign. 16995 int64_t AbsImm = std::abs(Imm); 16996 if (!Subtarget->isThumb()) 16997 return ARM_AM::getSOImmVal(AbsImm) != -1; 16998 if (Subtarget->isThumb2()) 16999 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 17000 // Thumb1 only has 8-bit unsigned immediate. 17001 return AbsImm >= 0 && AbsImm <= 255; 17002 } 17003 17004 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 17005 bool isSEXTLoad, SDValue &Base, 17006 SDValue &Offset, bool &isInc, 17007 SelectionDAG &DAG) { 17008 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17009 return false; 17010 17011 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 17012 // AddressingMode 3 17013 Base = Ptr->getOperand(0); 17014 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17015 int RHSC = (int)RHS->getZExtValue(); 17016 if (RHSC < 0 && RHSC > -256) { 17017 assert(Ptr->getOpcode() == ISD::ADD); 17018 isInc = false; 17019 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17020 return true; 17021 } 17022 } 17023 isInc = (Ptr->getOpcode() == ISD::ADD); 17024 Offset = Ptr->getOperand(1); 17025 return true; 17026 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 17027 // AddressingMode 2 17028 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17029 int RHSC = (int)RHS->getZExtValue(); 17030 if (RHSC < 0 && RHSC > -0x1000) { 17031 assert(Ptr->getOpcode() == ISD::ADD); 17032 isInc = false; 17033 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17034 Base = Ptr->getOperand(0); 17035 return true; 17036 } 17037 } 17038 17039 if (Ptr->getOpcode() == ISD::ADD) { 17040 isInc = true; 17041 ARM_AM::ShiftOpc ShOpcVal= 17042 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 17043 if (ShOpcVal != ARM_AM::no_shift) { 17044 Base = Ptr->getOperand(1); 17045 Offset = Ptr->getOperand(0); 17046 } else { 17047 Base = Ptr->getOperand(0); 17048 Offset = Ptr->getOperand(1); 17049 } 17050 return true; 17051 } 17052 17053 isInc = (Ptr->getOpcode() == ISD::ADD); 17054 Base = Ptr->getOperand(0); 17055 Offset = Ptr->getOperand(1); 17056 return true; 17057 } 17058 17059 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 17060 return false; 17061 } 17062 17063 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 17064 bool isSEXTLoad, SDValue &Base, 17065 SDValue &Offset, bool &isInc, 17066 SelectionDAG &DAG) { 17067 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17068 return false; 17069 17070 Base = Ptr->getOperand(0); 17071 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 17072 int RHSC = (int)RHS->getZExtValue(); 17073 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 17074 assert(Ptr->getOpcode() == ISD::ADD); 17075 isInc = false; 17076 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17077 return true; 17078 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 17079 isInc = Ptr->getOpcode() == ISD::ADD; 17080 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17081 return true; 17082 } 17083 } 17084 17085 return false; 17086 } 17087 17088 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment, 17089 bool isSEXTLoad, bool IsMasked, bool isLE, 17090 SDValue &Base, SDValue &Offset, 17091 bool &isInc, SelectionDAG &DAG) { 17092 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 17093 return false; 17094 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 17095 return false; 17096 17097 // We allow LE non-masked loads to change the type (for example use a vldrb.8 17098 // as opposed to a vldrw.32). This can allow extra addressing modes or 17099 // alignments for what is otherwise an equivalent instruction. 17100 bool CanChangeType = isLE && !IsMasked; 17101 17102 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 17103 int RHSC = (int)RHS->getZExtValue(); 17104 17105 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 17106 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 17107 assert(Ptr->getOpcode() == ISD::ADD); 17108 isInc = false; 17109 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17110 return true; 17111 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 17112 isInc = Ptr->getOpcode() == ISD::ADD; 17113 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 17114 return true; 17115 } 17116 return false; 17117 }; 17118 17119 // Try to find a matching instruction based on s/zext, Alignment, Offset and 17120 // (in BE/masked) type. 17121 Base = Ptr->getOperand(0); 17122 if (VT == MVT::v4i16) { 17123 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2)) 17124 return true; 17125 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 17126 if (IsInRange(RHSC, 0x80, 1)) 17127 return true; 17128 } else if (Alignment >= 4 && 17129 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) && 17130 IsInRange(RHSC, 0x80, 4)) 17131 return true; 17132 else if (Alignment >= 2 && 17133 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) && 17134 IsInRange(RHSC, 0x80, 2)) 17135 return true; 17136 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 17137 return true; 17138 return false; 17139 } 17140 17141 /// getPreIndexedAddressParts - returns true by value, base pointer and 17142 /// offset pointer and addressing mode by reference if the node's address 17143 /// can be legally represented as pre-indexed load / store address. 17144 bool 17145 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 17146 SDValue &Offset, 17147 ISD::MemIndexedMode &AM, 17148 SelectionDAG &DAG) const { 17149 if (Subtarget->isThumb1Only()) 17150 return false; 17151 17152 EVT VT; 17153 SDValue Ptr; 17154 Align Alignment; 17155 bool isSEXTLoad = false; 17156 bool IsMasked = false; 17157 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 17158 Ptr = LD->getBasePtr(); 17159 VT = LD->getMemoryVT(); 17160 Alignment = LD->getAlign(); 17161 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17162 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17163 Ptr = ST->getBasePtr(); 17164 VT = ST->getMemoryVT(); 17165 Alignment = ST->getAlign(); 17166 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17167 Ptr = LD->getBasePtr(); 17168 VT = LD->getMemoryVT(); 17169 Alignment = LD->getAlign(); 17170 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17171 IsMasked = true; 17172 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17173 Ptr = ST->getBasePtr(); 17174 VT = ST->getMemoryVT(); 17175 Alignment = ST->getAlign(); 17176 IsMasked = true; 17177 } else 17178 return false; 17179 17180 bool isInc; 17181 bool isLegal = false; 17182 if (VT.isVector()) 17183 isLegal = Subtarget->hasMVEIntegerOps() && 17184 getMVEIndexedAddressParts( 17185 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked, 17186 Subtarget->isLittle(), Base, Offset, isInc, DAG); 17187 else { 17188 if (Subtarget->isThumb2()) 17189 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17190 Offset, isInc, DAG); 17191 else 17192 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 17193 Offset, isInc, DAG); 17194 } 17195 if (!isLegal) 17196 return false; 17197 17198 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 17199 return true; 17200 } 17201 17202 /// getPostIndexedAddressParts - returns true by value, base pointer and 17203 /// offset pointer and addressing mode by reference if this node can be 17204 /// combined with a load / store to form a post-indexed load / store. 17205 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 17206 SDValue &Base, 17207 SDValue &Offset, 17208 ISD::MemIndexedMode &AM, 17209 SelectionDAG &DAG) const { 17210 EVT VT; 17211 SDValue Ptr; 17212 Align Alignment; 17213 bool isSEXTLoad = false, isNonExt; 17214 bool IsMasked = false; 17215 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 17216 VT = LD->getMemoryVT(); 17217 Ptr = LD->getBasePtr(); 17218 Alignment = LD->getAlign(); 17219 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17220 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17221 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 17222 VT = ST->getMemoryVT(); 17223 Ptr = ST->getBasePtr(); 17224 Alignment = ST->getAlign(); 17225 isNonExt = !ST->isTruncatingStore(); 17226 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 17227 VT = LD->getMemoryVT(); 17228 Ptr = LD->getBasePtr(); 17229 Alignment = LD->getAlign(); 17230 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 17231 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 17232 IsMasked = true; 17233 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 17234 VT = ST->getMemoryVT(); 17235 Ptr = ST->getBasePtr(); 17236 Alignment = ST->getAlign(); 17237 isNonExt = !ST->isTruncatingStore(); 17238 IsMasked = true; 17239 } else 17240 return false; 17241 17242 if (Subtarget->isThumb1Only()) { 17243 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 17244 // must be non-extending/truncating, i32, with an offset of 4. 17245 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 17246 if (Op->getOpcode() != ISD::ADD || !isNonExt) 17247 return false; 17248 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 17249 if (!RHS || RHS->getZExtValue() != 4) 17250 return false; 17251 17252 Offset = Op->getOperand(1); 17253 Base = Op->getOperand(0); 17254 AM = ISD::POST_INC; 17255 return true; 17256 } 17257 17258 bool isInc; 17259 bool isLegal = false; 17260 if (VT.isVector()) 17261 isLegal = Subtarget->hasMVEIntegerOps() && 17262 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked, 17263 Subtarget->isLittle(), Base, Offset, 17264 isInc, DAG); 17265 else { 17266 if (Subtarget->isThumb2()) 17267 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17268 isInc, DAG); 17269 else 17270 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 17271 isInc, DAG); 17272 } 17273 if (!isLegal) 17274 return false; 17275 17276 if (Ptr != Base) { 17277 // Swap base ptr and offset to catch more post-index load / store when 17278 // it's legal. In Thumb2 mode, offset must be an immediate. 17279 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 17280 !Subtarget->isThumb2()) 17281 std::swap(Base, Offset); 17282 17283 // Post-indexed load / store update the base pointer. 17284 if (Ptr != Base) 17285 return false; 17286 } 17287 17288 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 17289 return true; 17290 } 17291 17292 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 17293 KnownBits &Known, 17294 const APInt &DemandedElts, 17295 const SelectionDAG &DAG, 17296 unsigned Depth) const { 17297 unsigned BitWidth = Known.getBitWidth(); 17298 Known.resetAll(); 17299 switch (Op.getOpcode()) { 17300 default: break; 17301 case ARMISD::ADDC: 17302 case ARMISD::ADDE: 17303 case ARMISD::SUBC: 17304 case ARMISD::SUBE: 17305 // Special cases when we convert a carry to a boolean. 17306 if (Op.getResNo() == 0) { 17307 SDValue LHS = Op.getOperand(0); 17308 SDValue RHS = Op.getOperand(1); 17309 // (ADDE 0, 0, C) will give us a single bit. 17310 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 17311 isNullConstant(RHS)) { 17312 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 17313 return; 17314 } 17315 } 17316 break; 17317 case ARMISD::CMOV: { 17318 // Bits are known zero/one if known on the LHS and RHS. 17319 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 17320 if (Known.isUnknown()) 17321 return; 17322 17323 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 17324 Known.Zero &= KnownRHS.Zero; 17325 Known.One &= KnownRHS.One; 17326 return; 17327 } 17328 case ISD::INTRINSIC_W_CHAIN: { 17329 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 17330 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 17331 switch (IntID) { 17332 default: return; 17333 case Intrinsic::arm_ldaex: 17334 case Intrinsic::arm_ldrex: { 17335 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 17336 unsigned MemBits = VT.getScalarSizeInBits(); 17337 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 17338 return; 17339 } 17340 } 17341 } 17342 case ARMISD::BFI: { 17343 // Conservatively, we can recurse down the first operand 17344 // and just mask out all affected bits. 17345 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 17346 17347 // The operand to BFI is already a mask suitable for removing the bits it 17348 // sets. 17349 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 17350 const APInt &Mask = CI->getAPIntValue(); 17351 Known.Zero &= Mask; 17352 Known.One &= Mask; 17353 return; 17354 } 17355 case ARMISD::VGETLANEs: 17356 case ARMISD::VGETLANEu: { 17357 const SDValue &SrcSV = Op.getOperand(0); 17358 EVT VecVT = SrcSV.getValueType(); 17359 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 17360 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 17361 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 17362 assert(Pos->getAPIntValue().ult(NumSrcElts) && 17363 "VGETLANE index out of bounds"); 17364 unsigned Idx = Pos->getZExtValue(); 17365 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 17366 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 17367 17368 EVT VT = Op.getValueType(); 17369 const unsigned DstSz = VT.getScalarSizeInBits(); 17370 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 17371 (void)SrcSz; 17372 assert(SrcSz == Known.getBitWidth()); 17373 assert(DstSz > SrcSz); 17374 if (Op.getOpcode() == ARMISD::VGETLANEs) 17375 Known = Known.sext(DstSz); 17376 else { 17377 Known = Known.zext(DstSz); 17378 } 17379 assert(DstSz == Known.getBitWidth()); 17380 break; 17381 } 17382 case ARMISD::VMOVrh: { 17383 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 17384 assert(KnownOp.getBitWidth() == 16); 17385 Known = KnownOp.zext(32); 17386 break; 17387 } 17388 } 17389 } 17390 17391 bool ARMTargetLowering::targetShrinkDemandedConstant( 17392 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 17393 TargetLoweringOpt &TLO) const { 17394 // Delay optimization, so we don't have to deal with illegal types, or block 17395 // optimizations. 17396 if (!TLO.LegalOps) 17397 return false; 17398 17399 // Only optimize AND for now. 17400 if (Op.getOpcode() != ISD::AND) 17401 return false; 17402 17403 EVT VT = Op.getValueType(); 17404 17405 // Ignore vectors. 17406 if (VT.isVector()) 17407 return false; 17408 17409 assert(VT == MVT::i32 && "Unexpected integer type"); 17410 17411 // Make sure the RHS really is a constant. 17412 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 17413 if (!C) 17414 return false; 17415 17416 unsigned Mask = C->getZExtValue(); 17417 17418 unsigned Demanded = DemandedBits.getZExtValue(); 17419 unsigned ShrunkMask = Mask & Demanded; 17420 unsigned ExpandedMask = Mask | ~Demanded; 17421 17422 // If the mask is all zeros, let the target-independent code replace the 17423 // result with zero. 17424 if (ShrunkMask == 0) 17425 return false; 17426 17427 // If the mask is all ones, erase the AND. (Currently, the target-independent 17428 // code won't do this, so we have to do it explicitly to avoid an infinite 17429 // loop in obscure cases.) 17430 if (ExpandedMask == ~0U) 17431 return TLO.CombineTo(Op, Op.getOperand(0)); 17432 17433 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 17434 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 17435 }; 17436 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 17437 if (NewMask == Mask) 17438 return true; 17439 SDLoc DL(Op); 17440 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 17441 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 17442 return TLO.CombineTo(Op, NewOp); 17443 }; 17444 17445 // Prefer uxtb mask. 17446 if (IsLegalMask(0xFF)) 17447 return UseMask(0xFF); 17448 17449 // Prefer uxth mask. 17450 if (IsLegalMask(0xFFFF)) 17451 return UseMask(0xFFFF); 17452 17453 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 17454 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17455 if (ShrunkMask < 256) 17456 return UseMask(ShrunkMask); 17457 17458 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 17459 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 17460 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 17461 return UseMask(ExpandedMask); 17462 17463 // Potential improvements: 17464 // 17465 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 17466 // We could try to prefer Thumb1 immediates which can be lowered to a 17467 // two-instruction sequence. 17468 // We could try to recognize more legal ARM/Thumb2 immediates here. 17469 17470 return false; 17471 } 17472 17473 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode( 17474 SDValue Op, const APInt &OriginalDemandedBits, 17475 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 17476 unsigned Depth) const { 17477 unsigned Opc = Op.getOpcode(); 17478 17479 switch (Opc) { 17480 case ARMISD::ASRL: 17481 case ARMISD::LSRL: { 17482 // If this is result 0 and the other result is unused, see if the demand 17483 // bits allow us to shrink this long shift into a standard small shift in 17484 // the opposite direction. 17485 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) && 17486 isa<ConstantSDNode>(Op->getOperand(2))) { 17487 unsigned ShAmt = Op->getConstantOperandVal(2); 17488 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf( 17489 APInt::getAllOnesValue(32) << (32 - ShAmt))) 17490 return TLO.CombineTo( 17491 Op, TLO.DAG.getNode( 17492 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1), 17493 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32))); 17494 } 17495 break; 17496 } 17497 } 17498 17499 return TargetLowering::SimplifyDemandedBitsForTargetNode( 17500 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth); 17501 } 17502 17503 //===----------------------------------------------------------------------===// 17504 // ARM Inline Assembly Support 17505 //===----------------------------------------------------------------------===// 17506 17507 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 17508 // Looking for "rev" which is V6+. 17509 if (!Subtarget->hasV6Ops()) 17510 return false; 17511 17512 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand()); 17513 std::string AsmStr = IA->getAsmString(); 17514 SmallVector<StringRef, 4> AsmPieces; 17515 SplitString(AsmStr, AsmPieces, ";\n"); 17516 17517 switch (AsmPieces.size()) { 17518 default: return false; 17519 case 1: 17520 AsmStr = std::string(AsmPieces[0]); 17521 AsmPieces.clear(); 17522 SplitString(AsmStr, AsmPieces, " \t,"); 17523 17524 // rev $0, $1 17525 if (AsmPieces.size() == 3 && 17526 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 17527 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 17528 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 17529 if (Ty && Ty->getBitWidth() == 32) 17530 return IntrinsicLowering::LowerToByteSwap(CI); 17531 } 17532 break; 17533 } 17534 17535 return false; 17536 } 17537 17538 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 17539 // At this point, we have to lower this constraint to something else, so we 17540 // lower it to an "r" or "w". However, by doing this we will force the result 17541 // to be in register, while the X constraint is much more permissive. 17542 // 17543 // Although we are correct (we are free to emit anything, without 17544 // constraints), we might break use cases that would expect us to be more 17545 // efficient and emit something else. 17546 if (!Subtarget->hasVFP2Base()) 17547 return "r"; 17548 if (ConstraintVT.isFloatingPoint()) 17549 return "w"; 17550 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 17551 (ConstraintVT.getSizeInBits() == 64 || 17552 ConstraintVT.getSizeInBits() == 128)) 17553 return "w"; 17554 17555 return "r"; 17556 } 17557 17558 /// getConstraintType - Given a constraint letter, return the type of 17559 /// constraint it is for this target. 17560 ARMTargetLowering::ConstraintType 17561 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 17562 unsigned S = Constraint.size(); 17563 if (S == 1) { 17564 switch (Constraint[0]) { 17565 default: break; 17566 case 'l': return C_RegisterClass; 17567 case 'w': return C_RegisterClass; 17568 case 'h': return C_RegisterClass; 17569 case 'x': return C_RegisterClass; 17570 case 't': return C_RegisterClass; 17571 case 'j': return C_Immediate; // Constant for movw. 17572 // An address with a single base register. Due to the way we 17573 // currently handle addresses it is the same as an 'r' memory constraint. 17574 case 'Q': return C_Memory; 17575 } 17576 } else if (S == 2) { 17577 switch (Constraint[0]) { 17578 default: break; 17579 case 'T': return C_RegisterClass; 17580 // All 'U+' constraints are addresses. 17581 case 'U': return C_Memory; 17582 } 17583 } 17584 return TargetLowering::getConstraintType(Constraint); 17585 } 17586 17587 /// Examine constraint type and operand type and determine a weight value. 17588 /// This object must already have been set up with the operand type 17589 /// and the current alternative constraint selected. 17590 TargetLowering::ConstraintWeight 17591 ARMTargetLowering::getSingleConstraintMatchWeight( 17592 AsmOperandInfo &info, const char *constraint) const { 17593 ConstraintWeight weight = CW_Invalid; 17594 Value *CallOperandVal = info.CallOperandVal; 17595 // If we don't have a value, we can't do a match, 17596 // but allow it at the lowest weight. 17597 if (!CallOperandVal) 17598 return CW_Default; 17599 Type *type = CallOperandVal->getType(); 17600 // Look at the constraint type. 17601 switch (*constraint) { 17602 default: 17603 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 17604 break; 17605 case 'l': 17606 if (type->isIntegerTy()) { 17607 if (Subtarget->isThumb()) 17608 weight = CW_SpecificReg; 17609 else 17610 weight = CW_Register; 17611 } 17612 break; 17613 case 'w': 17614 if (type->isFloatingPointTy()) 17615 weight = CW_Register; 17616 break; 17617 } 17618 return weight; 17619 } 17620 17621 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 17622 17623 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 17624 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 17625 switch (Constraint.size()) { 17626 case 1: 17627 // GCC ARM Constraint Letters 17628 switch (Constraint[0]) { 17629 case 'l': // Low regs or general regs. 17630 if (Subtarget->isThumb()) 17631 return RCPair(0U, &ARM::tGPRRegClass); 17632 return RCPair(0U, &ARM::GPRRegClass); 17633 case 'h': // High regs or no regs. 17634 if (Subtarget->isThumb()) 17635 return RCPair(0U, &ARM::hGPRRegClass); 17636 break; 17637 case 'r': 17638 if (Subtarget->isThumb1Only()) 17639 return RCPair(0U, &ARM::tGPRRegClass); 17640 return RCPair(0U, &ARM::GPRRegClass); 17641 case 'w': 17642 if (VT == MVT::Other) 17643 break; 17644 if (VT == MVT::f32) 17645 return RCPair(0U, &ARM::SPRRegClass); 17646 if (VT.getSizeInBits() == 64) 17647 return RCPair(0U, &ARM::DPRRegClass); 17648 if (VT.getSizeInBits() == 128) 17649 return RCPair(0U, &ARM::QPRRegClass); 17650 break; 17651 case 'x': 17652 if (VT == MVT::Other) 17653 break; 17654 if (VT == MVT::f32) 17655 return RCPair(0U, &ARM::SPR_8RegClass); 17656 if (VT.getSizeInBits() == 64) 17657 return RCPair(0U, &ARM::DPR_8RegClass); 17658 if (VT.getSizeInBits() == 128) 17659 return RCPair(0U, &ARM::QPR_8RegClass); 17660 break; 17661 case 't': 17662 if (VT == MVT::Other) 17663 break; 17664 if (VT == MVT::f32 || VT == MVT::i32) 17665 return RCPair(0U, &ARM::SPRRegClass); 17666 if (VT.getSizeInBits() == 64) 17667 return RCPair(0U, &ARM::DPR_VFP2RegClass); 17668 if (VT.getSizeInBits() == 128) 17669 return RCPair(0U, &ARM::QPR_VFP2RegClass); 17670 break; 17671 } 17672 break; 17673 17674 case 2: 17675 if (Constraint[0] == 'T') { 17676 switch (Constraint[1]) { 17677 default: 17678 break; 17679 case 'e': 17680 return RCPair(0U, &ARM::tGPREvenRegClass); 17681 case 'o': 17682 return RCPair(0U, &ARM::tGPROddRegClass); 17683 } 17684 } 17685 break; 17686 17687 default: 17688 break; 17689 } 17690 17691 if (StringRef("{cc}").equals_lower(Constraint)) 17692 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 17693 17694 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 17695 } 17696 17697 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 17698 /// vector. If it is invalid, don't add anything to Ops. 17699 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 17700 std::string &Constraint, 17701 std::vector<SDValue>&Ops, 17702 SelectionDAG &DAG) const { 17703 SDValue Result; 17704 17705 // Currently only support length 1 constraints. 17706 if (Constraint.length() != 1) return; 17707 17708 char ConstraintLetter = Constraint[0]; 17709 switch (ConstraintLetter) { 17710 default: break; 17711 case 'j': 17712 case 'I': case 'J': case 'K': case 'L': 17713 case 'M': case 'N': case 'O': 17714 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 17715 if (!C) 17716 return; 17717 17718 int64_t CVal64 = C->getSExtValue(); 17719 int CVal = (int) CVal64; 17720 // None of these constraints allow values larger than 32 bits. Check 17721 // that the value fits in an int. 17722 if (CVal != CVal64) 17723 return; 17724 17725 switch (ConstraintLetter) { 17726 case 'j': 17727 // Constant suitable for movw, must be between 0 and 17728 // 65535. 17729 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps())) 17730 if (CVal >= 0 && CVal <= 65535) 17731 break; 17732 return; 17733 case 'I': 17734 if (Subtarget->isThumb1Only()) { 17735 // This must be a constant between 0 and 255, for ADD 17736 // immediates. 17737 if (CVal >= 0 && CVal <= 255) 17738 break; 17739 } else if (Subtarget->isThumb2()) { 17740 // A constant that can be used as an immediate value in a 17741 // data-processing instruction. 17742 if (ARM_AM::getT2SOImmVal(CVal) != -1) 17743 break; 17744 } else { 17745 // A constant that can be used as an immediate value in a 17746 // data-processing instruction. 17747 if (ARM_AM::getSOImmVal(CVal) != -1) 17748 break; 17749 } 17750 return; 17751 17752 case 'J': 17753 if (Subtarget->isThumb1Only()) { 17754 // This must be a constant between -255 and -1, for negated ADD 17755 // immediates. This can be used in GCC with an "n" modifier that 17756 // prints the negated value, for use with SUB instructions. It is 17757 // not useful otherwise but is implemented for compatibility. 17758 if (CVal >= -255 && CVal <= -1) 17759 break; 17760 } else { 17761 // This must be a constant between -4095 and 4095. It is not clear 17762 // what this constraint is intended for. Implemented for 17763 // compatibility with GCC. 17764 if (CVal >= -4095 && CVal <= 4095) 17765 break; 17766 } 17767 return; 17768 17769 case 'K': 17770 if (Subtarget->isThumb1Only()) { 17771 // A 32-bit value where only one byte has a nonzero value. Exclude 17772 // zero to match GCC. This constraint is used by GCC internally for 17773 // constants that can be loaded with a move/shift combination. 17774 // It is not useful otherwise but is implemented for compatibility. 17775 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 17776 break; 17777 } else if (Subtarget->isThumb2()) { 17778 // A constant whose bitwise inverse can be used as an immediate 17779 // value in a data-processing instruction. This can be used in GCC 17780 // with a "B" modifier that prints the inverted value, for use with 17781 // BIC and MVN instructions. It is not useful otherwise but is 17782 // implemented for compatibility. 17783 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 17784 break; 17785 } else { 17786 // A constant whose bitwise inverse can be used as an immediate 17787 // value in a data-processing instruction. This can be used in GCC 17788 // with a "B" modifier that prints the inverted value, for use with 17789 // BIC and MVN instructions. It is not useful otherwise but is 17790 // implemented for compatibility. 17791 if (ARM_AM::getSOImmVal(~CVal) != -1) 17792 break; 17793 } 17794 return; 17795 17796 case 'L': 17797 if (Subtarget->isThumb1Only()) { 17798 // This must be a constant between -7 and 7, 17799 // for 3-operand ADD/SUB immediate instructions. 17800 if (CVal >= -7 && CVal < 7) 17801 break; 17802 } else if (Subtarget->isThumb2()) { 17803 // A constant whose negation can be used as an immediate value in a 17804 // data-processing instruction. This can be used in GCC with an "n" 17805 // modifier that prints the negated value, for use with SUB 17806 // instructions. It is not useful otherwise but is implemented for 17807 // compatibility. 17808 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 17809 break; 17810 } else { 17811 // A constant whose negation can be used as an immediate value in a 17812 // data-processing instruction. This can be used in GCC with an "n" 17813 // modifier that prints the negated value, for use with SUB 17814 // instructions. It is not useful otherwise but is implemented for 17815 // compatibility. 17816 if (ARM_AM::getSOImmVal(-CVal) != -1) 17817 break; 17818 } 17819 return; 17820 17821 case 'M': 17822 if (Subtarget->isThumb1Only()) { 17823 // This must be a multiple of 4 between 0 and 1020, for 17824 // ADD sp + immediate. 17825 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 17826 break; 17827 } else { 17828 // A power of two or a constant between 0 and 32. This is used in 17829 // GCC for the shift amount on shifted register operands, but it is 17830 // useful in general for any shift amounts. 17831 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 17832 break; 17833 } 17834 return; 17835 17836 case 'N': 17837 if (Subtarget->isThumb1Only()) { 17838 // This must be a constant between 0 and 31, for shift amounts. 17839 if (CVal >= 0 && CVal <= 31) 17840 break; 17841 } 17842 return; 17843 17844 case 'O': 17845 if (Subtarget->isThumb1Only()) { 17846 // This must be a multiple of 4 between -508 and 508, for 17847 // ADD/SUB sp = sp + immediate. 17848 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 17849 break; 17850 } 17851 return; 17852 } 17853 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 17854 break; 17855 } 17856 17857 if (Result.getNode()) { 17858 Ops.push_back(Result); 17859 return; 17860 } 17861 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 17862 } 17863 17864 static RTLIB::Libcall getDivRemLibcall( 17865 const SDNode *N, MVT::SimpleValueType SVT) { 17866 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 17867 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 17868 "Unhandled Opcode in getDivRemLibcall"); 17869 bool isSigned = N->getOpcode() == ISD::SDIVREM || 17870 N->getOpcode() == ISD::SREM; 17871 RTLIB::Libcall LC; 17872 switch (SVT) { 17873 default: llvm_unreachable("Unexpected request for libcall!"); 17874 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 17875 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 17876 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 17877 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 17878 } 17879 return LC; 17880 } 17881 17882 static TargetLowering::ArgListTy getDivRemArgList( 17883 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 17884 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 17885 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 17886 "Unhandled Opcode in getDivRemArgList"); 17887 bool isSigned = N->getOpcode() == ISD::SDIVREM || 17888 N->getOpcode() == ISD::SREM; 17889 TargetLowering::ArgListTy Args; 17890 TargetLowering::ArgListEntry Entry; 17891 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 17892 EVT ArgVT = N->getOperand(i).getValueType(); 17893 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 17894 Entry.Node = N->getOperand(i); 17895 Entry.Ty = ArgTy; 17896 Entry.IsSExt = isSigned; 17897 Entry.IsZExt = !isSigned; 17898 Args.push_back(Entry); 17899 } 17900 if (Subtarget->isTargetWindows() && Args.size() >= 2) 17901 std::swap(Args[0], Args[1]); 17902 return Args; 17903 } 17904 17905 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 17906 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 17907 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 17908 Subtarget->isTargetWindows()) && 17909 "Register-based DivRem lowering only"); 17910 unsigned Opcode = Op->getOpcode(); 17911 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 17912 "Invalid opcode for Div/Rem lowering"); 17913 bool isSigned = (Opcode == ISD::SDIVREM); 17914 EVT VT = Op->getValueType(0); 17915 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 17916 SDLoc dl(Op); 17917 17918 // If the target has hardware divide, use divide + multiply + subtract: 17919 // div = a / b 17920 // rem = a - b * div 17921 // return {div, rem} 17922 // This should be lowered into UDIV/SDIV + MLS later on. 17923 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 17924 : Subtarget->hasDivideInARMMode(); 17925 if (hasDivide && Op->getValueType(0).isSimple() && 17926 Op->getSimpleValueType(0) == MVT::i32) { 17927 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 17928 const SDValue Dividend = Op->getOperand(0); 17929 const SDValue Divisor = Op->getOperand(1); 17930 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 17931 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 17932 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 17933 17934 SDValue Values[2] = {Div, Rem}; 17935 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 17936 } 17937 17938 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 17939 VT.getSimpleVT().SimpleTy); 17940 SDValue InChain = DAG.getEntryNode(); 17941 17942 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 17943 DAG.getContext(), 17944 Subtarget); 17945 17946 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 17947 getPointerTy(DAG.getDataLayout())); 17948 17949 Type *RetTy = StructType::get(Ty, Ty); 17950 17951 if (Subtarget->isTargetWindows()) 17952 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 17953 17954 TargetLowering::CallLoweringInfo CLI(DAG); 17955 CLI.setDebugLoc(dl).setChain(InChain) 17956 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 17957 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 17958 17959 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 17960 return CallInfo.first; 17961 } 17962 17963 // Lowers REM using divmod helpers 17964 // see RTABI section 4.2/4.3 17965 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 17966 // Build return types (div and rem) 17967 std::vector<Type*> RetTyParams; 17968 Type *RetTyElement; 17969 17970 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 17971 default: llvm_unreachable("Unexpected request for libcall!"); 17972 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 17973 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 17974 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 17975 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 17976 } 17977 17978 RetTyParams.push_back(RetTyElement); 17979 RetTyParams.push_back(RetTyElement); 17980 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 17981 Type *RetTy = StructType::get(*DAG.getContext(), ret); 17982 17983 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 17984 SimpleTy); 17985 SDValue InChain = DAG.getEntryNode(); 17986 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 17987 Subtarget); 17988 bool isSigned = N->getOpcode() == ISD::SREM; 17989 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 17990 getPointerTy(DAG.getDataLayout())); 17991 17992 if (Subtarget->isTargetWindows()) 17993 InChain = WinDBZCheckDenominator(DAG, N, InChain); 17994 17995 // Lower call 17996 CallLoweringInfo CLI(DAG); 17997 CLI.setChain(InChain) 17998 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 17999 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 18000 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 18001 18002 // Return second (rem) result operand (first contains div) 18003 SDNode *ResNode = CallResult.first.getNode(); 18004 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 18005 return ResNode->getOperand(1); 18006 } 18007 18008 SDValue 18009 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 18010 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 18011 SDLoc DL(Op); 18012 18013 // Get the inputs. 18014 SDValue Chain = Op.getOperand(0); 18015 SDValue Size = Op.getOperand(1); 18016 18017 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 18018 "no-stack-arg-probe")) { 18019 MaybeAlign Align = 18020 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue(); 18021 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 18022 Chain = SP.getValue(1); 18023 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 18024 if (Align) 18025 SP = 18026 DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 18027 DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32)); 18028 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 18029 SDValue Ops[2] = { SP, Chain }; 18030 return DAG.getMergeValues(Ops, DL); 18031 } 18032 18033 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 18034 DAG.getConstant(2, DL, MVT::i32)); 18035 18036 SDValue Flag; 18037 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 18038 Flag = Chain.getValue(1); 18039 18040 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 18041 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 18042 18043 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 18044 Chain = NewSP.getValue(1); 18045 18046 SDValue Ops[2] = { NewSP, Chain }; 18047 return DAG.getMergeValues(Ops, DL); 18048 } 18049 18050 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 18051 bool IsStrict = Op->isStrictFPOpcode(); 18052 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 18053 const unsigned DstSz = Op.getValueType().getSizeInBits(); 18054 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 18055 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 18056 "Unexpected type for custom-lowering FP_EXTEND"); 18057 18058 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 18059 "With both FP DP and 16, any FP conversion is legal!"); 18060 18061 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 18062 "With FP16, 16 to 32 conversion is legal!"); 18063 18064 // Converting from 32 -> 64 is valid if we have FP64. 18065 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) { 18066 // FIXME: Remove this when we have strict fp instruction selection patterns 18067 if (IsStrict) { 18068 SDLoc Loc(Op); 18069 SDValue Result = DAG.getNode(ISD::FP_EXTEND, 18070 Loc, Op.getValueType(), SrcVal); 18071 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc); 18072 } 18073 return Op; 18074 } 18075 18076 // Either we are converting from 16 -> 64, without FP16 and/or 18077 // FP.double-precision or without Armv8-fp. So we must do it in two 18078 // steps. 18079 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 18080 // without FP16. So we must do a function call. 18081 SDLoc Loc(Op); 18082 RTLIB::Libcall LC; 18083 MakeLibCallOptions CallOptions; 18084 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 18085 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) { 18086 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64()); 18087 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32); 18088 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64); 18089 if (Supported) { 18090 if (IsStrict) { 18091 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc, 18092 {DstVT, MVT::Other}, {Chain, SrcVal}); 18093 Chain = SrcVal.getValue(1); 18094 } else { 18095 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal); 18096 } 18097 } else { 18098 LC = RTLIB::getFPEXT(SrcVT, DstVT); 18099 assert(LC != RTLIB::UNKNOWN_LIBCALL && 18100 "Unexpected type for custom-lowering FP_EXTEND"); 18101 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 18102 Loc, Chain); 18103 } 18104 } 18105 18106 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal; 18107 } 18108 18109 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 18110 bool IsStrict = Op->isStrictFPOpcode(); 18111 18112 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 18113 EVT SrcVT = SrcVal.getValueType(); 18114 EVT DstVT = Op.getValueType(); 18115 const unsigned DstSz = Op.getValueType().getSizeInBits(); 18116 const unsigned SrcSz = SrcVT.getSizeInBits(); 18117 (void)DstSz; 18118 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 18119 "Unexpected type for custom-lowering FP_ROUND"); 18120 18121 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 18122 "With both FP DP and 16, any FP conversion is legal!"); 18123 18124 SDLoc Loc(Op); 18125 18126 // Instruction from 32 -> 16 if hasFP16 is valid 18127 if (SrcSz == 32 && Subtarget->hasFP16()) 18128 return Op; 18129 18130 // Lib call from 32 -> 16 / 64 -> [32, 16] 18131 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 18132 assert(LC != RTLIB::UNKNOWN_LIBCALL && 18133 "Unexpected type for custom-lowering FP_ROUND"); 18134 MakeLibCallOptions CallOptions; 18135 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 18136 SDValue Result; 18137 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, 18138 Loc, Chain); 18139 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result; 18140 } 18141 18142 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 18143 SelectionDAG &DAG) const { 18144 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 18145 MVT HalfT = MVT::i32; 18146 SDLoc dl(N); 18147 SDValue Hi, Lo, Tmp; 18148 18149 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 18150 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 18151 return ; 18152 18153 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 18154 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 18155 18156 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 18157 DAG.getConstant(0, dl, HalfT)); 18158 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 18159 DAG.getConstant(1, dl, HalfT)); 18160 18161 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 18162 DAG.getConstant(OpTypeBits - 1, dl, 18163 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 18164 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 18165 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 18166 SDValue(Lo.getNode(), 1)); 18167 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 18168 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 18169 18170 Results.push_back(Lo); 18171 Results.push_back(Hi); 18172 } 18173 18174 bool 18175 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 18176 // The ARM target isn't yet aware of offsets. 18177 return false; 18178 } 18179 18180 bool ARM::isBitFieldInvertedMask(unsigned v) { 18181 if (v == 0xffffffff) 18182 return false; 18183 18184 // there can be 1's on either or both "outsides", all the "inside" 18185 // bits must be 0's 18186 return isShiftedMask_32(~v); 18187 } 18188 18189 /// isFPImmLegal - Returns true if the target can instruction select the 18190 /// specified FP immediate natively. If false, the legalizer will 18191 /// materialize the FP immediate as a load from a constant pool. 18192 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 18193 bool ForCodeSize) const { 18194 if (!Subtarget->hasVFP3Base()) 18195 return false; 18196 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 18197 return ARM_AM::getFP16Imm(Imm) != -1; 18198 if (VT == MVT::f32 && Subtarget->hasFullFP16() && 18199 ARM_AM::getFP32FP16Imm(Imm) != -1) 18200 return true; 18201 if (VT == MVT::f32) 18202 return ARM_AM::getFP32Imm(Imm) != -1; 18203 if (VT == MVT::f64 && Subtarget->hasFP64()) 18204 return ARM_AM::getFP64Imm(Imm) != -1; 18205 return false; 18206 } 18207 18208 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 18209 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 18210 /// specified in the intrinsic calls. 18211 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 18212 const CallInst &I, 18213 MachineFunction &MF, 18214 unsigned Intrinsic) const { 18215 switch (Intrinsic) { 18216 case Intrinsic::arm_neon_vld1: 18217 case Intrinsic::arm_neon_vld2: 18218 case Intrinsic::arm_neon_vld3: 18219 case Intrinsic::arm_neon_vld4: 18220 case Intrinsic::arm_neon_vld2lane: 18221 case Intrinsic::arm_neon_vld3lane: 18222 case Intrinsic::arm_neon_vld4lane: 18223 case Intrinsic::arm_neon_vld2dup: 18224 case Intrinsic::arm_neon_vld3dup: 18225 case Intrinsic::arm_neon_vld4dup: { 18226 Info.opc = ISD::INTRINSIC_W_CHAIN; 18227 // Conservatively set memVT to the entire set of vectors loaded. 18228 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18229 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18230 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18231 Info.ptrVal = I.getArgOperand(0); 18232 Info.offset = 0; 18233 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18234 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18235 // volatile loads with NEON intrinsics not supported 18236 Info.flags = MachineMemOperand::MOLoad; 18237 return true; 18238 } 18239 case Intrinsic::arm_neon_vld1x2: 18240 case Intrinsic::arm_neon_vld1x3: 18241 case Intrinsic::arm_neon_vld1x4: { 18242 Info.opc = ISD::INTRINSIC_W_CHAIN; 18243 // Conservatively set memVT to the entire set of vectors loaded. 18244 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18245 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 18246 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18247 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 18248 Info.offset = 0; 18249 Info.align.reset(); 18250 // volatile loads with NEON intrinsics not supported 18251 Info.flags = MachineMemOperand::MOLoad; 18252 return true; 18253 } 18254 case Intrinsic::arm_neon_vst1: 18255 case Intrinsic::arm_neon_vst2: 18256 case Intrinsic::arm_neon_vst3: 18257 case Intrinsic::arm_neon_vst4: 18258 case Intrinsic::arm_neon_vst2lane: 18259 case Intrinsic::arm_neon_vst3lane: 18260 case Intrinsic::arm_neon_vst4lane: { 18261 Info.opc = ISD::INTRINSIC_VOID; 18262 // Conservatively set memVT to the entire set of vectors stored. 18263 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18264 unsigned NumElts = 0; 18265 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18266 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18267 if (!ArgTy->isVectorTy()) 18268 break; 18269 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18270 } 18271 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18272 Info.ptrVal = I.getArgOperand(0); 18273 Info.offset = 0; 18274 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 18275 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue(); 18276 // volatile stores with NEON intrinsics not supported 18277 Info.flags = MachineMemOperand::MOStore; 18278 return true; 18279 } 18280 case Intrinsic::arm_neon_vst1x2: 18281 case Intrinsic::arm_neon_vst1x3: 18282 case Intrinsic::arm_neon_vst1x4: { 18283 Info.opc = ISD::INTRINSIC_VOID; 18284 // Conservatively set memVT to the entire set of vectors stored. 18285 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18286 unsigned NumElts = 0; 18287 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 18288 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 18289 if (!ArgTy->isVectorTy()) 18290 break; 18291 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 18292 } 18293 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 18294 Info.ptrVal = I.getArgOperand(0); 18295 Info.offset = 0; 18296 Info.align.reset(); 18297 // volatile stores with NEON intrinsics not supported 18298 Info.flags = MachineMemOperand::MOStore; 18299 return true; 18300 } 18301 case Intrinsic::arm_mve_vld2q: 18302 case Intrinsic::arm_mve_vld4q: { 18303 Info.opc = ISD::INTRINSIC_W_CHAIN; 18304 // Conservatively set memVT to the entire set of vectors loaded. 18305 Type *VecTy = cast<StructType>(I.getType())->getElementType(1); 18306 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4; 18307 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18308 Info.ptrVal = I.getArgOperand(0); 18309 Info.offset = 0; 18310 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18311 // volatile loads with MVE intrinsics not supported 18312 Info.flags = MachineMemOperand::MOLoad; 18313 return true; 18314 } 18315 case Intrinsic::arm_mve_vst2q: 18316 case Intrinsic::arm_mve_vst4q: { 18317 Info.opc = ISD::INTRINSIC_VOID; 18318 // Conservatively set memVT to the entire set of vectors stored. 18319 Type *VecTy = I.getArgOperand(1)->getType(); 18320 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4; 18321 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2); 18322 Info.ptrVal = I.getArgOperand(0); 18323 Info.offset = 0; 18324 Info.align = Align(VecTy->getScalarSizeInBits() / 8); 18325 // volatile stores with MVE intrinsics not supported 18326 Info.flags = MachineMemOperand::MOStore; 18327 return true; 18328 } 18329 case Intrinsic::arm_ldaex: 18330 case Intrinsic::arm_ldrex: { 18331 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18332 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 18333 Info.opc = ISD::INTRINSIC_W_CHAIN; 18334 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18335 Info.ptrVal = I.getArgOperand(0); 18336 Info.offset = 0; 18337 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18338 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18339 return true; 18340 } 18341 case Intrinsic::arm_stlex: 18342 case Intrinsic::arm_strex: { 18343 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 18344 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 18345 Info.opc = ISD::INTRINSIC_W_CHAIN; 18346 Info.memVT = MVT::getVT(PtrTy->getElementType()); 18347 Info.ptrVal = I.getArgOperand(1); 18348 Info.offset = 0; 18349 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 18350 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18351 return true; 18352 } 18353 case Intrinsic::arm_stlexd: 18354 case Intrinsic::arm_strexd: 18355 Info.opc = ISD::INTRINSIC_W_CHAIN; 18356 Info.memVT = MVT::i64; 18357 Info.ptrVal = I.getArgOperand(2); 18358 Info.offset = 0; 18359 Info.align = Align(8); 18360 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 18361 return true; 18362 18363 case Intrinsic::arm_ldaexd: 18364 case Intrinsic::arm_ldrexd: 18365 Info.opc = ISD::INTRINSIC_W_CHAIN; 18366 Info.memVT = MVT::i64; 18367 Info.ptrVal = I.getArgOperand(0); 18368 Info.offset = 0; 18369 Info.align = Align(8); 18370 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 18371 return true; 18372 18373 default: 18374 break; 18375 } 18376 18377 return false; 18378 } 18379 18380 /// Returns true if it is beneficial to convert a load of a constant 18381 /// to just the constant itself. 18382 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 18383 Type *Ty) const { 18384 assert(Ty->isIntegerTy()); 18385 18386 unsigned Bits = Ty->getPrimitiveSizeInBits(); 18387 if (Bits == 0 || Bits > 32) 18388 return false; 18389 return true; 18390 } 18391 18392 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 18393 unsigned Index) const { 18394 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 18395 return false; 18396 18397 return (Index == 0 || Index == ResVT.getVectorNumElements()); 18398 } 18399 18400 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 18401 ARM_MB::MemBOpt Domain) const { 18402 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18403 18404 // First, if the target has no DMB, see what fallback we can use. 18405 if (!Subtarget->hasDataBarrier()) { 18406 // Some ARMv6 cpus can support data barriers with an mcr instruction. 18407 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 18408 // here. 18409 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 18410 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 18411 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 18412 Builder.getInt32(0), Builder.getInt32(7), 18413 Builder.getInt32(10), Builder.getInt32(5)}; 18414 return Builder.CreateCall(MCR, args); 18415 } else { 18416 // Instead of using barriers, atomic accesses on these subtargets use 18417 // libcalls. 18418 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 18419 } 18420 } else { 18421 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 18422 // Only a full system barrier exists in the M-class architectures. 18423 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 18424 Constant *CDomain = Builder.getInt32(Domain); 18425 return Builder.CreateCall(DMB, CDomain); 18426 } 18427 } 18428 18429 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 18430 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 18431 Instruction *Inst, 18432 AtomicOrdering Ord) const { 18433 switch (Ord) { 18434 case AtomicOrdering::NotAtomic: 18435 case AtomicOrdering::Unordered: 18436 llvm_unreachable("Invalid fence: unordered/non-atomic"); 18437 case AtomicOrdering::Monotonic: 18438 case AtomicOrdering::Acquire: 18439 return nullptr; // Nothing to do 18440 case AtomicOrdering::SequentiallyConsistent: 18441 if (!Inst->hasAtomicStore()) 18442 return nullptr; // Nothing to do 18443 LLVM_FALLTHROUGH; 18444 case AtomicOrdering::Release: 18445 case AtomicOrdering::AcquireRelease: 18446 if (Subtarget->preferISHSTBarriers()) 18447 return makeDMB(Builder, ARM_MB::ISHST); 18448 // FIXME: add a comment with a link to documentation justifying this. 18449 else 18450 return makeDMB(Builder, ARM_MB::ISH); 18451 } 18452 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 18453 } 18454 18455 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 18456 Instruction *Inst, 18457 AtomicOrdering Ord) const { 18458 switch (Ord) { 18459 case AtomicOrdering::NotAtomic: 18460 case AtomicOrdering::Unordered: 18461 llvm_unreachable("Invalid fence: unordered/not-atomic"); 18462 case AtomicOrdering::Monotonic: 18463 case AtomicOrdering::Release: 18464 return nullptr; // Nothing to do 18465 case AtomicOrdering::Acquire: 18466 case AtomicOrdering::AcquireRelease: 18467 case AtomicOrdering::SequentiallyConsistent: 18468 return makeDMB(Builder, ARM_MB::ISH); 18469 } 18470 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 18471 } 18472 18473 // Loads and stores less than 64-bits are already atomic; ones above that 18474 // are doomed anyway, so defer to the default libcall and blame the OS when 18475 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18476 // anything for those. 18477 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 18478 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 18479 return (Size == 64) && !Subtarget->isMClass(); 18480 } 18481 18482 // Loads and stores less than 64-bits are already atomic; ones above that 18483 // are doomed anyway, so defer to the default libcall and blame the OS when 18484 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 18485 // anything for those. 18486 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 18487 // guarantee, see DDI0406C ARM architecture reference manual, 18488 // sections A8.8.72-74 LDRD) 18489 TargetLowering::AtomicExpansionKind 18490 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 18491 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 18492 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 18493 : AtomicExpansionKind::None; 18494 } 18495 18496 // For the real atomic operations, we have ldrex/strex up to 32 bits, 18497 // and up to 64 bits on the non-M profiles 18498 TargetLowering::AtomicExpansionKind 18499 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18500 if (AI->isFloatingPointOperation()) 18501 return AtomicExpansionKind::CmpXChg; 18502 18503 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18504 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 18505 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 18506 ? AtomicExpansionKind::LLSC 18507 : AtomicExpansionKind::None; 18508 } 18509 18510 TargetLowering::AtomicExpansionKind 18511 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 18512 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 18513 // implement cmpxchg without spilling. If the address being exchanged is also 18514 // on the stack and close enough to the spill slot, this can lead to a 18515 // situation where the monitor always gets cleared and the atomic operation 18516 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 18517 bool HasAtomicCmpXchg = 18518 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 18519 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 18520 return AtomicExpansionKind::LLSC; 18521 return AtomicExpansionKind::None; 18522 } 18523 18524 bool ARMTargetLowering::shouldInsertFencesForAtomic( 18525 const Instruction *I) const { 18526 return InsertFencesForAtomic; 18527 } 18528 18529 // This has so far only been implemented for MachO. 18530 bool ARMTargetLowering::useLoadStackGuardNode() const { 18531 return Subtarget->isTargetMachO(); 18532 } 18533 18534 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 18535 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18536 return TargetLowering::insertSSPDeclarations(M); 18537 18538 // MSVC CRT has a global variable holding security cookie. 18539 M.getOrInsertGlobal("__security_cookie", 18540 Type::getInt8PtrTy(M.getContext())); 18541 18542 // MSVC CRT has a function to validate security cookie. 18543 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 18544 "__security_check_cookie", Type::getVoidTy(M.getContext()), 18545 Type::getInt8PtrTy(M.getContext())); 18546 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 18547 F->addAttribute(1, Attribute::AttrKind::InReg); 18548 } 18549 18550 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 18551 // MSVC CRT has a global variable holding security cookie. 18552 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18553 return M.getGlobalVariable("__security_cookie"); 18554 return TargetLowering::getSDagStackGuard(M); 18555 } 18556 18557 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 18558 // MSVC CRT has a function to validate security cookie. 18559 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 18560 return M.getFunction("__security_check_cookie"); 18561 return TargetLowering::getSSPStackGuardCheck(M); 18562 } 18563 18564 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 18565 unsigned &Cost) const { 18566 // If we do not have NEON, vector types are not natively supported. 18567 if (!Subtarget->hasNEON()) 18568 return false; 18569 18570 // Floating point values and vector values map to the same register file. 18571 // Therefore, although we could do a store extract of a vector type, this is 18572 // better to leave at float as we have more freedom in the addressing mode for 18573 // those. 18574 if (VectorTy->isFPOrFPVectorTy()) 18575 return false; 18576 18577 // If the index is unknown at compile time, this is very expensive to lower 18578 // and it is not possible to combine the store with the extract. 18579 if (!isa<ConstantInt>(Idx)) 18580 return false; 18581 18582 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 18583 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize(); 18584 // We can do a store + vector extract on any vector that fits perfectly in a D 18585 // or Q register. 18586 if (BitWidth == 64 || BitWidth == 128) { 18587 Cost = 0; 18588 return true; 18589 } 18590 return false; 18591 } 18592 18593 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 18594 return Subtarget->hasV6T2Ops(); 18595 } 18596 18597 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 18598 return Subtarget->hasV6T2Ops(); 18599 } 18600 18601 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 18602 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows(); 18603 } 18604 18605 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 18606 AtomicOrdering Ord) const { 18607 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18608 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 18609 bool IsAcquire = isAcquireOrStronger(Ord); 18610 18611 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 18612 // intrinsic must return {i32, i32} and we have to recombine them into a 18613 // single i64 here. 18614 if (ValTy->getPrimitiveSizeInBits() == 64) { 18615 Intrinsic::ID Int = 18616 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 18617 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 18618 18619 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 18620 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 18621 18622 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18623 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18624 if (!Subtarget->isLittle()) 18625 std::swap (Lo, Hi); 18626 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18627 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18628 return Builder.CreateOr( 18629 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 18630 } 18631 18632 Type *Tys[] = { Addr->getType() }; 18633 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 18634 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 18635 18636 return Builder.CreateTruncOrBitCast( 18637 Builder.CreateCall(Ldrex, Addr), 18638 cast<PointerType>(Addr->getType())->getElementType()); 18639 } 18640 18641 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 18642 IRBuilder<> &Builder) const { 18643 if (!Subtarget->hasV7Ops()) 18644 return; 18645 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18646 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 18647 } 18648 18649 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 18650 Value *Addr, 18651 AtomicOrdering Ord) const { 18652 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18653 bool IsRelease = isReleaseOrStronger(Ord); 18654 18655 // Since the intrinsics must have legal type, the i64 intrinsics take two 18656 // parameters: "i32, i32". We must marshal Val into the appropriate form 18657 // before the call. 18658 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 18659 Intrinsic::ID Int = 18660 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 18661 Function *Strex = Intrinsic::getDeclaration(M, Int); 18662 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 18663 18664 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 18665 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 18666 if (!Subtarget->isLittle()) 18667 std::swap(Lo, Hi); 18668 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 18669 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 18670 } 18671 18672 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 18673 Type *Tys[] = { Addr->getType() }; 18674 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 18675 18676 return Builder.CreateCall( 18677 Strex, {Builder.CreateZExtOrBitCast( 18678 Val, Strex->getFunctionType()->getParamType(0)), 18679 Addr}); 18680 } 18681 18682 18683 bool ARMTargetLowering::alignLoopsWithOptSize() const { 18684 return Subtarget->isMClass(); 18685 } 18686 18687 /// A helper function for determining the number of interleaved accesses we 18688 /// will generate when lowering accesses of the given type. 18689 unsigned 18690 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 18691 const DataLayout &DL) const { 18692 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 18693 } 18694 18695 bool ARMTargetLowering::isLegalInterleavedAccessType( 18696 unsigned Factor, FixedVectorType *VecTy, const DataLayout &DL) const { 18697 18698 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 18699 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 18700 18701 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) 18702 return false; 18703 18704 // Ensure the vector doesn't have f16 elements. Even though we could do an 18705 // i16 vldN, we can't hold the f16 vectors and will end up converting via 18706 // f32. 18707 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy()) 18708 return false; 18709 if (Subtarget->hasMVEIntegerOps() && Factor == 3) 18710 return false; 18711 18712 // Ensure the number of vector elements is greater than 1. 18713 if (VecTy->getNumElements() < 2) 18714 return false; 18715 18716 // Ensure the element type is legal. 18717 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 18718 return false; 18719 18720 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 18721 // 128 will be split into multiple interleaved accesses. 18722 if (Subtarget->hasNEON() && VecSize == 64) 18723 return true; 18724 return VecSize % 128 == 0; 18725 } 18726 18727 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const { 18728 if (Subtarget->hasNEON()) 18729 return 4; 18730 if (Subtarget->hasMVEIntegerOps()) 18731 return MVEMaxSupportedInterleaveFactor; 18732 return TargetLoweringBase::getMaxSupportedInterleaveFactor(); 18733 } 18734 18735 /// Lower an interleaved load into a vldN intrinsic. 18736 /// 18737 /// E.g. Lower an interleaved load (Factor = 2): 18738 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 18739 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 18740 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 18741 /// 18742 /// Into: 18743 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 18744 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 18745 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 18746 bool ARMTargetLowering::lowerInterleavedLoad( 18747 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 18748 ArrayRef<unsigned> Indices, unsigned Factor) const { 18749 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 18750 "Invalid interleave factor"); 18751 assert(!Shuffles.empty() && "Empty shufflevector input"); 18752 assert(Shuffles.size() == Indices.size() && 18753 "Unmatched number of shufflevectors and indices"); 18754 18755 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType()); 18756 Type *EltTy = VecTy->getElementType(); 18757 18758 const DataLayout &DL = LI->getModule()->getDataLayout(); 18759 18760 // Skip if we do not have NEON and skip illegal vector types. We can 18761 // "legalize" wide vector types into multiple interleaved accesses as long as 18762 // the vector types are divisible by 128. 18763 if (!isLegalInterleavedAccessType(Factor, VecTy, DL)) 18764 return false; 18765 18766 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 18767 18768 // A pointer vector can not be the return type of the ldN intrinsics. Need to 18769 // load integer vectors first and then convert to pointer vectors. 18770 if (EltTy->isPointerTy()) 18771 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy); 18772 18773 IRBuilder<> Builder(LI); 18774 18775 // The base address of the load. 18776 Value *BaseAddr = LI->getPointerOperand(); 18777 18778 if (NumLoads > 1) { 18779 // If we're going to generate more than one load, reset the sub-vector type 18780 // to something legal. 18781 VecTy = FixedVectorType::get(VecTy->getElementType(), 18782 VecTy->getNumElements() / NumLoads); 18783 18784 // We will compute the pointer operand of each load from the original base 18785 // address using GEPs. Cast the base address to a pointer to the scalar 18786 // element type. 18787 BaseAddr = Builder.CreateBitCast( 18788 BaseAddr, 18789 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 18790 } 18791 18792 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 18793 18794 auto createLoadIntrinsic = [&](Value *BaseAddr) { 18795 if (Subtarget->hasNEON()) { 18796 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 18797 Type *Tys[] = {VecTy, Int8Ptr}; 18798 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 18799 Intrinsic::arm_neon_vld3, 18800 Intrinsic::arm_neon_vld4}; 18801 Function *VldnFunc = 18802 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 18803 18804 SmallVector<Value *, 2> Ops; 18805 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 18806 Ops.push_back(Builder.getInt32(LI->getAlignment())); 18807 18808 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 18809 } else { 18810 assert((Factor == 2 || Factor == 4) && 18811 "expected interleave factor of 2 or 4 for MVE"); 18812 Intrinsic::ID LoadInts = 18813 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q; 18814 Type *VecEltTy = 18815 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()); 18816 Type *Tys[] = {VecTy, VecEltTy}; 18817 Function *VldnFunc = 18818 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys); 18819 18820 SmallVector<Value *, 2> Ops; 18821 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy)); 18822 return Builder.CreateCall(VldnFunc, Ops, "vldN"); 18823 } 18824 }; 18825 18826 // Holds sub-vectors extracted from the load intrinsic return values. The 18827 // sub-vectors are associated with the shufflevector instructions they will 18828 // replace. 18829 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 18830 18831 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 18832 // If we're generating more than one load, compute the base address of 18833 // subsequent loads as an offset from the previous. 18834 if (LoadCount > 0) 18835 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr, 18836 VecTy->getNumElements() * Factor); 18837 18838 CallInst *VldN = createLoadIntrinsic(BaseAddr); 18839 18840 // Replace uses of each shufflevector with the corresponding vector loaded 18841 // by ldN. 18842 for (unsigned i = 0; i < Shuffles.size(); i++) { 18843 ShuffleVectorInst *SV = Shuffles[i]; 18844 unsigned Index = Indices[i]; 18845 18846 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 18847 18848 // Convert the integer vector to pointer vector if the element is pointer. 18849 if (EltTy->isPointerTy()) 18850 SubVec = Builder.CreateIntToPtr( 18851 SubVec, 18852 FixedVectorType::get(SV->getType()->getElementType(), VecTy)); 18853 18854 SubVecs[SV].push_back(SubVec); 18855 } 18856 } 18857 18858 // Replace uses of the shufflevector instructions with the sub-vectors 18859 // returned by the load intrinsic. If a shufflevector instruction is 18860 // associated with more than one sub-vector, those sub-vectors will be 18861 // concatenated into a single wide vector. 18862 for (ShuffleVectorInst *SVI : Shuffles) { 18863 auto &SubVec = SubVecs[SVI]; 18864 auto *WideVec = 18865 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 18866 SVI->replaceAllUsesWith(WideVec); 18867 } 18868 18869 return true; 18870 } 18871 18872 /// Lower an interleaved store into a vstN intrinsic. 18873 /// 18874 /// E.g. Lower an interleaved store (Factor = 3): 18875 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 18876 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 18877 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 18878 /// 18879 /// Into: 18880 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 18881 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 18882 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 18883 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 18884 /// 18885 /// Note that the new shufflevectors will be removed and we'll only generate one 18886 /// vst3 instruction in CodeGen. 18887 /// 18888 /// Example for a more general valid mask (Factor 3). Lower: 18889 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 18890 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 18891 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 18892 /// 18893 /// Into: 18894 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 18895 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 18896 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 18897 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 18898 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 18899 ShuffleVectorInst *SVI, 18900 unsigned Factor) const { 18901 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 18902 "Invalid interleave factor"); 18903 18904 auto *VecTy = cast<FixedVectorType>(SVI->getType()); 18905 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 18906 18907 unsigned LaneLen = VecTy->getNumElements() / Factor; 18908 Type *EltTy = VecTy->getElementType(); 18909 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen); 18910 18911 const DataLayout &DL = SI->getModule()->getDataLayout(); 18912 18913 // Skip if we do not have NEON and skip illegal vector types. We can 18914 // "legalize" wide vector types into multiple interleaved accesses as long as 18915 // the vector types are divisible by 128. 18916 if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL)) 18917 return false; 18918 18919 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 18920 18921 Value *Op0 = SVI->getOperand(0); 18922 Value *Op1 = SVI->getOperand(1); 18923 IRBuilder<> Builder(SI); 18924 18925 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 18926 // vectors to integer vectors. 18927 if (EltTy->isPointerTy()) { 18928 Type *IntTy = DL.getIntPtrType(EltTy); 18929 18930 // Convert to the corresponding integer vector. 18931 auto *IntVecTy = 18932 FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType())); 18933 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 18934 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 18935 18936 SubVecTy = FixedVectorType::get(IntTy, LaneLen); 18937 } 18938 18939 // The base address of the store. 18940 Value *BaseAddr = SI->getPointerOperand(); 18941 18942 if (NumStores > 1) { 18943 // If we're going to generate more than one store, reset the lane length 18944 // and sub-vector type to something legal. 18945 LaneLen /= NumStores; 18946 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen); 18947 18948 // We will compute the pointer operand of each store from the original base 18949 // address using GEPs. Cast the base address to a pointer to the scalar 18950 // element type. 18951 BaseAddr = Builder.CreateBitCast( 18952 BaseAddr, 18953 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 18954 } 18955 18956 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 18957 18958 auto Mask = SVI->getShuffleMask(); 18959 18960 auto createStoreIntrinsic = [&](Value *BaseAddr, 18961 SmallVectorImpl<Value *> &Shuffles) { 18962 if (Subtarget->hasNEON()) { 18963 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 18964 Intrinsic::arm_neon_vst3, 18965 Intrinsic::arm_neon_vst4}; 18966 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 18967 Type *Tys[] = {Int8Ptr, SubVecTy}; 18968 18969 Function *VstNFunc = Intrinsic::getDeclaration( 18970 SI->getModule(), StoreInts[Factor - 2], Tys); 18971 18972 SmallVector<Value *, 6> Ops; 18973 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 18974 for (auto S : Shuffles) 18975 Ops.push_back(S); 18976 Ops.push_back(Builder.getInt32(SI->getAlignment())); 18977 Builder.CreateCall(VstNFunc, Ops); 18978 } else { 18979 assert((Factor == 2 || Factor == 4) && 18980 "expected interleave factor of 2 or 4 for MVE"); 18981 Intrinsic::ID StoreInts = 18982 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q; 18983 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo( 18984 SI->getPointerAddressSpace()); 18985 Type *Tys[] = {EltPtrTy, SubVecTy}; 18986 Function *VstNFunc = 18987 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys); 18988 18989 SmallVector<Value *, 6> Ops; 18990 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy)); 18991 for (auto S : Shuffles) 18992 Ops.push_back(S); 18993 for (unsigned F = 0; F < Factor; F++) { 18994 Ops.push_back(Builder.getInt32(F)); 18995 Builder.CreateCall(VstNFunc, Ops); 18996 Ops.pop_back(); 18997 } 18998 } 18999 }; 19000 19001 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 19002 // If we generating more than one store, we compute the base address of 19003 // subsequent stores as an offset from the previous. 19004 if (StoreCount > 0) 19005 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 19006 BaseAddr, LaneLen * Factor); 19007 19008 SmallVector<Value *, 4> Shuffles; 19009 19010 // Split the shufflevector operands into sub vectors for the new vstN call. 19011 for (unsigned i = 0; i < Factor; i++) { 19012 unsigned IdxI = StoreCount * LaneLen * Factor + i; 19013 if (Mask[IdxI] >= 0) { 19014 Shuffles.push_back(Builder.CreateShuffleVector( 19015 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0))); 19016 } else { 19017 unsigned StartMask = 0; 19018 for (unsigned j = 1; j < LaneLen; j++) { 19019 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 19020 if (Mask[IdxJ * Factor + IdxI] >= 0) { 19021 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 19022 break; 19023 } 19024 } 19025 // Note: If all elements in a chunk are undefs, StartMask=0! 19026 // Note: Filling undef gaps with random elements is ok, since 19027 // those elements were being written anyway (with undefs). 19028 // In the case of all undefs we're defaulting to using elems from 0 19029 // Note: StartMask cannot be negative, it's checked in 19030 // isReInterleaveMask 19031 Shuffles.push_back(Builder.CreateShuffleVector( 19032 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0))); 19033 } 19034 } 19035 19036 createStoreIntrinsic(BaseAddr, Shuffles); 19037 } 19038 return true; 19039 } 19040 19041 enum HABaseType { 19042 HA_UNKNOWN = 0, 19043 HA_FLOAT, 19044 HA_DOUBLE, 19045 HA_VECT64, 19046 HA_VECT128 19047 }; 19048 19049 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 19050 uint64_t &Members) { 19051 if (auto *ST = dyn_cast<StructType>(Ty)) { 19052 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 19053 uint64_t SubMembers = 0; 19054 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 19055 return false; 19056 Members += SubMembers; 19057 } 19058 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 19059 uint64_t SubMembers = 0; 19060 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 19061 return false; 19062 Members += SubMembers * AT->getNumElements(); 19063 } else if (Ty->isFloatTy()) { 19064 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 19065 return false; 19066 Members = 1; 19067 Base = HA_FLOAT; 19068 } else if (Ty->isDoubleTy()) { 19069 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 19070 return false; 19071 Members = 1; 19072 Base = HA_DOUBLE; 19073 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 19074 Members = 1; 19075 switch (Base) { 19076 case HA_FLOAT: 19077 case HA_DOUBLE: 19078 return false; 19079 case HA_VECT64: 19080 return VT->getPrimitiveSizeInBits().getFixedSize() == 64; 19081 case HA_VECT128: 19082 return VT->getPrimitiveSizeInBits().getFixedSize() == 128; 19083 case HA_UNKNOWN: 19084 switch (VT->getPrimitiveSizeInBits().getFixedSize()) { 19085 case 64: 19086 Base = HA_VECT64; 19087 return true; 19088 case 128: 19089 Base = HA_VECT128; 19090 return true; 19091 default: 19092 return false; 19093 } 19094 } 19095 } 19096 19097 return (Members > 0 && Members <= 4); 19098 } 19099 19100 /// Return the correct alignment for the current calling convention. 19101 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 19102 DataLayout DL) const { 19103 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy); 19104 if (!ArgTy->isVectorTy()) 19105 return ABITypeAlign; 19106 19107 // Avoid over-aligning vector parameters. It would require realigning the 19108 // stack and waste space for no real benefit. 19109 return std::min(ABITypeAlign, DL.getStackAlignment()); 19110 } 19111 19112 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 19113 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 19114 /// passing according to AAPCS rules. 19115 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 19116 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 19117 if (getEffectiveCallingConv(CallConv, isVarArg) != 19118 CallingConv::ARM_AAPCS_VFP) 19119 return false; 19120 19121 HABaseType Base = HA_UNKNOWN; 19122 uint64_t Members = 0; 19123 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 19124 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 19125 19126 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 19127 return IsHA || IsIntArray; 19128 } 19129 19130 Register ARMTargetLowering::getExceptionPointerRegister( 19131 const Constant *PersonalityFn) const { 19132 // Platforms which do not use SjLj EH may return values in these registers 19133 // via the personality function. 19134 return Subtarget->useSjLjEH() ? Register() : ARM::R0; 19135 } 19136 19137 Register ARMTargetLowering::getExceptionSelectorRegister( 19138 const Constant *PersonalityFn) const { 19139 // Platforms which do not use SjLj EH may return values in these registers 19140 // via the personality function. 19141 return Subtarget->useSjLjEH() ? Register() : ARM::R1; 19142 } 19143 19144 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 19145 // Update IsSplitCSR in ARMFunctionInfo. 19146 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 19147 AFI->setIsSplitCSR(true); 19148 } 19149 19150 void ARMTargetLowering::insertCopiesSplitCSR( 19151 MachineBasicBlock *Entry, 19152 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 19153 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 19154 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 19155 if (!IStart) 19156 return; 19157 19158 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 19159 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 19160 MachineBasicBlock::iterator MBBI = Entry->begin(); 19161 for (const MCPhysReg *I = IStart; *I; ++I) { 19162 const TargetRegisterClass *RC = nullptr; 19163 if (ARM::GPRRegClass.contains(*I)) 19164 RC = &ARM::GPRRegClass; 19165 else if (ARM::DPRRegClass.contains(*I)) 19166 RC = &ARM::DPRRegClass; 19167 else 19168 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 19169 19170 Register NewVR = MRI->createVirtualRegister(RC); 19171 // Create copy from CSR to a virtual register. 19172 // FIXME: this currently does not emit CFI pseudo-instructions, it works 19173 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 19174 // nounwind. If we want to generalize this later, we may need to emit 19175 // CFI pseudo-instructions. 19176 assert(Entry->getParent()->getFunction().hasFnAttribute( 19177 Attribute::NoUnwind) && 19178 "Function should be nounwind in insertCopiesSplitCSR!"); 19179 Entry->addLiveIn(*I); 19180 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 19181 .addReg(*I); 19182 19183 // Insert the copy-back instructions right before the terminator. 19184 for (auto *Exit : Exits) 19185 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 19186 TII->get(TargetOpcode::COPY), *I) 19187 .addReg(NewVR); 19188 } 19189 } 19190 19191 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 19192 MF.getFrameInfo().computeMaxCallFrameSize(MF); 19193 TargetLoweringBase::finalizeLowering(MF); 19194 } 19195