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/Module.h" 82 #include "llvm/IR/PatternMatch.h" 83 #include "llvm/IR/Type.h" 84 #include "llvm/IR/User.h" 85 #include "llvm/IR/Value.h" 86 #include "llvm/MC/MCInstrDesc.h" 87 #include "llvm/MC/MCInstrItineraries.h" 88 #include "llvm/MC/MCRegisterInfo.h" 89 #include "llvm/MC/MCSchedule.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/BranchProbability.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CodeGen.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/ErrorHandling.h" 98 #include "llvm/Support/KnownBits.h" 99 #include "llvm/Support/MachineValueType.h" 100 #include "llvm/Support/MathExtras.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include <algorithm> 105 #include <cassert> 106 #include <cstdint> 107 #include <cstdlib> 108 #include <iterator> 109 #include <limits> 110 #include <string> 111 #include <tuple> 112 #include <utility> 113 #include <vector> 114 115 using namespace llvm; 116 using namespace llvm::PatternMatch; 117 118 #define DEBUG_TYPE "arm-isel" 119 120 STATISTIC(NumTailCalls, "Number of tail calls"); 121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 123 STATISTIC(NumConstpoolPromoted, 124 "Number of constants with their storage promoted into constant pools"); 125 126 static cl::opt<bool> 127 ARMInterworking("arm-interworking", cl::Hidden, 128 cl::desc("Enable / disable ARM interworking (for debugging only)"), 129 cl::init(true)); 130 131 static cl::opt<bool> EnableConstpoolPromotion( 132 "arm-promote-constant", cl::Hidden, 133 cl::desc("Enable / disable promotion of unnamed_addr constants into " 134 "constant pools"), 135 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 136 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 137 "arm-promote-constant-max-size", cl::Hidden, 138 cl::desc("Maximum size of constant to promote into a constant pool"), 139 cl::init(64)); 140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 141 "arm-promote-constant-max-total", cl::Hidden, 142 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 143 cl::init(128)); 144 145 // The APCS parameter registers. 146 static const MCPhysReg GPRArgRegs[] = { 147 ARM::R0, ARM::R1, ARM::R2, ARM::R3 148 }; 149 150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 151 MVT PromotedBitwiseVT) { 152 if (VT != PromotedLdStVT) { 153 setOperationAction(ISD::LOAD, VT, Promote); 154 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 155 156 setOperationAction(ISD::STORE, VT, Promote); 157 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 158 } 159 160 MVT ElemTy = VT.getVectorElementType(); 161 if (ElemTy != MVT::f64) 162 setOperationAction(ISD::SETCC, VT, Custom); 163 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 164 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 165 if (ElemTy == MVT::i32) { 166 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 167 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 168 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 169 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 170 } else { 171 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 172 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 173 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 174 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 175 } 176 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 177 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 178 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 179 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 180 setOperationAction(ISD::SELECT, VT, Expand); 181 setOperationAction(ISD::SELECT_CC, VT, Expand); 182 setOperationAction(ISD::VSELECT, VT, Expand); 183 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 184 if (VT.isInteger()) { 185 setOperationAction(ISD::SHL, VT, Custom); 186 setOperationAction(ISD::SRA, VT, Custom); 187 setOperationAction(ISD::SRL, VT, Custom); 188 } 189 190 // Promote all bit-wise operations. 191 if (VT.isInteger() && VT != PromotedBitwiseVT) { 192 setOperationAction(ISD::AND, VT, Promote); 193 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 194 setOperationAction(ISD::OR, VT, Promote); 195 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 196 setOperationAction(ISD::XOR, VT, Promote); 197 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 198 } 199 200 // Neon does not support vector divide/remainder operations. 201 setOperationAction(ISD::SDIV, VT, Expand); 202 setOperationAction(ISD::UDIV, VT, Expand); 203 setOperationAction(ISD::FDIV, VT, Expand); 204 setOperationAction(ISD::SREM, VT, Expand); 205 setOperationAction(ISD::UREM, VT, Expand); 206 setOperationAction(ISD::FREM, VT, Expand); 207 208 if (!VT.isFloatingPoint() && 209 VT != MVT::v2i64 && VT != MVT::v1i64) 210 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 211 setOperationAction(Opcode, VT, Legal); 212 } 213 214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 215 addRegisterClass(VT, &ARM::DPRRegClass); 216 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 217 } 218 219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 220 addRegisterClass(VT, &ARM::DPairRegClass); 221 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 222 } 223 224 void ARMTargetLowering::setAllExpand(MVT VT) { 225 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc) 226 setOperationAction(Opc, VT, Expand); 227 228 // We support these really simple operations even on types where all 229 // the actual arithmetic has to be broken down into simpler 230 // operations or turned into library calls. 231 setOperationAction(ISD::BITCAST, VT, Legal); 232 setOperationAction(ISD::LOAD, VT, Legal); 233 setOperationAction(ISD::STORE, VT, Legal); 234 setOperationAction(ISD::UNDEF, VT, Legal); 235 } 236 237 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To, 238 LegalizeAction Action) { 239 setLoadExtAction(ISD::EXTLOAD, From, To, Action); 240 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action); 241 setLoadExtAction(ISD::SEXTLOAD, From, To, Action); 242 } 243 244 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) { 245 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 }; 246 247 for (auto VT : IntTypes) { 248 addRegisterClass(VT, &ARM::QPRRegClass); 249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 250 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 251 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 252 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 253 setOperationAction(ISD::SHL, VT, Custom); 254 setOperationAction(ISD::SRA, VT, Custom); 255 setOperationAction(ISD::SRL, VT, Custom); 256 setOperationAction(ISD::SMIN, VT, Legal); 257 setOperationAction(ISD::SMAX, VT, Legal); 258 setOperationAction(ISD::UMIN, VT, Legal); 259 setOperationAction(ISD::UMAX, VT, Legal); 260 setOperationAction(ISD::ABS, VT, Legal); 261 setOperationAction(ISD::SETCC, VT, Custom); 262 263 // No native support for these. 264 setOperationAction(ISD::UDIV, VT, Expand); 265 setOperationAction(ISD::SDIV, VT, Expand); 266 setOperationAction(ISD::UREM, VT, Expand); 267 setOperationAction(ISD::SREM, VT, Expand); 268 setOperationAction(ISD::CTPOP, VT, Expand); 269 270 // Vector reductions 271 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal); 272 273 if (!HasMVEFP) { 274 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 275 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 276 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 277 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 278 } 279 280 // Pre and Post inc are supported on loads and stores 281 for (unsigned im = (unsigned)ISD::PRE_INC; 282 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 283 setIndexedLoadAction(im, VT, Legal); 284 setIndexedStoreAction(im, VT, Legal); 285 } 286 } 287 288 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 289 for (auto VT : FloatTypes) { 290 addRegisterClass(VT, &ARM::QPRRegClass); 291 if (!HasMVEFP) 292 setAllExpand(VT); 293 294 // These are legal or custom whether we have MVE.fp or not 295 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 296 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 297 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 298 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 299 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 300 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 301 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 302 setOperationAction(ISD::SETCC, VT, Custom); 303 304 // Pre and Post inc are supported on loads and stores 305 for (unsigned im = (unsigned)ISD::PRE_INC; 306 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 307 setIndexedLoadAction(im, VT, Legal); 308 setIndexedStoreAction(im, VT, Legal); 309 } 310 311 if (HasMVEFP) { 312 setOperationAction(ISD::FMINNUM, VT, Legal); 313 setOperationAction(ISD::FMAXNUM, VT, Legal); 314 setOperationAction(ISD::FROUND, VT, Legal); 315 316 // No native support for these. 317 setOperationAction(ISD::FDIV, VT, Expand); 318 setOperationAction(ISD::FREM, VT, Expand); 319 setOperationAction(ISD::FSQRT, VT, Expand); 320 setOperationAction(ISD::FSIN, VT, Expand); 321 setOperationAction(ISD::FCOS, VT, Expand); 322 setOperationAction(ISD::FPOW, VT, Expand); 323 setOperationAction(ISD::FLOG, VT, Expand); 324 setOperationAction(ISD::FLOG2, VT, Expand); 325 setOperationAction(ISD::FLOG10, VT, Expand); 326 setOperationAction(ISD::FEXP, VT, Expand); 327 setOperationAction(ISD::FEXP2, VT, Expand); 328 setOperationAction(ISD::FNEARBYINT, VT, Expand); 329 } 330 } 331 332 // We 'support' these types up to bitcast/load/store level, regardless of 333 // MVE integer-only / float support. Only doing FP data processing on the FP 334 // vector types is inhibited at integer-only level. 335 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 336 for (auto VT : LongTypes) { 337 addRegisterClass(VT, &ARM::QPRRegClass); 338 setAllExpand(VT); 339 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 340 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 341 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 342 } 343 // We can do bitwise operations on v2i64 vectors 344 setOperationAction(ISD::AND, MVT::v2i64, Legal); 345 setOperationAction(ISD::OR, MVT::v2i64, Legal); 346 setOperationAction(ISD::XOR, MVT::v2i64, Legal); 347 348 // It is legal to extload from v4i8 to v4i16 or v4i32. 349 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 350 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 351 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 352 353 // Some truncating stores are legal too. 354 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 355 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 356 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 357 358 // Pre and Post inc on these are legal, given the correct extends 359 for (unsigned im = (unsigned)ISD::PRE_INC; 360 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 361 setIndexedLoadAction(im, MVT::v8i8, Legal); 362 setIndexedStoreAction(im, MVT::v8i8, Legal); 363 setIndexedLoadAction(im, MVT::v4i8, Legal); 364 setIndexedStoreAction(im, MVT::v4i8, Legal); 365 setIndexedLoadAction(im, MVT::v4i16, Legal); 366 setIndexedStoreAction(im, MVT::v4i16, Legal); 367 } 368 369 // Predicate types 370 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1}; 371 for (auto VT : pTypes) { 372 addRegisterClass(VT, &ARM::VCCRRegClass); 373 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 374 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 375 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 376 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 377 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 378 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 379 setOperationAction(ISD::SETCC, VT, Custom); 380 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 381 } 382 } 383 384 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 385 const ARMSubtarget &STI) 386 : TargetLowering(TM), Subtarget(&STI) { 387 RegInfo = Subtarget->getRegisterInfo(); 388 Itins = Subtarget->getInstrItineraryData(); 389 390 setBooleanContents(ZeroOrOneBooleanContent); 391 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 392 393 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 394 !Subtarget->isTargetWatchOS()) { 395 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 396 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 397 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 398 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 399 : CallingConv::ARM_AAPCS); 400 } 401 402 if (Subtarget->isTargetMachO()) { 403 // Uses VFP for Thumb libfuncs if available. 404 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 405 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 406 static const struct { 407 const RTLIB::Libcall Op; 408 const char * const Name; 409 const ISD::CondCode Cond; 410 } LibraryCalls[] = { 411 // Single-precision floating-point arithmetic. 412 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 413 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 414 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 415 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 416 417 // Double-precision floating-point arithmetic. 418 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 419 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 420 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 421 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 422 423 // Single-precision comparisons. 424 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 425 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 426 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 427 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 428 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 429 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 430 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 431 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 432 433 // Double-precision comparisons. 434 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 435 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 436 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 437 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 438 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 439 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 440 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 441 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 442 443 // Floating-point to integer conversions. 444 // i64 conversions are done via library routines even when generating VFP 445 // instructions, so use the same ones. 446 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 447 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 448 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 449 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 450 451 // Conversions between floating types. 452 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 453 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 454 455 // Integer to floating-point conversions. 456 // i64 conversions are done via library routines even when generating VFP 457 // instructions, so use the same ones. 458 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 459 // e.g., __floatunsidf vs. __floatunssidfvfp. 460 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 461 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 462 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 463 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 464 }; 465 466 for (const auto &LC : LibraryCalls) { 467 setLibcallName(LC.Op, LC.Name); 468 if (LC.Cond != ISD::SETCC_INVALID) 469 setCmpLibcallCC(LC.Op, LC.Cond); 470 } 471 } 472 } 473 474 // These libcalls are not available in 32-bit. 475 setLibcallName(RTLIB::SHL_I128, nullptr); 476 setLibcallName(RTLIB::SRL_I128, nullptr); 477 setLibcallName(RTLIB::SRA_I128, nullptr); 478 479 // RTLIB 480 if (Subtarget->isAAPCS_ABI() && 481 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 482 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 483 static const struct { 484 const RTLIB::Libcall Op; 485 const char * const Name; 486 const CallingConv::ID CC; 487 const ISD::CondCode Cond; 488 } LibraryCalls[] = { 489 // Double-precision floating-point arithmetic helper functions 490 // RTABI chapter 4.1.2, Table 2 491 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 492 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 493 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 494 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 495 496 // Double-precision floating-point comparison helper functions 497 // RTABI chapter 4.1.2, Table 3 498 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 499 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 500 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 501 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 502 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 503 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 504 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 505 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 506 507 // Single-precision floating-point arithmetic helper functions 508 // RTABI chapter 4.1.2, Table 4 509 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 510 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 511 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 512 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 513 514 // Single-precision floating-point comparison helper functions 515 // RTABI chapter 4.1.2, Table 5 516 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 517 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 518 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 519 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 520 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 521 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 522 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 523 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 524 525 // Floating-point to integer conversions. 526 // RTABI chapter 4.1.2, Table 6 527 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 528 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 529 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 530 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 531 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 532 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 533 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 534 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 535 536 // Conversions between floating types. 537 // RTABI chapter 4.1.2, Table 7 538 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 539 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 540 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 541 542 // Integer to floating-point conversions. 543 // RTABI chapter 4.1.2, Table 8 544 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 545 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 546 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 547 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 548 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 549 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 550 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 551 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 552 553 // Long long helper functions 554 // RTABI chapter 4.2, Table 9 555 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 556 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 557 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 558 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 559 560 // Integer division functions 561 // RTABI chapter 4.3.1 562 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 563 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 564 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 565 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 566 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 567 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 568 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 569 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 570 }; 571 572 for (const auto &LC : LibraryCalls) { 573 setLibcallName(LC.Op, LC.Name); 574 setLibcallCallingConv(LC.Op, LC.CC); 575 if (LC.Cond != ISD::SETCC_INVALID) 576 setCmpLibcallCC(LC.Op, LC.Cond); 577 } 578 579 // EABI dependent RTLIB 580 if (TM.Options.EABIVersion == EABI::EABI4 || 581 TM.Options.EABIVersion == EABI::EABI5) { 582 static const struct { 583 const RTLIB::Libcall Op; 584 const char *const Name; 585 const CallingConv::ID CC; 586 const ISD::CondCode Cond; 587 } MemOpsLibraryCalls[] = { 588 // Memory operations 589 // RTABI chapter 4.3.4 590 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 591 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 592 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 593 }; 594 595 for (const auto &LC : MemOpsLibraryCalls) { 596 setLibcallName(LC.Op, LC.Name); 597 setLibcallCallingConv(LC.Op, LC.CC); 598 if (LC.Cond != ISD::SETCC_INVALID) 599 setCmpLibcallCC(LC.Op, LC.Cond); 600 } 601 } 602 } 603 604 if (Subtarget->isTargetWindows()) { 605 static const struct { 606 const RTLIB::Libcall Op; 607 const char * const Name; 608 const CallingConv::ID CC; 609 } LibraryCalls[] = { 610 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 611 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 612 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 613 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 614 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 615 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 616 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 617 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 618 }; 619 620 for (const auto &LC : LibraryCalls) { 621 setLibcallName(LC.Op, LC.Name); 622 setLibcallCallingConv(LC.Op, LC.CC); 623 } 624 } 625 626 // Use divmod compiler-rt calls for iOS 5.0 and later. 627 if (Subtarget->isTargetMachO() && 628 !(Subtarget->isTargetIOS() && 629 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 630 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 631 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 632 } 633 634 // The half <-> float conversion functions are always soft-float on 635 // non-watchos platforms, but are needed for some targets which use a 636 // hard-float calling convention by default. 637 if (!Subtarget->isTargetWatchABI()) { 638 if (Subtarget->isAAPCS_ABI()) { 639 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 640 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 641 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 642 } else { 643 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 644 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 645 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 646 } 647 } 648 649 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 650 // a __gnu_ prefix (which is the default). 651 if (Subtarget->isTargetAEABI()) { 652 static const struct { 653 const RTLIB::Libcall Op; 654 const char * const Name; 655 const CallingConv::ID CC; 656 } LibraryCalls[] = { 657 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 658 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 659 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 660 }; 661 662 for (const auto &LC : LibraryCalls) { 663 setLibcallName(LC.Op, LC.Name); 664 setLibcallCallingConv(LC.Op, LC.CC); 665 } 666 } 667 668 if (Subtarget->isThumb1Only()) 669 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 670 else 671 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 672 673 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 674 Subtarget->hasFPRegs()) { 675 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 676 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 677 if (!Subtarget->hasVFP2Base()) 678 setAllExpand(MVT::f32); 679 if (!Subtarget->hasFP64()) 680 setAllExpand(MVT::f64); 681 } 682 683 if (Subtarget->hasFullFP16()) { 684 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 685 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 686 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 687 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 688 689 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 690 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 691 } 692 693 for (MVT VT : MVT::vector_valuetypes()) { 694 for (MVT InnerVT : MVT::vector_valuetypes()) { 695 setTruncStoreAction(VT, InnerVT, Expand); 696 addAllExtLoads(VT, InnerVT, Expand); 697 } 698 699 setOperationAction(ISD::MULHS, VT, Expand); 700 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 701 setOperationAction(ISD::MULHU, VT, Expand); 702 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 703 704 setOperationAction(ISD::BSWAP, VT, Expand); 705 } 706 707 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 708 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 709 710 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 711 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 712 713 if (Subtarget->hasMVEIntegerOps()) 714 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 715 716 // Combine low-overhead loop intrinsics so that we can lower i1 types. 717 if (Subtarget->hasLOB()) { 718 setTargetDAGCombine(ISD::BRCOND); 719 setTargetDAGCombine(ISD::BR_CC); 720 } 721 722 if (Subtarget->hasNEON()) { 723 addDRTypeForNEON(MVT::v2f32); 724 addDRTypeForNEON(MVT::v8i8); 725 addDRTypeForNEON(MVT::v4i16); 726 addDRTypeForNEON(MVT::v2i32); 727 addDRTypeForNEON(MVT::v1i64); 728 729 addQRTypeForNEON(MVT::v4f32); 730 addQRTypeForNEON(MVT::v2f64); 731 addQRTypeForNEON(MVT::v16i8); 732 addQRTypeForNEON(MVT::v8i16); 733 addQRTypeForNEON(MVT::v4i32); 734 addQRTypeForNEON(MVT::v2i64); 735 736 if (Subtarget->hasFullFP16()) { 737 addQRTypeForNEON(MVT::v8f16); 738 addDRTypeForNEON(MVT::v4f16); 739 } 740 } 741 742 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 743 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 744 // none of Neon, MVE or VFP supports any arithmetic operations on it. 745 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 746 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 747 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 748 // FIXME: Code duplication: FDIV and FREM are expanded always, see 749 // ARMTargetLowering::addTypeForNEON method for details. 750 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 751 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 752 // FIXME: Create unittest. 753 // In another words, find a way when "copysign" appears in DAG with vector 754 // operands. 755 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 756 // FIXME: Code duplication: SETCC has custom operation action, see 757 // ARMTargetLowering::addTypeForNEON method for details. 758 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 759 // FIXME: Create unittest for FNEG and for FABS. 760 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 761 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 762 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 763 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 764 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 765 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 766 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 767 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 768 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 769 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 770 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 771 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 772 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 773 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 774 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 775 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 776 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 777 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 778 } 779 780 if (Subtarget->hasNEON()) { 781 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 782 // supported for v4f32. 783 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 784 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 785 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 786 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 787 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 788 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 789 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 790 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 791 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 792 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 793 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 794 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 795 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 796 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 797 798 // Mark v2f32 intrinsics. 799 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 800 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 801 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 802 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 803 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 804 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 805 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 806 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 807 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 808 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 809 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 810 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 811 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 812 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 813 814 // Neon does not support some operations on v1i64 and v2i64 types. 815 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 816 // Custom handling for some quad-vector types to detect VMULL. 817 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 818 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 819 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 820 // Custom handling for some vector types to avoid expensive expansions 821 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 822 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 823 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 824 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 825 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 826 // a destination type that is wider than the source, and nor does 827 // it have a FP_TO_[SU]INT instruction with a narrower destination than 828 // source. 829 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 830 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 831 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 832 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 833 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 834 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 835 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 836 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 837 838 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 839 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 840 841 // NEON does not have single instruction CTPOP for vectors with element 842 // types wider than 8-bits. However, custom lowering can leverage the 843 // v8i8/v16i8 vcnt instruction. 844 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 845 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 846 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 847 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 848 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 849 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 850 851 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 852 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 853 854 // NEON does not have single instruction CTTZ for vectors. 855 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 856 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 857 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 858 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 859 860 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 861 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 862 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 863 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 864 865 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 866 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 867 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 868 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 869 870 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 871 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 872 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 874 875 // NEON only has FMA instructions as of VFP4. 876 if (!Subtarget->hasVFP4Base()) { 877 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 878 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 879 } 880 881 setTargetDAGCombine(ISD::INTRINSIC_VOID); 882 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 883 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 884 setTargetDAGCombine(ISD::SHL); 885 setTargetDAGCombine(ISD::SRL); 886 setTargetDAGCombine(ISD::SRA); 887 setTargetDAGCombine(ISD::SIGN_EXTEND); 888 setTargetDAGCombine(ISD::ZERO_EXTEND); 889 setTargetDAGCombine(ISD::ANY_EXTEND); 890 setTargetDAGCombine(ISD::STORE); 891 setTargetDAGCombine(ISD::FP_TO_SINT); 892 setTargetDAGCombine(ISD::FP_TO_UINT); 893 setTargetDAGCombine(ISD::FDIV); 894 setTargetDAGCombine(ISD::LOAD); 895 896 // It is legal to extload from v4i8 to v4i16 or v4i32. 897 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 898 MVT::v2i32}) { 899 for (MVT VT : MVT::integer_vector_valuetypes()) { 900 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 901 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 902 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 903 } 904 } 905 } 906 907 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 908 setTargetDAGCombine(ISD::BUILD_VECTOR); 909 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 910 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 911 } 912 913 if (!Subtarget->hasFP64()) { 914 // When targeting a floating-point unit with only single-precision 915 // operations, f64 is legal for the few double-precision instructions which 916 // are present However, no double-precision operations other than moves, 917 // loads and stores are provided by the hardware. 918 setOperationAction(ISD::FADD, MVT::f64, Expand); 919 setOperationAction(ISD::FSUB, MVT::f64, Expand); 920 setOperationAction(ISD::FMUL, MVT::f64, Expand); 921 setOperationAction(ISD::FMA, MVT::f64, Expand); 922 setOperationAction(ISD::FDIV, MVT::f64, Expand); 923 setOperationAction(ISD::FREM, MVT::f64, Expand); 924 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 925 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 926 setOperationAction(ISD::FNEG, MVT::f64, Expand); 927 setOperationAction(ISD::FABS, MVT::f64, Expand); 928 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 929 setOperationAction(ISD::FSIN, MVT::f64, Expand); 930 setOperationAction(ISD::FCOS, MVT::f64, Expand); 931 setOperationAction(ISD::FPOW, MVT::f64, Expand); 932 setOperationAction(ISD::FLOG, MVT::f64, Expand); 933 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 934 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 935 setOperationAction(ISD::FEXP, MVT::f64, Expand); 936 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 937 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 938 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 939 setOperationAction(ISD::FRINT, MVT::f64, Expand); 940 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 941 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 942 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 943 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 944 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 945 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 946 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 947 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 948 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 949 } 950 951 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 952 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 953 if (Subtarget->hasFullFP16()) 954 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 955 } 956 957 if (!Subtarget->hasFP16()) 958 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 959 960 if (!Subtarget->hasFP64()) 961 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 962 963 computeRegisterProperties(Subtarget->getRegisterInfo()); 964 965 // ARM does not have floating-point extending loads. 966 for (MVT VT : MVT::fp_valuetypes()) { 967 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 968 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 969 } 970 971 // ... or truncating stores 972 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 973 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 974 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 975 976 // ARM does not have i1 sign extending load. 977 for (MVT VT : MVT::integer_valuetypes()) 978 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 979 980 // ARM supports all 4 flavors of integer indexed load / store. 981 if (!Subtarget->isThumb1Only()) { 982 for (unsigned im = (unsigned)ISD::PRE_INC; 983 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 984 setIndexedLoadAction(im, MVT::i1, Legal); 985 setIndexedLoadAction(im, MVT::i8, Legal); 986 setIndexedLoadAction(im, MVT::i16, Legal); 987 setIndexedLoadAction(im, MVT::i32, Legal); 988 setIndexedStoreAction(im, MVT::i1, Legal); 989 setIndexedStoreAction(im, MVT::i8, Legal); 990 setIndexedStoreAction(im, MVT::i16, Legal); 991 setIndexedStoreAction(im, MVT::i32, Legal); 992 } 993 } else { 994 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 995 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 996 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 997 } 998 999 setOperationAction(ISD::SADDO, MVT::i32, Custom); 1000 setOperationAction(ISD::UADDO, MVT::i32, Custom); 1001 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 1002 setOperationAction(ISD::USUBO, MVT::i32, Custom); 1003 1004 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 1005 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 1006 1007 // i64 operation support. 1008 setOperationAction(ISD::MUL, MVT::i64, Expand); 1009 setOperationAction(ISD::MULHU, MVT::i32, Expand); 1010 if (Subtarget->isThumb1Only()) { 1011 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 1012 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 1013 } 1014 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 1015 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 1016 setOperationAction(ISD::MULHS, MVT::i32, Expand); 1017 1018 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 1019 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 1020 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 1021 setOperationAction(ISD::SRL, MVT::i64, Custom); 1022 setOperationAction(ISD::SRA, MVT::i64, Custom); 1023 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 1024 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 1025 1026 // MVE lowers 64 bit shifts to lsll and lsrl 1027 // assuming that ISD::SRL and SRA of i64 are already marked custom 1028 if (Subtarget->hasMVEIntegerOps()) 1029 setOperationAction(ISD::SHL, MVT::i64, Custom); 1030 1031 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1032 if (Subtarget->isThumb1Only()) { 1033 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1034 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1035 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1036 } 1037 1038 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1039 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1040 1041 // ARM does not have ROTL. 1042 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1043 for (MVT VT : MVT::vector_valuetypes()) { 1044 setOperationAction(ISD::ROTL, VT, Expand); 1045 setOperationAction(ISD::ROTR, VT, Expand); 1046 } 1047 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1048 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1049 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1050 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1051 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1052 } 1053 1054 // @llvm.readcyclecounter requires the Performance Monitors extension. 1055 // Default to the 0 expansion on unsupported platforms. 1056 // FIXME: Technically there are older ARM CPUs that have 1057 // implementation-specific ways of obtaining this information. 1058 if (Subtarget->hasPerfMon()) 1059 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1060 1061 // Only ARMv6 has BSWAP. 1062 if (!Subtarget->hasV6Ops()) 1063 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1064 1065 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1066 : Subtarget->hasDivideInARMMode(); 1067 if (!hasDivide) { 1068 // These are expanded into libcalls if the cpu doesn't have HW divider. 1069 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1070 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1071 } 1072 1073 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1074 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1075 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1076 1077 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1078 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1079 } 1080 1081 setOperationAction(ISD::SREM, MVT::i32, Expand); 1082 setOperationAction(ISD::UREM, MVT::i32, Expand); 1083 1084 // Register based DivRem for AEABI (RTABI 4.2) 1085 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1086 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1087 Subtarget->isTargetWindows()) { 1088 setOperationAction(ISD::SREM, MVT::i64, Custom); 1089 setOperationAction(ISD::UREM, MVT::i64, Custom); 1090 HasStandaloneRem = false; 1091 1092 if (Subtarget->isTargetWindows()) { 1093 const struct { 1094 const RTLIB::Libcall Op; 1095 const char * const Name; 1096 const CallingConv::ID CC; 1097 } LibraryCalls[] = { 1098 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1099 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1100 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1101 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1102 1103 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1104 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1105 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1106 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1107 }; 1108 1109 for (const auto &LC : LibraryCalls) { 1110 setLibcallName(LC.Op, LC.Name); 1111 setLibcallCallingConv(LC.Op, LC.CC); 1112 } 1113 } else { 1114 const struct { 1115 const RTLIB::Libcall Op; 1116 const char * const Name; 1117 const CallingConv::ID CC; 1118 } LibraryCalls[] = { 1119 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1120 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1121 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1122 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1123 1124 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1125 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1126 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1127 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1128 }; 1129 1130 for (const auto &LC : LibraryCalls) { 1131 setLibcallName(LC.Op, LC.Name); 1132 setLibcallCallingConv(LC.Op, LC.CC); 1133 } 1134 } 1135 1136 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1137 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1138 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1139 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1140 } else { 1141 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1142 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1143 } 1144 1145 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 1146 for (auto &VT : {MVT::f32, MVT::f64}) 1147 setOperationAction(ISD::FPOWI, VT, Custom); 1148 1149 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1150 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1151 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1152 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1153 1154 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1155 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1156 1157 // Use the default implementation. 1158 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1159 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1160 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1161 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1162 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1163 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1164 1165 if (Subtarget->isTargetWindows()) 1166 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1167 else 1168 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1169 1170 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1171 // the default expansion. 1172 InsertFencesForAtomic = false; 1173 if (Subtarget->hasAnyDataBarrier() && 1174 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1175 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1176 // to ldrex/strex loops already. 1177 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1178 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1179 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1180 1181 // On v8, we have particularly efficient implementations of atomic fences 1182 // if they can be combined with nearby atomic loads and stores. 1183 if (!Subtarget->hasAcquireRelease() || 1184 getTargetMachine().getOptLevel() == 0) { 1185 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1186 InsertFencesForAtomic = true; 1187 } 1188 } else { 1189 // If there's anything we can use as a barrier, go through custom lowering 1190 // for ATOMIC_FENCE. 1191 // If target has DMB in thumb, Fences can be inserted. 1192 if (Subtarget->hasDataBarrier()) 1193 InsertFencesForAtomic = true; 1194 1195 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1196 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1197 1198 // Set them all for expansion, which will force libcalls. 1199 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1200 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1201 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1202 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1203 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1204 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1205 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1206 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1207 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1208 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1209 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1210 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1211 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1212 // Unordered/Monotonic case. 1213 if (!InsertFencesForAtomic) { 1214 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1215 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1216 } 1217 } 1218 1219 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1220 1221 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1222 if (!Subtarget->hasV6Ops()) { 1223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1224 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1225 } 1226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1227 1228 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1229 !Subtarget->isThumb1Only()) { 1230 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1231 // iff target supports vfp2. 1232 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1233 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1234 } 1235 1236 // We want to custom lower some of our intrinsics. 1237 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1238 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1239 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1240 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1241 if (Subtarget->useSjLjEH()) 1242 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1243 1244 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1245 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1246 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1247 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1248 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1249 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1250 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1251 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1252 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1253 if (Subtarget->hasFullFP16()) { 1254 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1255 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1256 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1257 } 1258 1259 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1260 1261 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1262 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1263 if (Subtarget->hasFullFP16()) 1264 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1265 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1266 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1267 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1268 1269 // We don't support sin/cos/fmod/copysign/pow 1270 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1271 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1272 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1273 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1274 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1275 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1276 setOperationAction(ISD::FREM, MVT::f64, Expand); 1277 setOperationAction(ISD::FREM, MVT::f32, Expand); 1278 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1279 !Subtarget->isThumb1Only()) { 1280 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1281 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1282 } 1283 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1284 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1285 1286 if (!Subtarget->hasVFP4Base()) { 1287 setOperationAction(ISD::FMA, MVT::f64, Expand); 1288 setOperationAction(ISD::FMA, MVT::f32, Expand); 1289 } 1290 1291 // Various VFP goodness 1292 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1293 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1294 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1295 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1296 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1297 } 1298 1299 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1300 if (!Subtarget->hasFP16()) { 1301 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1302 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1303 } 1304 } 1305 1306 // Use __sincos_stret if available. 1307 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1308 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1309 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1310 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1311 } 1312 1313 // FP-ARMv8 implements a lot of rounding-like FP operations. 1314 if (Subtarget->hasFPARMv8Base()) { 1315 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1316 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1317 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1318 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1319 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1320 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1321 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1322 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1323 if (Subtarget->hasNEON()) { 1324 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1325 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1326 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1327 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1328 } 1329 1330 if (Subtarget->hasFP64()) { 1331 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1332 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1333 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1334 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1335 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1336 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1337 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1338 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1339 } 1340 } 1341 1342 // FP16 often need to be promoted to call lib functions 1343 if (Subtarget->hasFullFP16()) { 1344 setOperationAction(ISD::FREM, MVT::f16, Promote); 1345 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1346 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1347 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1348 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1349 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1350 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1351 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1352 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1353 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1354 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1355 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1356 1357 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1358 } 1359 1360 if (Subtarget->hasNEON()) { 1361 // vmin and vmax aren't available in a scalar form, so we use 1362 // a NEON instruction with an undef lane instead. 1363 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1364 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1365 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1366 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1367 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1368 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1369 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1370 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1371 1372 if (Subtarget->hasFullFP16()) { 1373 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1374 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1375 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1376 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1377 1378 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1379 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1380 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1381 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1382 } 1383 } 1384 1385 // We have target-specific dag combine patterns for the following nodes: 1386 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1387 setTargetDAGCombine(ISD::ADD); 1388 setTargetDAGCombine(ISD::SUB); 1389 setTargetDAGCombine(ISD::MUL); 1390 setTargetDAGCombine(ISD::AND); 1391 setTargetDAGCombine(ISD::OR); 1392 setTargetDAGCombine(ISD::XOR); 1393 1394 if (Subtarget->hasV6Ops()) 1395 setTargetDAGCombine(ISD::SRL); 1396 if (Subtarget->isThumb1Only()) 1397 setTargetDAGCombine(ISD::SHL); 1398 1399 setStackPointerRegisterToSaveRestore(ARM::SP); 1400 1401 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1402 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1403 setSchedulingPreference(Sched::RegPressure); 1404 else 1405 setSchedulingPreference(Sched::Hybrid); 1406 1407 //// temporary - rewrite interface to use type 1408 MaxStoresPerMemset = 8; 1409 MaxStoresPerMemsetOptSize = 4; 1410 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1411 MaxStoresPerMemcpyOptSize = 2; 1412 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1413 MaxStoresPerMemmoveOptSize = 2; 1414 1415 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1416 // are at least 4 bytes aligned. 1417 setMinStackArgumentAlignment(4); 1418 1419 // Prefer likely predicted branches to selects on out-of-order cores. 1420 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1421 1422 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment()); 1423 1424 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1425 1426 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1427 setTargetDAGCombine(ISD::ABS); 1428 } 1429 1430 bool ARMTargetLowering::useSoftFloat() const { 1431 return Subtarget->useSoftFloat(); 1432 } 1433 1434 // FIXME: It might make sense to define the representative register class as the 1435 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1436 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1437 // SPR's representative would be DPR_VFP2. This should work well if register 1438 // pressure tracking were modified such that a register use would increment the 1439 // pressure of the register class's representative and all of it's super 1440 // classes' representatives transitively. We have not implemented this because 1441 // of the difficulty prior to coalescing of modeling operand register classes 1442 // due to the common occurrence of cross class copies and subregister insertions 1443 // and extractions. 1444 std::pair<const TargetRegisterClass *, uint8_t> 1445 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1446 MVT VT) const { 1447 const TargetRegisterClass *RRC = nullptr; 1448 uint8_t Cost = 1; 1449 switch (VT.SimpleTy) { 1450 default: 1451 return TargetLowering::findRepresentativeClass(TRI, VT); 1452 // Use DPR as representative register class for all floating point 1453 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1454 // the cost is 1 for both f32 and f64. 1455 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1456 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1457 RRC = &ARM::DPRRegClass; 1458 // When NEON is used for SP, only half of the register file is available 1459 // because operations that define both SP and DP results will be constrained 1460 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1461 // coalescing by double-counting the SP regs. See the FIXME above. 1462 if (Subtarget->useNEONForSinglePrecisionFP()) 1463 Cost = 2; 1464 break; 1465 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1466 case MVT::v4f32: case MVT::v2f64: 1467 RRC = &ARM::DPRRegClass; 1468 Cost = 2; 1469 break; 1470 case MVT::v4i64: 1471 RRC = &ARM::DPRRegClass; 1472 Cost = 4; 1473 break; 1474 case MVT::v8i64: 1475 RRC = &ARM::DPRRegClass; 1476 Cost = 8; 1477 break; 1478 } 1479 return std::make_pair(RRC, Cost); 1480 } 1481 1482 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1483 switch ((ARMISD::NodeType)Opcode) { 1484 case ARMISD::FIRST_NUMBER: break; 1485 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1486 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1487 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1488 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1489 case ARMISD::CALL: return "ARMISD::CALL"; 1490 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1491 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1492 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1493 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1494 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1495 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1496 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1497 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1498 case ARMISD::CMP: return "ARMISD::CMP"; 1499 case ARMISD::CMN: return "ARMISD::CMN"; 1500 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1501 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1502 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1503 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1504 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1505 1506 case ARMISD::CMOV: return "ARMISD::CMOV"; 1507 case ARMISD::SUBS: return "ARMISD::SUBS"; 1508 1509 case ARMISD::SSAT: return "ARMISD::SSAT"; 1510 case ARMISD::USAT: return "ARMISD::USAT"; 1511 1512 case ARMISD::ASRL: return "ARMISD::ASRL"; 1513 case ARMISD::LSRL: return "ARMISD::LSRL"; 1514 case ARMISD::LSLL: return "ARMISD::LSLL"; 1515 1516 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1517 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1518 case ARMISD::RRX: return "ARMISD::RRX"; 1519 1520 case ARMISD::ADDC: return "ARMISD::ADDC"; 1521 case ARMISD::ADDE: return "ARMISD::ADDE"; 1522 case ARMISD::SUBC: return "ARMISD::SUBC"; 1523 case ARMISD::SUBE: return "ARMISD::SUBE"; 1524 case ARMISD::LSLS: return "ARMISD::LSLS"; 1525 1526 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1527 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1528 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1529 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1530 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1531 1532 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1533 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1534 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1535 1536 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1537 1538 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1539 1540 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1541 1542 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1543 1544 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1545 1546 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1547 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1548 1549 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST"; 1550 case ARMISD::VCMP: return "ARMISD::VCMP"; 1551 case ARMISD::VCMPZ: return "ARMISD::VCMPZ"; 1552 case ARMISD::VTST: return "ARMISD::VTST"; 1553 1554 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1555 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1556 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1557 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1558 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1559 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1560 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1561 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1562 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1563 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1564 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1565 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1566 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1567 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1568 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1569 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1570 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1571 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1572 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1573 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1574 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1575 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1576 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1577 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1578 case ARMISD::VDUP: return "ARMISD::VDUP"; 1579 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1580 case ARMISD::VEXT: return "ARMISD::VEXT"; 1581 case ARMISD::VREV64: return "ARMISD::VREV64"; 1582 case ARMISD::VREV32: return "ARMISD::VREV32"; 1583 case ARMISD::VREV16: return "ARMISD::VREV16"; 1584 case ARMISD::VZIP: return "ARMISD::VZIP"; 1585 case ARMISD::VUZP: return "ARMISD::VUZP"; 1586 case ARMISD::VTRN: return "ARMISD::VTRN"; 1587 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1588 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1589 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1590 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1591 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1592 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1593 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1594 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1595 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1596 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1597 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1598 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1599 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1600 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1601 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1602 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1603 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1604 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1605 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1606 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1607 case ARMISD::BFI: return "ARMISD::BFI"; 1608 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1609 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1610 case ARMISD::VBSL: return "ARMISD::VBSL"; 1611 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1612 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1613 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1614 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1615 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1616 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1617 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1618 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1619 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1620 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1621 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1622 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1623 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1624 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1625 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1626 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1627 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1628 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1629 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1630 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1631 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1632 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1633 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1634 case ARMISD::WLS: return "ARMISD::WLS"; 1635 case ARMISD::LE: return "ARMISD::LE"; 1636 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1637 } 1638 return nullptr; 1639 } 1640 1641 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1642 EVT VT) const { 1643 if (!VT.isVector()) 1644 return getPointerTy(DL); 1645 1646 // MVE has a predicate register. 1647 if (Subtarget->hasMVEIntegerOps() && 1648 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1649 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1650 return VT.changeVectorElementTypeToInteger(); 1651 } 1652 1653 /// getRegClassFor - Return the register class that should be used for the 1654 /// specified value type. 1655 const TargetRegisterClass * 1656 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1657 (void)isDivergent; 1658 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1659 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1660 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1661 // MVE Q registers. 1662 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1663 if (VT == MVT::v4i64) 1664 return &ARM::QQPRRegClass; 1665 if (VT == MVT::v8i64) 1666 return &ARM::QQQQPRRegClass; 1667 } 1668 return TargetLowering::getRegClassFor(VT); 1669 } 1670 1671 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1672 // source/dest is aligned and the copy size is large enough. We therefore want 1673 // to align such objects passed to memory intrinsics. 1674 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1675 unsigned &PrefAlign) const { 1676 if (!isa<MemIntrinsic>(CI)) 1677 return false; 1678 MinSize = 8; 1679 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1680 // cycle faster than 4-byte aligned LDM. 1681 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1682 return true; 1683 } 1684 1685 // Create a fast isel object. 1686 FastISel * 1687 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1688 const TargetLibraryInfo *libInfo) const { 1689 return ARM::createFastISel(funcInfo, libInfo); 1690 } 1691 1692 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1693 unsigned NumVals = N->getNumValues(); 1694 if (!NumVals) 1695 return Sched::RegPressure; 1696 1697 for (unsigned i = 0; i != NumVals; ++i) { 1698 EVT VT = N->getValueType(i); 1699 if (VT == MVT::Glue || VT == MVT::Other) 1700 continue; 1701 if (VT.isFloatingPoint() || VT.isVector()) 1702 return Sched::ILP; 1703 } 1704 1705 if (!N->isMachineOpcode()) 1706 return Sched::RegPressure; 1707 1708 // Load are scheduled for latency even if there instruction itinerary 1709 // is not available. 1710 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1711 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1712 1713 if (MCID.getNumDefs() == 0) 1714 return Sched::RegPressure; 1715 if (!Itins->isEmpty() && 1716 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1717 return Sched::ILP; 1718 1719 return Sched::RegPressure; 1720 } 1721 1722 //===----------------------------------------------------------------------===// 1723 // Lowering Code 1724 //===----------------------------------------------------------------------===// 1725 1726 static bool isSRL16(const SDValue &Op) { 1727 if (Op.getOpcode() != ISD::SRL) 1728 return false; 1729 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1730 return Const->getZExtValue() == 16; 1731 return false; 1732 } 1733 1734 static bool isSRA16(const SDValue &Op) { 1735 if (Op.getOpcode() != ISD::SRA) 1736 return false; 1737 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1738 return Const->getZExtValue() == 16; 1739 return false; 1740 } 1741 1742 static bool isSHL16(const SDValue &Op) { 1743 if (Op.getOpcode() != ISD::SHL) 1744 return false; 1745 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1746 return Const->getZExtValue() == 16; 1747 return false; 1748 } 1749 1750 // Check for a signed 16-bit value. We special case SRA because it makes it 1751 // more simple when also looking for SRAs that aren't sign extending a 1752 // smaller value. Without the check, we'd need to take extra care with 1753 // checking order for some operations. 1754 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1755 if (isSRA16(Op)) 1756 return isSHL16(Op.getOperand(0)); 1757 return DAG.ComputeNumSignBits(Op) == 17; 1758 } 1759 1760 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1761 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1762 switch (CC) { 1763 default: llvm_unreachable("Unknown condition code!"); 1764 case ISD::SETNE: return ARMCC::NE; 1765 case ISD::SETEQ: return ARMCC::EQ; 1766 case ISD::SETGT: return ARMCC::GT; 1767 case ISD::SETGE: return ARMCC::GE; 1768 case ISD::SETLT: return ARMCC::LT; 1769 case ISD::SETLE: return ARMCC::LE; 1770 case ISD::SETUGT: return ARMCC::HI; 1771 case ISD::SETUGE: return ARMCC::HS; 1772 case ISD::SETULT: return ARMCC::LO; 1773 case ISD::SETULE: return ARMCC::LS; 1774 } 1775 } 1776 1777 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1778 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1779 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1780 CondCode2 = ARMCC::AL; 1781 InvalidOnQNaN = true; 1782 switch (CC) { 1783 default: llvm_unreachable("Unknown FP condition!"); 1784 case ISD::SETEQ: 1785 case ISD::SETOEQ: 1786 CondCode = ARMCC::EQ; 1787 InvalidOnQNaN = false; 1788 break; 1789 case ISD::SETGT: 1790 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1791 case ISD::SETGE: 1792 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1793 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1794 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1795 case ISD::SETONE: 1796 CondCode = ARMCC::MI; 1797 CondCode2 = ARMCC::GT; 1798 InvalidOnQNaN = false; 1799 break; 1800 case ISD::SETO: CondCode = ARMCC::VC; break; 1801 case ISD::SETUO: CondCode = ARMCC::VS; break; 1802 case ISD::SETUEQ: 1803 CondCode = ARMCC::EQ; 1804 CondCode2 = ARMCC::VS; 1805 InvalidOnQNaN = false; 1806 break; 1807 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1808 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1809 case ISD::SETLT: 1810 case ISD::SETULT: CondCode = ARMCC::LT; break; 1811 case ISD::SETLE: 1812 case ISD::SETULE: CondCode = ARMCC::LE; break; 1813 case ISD::SETNE: 1814 case ISD::SETUNE: 1815 CondCode = ARMCC::NE; 1816 InvalidOnQNaN = false; 1817 break; 1818 } 1819 } 1820 1821 //===----------------------------------------------------------------------===// 1822 // Calling Convention Implementation 1823 //===----------------------------------------------------------------------===// 1824 1825 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1826 /// account presence of floating point hardware and calling convention 1827 /// limitations, such as support for variadic functions. 1828 CallingConv::ID 1829 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1830 bool isVarArg) const { 1831 switch (CC) { 1832 default: 1833 report_fatal_error("Unsupported calling convention"); 1834 case CallingConv::ARM_AAPCS: 1835 case CallingConv::ARM_APCS: 1836 case CallingConv::GHC: 1837 return CC; 1838 case CallingConv::PreserveMost: 1839 return CallingConv::PreserveMost; 1840 case CallingConv::ARM_AAPCS_VFP: 1841 case CallingConv::Swift: 1842 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1843 case CallingConv::C: 1844 if (!Subtarget->isAAPCS_ABI()) 1845 return CallingConv::ARM_APCS; 1846 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1847 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1848 !isVarArg) 1849 return CallingConv::ARM_AAPCS_VFP; 1850 else 1851 return CallingConv::ARM_AAPCS; 1852 case CallingConv::Fast: 1853 case CallingConv::CXX_FAST_TLS: 1854 if (!Subtarget->isAAPCS_ABI()) { 1855 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 1856 return CallingConv::Fast; 1857 return CallingConv::ARM_APCS; 1858 } else if (Subtarget->hasVFP2Base() && 1859 !Subtarget->isThumb1Only() && !isVarArg) 1860 return CallingConv::ARM_AAPCS_VFP; 1861 else 1862 return CallingConv::ARM_AAPCS; 1863 } 1864 } 1865 1866 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1867 bool isVarArg) const { 1868 return CCAssignFnForNode(CC, false, isVarArg); 1869 } 1870 1871 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1872 bool isVarArg) const { 1873 return CCAssignFnForNode(CC, true, isVarArg); 1874 } 1875 1876 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1877 /// CallingConvention. 1878 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1879 bool Return, 1880 bool isVarArg) const { 1881 switch (getEffectiveCallingConv(CC, isVarArg)) { 1882 default: 1883 report_fatal_error("Unsupported calling convention"); 1884 case CallingConv::ARM_APCS: 1885 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1886 case CallingConv::ARM_AAPCS: 1887 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1888 case CallingConv::ARM_AAPCS_VFP: 1889 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1890 case CallingConv::Fast: 1891 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1892 case CallingConv::GHC: 1893 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1894 case CallingConv::PreserveMost: 1895 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1896 } 1897 } 1898 1899 /// LowerCallResult - Lower the result values of a call into the 1900 /// appropriate copies out of appropriate physical registers. 1901 SDValue ARMTargetLowering::LowerCallResult( 1902 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1903 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1904 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1905 SDValue ThisVal) const { 1906 // Assign locations to each value returned by this call. 1907 SmallVector<CCValAssign, 16> RVLocs; 1908 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1909 *DAG.getContext()); 1910 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1911 1912 // Copy all of the result registers out of their specified physreg. 1913 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1914 CCValAssign VA = RVLocs[i]; 1915 1916 // Pass 'this' value directly from the argument to return value, to avoid 1917 // reg unit interference 1918 if (i == 0 && isThisReturn) { 1919 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1920 "unexpected return calling convention register assignment"); 1921 InVals.push_back(ThisVal); 1922 continue; 1923 } 1924 1925 SDValue Val; 1926 if (VA.needsCustom()) { 1927 // Handle f64 or half of a v2f64. 1928 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1929 InFlag); 1930 Chain = Lo.getValue(1); 1931 InFlag = Lo.getValue(2); 1932 VA = RVLocs[++i]; // skip ahead to next loc 1933 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1934 InFlag); 1935 Chain = Hi.getValue(1); 1936 InFlag = Hi.getValue(2); 1937 if (!Subtarget->isLittle()) 1938 std::swap (Lo, Hi); 1939 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1940 1941 if (VA.getLocVT() == MVT::v2f64) { 1942 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1943 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1944 DAG.getConstant(0, dl, MVT::i32)); 1945 1946 VA = RVLocs[++i]; // skip ahead to next loc 1947 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1948 Chain = Lo.getValue(1); 1949 InFlag = Lo.getValue(2); 1950 VA = RVLocs[++i]; // skip ahead to next loc 1951 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1952 Chain = Hi.getValue(1); 1953 InFlag = Hi.getValue(2); 1954 if (!Subtarget->isLittle()) 1955 std::swap (Lo, Hi); 1956 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1957 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1958 DAG.getConstant(1, dl, MVT::i32)); 1959 } 1960 } else { 1961 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1962 InFlag); 1963 Chain = Val.getValue(1); 1964 InFlag = Val.getValue(2); 1965 } 1966 1967 switch (VA.getLocInfo()) { 1968 default: llvm_unreachable("Unknown loc info!"); 1969 case CCValAssign::Full: break; 1970 case CCValAssign::BCvt: 1971 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1972 break; 1973 } 1974 1975 InVals.push_back(Val); 1976 } 1977 1978 return Chain; 1979 } 1980 1981 /// LowerMemOpCallTo - Store the argument to the stack. 1982 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1983 SDValue Arg, const SDLoc &dl, 1984 SelectionDAG &DAG, 1985 const CCValAssign &VA, 1986 ISD::ArgFlagsTy Flags) const { 1987 unsigned LocMemOffset = VA.getLocMemOffset(); 1988 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1989 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1990 StackPtr, PtrOff); 1991 return DAG.getStore( 1992 Chain, dl, Arg, PtrOff, 1993 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1994 } 1995 1996 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1997 SDValue Chain, SDValue &Arg, 1998 RegsToPassVector &RegsToPass, 1999 CCValAssign &VA, CCValAssign &NextVA, 2000 SDValue &StackPtr, 2001 SmallVectorImpl<SDValue> &MemOpChains, 2002 ISD::ArgFlagsTy Flags) const { 2003 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2004 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2005 unsigned id = Subtarget->isLittle() ? 0 : 1; 2006 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2007 2008 if (NextVA.isRegLoc()) 2009 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2010 else { 2011 assert(NextVA.isMemLoc()); 2012 if (!StackPtr.getNode()) 2013 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2014 getPointerTy(DAG.getDataLayout())); 2015 2016 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2017 dl, DAG, NextVA, 2018 Flags)); 2019 } 2020 } 2021 2022 /// LowerCall - Lowering a call into a callseq_start <- 2023 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2024 /// nodes. 2025 SDValue 2026 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2027 SmallVectorImpl<SDValue> &InVals) const { 2028 SelectionDAG &DAG = CLI.DAG; 2029 SDLoc &dl = CLI.DL; 2030 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2031 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2032 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2033 SDValue Chain = CLI.Chain; 2034 SDValue Callee = CLI.Callee; 2035 bool &isTailCall = CLI.IsTailCall; 2036 CallingConv::ID CallConv = CLI.CallConv; 2037 bool doesNotRet = CLI.DoesNotReturn; 2038 bool isVarArg = CLI.IsVarArg; 2039 2040 MachineFunction &MF = DAG.getMachineFunction(); 2041 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2042 bool isThisReturn = false; 2043 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 2044 bool PreferIndirect = false; 2045 2046 // Disable tail calls if they're not supported. 2047 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 2048 isTailCall = false; 2049 2050 if (isa<GlobalAddressSDNode>(Callee)) { 2051 // If we're optimizing for minimum size and the function is called three or 2052 // more times in this block, we can improve codesize by calling indirectly 2053 // as BLXr has a 16-bit encoding. 2054 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2055 if (CLI.CS) { 2056 auto *BB = CLI.CS.getParent(); 2057 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2058 count_if(GV->users(), [&BB](const User *U) { 2059 return isa<Instruction>(U) && 2060 cast<Instruction>(U)->getParent() == BB; 2061 }) > 2; 2062 } 2063 } 2064 if (isTailCall) { 2065 // Check if it's really possible to do a tail call. 2066 isTailCall = IsEligibleForTailCallOptimization( 2067 Callee, CallConv, isVarArg, isStructRet, 2068 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2069 PreferIndirect); 2070 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 2071 report_fatal_error("failed to perform tail call elimination on a call " 2072 "site marked musttail"); 2073 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2074 // detected sibcalls. 2075 if (isTailCall) 2076 ++NumTailCalls; 2077 } 2078 2079 // Analyze operands of the call, assigning locations to each operand. 2080 SmallVector<CCValAssign, 16> ArgLocs; 2081 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2082 *DAG.getContext()); 2083 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2084 2085 // Get a count of how many bytes are to be pushed on the stack. 2086 unsigned NumBytes = CCInfo.getNextStackOffset(); 2087 2088 if (isTailCall) { 2089 // For tail calls, memory operands are available in our caller's stack. 2090 NumBytes = 0; 2091 } else { 2092 // Adjust the stack pointer for the new arguments... 2093 // These operations are automatically eliminated by the prolog/epilog pass 2094 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2095 } 2096 2097 SDValue StackPtr = 2098 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2099 2100 RegsToPassVector RegsToPass; 2101 SmallVector<SDValue, 8> MemOpChains; 2102 2103 // Walk the register/memloc assignments, inserting copies/loads. In the case 2104 // of tail call optimization, arguments are handled later. 2105 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2106 i != e; 2107 ++i, ++realArgIdx) { 2108 CCValAssign &VA = ArgLocs[i]; 2109 SDValue Arg = OutVals[realArgIdx]; 2110 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2111 bool isByVal = Flags.isByVal(); 2112 2113 // Promote the value if needed. 2114 switch (VA.getLocInfo()) { 2115 default: llvm_unreachable("Unknown loc info!"); 2116 case CCValAssign::Full: break; 2117 case CCValAssign::SExt: 2118 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2119 break; 2120 case CCValAssign::ZExt: 2121 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2122 break; 2123 case CCValAssign::AExt: 2124 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2125 break; 2126 case CCValAssign::BCvt: 2127 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2128 break; 2129 } 2130 2131 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2132 if (VA.needsCustom()) { 2133 if (VA.getLocVT() == MVT::v2f64) { 2134 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2135 DAG.getConstant(0, dl, MVT::i32)); 2136 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2137 DAG.getConstant(1, dl, MVT::i32)); 2138 2139 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 2140 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2141 2142 VA = ArgLocs[++i]; // skip ahead to next loc 2143 if (VA.isRegLoc()) { 2144 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 2145 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2146 } else { 2147 assert(VA.isMemLoc()); 2148 2149 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 2150 dl, DAG, VA, Flags)); 2151 } 2152 } else { 2153 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2154 StackPtr, MemOpChains, Flags); 2155 } 2156 } else if (VA.isRegLoc()) { 2157 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2158 Outs[0].VT == MVT::i32) { 2159 assert(VA.getLocVT() == MVT::i32 && 2160 "unexpected calling convention register assignment"); 2161 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2162 "unexpected use of 'returned'"); 2163 isThisReturn = true; 2164 } 2165 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2166 } else if (isByVal) { 2167 assert(VA.isMemLoc()); 2168 unsigned offset = 0; 2169 2170 // True if this byval aggregate will be split between registers 2171 // and memory. 2172 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2173 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2174 2175 if (CurByValIdx < ByValArgsCount) { 2176 2177 unsigned RegBegin, RegEnd; 2178 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2179 2180 EVT PtrVT = 2181 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2182 unsigned int i, j; 2183 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2184 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2185 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2186 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 2187 MachinePointerInfo(), 2188 DAG.InferPtrAlignment(AddArg)); 2189 MemOpChains.push_back(Load.getValue(1)); 2190 RegsToPass.push_back(std::make_pair(j, Load)); 2191 } 2192 2193 // If parameter size outsides register area, "offset" value 2194 // helps us to calculate stack slot for remained part properly. 2195 offset = RegEnd - RegBegin; 2196 2197 CCInfo.nextInRegsParam(); 2198 } 2199 2200 if (Flags.getByValSize() > 4*offset) { 2201 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2202 unsigned LocMemOffset = VA.getLocMemOffset(); 2203 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2204 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2205 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2206 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2207 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2208 MVT::i32); 2209 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 2210 MVT::i32); 2211 2212 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2213 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2214 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2215 Ops)); 2216 } 2217 } else if (!isTailCall) { 2218 assert(VA.isMemLoc()); 2219 2220 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2221 dl, DAG, VA, Flags)); 2222 } 2223 } 2224 2225 if (!MemOpChains.empty()) 2226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2227 2228 // Build a sequence of copy-to-reg nodes chained together with token chain 2229 // and flag operands which copy the outgoing args into the appropriate regs. 2230 SDValue InFlag; 2231 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2232 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2233 RegsToPass[i].second, InFlag); 2234 InFlag = Chain.getValue(1); 2235 } 2236 2237 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2238 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2239 // node so that legalize doesn't hack it. 2240 bool isDirect = false; 2241 2242 const TargetMachine &TM = getTargetMachine(); 2243 const Module *Mod = MF.getFunction().getParent(); 2244 const GlobalValue *GV = nullptr; 2245 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2246 GV = G->getGlobal(); 2247 bool isStub = 2248 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2249 2250 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2251 bool isLocalARMFunc = false; 2252 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2253 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2254 2255 if (Subtarget->genLongCalls()) { 2256 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2257 "long-calls codegen is not position independent!"); 2258 // Handle a global address or an external symbol. If it's not one of 2259 // those, the target's already in a register, so we don't need to do 2260 // anything extra. 2261 if (isa<GlobalAddressSDNode>(Callee)) { 2262 // Create a constant pool entry for the callee address 2263 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2264 ARMConstantPoolValue *CPV = 2265 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2266 2267 // Get the address of the callee into a register 2268 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2269 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2270 Callee = DAG.getLoad( 2271 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2272 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2273 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2274 const char *Sym = S->getSymbol(); 2275 2276 // Create a constant pool entry for the callee address 2277 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2278 ARMConstantPoolValue *CPV = 2279 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2280 ARMPCLabelIndex, 0); 2281 // Get the address of the callee into a register 2282 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2283 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2284 Callee = DAG.getLoad( 2285 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2286 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2287 } 2288 } else if (isa<GlobalAddressSDNode>(Callee)) { 2289 if (!PreferIndirect) { 2290 isDirect = true; 2291 bool isDef = GV->isStrongDefinitionForLinker(); 2292 2293 // ARM call to a local ARM function is predicable. 2294 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2295 // tBX takes a register source operand. 2296 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2297 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2298 Callee = DAG.getNode( 2299 ARMISD::WrapperPIC, dl, PtrVt, 2300 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2301 Callee = DAG.getLoad( 2302 PtrVt, dl, DAG.getEntryNode(), Callee, 2303 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2304 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2305 MachineMemOperand::MOInvariant); 2306 } else if (Subtarget->isTargetCOFF()) { 2307 assert(Subtarget->isTargetWindows() && 2308 "Windows is the only supported COFF target"); 2309 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2310 ? ARMII::MO_DLLIMPORT 2311 : ARMII::MO_NO_FLAG; 2312 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2313 TargetFlags); 2314 if (GV->hasDLLImportStorageClass()) 2315 Callee = 2316 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2317 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2318 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2319 } else { 2320 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2321 } 2322 } 2323 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2324 isDirect = true; 2325 // tBX takes a register source operand. 2326 const char *Sym = S->getSymbol(); 2327 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2328 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2329 ARMConstantPoolValue *CPV = 2330 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2331 ARMPCLabelIndex, 4); 2332 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2333 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2334 Callee = DAG.getLoad( 2335 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2336 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2337 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2338 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2339 } else { 2340 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2341 } 2342 } 2343 2344 // FIXME: handle tail calls differently. 2345 unsigned CallOpc; 2346 if (Subtarget->isThumb()) { 2347 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2348 CallOpc = ARMISD::CALL_NOLINK; 2349 else 2350 CallOpc = ARMISD::CALL; 2351 } else { 2352 if (!isDirect && !Subtarget->hasV5TOps()) 2353 CallOpc = ARMISD::CALL_NOLINK; 2354 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2355 // Emit regular call when code size is the priority 2356 !Subtarget->hasMinSize()) 2357 // "mov lr, pc; b _foo" to avoid confusing the RSP 2358 CallOpc = ARMISD::CALL_NOLINK; 2359 else 2360 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2361 } 2362 2363 std::vector<SDValue> Ops; 2364 Ops.push_back(Chain); 2365 Ops.push_back(Callee); 2366 2367 // Add argument registers to the end of the list so that they are known live 2368 // into the call. 2369 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2370 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2371 RegsToPass[i].second.getValueType())); 2372 2373 // Add a register mask operand representing the call-preserved registers. 2374 if (!isTailCall) { 2375 const uint32_t *Mask; 2376 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2377 if (isThisReturn) { 2378 // For 'this' returns, use the R0-preserving mask if applicable 2379 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2380 if (!Mask) { 2381 // Set isThisReturn to false if the calling convention is not one that 2382 // allows 'returned' to be modeled in this way, so LowerCallResult does 2383 // not try to pass 'this' straight through 2384 isThisReturn = false; 2385 Mask = ARI->getCallPreservedMask(MF, CallConv); 2386 } 2387 } else 2388 Mask = ARI->getCallPreservedMask(MF, CallConv); 2389 2390 assert(Mask && "Missing call preserved mask for calling convention"); 2391 Ops.push_back(DAG.getRegisterMask(Mask)); 2392 } 2393 2394 if (InFlag.getNode()) 2395 Ops.push_back(InFlag); 2396 2397 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2398 if (isTailCall) { 2399 MF.getFrameInfo().setHasTailCall(); 2400 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2401 } 2402 2403 // Returns a chain and a flag for retval copy to use. 2404 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2405 InFlag = Chain.getValue(1); 2406 2407 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2408 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2409 if (!Ins.empty()) 2410 InFlag = Chain.getValue(1); 2411 2412 // Handle result values, copying them out of physregs into vregs that we 2413 // return. 2414 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2415 InVals, isThisReturn, 2416 isThisReturn ? OutVals[0] : SDValue()); 2417 } 2418 2419 /// HandleByVal - Every parameter *after* a byval parameter is passed 2420 /// on the stack. Remember the next parameter register to allocate, 2421 /// and then confiscate the rest of the parameter registers to insure 2422 /// this. 2423 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2424 unsigned Align) const { 2425 // Byval (as with any stack) slots are always at least 4 byte aligned. 2426 Align = std::max(Align, 4U); 2427 2428 unsigned Reg = State->AllocateReg(GPRArgRegs); 2429 if (!Reg) 2430 return; 2431 2432 unsigned AlignInRegs = Align / 4; 2433 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2434 for (unsigned i = 0; i < Waste; ++i) 2435 Reg = State->AllocateReg(GPRArgRegs); 2436 2437 if (!Reg) 2438 return; 2439 2440 unsigned Excess = 4 * (ARM::R4 - Reg); 2441 2442 // Special case when NSAA != SP and parameter size greater than size of 2443 // all remained GPR regs. In that case we can't split parameter, we must 2444 // send it to stack. We also must set NCRN to R4, so waste all 2445 // remained registers. 2446 const unsigned NSAAOffset = State->getNextStackOffset(); 2447 if (NSAAOffset != 0 && Size > Excess) { 2448 while (State->AllocateReg(GPRArgRegs)) 2449 ; 2450 return; 2451 } 2452 2453 // First register for byval parameter is the first register that wasn't 2454 // allocated before this method call, so it would be "reg". 2455 // If parameter is small enough to be saved in range [reg, r4), then 2456 // the end (first after last) register would be reg + param-size-in-regs, 2457 // else parameter would be splitted between registers and stack, 2458 // end register would be r4 in this case. 2459 unsigned ByValRegBegin = Reg; 2460 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2461 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2462 // Note, first register is allocated in the beginning of function already, 2463 // allocate remained amount of registers we need. 2464 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2465 State->AllocateReg(GPRArgRegs); 2466 // A byval parameter that is split between registers and memory needs its 2467 // size truncated here. 2468 // In the case where the entire structure fits in registers, we set the 2469 // size in memory to zero. 2470 Size = std::max<int>(Size - Excess, 0); 2471 } 2472 2473 /// MatchingStackOffset - Return true if the given stack call argument is 2474 /// already available in the same position (relatively) of the caller's 2475 /// incoming argument stack. 2476 static 2477 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2478 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2479 const TargetInstrInfo *TII) { 2480 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2481 int FI = std::numeric_limits<int>::max(); 2482 if (Arg.getOpcode() == ISD::CopyFromReg) { 2483 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2484 if (!Register::isVirtualRegister(VR)) 2485 return false; 2486 MachineInstr *Def = MRI->getVRegDef(VR); 2487 if (!Def) 2488 return false; 2489 if (!Flags.isByVal()) { 2490 if (!TII->isLoadFromStackSlot(*Def, FI)) 2491 return false; 2492 } else { 2493 return false; 2494 } 2495 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2496 if (Flags.isByVal()) 2497 // ByVal argument is passed in as a pointer but it's now being 2498 // dereferenced. e.g. 2499 // define @foo(%struct.X* %A) { 2500 // tail call @bar(%struct.X* byval %A) 2501 // } 2502 return false; 2503 SDValue Ptr = Ld->getBasePtr(); 2504 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2505 if (!FINode) 2506 return false; 2507 FI = FINode->getIndex(); 2508 } else 2509 return false; 2510 2511 assert(FI != std::numeric_limits<int>::max()); 2512 if (!MFI.isFixedObjectIndex(FI)) 2513 return false; 2514 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2515 } 2516 2517 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2518 /// for tail call optimization. Targets which want to do tail call 2519 /// optimization should implement this function. 2520 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2521 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2522 bool isCalleeStructRet, bool isCallerStructRet, 2523 const SmallVectorImpl<ISD::OutputArg> &Outs, 2524 const SmallVectorImpl<SDValue> &OutVals, 2525 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2526 const bool isIndirect) const { 2527 MachineFunction &MF = DAG.getMachineFunction(); 2528 const Function &CallerF = MF.getFunction(); 2529 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2530 2531 assert(Subtarget->supportsTailCall()); 2532 2533 // Indirect tail calls cannot be optimized for Thumb1 if the args 2534 // to the call take up r0-r3. The reason is that there are no legal registers 2535 // left to hold the pointer to the function to be called. 2536 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2537 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2538 return false; 2539 2540 // Look for obvious safe cases to perform tail call optimization that do not 2541 // require ABI changes. This is what gcc calls sibcall. 2542 2543 // Exception-handling functions need a special set of instructions to indicate 2544 // a return to the hardware. Tail-calling another function would probably 2545 // break this. 2546 if (CallerF.hasFnAttribute("interrupt")) 2547 return false; 2548 2549 // Also avoid sibcall optimization if either caller or callee uses struct 2550 // return semantics. 2551 if (isCalleeStructRet || isCallerStructRet) 2552 return false; 2553 2554 // Externally-defined functions with weak linkage should not be 2555 // tail-called on ARM when the OS does not support dynamic 2556 // pre-emption of symbols, as the AAELF spec requires normal calls 2557 // to undefined weak functions to be replaced with a NOP or jump to the 2558 // next instruction. The behaviour of branch instructions in this 2559 // situation (as used for tail calls) is implementation-defined, so we 2560 // cannot rely on the linker replacing the tail call with a return. 2561 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2562 const GlobalValue *GV = G->getGlobal(); 2563 const Triple &TT = getTargetMachine().getTargetTriple(); 2564 if (GV->hasExternalWeakLinkage() && 2565 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2566 return false; 2567 } 2568 2569 // Check that the call results are passed in the same way. 2570 LLVMContext &C = *DAG.getContext(); 2571 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2572 CCAssignFnForReturn(CalleeCC, isVarArg), 2573 CCAssignFnForReturn(CallerCC, isVarArg))) 2574 return false; 2575 // The callee has to preserve all registers the caller needs to preserve. 2576 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2577 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2578 if (CalleeCC != CallerCC) { 2579 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2580 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2581 return false; 2582 } 2583 2584 // If Caller's vararg or byval argument has been split between registers and 2585 // stack, do not perform tail call, since part of the argument is in caller's 2586 // local frame. 2587 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2588 if (AFI_Caller->getArgRegsSaveSize()) 2589 return false; 2590 2591 // If the callee takes no arguments then go on to check the results of the 2592 // call. 2593 if (!Outs.empty()) { 2594 // Check if stack adjustment is needed. For now, do not do this if any 2595 // argument is passed on the stack. 2596 SmallVector<CCValAssign, 16> ArgLocs; 2597 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2598 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2599 if (CCInfo.getNextStackOffset()) { 2600 // Check if the arguments are already laid out in the right way as 2601 // the caller's fixed stack objects. 2602 MachineFrameInfo &MFI = MF.getFrameInfo(); 2603 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2604 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2605 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2606 i != e; 2607 ++i, ++realArgIdx) { 2608 CCValAssign &VA = ArgLocs[i]; 2609 EVT RegVT = VA.getLocVT(); 2610 SDValue Arg = OutVals[realArgIdx]; 2611 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2612 if (VA.getLocInfo() == CCValAssign::Indirect) 2613 return false; 2614 if (VA.needsCustom()) { 2615 // f64 and vector types are split into multiple registers or 2616 // register/stack-slot combinations. The types will not match 2617 // the registers; give up on memory f64 refs until we figure 2618 // out what to do about this. 2619 if (!VA.isRegLoc()) 2620 return false; 2621 if (!ArgLocs[++i].isRegLoc()) 2622 return false; 2623 if (RegVT == MVT::v2f64) { 2624 if (!ArgLocs[++i].isRegLoc()) 2625 return false; 2626 if (!ArgLocs[++i].isRegLoc()) 2627 return false; 2628 } 2629 } else if (!VA.isRegLoc()) { 2630 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2631 MFI, MRI, TII)) 2632 return false; 2633 } 2634 } 2635 } 2636 2637 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2638 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2639 return false; 2640 } 2641 2642 return true; 2643 } 2644 2645 bool 2646 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2647 MachineFunction &MF, bool isVarArg, 2648 const SmallVectorImpl<ISD::OutputArg> &Outs, 2649 LLVMContext &Context) const { 2650 SmallVector<CCValAssign, 16> RVLocs; 2651 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2652 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2653 } 2654 2655 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2656 const SDLoc &DL, SelectionDAG &DAG) { 2657 const MachineFunction &MF = DAG.getMachineFunction(); 2658 const Function &F = MF.getFunction(); 2659 2660 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2661 2662 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2663 // version of the "preferred return address". These offsets affect the return 2664 // instruction if this is a return from PL1 without hypervisor extensions. 2665 // IRQ/FIQ: +4 "subs pc, lr, #4" 2666 // SWI: 0 "subs pc, lr, #0" 2667 // ABORT: +4 "subs pc, lr, #4" 2668 // UNDEF: +4/+2 "subs pc, lr, #0" 2669 // UNDEF varies depending on where the exception came from ARM or Thumb 2670 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2671 2672 int64_t LROffset; 2673 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2674 IntKind == "ABORT") 2675 LROffset = 4; 2676 else if (IntKind == "SWI" || IntKind == "UNDEF") 2677 LROffset = 0; 2678 else 2679 report_fatal_error("Unsupported interrupt attribute. If present, value " 2680 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2681 2682 RetOps.insert(RetOps.begin() + 1, 2683 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2684 2685 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2686 } 2687 2688 SDValue 2689 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2690 bool isVarArg, 2691 const SmallVectorImpl<ISD::OutputArg> &Outs, 2692 const SmallVectorImpl<SDValue> &OutVals, 2693 const SDLoc &dl, SelectionDAG &DAG) const { 2694 // CCValAssign - represent the assignment of the return value to a location. 2695 SmallVector<CCValAssign, 16> RVLocs; 2696 2697 // CCState - Info about the registers and stack slots. 2698 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2699 *DAG.getContext()); 2700 2701 // Analyze outgoing return values. 2702 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2703 2704 SDValue Flag; 2705 SmallVector<SDValue, 4> RetOps; 2706 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2707 bool isLittleEndian = Subtarget->isLittle(); 2708 2709 MachineFunction &MF = DAG.getMachineFunction(); 2710 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2711 AFI->setReturnRegsCount(RVLocs.size()); 2712 2713 // Copy the result values into the output registers. 2714 for (unsigned i = 0, realRVLocIdx = 0; 2715 i != RVLocs.size(); 2716 ++i, ++realRVLocIdx) { 2717 CCValAssign &VA = RVLocs[i]; 2718 assert(VA.isRegLoc() && "Can only return in registers!"); 2719 2720 SDValue Arg = OutVals[realRVLocIdx]; 2721 bool ReturnF16 = false; 2722 2723 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2724 // Half-precision return values can be returned like this: 2725 // 2726 // t11 f16 = fadd ... 2727 // t12: i16 = bitcast t11 2728 // t13: i32 = zero_extend t12 2729 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2730 // 2731 // to avoid code generation for bitcasts, we simply set Arg to the node 2732 // that produces the f16 value, t11 in this case. 2733 // 2734 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2735 SDValue ZE = Arg.getOperand(0); 2736 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2737 SDValue BC = ZE.getOperand(0); 2738 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2739 Arg = BC.getOperand(0); 2740 ReturnF16 = true; 2741 } 2742 } 2743 } 2744 } 2745 2746 switch (VA.getLocInfo()) { 2747 default: llvm_unreachable("Unknown loc info!"); 2748 case CCValAssign::Full: break; 2749 case CCValAssign::BCvt: 2750 if (!ReturnF16) 2751 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2752 break; 2753 } 2754 2755 if (VA.needsCustom()) { 2756 if (VA.getLocVT() == MVT::v2f64) { 2757 // Extract the first half and return it in two registers. 2758 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2759 DAG.getConstant(0, dl, MVT::i32)); 2760 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2761 DAG.getVTList(MVT::i32, MVT::i32), Half); 2762 2763 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2764 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2765 Flag); 2766 Flag = Chain.getValue(1); 2767 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2768 VA = RVLocs[++i]; // skip ahead to next loc 2769 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2770 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2771 Flag); 2772 Flag = Chain.getValue(1); 2773 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2774 VA = RVLocs[++i]; // skip ahead to next loc 2775 2776 // Extract the 2nd half and fall through to handle it as an f64 value. 2777 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2778 DAG.getConstant(1, dl, MVT::i32)); 2779 } 2780 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2781 // available. 2782 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2783 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2784 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2785 fmrrd.getValue(isLittleEndian ? 0 : 1), 2786 Flag); 2787 Flag = Chain.getValue(1); 2788 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2789 VA = RVLocs[++i]; // skip ahead to next loc 2790 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2791 fmrrd.getValue(isLittleEndian ? 1 : 0), 2792 Flag); 2793 } else 2794 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2795 2796 // Guarantee that all emitted copies are 2797 // stuck together, avoiding something bad. 2798 Flag = Chain.getValue(1); 2799 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2800 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2801 } 2802 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2803 const MCPhysReg *I = 2804 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2805 if (I) { 2806 for (; *I; ++I) { 2807 if (ARM::GPRRegClass.contains(*I)) 2808 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2809 else if (ARM::DPRRegClass.contains(*I)) 2810 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2811 else 2812 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2813 } 2814 } 2815 2816 // Update chain and glue. 2817 RetOps[0] = Chain; 2818 if (Flag.getNode()) 2819 RetOps.push_back(Flag); 2820 2821 // CPUs which aren't M-class use a special sequence to return from 2822 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2823 // though we use "subs pc, lr, #N"). 2824 // 2825 // M-class CPUs actually use a normal return sequence with a special 2826 // (hardware-provided) value in LR, so the normal code path works. 2827 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2828 !Subtarget->isMClass()) { 2829 if (Subtarget->isThumb1Only()) 2830 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2831 return LowerInterruptReturn(RetOps, dl, DAG); 2832 } 2833 2834 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2835 } 2836 2837 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2838 if (N->getNumValues() != 1) 2839 return false; 2840 if (!N->hasNUsesOfValue(1, 0)) 2841 return false; 2842 2843 SDValue TCChain = Chain; 2844 SDNode *Copy = *N->use_begin(); 2845 if (Copy->getOpcode() == ISD::CopyToReg) { 2846 // If the copy has a glue operand, we conservatively assume it isn't safe to 2847 // perform a tail call. 2848 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2849 return false; 2850 TCChain = Copy->getOperand(0); 2851 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2852 SDNode *VMov = Copy; 2853 // f64 returned in a pair of GPRs. 2854 SmallPtrSet<SDNode*, 2> Copies; 2855 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2856 UI != UE; ++UI) { 2857 if (UI->getOpcode() != ISD::CopyToReg) 2858 return false; 2859 Copies.insert(*UI); 2860 } 2861 if (Copies.size() > 2) 2862 return false; 2863 2864 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2865 UI != UE; ++UI) { 2866 SDValue UseChain = UI->getOperand(0); 2867 if (Copies.count(UseChain.getNode())) 2868 // Second CopyToReg 2869 Copy = *UI; 2870 else { 2871 // We are at the top of this chain. 2872 // If the copy has a glue operand, we conservatively assume it 2873 // isn't safe to perform a tail call. 2874 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2875 return false; 2876 // First CopyToReg 2877 TCChain = UseChain; 2878 } 2879 } 2880 } else if (Copy->getOpcode() == ISD::BITCAST) { 2881 // f32 returned in a single GPR. 2882 if (!Copy->hasOneUse()) 2883 return false; 2884 Copy = *Copy->use_begin(); 2885 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2886 return false; 2887 // If the copy has a glue operand, we conservatively assume it isn't safe to 2888 // perform a tail call. 2889 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2890 return false; 2891 TCChain = Copy->getOperand(0); 2892 } else { 2893 return false; 2894 } 2895 2896 bool HasRet = false; 2897 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2898 UI != UE; ++UI) { 2899 if (UI->getOpcode() != ARMISD::RET_FLAG && 2900 UI->getOpcode() != ARMISD::INTRET_FLAG) 2901 return false; 2902 HasRet = true; 2903 } 2904 2905 if (!HasRet) 2906 return false; 2907 2908 Chain = TCChain; 2909 return true; 2910 } 2911 2912 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2913 if (!Subtarget->supportsTailCall()) 2914 return false; 2915 2916 auto Attr = 2917 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2918 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2919 return false; 2920 2921 return true; 2922 } 2923 2924 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2925 // and pass the lower and high parts through. 2926 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2927 SDLoc DL(Op); 2928 SDValue WriteValue = Op->getOperand(2); 2929 2930 // This function is only supposed to be called for i64 type argument. 2931 assert(WriteValue.getValueType() == MVT::i64 2932 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2933 2934 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2935 DAG.getConstant(0, DL, MVT::i32)); 2936 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2937 DAG.getConstant(1, DL, MVT::i32)); 2938 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2939 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2940 } 2941 2942 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2943 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2944 // one of the above mentioned nodes. It has to be wrapped because otherwise 2945 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2946 // be used to form addressing mode. These wrapped nodes will be selected 2947 // into MOVi. 2948 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2949 SelectionDAG &DAG) const { 2950 EVT PtrVT = Op.getValueType(); 2951 // FIXME there is no actual debug info here 2952 SDLoc dl(Op); 2953 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2954 SDValue Res; 2955 2956 // When generating execute-only code Constant Pools must be promoted to the 2957 // global data section. It's a bit ugly that we can't share them across basic 2958 // blocks, but this way we guarantee that execute-only behaves correct with 2959 // position-independent addressing modes. 2960 if (Subtarget->genExecuteOnly()) { 2961 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2962 auto T = const_cast<Type*>(CP->getType()); 2963 auto C = const_cast<Constant*>(CP->getConstVal()); 2964 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2965 getFunction().getParent()); 2966 auto GV = new GlobalVariable( 2967 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 2968 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2969 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2970 Twine(AFI->createPICLabelUId()) 2971 ); 2972 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2973 dl, PtrVT); 2974 return LowerGlobalAddress(GA, DAG); 2975 } 2976 2977 if (CP->isMachineConstantPoolEntry()) 2978 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2979 CP->getAlignment()); 2980 else 2981 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2982 CP->getAlignment()); 2983 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2984 } 2985 2986 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2987 return MachineJumpTableInfo::EK_Inline; 2988 } 2989 2990 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2991 SelectionDAG &DAG) const { 2992 MachineFunction &MF = DAG.getMachineFunction(); 2993 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2994 unsigned ARMPCLabelIndex = 0; 2995 SDLoc DL(Op); 2996 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2997 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2998 SDValue CPAddr; 2999 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 3000 if (!IsPositionIndependent) { 3001 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 3002 } else { 3003 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3004 ARMPCLabelIndex = AFI->createPICLabelUId(); 3005 ARMConstantPoolValue *CPV = 3006 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3007 ARMCP::CPBlockAddress, PCAdj); 3008 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3009 } 3010 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3011 SDValue Result = DAG.getLoad( 3012 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3013 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3014 if (!IsPositionIndependent) 3015 return Result; 3016 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3017 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3018 } 3019 3020 /// Convert a TLS address reference into the correct sequence of loads 3021 /// and calls to compute the variable's address for Darwin, and return an 3022 /// SDValue containing the final node. 3023 3024 /// Darwin only has one TLS scheme which must be capable of dealing with the 3025 /// fully general situation, in the worst case. This means: 3026 /// + "extern __thread" declaration. 3027 /// + Defined in a possibly unknown dynamic library. 3028 /// 3029 /// The general system is that each __thread variable has a [3 x i32] descriptor 3030 /// which contains information used by the runtime to calculate the address. The 3031 /// only part of this the compiler needs to know about is the first word, which 3032 /// contains a function pointer that must be called with the address of the 3033 /// entire descriptor in "r0". 3034 /// 3035 /// Since this descriptor may be in a different unit, in general access must 3036 /// proceed along the usual ARM rules. A common sequence to produce is: 3037 /// 3038 /// movw rT1, :lower16:_var$non_lazy_ptr 3039 /// movt rT1, :upper16:_var$non_lazy_ptr 3040 /// ldr r0, [rT1] 3041 /// ldr rT2, [r0] 3042 /// blx rT2 3043 /// [...address now in r0...] 3044 SDValue 3045 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3046 SelectionDAG &DAG) const { 3047 assert(Subtarget->isTargetDarwin() && 3048 "This function expects a Darwin target"); 3049 SDLoc DL(Op); 3050 3051 // First step is to get the address of the actua global symbol. This is where 3052 // the TLS descriptor lives. 3053 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3054 3055 // The first entry in the descriptor is a function pointer that we must call 3056 // to obtain the address of the variable. 3057 SDValue Chain = DAG.getEntryNode(); 3058 SDValue FuncTLVGet = DAG.getLoad( 3059 MVT::i32, DL, Chain, DescAddr, 3060 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3061 /* Alignment = */ 4, 3062 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3063 MachineMemOperand::MOInvariant); 3064 Chain = FuncTLVGet.getValue(1); 3065 3066 MachineFunction &F = DAG.getMachineFunction(); 3067 MachineFrameInfo &MFI = F.getFrameInfo(); 3068 MFI.setAdjustsStack(true); 3069 3070 // TLS calls preserve all registers except those that absolutely must be 3071 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3072 // silly). 3073 auto TRI = 3074 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3075 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3076 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3077 3078 // Finally, we can make the call. This is just a degenerate version of a 3079 // normal AArch64 call node: r0 takes the address of the descriptor, and 3080 // returns the address of the variable in this thread. 3081 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3082 Chain = 3083 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3084 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3085 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3086 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3087 } 3088 3089 SDValue 3090 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3091 SelectionDAG &DAG) const { 3092 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3093 3094 SDValue Chain = DAG.getEntryNode(); 3095 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3096 SDLoc DL(Op); 3097 3098 // Load the current TEB (thread environment block) 3099 SDValue Ops[] = {Chain, 3100 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3101 DAG.getConstant(15, DL, MVT::i32), 3102 DAG.getConstant(0, DL, MVT::i32), 3103 DAG.getConstant(13, DL, MVT::i32), 3104 DAG.getConstant(0, DL, MVT::i32), 3105 DAG.getConstant(2, DL, MVT::i32)}; 3106 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3107 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3108 3109 SDValue TEB = CurrentTEB.getValue(0); 3110 Chain = CurrentTEB.getValue(1); 3111 3112 // Load the ThreadLocalStoragePointer from the TEB 3113 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3114 SDValue TLSArray = 3115 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3116 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3117 3118 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3119 // offset into the TLSArray. 3120 3121 // Load the TLS index from the C runtime 3122 SDValue TLSIndex = 3123 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3124 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3125 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3126 3127 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3128 DAG.getConstant(2, DL, MVT::i32)); 3129 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3130 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3131 MachinePointerInfo()); 3132 3133 // Get the offset of the start of the .tls section (section base) 3134 const auto *GA = cast<GlobalAddressSDNode>(Op); 3135 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3136 SDValue Offset = DAG.getLoad( 3137 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3138 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 3139 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3140 3141 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3142 } 3143 3144 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3145 SDValue 3146 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3147 SelectionDAG &DAG) const { 3148 SDLoc dl(GA); 3149 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3150 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3151 MachineFunction &MF = DAG.getMachineFunction(); 3152 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3153 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3154 ARMConstantPoolValue *CPV = 3155 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3156 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3157 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3158 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3159 Argument = DAG.getLoad( 3160 PtrVT, dl, DAG.getEntryNode(), Argument, 3161 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3162 SDValue Chain = Argument.getValue(1); 3163 3164 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3165 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3166 3167 // call __tls_get_addr. 3168 ArgListTy Args; 3169 ArgListEntry Entry; 3170 Entry.Node = Argument; 3171 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3172 Args.push_back(Entry); 3173 3174 // FIXME: is there useful debug info available here? 3175 TargetLowering::CallLoweringInfo CLI(DAG); 3176 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3177 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3178 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3179 3180 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3181 return CallResult.first; 3182 } 3183 3184 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3185 // "local exec" model. 3186 SDValue 3187 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3188 SelectionDAG &DAG, 3189 TLSModel::Model model) const { 3190 const GlobalValue *GV = GA->getGlobal(); 3191 SDLoc dl(GA); 3192 SDValue Offset; 3193 SDValue Chain = DAG.getEntryNode(); 3194 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3195 // Get the Thread Pointer 3196 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3197 3198 if (model == TLSModel::InitialExec) { 3199 MachineFunction &MF = DAG.getMachineFunction(); 3200 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3201 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3202 // Initial exec model. 3203 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3204 ARMConstantPoolValue *CPV = 3205 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3206 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3207 true); 3208 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3209 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3210 Offset = DAG.getLoad( 3211 PtrVT, dl, Chain, Offset, 3212 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3213 Chain = Offset.getValue(1); 3214 3215 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3216 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3217 3218 Offset = DAG.getLoad( 3219 PtrVT, dl, Chain, Offset, 3220 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3221 } else { 3222 // local exec model 3223 assert(model == TLSModel::LocalExec); 3224 ARMConstantPoolValue *CPV = 3225 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3226 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3227 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3228 Offset = DAG.getLoad( 3229 PtrVT, dl, Chain, Offset, 3230 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3231 } 3232 3233 // The address of the thread local variable is the add of the thread 3234 // pointer with the offset of the variable. 3235 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3236 } 3237 3238 SDValue 3239 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3240 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3241 if (DAG.getTarget().useEmulatedTLS()) 3242 return LowerToTLSEmulatedModel(GA, DAG); 3243 3244 if (Subtarget->isTargetDarwin()) 3245 return LowerGlobalTLSAddressDarwin(Op, DAG); 3246 3247 if (Subtarget->isTargetWindows()) 3248 return LowerGlobalTLSAddressWindows(Op, DAG); 3249 3250 // TODO: implement the "local dynamic" model 3251 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3252 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3253 3254 switch (model) { 3255 case TLSModel::GeneralDynamic: 3256 case TLSModel::LocalDynamic: 3257 return LowerToTLSGeneralDynamicModel(GA, DAG); 3258 case TLSModel::InitialExec: 3259 case TLSModel::LocalExec: 3260 return LowerToTLSExecModels(GA, DAG, model); 3261 } 3262 llvm_unreachable("bogus TLS model"); 3263 } 3264 3265 /// Return true if all users of V are within function F, looking through 3266 /// ConstantExprs. 3267 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3268 SmallVector<const User*,4> Worklist; 3269 for (auto *U : V->users()) 3270 Worklist.push_back(U); 3271 while (!Worklist.empty()) { 3272 auto *U = Worklist.pop_back_val(); 3273 if (isa<ConstantExpr>(U)) { 3274 for (auto *UU : U->users()) 3275 Worklist.push_back(UU); 3276 continue; 3277 } 3278 3279 auto *I = dyn_cast<Instruction>(U); 3280 if (!I || I->getParent()->getParent() != F) 3281 return false; 3282 } 3283 return true; 3284 } 3285 3286 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3287 const GlobalValue *GV, SelectionDAG &DAG, 3288 EVT PtrVT, const SDLoc &dl) { 3289 // If we're creating a pool entry for a constant global with unnamed address, 3290 // and the global is small enough, we can emit it inline into the constant pool 3291 // to save ourselves an indirection. 3292 // 3293 // This is a win if the constant is only used in one function (so it doesn't 3294 // need to be duplicated) or duplicating the constant wouldn't increase code 3295 // size (implying the constant is no larger than 4 bytes). 3296 const Function &F = DAG.getMachineFunction().getFunction(); 3297 3298 // We rely on this decision to inline being idemopotent and unrelated to the 3299 // use-site. We know that if we inline a variable at one use site, we'll 3300 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3301 // doesn't know about this optimization, so bail out if it's enabled else 3302 // we could decide to inline here (and thus never emit the GV) but require 3303 // the GV from fast-isel generated code. 3304 if (!EnableConstpoolPromotion || 3305 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3306 return SDValue(); 3307 3308 auto *GVar = dyn_cast<GlobalVariable>(GV); 3309 if (!GVar || !GVar->hasInitializer() || 3310 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3311 !GVar->hasLocalLinkage()) 3312 return SDValue(); 3313 3314 // If we inline a value that contains relocations, we move the relocations 3315 // from .data to .text. This is not allowed in position-independent code. 3316 auto *Init = GVar->getInitializer(); 3317 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3318 Init->needsRelocation()) 3319 return SDValue(); 3320 3321 // The constant islands pass can only really deal with alignment requests 3322 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3323 // any type wanting greater alignment requirements than 4 bytes. We also 3324 // can only promote constants that are multiples of 4 bytes in size or 3325 // are paddable to a multiple of 4. Currently we only try and pad constants 3326 // that are strings for simplicity. 3327 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3328 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3329 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3330 unsigned RequiredPadding = 4 - (Size % 4); 3331 bool PaddingPossible = 3332 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3333 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3334 Size == 0) 3335 return SDValue(); 3336 3337 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3338 MachineFunction &MF = DAG.getMachineFunction(); 3339 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3340 3341 // We can't bloat the constant pool too much, else the ConstantIslands pass 3342 // may fail to converge. If we haven't promoted this global yet (it may have 3343 // multiple uses), and promoting it would increase the constant pool size (Sz 3344 // > 4), ensure we have space to do so up to MaxTotal. 3345 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3346 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3347 ConstpoolPromotionMaxTotal) 3348 return SDValue(); 3349 3350 // This is only valid if all users are in a single function; we can't clone 3351 // the constant in general. The LLVM IR unnamed_addr allows merging 3352 // constants, but not cloning them. 3353 // 3354 // We could potentially allow cloning if we could prove all uses of the 3355 // constant in the current function don't care about the address, like 3356 // printf format strings. But that isn't implemented for now. 3357 if (!allUsersAreInFunction(GVar, &F)) 3358 return SDValue(); 3359 3360 // We're going to inline this global. Pad it out if needed. 3361 if (RequiredPadding != 4) { 3362 StringRef S = CDAInit->getAsString(); 3363 3364 SmallVector<uint8_t,16> V(S.size()); 3365 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3366 while (RequiredPadding--) 3367 V.push_back(0); 3368 Init = ConstantDataArray::get(*DAG.getContext(), V); 3369 } 3370 3371 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3372 SDValue CPAddr = 3373 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3374 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3375 AFI->markGlobalAsPromotedToConstantPool(GVar); 3376 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3377 PaddedSize - 4); 3378 } 3379 ++NumConstpoolPromoted; 3380 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3381 } 3382 3383 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3384 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3385 if (!(GV = GA->getBaseObject())) 3386 return false; 3387 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3388 return V->isConstant(); 3389 return isa<Function>(GV); 3390 } 3391 3392 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3393 SelectionDAG &DAG) const { 3394 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3395 default: llvm_unreachable("unknown object format"); 3396 case Triple::COFF: 3397 return LowerGlobalAddressWindows(Op, DAG); 3398 case Triple::ELF: 3399 return LowerGlobalAddressELF(Op, DAG); 3400 case Triple::MachO: 3401 return LowerGlobalAddressDarwin(Op, DAG); 3402 } 3403 } 3404 3405 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3406 SelectionDAG &DAG) const { 3407 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3408 SDLoc dl(Op); 3409 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3410 const TargetMachine &TM = getTargetMachine(); 3411 bool IsRO = isReadOnly(GV); 3412 3413 // promoteToConstantPool only if not generating XO text section 3414 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3415 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3416 return V; 3417 3418 if (isPositionIndependent()) { 3419 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3420 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3421 UseGOT_PREL ? ARMII::MO_GOT : 0); 3422 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3423 if (UseGOT_PREL) 3424 Result = 3425 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3426 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3427 return Result; 3428 } else if (Subtarget->isROPI() && IsRO) { 3429 // PC-relative. 3430 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3431 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3432 return Result; 3433 } else if (Subtarget->isRWPI() && !IsRO) { 3434 // SB-relative. 3435 SDValue RelAddr; 3436 if (Subtarget->useMovt()) { 3437 ++NumMovwMovt; 3438 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3439 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3440 } else { // use literal pool for address constant 3441 ARMConstantPoolValue *CPV = 3442 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3443 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3444 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3445 RelAddr = DAG.getLoad( 3446 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3447 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3448 } 3449 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3450 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3451 return Result; 3452 } 3453 3454 // If we have T2 ops, we can materialize the address directly via movt/movw 3455 // pair. This is always cheaper. 3456 if (Subtarget->useMovt()) { 3457 ++NumMovwMovt; 3458 // FIXME: Once remat is capable of dealing with instructions with register 3459 // operands, expand this into two nodes. 3460 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3461 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3462 } else { 3463 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3464 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3465 return DAG.getLoad( 3466 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3467 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3468 } 3469 } 3470 3471 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3472 SelectionDAG &DAG) const { 3473 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3474 "ROPI/RWPI not currently supported for Darwin"); 3475 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3476 SDLoc dl(Op); 3477 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3478 3479 if (Subtarget->useMovt()) 3480 ++NumMovwMovt; 3481 3482 // FIXME: Once remat is capable of dealing with instructions with register 3483 // operands, expand this into multiple nodes 3484 unsigned Wrapper = 3485 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3486 3487 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3488 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3489 3490 if (Subtarget->isGVIndirectSymbol(GV)) 3491 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3492 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3493 return Result; 3494 } 3495 3496 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3497 SelectionDAG &DAG) const { 3498 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3499 assert(Subtarget->useMovt() && 3500 "Windows on ARM expects to use movw/movt"); 3501 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3502 "ROPI/RWPI not currently supported for Windows"); 3503 3504 const TargetMachine &TM = getTargetMachine(); 3505 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3506 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3507 if (GV->hasDLLImportStorageClass()) 3508 TargetFlags = ARMII::MO_DLLIMPORT; 3509 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3510 TargetFlags = ARMII::MO_COFFSTUB; 3511 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3512 SDValue Result; 3513 SDLoc DL(Op); 3514 3515 ++NumMovwMovt; 3516 3517 // FIXME: Once remat is capable of dealing with instructions with register 3518 // operands, expand this into two nodes. 3519 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3520 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3521 TargetFlags)); 3522 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3523 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3524 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3525 return Result; 3526 } 3527 3528 SDValue 3529 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3530 SDLoc dl(Op); 3531 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3532 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3533 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3534 Op.getOperand(1), Val); 3535 } 3536 3537 SDValue 3538 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3539 SDLoc dl(Op); 3540 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3541 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3542 } 3543 3544 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3545 SelectionDAG &DAG) const { 3546 SDLoc dl(Op); 3547 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3548 Op.getOperand(0)); 3549 } 3550 3551 SDValue ARMTargetLowering::LowerINTRINSIC_VOID( 3552 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const { 3553 unsigned IntNo = 3554 cast<ConstantSDNode>( 3555 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other)) 3556 ->getZExtValue(); 3557 switch (IntNo) { 3558 default: 3559 return SDValue(); // Don't custom lower most intrinsics. 3560 case Intrinsic::arm_gnu_eabi_mcount: { 3561 MachineFunction &MF = DAG.getMachineFunction(); 3562 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3563 SDLoc dl(Op); 3564 SDValue Chain = Op.getOperand(0); 3565 // call "\01__gnu_mcount_nc" 3566 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 3567 const uint32_t *Mask = 3568 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C); 3569 assert(Mask && "Missing call preserved mask for calling convention"); 3570 // Mark LR an implicit live-in. 3571 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3572 SDValue ReturnAddress = 3573 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT); 3574 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue}; 3575 SDValue Callee = 3576 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0); 3577 SDValue RegisterMask = DAG.getRegisterMask(Mask); 3578 if (Subtarget->isThumb()) 3579 return SDValue( 3580 DAG.getMachineNode( 3581 ARM::tBL_PUSHLR, dl, ResultTys, 3582 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT), 3583 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}), 3584 0); 3585 return SDValue( 3586 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys, 3587 {ReturnAddress, Callee, RegisterMask, Chain}), 3588 0); 3589 } 3590 } 3591 } 3592 3593 SDValue 3594 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3595 const ARMSubtarget *Subtarget) const { 3596 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3597 SDLoc dl(Op); 3598 switch (IntNo) { 3599 default: return SDValue(); // Don't custom lower most intrinsics. 3600 case Intrinsic::thread_pointer: { 3601 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3602 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3603 } 3604 case Intrinsic::eh_sjlj_lsda: { 3605 MachineFunction &MF = DAG.getMachineFunction(); 3606 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3607 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3608 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3609 SDValue CPAddr; 3610 bool IsPositionIndependent = isPositionIndependent(); 3611 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3612 ARMConstantPoolValue *CPV = 3613 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3614 ARMCP::CPLSDA, PCAdj); 3615 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3616 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3617 SDValue Result = DAG.getLoad( 3618 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3619 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3620 3621 if (IsPositionIndependent) { 3622 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3623 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3624 } 3625 return Result; 3626 } 3627 case Intrinsic::arm_neon_vabs: 3628 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3629 Op.getOperand(1)); 3630 case Intrinsic::arm_neon_vmulls: 3631 case Intrinsic::arm_neon_vmullu: { 3632 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3633 ? ARMISD::VMULLs : ARMISD::VMULLu; 3634 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3635 Op.getOperand(1), Op.getOperand(2)); 3636 } 3637 case Intrinsic::arm_neon_vminnm: 3638 case Intrinsic::arm_neon_vmaxnm: { 3639 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3640 ? ISD::FMINNUM : ISD::FMAXNUM; 3641 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3642 Op.getOperand(1), Op.getOperand(2)); 3643 } 3644 case Intrinsic::arm_neon_vminu: 3645 case Intrinsic::arm_neon_vmaxu: { 3646 if (Op.getValueType().isFloatingPoint()) 3647 return SDValue(); 3648 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3649 ? ISD::UMIN : ISD::UMAX; 3650 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3651 Op.getOperand(1), Op.getOperand(2)); 3652 } 3653 case Intrinsic::arm_neon_vmins: 3654 case Intrinsic::arm_neon_vmaxs: { 3655 // v{min,max}s is overloaded between signed integers and floats. 3656 if (!Op.getValueType().isFloatingPoint()) { 3657 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3658 ? ISD::SMIN : ISD::SMAX; 3659 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3660 Op.getOperand(1), Op.getOperand(2)); 3661 } 3662 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3663 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3664 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3665 Op.getOperand(1), Op.getOperand(2)); 3666 } 3667 case Intrinsic::arm_neon_vtbl1: 3668 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3669 Op.getOperand(1), Op.getOperand(2)); 3670 case Intrinsic::arm_neon_vtbl2: 3671 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3672 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3673 } 3674 } 3675 3676 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3677 const ARMSubtarget *Subtarget) { 3678 SDLoc dl(Op); 3679 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3680 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3681 if (SSID == SyncScope::SingleThread) 3682 return Op; 3683 3684 if (!Subtarget->hasDataBarrier()) { 3685 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3686 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3687 // here. 3688 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3689 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3690 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3691 DAG.getConstant(0, dl, MVT::i32)); 3692 } 3693 3694 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3695 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3696 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3697 if (Subtarget->isMClass()) { 3698 // Only a full system barrier exists in the M-class architectures. 3699 Domain = ARM_MB::SY; 3700 } else if (Subtarget->preferISHSTBarriers() && 3701 Ord == AtomicOrdering::Release) { 3702 // Swift happens to implement ISHST barriers in a way that's compatible with 3703 // Release semantics but weaker than ISH so we'd be fools not to use 3704 // it. Beware: other processors probably don't! 3705 Domain = ARM_MB::ISHST; 3706 } 3707 3708 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3709 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3710 DAG.getConstant(Domain, dl, MVT::i32)); 3711 } 3712 3713 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3714 const ARMSubtarget *Subtarget) { 3715 // ARM pre v5TE and Thumb1 does not have preload instructions. 3716 if (!(Subtarget->isThumb2() || 3717 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3718 // Just preserve the chain. 3719 return Op.getOperand(0); 3720 3721 SDLoc dl(Op); 3722 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3723 if (!isRead && 3724 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3725 // ARMv7 with MP extension has PLDW. 3726 return Op.getOperand(0); 3727 3728 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3729 if (Subtarget->isThumb()) { 3730 // Invert the bits. 3731 isRead = ~isRead & 1; 3732 isData = ~isData & 1; 3733 } 3734 3735 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3736 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3737 DAG.getConstant(isData, dl, MVT::i32)); 3738 } 3739 3740 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3741 MachineFunction &MF = DAG.getMachineFunction(); 3742 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3743 3744 // vastart just stores the address of the VarArgsFrameIndex slot into the 3745 // memory location argument. 3746 SDLoc dl(Op); 3747 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3748 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3749 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3750 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3751 MachinePointerInfo(SV)); 3752 } 3753 3754 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3755 CCValAssign &NextVA, 3756 SDValue &Root, 3757 SelectionDAG &DAG, 3758 const SDLoc &dl) const { 3759 MachineFunction &MF = DAG.getMachineFunction(); 3760 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3761 3762 const TargetRegisterClass *RC; 3763 if (AFI->isThumb1OnlyFunction()) 3764 RC = &ARM::tGPRRegClass; 3765 else 3766 RC = &ARM::GPRRegClass; 3767 3768 // Transform the arguments stored in physical registers into virtual ones. 3769 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3770 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3771 3772 SDValue ArgValue2; 3773 if (NextVA.isMemLoc()) { 3774 MachineFrameInfo &MFI = MF.getFrameInfo(); 3775 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3776 3777 // Create load node to retrieve arguments from the stack. 3778 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3779 ArgValue2 = DAG.getLoad( 3780 MVT::i32, dl, Root, FIN, 3781 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3782 } else { 3783 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3784 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3785 } 3786 if (!Subtarget->isLittle()) 3787 std::swap (ArgValue, ArgValue2); 3788 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3789 } 3790 3791 // The remaining GPRs hold either the beginning of variable-argument 3792 // data, or the beginning of an aggregate passed by value (usually 3793 // byval). Either way, we allocate stack slots adjacent to the data 3794 // provided by our caller, and store the unallocated registers there. 3795 // If this is a variadic function, the va_list pointer will begin with 3796 // these values; otherwise, this reassembles a (byval) structure that 3797 // was split between registers and memory. 3798 // Return: The frame index registers were stored into. 3799 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3800 const SDLoc &dl, SDValue &Chain, 3801 const Value *OrigArg, 3802 unsigned InRegsParamRecordIdx, 3803 int ArgOffset, unsigned ArgSize) const { 3804 // Currently, two use-cases possible: 3805 // Case #1. Non-var-args function, and we meet first byval parameter. 3806 // Setup first unallocated register as first byval register; 3807 // eat all remained registers 3808 // (these two actions are performed by HandleByVal method). 3809 // Then, here, we initialize stack frame with 3810 // "store-reg" instructions. 3811 // Case #2. Var-args function, that doesn't contain byval parameters. 3812 // The same: eat all remained unallocated registers, 3813 // initialize stack frame. 3814 3815 MachineFunction &MF = DAG.getMachineFunction(); 3816 MachineFrameInfo &MFI = MF.getFrameInfo(); 3817 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3818 unsigned RBegin, REnd; 3819 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3820 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3821 } else { 3822 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3823 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3824 REnd = ARM::R4; 3825 } 3826 3827 if (REnd != RBegin) 3828 ArgOffset = -4 * (ARM::R4 - RBegin); 3829 3830 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3831 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3832 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3833 3834 SmallVector<SDValue, 4> MemOps; 3835 const TargetRegisterClass *RC = 3836 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3837 3838 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3839 unsigned VReg = MF.addLiveIn(Reg, RC); 3840 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3841 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3842 MachinePointerInfo(OrigArg, 4 * i)); 3843 MemOps.push_back(Store); 3844 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3845 } 3846 3847 if (!MemOps.empty()) 3848 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3849 return FrameIndex; 3850 } 3851 3852 // Setup stack frame, the va_list pointer will start from. 3853 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3854 const SDLoc &dl, SDValue &Chain, 3855 unsigned ArgOffset, 3856 unsigned TotalArgRegsSaveSize, 3857 bool ForceMutable) const { 3858 MachineFunction &MF = DAG.getMachineFunction(); 3859 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3860 3861 // Try to store any remaining integer argument regs 3862 // to their spots on the stack so that they may be loaded by dereferencing 3863 // the result of va_next. 3864 // If there is no regs to be stored, just point address after last 3865 // argument passed via stack. 3866 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3867 CCInfo.getInRegsParamsCount(), 3868 CCInfo.getNextStackOffset(), 3869 std::max(4U, TotalArgRegsSaveSize)); 3870 AFI->setVarArgsFrameIndex(FrameIndex); 3871 } 3872 3873 SDValue ARMTargetLowering::LowerFormalArguments( 3874 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3875 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3876 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3877 MachineFunction &MF = DAG.getMachineFunction(); 3878 MachineFrameInfo &MFI = MF.getFrameInfo(); 3879 3880 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3881 3882 // Assign locations to all of the incoming arguments. 3883 SmallVector<CCValAssign, 16> ArgLocs; 3884 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3885 *DAG.getContext()); 3886 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3887 3888 SmallVector<SDValue, 16> ArgValues; 3889 SDValue ArgValue; 3890 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3891 unsigned CurArgIdx = 0; 3892 3893 // Initially ArgRegsSaveSize is zero. 3894 // Then we increase this value each time we meet byval parameter. 3895 // We also increase this value in case of varargs function. 3896 AFI->setArgRegsSaveSize(0); 3897 3898 // Calculate the amount of stack space that we need to allocate to store 3899 // byval and variadic arguments that are passed in registers. 3900 // We need to know this before we allocate the first byval or variadic 3901 // argument, as they will be allocated a stack slot below the CFA (Canonical 3902 // Frame Address, the stack pointer at entry to the function). 3903 unsigned ArgRegBegin = ARM::R4; 3904 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3905 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3906 break; 3907 3908 CCValAssign &VA = ArgLocs[i]; 3909 unsigned Index = VA.getValNo(); 3910 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3911 if (!Flags.isByVal()) 3912 continue; 3913 3914 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3915 unsigned RBegin, REnd; 3916 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3917 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3918 3919 CCInfo.nextInRegsParam(); 3920 } 3921 CCInfo.rewindByValRegsInfo(); 3922 3923 int lastInsIndex = -1; 3924 if (isVarArg && MFI.hasVAStart()) { 3925 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3926 if (RegIdx != array_lengthof(GPRArgRegs)) 3927 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3928 } 3929 3930 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3931 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3932 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3933 3934 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3935 CCValAssign &VA = ArgLocs[i]; 3936 if (Ins[VA.getValNo()].isOrigArg()) { 3937 std::advance(CurOrigArg, 3938 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3939 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3940 } 3941 // Arguments stored in registers. 3942 if (VA.isRegLoc()) { 3943 EVT RegVT = VA.getLocVT(); 3944 3945 if (VA.needsCustom()) { 3946 // f64 and vector types are split up into multiple registers or 3947 // combinations of registers and stack slots. 3948 if (VA.getLocVT() == MVT::v2f64) { 3949 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3950 Chain, DAG, dl); 3951 VA = ArgLocs[++i]; // skip ahead to next loc 3952 SDValue ArgValue2; 3953 if (VA.isMemLoc()) { 3954 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3955 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3956 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3957 MachinePointerInfo::getFixedStack( 3958 DAG.getMachineFunction(), FI)); 3959 } else { 3960 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3961 Chain, DAG, dl); 3962 } 3963 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3964 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3965 ArgValue, ArgValue1, 3966 DAG.getIntPtrConstant(0, dl)); 3967 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3968 ArgValue, ArgValue2, 3969 DAG.getIntPtrConstant(1, dl)); 3970 } else 3971 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3972 } else { 3973 const TargetRegisterClass *RC; 3974 3975 3976 if (RegVT == MVT::f16) 3977 RC = &ARM::HPRRegClass; 3978 else if (RegVT == MVT::f32) 3979 RC = &ARM::SPRRegClass; 3980 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3981 RC = &ARM::DPRRegClass; 3982 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3983 RC = &ARM::QPRRegClass; 3984 else if (RegVT == MVT::i32) 3985 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3986 : &ARM::GPRRegClass; 3987 else 3988 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3989 3990 // Transform the arguments in physical registers into virtual ones. 3991 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3992 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3993 3994 // If this value is passed in r0 and has the returned attribute (e.g. 3995 // C++ 'structors), record this fact for later use. 3996 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 3997 AFI->setPreservesR0(); 3998 } 3999 } 4000 4001 // If this is an 8 or 16-bit value, it is really passed promoted 4002 // to 32 bits. Insert an assert[sz]ext to capture this, then 4003 // truncate to the right size. 4004 switch (VA.getLocInfo()) { 4005 default: llvm_unreachable("Unknown loc info!"); 4006 case CCValAssign::Full: break; 4007 case CCValAssign::BCvt: 4008 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 4009 break; 4010 case CCValAssign::SExt: 4011 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 4012 DAG.getValueType(VA.getValVT())); 4013 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4014 break; 4015 case CCValAssign::ZExt: 4016 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 4017 DAG.getValueType(VA.getValVT())); 4018 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 4019 break; 4020 } 4021 4022 InVals.push_back(ArgValue); 4023 } else { // VA.isRegLoc() 4024 // sanity check 4025 assert(VA.isMemLoc()); 4026 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 4027 4028 int index = VA.getValNo(); 4029 4030 // Some Ins[] entries become multiple ArgLoc[] entries. 4031 // Process them only once. 4032 if (index != lastInsIndex) 4033 { 4034 ISD::ArgFlagsTy Flags = Ins[index].Flags; 4035 // FIXME: For now, all byval parameter objects are marked mutable. 4036 // This can be changed with more analysis. 4037 // In case of tail call optimization mark all arguments mutable. 4038 // Since they could be overwritten by lowering of arguments in case of 4039 // a tail call. 4040 if (Flags.isByVal()) { 4041 assert(Ins[index].isOrigArg() && 4042 "Byval arguments cannot be implicit"); 4043 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 4044 4045 int FrameIndex = StoreByValRegs( 4046 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4047 VA.getLocMemOffset(), Flags.getByValSize()); 4048 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4049 CCInfo.nextInRegsParam(); 4050 } else { 4051 unsigned FIOffset = VA.getLocMemOffset(); 4052 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4053 FIOffset, true); 4054 4055 // Create load nodes to retrieve arguments from the stack. 4056 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4057 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4058 MachinePointerInfo::getFixedStack( 4059 DAG.getMachineFunction(), FI))); 4060 } 4061 lastInsIndex = index; 4062 } 4063 } 4064 } 4065 4066 // varargs 4067 if (isVarArg && MFI.hasVAStart()) 4068 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 4069 CCInfo.getNextStackOffset(), 4070 TotalArgRegsSaveSize); 4071 4072 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4073 4074 return Chain; 4075 } 4076 4077 /// isFloatingPointZero - Return true if this is +0.0. 4078 static bool isFloatingPointZero(SDValue Op) { 4079 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4080 return CFP->getValueAPF().isPosZero(); 4081 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4082 // Maybe this has already been legalized into the constant pool? 4083 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4084 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4085 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4086 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4087 return CFP->getValueAPF().isPosZero(); 4088 } 4089 } else if (Op->getOpcode() == ISD::BITCAST && 4090 Op->getValueType(0) == MVT::f64) { 4091 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4092 // created by LowerConstantFP(). 4093 SDValue BitcastOp = Op->getOperand(0); 4094 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4095 isNullConstant(BitcastOp->getOperand(0))) 4096 return true; 4097 } 4098 return false; 4099 } 4100 4101 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4102 /// the given operands. 4103 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4104 SDValue &ARMcc, SelectionDAG &DAG, 4105 const SDLoc &dl) const { 4106 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4107 unsigned C = RHSC->getZExtValue(); 4108 if (!isLegalICmpImmediate((int32_t)C)) { 4109 // Constant does not fit, try adjusting it by one. 4110 switch (CC) { 4111 default: break; 4112 case ISD::SETLT: 4113 case ISD::SETGE: 4114 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4115 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4116 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4117 } 4118 break; 4119 case ISD::SETULT: 4120 case ISD::SETUGE: 4121 if (C != 0 && isLegalICmpImmediate(C-1)) { 4122 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4123 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4124 } 4125 break; 4126 case ISD::SETLE: 4127 case ISD::SETGT: 4128 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4129 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4130 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4131 } 4132 break; 4133 case ISD::SETULE: 4134 case ISD::SETUGT: 4135 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4136 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4137 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4138 } 4139 break; 4140 } 4141 } 4142 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4143 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4144 // In ARM and Thumb-2, the compare instructions can shift their second 4145 // operand. 4146 CC = ISD::getSetCCSwappedOperands(CC); 4147 std::swap(LHS, RHS); 4148 } 4149 4150 // Thumb1 has very limited immediate modes, so turning an "and" into a 4151 // shift can save multiple instructions. 4152 // 4153 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4154 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4155 // own. If it's the operand to an unsigned comparison with an immediate, 4156 // we can eliminate one of the shifts: we transform 4157 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4158 // 4159 // We avoid transforming cases which aren't profitable due to encoding 4160 // details: 4161 // 4162 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4163 // would not; in that case, we're essentially trading one immediate load for 4164 // another. 4165 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4166 // 3. C2 is zero; we have other code for this special case. 4167 // 4168 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4169 // instruction, since the AND is always one instruction anyway, but we could 4170 // use narrow instructions in some cases. 4171 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4172 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4173 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4174 !isSignedIntSetCC(CC)) { 4175 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4176 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4177 uint64_t RHSV = RHSC->getZExtValue(); 4178 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4179 unsigned ShiftBits = countLeadingZeros(Mask); 4180 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4181 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4182 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4183 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4184 } 4185 } 4186 } 4187 4188 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4189 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4190 // way a cmp would. 4191 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4192 // some tweaks to the heuristics for the previous and->shift transform. 4193 // FIXME: Optimize cases where the LHS isn't a shift. 4194 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4195 isa<ConstantSDNode>(RHS) && 4196 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4197 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4198 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4199 unsigned ShiftAmt = 4200 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4201 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4202 DAG.getVTList(MVT::i32, MVT::i32), 4203 LHS.getOperand(0), 4204 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4205 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4206 Shift.getValue(1), SDValue()); 4207 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4208 return Chain.getValue(1); 4209 } 4210 4211 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4212 4213 // If the RHS is a constant zero then the V (overflow) flag will never be 4214 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4215 // simpler for other passes (like the peephole optimiser) to deal with. 4216 if (isNullConstant(RHS)) { 4217 switch (CondCode) { 4218 default: break; 4219 case ARMCC::GE: 4220 CondCode = ARMCC::PL; 4221 break; 4222 case ARMCC::LT: 4223 CondCode = ARMCC::MI; 4224 break; 4225 } 4226 } 4227 4228 ARMISD::NodeType CompareType; 4229 switch (CondCode) { 4230 default: 4231 CompareType = ARMISD::CMP; 4232 break; 4233 case ARMCC::EQ: 4234 case ARMCC::NE: 4235 // Uses only Z Flag 4236 CompareType = ARMISD::CMPZ; 4237 break; 4238 } 4239 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4240 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4241 } 4242 4243 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4244 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4245 SelectionDAG &DAG, const SDLoc &dl, 4246 bool InvalidOnQNaN) const { 4247 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4248 SDValue Cmp; 4249 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 4250 if (!isFloatingPointZero(RHS)) 4251 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 4252 else 4253 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 4254 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4255 } 4256 4257 /// duplicateCmp - Glue values can have only one use, so this function 4258 /// duplicates a comparison node. 4259 SDValue 4260 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4261 unsigned Opc = Cmp.getOpcode(); 4262 SDLoc DL(Cmp); 4263 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4264 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4265 4266 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4267 Cmp = Cmp.getOperand(0); 4268 Opc = Cmp.getOpcode(); 4269 if (Opc == ARMISD::CMPFP) 4270 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4271 Cmp.getOperand(1), Cmp.getOperand(2)); 4272 else { 4273 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4274 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4275 Cmp.getOperand(1)); 4276 } 4277 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4278 } 4279 4280 // This function returns three things: the arithmetic computation itself 4281 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4282 // comparison and the condition code define the case in which the arithmetic 4283 // computation *does not* overflow. 4284 std::pair<SDValue, SDValue> 4285 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4286 SDValue &ARMcc) const { 4287 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4288 4289 SDValue Value, OverflowCmp; 4290 SDValue LHS = Op.getOperand(0); 4291 SDValue RHS = Op.getOperand(1); 4292 SDLoc dl(Op); 4293 4294 // FIXME: We are currently always generating CMPs because we don't support 4295 // generating CMN through the backend. This is not as good as the natural 4296 // CMP case because it causes a register dependency and cannot be folded 4297 // later. 4298 4299 switch (Op.getOpcode()) { 4300 default: 4301 llvm_unreachable("Unknown overflow instruction!"); 4302 case ISD::SADDO: 4303 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4304 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4305 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4306 break; 4307 case ISD::UADDO: 4308 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4309 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4310 // We do not use it in the USUBO case as Value may not be used. 4311 Value = DAG.getNode(ARMISD::ADDC, dl, 4312 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4313 .getValue(0); 4314 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4315 break; 4316 case ISD::SSUBO: 4317 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4318 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4319 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4320 break; 4321 case ISD::USUBO: 4322 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4323 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4324 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4325 break; 4326 case ISD::UMULO: 4327 // We generate a UMUL_LOHI and then check if the high word is 0. 4328 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4329 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4330 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4331 LHS, RHS); 4332 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4333 DAG.getConstant(0, dl, MVT::i32)); 4334 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4335 break; 4336 case ISD::SMULO: 4337 // We generate a SMUL_LOHI and then check if all the bits of the high word 4338 // are the same as the sign bit of the low word. 4339 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4340 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4341 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4342 LHS, RHS); 4343 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4344 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4345 Value.getValue(0), 4346 DAG.getConstant(31, dl, MVT::i32))); 4347 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4348 break; 4349 } // switch (...) 4350 4351 return std::make_pair(Value, OverflowCmp); 4352 } 4353 4354 SDValue 4355 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4356 // Let legalize expand this if it isn't a legal type yet. 4357 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4358 return SDValue(); 4359 4360 SDValue Value, OverflowCmp; 4361 SDValue ARMcc; 4362 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4363 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4364 SDLoc dl(Op); 4365 // We use 0 and 1 as false and true values. 4366 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4367 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4368 EVT VT = Op.getValueType(); 4369 4370 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4371 ARMcc, CCR, OverflowCmp); 4372 4373 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4374 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4375 } 4376 4377 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4378 SelectionDAG &DAG) { 4379 SDLoc DL(BoolCarry); 4380 EVT CarryVT = BoolCarry.getValueType(); 4381 4382 // This converts the boolean value carry into the carry flag by doing 4383 // ARMISD::SUBC Carry, 1 4384 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4385 DAG.getVTList(CarryVT, MVT::i32), 4386 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4387 return Carry.getValue(1); 4388 } 4389 4390 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4391 SelectionDAG &DAG) { 4392 SDLoc DL(Flags); 4393 4394 // Now convert the carry flag into a boolean carry. We do this 4395 // using ARMISD:ADDE 0, 0, Carry 4396 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4397 DAG.getConstant(0, DL, MVT::i32), 4398 DAG.getConstant(0, DL, MVT::i32), Flags); 4399 } 4400 4401 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4402 SelectionDAG &DAG) const { 4403 // Let legalize expand this if it isn't a legal type yet. 4404 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4405 return SDValue(); 4406 4407 SDValue LHS = Op.getOperand(0); 4408 SDValue RHS = Op.getOperand(1); 4409 SDLoc dl(Op); 4410 4411 EVT VT = Op.getValueType(); 4412 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4413 SDValue Value; 4414 SDValue Overflow; 4415 switch (Op.getOpcode()) { 4416 default: 4417 llvm_unreachable("Unknown overflow instruction!"); 4418 case ISD::UADDO: 4419 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4420 // Convert the carry flag into a boolean value. 4421 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4422 break; 4423 case ISD::USUBO: { 4424 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4425 // Convert the carry flag into a boolean value. 4426 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4427 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4428 // value. So compute 1 - C. 4429 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4430 DAG.getConstant(1, dl, MVT::i32), Overflow); 4431 break; 4432 } 4433 } 4434 4435 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4436 } 4437 4438 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4439 SDValue Cond = Op.getOperand(0); 4440 SDValue SelectTrue = Op.getOperand(1); 4441 SDValue SelectFalse = Op.getOperand(2); 4442 SDLoc dl(Op); 4443 unsigned Opc = Cond.getOpcode(); 4444 4445 if (Cond.getResNo() == 1 && 4446 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4447 Opc == ISD::USUBO)) { 4448 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4449 return SDValue(); 4450 4451 SDValue Value, OverflowCmp; 4452 SDValue ARMcc; 4453 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4454 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4455 EVT VT = Op.getValueType(); 4456 4457 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4458 OverflowCmp, DAG); 4459 } 4460 4461 // Convert: 4462 // 4463 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4464 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4465 // 4466 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4467 const ConstantSDNode *CMOVTrue = 4468 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4469 const ConstantSDNode *CMOVFalse = 4470 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4471 4472 if (CMOVTrue && CMOVFalse) { 4473 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4474 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4475 4476 SDValue True; 4477 SDValue False; 4478 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4479 True = SelectTrue; 4480 False = SelectFalse; 4481 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4482 True = SelectFalse; 4483 False = SelectTrue; 4484 } 4485 4486 if (True.getNode() && False.getNode()) { 4487 EVT VT = Op.getValueType(); 4488 SDValue ARMcc = Cond.getOperand(2); 4489 SDValue CCR = Cond.getOperand(3); 4490 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4491 assert(True.getValueType() == VT); 4492 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4493 } 4494 } 4495 } 4496 4497 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4498 // undefined bits before doing a full-word comparison with zero. 4499 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4500 DAG.getConstant(1, dl, Cond.getValueType())); 4501 4502 return DAG.getSelectCC(dl, Cond, 4503 DAG.getConstant(0, dl, Cond.getValueType()), 4504 SelectTrue, SelectFalse, ISD::SETNE); 4505 } 4506 4507 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4508 bool &swpCmpOps, bool &swpVselOps) { 4509 // Start by selecting the GE condition code for opcodes that return true for 4510 // 'equality' 4511 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4512 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4513 CondCode = ARMCC::GE; 4514 4515 // and GT for opcodes that return false for 'equality'. 4516 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4517 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4518 CondCode = ARMCC::GT; 4519 4520 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4521 // to swap the compare operands. 4522 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4523 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4524 swpCmpOps = true; 4525 4526 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4527 // If we have an unordered opcode, we need to swap the operands to the VSEL 4528 // instruction (effectively negating the condition). 4529 // 4530 // This also has the effect of swapping which one of 'less' or 'greater' 4531 // returns true, so we also swap the compare operands. It also switches 4532 // whether we return true for 'equality', so we compensate by picking the 4533 // opposite condition code to our original choice. 4534 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4535 CC == ISD::SETUGT) { 4536 swpCmpOps = !swpCmpOps; 4537 swpVselOps = !swpVselOps; 4538 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4539 } 4540 4541 // 'ordered' is 'anything but unordered', so use the VS condition code and 4542 // swap the VSEL operands. 4543 if (CC == ISD::SETO) { 4544 CondCode = ARMCC::VS; 4545 swpVselOps = true; 4546 } 4547 4548 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4549 // code and swap the VSEL operands. Also do this if we don't care about the 4550 // unordered case. 4551 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4552 CondCode = ARMCC::EQ; 4553 swpVselOps = true; 4554 } 4555 } 4556 4557 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4558 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4559 SDValue Cmp, SelectionDAG &DAG) const { 4560 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4561 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4562 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4563 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4564 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4565 4566 SDValue TrueLow = TrueVal.getValue(0); 4567 SDValue TrueHigh = TrueVal.getValue(1); 4568 SDValue FalseLow = FalseVal.getValue(0); 4569 SDValue FalseHigh = FalseVal.getValue(1); 4570 4571 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4572 ARMcc, CCR, Cmp); 4573 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4574 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4575 4576 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4577 } else { 4578 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4579 Cmp); 4580 } 4581 } 4582 4583 static bool isGTorGE(ISD::CondCode CC) { 4584 return CC == ISD::SETGT || CC == ISD::SETGE; 4585 } 4586 4587 static bool isLTorLE(ISD::CondCode CC) { 4588 return CC == ISD::SETLT || CC == ISD::SETLE; 4589 } 4590 4591 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4592 // All of these conditions (and their <= and >= counterparts) will do: 4593 // x < k ? k : x 4594 // x > k ? x : k 4595 // k < x ? x : k 4596 // k > x ? k : x 4597 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4598 const SDValue TrueVal, const SDValue FalseVal, 4599 const ISD::CondCode CC, const SDValue K) { 4600 return (isGTorGE(CC) && 4601 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4602 (isLTorLE(CC) && 4603 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4604 } 4605 4606 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4607 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4608 const SDValue TrueVal, const SDValue FalseVal, 4609 const ISD::CondCode CC, const SDValue K) { 4610 return (isGTorGE(CC) && 4611 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4612 (isLTorLE(CC) && 4613 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4614 } 4615 4616 // Check if two chained conditionals could be converted into SSAT or USAT. 4617 // 4618 // SSAT can replace a set of two conditional selectors that bound a number to an 4619 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4620 // 4621 // x < -k ? -k : (x > k ? k : x) 4622 // x < -k ? -k : (x < k ? x : k) 4623 // x > -k ? (x > k ? k : x) : -k 4624 // x < k ? (x < -k ? -k : x) : k 4625 // etc. 4626 // 4627 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4628 // a power of 2. 4629 // 4630 // It returns true if the conversion can be done, false otherwise. 4631 // Additionally, the variable is returned in parameter V, the constant in K and 4632 // usat is set to true if the conditional represents an unsigned saturation 4633 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4634 uint64_t &K, bool &usat) { 4635 SDValue LHS1 = Op.getOperand(0); 4636 SDValue RHS1 = Op.getOperand(1); 4637 SDValue TrueVal1 = Op.getOperand(2); 4638 SDValue FalseVal1 = Op.getOperand(3); 4639 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4640 4641 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4642 if (Op2.getOpcode() != ISD::SELECT_CC) 4643 return false; 4644 4645 SDValue LHS2 = Op2.getOperand(0); 4646 SDValue RHS2 = Op2.getOperand(1); 4647 SDValue TrueVal2 = Op2.getOperand(2); 4648 SDValue FalseVal2 = Op2.getOperand(3); 4649 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4650 4651 // Find out which are the constants and which are the variables 4652 // in each conditional 4653 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4654 ? &RHS1 4655 : nullptr; 4656 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4657 ? &RHS2 4658 : nullptr; 4659 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4660 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4661 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4662 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4663 4664 // We must detect cases where the original operations worked with 16- or 4665 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4666 // must work with sign-extended values but the select operations return 4667 // the original non-extended value. 4668 SDValue V2TmpReg = V2Tmp; 4669 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4670 V2TmpReg = V2Tmp->getOperand(0); 4671 4672 // Check that the registers and the constants have the correct values 4673 // in both conditionals 4674 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4675 V2TmpReg != V2) 4676 return false; 4677 4678 // Figure out which conditional is saturating the lower/upper bound. 4679 const SDValue *LowerCheckOp = 4680 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4681 ? &Op 4682 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4683 ? &Op2 4684 : nullptr; 4685 const SDValue *UpperCheckOp = 4686 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4687 ? &Op 4688 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4689 ? &Op2 4690 : nullptr; 4691 4692 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4693 return false; 4694 4695 // Check that the constant in the lower-bound check is 4696 // the opposite of the constant in the upper-bound check 4697 // in 1's complement. 4698 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4699 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4700 int64_t PosVal = std::max(Val1, Val2); 4701 int64_t NegVal = std::min(Val1, Val2); 4702 4703 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4704 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4705 isPowerOf2_64(PosVal + 1)) { 4706 4707 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4708 if (Val1 == ~Val2) 4709 usat = false; 4710 else if (NegVal == 0) 4711 usat = true; 4712 else 4713 return false; 4714 4715 V = V2; 4716 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4717 4718 return true; 4719 } 4720 4721 return false; 4722 } 4723 4724 // Check if a condition of the type x < k ? k : x can be converted into a 4725 // bit operation instead of conditional moves. 4726 // Currently this is allowed given: 4727 // - The conditions and values match up 4728 // - k is 0 or -1 (all ones) 4729 // This function will not check the last condition, thats up to the caller 4730 // It returns true if the transformation can be made, and in such case 4731 // returns x in V, and k in SatK. 4732 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4733 SDValue &SatK) 4734 { 4735 SDValue LHS = Op.getOperand(0); 4736 SDValue RHS = Op.getOperand(1); 4737 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4738 SDValue TrueVal = Op.getOperand(2); 4739 SDValue FalseVal = Op.getOperand(3); 4740 4741 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4742 ? &RHS 4743 : nullptr; 4744 4745 // No constant operation in comparison, early out 4746 if (!K) 4747 return false; 4748 4749 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4750 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4751 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4752 4753 // If the constant on left and right side, or variable on left and right, 4754 // does not match, early out 4755 if (*K != KTmp || V != VTmp) 4756 return false; 4757 4758 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4759 SatK = *K; 4760 return true; 4761 } 4762 4763 return false; 4764 } 4765 4766 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 4767 if (VT == MVT::f32) 4768 return !Subtarget->hasVFP2Base(); 4769 if (VT == MVT::f64) 4770 return !Subtarget->hasFP64(); 4771 if (VT == MVT::f16) 4772 return !Subtarget->hasFullFP16(); 4773 return false; 4774 } 4775 4776 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4777 EVT VT = Op.getValueType(); 4778 SDLoc dl(Op); 4779 4780 // Try to convert two saturating conditional selects into a single SSAT 4781 SDValue SatValue; 4782 uint64_t SatConstant; 4783 bool SatUSat; 4784 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4785 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4786 if (SatUSat) 4787 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4788 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4789 else 4790 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4791 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4792 } 4793 4794 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4795 // into more efficient bit operations, which is possible when k is 0 or -1 4796 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4797 // single instructions. On Thumb the shift and the bit operation will be two 4798 // instructions. 4799 // Only allow this transformation on full-width (32-bit) operations 4800 SDValue LowerSatConstant; 4801 if (VT == MVT::i32 && 4802 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4803 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4804 DAG.getConstant(31, dl, VT)); 4805 if (isNullConstant(LowerSatConstant)) { 4806 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4807 DAG.getAllOnesConstant(dl, VT)); 4808 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4809 } else if (isAllOnesConstant(LowerSatConstant)) 4810 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4811 } 4812 4813 SDValue LHS = Op.getOperand(0); 4814 SDValue RHS = Op.getOperand(1); 4815 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4816 SDValue TrueVal = Op.getOperand(2); 4817 SDValue FalseVal = Op.getOperand(3); 4818 4819 if (isUnsupportedFloatingType(LHS.getValueType())) { 4820 DAG.getTargetLoweringInfo().softenSetCCOperands( 4821 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 4822 4823 // If softenSetCCOperands only returned one value, we should compare it to 4824 // zero. 4825 if (!RHS.getNode()) { 4826 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4827 CC = ISD::SETNE; 4828 } 4829 } 4830 4831 if (LHS.getValueType() == MVT::i32) { 4832 // Try to generate VSEL on ARMv8. 4833 // The VSEL instruction can't use all the usual ARM condition 4834 // codes: it only has two bits to select the condition code, so it's 4835 // constrained to use only GE, GT, VS and EQ. 4836 // 4837 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4838 // swap the operands of the previous compare instruction (effectively 4839 // inverting the compare condition, swapping 'less' and 'greater') and 4840 // sometimes need to swap the operands to the VSEL (which inverts the 4841 // condition in the sense of firing whenever the previous condition didn't) 4842 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 4843 TrueVal.getValueType() == MVT::f32 || 4844 TrueVal.getValueType() == MVT::f64)) { 4845 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4846 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4847 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4848 CC = ISD::getSetCCInverse(CC, true); 4849 std::swap(TrueVal, FalseVal); 4850 } 4851 } 4852 4853 SDValue ARMcc; 4854 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4855 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4856 // Choose GE over PL, which vsel does now support 4857 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 4858 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 4859 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4860 } 4861 4862 ARMCC::CondCodes CondCode, CondCode2; 4863 bool InvalidOnQNaN; 4864 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4865 4866 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 4867 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 4868 // must use VSEL (limited condition codes), due to not having conditional f16 4869 // moves. 4870 if (Subtarget->hasFPARMv8Base() && 4871 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 4872 (TrueVal.getValueType() == MVT::f16 || 4873 TrueVal.getValueType() == MVT::f32 || 4874 TrueVal.getValueType() == MVT::f64)) { 4875 bool swpCmpOps = false; 4876 bool swpVselOps = false; 4877 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4878 4879 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4880 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4881 if (swpCmpOps) 4882 std::swap(LHS, RHS); 4883 if (swpVselOps) 4884 std::swap(TrueVal, FalseVal); 4885 } 4886 } 4887 4888 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4889 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4890 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4891 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4892 if (CondCode2 != ARMCC::AL) { 4893 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4894 // FIXME: Needs another CMP because flag can have but one use. 4895 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4896 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4897 } 4898 return Result; 4899 } 4900 4901 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4902 /// to morph to an integer compare sequence. 4903 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4904 const ARMSubtarget *Subtarget) { 4905 SDNode *N = Op.getNode(); 4906 if (!N->hasOneUse()) 4907 // Otherwise it requires moving the value from fp to integer registers. 4908 return false; 4909 if (!N->getNumValues()) 4910 return false; 4911 EVT VT = Op.getValueType(); 4912 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4913 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4914 // vmrs are very slow, e.g. cortex-a8. 4915 return false; 4916 4917 if (isFloatingPointZero(Op)) { 4918 SeenZero = true; 4919 return true; 4920 } 4921 return ISD::isNormalLoad(N); 4922 } 4923 4924 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4925 if (isFloatingPointZero(Op)) 4926 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4927 4928 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4929 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4930 Ld->getPointerInfo(), Ld->getAlignment(), 4931 Ld->getMemOperand()->getFlags()); 4932 4933 llvm_unreachable("Unknown VFP cmp argument!"); 4934 } 4935 4936 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4937 SDValue &RetVal1, SDValue &RetVal2) { 4938 SDLoc dl(Op); 4939 4940 if (isFloatingPointZero(Op)) { 4941 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4942 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4943 return; 4944 } 4945 4946 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4947 SDValue Ptr = Ld->getBasePtr(); 4948 RetVal1 = 4949 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4950 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4951 4952 EVT PtrType = Ptr.getValueType(); 4953 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4954 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4955 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4956 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4957 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4958 Ld->getMemOperand()->getFlags()); 4959 return; 4960 } 4961 4962 llvm_unreachable("Unknown VFP cmp argument!"); 4963 } 4964 4965 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4966 /// f32 and even f64 comparisons to integer ones. 4967 SDValue 4968 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4969 SDValue Chain = Op.getOperand(0); 4970 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4971 SDValue LHS = Op.getOperand(2); 4972 SDValue RHS = Op.getOperand(3); 4973 SDValue Dest = Op.getOperand(4); 4974 SDLoc dl(Op); 4975 4976 bool LHSSeenZero = false; 4977 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4978 bool RHSSeenZero = false; 4979 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4980 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4981 // If unsafe fp math optimization is enabled and there are no other uses of 4982 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4983 // to an integer comparison. 4984 if (CC == ISD::SETOEQ) 4985 CC = ISD::SETEQ; 4986 else if (CC == ISD::SETUNE) 4987 CC = ISD::SETNE; 4988 4989 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4990 SDValue ARMcc; 4991 if (LHS.getValueType() == MVT::f32) { 4992 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4993 bitcastf32Toi32(LHS, DAG), Mask); 4994 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4995 bitcastf32Toi32(RHS, DAG), Mask); 4996 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4997 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4998 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4999 Chain, Dest, ARMcc, CCR, Cmp); 5000 } 5001 5002 SDValue LHS1, LHS2; 5003 SDValue RHS1, RHS2; 5004 expandf64Toi32(LHS, DAG, LHS1, LHS2); 5005 expandf64Toi32(RHS, DAG, RHS1, RHS2); 5006 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 5007 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 5008 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 5009 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5010 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5011 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 5012 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 5013 } 5014 5015 return SDValue(); 5016 } 5017 5018 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 5019 SDValue Chain = Op.getOperand(0); 5020 SDValue Cond = Op.getOperand(1); 5021 SDValue Dest = Op.getOperand(2); 5022 SDLoc dl(Op); 5023 5024 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5025 // instruction. 5026 unsigned Opc = Cond.getOpcode(); 5027 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5028 !Subtarget->isThumb1Only(); 5029 if (Cond.getResNo() == 1 && 5030 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5031 Opc == ISD::USUBO || OptimizeMul)) { 5032 // Only lower legal XALUO ops. 5033 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 5034 return SDValue(); 5035 5036 // The actual operation with overflow check. 5037 SDValue Value, OverflowCmp; 5038 SDValue ARMcc; 5039 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 5040 5041 // Reverse the condition code. 5042 ARMCC::CondCodes CondCode = 5043 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5044 CondCode = ARMCC::getOppositeCondition(CondCode); 5045 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5046 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5047 5048 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5049 OverflowCmp); 5050 } 5051 5052 return SDValue(); 5053 } 5054 5055 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5056 SDValue Chain = Op.getOperand(0); 5057 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5058 SDValue LHS = Op.getOperand(2); 5059 SDValue RHS = Op.getOperand(3); 5060 SDValue Dest = Op.getOperand(4); 5061 SDLoc dl(Op); 5062 5063 if (isUnsupportedFloatingType(LHS.getValueType())) { 5064 DAG.getTargetLoweringInfo().softenSetCCOperands( 5065 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 5066 5067 // If softenSetCCOperands only returned one value, we should compare it to 5068 // zero. 5069 if (!RHS.getNode()) { 5070 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5071 CC = ISD::SETNE; 5072 } 5073 } 5074 5075 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5076 // instruction. 5077 unsigned Opc = LHS.getOpcode(); 5078 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5079 !Subtarget->isThumb1Only(); 5080 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5081 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5082 Opc == ISD::USUBO || OptimizeMul) && 5083 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5084 // Only lower legal XALUO ops. 5085 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5086 return SDValue(); 5087 5088 // The actual operation with overflow check. 5089 SDValue Value, OverflowCmp; 5090 SDValue ARMcc; 5091 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5092 5093 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5094 // Reverse the condition code. 5095 ARMCC::CondCodes CondCode = 5096 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5097 CondCode = ARMCC::getOppositeCondition(CondCode); 5098 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5099 } 5100 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5101 5102 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5103 OverflowCmp); 5104 } 5105 5106 if (LHS.getValueType() == MVT::i32) { 5107 SDValue ARMcc; 5108 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5109 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5110 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5111 Chain, Dest, ARMcc, CCR, Cmp); 5112 } 5113 5114 if (getTargetMachine().Options.UnsafeFPMath && 5115 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5116 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5117 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5118 return Result; 5119 } 5120 5121 ARMCC::CondCodes CondCode, CondCode2; 5122 bool InvalidOnQNaN; 5123 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 5124 5125 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5126 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 5127 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5128 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5129 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5130 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5131 if (CondCode2 != ARMCC::AL) { 5132 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5133 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5134 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5135 } 5136 return Res; 5137 } 5138 5139 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5140 SDValue Chain = Op.getOperand(0); 5141 SDValue Table = Op.getOperand(1); 5142 SDValue Index = Op.getOperand(2); 5143 SDLoc dl(Op); 5144 5145 EVT PTy = getPointerTy(DAG.getDataLayout()); 5146 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5147 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5148 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5149 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5150 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5151 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5152 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5153 // which does another jump to the destination. This also makes it easier 5154 // to translate it to TBB / TBH later (Thumb2 only). 5155 // FIXME: This might not work if the function is extremely large. 5156 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5157 Addr, Op.getOperand(2), JTI); 5158 } 5159 if (isPositionIndependent() || Subtarget->isROPI()) { 5160 Addr = 5161 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5162 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5163 Chain = Addr.getValue(1); 5164 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5165 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5166 } else { 5167 Addr = 5168 DAG.getLoad(PTy, dl, Chain, Addr, 5169 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5170 Chain = Addr.getValue(1); 5171 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5172 } 5173 } 5174 5175 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5176 EVT VT = Op.getValueType(); 5177 SDLoc dl(Op); 5178 5179 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5180 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5181 return Op; 5182 return DAG.UnrollVectorOp(Op.getNode()); 5183 } 5184 5185 const bool HasFullFP16 = 5186 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5187 5188 EVT NewTy; 5189 const EVT OpTy = Op.getOperand(0).getValueType(); 5190 if (OpTy == MVT::v4f32) 5191 NewTy = MVT::v4i32; 5192 else if (OpTy == MVT::v4f16 && HasFullFP16) 5193 NewTy = MVT::v4i16; 5194 else if (OpTy == MVT::v8f16 && HasFullFP16) 5195 NewTy = MVT::v8i16; 5196 else 5197 llvm_unreachable("Invalid type for custom lowering!"); 5198 5199 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5200 return DAG.UnrollVectorOp(Op.getNode()); 5201 5202 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5203 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5204 } 5205 5206 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5207 EVT VT = Op.getValueType(); 5208 if (VT.isVector()) 5209 return LowerVectorFP_TO_INT(Op, DAG); 5210 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) { 5211 RTLIB::Libcall LC; 5212 if (Op.getOpcode() == ISD::FP_TO_SINT) 5213 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 5214 Op.getValueType()); 5215 else 5216 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 5217 Op.getValueType()); 5218 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5219 /*isSigned*/ false, SDLoc(Op)).first; 5220 } 5221 5222 return Op; 5223 } 5224 5225 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5226 EVT VT = Op.getValueType(); 5227 SDLoc dl(Op); 5228 5229 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5230 if (VT.getVectorElementType() == MVT::f32) 5231 return Op; 5232 return DAG.UnrollVectorOp(Op.getNode()); 5233 } 5234 5235 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5236 Op.getOperand(0).getValueType() == MVT::v8i16) && 5237 "Invalid type for custom lowering!"); 5238 5239 const bool HasFullFP16 = 5240 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5241 5242 EVT DestVecType; 5243 if (VT == MVT::v4f32) 5244 DestVecType = MVT::v4i32; 5245 else if (VT == MVT::v4f16 && HasFullFP16) 5246 DestVecType = MVT::v4i16; 5247 else if (VT == MVT::v8f16 && HasFullFP16) 5248 DestVecType = MVT::v8i16; 5249 else 5250 return DAG.UnrollVectorOp(Op.getNode()); 5251 5252 unsigned CastOpc; 5253 unsigned Opc; 5254 switch (Op.getOpcode()) { 5255 default: llvm_unreachable("Invalid opcode!"); 5256 case ISD::SINT_TO_FP: 5257 CastOpc = ISD::SIGN_EXTEND; 5258 Opc = ISD::SINT_TO_FP; 5259 break; 5260 case ISD::UINT_TO_FP: 5261 CastOpc = ISD::ZERO_EXTEND; 5262 Opc = ISD::UINT_TO_FP; 5263 break; 5264 } 5265 5266 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5267 return DAG.getNode(Opc, dl, VT, Op); 5268 } 5269 5270 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5271 EVT VT = Op.getValueType(); 5272 if (VT.isVector()) 5273 return LowerVectorINT_TO_FP(Op, DAG); 5274 if (isUnsupportedFloatingType(VT)) { 5275 RTLIB::Libcall LC; 5276 if (Op.getOpcode() == ISD::SINT_TO_FP) 5277 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5278 Op.getValueType()); 5279 else 5280 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5281 Op.getValueType()); 5282 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5283 /*isSigned*/ false, SDLoc(Op)).first; 5284 } 5285 5286 return Op; 5287 } 5288 5289 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5290 // Implement fcopysign with a fabs and a conditional fneg. 5291 SDValue Tmp0 = Op.getOperand(0); 5292 SDValue Tmp1 = Op.getOperand(1); 5293 SDLoc dl(Op); 5294 EVT VT = Op.getValueType(); 5295 EVT SrcVT = Tmp1.getValueType(); 5296 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5297 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5298 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5299 5300 if (UseNEON) { 5301 // Use VBSL to copy the sign bit. 5302 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5303 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5304 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5305 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5306 if (VT == MVT::f64) 5307 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5308 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5309 DAG.getConstant(32, dl, MVT::i32)); 5310 else /*if (VT == MVT::f32)*/ 5311 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5312 if (SrcVT == MVT::f32) { 5313 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5314 if (VT == MVT::f64) 5315 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5316 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5317 DAG.getConstant(32, dl, MVT::i32)); 5318 } else if (VT == MVT::f32) 5319 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5320 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5321 DAG.getConstant(32, dl, MVT::i32)); 5322 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5323 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5324 5325 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5326 dl, MVT::i32); 5327 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5328 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5329 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5330 5331 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5332 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5333 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5334 if (VT == MVT::f32) { 5335 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5336 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5337 DAG.getConstant(0, dl, MVT::i32)); 5338 } else { 5339 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5340 } 5341 5342 return Res; 5343 } 5344 5345 // Bitcast operand 1 to i32. 5346 if (SrcVT == MVT::f64) 5347 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5348 Tmp1).getValue(1); 5349 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5350 5351 // Or in the signbit with integer operations. 5352 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5353 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5354 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5355 if (VT == MVT::f32) { 5356 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5357 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5358 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5359 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5360 } 5361 5362 // f64: Or the high part with signbit and then combine two parts. 5363 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5364 Tmp0); 5365 SDValue Lo = Tmp0.getValue(0); 5366 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5367 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5368 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5369 } 5370 5371 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5372 MachineFunction &MF = DAG.getMachineFunction(); 5373 MachineFrameInfo &MFI = MF.getFrameInfo(); 5374 MFI.setReturnAddressIsTaken(true); 5375 5376 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5377 return SDValue(); 5378 5379 EVT VT = Op.getValueType(); 5380 SDLoc dl(Op); 5381 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5382 if (Depth) { 5383 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5384 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5385 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5386 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5387 MachinePointerInfo()); 5388 } 5389 5390 // Return LR, which contains the return address. Mark it an implicit live-in. 5391 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5392 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5393 } 5394 5395 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5396 const ARMBaseRegisterInfo &ARI = 5397 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5398 MachineFunction &MF = DAG.getMachineFunction(); 5399 MachineFrameInfo &MFI = MF.getFrameInfo(); 5400 MFI.setFrameAddressIsTaken(true); 5401 5402 EVT VT = Op.getValueType(); 5403 SDLoc dl(Op); // FIXME probably not meaningful 5404 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5405 Register FrameReg = ARI.getFrameRegister(MF); 5406 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5407 while (Depth--) 5408 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5409 MachinePointerInfo()); 5410 return FrameAddr; 5411 } 5412 5413 // FIXME? Maybe this could be a TableGen attribute on some registers and 5414 // this table could be generated automatically from RegInfo. 5415 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5416 SelectionDAG &DAG) const { 5417 unsigned Reg = StringSwitch<unsigned>(RegName) 5418 .Case("sp", ARM::SP) 5419 .Default(0); 5420 if (Reg) 5421 return Reg; 5422 report_fatal_error(Twine("Invalid register name \"" 5423 + StringRef(RegName) + "\".")); 5424 } 5425 5426 // Result is 64 bit value so split into two 32 bit values and return as a 5427 // pair of values. 5428 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5429 SelectionDAG &DAG) { 5430 SDLoc DL(N); 5431 5432 // This function is only supposed to be called for i64 type destination. 5433 assert(N->getValueType(0) == MVT::i64 5434 && "ExpandREAD_REGISTER called for non-i64 type result."); 5435 5436 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5437 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5438 N->getOperand(0), 5439 N->getOperand(1)); 5440 5441 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5442 Read.getValue(1))); 5443 Results.push_back(Read.getOperand(0)); 5444 } 5445 5446 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5447 /// When \p DstVT, the destination type of \p BC, is on the vector 5448 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5449 /// it might be possible to combine them, such that everything stays on the 5450 /// vector register bank. 5451 /// \p return The node that would replace \p BT, if the combine 5452 /// is possible. 5453 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5454 SelectionDAG &DAG) { 5455 SDValue Op = BC->getOperand(0); 5456 EVT DstVT = BC->getValueType(0); 5457 5458 // The only vector instruction that can produce a scalar (remember, 5459 // since the bitcast was about to be turned into VMOVDRR, the source 5460 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5461 // Moreover, we can do this combine only if there is one use. 5462 // Finally, if the destination type is not a vector, there is not 5463 // much point on forcing everything on the vector bank. 5464 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5465 !Op.hasOneUse()) 5466 return SDValue(); 5467 5468 // If the index is not constant, we will introduce an additional 5469 // multiply that will stick. 5470 // Give up in that case. 5471 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5472 if (!Index) 5473 return SDValue(); 5474 unsigned DstNumElt = DstVT.getVectorNumElements(); 5475 5476 // Compute the new index. 5477 const APInt &APIntIndex = Index->getAPIntValue(); 5478 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5479 NewIndex *= APIntIndex; 5480 // Check if the new constant index fits into i32. 5481 if (NewIndex.getBitWidth() > 32) 5482 return SDValue(); 5483 5484 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5485 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5486 SDLoc dl(Op); 5487 SDValue ExtractSrc = Op.getOperand(0); 5488 EVT VecVT = EVT::getVectorVT( 5489 *DAG.getContext(), DstVT.getScalarType(), 5490 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5491 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5492 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5493 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5494 } 5495 5496 /// ExpandBITCAST - If the target supports VFP, this function is called to 5497 /// expand a bit convert where either the source or destination type is i64 to 5498 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5499 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5500 /// vectors), since the legalizer won't know what to do with that. 5501 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5502 const ARMSubtarget *Subtarget) { 5503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5504 SDLoc dl(N); 5505 SDValue Op = N->getOperand(0); 5506 5507 // This function is only supposed to be called for i64 types, either as the 5508 // source or destination of the bit convert. 5509 EVT SrcVT = Op.getValueType(); 5510 EVT DstVT = N->getValueType(0); 5511 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5512 5513 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5514 // FullFP16: half values are passed in S-registers, and we don't 5515 // need any of the bitcast and moves: 5516 // 5517 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5518 // t5: i32 = bitcast t2 5519 // t18: f16 = ARMISD::VMOVhr t5 5520 if (Op.getOpcode() != ISD::CopyFromReg || 5521 Op.getValueType() != MVT::f32) 5522 return SDValue(); 5523 5524 auto Move = N->use_begin(); 5525 if (Move->getOpcode() != ARMISD::VMOVhr) 5526 return SDValue(); 5527 5528 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5529 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5530 DAG.ReplaceAllUsesWith(*Move, &Copy); 5531 return Copy; 5532 } 5533 5534 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5535 if (!HasFullFP16) 5536 return SDValue(); 5537 // SoftFP: read half-precision arguments: 5538 // 5539 // t2: i32,ch = ... 5540 // t7: i16 = truncate t2 <~~~~ Op 5541 // t8: f16 = bitcast t7 <~~~~ N 5542 // 5543 if (Op.getOperand(0).getValueType() == MVT::i32) 5544 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5545 MVT::f16, Op.getOperand(0)); 5546 5547 return SDValue(); 5548 } 5549 5550 // Half-precision return values 5551 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5552 if (!HasFullFP16) 5553 return SDValue(); 5554 // 5555 // t11: f16 = fadd t8, t10 5556 // t12: i16 = bitcast t11 <~~~ SDNode N 5557 // t13: i32 = zero_extend t12 5558 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5559 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5560 // 5561 // transform this into: 5562 // 5563 // t20: i32 = ARMISD::VMOVrh t11 5564 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5565 // 5566 auto ZeroExtend = N->use_begin(); 5567 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5568 ZeroExtend->getValueType(0) != MVT::i32) 5569 return SDValue(); 5570 5571 auto Copy = ZeroExtend->use_begin(); 5572 if (Copy->getOpcode() == ISD::CopyToReg && 5573 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5574 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5575 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5576 return Cvt; 5577 } 5578 return SDValue(); 5579 } 5580 5581 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5582 return SDValue(); 5583 5584 // Turn i64->f64 into VMOVDRR. 5585 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5586 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5587 // if we can combine the bitcast with its source. 5588 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5589 return Val; 5590 5591 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5592 DAG.getConstant(0, dl, MVT::i32)); 5593 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5594 DAG.getConstant(1, dl, MVT::i32)); 5595 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5596 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5597 } 5598 5599 // Turn f64->i64 into VMOVRRD. 5600 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5601 SDValue Cvt; 5602 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5603 SrcVT.getVectorNumElements() > 1) 5604 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5605 DAG.getVTList(MVT::i32, MVT::i32), 5606 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5607 else 5608 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5609 DAG.getVTList(MVT::i32, MVT::i32), Op); 5610 // Merge the pieces into a single i64 value. 5611 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5612 } 5613 5614 return SDValue(); 5615 } 5616 5617 /// getZeroVector - Returns a vector of specified type with all zero elements. 5618 /// Zero vectors are used to represent vector negation and in those cases 5619 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5620 /// not support i64 elements, so sometimes the zero vectors will need to be 5621 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5622 /// zero vector. 5623 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5624 assert(VT.isVector() && "Expected a vector type"); 5625 // The canonical modified immediate encoding of a zero vector is....0! 5626 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5627 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5628 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5629 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5630 } 5631 5632 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5633 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5634 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5635 SelectionDAG &DAG) const { 5636 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5637 EVT VT = Op.getValueType(); 5638 unsigned VTBits = VT.getSizeInBits(); 5639 SDLoc dl(Op); 5640 SDValue ShOpLo = Op.getOperand(0); 5641 SDValue ShOpHi = Op.getOperand(1); 5642 SDValue ShAmt = Op.getOperand(2); 5643 SDValue ARMcc; 5644 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5645 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5646 5647 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5648 5649 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5650 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5651 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5652 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5653 DAG.getConstant(VTBits, dl, MVT::i32)); 5654 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5655 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5656 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5657 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5658 ISD::SETGE, ARMcc, DAG, dl); 5659 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5660 ARMcc, CCR, CmpLo); 5661 5662 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5663 SDValue HiBigShift = Opc == ISD::SRA 5664 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5665 DAG.getConstant(VTBits - 1, dl, VT)) 5666 : DAG.getConstant(0, dl, VT); 5667 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5668 ISD::SETGE, ARMcc, DAG, dl); 5669 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5670 ARMcc, CCR, CmpHi); 5671 5672 SDValue Ops[2] = { Lo, Hi }; 5673 return DAG.getMergeValues(Ops, dl); 5674 } 5675 5676 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5677 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5678 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5679 SelectionDAG &DAG) const { 5680 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5681 EVT VT = Op.getValueType(); 5682 unsigned VTBits = VT.getSizeInBits(); 5683 SDLoc dl(Op); 5684 SDValue ShOpLo = Op.getOperand(0); 5685 SDValue ShOpHi = Op.getOperand(1); 5686 SDValue ShAmt = Op.getOperand(2); 5687 SDValue ARMcc; 5688 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5689 5690 assert(Op.getOpcode() == ISD::SHL_PARTS); 5691 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5692 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5693 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5694 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5695 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5696 5697 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5698 DAG.getConstant(VTBits, dl, MVT::i32)); 5699 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5700 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5701 ISD::SETGE, ARMcc, DAG, dl); 5702 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5703 ARMcc, CCR, CmpHi); 5704 5705 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5706 ISD::SETGE, ARMcc, DAG, dl); 5707 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5708 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5709 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5710 5711 SDValue Ops[2] = { Lo, Hi }; 5712 return DAG.getMergeValues(Ops, dl); 5713 } 5714 5715 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5716 SelectionDAG &DAG) const { 5717 // The rounding mode is in bits 23:22 of the FPSCR. 5718 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5719 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5720 // so that the shift + and get folded into a bitfield extract. 5721 SDLoc dl(Op); 5722 SDValue Ops[] = { DAG.getEntryNode(), 5723 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5724 5725 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5726 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5727 DAG.getConstant(1U << 22, dl, MVT::i32)); 5728 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5729 DAG.getConstant(22, dl, MVT::i32)); 5730 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5731 DAG.getConstant(3, dl, MVT::i32)); 5732 } 5733 5734 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5735 const ARMSubtarget *ST) { 5736 SDLoc dl(N); 5737 EVT VT = N->getValueType(0); 5738 if (VT.isVector()) { 5739 assert(ST->hasNEON()); 5740 5741 // Compute the least significant set bit: LSB = X & -X 5742 SDValue X = N->getOperand(0); 5743 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5744 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5745 5746 EVT ElemTy = VT.getVectorElementType(); 5747 5748 if (ElemTy == MVT::i8) { 5749 // Compute with: cttz(x) = ctpop(lsb - 1) 5750 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5751 DAG.getTargetConstant(1, dl, ElemTy)); 5752 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5753 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5754 } 5755 5756 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5757 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5758 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5759 unsigned NumBits = ElemTy.getSizeInBits(); 5760 SDValue WidthMinus1 = 5761 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5762 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5763 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5764 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5765 } 5766 5767 // Compute with: cttz(x) = ctpop(lsb - 1) 5768 5769 // Compute LSB - 1. 5770 SDValue Bits; 5771 if (ElemTy == MVT::i64) { 5772 // Load constant 0xffff'ffff'ffff'ffff to register. 5773 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5774 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5775 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5776 } else { 5777 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5778 DAG.getTargetConstant(1, dl, ElemTy)); 5779 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5780 } 5781 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5782 } 5783 5784 if (!ST->hasV6T2Ops()) 5785 return SDValue(); 5786 5787 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5788 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5789 } 5790 5791 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5792 const ARMSubtarget *ST) { 5793 EVT VT = N->getValueType(0); 5794 SDLoc DL(N); 5795 5796 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5797 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5798 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5799 "Unexpected type for custom ctpop lowering"); 5800 5801 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5802 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5803 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 5804 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 5805 5806 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5807 unsigned EltSize = 8; 5808 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5809 while (EltSize != VT.getScalarSizeInBits()) { 5810 SmallVector<SDValue, 8> Ops; 5811 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 5812 TLI.getPointerTy(DAG.getDataLayout()))); 5813 Ops.push_back(Res); 5814 5815 EltSize *= 2; 5816 NumElts /= 2; 5817 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5818 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 5819 } 5820 5821 return Res; 5822 } 5823 5824 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 5825 /// operand of a vector shift operation, where all the elements of the 5826 /// build_vector must have the same constant integer value. 5827 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 5828 // Ignore bit_converts. 5829 while (Op.getOpcode() == ISD::BITCAST) 5830 Op = Op.getOperand(0); 5831 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 5832 APInt SplatBits, SplatUndef; 5833 unsigned SplatBitSize; 5834 bool HasAnyUndefs; 5835 if (!BVN || 5836 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 5837 ElementBits) || 5838 SplatBitSize > ElementBits) 5839 return false; 5840 Cnt = SplatBits.getSExtValue(); 5841 return true; 5842 } 5843 5844 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 5845 /// operand of a vector shift left operation. That value must be in the range: 5846 /// 0 <= Value < ElementBits for a left shift; or 5847 /// 0 <= Value <= ElementBits for a long left shift. 5848 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 5849 assert(VT.isVector() && "vector shift count is not a vector type"); 5850 int64_t ElementBits = VT.getScalarSizeInBits(); 5851 if (!getVShiftImm(Op, ElementBits, Cnt)) 5852 return false; 5853 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 5854 } 5855 5856 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 5857 /// operand of a vector shift right operation. For a shift opcode, the value 5858 /// is positive, but for an intrinsic the value count must be negative. The 5859 /// absolute value must be in the range: 5860 /// 1 <= |Value| <= ElementBits for a right shift; or 5861 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 5862 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 5863 int64_t &Cnt) { 5864 assert(VT.isVector() && "vector shift count is not a vector type"); 5865 int64_t ElementBits = VT.getScalarSizeInBits(); 5866 if (!getVShiftImm(Op, ElementBits, Cnt)) 5867 return false; 5868 if (!isIntrinsic) 5869 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 5870 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 5871 Cnt = -Cnt; 5872 return true; 5873 } 5874 return false; 5875 } 5876 5877 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5878 const ARMSubtarget *ST) { 5879 EVT VT = N->getValueType(0); 5880 SDLoc dl(N); 5881 int64_t Cnt; 5882 5883 if (!VT.isVector()) 5884 return SDValue(); 5885 5886 // We essentially have two forms here. Shift by an immediate and shift by a 5887 // vector register (there are also shift by a gpr, but that is just handled 5888 // with a tablegen pattern). We cannot easily match shift by an immediate in 5889 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 5890 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 5891 // signed or unsigned, and a negative shift indicates a shift right). 5892 if (N->getOpcode() == ISD::SHL) { 5893 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 5894 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 5895 DAG.getConstant(Cnt, dl, MVT::i32)); 5896 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 5897 N->getOperand(1)); 5898 } 5899 5900 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 5901 "unexpected vector shift opcode"); 5902 5903 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 5904 unsigned VShiftOpc = 5905 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 5906 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 5907 DAG.getConstant(Cnt, dl, MVT::i32)); 5908 } 5909 5910 // Other right shifts we don't have operations for (we use a shift left by a 5911 // negative number). 5912 EVT ShiftVT = N->getOperand(1).getValueType(); 5913 SDValue NegatedCount = DAG.getNode( 5914 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 5915 unsigned VShiftOpc = 5916 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 5917 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 5918 } 5919 5920 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5921 const ARMSubtarget *ST) { 5922 EVT VT = N->getValueType(0); 5923 SDLoc dl(N); 5924 5925 // We can get here for a node like i32 = ISD::SHL i32, i64 5926 if (VT != MVT::i64) 5927 return SDValue(); 5928 5929 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 5930 N->getOpcode() == ISD::SHL) && 5931 "Unknown shift to lower!"); 5932 5933 unsigned ShOpc = N->getOpcode(); 5934 if (ST->hasMVEIntegerOps()) { 5935 SDValue ShAmt = N->getOperand(1); 5936 unsigned ShPartsOpc = ARMISD::LSLL; 5937 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 5938 5939 // If the shift amount is greater than 32 then do the default optimisation 5940 if (Con && Con->getZExtValue() > 32) 5941 return SDValue(); 5942 5943 // Extract the lower 32 bits of the shift amount if it's an i64 5944 if (ShAmt->getValueType(0) == MVT::i64) 5945 ShAmt = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, ShAmt, 5946 DAG.getConstant(0, dl, MVT::i32)); 5947 5948 if (ShOpc == ISD::SRL) { 5949 if (!Con) 5950 // There is no t2LSRLr instruction so negate and perform an lsll if the 5951 // shift amount is in a register, emulating a right shift. 5952 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5953 DAG.getConstant(0, dl, MVT::i32), ShAmt); 5954 else 5955 // Else generate an lsrl on the immediate shift amount 5956 ShPartsOpc = ARMISD::LSRL; 5957 } else if (ShOpc == ISD::SRA) 5958 ShPartsOpc = ARMISD::ASRL; 5959 5960 // Lower 32 bits of the destination/source 5961 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5962 DAG.getConstant(0, dl, MVT::i32)); 5963 // Upper 32 bits of the destination/source 5964 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5965 DAG.getConstant(1, dl, MVT::i32)); 5966 5967 // Generate the shift operation as computed above 5968 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 5969 ShAmt); 5970 // The upper 32 bits come from the second return value of lsll 5971 Hi = SDValue(Lo.getNode(), 1); 5972 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5973 } 5974 5975 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5976 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 5977 return SDValue(); 5978 5979 // If we are in thumb mode, we don't have RRX. 5980 if (ST->isThumb1Only()) 5981 return SDValue(); 5982 5983 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5984 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5985 DAG.getConstant(0, dl, MVT::i32)); 5986 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5987 DAG.getConstant(1, dl, MVT::i32)); 5988 5989 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5990 // captures the result into a carry flag. 5991 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5992 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5993 5994 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5995 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5996 5997 // Merge the pieces into a single i64 value. 5998 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5999 } 6000 6001 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 6002 const ARMSubtarget *ST) { 6003 bool Invert = false; 6004 bool Swap = false; 6005 unsigned Opc = ARMCC::AL; 6006 6007 SDValue Op0 = Op.getOperand(0); 6008 SDValue Op1 = Op.getOperand(1); 6009 SDValue CC = Op.getOperand(2); 6010 EVT VT = Op.getValueType(); 6011 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 6012 SDLoc dl(Op); 6013 6014 EVT CmpVT; 6015 if (ST->hasNEON()) 6016 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 6017 else { 6018 assert(ST->hasMVEIntegerOps() && 6019 "No hardware support for integer vector comparison!"); 6020 6021 if (Op.getValueType().getVectorElementType() != MVT::i1) 6022 return SDValue(); 6023 6024 // Make sure we expand floating point setcc to scalar if we do not have 6025 // mve.fp, so that we can handle them from there. 6026 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 6027 return SDValue(); 6028 6029 CmpVT = VT; 6030 } 6031 6032 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 6033 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 6034 // Special-case integer 64-bit equality comparisons. They aren't legal, 6035 // but they can be lowered with a few vector instructions. 6036 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 6037 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 6038 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 6039 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 6040 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 6041 DAG.getCondCode(ISD::SETEQ)); 6042 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 6043 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 6044 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 6045 if (SetCCOpcode == ISD::SETNE) 6046 Merged = DAG.getNOT(dl, Merged, CmpVT); 6047 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6048 return Merged; 6049 } 6050 6051 if (CmpVT.getVectorElementType() == MVT::i64) 6052 // 64-bit comparisons are not legal in general. 6053 return SDValue(); 6054 6055 if (Op1.getValueType().isFloatingPoint()) { 6056 switch (SetCCOpcode) { 6057 default: llvm_unreachable("Illegal FP comparison"); 6058 case ISD::SETUNE: 6059 case ISD::SETNE: 6060 if (ST->hasMVEFloatOps()) { 6061 Opc = ARMCC::NE; break; 6062 } else { 6063 Invert = true; LLVM_FALLTHROUGH; 6064 } 6065 case ISD::SETOEQ: 6066 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6067 case ISD::SETOLT: 6068 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6069 case ISD::SETOGT: 6070 case ISD::SETGT: Opc = ARMCC::GT; break; 6071 case ISD::SETOLE: 6072 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6073 case ISD::SETOGE: 6074 case ISD::SETGE: Opc = ARMCC::GE; break; 6075 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6076 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6077 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6078 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6079 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6080 case ISD::SETONE: { 6081 // Expand this to (OLT | OGT). 6082 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6083 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6084 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6085 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6086 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6087 if (Invert) 6088 Result = DAG.getNOT(dl, Result, VT); 6089 return Result; 6090 } 6091 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6092 case ISD::SETO: { 6093 // Expand this to (OLT | OGE). 6094 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6095 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6096 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6097 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6098 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6099 if (Invert) 6100 Result = DAG.getNOT(dl, Result, VT); 6101 return Result; 6102 } 6103 } 6104 } else { 6105 // Integer comparisons. 6106 switch (SetCCOpcode) { 6107 default: llvm_unreachable("Illegal integer comparison"); 6108 case ISD::SETNE: 6109 if (ST->hasMVEIntegerOps()) { 6110 Opc = ARMCC::NE; break; 6111 } else { 6112 Invert = true; LLVM_FALLTHROUGH; 6113 } 6114 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6115 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6116 case ISD::SETGT: Opc = ARMCC::GT; break; 6117 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6118 case ISD::SETGE: Opc = ARMCC::GE; break; 6119 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6120 case ISD::SETUGT: Opc = ARMCC::HI; break; 6121 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6122 case ISD::SETUGE: Opc = ARMCC::HS; break; 6123 } 6124 6125 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6126 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6127 SDValue AndOp; 6128 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6129 AndOp = Op0; 6130 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6131 AndOp = Op1; 6132 6133 // Ignore bitconvert. 6134 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6135 AndOp = AndOp.getOperand(0); 6136 6137 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6138 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6139 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6140 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6141 if (!Invert) 6142 Result = DAG.getNOT(dl, Result, VT); 6143 return Result; 6144 } 6145 } 6146 } 6147 6148 if (Swap) 6149 std::swap(Op0, Op1); 6150 6151 // If one of the operands is a constant vector zero, attempt to fold the 6152 // comparison to a specialized compare-against-zero form. 6153 SDValue SingleOp; 6154 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6155 SingleOp = Op0; 6156 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6157 if (Opc == ARMCC::GE) 6158 Opc = ARMCC::LE; 6159 else if (Opc == ARMCC::GT) 6160 Opc = ARMCC::LT; 6161 SingleOp = Op1; 6162 } 6163 6164 SDValue Result; 6165 if (SingleOp.getNode()) { 6166 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6167 DAG.getConstant(Opc, dl, MVT::i32)); 6168 } else { 6169 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6170 DAG.getConstant(Opc, dl, MVT::i32)); 6171 } 6172 6173 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6174 6175 if (Invert) 6176 Result = DAG.getNOT(dl, Result, VT); 6177 6178 return Result; 6179 } 6180 6181 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6182 SDValue LHS = Op.getOperand(0); 6183 SDValue RHS = Op.getOperand(1); 6184 SDValue Carry = Op.getOperand(2); 6185 SDValue Cond = Op.getOperand(3); 6186 SDLoc DL(Op); 6187 6188 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6189 6190 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6191 // have to invert the carry first. 6192 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6193 DAG.getConstant(1, DL, MVT::i32), Carry); 6194 // This converts the boolean value carry into the carry flag. 6195 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6196 6197 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6198 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6199 6200 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6201 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6202 SDValue ARMcc = DAG.getConstant( 6203 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6204 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6205 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6206 Cmp.getValue(1), SDValue()); 6207 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6208 CCR, Chain.getValue(1)); 6209 } 6210 6211 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6212 /// valid vector constant for a NEON or MVE instruction with a "modified 6213 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6214 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6215 unsigned SplatBitSize, SelectionDAG &DAG, 6216 const SDLoc &dl, EVT &VT, bool is128Bits, 6217 VMOVModImmType type) { 6218 unsigned OpCmode, Imm; 6219 6220 // SplatBitSize is set to the smallest size that splats the vector, so a 6221 // zero vector will always have SplatBitSize == 8. However, NEON modified 6222 // immediate instructions others than VMOV do not support the 8-bit encoding 6223 // of a zero vector, and the default encoding of zero is supposed to be the 6224 // 32-bit version. 6225 if (SplatBits == 0) 6226 SplatBitSize = 32; 6227 6228 switch (SplatBitSize) { 6229 case 8: 6230 if (type != VMOVModImm) 6231 return SDValue(); 6232 // Any 1-byte value is OK. Op=0, Cmode=1110. 6233 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6234 OpCmode = 0xe; 6235 Imm = SplatBits; 6236 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6237 break; 6238 6239 case 16: 6240 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6241 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6242 if ((SplatBits & ~0xff) == 0) { 6243 // Value = 0x00nn: Op=x, Cmode=100x. 6244 OpCmode = 0x8; 6245 Imm = SplatBits; 6246 break; 6247 } 6248 if ((SplatBits & ~0xff00) == 0) { 6249 // Value = 0xnn00: Op=x, Cmode=101x. 6250 OpCmode = 0xa; 6251 Imm = SplatBits >> 8; 6252 break; 6253 } 6254 return SDValue(); 6255 6256 case 32: 6257 // NEON's 32-bit VMOV supports splat values where: 6258 // * only one byte is nonzero, or 6259 // * the least significant byte is 0xff and the second byte is nonzero, or 6260 // * the least significant 2 bytes are 0xff and the third is nonzero. 6261 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6262 if ((SplatBits & ~0xff) == 0) { 6263 // Value = 0x000000nn: Op=x, Cmode=000x. 6264 OpCmode = 0; 6265 Imm = SplatBits; 6266 break; 6267 } 6268 if ((SplatBits & ~0xff00) == 0) { 6269 // Value = 0x0000nn00: Op=x, Cmode=001x. 6270 OpCmode = 0x2; 6271 Imm = SplatBits >> 8; 6272 break; 6273 } 6274 if ((SplatBits & ~0xff0000) == 0) { 6275 // Value = 0x00nn0000: Op=x, Cmode=010x. 6276 OpCmode = 0x4; 6277 Imm = SplatBits >> 16; 6278 break; 6279 } 6280 if ((SplatBits & ~0xff000000) == 0) { 6281 // Value = 0xnn000000: Op=x, Cmode=011x. 6282 OpCmode = 0x6; 6283 Imm = SplatBits >> 24; 6284 break; 6285 } 6286 6287 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6288 if (type == OtherModImm) return SDValue(); 6289 6290 if ((SplatBits & ~0xffff) == 0 && 6291 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6292 // Value = 0x0000nnff: Op=x, Cmode=1100. 6293 OpCmode = 0xc; 6294 Imm = SplatBits >> 8; 6295 break; 6296 } 6297 6298 // cmode == 0b1101 is not supported for MVE VMVN 6299 if (type == MVEVMVNModImm) 6300 return SDValue(); 6301 6302 if ((SplatBits & ~0xffffff) == 0 && 6303 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6304 // Value = 0x00nnffff: Op=x, Cmode=1101. 6305 OpCmode = 0xd; 6306 Imm = SplatBits >> 16; 6307 break; 6308 } 6309 6310 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6311 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6312 // VMOV.I32. A (very) minor optimization would be to replicate the value 6313 // and fall through here to test for a valid 64-bit splat. But, then the 6314 // caller would also need to check and handle the change in size. 6315 return SDValue(); 6316 6317 case 64: { 6318 if (type != VMOVModImm) 6319 return SDValue(); 6320 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6321 uint64_t BitMask = 0xff; 6322 uint64_t Val = 0; 6323 unsigned ImmMask = 1; 6324 Imm = 0; 6325 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6326 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6327 Val |= BitMask; 6328 Imm |= ImmMask; 6329 } else if ((SplatBits & BitMask) != 0) { 6330 return SDValue(); 6331 } 6332 BitMask <<= 8; 6333 ImmMask <<= 1; 6334 } 6335 6336 if (DAG.getDataLayout().isBigEndian()) 6337 // swap higher and lower 32 bit word 6338 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 6339 6340 // Op=1, Cmode=1110. 6341 OpCmode = 0x1e; 6342 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6343 break; 6344 } 6345 6346 default: 6347 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6348 } 6349 6350 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6351 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6352 } 6353 6354 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6355 const ARMSubtarget *ST) const { 6356 EVT VT = Op.getValueType(); 6357 bool IsDouble = (VT == MVT::f64); 6358 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6359 const APFloat &FPVal = CFP->getValueAPF(); 6360 6361 // Prevent floating-point constants from using literal loads 6362 // when execute-only is enabled. 6363 if (ST->genExecuteOnly()) { 6364 // If we can represent the constant as an immediate, don't lower it 6365 if (isFPImmLegal(FPVal, VT)) 6366 return Op; 6367 // Otherwise, construct as integer, and move to float register 6368 APInt INTVal = FPVal.bitcastToAPInt(); 6369 SDLoc DL(CFP); 6370 switch (VT.getSimpleVT().SimpleTy) { 6371 default: 6372 llvm_unreachable("Unknown floating point type!"); 6373 break; 6374 case MVT::f64: { 6375 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6376 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6377 if (!ST->isLittle()) 6378 std::swap(Lo, Hi); 6379 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6380 } 6381 case MVT::f32: 6382 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6383 DAG.getConstant(INTVal, DL, MVT::i32)); 6384 } 6385 } 6386 6387 if (!ST->hasVFP3Base()) 6388 return SDValue(); 6389 6390 // Use the default (constant pool) lowering for double constants when we have 6391 // an SP-only FPU 6392 if (IsDouble && !Subtarget->hasFP64()) 6393 return SDValue(); 6394 6395 // Try splatting with a VMOV.f32... 6396 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6397 6398 if (ImmVal != -1) { 6399 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6400 // We have code in place to select a valid ConstantFP already, no need to 6401 // do any mangling. 6402 return Op; 6403 } 6404 6405 // It's a float and we are trying to use NEON operations where 6406 // possible. Lower it to a splat followed by an extract. 6407 SDLoc DL(Op); 6408 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6409 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6410 NewVal); 6411 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6412 DAG.getConstant(0, DL, MVT::i32)); 6413 } 6414 6415 // The rest of our options are NEON only, make sure that's allowed before 6416 // proceeding.. 6417 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6418 return SDValue(); 6419 6420 EVT VMovVT; 6421 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6422 6423 // It wouldn't really be worth bothering for doubles except for one very 6424 // important value, which does happen to match: 0.0. So make sure we don't do 6425 // anything stupid. 6426 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6427 return SDValue(); 6428 6429 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6430 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6431 VMovVT, false, VMOVModImm); 6432 if (NewVal != SDValue()) { 6433 SDLoc DL(Op); 6434 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6435 NewVal); 6436 if (IsDouble) 6437 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6438 6439 // It's a float: cast and extract a vector element. 6440 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6441 VecConstant); 6442 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6443 DAG.getConstant(0, DL, MVT::i32)); 6444 } 6445 6446 // Finally, try a VMVN.i32 6447 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6448 false, VMVNModImm); 6449 if (NewVal != SDValue()) { 6450 SDLoc DL(Op); 6451 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6452 6453 if (IsDouble) 6454 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6455 6456 // It's a float: cast and extract a vector element. 6457 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6458 VecConstant); 6459 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6460 DAG.getConstant(0, DL, MVT::i32)); 6461 } 6462 6463 return SDValue(); 6464 } 6465 6466 // check if an VEXT instruction can handle the shuffle mask when the 6467 // vector sources of the shuffle are the same. 6468 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6469 unsigned NumElts = VT.getVectorNumElements(); 6470 6471 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6472 if (M[0] < 0) 6473 return false; 6474 6475 Imm = M[0]; 6476 6477 // If this is a VEXT shuffle, the immediate value is the index of the first 6478 // element. The other shuffle indices must be the successive elements after 6479 // the first one. 6480 unsigned ExpectedElt = Imm; 6481 for (unsigned i = 1; i < NumElts; ++i) { 6482 // Increment the expected index. If it wraps around, just follow it 6483 // back to index zero and keep going. 6484 ++ExpectedElt; 6485 if (ExpectedElt == NumElts) 6486 ExpectedElt = 0; 6487 6488 if (M[i] < 0) continue; // ignore UNDEF indices 6489 if (ExpectedElt != static_cast<unsigned>(M[i])) 6490 return false; 6491 } 6492 6493 return true; 6494 } 6495 6496 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6497 bool &ReverseVEXT, unsigned &Imm) { 6498 unsigned NumElts = VT.getVectorNumElements(); 6499 ReverseVEXT = false; 6500 6501 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6502 if (M[0] < 0) 6503 return false; 6504 6505 Imm = M[0]; 6506 6507 // If this is a VEXT shuffle, the immediate value is the index of the first 6508 // element. The other shuffle indices must be the successive elements after 6509 // the first one. 6510 unsigned ExpectedElt = Imm; 6511 for (unsigned i = 1; i < NumElts; ++i) { 6512 // Increment the expected index. If it wraps around, it may still be 6513 // a VEXT but the source vectors must be swapped. 6514 ExpectedElt += 1; 6515 if (ExpectedElt == NumElts * 2) { 6516 ExpectedElt = 0; 6517 ReverseVEXT = true; 6518 } 6519 6520 if (M[i] < 0) continue; // ignore UNDEF indices 6521 if (ExpectedElt != static_cast<unsigned>(M[i])) 6522 return false; 6523 } 6524 6525 // Adjust the index value if the source operands will be swapped. 6526 if (ReverseVEXT) 6527 Imm -= NumElts; 6528 6529 return true; 6530 } 6531 6532 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6533 /// instruction with the specified blocksize. (The order of the elements 6534 /// within each block of the vector is reversed.) 6535 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6536 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6537 "Only possible block sizes for VREV are: 16, 32, 64"); 6538 6539 unsigned EltSz = VT.getScalarSizeInBits(); 6540 if (EltSz == 64) 6541 return false; 6542 6543 unsigned NumElts = VT.getVectorNumElements(); 6544 unsigned BlockElts = M[0] + 1; 6545 // If the first shuffle index is UNDEF, be optimistic. 6546 if (M[0] < 0) 6547 BlockElts = BlockSize / EltSz; 6548 6549 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6550 return false; 6551 6552 for (unsigned i = 0; i < NumElts; ++i) { 6553 if (M[i] < 0) continue; // ignore UNDEF indices 6554 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6555 return false; 6556 } 6557 6558 return true; 6559 } 6560 6561 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6562 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6563 // range, then 0 is placed into the resulting vector. So pretty much any mask 6564 // of 8 elements can work here. 6565 return VT == MVT::v8i8 && M.size() == 8; 6566 } 6567 6568 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6569 unsigned Index) { 6570 if (Mask.size() == Elements * 2) 6571 return Index / Elements; 6572 return Mask[Index] == 0 ? 0 : 1; 6573 } 6574 6575 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6576 // checking that pairs of elements in the shuffle mask represent the same index 6577 // in each vector, incrementing the expected index by 2 at each step. 6578 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6579 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6580 // v2={e,f,g,h} 6581 // WhichResult gives the offset for each element in the mask based on which 6582 // of the two results it belongs to. 6583 // 6584 // The transpose can be represented either as: 6585 // result1 = shufflevector v1, v2, result1_shuffle_mask 6586 // result2 = shufflevector v1, v2, result2_shuffle_mask 6587 // where v1/v2 and the shuffle masks have the same number of elements 6588 // (here WhichResult (see below) indicates which result is being checked) 6589 // 6590 // or as: 6591 // results = shufflevector v1, v2, shuffle_mask 6592 // where both results are returned in one vector and the shuffle mask has twice 6593 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6594 // want to check the low half and high half of the shuffle mask as if it were 6595 // the other case 6596 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6597 unsigned EltSz = VT.getScalarSizeInBits(); 6598 if (EltSz == 64) 6599 return false; 6600 6601 unsigned NumElts = VT.getVectorNumElements(); 6602 if (M.size() != NumElts && M.size() != NumElts*2) 6603 return false; 6604 6605 // If the mask is twice as long as the input vector then we need to check the 6606 // upper and lower parts of the mask with a matching value for WhichResult 6607 // FIXME: A mask with only even values will be rejected in case the first 6608 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6609 // M[0] is used to determine WhichResult 6610 for (unsigned i = 0; i < M.size(); i += NumElts) { 6611 WhichResult = SelectPairHalf(NumElts, M, i); 6612 for (unsigned j = 0; j < NumElts; j += 2) { 6613 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6614 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6615 return false; 6616 } 6617 } 6618 6619 if (M.size() == NumElts*2) 6620 WhichResult = 0; 6621 6622 return true; 6623 } 6624 6625 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6626 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6627 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6628 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6629 unsigned EltSz = VT.getScalarSizeInBits(); 6630 if (EltSz == 64) 6631 return false; 6632 6633 unsigned NumElts = VT.getVectorNumElements(); 6634 if (M.size() != NumElts && M.size() != NumElts*2) 6635 return false; 6636 6637 for (unsigned i = 0; i < M.size(); i += NumElts) { 6638 WhichResult = SelectPairHalf(NumElts, M, i); 6639 for (unsigned j = 0; j < NumElts; j += 2) { 6640 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6641 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6642 return false; 6643 } 6644 } 6645 6646 if (M.size() == NumElts*2) 6647 WhichResult = 0; 6648 6649 return true; 6650 } 6651 6652 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6653 // that the mask elements are either all even and in steps of size 2 or all odd 6654 // and in steps of size 2. 6655 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6656 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6657 // v2={e,f,g,h} 6658 // Requires similar checks to that of isVTRNMask with 6659 // respect the how results are returned. 6660 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6661 unsigned EltSz = VT.getScalarSizeInBits(); 6662 if (EltSz == 64) 6663 return false; 6664 6665 unsigned NumElts = VT.getVectorNumElements(); 6666 if (M.size() != NumElts && M.size() != NumElts*2) 6667 return false; 6668 6669 for (unsigned i = 0; i < M.size(); i += NumElts) { 6670 WhichResult = SelectPairHalf(NumElts, M, i); 6671 for (unsigned j = 0; j < NumElts; ++j) { 6672 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6673 return false; 6674 } 6675 } 6676 6677 if (M.size() == NumElts*2) 6678 WhichResult = 0; 6679 6680 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6681 if (VT.is64BitVector() && EltSz == 32) 6682 return false; 6683 6684 return true; 6685 } 6686 6687 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6688 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6689 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6690 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6691 unsigned EltSz = VT.getScalarSizeInBits(); 6692 if (EltSz == 64) 6693 return false; 6694 6695 unsigned NumElts = VT.getVectorNumElements(); 6696 if (M.size() != NumElts && M.size() != NumElts*2) 6697 return false; 6698 6699 unsigned Half = NumElts / 2; 6700 for (unsigned i = 0; i < M.size(); i += NumElts) { 6701 WhichResult = SelectPairHalf(NumElts, M, i); 6702 for (unsigned j = 0; j < NumElts; j += Half) { 6703 unsigned Idx = WhichResult; 6704 for (unsigned k = 0; k < Half; ++k) { 6705 int MIdx = M[i + j + k]; 6706 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6707 return false; 6708 Idx += 2; 6709 } 6710 } 6711 } 6712 6713 if (M.size() == NumElts*2) 6714 WhichResult = 0; 6715 6716 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6717 if (VT.is64BitVector() && EltSz == 32) 6718 return false; 6719 6720 return true; 6721 } 6722 6723 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6724 // that pairs of elements of the shufflemask represent the same index in each 6725 // vector incrementing sequentially through the vectors. 6726 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6727 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6728 // v2={e,f,g,h} 6729 // Requires similar checks to that of isVTRNMask with respect the how results 6730 // are returned. 6731 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6732 unsigned EltSz = VT.getScalarSizeInBits(); 6733 if (EltSz == 64) 6734 return false; 6735 6736 unsigned NumElts = VT.getVectorNumElements(); 6737 if (M.size() != NumElts && M.size() != NumElts*2) 6738 return false; 6739 6740 for (unsigned i = 0; i < M.size(); i += NumElts) { 6741 WhichResult = SelectPairHalf(NumElts, M, i); 6742 unsigned Idx = WhichResult * NumElts / 2; 6743 for (unsigned j = 0; j < NumElts; j += 2) { 6744 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6745 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6746 return false; 6747 Idx += 1; 6748 } 6749 } 6750 6751 if (M.size() == NumElts*2) 6752 WhichResult = 0; 6753 6754 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6755 if (VT.is64BitVector() && EltSz == 32) 6756 return false; 6757 6758 return true; 6759 } 6760 6761 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6762 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6763 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6764 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6765 unsigned EltSz = VT.getScalarSizeInBits(); 6766 if (EltSz == 64) 6767 return false; 6768 6769 unsigned NumElts = VT.getVectorNumElements(); 6770 if (M.size() != NumElts && M.size() != NumElts*2) 6771 return false; 6772 6773 for (unsigned i = 0; i < M.size(); i += NumElts) { 6774 WhichResult = SelectPairHalf(NumElts, M, i); 6775 unsigned Idx = WhichResult * NumElts / 2; 6776 for (unsigned j = 0; j < NumElts; j += 2) { 6777 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6778 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6779 return false; 6780 Idx += 1; 6781 } 6782 } 6783 6784 if (M.size() == NumElts*2) 6785 WhichResult = 0; 6786 6787 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6788 if (VT.is64BitVector() && EltSz == 32) 6789 return false; 6790 6791 return true; 6792 } 6793 6794 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6795 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6796 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6797 unsigned &WhichResult, 6798 bool &isV_UNDEF) { 6799 isV_UNDEF = false; 6800 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6801 return ARMISD::VTRN; 6802 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6803 return ARMISD::VUZP; 6804 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6805 return ARMISD::VZIP; 6806 6807 isV_UNDEF = true; 6808 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6809 return ARMISD::VTRN; 6810 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6811 return ARMISD::VUZP; 6812 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6813 return ARMISD::VZIP; 6814 6815 return 0; 6816 } 6817 6818 /// \return true if this is a reverse operation on an vector. 6819 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6820 unsigned NumElts = VT.getVectorNumElements(); 6821 // Make sure the mask has the right size. 6822 if (NumElts != M.size()) 6823 return false; 6824 6825 // Look for <15, ..., 3, -1, 1, 0>. 6826 for (unsigned i = 0; i != NumElts; ++i) 6827 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6828 return false; 6829 6830 return true; 6831 } 6832 6833 // If N is an integer constant that can be moved into a register in one 6834 // instruction, return an SDValue of such a constant (will become a MOV 6835 // instruction). Otherwise return null. 6836 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6837 const ARMSubtarget *ST, const SDLoc &dl) { 6838 uint64_t Val; 6839 if (!isa<ConstantSDNode>(N)) 6840 return SDValue(); 6841 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6842 6843 if (ST->isThumb1Only()) { 6844 if (Val <= 255 || ~Val <= 255) 6845 return DAG.getConstant(Val, dl, MVT::i32); 6846 } else { 6847 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6848 return DAG.getConstant(Val, dl, MVT::i32); 6849 } 6850 return SDValue(); 6851 } 6852 6853 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 6854 const ARMSubtarget *ST) { 6855 SDLoc dl(Op); 6856 EVT VT = Op.getValueType(); 6857 6858 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 6859 6860 unsigned NumElts = VT.getVectorNumElements(); 6861 unsigned BoolMask; 6862 unsigned BitsPerBool; 6863 if (NumElts == 4) { 6864 BitsPerBool = 4; 6865 BoolMask = 0xf; 6866 } else if (NumElts == 8) { 6867 BitsPerBool = 2; 6868 BoolMask = 0x3; 6869 } else if (NumElts == 16) { 6870 BitsPerBool = 1; 6871 BoolMask = 0x1; 6872 } else 6873 return SDValue(); 6874 6875 // First create base with bits set where known 6876 unsigned Bits32 = 0; 6877 for (unsigned i = 0; i < NumElts; ++i) { 6878 SDValue V = Op.getOperand(i); 6879 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 6880 continue; 6881 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 6882 if (BitSet) 6883 Bits32 |= BoolMask << (i * BitsPerBool); 6884 } 6885 6886 // Add in unknown nodes 6887 // FIXME: Handle splats of the same value better. 6888 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 6889 DAG.getConstant(Bits32, dl, MVT::i32)); 6890 for (unsigned i = 0; i < NumElts; ++i) { 6891 SDValue V = Op.getOperand(i); 6892 if (isa<ConstantSDNode>(V) || V.isUndef()) 6893 continue; 6894 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 6895 DAG.getConstant(i, dl, MVT::i32)); 6896 } 6897 6898 return Base; 6899 } 6900 6901 // If this is a case we can't handle, return null and let the default 6902 // expansion code take care of it. 6903 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6904 const ARMSubtarget *ST) const { 6905 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6906 SDLoc dl(Op); 6907 EVT VT = Op.getValueType(); 6908 6909 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 6910 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 6911 6912 APInt SplatBits, SplatUndef; 6913 unsigned SplatBitSize; 6914 bool HasAnyUndefs; 6915 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6916 if (SplatUndef.isAllOnesValue()) 6917 return DAG.getUNDEF(VT); 6918 6919 if ((ST->hasNEON() && SplatBitSize <= 64) || 6920 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) { 6921 // Check if an immediate VMOV works. 6922 EVT VmovVT; 6923 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 6924 SplatUndef.getZExtValue(), SplatBitSize, 6925 DAG, dl, VmovVT, VT.is128BitVector(), 6926 VMOVModImm); 6927 6928 if (Val.getNode()) { 6929 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6930 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6931 } 6932 6933 // Try an immediate VMVN. 6934 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6935 Val = isVMOVModifiedImm( 6936 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, 6937 DAG, dl, VmovVT, VT.is128BitVector(), 6938 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 6939 if (Val.getNode()) { 6940 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6941 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6942 } 6943 6944 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6945 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6946 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6947 if (ImmVal != -1) { 6948 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6949 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6950 } 6951 } 6952 } 6953 } 6954 6955 // Scan through the operands to see if only one value is used. 6956 // 6957 // As an optimisation, even if more than one value is used it may be more 6958 // profitable to splat with one value then change some lanes. 6959 // 6960 // Heuristically we decide to do this if the vector has a "dominant" value, 6961 // defined as splatted to more than half of the lanes. 6962 unsigned NumElts = VT.getVectorNumElements(); 6963 bool isOnlyLowElement = true; 6964 bool usesOnlyOneValue = true; 6965 bool hasDominantValue = false; 6966 bool isConstant = true; 6967 6968 // Map of the number of times a particular SDValue appears in the 6969 // element list. 6970 DenseMap<SDValue, unsigned> ValueCounts; 6971 SDValue Value; 6972 for (unsigned i = 0; i < NumElts; ++i) { 6973 SDValue V = Op.getOperand(i); 6974 if (V.isUndef()) 6975 continue; 6976 if (i > 0) 6977 isOnlyLowElement = false; 6978 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6979 isConstant = false; 6980 6981 ValueCounts.insert(std::make_pair(V, 0)); 6982 unsigned &Count = ValueCounts[V]; 6983 6984 // Is this value dominant? (takes up more than half of the lanes) 6985 if (++Count > (NumElts / 2)) { 6986 hasDominantValue = true; 6987 Value = V; 6988 } 6989 } 6990 if (ValueCounts.size() != 1) 6991 usesOnlyOneValue = false; 6992 if (!Value.getNode() && !ValueCounts.empty()) 6993 Value = ValueCounts.begin()->first; 6994 6995 if (ValueCounts.empty()) 6996 return DAG.getUNDEF(VT); 6997 6998 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6999 // Keep going if we are hitting this case. 7000 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 7001 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7002 7003 unsigned EltSize = VT.getScalarSizeInBits(); 7004 7005 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 7006 // i32 and try again. 7007 if (hasDominantValue && EltSize <= 32) { 7008 if (!isConstant) { 7009 SDValue N; 7010 7011 // If we are VDUPing a value that comes directly from a vector, that will 7012 // cause an unnecessary move to and from a GPR, where instead we could 7013 // just use VDUPLANE. We can only do this if the lane being extracted 7014 // is at a constant index, as the VDUP from lane instructions only have 7015 // constant-index forms. 7016 ConstantSDNode *constIndex; 7017 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7018 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 7019 // We need to create a new undef vector to use for the VDUPLANE if the 7020 // size of the vector from which we get the value is different than the 7021 // size of the vector that we need to create. We will insert the element 7022 // such that the register coalescer will remove unnecessary copies. 7023 if (VT != Value->getOperand(0).getValueType()) { 7024 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 7025 VT.getVectorNumElements(); 7026 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7027 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 7028 Value, DAG.getConstant(index, dl, MVT::i32)), 7029 DAG.getConstant(index, dl, MVT::i32)); 7030 } else 7031 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7032 Value->getOperand(0), Value->getOperand(1)); 7033 } else 7034 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 7035 7036 if (!usesOnlyOneValue) { 7037 // The dominant value was splatted as 'N', but we now have to insert 7038 // all differing elements. 7039 for (unsigned I = 0; I < NumElts; ++I) { 7040 if (Op.getOperand(I) == Value) 7041 continue; 7042 SmallVector<SDValue, 3> Ops; 7043 Ops.push_back(N); 7044 Ops.push_back(Op.getOperand(I)); 7045 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7046 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7047 } 7048 } 7049 return N; 7050 } 7051 if (VT.getVectorElementType().isFloatingPoint()) { 7052 SmallVector<SDValue, 8> Ops; 7053 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7054 assert(FVT == MVT::f32 || FVT == MVT::f16); 7055 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7056 for (unsigned i = 0; i < NumElts; ++i) 7057 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7058 Op.getOperand(i))); 7059 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7060 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7061 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7062 if (Val.getNode()) 7063 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7064 } 7065 if (usesOnlyOneValue) { 7066 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7067 if (isConstant && Val.getNode()) 7068 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7069 } 7070 } 7071 7072 // If all elements are constants and the case above didn't get hit, fall back 7073 // to the default expansion, which will generate a load from the constant 7074 // pool. 7075 if (isConstant) 7076 return SDValue(); 7077 7078 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 7079 if (NumElts >= 4) { 7080 SDValue shuffle = ReconstructShuffle(Op, DAG); 7081 if (shuffle != SDValue()) 7082 return shuffle; 7083 } 7084 7085 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7086 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7087 // into two 64-bit vectors; we might discover a better way to lower it. 7088 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7089 EVT ExtVT = VT.getVectorElementType(); 7090 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7091 SDValue Lower = 7092 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7093 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7094 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7095 SDValue Upper = DAG.getBuildVector( 7096 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7097 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7098 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7099 if (Lower && Upper) 7100 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7101 } 7102 7103 // Vectors with 32- or 64-bit elements can be built by directly assigning 7104 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7105 // will be legalized. 7106 if (EltSize >= 32) { 7107 // Do the expansion with floating-point types, since that is what the VFP 7108 // registers are defined to use, and since i64 is not legal. 7109 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7110 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7111 SmallVector<SDValue, 8> Ops; 7112 for (unsigned i = 0; i < NumElts; ++i) 7113 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7114 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7115 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7116 } 7117 7118 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7119 // know the default expansion would otherwise fall back on something even 7120 // worse. For a vector with one or two non-undef values, that's 7121 // scalar_to_vector for the elements followed by a shuffle (provided the 7122 // shuffle is valid for the target) and materialization element by element 7123 // on the stack followed by a load for everything else. 7124 if (!isConstant && !usesOnlyOneValue) { 7125 SDValue Vec = DAG.getUNDEF(VT); 7126 for (unsigned i = 0 ; i < NumElts; ++i) { 7127 SDValue V = Op.getOperand(i); 7128 if (V.isUndef()) 7129 continue; 7130 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7131 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7132 } 7133 return Vec; 7134 } 7135 7136 return SDValue(); 7137 } 7138 7139 // Gather data to see if the operation can be modelled as a 7140 // shuffle in combination with VEXTs. 7141 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7142 SelectionDAG &DAG) const { 7143 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7144 SDLoc dl(Op); 7145 EVT VT = Op.getValueType(); 7146 unsigned NumElts = VT.getVectorNumElements(); 7147 7148 struct ShuffleSourceInfo { 7149 SDValue Vec; 7150 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7151 unsigned MaxElt = 0; 7152 7153 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7154 // be compatible with the shuffle we intend to construct. As a result 7155 // ShuffleVec will be some sliding window into the original Vec. 7156 SDValue ShuffleVec; 7157 7158 // Code should guarantee that element i in Vec starts at element "WindowBase 7159 // + i * WindowScale in ShuffleVec". 7160 int WindowBase = 0; 7161 int WindowScale = 1; 7162 7163 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7164 7165 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7166 }; 7167 7168 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7169 // node. 7170 SmallVector<ShuffleSourceInfo, 2> Sources; 7171 for (unsigned i = 0; i < NumElts; ++i) { 7172 SDValue V = Op.getOperand(i); 7173 if (V.isUndef()) 7174 continue; 7175 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7176 // A shuffle can only come from building a vector from various 7177 // elements of other vectors. 7178 return SDValue(); 7179 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7180 // Furthermore, shuffles require a constant mask, whereas extractelts 7181 // accept variable indices. 7182 return SDValue(); 7183 } 7184 7185 // Add this element source to the list if it's not already there. 7186 SDValue SourceVec = V.getOperand(0); 7187 auto Source = llvm::find(Sources, SourceVec); 7188 if (Source == Sources.end()) 7189 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7190 7191 // Update the minimum and maximum lane number seen. 7192 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7193 Source->MinElt = std::min(Source->MinElt, EltNo); 7194 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7195 } 7196 7197 // Currently only do something sane when at most two source vectors 7198 // are involved. 7199 if (Sources.size() > 2) 7200 return SDValue(); 7201 7202 // Find out the smallest element size among result and two sources, and use 7203 // it as element size to build the shuffle_vector. 7204 EVT SmallestEltTy = VT.getVectorElementType(); 7205 for (auto &Source : Sources) { 7206 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7207 if (SrcEltTy.bitsLT(SmallestEltTy)) 7208 SmallestEltTy = SrcEltTy; 7209 } 7210 unsigned ResMultiplier = 7211 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7212 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7213 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7214 7215 // If the source vector is too wide or too narrow, we may nevertheless be able 7216 // to construct a compatible shuffle either by concatenating it with UNDEF or 7217 // extracting a suitable range of elements. 7218 for (auto &Src : Sources) { 7219 EVT SrcVT = Src.ShuffleVec.getValueType(); 7220 7221 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 7222 continue; 7223 7224 // This stage of the search produces a source with the same element type as 7225 // the original, but with a total width matching the BUILD_VECTOR output. 7226 EVT EltVT = SrcVT.getVectorElementType(); 7227 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 7228 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7229 7230 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 7231 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 7232 return SDValue(); 7233 // We can pad out the smaller vector for free, so if it's part of a 7234 // shuffle... 7235 Src.ShuffleVec = 7236 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7237 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7238 continue; 7239 } 7240 7241 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 7242 return SDValue(); 7243 7244 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7245 // Span too large for a VEXT to cope 7246 return SDValue(); 7247 } 7248 7249 if (Src.MinElt >= NumSrcElts) { 7250 // The extraction can just take the second half 7251 Src.ShuffleVec = 7252 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7253 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7254 Src.WindowBase = -NumSrcElts; 7255 } else if (Src.MaxElt < NumSrcElts) { 7256 // The extraction can just take the first half 7257 Src.ShuffleVec = 7258 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7259 DAG.getConstant(0, dl, MVT::i32)); 7260 } else { 7261 // An actual VEXT is needed 7262 SDValue VEXTSrc1 = 7263 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7264 DAG.getConstant(0, dl, MVT::i32)); 7265 SDValue VEXTSrc2 = 7266 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7267 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7268 7269 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7270 VEXTSrc2, 7271 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7272 Src.WindowBase = -Src.MinElt; 7273 } 7274 } 7275 7276 // Another possible incompatibility occurs from the vector element types. We 7277 // can fix this by bitcasting the source vectors to the same type we intend 7278 // for the shuffle. 7279 for (auto &Src : Sources) { 7280 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7281 if (SrcEltTy == SmallestEltTy) 7282 continue; 7283 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7284 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 7285 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7286 Src.WindowBase *= Src.WindowScale; 7287 } 7288 7289 // Final sanity check before we try to actually produce a shuffle. 7290 LLVM_DEBUG(for (auto Src 7291 : Sources) 7292 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7293 7294 // The stars all align, our next step is to produce the mask for the shuffle. 7295 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7296 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7297 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7298 SDValue Entry = Op.getOperand(i); 7299 if (Entry.isUndef()) 7300 continue; 7301 7302 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7303 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7304 7305 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7306 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7307 // segment. 7308 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7309 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 7310 VT.getScalarSizeInBits()); 7311 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7312 7313 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7314 // starting at the appropriate offset. 7315 int *LaneMask = &Mask[i * ResMultiplier]; 7316 7317 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7318 ExtractBase += NumElts * (Src - Sources.begin()); 7319 for (int j = 0; j < LanesDefined; ++j) 7320 LaneMask[j] = ExtractBase + j; 7321 } 7322 7323 // Final check before we try to produce nonsense... 7324 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 7325 return SDValue(); 7326 7327 // We can't handle more than two sources. This should have already 7328 // been checked before this point. 7329 assert(Sources.size() <= 2 && "Too many sources!"); 7330 7331 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7332 for (unsigned i = 0; i < Sources.size(); ++i) 7333 ShuffleOps[i] = Sources[i].ShuffleVec; 7334 7335 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7336 ShuffleOps[1], Mask); 7337 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 7338 } 7339 7340 enum ShuffleOpCodes { 7341 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7342 OP_VREV, 7343 OP_VDUP0, 7344 OP_VDUP1, 7345 OP_VDUP2, 7346 OP_VDUP3, 7347 OP_VEXT1, 7348 OP_VEXT2, 7349 OP_VEXT3, 7350 OP_VUZPL, // VUZP, left result 7351 OP_VUZPR, // VUZP, right result 7352 OP_VZIPL, // VZIP, left result 7353 OP_VZIPR, // VZIP, right result 7354 OP_VTRNL, // VTRN, left result 7355 OP_VTRNR // VTRN, right result 7356 }; 7357 7358 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7359 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7360 switch (OpNum) { 7361 case OP_COPY: 7362 case OP_VREV: 7363 case OP_VDUP0: 7364 case OP_VDUP1: 7365 case OP_VDUP2: 7366 case OP_VDUP3: 7367 return true; 7368 } 7369 return false; 7370 } 7371 7372 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7373 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7374 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7375 /// are assumed to be legal. 7376 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7377 if (VT.getVectorNumElements() == 4 && 7378 (VT.is128BitVector() || VT.is64BitVector())) { 7379 unsigned PFIndexes[4]; 7380 for (unsigned i = 0; i != 4; ++i) { 7381 if (M[i] < 0) 7382 PFIndexes[i] = 8; 7383 else 7384 PFIndexes[i] = M[i]; 7385 } 7386 7387 // Compute the index in the perfect shuffle table. 7388 unsigned PFTableIndex = 7389 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7390 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7391 unsigned Cost = (PFEntry >> 30); 7392 7393 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7394 return true; 7395 } 7396 7397 bool ReverseVEXT, isV_UNDEF; 7398 unsigned Imm, WhichResult; 7399 7400 unsigned EltSize = VT.getScalarSizeInBits(); 7401 if (EltSize >= 32 || 7402 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7403 isVREVMask(M, VT, 64) || 7404 isVREVMask(M, VT, 32) || 7405 isVREVMask(M, VT, 16)) 7406 return true; 7407 else if (Subtarget->hasNEON() && 7408 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7409 isVTBLMask(M, VT) || 7410 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7411 return true; 7412 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7413 isReverseMask(M, VT)) 7414 return true; 7415 else 7416 return false; 7417 } 7418 7419 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7420 /// the specified operations to build the shuffle. 7421 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7422 SDValue RHS, SelectionDAG &DAG, 7423 const SDLoc &dl) { 7424 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7425 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7426 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7427 7428 if (OpNum == OP_COPY) { 7429 if (LHSID == (1*9+2)*9+3) return LHS; 7430 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7431 return RHS; 7432 } 7433 7434 SDValue OpLHS, OpRHS; 7435 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7436 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7437 EVT VT = OpLHS.getValueType(); 7438 7439 switch (OpNum) { 7440 default: llvm_unreachable("Unknown shuffle opcode!"); 7441 case OP_VREV: 7442 // VREV divides the vector in half and swaps within the half. 7443 if (VT.getVectorElementType() == MVT::i32 || 7444 VT.getVectorElementType() == MVT::f32) 7445 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7446 // vrev <4 x i16> -> VREV32 7447 if (VT.getVectorElementType() == MVT::i16) 7448 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7449 // vrev <4 x i8> -> VREV16 7450 assert(VT.getVectorElementType() == MVT::i8); 7451 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 7452 case OP_VDUP0: 7453 case OP_VDUP1: 7454 case OP_VDUP2: 7455 case OP_VDUP3: 7456 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7457 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 7458 case OP_VEXT1: 7459 case OP_VEXT2: 7460 case OP_VEXT3: 7461 return DAG.getNode(ARMISD::VEXT, dl, VT, 7462 OpLHS, OpRHS, 7463 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 7464 case OP_VUZPL: 7465 case OP_VUZPR: 7466 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7467 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7468 case OP_VZIPL: 7469 case OP_VZIPR: 7470 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7471 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7472 case OP_VTRNL: 7473 case OP_VTRNR: 7474 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7475 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7476 } 7477 } 7478 7479 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7480 ArrayRef<int> ShuffleMask, 7481 SelectionDAG &DAG) { 7482 // Check to see if we can use the VTBL instruction. 7483 SDValue V1 = Op.getOperand(0); 7484 SDValue V2 = Op.getOperand(1); 7485 SDLoc DL(Op); 7486 7487 SmallVector<SDValue, 8> VTBLMask; 7488 for (ArrayRef<int>::iterator 7489 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7490 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7491 7492 if (V2.getNode()->isUndef()) 7493 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7494 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7495 7496 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7497 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7498 } 7499 7500 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7501 SelectionDAG &DAG) { 7502 SDLoc DL(Op); 7503 SDValue OpLHS = Op.getOperand(0); 7504 EVT VT = OpLHS.getValueType(); 7505 7506 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7507 "Expect an v8i16/v16i8 type"); 7508 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7509 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7510 // extract the first 8 bytes into the top double word and the last 8 bytes 7511 // into the bottom double word. The v8i16 case is similar. 7512 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7513 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7514 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7515 } 7516 7517 static EVT getVectorTyFromPredicateVector(EVT VT) { 7518 switch (VT.getSimpleVT().SimpleTy) { 7519 case MVT::v4i1: 7520 return MVT::v4i32; 7521 case MVT::v8i1: 7522 return MVT::v8i16; 7523 case MVT::v16i1: 7524 return MVT::v16i8; 7525 default: 7526 llvm_unreachable("Unexpected vector predicate type"); 7527 } 7528 } 7529 7530 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 7531 SelectionDAG &DAG) { 7532 // Converting from boolean predicates to integers involves creating a vector 7533 // of all ones or all zeroes and selecting the lanes based upon the real 7534 // predicate. 7535 SDValue AllOnes = 7536 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 7537 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 7538 7539 SDValue AllZeroes = 7540 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 7541 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 7542 7543 // Get full vector type from predicate type 7544 EVT NewVT = getVectorTyFromPredicateVector(VT); 7545 7546 SDValue RecastV1; 7547 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 7548 // this to a v16i1. This cannot be done with an ordinary bitcast because the 7549 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 7550 // since we know in hardware the sizes are really the same. 7551 if (VT != MVT::v16i1) 7552 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 7553 else 7554 RecastV1 = Pred; 7555 7556 // Select either all ones or zeroes depending upon the real predicate bits. 7557 SDValue PredAsVector = 7558 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 7559 7560 // Recast our new predicate-as-integer v16i8 vector into something 7561 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 7562 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 7563 } 7564 7565 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 7566 const ARMSubtarget *ST) { 7567 EVT VT = Op.getValueType(); 7568 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7569 ArrayRef<int> ShuffleMask = SVN->getMask(); 7570 7571 assert(ST->hasMVEIntegerOps() && 7572 "No support for vector shuffle of boolean predicates"); 7573 7574 SDValue V1 = Op.getOperand(0); 7575 SDLoc dl(Op); 7576 if (isReverseMask(ShuffleMask, VT)) { 7577 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 7578 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 7579 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 7580 DAG.getConstant(16, dl, MVT::i32)); 7581 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 7582 } 7583 7584 // Until we can come up with optimised cases for every single vector 7585 // shuffle in existence we have chosen the least painful strategy. This is 7586 // to essentially promote the boolean predicate to a 8-bit integer, where 7587 // each predicate represents a byte. Then we fall back on a normal integer 7588 // vector shuffle and convert the result back into a predicate vector. In 7589 // many cases the generated code might be even better than scalar code 7590 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 7591 // fields in a register into 8 other arbitrary 2-bit fields! 7592 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 7593 EVT NewVT = PredAsVector.getValueType(); 7594 7595 // Do the shuffle! 7596 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 7597 DAG.getUNDEF(NewVT), ShuffleMask); 7598 7599 // Now return the result of comparing the shuffled vector with zero, 7600 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7601 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 7602 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7603 } 7604 7605 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 7606 const ARMSubtarget *ST) { 7607 SDValue V1 = Op.getOperand(0); 7608 SDValue V2 = Op.getOperand(1); 7609 SDLoc dl(Op); 7610 EVT VT = Op.getValueType(); 7611 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7612 unsigned EltSize = VT.getScalarSizeInBits(); 7613 7614 if (ST->hasMVEIntegerOps() && EltSize == 1) 7615 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 7616 7617 // Convert shuffles that are directly supported on NEON to target-specific 7618 // DAG nodes, instead of keeping them as shuffles and matching them again 7619 // during code selection. This is more efficient and avoids the possibility 7620 // of inconsistencies between legalization and selection. 7621 // FIXME: floating-point vectors should be canonicalized to integer vectors 7622 // of the same time so that they get CSEd properly. 7623 ArrayRef<int> ShuffleMask = SVN->getMask(); 7624 7625 if (EltSize <= 32) { 7626 if (SVN->isSplat()) { 7627 int Lane = SVN->getSplatIndex(); 7628 // If this is undef splat, generate it via "just" vdup, if possible. 7629 if (Lane == -1) Lane = 0; 7630 7631 // Test if V1 is a SCALAR_TO_VECTOR. 7632 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7633 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7634 } 7635 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7636 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7637 // reaches it). 7638 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7639 !isa<ConstantSDNode>(V1.getOperand(0))) { 7640 bool IsScalarToVector = true; 7641 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7642 if (!V1.getOperand(i).isUndef()) { 7643 IsScalarToVector = false; 7644 break; 7645 } 7646 if (IsScalarToVector) 7647 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7648 } 7649 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7650 DAG.getConstant(Lane, dl, MVT::i32)); 7651 } 7652 7653 bool ReverseVEXT = false; 7654 unsigned Imm = 0; 7655 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7656 if (ReverseVEXT) 7657 std::swap(V1, V2); 7658 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7659 DAG.getConstant(Imm, dl, MVT::i32)); 7660 } 7661 7662 if (isVREVMask(ShuffleMask, VT, 64)) 7663 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7664 if (isVREVMask(ShuffleMask, VT, 32)) 7665 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7666 if (isVREVMask(ShuffleMask, VT, 16)) 7667 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7668 7669 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7670 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7671 DAG.getConstant(Imm, dl, MVT::i32)); 7672 } 7673 7674 // Check for Neon shuffles that modify both input vectors in place. 7675 // If both results are used, i.e., if there are two shuffles with the same 7676 // source operands and with masks corresponding to both results of one of 7677 // these operations, DAG memoization will ensure that a single node is 7678 // used for both shuffles. 7679 unsigned WhichResult = 0; 7680 bool isV_UNDEF = false; 7681 if (ST->hasNEON()) { 7682 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7683 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7684 if (isV_UNDEF) 7685 V2 = V1; 7686 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7687 .getValue(WhichResult); 7688 } 7689 } 7690 7691 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7692 // shuffles that produce a result larger than their operands with: 7693 // shuffle(concat(v1, undef), concat(v2, undef)) 7694 // -> 7695 // shuffle(concat(v1, v2), undef) 7696 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7697 // 7698 // This is useful in the general case, but there are special cases where 7699 // native shuffles produce larger results: the two-result ops. 7700 // 7701 // Look through the concat when lowering them: 7702 // shuffle(concat(v1, v2), undef) 7703 // -> 7704 // concat(VZIP(v1, v2):0, :1) 7705 // 7706 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7707 SDValue SubV1 = V1->getOperand(0); 7708 SDValue SubV2 = V1->getOperand(1); 7709 EVT SubVT = SubV1.getValueType(); 7710 7711 // We expect these to have been canonicalized to -1. 7712 assert(llvm::all_of(ShuffleMask, [&](int i) { 7713 return i < (int)VT.getVectorNumElements(); 7714 }) && "Unexpected shuffle index into UNDEF operand!"); 7715 7716 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7717 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7718 if (isV_UNDEF) 7719 SubV2 = SubV1; 7720 assert((WhichResult == 0) && 7721 "In-place shuffle of concat can only have one result!"); 7722 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7723 SubV1, SubV2); 7724 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7725 Res.getValue(1)); 7726 } 7727 } 7728 } 7729 7730 // If the shuffle is not directly supported and it has 4 elements, use 7731 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7732 unsigned NumElts = VT.getVectorNumElements(); 7733 if (NumElts == 4) { 7734 unsigned PFIndexes[4]; 7735 for (unsigned i = 0; i != 4; ++i) { 7736 if (ShuffleMask[i] < 0) 7737 PFIndexes[i] = 8; 7738 else 7739 PFIndexes[i] = ShuffleMask[i]; 7740 } 7741 7742 // Compute the index in the perfect shuffle table. 7743 unsigned PFTableIndex = 7744 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7745 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7746 unsigned Cost = (PFEntry >> 30); 7747 7748 if (Cost <= 4) { 7749 if (ST->hasNEON()) 7750 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7751 else if (isLegalMVEShuffleOp(PFEntry)) { 7752 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7753 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7754 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 7755 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 7756 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 7757 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7758 } 7759 } 7760 } 7761 7762 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7763 if (EltSize >= 32) { 7764 // Do the expansion with floating-point types, since that is what the VFP 7765 // registers are defined to use, and since i64 is not legal. 7766 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7767 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7768 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7769 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7770 SmallVector<SDValue, 8> Ops; 7771 for (unsigned i = 0; i < NumElts; ++i) { 7772 if (ShuffleMask[i] < 0) 7773 Ops.push_back(DAG.getUNDEF(EltVT)); 7774 else 7775 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7776 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7777 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7778 dl, MVT::i32))); 7779 } 7780 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7781 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7782 } 7783 7784 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7785 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7786 7787 if (ST->hasNEON() && VT == MVT::v8i8) 7788 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7789 return NewOp; 7790 7791 return SDValue(); 7792 } 7793 7794 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 7795 const ARMSubtarget *ST) { 7796 EVT VecVT = Op.getOperand(0).getValueType(); 7797 SDLoc dl(Op); 7798 7799 assert(ST->hasMVEIntegerOps() && 7800 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 7801 7802 SDValue Conv = 7803 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 7804 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 7805 unsigned LaneWidth = 7806 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 7807 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 7808 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 7809 Op.getOperand(1), DAG.getValueType(MVT::i1)); 7810 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 7811 DAG.getConstant(~Mask, dl, MVT::i32)); 7812 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 7813 } 7814 7815 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 7816 SelectionDAG &DAG) const { 7817 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7818 SDValue Lane = Op.getOperand(2); 7819 if (!isa<ConstantSDNode>(Lane)) 7820 return SDValue(); 7821 7822 SDValue Elt = Op.getOperand(1); 7823 EVT EltVT = Elt.getValueType(); 7824 7825 if (Subtarget->hasMVEIntegerOps() && 7826 Op.getValueType().getScalarSizeInBits() == 1) 7827 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 7828 7829 if (getTypeAction(*DAG.getContext(), EltVT) == 7830 TargetLowering::TypePromoteFloat) { 7831 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 7832 // but the type system will try to do that if we don't intervene. 7833 // Reinterpret any such vector-element insertion as one with the 7834 // corresponding integer types. 7835 7836 SDLoc dl(Op); 7837 7838 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 7839 assert(getTypeAction(*DAG.getContext(), IEltVT) != 7840 TargetLowering::TypePromoteFloat); 7841 7842 SDValue VecIn = Op.getOperand(0); 7843 EVT VecVT = VecIn.getValueType(); 7844 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 7845 VecVT.getVectorNumElements()); 7846 7847 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 7848 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 7849 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 7850 IVecIn, IElt, Lane); 7851 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 7852 } 7853 7854 return Op; 7855 } 7856 7857 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 7858 const ARMSubtarget *ST) { 7859 EVT VecVT = Op.getOperand(0).getValueType(); 7860 SDLoc dl(Op); 7861 7862 assert(ST->hasMVEIntegerOps() && 7863 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 7864 7865 SDValue Conv = 7866 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 7867 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7868 unsigned LaneWidth = 7869 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 7870 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 7871 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 7872 return Shift; 7873 } 7874 7875 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 7876 const ARMSubtarget *ST) { 7877 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7878 SDValue Lane = Op.getOperand(1); 7879 if (!isa<ConstantSDNode>(Lane)) 7880 return SDValue(); 7881 7882 SDValue Vec = Op.getOperand(0); 7883 EVT VT = Vec.getValueType(); 7884 7885 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7886 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 7887 7888 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7889 SDLoc dl(Op); 7890 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7891 } 7892 7893 return Op; 7894 } 7895 7896 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 7897 const ARMSubtarget *ST) { 7898 SDValue V1 = Op.getOperand(0); 7899 SDValue V2 = Op.getOperand(1); 7900 SDLoc dl(Op); 7901 EVT VT = Op.getValueType(); 7902 EVT Op1VT = V1.getValueType(); 7903 EVT Op2VT = V2.getValueType(); 7904 unsigned NumElts = VT.getVectorNumElements(); 7905 7906 assert(Op1VT == Op2VT && "Operand types don't match!"); 7907 assert(VT.getScalarSizeInBits() == 1 && 7908 "Unexpected custom CONCAT_VECTORS lowering"); 7909 assert(ST->hasMVEIntegerOps() && 7910 "CONCAT_VECTORS lowering only supported for MVE"); 7911 7912 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 7913 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 7914 7915 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 7916 // promoted to v8i16, etc. 7917 7918 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 7919 7920 // Extract the vector elements from Op1 and Op2 one by one and truncate them 7921 // to be the right size for the destination. For example, if Op1 is v4i1 then 7922 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 7923 // which when promoted is v8i16. That means each i32 element from Op1 needs 7924 // truncating to i16 and inserting in the result. 7925 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 7926 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 7927 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 7928 EVT NewVT = NewV.getValueType(); 7929 EVT ConcatVT = ConVec.getValueType(); 7930 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 7931 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 7932 DAG.getIntPtrConstant(i, dl)); 7933 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 7934 DAG.getConstant(j, dl, MVT::i32)); 7935 } 7936 return ConVec; 7937 }; 7938 unsigned j = 0; 7939 ConVec = ExractInto(NewV1, ConVec, j); 7940 ConVec = ExractInto(NewV2, ConVec, j); 7941 7942 // Now return the result of comparing the subvector with zero, 7943 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7944 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 7945 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7946 } 7947 7948 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 7949 const ARMSubtarget *ST) { 7950 EVT VT = Op->getValueType(0); 7951 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7952 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 7953 7954 // The only time a CONCAT_VECTORS operation can have legal types is when 7955 // two 64-bit vectors are concatenated to a 128-bit vector. 7956 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7957 "unexpected CONCAT_VECTORS"); 7958 SDLoc dl(Op); 7959 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7960 SDValue Op0 = Op.getOperand(0); 7961 SDValue Op1 = Op.getOperand(1); 7962 if (!Op0.isUndef()) 7963 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7964 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7965 DAG.getIntPtrConstant(0, dl)); 7966 if (!Op1.isUndef()) 7967 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7968 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7969 DAG.getIntPtrConstant(1, dl)); 7970 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7971 } 7972 7973 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 7974 const ARMSubtarget *ST) { 7975 SDValue V1 = Op.getOperand(0); 7976 SDValue V2 = Op.getOperand(1); 7977 SDLoc dl(Op); 7978 EVT VT = Op.getValueType(); 7979 EVT Op1VT = V1.getValueType(); 7980 unsigned NumElts = VT.getVectorNumElements(); 7981 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 7982 7983 assert(VT.getScalarSizeInBits() == 1 && 7984 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 7985 assert(ST->hasMVEIntegerOps() && 7986 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 7987 7988 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 7989 7990 // We now have Op1 promoted to a vector of integers, where v8i1 gets 7991 // promoted to v8i16, etc. 7992 7993 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 7994 7995 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 7996 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 7997 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 7998 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 7999 DAG.getIntPtrConstant(i, dl)); 8000 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 8001 DAG.getConstant(j, dl, MVT::i32)); 8002 } 8003 8004 // Now return the result of comparing the subvector with zero, 8005 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 8006 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 8007 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 8008 } 8009 8010 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 8011 /// element has been zero/sign-extended, depending on the isSigned parameter, 8012 /// from an integer type half its size. 8013 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 8014 bool isSigned) { 8015 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 8016 EVT VT = N->getValueType(0); 8017 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 8018 SDNode *BVN = N->getOperand(0).getNode(); 8019 if (BVN->getValueType(0) != MVT::v4i32 || 8020 BVN->getOpcode() != ISD::BUILD_VECTOR) 8021 return false; 8022 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8023 unsigned HiElt = 1 - LoElt; 8024 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 8025 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 8026 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 8027 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 8028 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 8029 return false; 8030 if (isSigned) { 8031 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 8032 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 8033 return true; 8034 } else { 8035 if (Hi0->isNullValue() && Hi1->isNullValue()) 8036 return true; 8037 } 8038 return false; 8039 } 8040 8041 if (N->getOpcode() != ISD::BUILD_VECTOR) 8042 return false; 8043 8044 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8045 SDNode *Elt = N->getOperand(i).getNode(); 8046 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8047 unsigned EltSize = VT.getScalarSizeInBits(); 8048 unsigned HalfSize = EltSize / 2; 8049 if (isSigned) { 8050 if (!isIntN(HalfSize, C->getSExtValue())) 8051 return false; 8052 } else { 8053 if (!isUIntN(HalfSize, C->getZExtValue())) 8054 return false; 8055 } 8056 continue; 8057 } 8058 return false; 8059 } 8060 8061 return true; 8062 } 8063 8064 /// isSignExtended - Check if a node is a vector value that is sign-extended 8065 /// or a constant BUILD_VECTOR with sign-extended elements. 8066 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8067 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8068 return true; 8069 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8070 return true; 8071 return false; 8072 } 8073 8074 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8075 /// or a constant BUILD_VECTOR with zero-extended elements. 8076 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8077 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8078 return true; 8079 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8080 return true; 8081 return false; 8082 } 8083 8084 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8085 if (OrigVT.getSizeInBits() >= 64) 8086 return OrigVT; 8087 8088 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8089 8090 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8091 switch (OrigSimpleTy) { 8092 default: llvm_unreachable("Unexpected Vector Type"); 8093 case MVT::v2i8: 8094 case MVT::v2i16: 8095 return MVT::v2i32; 8096 case MVT::v4i8: 8097 return MVT::v4i16; 8098 } 8099 } 8100 8101 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8102 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8103 /// We insert the required extension here to get the vector to fill a D register. 8104 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8105 const EVT &OrigTy, 8106 const EVT &ExtTy, 8107 unsigned ExtOpcode) { 8108 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8109 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8110 // 64-bits we need to insert a new extension so that it will be 64-bits. 8111 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8112 if (OrigTy.getSizeInBits() >= 64) 8113 return N; 8114 8115 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8116 EVT NewVT = getExtensionTo64Bits(OrigTy); 8117 8118 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8119 } 8120 8121 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8122 /// does not do any sign/zero extension. If the original vector is less 8123 /// than 64 bits, an appropriate extension will be added after the load to 8124 /// reach a total size of 64 bits. We have to add the extension separately 8125 /// because ARM does not have a sign/zero extending load for vectors. 8126 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8127 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8128 8129 // The load already has the right type. 8130 if (ExtendedTy == LD->getMemoryVT()) 8131 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8132 LD->getBasePtr(), LD->getPointerInfo(), 8133 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8134 8135 // We need to create a zextload/sextload. We cannot just create a load 8136 // followed by a zext/zext node because LowerMUL is also run during normal 8137 // operation legalization where we can't create illegal types. 8138 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8139 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8140 LD->getMemoryVT(), LD->getAlignment(), 8141 LD->getMemOperand()->getFlags()); 8142 } 8143 8144 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8145 /// extending load, or BUILD_VECTOR with extended elements, return the 8146 /// unextended value. The unextended vector should be 64 bits so that it can 8147 /// be used as an operand to a VMULL instruction. If the original vector size 8148 /// before extension is less than 64 bits we add a an extension to resize 8149 /// the vector to 64 bits. 8150 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8151 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8152 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8153 N->getOperand(0)->getValueType(0), 8154 N->getValueType(0), 8155 N->getOpcode()); 8156 8157 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8158 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8159 "Expected extending load"); 8160 8161 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8162 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8163 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8164 SDValue extLoad = 8165 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8166 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8167 8168 return newLoad; 8169 } 8170 8171 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8172 // have been legalized as a BITCAST from v4i32. 8173 if (N->getOpcode() == ISD::BITCAST) { 8174 SDNode *BVN = N->getOperand(0).getNode(); 8175 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8176 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8177 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8178 return DAG.getBuildVector( 8179 MVT::v2i32, SDLoc(N), 8180 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8181 } 8182 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8183 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8184 EVT VT = N->getValueType(0); 8185 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8186 unsigned NumElts = VT.getVectorNumElements(); 8187 MVT TruncVT = MVT::getIntegerVT(EltSize); 8188 SmallVector<SDValue, 8> Ops; 8189 SDLoc dl(N); 8190 for (unsigned i = 0; i != NumElts; ++i) { 8191 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8192 const APInt &CInt = C->getAPIntValue(); 8193 // Element types smaller than 32 bits are not legal, so use i32 elements. 8194 // The values are implicitly truncated so sext vs. zext doesn't matter. 8195 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8196 } 8197 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8198 } 8199 8200 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8201 unsigned Opcode = N->getOpcode(); 8202 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8203 SDNode *N0 = N->getOperand(0).getNode(); 8204 SDNode *N1 = N->getOperand(1).getNode(); 8205 return N0->hasOneUse() && N1->hasOneUse() && 8206 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8207 } 8208 return false; 8209 } 8210 8211 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8212 unsigned Opcode = N->getOpcode(); 8213 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8214 SDNode *N0 = N->getOperand(0).getNode(); 8215 SDNode *N1 = N->getOperand(1).getNode(); 8216 return N0->hasOneUse() && N1->hasOneUse() && 8217 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8218 } 8219 return false; 8220 } 8221 8222 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8223 // Multiplications are only custom-lowered for 128-bit vectors so that 8224 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8225 EVT VT = Op.getValueType(); 8226 assert(VT.is128BitVector() && VT.isInteger() && 8227 "unexpected type for custom-lowering ISD::MUL"); 8228 SDNode *N0 = Op.getOperand(0).getNode(); 8229 SDNode *N1 = Op.getOperand(1).getNode(); 8230 unsigned NewOpc = 0; 8231 bool isMLA = false; 8232 bool isN0SExt = isSignExtended(N0, DAG); 8233 bool isN1SExt = isSignExtended(N1, DAG); 8234 if (isN0SExt && isN1SExt) 8235 NewOpc = ARMISD::VMULLs; 8236 else { 8237 bool isN0ZExt = isZeroExtended(N0, DAG); 8238 bool isN1ZExt = isZeroExtended(N1, DAG); 8239 if (isN0ZExt && isN1ZExt) 8240 NewOpc = ARMISD::VMULLu; 8241 else if (isN1SExt || isN1ZExt) { 8242 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8243 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8244 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8245 NewOpc = ARMISD::VMULLs; 8246 isMLA = true; 8247 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8248 NewOpc = ARMISD::VMULLu; 8249 isMLA = true; 8250 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8251 std::swap(N0, N1); 8252 NewOpc = ARMISD::VMULLu; 8253 isMLA = true; 8254 } 8255 } 8256 8257 if (!NewOpc) { 8258 if (VT == MVT::v2i64) 8259 // Fall through to expand this. It is not legal. 8260 return SDValue(); 8261 else 8262 // Other vector multiplications are legal. 8263 return Op; 8264 } 8265 } 8266 8267 // Legalize to a VMULL instruction. 8268 SDLoc DL(Op); 8269 SDValue Op0; 8270 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8271 if (!isMLA) { 8272 Op0 = SkipExtensionForVMULL(N0, DAG); 8273 assert(Op0.getValueType().is64BitVector() && 8274 Op1.getValueType().is64BitVector() && 8275 "unexpected types for extended operands to VMULL"); 8276 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8277 } 8278 8279 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8280 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8281 // vmull q0, d4, d6 8282 // vmlal q0, d5, d6 8283 // is faster than 8284 // vaddl q0, d4, d5 8285 // vmovl q1, d6 8286 // vmul q0, q0, q1 8287 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8288 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8289 EVT Op1VT = Op1.getValueType(); 8290 return DAG.getNode(N0->getOpcode(), DL, VT, 8291 DAG.getNode(NewOpc, DL, VT, 8292 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8293 DAG.getNode(NewOpc, DL, VT, 8294 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8295 } 8296 8297 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8298 SelectionDAG &DAG) { 8299 // TODO: Should this propagate fast-math-flags? 8300 8301 // Convert to float 8302 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8303 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8304 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8305 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8306 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8307 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8308 // Get reciprocal estimate. 8309 // float4 recip = vrecpeq_f32(yf); 8310 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8311 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8312 Y); 8313 // Because char has a smaller range than uchar, we can actually get away 8314 // without any newton steps. This requires that we use a weird bias 8315 // of 0xb000, however (again, this has been exhaustively tested). 8316 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8317 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8318 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8319 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8320 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8321 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8322 // Convert back to short. 8323 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8324 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8325 return X; 8326 } 8327 8328 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8329 SelectionDAG &DAG) { 8330 // TODO: Should this propagate fast-math-flags? 8331 8332 SDValue N2; 8333 // Convert to float. 8334 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8335 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8336 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8337 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8338 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8339 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8340 8341 // Use reciprocal estimate and one refinement step. 8342 // float4 recip = vrecpeq_f32(yf); 8343 // recip *= vrecpsq_f32(yf, recip); 8344 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8345 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8346 N1); 8347 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8348 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8349 N1, N2); 8350 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8351 // Because short has a smaller range than ushort, we can actually get away 8352 // with only a single newton step. This requires that we use a weird bias 8353 // of 89, however (again, this has been exhaustively tested). 8354 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 8355 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8356 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8357 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 8358 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8359 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8360 // Convert back to integer and return. 8361 // return vmovn_s32(vcvt_s32_f32(result)); 8362 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8363 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8364 return N0; 8365 } 8366 8367 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 8368 const ARMSubtarget *ST) { 8369 EVT VT = Op.getValueType(); 8370 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8371 "unexpected type for custom-lowering ISD::SDIV"); 8372 8373 SDLoc dl(Op); 8374 SDValue N0 = Op.getOperand(0); 8375 SDValue N1 = Op.getOperand(1); 8376 SDValue N2, N3; 8377 8378 if (VT == MVT::v8i8) { 8379 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 8380 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 8381 8382 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8383 DAG.getIntPtrConstant(4, dl)); 8384 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8385 DAG.getIntPtrConstant(4, dl)); 8386 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8387 DAG.getIntPtrConstant(0, dl)); 8388 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8389 DAG.getIntPtrConstant(0, dl)); 8390 8391 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 8392 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 8393 8394 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8395 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8396 8397 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 8398 return N0; 8399 } 8400 return LowerSDIV_v4i16(N0, N1, dl, DAG); 8401 } 8402 8403 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 8404 const ARMSubtarget *ST) { 8405 // TODO: Should this propagate fast-math-flags? 8406 EVT VT = Op.getValueType(); 8407 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8408 "unexpected type for custom-lowering ISD::UDIV"); 8409 8410 SDLoc dl(Op); 8411 SDValue N0 = Op.getOperand(0); 8412 SDValue N1 = Op.getOperand(1); 8413 SDValue N2, N3; 8414 8415 if (VT == MVT::v8i8) { 8416 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 8417 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 8418 8419 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8420 DAG.getIntPtrConstant(4, dl)); 8421 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8422 DAG.getIntPtrConstant(4, dl)); 8423 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8424 DAG.getIntPtrConstant(0, dl)); 8425 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8426 DAG.getIntPtrConstant(0, dl)); 8427 8428 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 8429 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 8430 8431 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8432 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8433 8434 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 8435 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 8436 MVT::i32), 8437 N0); 8438 return N0; 8439 } 8440 8441 // v4i16 sdiv ... Convert to float. 8442 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 8443 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 8444 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 8445 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 8446 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8447 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8448 8449 // Use reciprocal estimate and two refinement steps. 8450 // float4 recip = vrecpeq_f32(yf); 8451 // recip *= vrecpsq_f32(yf, recip); 8452 // recip *= vrecpsq_f32(yf, recip); 8453 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8454 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8455 BN1); 8456 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8457 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8458 BN1, N2); 8459 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8460 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8461 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8462 BN1, N2); 8463 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8464 // Simply multiplying by the reciprocal estimate can leave us a few ulps 8465 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 8466 // and that it will never cause us to return an answer too large). 8467 // float4 result = as_float4(as_int4(xf*recip) + 2); 8468 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8469 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8470 N1 = DAG.getConstant(2, dl, MVT::v4i32); 8471 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8472 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8473 // Convert back to integer and return. 8474 // return vmovn_u32(vcvt_s32_f32(result)); 8475 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8476 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8477 return N0; 8478 } 8479 8480 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 8481 SDNode *N = Op.getNode(); 8482 EVT VT = N->getValueType(0); 8483 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 8484 8485 SDValue Carry = Op.getOperand(2); 8486 8487 SDLoc DL(Op); 8488 8489 SDValue Result; 8490 if (Op.getOpcode() == ISD::ADDCARRY) { 8491 // This converts the boolean value carry into the carry flag. 8492 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8493 8494 // Do the addition proper using the carry flag we wanted. 8495 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 8496 Op.getOperand(1), Carry); 8497 8498 // Now convert the carry flag into a boolean value. 8499 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8500 } else { 8501 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 8502 // have to invert the carry first. 8503 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8504 DAG.getConstant(1, DL, MVT::i32), Carry); 8505 // This converts the boolean value carry into the carry flag. 8506 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8507 8508 // Do the subtraction proper using the carry flag we wanted. 8509 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 8510 Op.getOperand(1), Carry); 8511 8512 // Now convert the carry flag into a boolean value. 8513 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8514 // But the carry returned by ARMISD::SUBE is not a borrow as expected 8515 // by ISD::SUBCARRY, so compute 1 - C. 8516 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8517 DAG.getConstant(1, DL, MVT::i32), Carry); 8518 } 8519 8520 // Return both values. 8521 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 8522 } 8523 8524 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 8525 assert(Subtarget->isTargetDarwin()); 8526 8527 // For iOS, we want to call an alternative entry point: __sincos_stret, 8528 // return values are passed via sret. 8529 SDLoc dl(Op); 8530 SDValue Arg = Op.getOperand(0); 8531 EVT ArgVT = Arg.getValueType(); 8532 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 8533 auto PtrVT = getPointerTy(DAG.getDataLayout()); 8534 8535 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8536 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8537 8538 // Pair of floats / doubles used to pass the result. 8539 Type *RetTy = StructType::get(ArgTy, ArgTy); 8540 auto &DL = DAG.getDataLayout(); 8541 8542 ArgListTy Args; 8543 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 8544 SDValue SRet; 8545 if (ShouldUseSRet) { 8546 // Create stack object for sret. 8547 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 8548 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 8549 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 8550 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 8551 8552 ArgListEntry Entry; 8553 Entry.Node = SRet; 8554 Entry.Ty = RetTy->getPointerTo(); 8555 Entry.IsSExt = false; 8556 Entry.IsZExt = false; 8557 Entry.IsSRet = true; 8558 Args.push_back(Entry); 8559 RetTy = Type::getVoidTy(*DAG.getContext()); 8560 } 8561 8562 ArgListEntry Entry; 8563 Entry.Node = Arg; 8564 Entry.Ty = ArgTy; 8565 Entry.IsSExt = false; 8566 Entry.IsZExt = false; 8567 Args.push_back(Entry); 8568 8569 RTLIB::Libcall LC = 8570 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 8571 const char *LibcallName = getLibcallName(LC); 8572 CallingConv::ID CC = getLibcallCallingConv(LC); 8573 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 8574 8575 TargetLowering::CallLoweringInfo CLI(DAG); 8576 CLI.setDebugLoc(dl) 8577 .setChain(DAG.getEntryNode()) 8578 .setCallee(CC, RetTy, Callee, std::move(Args)) 8579 .setDiscardResult(ShouldUseSRet); 8580 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8581 8582 if (!ShouldUseSRet) 8583 return CallResult.first; 8584 8585 SDValue LoadSin = 8586 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 8587 8588 // Address of cos field. 8589 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 8590 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 8591 SDValue LoadCos = 8592 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 8593 8594 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 8595 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 8596 LoadSin.getValue(0), LoadCos.getValue(0)); 8597 } 8598 8599 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 8600 bool Signed, 8601 SDValue &Chain) const { 8602 EVT VT = Op.getValueType(); 8603 assert((VT == MVT::i32 || VT == MVT::i64) && 8604 "unexpected type for custom lowering DIV"); 8605 SDLoc dl(Op); 8606 8607 const auto &DL = DAG.getDataLayout(); 8608 const auto &TLI = DAG.getTargetLoweringInfo(); 8609 8610 const char *Name = nullptr; 8611 if (Signed) 8612 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 8613 else 8614 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 8615 8616 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 8617 8618 ARMTargetLowering::ArgListTy Args; 8619 8620 for (auto AI : {1, 0}) { 8621 ArgListEntry Arg; 8622 Arg.Node = Op.getOperand(AI); 8623 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 8624 Args.push_back(Arg); 8625 } 8626 8627 CallLoweringInfo CLI(DAG); 8628 CLI.setDebugLoc(dl) 8629 .setChain(Chain) 8630 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 8631 ES, std::move(Args)); 8632 8633 return LowerCallTo(CLI).first; 8634 } 8635 8636 // This is a code size optimisation: return the original SDIV node to 8637 // DAGCombiner when we don't want to expand SDIV into a sequence of 8638 // instructions, and an empty node otherwise which will cause the 8639 // SDIV to be expanded in DAGCombine. 8640 SDValue 8641 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8642 SelectionDAG &DAG, 8643 SmallVectorImpl<SDNode *> &Created) const { 8644 // TODO: Support SREM 8645 if (N->getOpcode() != ISD::SDIV) 8646 return SDValue(); 8647 8648 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 8649 const bool MinSize = ST.hasMinSize(); 8650 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 8651 : ST.hasDivideInARMMode(); 8652 8653 // Don't touch vector types; rewriting this may lead to scalarizing 8654 // the int divs. 8655 if (N->getOperand(0).getValueType().isVector()) 8656 return SDValue(); 8657 8658 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 8659 // hwdiv support for this to be really profitable. 8660 if (!(MinSize && HasDivide)) 8661 return SDValue(); 8662 8663 // ARM mode is a bit simpler than Thumb: we can handle large power 8664 // of 2 immediates with 1 mov instruction; no further checks required, 8665 // just return the sdiv node. 8666 if (!ST.isThumb()) 8667 return SDValue(N, 0); 8668 8669 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 8670 // and thus lose the code size benefits of a MOVS that requires only 2. 8671 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 8672 // but as it's doing exactly this, it's not worth the trouble to get TTI. 8673 if (Divisor.sgt(128)) 8674 return SDValue(); 8675 8676 return SDValue(N, 0); 8677 } 8678 8679 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 8680 bool Signed) const { 8681 assert(Op.getValueType() == MVT::i32 && 8682 "unexpected type for custom lowering DIV"); 8683 SDLoc dl(Op); 8684 8685 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 8686 DAG.getEntryNode(), Op.getOperand(1)); 8687 8688 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8689 } 8690 8691 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 8692 SDLoc DL(N); 8693 SDValue Op = N->getOperand(1); 8694 if (N->getValueType(0) == MVT::i32) 8695 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 8696 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8697 DAG.getConstant(0, DL, MVT::i32)); 8698 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8699 DAG.getConstant(1, DL, MVT::i32)); 8700 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 8701 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 8702 } 8703 8704 void ARMTargetLowering::ExpandDIV_Windows( 8705 SDValue Op, SelectionDAG &DAG, bool Signed, 8706 SmallVectorImpl<SDValue> &Results) const { 8707 const auto &DL = DAG.getDataLayout(); 8708 const auto &TLI = DAG.getTargetLoweringInfo(); 8709 8710 assert(Op.getValueType() == MVT::i64 && 8711 "unexpected type for custom lowering DIV"); 8712 SDLoc dl(Op); 8713 8714 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 8715 8716 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8717 8718 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 8719 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 8720 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 8721 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 8722 8723 Results.push_back(Lower); 8724 Results.push_back(Upper); 8725 } 8726 8727 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 8728 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 8729 // Acquire/Release load/store is not legal for targets without a dmb or 8730 // equivalent available. 8731 return SDValue(); 8732 8733 // Monotonic load/store is legal for all targets. 8734 return Op; 8735 } 8736 8737 static void ReplaceREADCYCLECOUNTER(SDNode *N, 8738 SmallVectorImpl<SDValue> &Results, 8739 SelectionDAG &DAG, 8740 const ARMSubtarget *Subtarget) { 8741 SDLoc DL(N); 8742 // Under Power Management extensions, the cycle-count is: 8743 // mrc p15, #0, <Rt>, c9, c13, #0 8744 SDValue Ops[] = { N->getOperand(0), // Chain 8745 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 8746 DAG.getConstant(15, DL, MVT::i32), 8747 DAG.getConstant(0, DL, MVT::i32), 8748 DAG.getConstant(9, DL, MVT::i32), 8749 DAG.getConstant(13, DL, MVT::i32), 8750 DAG.getConstant(0, DL, MVT::i32) 8751 }; 8752 8753 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 8754 DAG.getVTList(MVT::i32, MVT::Other), Ops); 8755 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 8756 DAG.getConstant(0, DL, MVT::i32))); 8757 Results.push_back(Cycles32.getValue(1)); 8758 } 8759 8760 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 8761 SDLoc dl(V.getNode()); 8762 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 8763 SDValue VHi = DAG.getAnyExtOrTrunc( 8764 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 8765 dl, MVT::i32); 8766 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8767 if (isBigEndian) 8768 std::swap (VLo, VHi); 8769 SDValue RegClass = 8770 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 8771 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 8772 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 8773 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 8774 return SDValue( 8775 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 8776 } 8777 8778 static void ReplaceCMP_SWAP_64Results(SDNode *N, 8779 SmallVectorImpl<SDValue> & Results, 8780 SelectionDAG &DAG) { 8781 assert(N->getValueType(0) == MVT::i64 && 8782 "AtomicCmpSwap on types less than 64 should be legal"); 8783 SDValue Ops[] = {N->getOperand(1), 8784 createGPRPairNode(DAG, N->getOperand(2)), 8785 createGPRPairNode(DAG, N->getOperand(3)), 8786 N->getOperand(0)}; 8787 SDNode *CmpSwap = DAG.getMachineNode( 8788 ARM::CMP_SWAP_64, SDLoc(N), 8789 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 8790 8791 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 8792 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 8793 8794 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8795 8796 Results.push_back( 8797 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 8798 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8799 Results.push_back( 8800 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 8801 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8802 Results.push_back(SDValue(CmpSwap, 2)); 8803 } 8804 8805 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 8806 SelectionDAG &DAG) { 8807 const auto &TLI = DAG.getTargetLoweringInfo(); 8808 8809 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 8810 "Custom lowering is MSVCRT specific!"); 8811 8812 SDLoc dl(Op); 8813 SDValue Val = Op.getOperand(0); 8814 MVT Ty = Val->getSimpleValueType(0); 8815 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 8816 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 8817 TLI.getPointerTy(DAG.getDataLayout())); 8818 8819 TargetLowering::ArgListTy Args; 8820 TargetLowering::ArgListEntry Entry; 8821 8822 Entry.Node = Val; 8823 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8824 Entry.IsZExt = true; 8825 Args.push_back(Entry); 8826 8827 Entry.Node = Exponent; 8828 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8829 Entry.IsZExt = true; 8830 Args.push_back(Entry); 8831 8832 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8833 8834 // In the in-chain to the call is the entry node If we are emitting a 8835 // tailcall, the chain will be mutated if the node has a non-entry input 8836 // chain. 8837 SDValue InChain = DAG.getEntryNode(); 8838 SDValue TCChain = InChain; 8839 8840 const Function &F = DAG.getMachineFunction().getFunction(); 8841 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8842 F.getReturnType() == LCRTy; 8843 if (IsTC) 8844 InChain = TCChain; 8845 8846 TargetLowering::CallLoweringInfo CLI(DAG); 8847 CLI.setDebugLoc(dl) 8848 .setChain(InChain) 8849 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8850 .setTailCall(IsTC); 8851 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8852 8853 // Return the chain (the DAG root) if it is a tail call 8854 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8855 } 8856 8857 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8858 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8859 switch (Op.getOpcode()) { 8860 default: llvm_unreachable("Don't know how to custom lower this!"); 8861 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8862 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8863 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8864 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8865 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8866 case ISD::SELECT: return LowerSELECT(Op, DAG); 8867 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8868 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8869 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8870 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8871 case ISD::VASTART: return LowerVASTART(Op, DAG); 8872 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8873 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8874 case ISD::SINT_TO_FP: 8875 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8876 case ISD::FP_TO_SINT: 8877 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8878 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8879 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8880 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8881 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8882 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8883 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8884 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget); 8885 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8886 Subtarget); 8887 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8888 case ISD::SHL: 8889 case ISD::SRL: 8890 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8891 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8892 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8893 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8894 case ISD::SRL_PARTS: 8895 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8896 case ISD::CTTZ: 8897 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8898 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8899 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 8900 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8901 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8902 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8903 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 8904 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 8905 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8906 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 8907 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 8908 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8909 case ISD::MUL: return LowerMUL(Op, DAG); 8910 case ISD::SDIV: 8911 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8912 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8913 return LowerSDIV(Op, DAG, Subtarget); 8914 case ISD::UDIV: 8915 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8916 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8917 return LowerUDIV(Op, DAG, Subtarget); 8918 case ISD::ADDCARRY: 8919 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8920 case ISD::SADDO: 8921 case ISD::SSUBO: 8922 return LowerSignedALUO(Op, DAG); 8923 case ISD::UADDO: 8924 case ISD::USUBO: 8925 return LowerUnsignedALUO(Op, DAG); 8926 case ISD::ATOMIC_LOAD: 8927 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8928 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8929 case ISD::SDIVREM: 8930 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8931 case ISD::DYNAMIC_STACKALLOC: 8932 if (Subtarget->isTargetWindows()) 8933 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8934 llvm_unreachable("Don't know how to custom lower this!"); 8935 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8936 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8937 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8938 case ARMISD::WIN__DBZCHK: return SDValue(); 8939 } 8940 } 8941 8942 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8943 SelectionDAG &DAG) { 8944 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8945 unsigned Opc = 0; 8946 if (IntNo == Intrinsic::arm_smlald) 8947 Opc = ARMISD::SMLALD; 8948 else if (IntNo == Intrinsic::arm_smlaldx) 8949 Opc = ARMISD::SMLALDX; 8950 else if (IntNo == Intrinsic::arm_smlsld) 8951 Opc = ARMISD::SMLSLD; 8952 else if (IntNo == Intrinsic::arm_smlsldx) 8953 Opc = ARMISD::SMLSLDX; 8954 else 8955 return; 8956 8957 SDLoc dl(N); 8958 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8959 N->getOperand(3), 8960 DAG.getConstant(0, dl, MVT::i32)); 8961 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8962 N->getOperand(3), 8963 DAG.getConstant(1, dl, MVT::i32)); 8964 8965 SDValue LongMul = DAG.getNode(Opc, dl, 8966 DAG.getVTList(MVT::i32, MVT::i32), 8967 N->getOperand(1), N->getOperand(2), 8968 Lo, Hi); 8969 Results.push_back(LongMul.getValue(0)); 8970 Results.push_back(LongMul.getValue(1)); 8971 } 8972 8973 /// ReplaceNodeResults - Replace the results of node with an illegal result 8974 /// type with new values built out of custom code. 8975 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8976 SmallVectorImpl<SDValue> &Results, 8977 SelectionDAG &DAG) const { 8978 SDValue Res; 8979 switch (N->getOpcode()) { 8980 default: 8981 llvm_unreachable("Don't know how to custom expand this!"); 8982 case ISD::READ_REGISTER: 8983 ExpandREAD_REGISTER(N, Results, DAG); 8984 break; 8985 case ISD::BITCAST: 8986 Res = ExpandBITCAST(N, DAG, Subtarget); 8987 break; 8988 case ISD::SRL: 8989 case ISD::SRA: 8990 case ISD::SHL: 8991 Res = Expand64BitShift(N, DAG, Subtarget); 8992 break; 8993 case ISD::SREM: 8994 case ISD::UREM: 8995 Res = LowerREM(N, DAG); 8996 break; 8997 case ISD::SDIVREM: 8998 case ISD::UDIVREM: 8999 Res = LowerDivRem(SDValue(N, 0), DAG); 9000 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 9001 Results.push_back(Res.getValue(0)); 9002 Results.push_back(Res.getValue(1)); 9003 return; 9004 case ISD::READCYCLECOUNTER: 9005 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 9006 return; 9007 case ISD::UDIV: 9008 case ISD::SDIV: 9009 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 9010 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 9011 Results); 9012 case ISD::ATOMIC_CMP_SWAP: 9013 ReplaceCMP_SWAP_64Results(N, Results, DAG); 9014 return; 9015 case ISD::INTRINSIC_WO_CHAIN: 9016 return ReplaceLongIntrinsic(N, Results, DAG); 9017 case ISD::ABS: 9018 lowerABS(N, Results, DAG); 9019 return ; 9020 9021 } 9022 if (Res.getNode()) 9023 Results.push_back(Res); 9024 } 9025 9026 //===----------------------------------------------------------------------===// 9027 // ARM Scheduler Hooks 9028 //===----------------------------------------------------------------------===// 9029 9030 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 9031 /// registers the function context. 9032 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 9033 MachineBasicBlock *MBB, 9034 MachineBasicBlock *DispatchBB, 9035 int FI) const { 9036 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 9037 "ROPI/RWPI not currently supported with SjLj"); 9038 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9039 DebugLoc dl = MI.getDebugLoc(); 9040 MachineFunction *MF = MBB->getParent(); 9041 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9042 MachineConstantPool *MCP = MF->getConstantPool(); 9043 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 9044 const Function &F = MF->getFunction(); 9045 9046 bool isThumb = Subtarget->isThumb(); 9047 bool isThumb2 = Subtarget->isThumb2(); 9048 9049 unsigned PCLabelId = AFI->createPICLabelUId(); 9050 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 9051 ARMConstantPoolValue *CPV = 9052 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 9053 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 9054 9055 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 9056 : &ARM::GPRRegClass; 9057 9058 // Grab constant pool and fixed stack memory operands. 9059 MachineMemOperand *CPMMO = 9060 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9061 MachineMemOperand::MOLoad, 4, 4); 9062 9063 MachineMemOperand *FIMMOSt = 9064 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 9065 MachineMemOperand::MOStore, 4, 4); 9066 9067 // Load the address of the dispatch MBB into the jump buffer. 9068 if (isThumb2) { 9069 // Incoming value: jbuf 9070 // ldr.n r5, LCPI1_1 9071 // orr r5, r5, #1 9072 // add r5, pc 9073 // str r5, [$jbuf, #+4] ; &jbuf[1] 9074 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9075 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9076 .addConstantPoolIndex(CPI) 9077 .addMemOperand(CPMMO) 9078 .add(predOps(ARMCC::AL)); 9079 // Set the low bit because of thumb mode. 9080 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9081 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9082 .addReg(NewVReg1, RegState::Kill) 9083 .addImm(0x01) 9084 .add(predOps(ARMCC::AL)) 9085 .add(condCodeOp()); 9086 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9087 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9088 .addReg(NewVReg2, RegState::Kill) 9089 .addImm(PCLabelId); 9090 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9091 .addReg(NewVReg3, RegState::Kill) 9092 .addFrameIndex(FI) 9093 .addImm(36) // &jbuf[1] :: pc 9094 .addMemOperand(FIMMOSt) 9095 .add(predOps(ARMCC::AL)); 9096 } else if (isThumb) { 9097 // Incoming value: jbuf 9098 // ldr.n r1, LCPI1_4 9099 // add r1, pc 9100 // mov r2, #1 9101 // orrs r1, r2 9102 // add r2, $jbuf, #+4 ; &jbuf[1] 9103 // str r1, [r2] 9104 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9105 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 9106 .addConstantPoolIndex(CPI) 9107 .addMemOperand(CPMMO) 9108 .add(predOps(ARMCC::AL)); 9109 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9110 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 9111 .addReg(NewVReg1, RegState::Kill) 9112 .addImm(PCLabelId); 9113 // Set the low bit because of thumb mode. 9114 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9115 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 9116 .addReg(ARM::CPSR, RegState::Define) 9117 .addImm(1) 9118 .add(predOps(ARMCC::AL)); 9119 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9120 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 9121 .addReg(ARM::CPSR, RegState::Define) 9122 .addReg(NewVReg2, RegState::Kill) 9123 .addReg(NewVReg3, RegState::Kill) 9124 .add(predOps(ARMCC::AL)); 9125 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9126 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 9127 .addFrameIndex(FI) 9128 .addImm(36); // &jbuf[1] :: pc 9129 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 9130 .addReg(NewVReg4, RegState::Kill) 9131 .addReg(NewVReg5, RegState::Kill) 9132 .addImm(0) 9133 .addMemOperand(FIMMOSt) 9134 .add(predOps(ARMCC::AL)); 9135 } else { 9136 // Incoming value: jbuf 9137 // ldr r1, LCPI1_1 9138 // add r1, pc, r1 9139 // str r1, [$jbuf, #+4] ; &jbuf[1] 9140 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9141 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 9142 .addConstantPoolIndex(CPI) 9143 .addImm(0) 9144 .addMemOperand(CPMMO) 9145 .add(predOps(ARMCC::AL)); 9146 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9147 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 9148 .addReg(NewVReg1, RegState::Kill) 9149 .addImm(PCLabelId) 9150 .add(predOps(ARMCC::AL)); 9151 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 9152 .addReg(NewVReg2, RegState::Kill) 9153 .addFrameIndex(FI) 9154 .addImm(36) // &jbuf[1] :: pc 9155 .addMemOperand(FIMMOSt) 9156 .add(predOps(ARMCC::AL)); 9157 } 9158 } 9159 9160 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 9161 MachineBasicBlock *MBB) const { 9162 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9163 DebugLoc dl = MI.getDebugLoc(); 9164 MachineFunction *MF = MBB->getParent(); 9165 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9166 MachineFrameInfo &MFI = MF->getFrameInfo(); 9167 int FI = MFI.getFunctionContextIndex(); 9168 9169 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 9170 : &ARM::GPRnopcRegClass; 9171 9172 // Get a mapping of the call site numbers to all of the landing pads they're 9173 // associated with. 9174 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 9175 unsigned MaxCSNum = 0; 9176 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 9177 ++BB) { 9178 if (!BB->isEHPad()) continue; 9179 9180 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 9181 // pad. 9182 for (MachineBasicBlock::iterator 9183 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 9184 if (!II->isEHLabel()) continue; 9185 9186 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 9187 if (!MF->hasCallSiteLandingPad(Sym)) continue; 9188 9189 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 9190 for (SmallVectorImpl<unsigned>::iterator 9191 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 9192 CSI != CSE; ++CSI) { 9193 CallSiteNumToLPad[*CSI].push_back(&*BB); 9194 MaxCSNum = std::max(MaxCSNum, *CSI); 9195 } 9196 break; 9197 } 9198 } 9199 9200 // Get an ordered list of the machine basic blocks for the jump table. 9201 std::vector<MachineBasicBlock*> LPadList; 9202 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 9203 LPadList.reserve(CallSiteNumToLPad.size()); 9204 for (unsigned I = 1; I <= MaxCSNum; ++I) { 9205 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 9206 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9207 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 9208 LPadList.push_back(*II); 9209 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 9210 } 9211 } 9212 9213 assert(!LPadList.empty() && 9214 "No landing pad destinations for the dispatch jump table!"); 9215 9216 // Create the jump table and associated information. 9217 MachineJumpTableInfo *JTI = 9218 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 9219 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 9220 9221 // Create the MBBs for the dispatch code. 9222 9223 // Shove the dispatch's address into the return slot in the function context. 9224 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 9225 DispatchBB->setIsEHPad(); 9226 9227 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9228 unsigned trap_opcode; 9229 if (Subtarget->isThumb()) 9230 trap_opcode = ARM::tTRAP; 9231 else 9232 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 9233 9234 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 9235 DispatchBB->addSuccessor(TrapBB); 9236 9237 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 9238 DispatchBB->addSuccessor(DispContBB); 9239 9240 // Insert and MBBs. 9241 MF->insert(MF->end(), DispatchBB); 9242 MF->insert(MF->end(), DispContBB); 9243 MF->insert(MF->end(), TrapBB); 9244 9245 // Insert code into the entry block that creates and registers the function 9246 // context. 9247 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 9248 9249 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 9250 MachinePointerInfo::getFixedStack(*MF, FI), 9251 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 9252 9253 MachineInstrBuilder MIB; 9254 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 9255 9256 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 9257 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 9258 9259 // Add a register mask with no preserved registers. This results in all 9260 // registers being marked as clobbered. This can't work if the dispatch block 9261 // is in a Thumb1 function and is linked with ARM code which uses the FP 9262 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 9263 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 9264 9265 bool IsPositionIndependent = isPositionIndependent(); 9266 unsigned NumLPads = LPadList.size(); 9267 if (Subtarget->isThumb2()) { 9268 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9269 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 9270 .addFrameIndex(FI) 9271 .addImm(4) 9272 .addMemOperand(FIMMOLd) 9273 .add(predOps(ARMCC::AL)); 9274 9275 if (NumLPads < 256) { 9276 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 9277 .addReg(NewVReg1) 9278 .addImm(LPadList.size()) 9279 .add(predOps(ARMCC::AL)); 9280 } else { 9281 Register VReg1 = MRI->createVirtualRegister(TRC); 9282 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 9283 .addImm(NumLPads & 0xFFFF) 9284 .add(predOps(ARMCC::AL)); 9285 9286 unsigned VReg2 = VReg1; 9287 if ((NumLPads & 0xFFFF0000) != 0) { 9288 VReg2 = MRI->createVirtualRegister(TRC); 9289 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 9290 .addReg(VReg1) 9291 .addImm(NumLPads >> 16) 9292 .add(predOps(ARMCC::AL)); 9293 } 9294 9295 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 9296 .addReg(NewVReg1) 9297 .addReg(VReg2) 9298 .add(predOps(ARMCC::AL)); 9299 } 9300 9301 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 9302 .addMBB(TrapBB) 9303 .addImm(ARMCC::HI) 9304 .addReg(ARM::CPSR); 9305 9306 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9307 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 9308 .addJumpTableIndex(MJTI) 9309 .add(predOps(ARMCC::AL)); 9310 9311 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9312 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 9313 .addReg(NewVReg3, RegState::Kill) 9314 .addReg(NewVReg1) 9315 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9316 .add(predOps(ARMCC::AL)) 9317 .add(condCodeOp()); 9318 9319 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 9320 .addReg(NewVReg4, RegState::Kill) 9321 .addReg(NewVReg1) 9322 .addJumpTableIndex(MJTI); 9323 } else if (Subtarget->isThumb()) { 9324 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9325 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 9326 .addFrameIndex(FI) 9327 .addImm(1) 9328 .addMemOperand(FIMMOLd) 9329 .add(predOps(ARMCC::AL)); 9330 9331 if (NumLPads < 256) { 9332 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 9333 .addReg(NewVReg1) 9334 .addImm(NumLPads) 9335 .add(predOps(ARMCC::AL)); 9336 } else { 9337 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9338 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9339 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9340 9341 // MachineConstantPool wants an explicit alignment. 9342 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9343 if (Align == 0) 9344 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9345 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9346 9347 Register VReg1 = MRI->createVirtualRegister(TRC); 9348 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 9349 .addReg(VReg1, RegState::Define) 9350 .addConstantPoolIndex(Idx) 9351 .add(predOps(ARMCC::AL)); 9352 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 9353 .addReg(NewVReg1) 9354 .addReg(VReg1) 9355 .add(predOps(ARMCC::AL)); 9356 } 9357 9358 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 9359 .addMBB(TrapBB) 9360 .addImm(ARMCC::HI) 9361 .addReg(ARM::CPSR); 9362 9363 Register NewVReg2 = MRI->createVirtualRegister(TRC); 9364 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 9365 .addReg(ARM::CPSR, RegState::Define) 9366 .addReg(NewVReg1) 9367 .addImm(2) 9368 .add(predOps(ARMCC::AL)); 9369 9370 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9371 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 9372 .addJumpTableIndex(MJTI) 9373 .add(predOps(ARMCC::AL)); 9374 9375 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9376 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 9377 .addReg(ARM::CPSR, RegState::Define) 9378 .addReg(NewVReg2, RegState::Kill) 9379 .addReg(NewVReg3) 9380 .add(predOps(ARMCC::AL)); 9381 9382 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9383 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9384 9385 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9386 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 9387 .addReg(NewVReg4, RegState::Kill) 9388 .addImm(0) 9389 .addMemOperand(JTMMOLd) 9390 .add(predOps(ARMCC::AL)); 9391 9392 unsigned NewVReg6 = NewVReg5; 9393 if (IsPositionIndependent) { 9394 NewVReg6 = MRI->createVirtualRegister(TRC); 9395 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 9396 .addReg(ARM::CPSR, RegState::Define) 9397 .addReg(NewVReg5, RegState::Kill) 9398 .addReg(NewVReg3) 9399 .add(predOps(ARMCC::AL)); 9400 } 9401 9402 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 9403 .addReg(NewVReg6, RegState::Kill) 9404 .addJumpTableIndex(MJTI); 9405 } else { 9406 Register NewVReg1 = MRI->createVirtualRegister(TRC); 9407 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 9408 .addFrameIndex(FI) 9409 .addImm(4) 9410 .addMemOperand(FIMMOLd) 9411 .add(predOps(ARMCC::AL)); 9412 9413 if (NumLPads < 256) { 9414 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 9415 .addReg(NewVReg1) 9416 .addImm(NumLPads) 9417 .add(predOps(ARMCC::AL)); 9418 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 9419 Register VReg1 = MRI->createVirtualRegister(TRC); 9420 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 9421 .addImm(NumLPads & 0xFFFF) 9422 .add(predOps(ARMCC::AL)); 9423 9424 unsigned VReg2 = VReg1; 9425 if ((NumLPads & 0xFFFF0000) != 0) { 9426 VReg2 = MRI->createVirtualRegister(TRC); 9427 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 9428 .addReg(VReg1) 9429 .addImm(NumLPads >> 16) 9430 .add(predOps(ARMCC::AL)); 9431 } 9432 9433 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9434 .addReg(NewVReg1) 9435 .addReg(VReg2) 9436 .add(predOps(ARMCC::AL)); 9437 } else { 9438 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9439 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9440 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9441 9442 // MachineConstantPool wants an explicit alignment. 9443 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9444 if (Align == 0) 9445 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9446 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9447 9448 Register VReg1 = MRI->createVirtualRegister(TRC); 9449 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 9450 .addReg(VReg1, RegState::Define) 9451 .addConstantPoolIndex(Idx) 9452 .addImm(0) 9453 .add(predOps(ARMCC::AL)); 9454 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9455 .addReg(NewVReg1) 9456 .addReg(VReg1, RegState::Kill) 9457 .add(predOps(ARMCC::AL)); 9458 } 9459 9460 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 9461 .addMBB(TrapBB) 9462 .addImm(ARMCC::HI) 9463 .addReg(ARM::CPSR); 9464 9465 Register NewVReg3 = MRI->createVirtualRegister(TRC); 9466 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 9467 .addReg(NewVReg1) 9468 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9469 .add(predOps(ARMCC::AL)) 9470 .add(condCodeOp()); 9471 Register NewVReg4 = MRI->createVirtualRegister(TRC); 9472 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 9473 .addJumpTableIndex(MJTI) 9474 .add(predOps(ARMCC::AL)); 9475 9476 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9477 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9478 Register NewVReg5 = MRI->createVirtualRegister(TRC); 9479 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 9480 .addReg(NewVReg3, RegState::Kill) 9481 .addReg(NewVReg4) 9482 .addImm(0) 9483 .addMemOperand(JTMMOLd) 9484 .add(predOps(ARMCC::AL)); 9485 9486 if (IsPositionIndependent) { 9487 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 9488 .addReg(NewVReg5, RegState::Kill) 9489 .addReg(NewVReg4) 9490 .addJumpTableIndex(MJTI); 9491 } else { 9492 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 9493 .addReg(NewVReg5, RegState::Kill) 9494 .addJumpTableIndex(MJTI); 9495 } 9496 } 9497 9498 // Add the jump table entries as successors to the MBB. 9499 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 9500 for (std::vector<MachineBasicBlock*>::iterator 9501 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 9502 MachineBasicBlock *CurMBB = *I; 9503 if (SeenMBBs.insert(CurMBB).second) 9504 DispContBB->addSuccessor(CurMBB); 9505 } 9506 9507 // N.B. the order the invoke BBs are processed in doesn't matter here. 9508 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 9509 SmallVector<MachineBasicBlock*, 64> MBBLPads; 9510 for (MachineBasicBlock *BB : InvokeBBs) { 9511 9512 // Remove the landing pad successor from the invoke block and replace it 9513 // with the new dispatch block. 9514 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 9515 BB->succ_end()); 9516 while (!Successors.empty()) { 9517 MachineBasicBlock *SMBB = Successors.pop_back_val(); 9518 if (SMBB->isEHPad()) { 9519 BB->removeSuccessor(SMBB); 9520 MBBLPads.push_back(SMBB); 9521 } 9522 } 9523 9524 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 9525 BB->normalizeSuccProbs(); 9526 9527 // Find the invoke call and mark all of the callee-saved registers as 9528 // 'implicit defined' so that they're spilled. This prevents code from 9529 // moving instructions to before the EH block, where they will never be 9530 // executed. 9531 for (MachineBasicBlock::reverse_iterator 9532 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 9533 if (!II->isCall()) continue; 9534 9535 DenseMap<unsigned, bool> DefRegs; 9536 for (MachineInstr::mop_iterator 9537 OI = II->operands_begin(), OE = II->operands_end(); 9538 OI != OE; ++OI) { 9539 if (!OI->isReg()) continue; 9540 DefRegs[OI->getReg()] = true; 9541 } 9542 9543 MachineInstrBuilder MIB(*MF, &*II); 9544 9545 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 9546 unsigned Reg = SavedRegs[i]; 9547 if (Subtarget->isThumb2() && 9548 !ARM::tGPRRegClass.contains(Reg) && 9549 !ARM::hGPRRegClass.contains(Reg)) 9550 continue; 9551 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 9552 continue; 9553 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 9554 continue; 9555 if (!DefRegs[Reg]) 9556 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 9557 } 9558 9559 break; 9560 } 9561 } 9562 9563 // Mark all former landing pads as non-landing pads. The dispatch is the only 9564 // landing pad now. 9565 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9566 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 9567 (*I)->setIsEHPad(false); 9568 9569 // The instruction is gone now. 9570 MI.eraseFromParent(); 9571 } 9572 9573 static 9574 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 9575 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 9576 E = MBB->succ_end(); I != E; ++I) 9577 if (*I != Succ) 9578 return *I; 9579 llvm_unreachable("Expecting a BB with two successors!"); 9580 } 9581 9582 /// Return the load opcode for a given load size. If load size >= 8, 9583 /// neon opcode will be returned. 9584 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 9585 if (LdSize >= 8) 9586 return LdSize == 16 ? ARM::VLD1q32wb_fixed 9587 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 9588 if (IsThumb1) 9589 return LdSize == 4 ? ARM::tLDRi 9590 : LdSize == 2 ? ARM::tLDRHi 9591 : LdSize == 1 ? ARM::tLDRBi : 0; 9592 if (IsThumb2) 9593 return LdSize == 4 ? ARM::t2LDR_POST 9594 : LdSize == 2 ? ARM::t2LDRH_POST 9595 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 9596 return LdSize == 4 ? ARM::LDR_POST_IMM 9597 : LdSize == 2 ? ARM::LDRH_POST 9598 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 9599 } 9600 9601 /// Return the store opcode for a given store size. If store size >= 8, 9602 /// neon opcode will be returned. 9603 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 9604 if (StSize >= 8) 9605 return StSize == 16 ? ARM::VST1q32wb_fixed 9606 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 9607 if (IsThumb1) 9608 return StSize == 4 ? ARM::tSTRi 9609 : StSize == 2 ? ARM::tSTRHi 9610 : StSize == 1 ? ARM::tSTRBi : 0; 9611 if (IsThumb2) 9612 return StSize == 4 ? ARM::t2STR_POST 9613 : StSize == 2 ? ARM::t2STRH_POST 9614 : StSize == 1 ? ARM::t2STRB_POST : 0; 9615 return StSize == 4 ? ARM::STR_POST_IMM 9616 : StSize == 2 ? ARM::STRH_POST 9617 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 9618 } 9619 9620 /// Emit a post-increment load operation with given size. The instructions 9621 /// will be added to BB at Pos. 9622 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9623 const TargetInstrInfo *TII, const DebugLoc &dl, 9624 unsigned LdSize, unsigned Data, unsigned AddrIn, 9625 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9626 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 9627 assert(LdOpc != 0 && "Should have a load opcode"); 9628 if (LdSize >= 8) { 9629 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9630 .addReg(AddrOut, RegState::Define) 9631 .addReg(AddrIn) 9632 .addImm(0) 9633 .add(predOps(ARMCC::AL)); 9634 } else if (IsThumb1) { 9635 // load + update AddrIn 9636 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9637 .addReg(AddrIn) 9638 .addImm(0) 9639 .add(predOps(ARMCC::AL)); 9640 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9641 .add(t1CondCodeOp()) 9642 .addReg(AddrIn) 9643 .addImm(LdSize) 9644 .add(predOps(ARMCC::AL)); 9645 } else if (IsThumb2) { 9646 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9647 .addReg(AddrOut, RegState::Define) 9648 .addReg(AddrIn) 9649 .addImm(LdSize) 9650 .add(predOps(ARMCC::AL)); 9651 } else { // arm 9652 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9653 .addReg(AddrOut, RegState::Define) 9654 .addReg(AddrIn) 9655 .addReg(0) 9656 .addImm(LdSize) 9657 .add(predOps(ARMCC::AL)); 9658 } 9659 } 9660 9661 /// Emit a post-increment store operation with given size. The instructions 9662 /// will be added to BB at Pos. 9663 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9664 const TargetInstrInfo *TII, const DebugLoc &dl, 9665 unsigned StSize, unsigned Data, unsigned AddrIn, 9666 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9667 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 9668 assert(StOpc != 0 && "Should have a store opcode"); 9669 if (StSize >= 8) { 9670 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9671 .addReg(AddrIn) 9672 .addImm(0) 9673 .addReg(Data) 9674 .add(predOps(ARMCC::AL)); 9675 } else if (IsThumb1) { 9676 // store + update AddrIn 9677 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 9678 .addReg(Data) 9679 .addReg(AddrIn) 9680 .addImm(0) 9681 .add(predOps(ARMCC::AL)); 9682 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9683 .add(t1CondCodeOp()) 9684 .addReg(AddrIn) 9685 .addImm(StSize) 9686 .add(predOps(ARMCC::AL)); 9687 } else if (IsThumb2) { 9688 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9689 .addReg(Data) 9690 .addReg(AddrIn) 9691 .addImm(StSize) 9692 .add(predOps(ARMCC::AL)); 9693 } else { // arm 9694 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9695 .addReg(Data) 9696 .addReg(AddrIn) 9697 .addReg(0) 9698 .addImm(StSize) 9699 .add(predOps(ARMCC::AL)); 9700 } 9701 } 9702 9703 MachineBasicBlock * 9704 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 9705 MachineBasicBlock *BB) const { 9706 // This pseudo instruction has 3 operands: dst, src, size 9707 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 9708 // Otherwise, we will generate unrolled scalar copies. 9709 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9710 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9711 MachineFunction::iterator It = ++BB->getIterator(); 9712 9713 Register dest = MI.getOperand(0).getReg(); 9714 Register src = MI.getOperand(1).getReg(); 9715 unsigned SizeVal = MI.getOperand(2).getImm(); 9716 unsigned Align = MI.getOperand(3).getImm(); 9717 DebugLoc dl = MI.getDebugLoc(); 9718 9719 MachineFunction *MF = BB->getParent(); 9720 MachineRegisterInfo &MRI = MF->getRegInfo(); 9721 unsigned UnitSize = 0; 9722 const TargetRegisterClass *TRC = nullptr; 9723 const TargetRegisterClass *VecTRC = nullptr; 9724 9725 bool IsThumb1 = Subtarget->isThumb1Only(); 9726 bool IsThumb2 = Subtarget->isThumb2(); 9727 bool IsThumb = Subtarget->isThumb(); 9728 9729 if (Align & 1) { 9730 UnitSize = 1; 9731 } else if (Align & 2) { 9732 UnitSize = 2; 9733 } else { 9734 // Check whether we can use NEON instructions. 9735 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 9736 Subtarget->hasNEON()) { 9737 if ((Align % 16 == 0) && SizeVal >= 16) 9738 UnitSize = 16; 9739 else if ((Align % 8 == 0) && SizeVal >= 8) 9740 UnitSize = 8; 9741 } 9742 // Can't use NEON instructions. 9743 if (UnitSize == 0) 9744 UnitSize = 4; 9745 } 9746 9747 // Select the correct opcode and register class for unit size load/store 9748 bool IsNeon = UnitSize >= 8; 9749 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 9750 if (IsNeon) 9751 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 9752 : UnitSize == 8 ? &ARM::DPRRegClass 9753 : nullptr; 9754 9755 unsigned BytesLeft = SizeVal % UnitSize; 9756 unsigned LoopSize = SizeVal - BytesLeft; 9757 9758 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 9759 // Use LDR and STR to copy. 9760 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 9761 // [destOut] = STR_POST(scratch, destIn, UnitSize) 9762 unsigned srcIn = src; 9763 unsigned destIn = dest; 9764 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 9765 Register srcOut = MRI.createVirtualRegister(TRC); 9766 Register destOut = MRI.createVirtualRegister(TRC); 9767 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9768 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 9769 IsThumb1, IsThumb2); 9770 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 9771 IsThumb1, IsThumb2); 9772 srcIn = srcOut; 9773 destIn = destOut; 9774 } 9775 9776 // Handle the leftover bytes with LDRB and STRB. 9777 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 9778 // [destOut] = STRB_POST(scratch, destIn, 1) 9779 for (unsigned i = 0; i < BytesLeft; i++) { 9780 Register srcOut = MRI.createVirtualRegister(TRC); 9781 Register destOut = MRI.createVirtualRegister(TRC); 9782 Register scratch = MRI.createVirtualRegister(TRC); 9783 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 9784 IsThumb1, IsThumb2); 9785 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 9786 IsThumb1, IsThumb2); 9787 srcIn = srcOut; 9788 destIn = destOut; 9789 } 9790 MI.eraseFromParent(); // The instruction is gone now. 9791 return BB; 9792 } 9793 9794 // Expand the pseudo op to a loop. 9795 // thisMBB: 9796 // ... 9797 // movw varEnd, # --> with thumb2 9798 // movt varEnd, # 9799 // ldrcp varEnd, idx --> without thumb2 9800 // fallthrough --> loopMBB 9801 // loopMBB: 9802 // PHI varPhi, varEnd, varLoop 9803 // PHI srcPhi, src, srcLoop 9804 // PHI destPhi, dst, destLoop 9805 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9806 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 9807 // subs varLoop, varPhi, #UnitSize 9808 // bne loopMBB 9809 // fallthrough --> exitMBB 9810 // exitMBB: 9811 // epilogue to handle left-over bytes 9812 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9813 // [destOut] = STRB_POST(scratch, destLoop, 1) 9814 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9815 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9816 MF->insert(It, loopMBB); 9817 MF->insert(It, exitMBB); 9818 9819 // Transfer the remainder of BB and its successor edges to exitMBB. 9820 exitMBB->splice(exitMBB->begin(), BB, 9821 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9822 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9823 9824 // Load an immediate to varEnd. 9825 Register varEnd = MRI.createVirtualRegister(TRC); 9826 if (Subtarget->useMovt()) { 9827 unsigned Vtmp = varEnd; 9828 if ((LoopSize & 0xFFFF0000) != 0) 9829 Vtmp = MRI.createVirtualRegister(TRC); 9830 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 9831 .addImm(LoopSize & 0xFFFF) 9832 .add(predOps(ARMCC::AL)); 9833 9834 if ((LoopSize & 0xFFFF0000) != 0) 9835 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9836 .addReg(Vtmp) 9837 .addImm(LoopSize >> 16) 9838 .add(predOps(ARMCC::AL)); 9839 } else { 9840 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9841 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9842 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9843 9844 // MachineConstantPool wants an explicit alignment. 9845 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9846 if (Align == 0) 9847 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9848 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9849 MachineMemOperand *CPMMO = 9850 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9851 MachineMemOperand::MOLoad, 4, 4); 9852 9853 if (IsThumb) 9854 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9855 .addReg(varEnd, RegState::Define) 9856 .addConstantPoolIndex(Idx) 9857 .add(predOps(ARMCC::AL)) 9858 .addMemOperand(CPMMO); 9859 else 9860 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9861 .addReg(varEnd, RegState::Define) 9862 .addConstantPoolIndex(Idx) 9863 .addImm(0) 9864 .add(predOps(ARMCC::AL)) 9865 .addMemOperand(CPMMO); 9866 } 9867 BB->addSuccessor(loopMBB); 9868 9869 // Generate the loop body: 9870 // varPhi = PHI(varLoop, varEnd) 9871 // srcPhi = PHI(srcLoop, src) 9872 // destPhi = PHI(destLoop, dst) 9873 MachineBasicBlock *entryBB = BB; 9874 BB = loopMBB; 9875 Register varLoop = MRI.createVirtualRegister(TRC); 9876 Register varPhi = MRI.createVirtualRegister(TRC); 9877 Register srcLoop = MRI.createVirtualRegister(TRC); 9878 Register srcPhi = MRI.createVirtualRegister(TRC); 9879 Register destLoop = MRI.createVirtualRegister(TRC); 9880 Register destPhi = MRI.createVirtualRegister(TRC); 9881 9882 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9883 .addReg(varLoop).addMBB(loopMBB) 9884 .addReg(varEnd).addMBB(entryBB); 9885 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9886 .addReg(srcLoop).addMBB(loopMBB) 9887 .addReg(src).addMBB(entryBB); 9888 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9889 .addReg(destLoop).addMBB(loopMBB) 9890 .addReg(dest).addMBB(entryBB); 9891 9892 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9893 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9894 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9895 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9896 IsThumb1, IsThumb2); 9897 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9898 IsThumb1, IsThumb2); 9899 9900 // Decrement loop variable by UnitSize. 9901 if (IsThumb1) { 9902 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9903 .add(t1CondCodeOp()) 9904 .addReg(varPhi) 9905 .addImm(UnitSize) 9906 .add(predOps(ARMCC::AL)); 9907 } else { 9908 MachineInstrBuilder MIB = 9909 BuildMI(*BB, BB->end(), dl, 9910 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9911 MIB.addReg(varPhi) 9912 .addImm(UnitSize) 9913 .add(predOps(ARMCC::AL)) 9914 .add(condCodeOp()); 9915 MIB->getOperand(5).setReg(ARM::CPSR); 9916 MIB->getOperand(5).setIsDef(true); 9917 } 9918 BuildMI(*BB, BB->end(), dl, 9919 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9920 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9921 9922 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9923 BB->addSuccessor(loopMBB); 9924 BB->addSuccessor(exitMBB); 9925 9926 // Add epilogue to handle BytesLeft. 9927 BB = exitMBB; 9928 auto StartOfExit = exitMBB->begin(); 9929 9930 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9931 // [destOut] = STRB_POST(scratch, destLoop, 1) 9932 unsigned srcIn = srcLoop; 9933 unsigned destIn = destLoop; 9934 for (unsigned i = 0; i < BytesLeft; i++) { 9935 Register srcOut = MRI.createVirtualRegister(TRC); 9936 Register destOut = MRI.createVirtualRegister(TRC); 9937 Register scratch = MRI.createVirtualRegister(TRC); 9938 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9939 IsThumb1, IsThumb2); 9940 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9941 IsThumb1, IsThumb2); 9942 srcIn = srcOut; 9943 destIn = destOut; 9944 } 9945 9946 MI.eraseFromParent(); // The instruction is gone now. 9947 return BB; 9948 } 9949 9950 MachineBasicBlock * 9951 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9952 MachineBasicBlock *MBB) const { 9953 const TargetMachine &TM = getTargetMachine(); 9954 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9955 DebugLoc DL = MI.getDebugLoc(); 9956 9957 assert(Subtarget->isTargetWindows() && 9958 "__chkstk is only supported on Windows"); 9959 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9960 9961 // __chkstk takes the number of words to allocate on the stack in R4, and 9962 // returns the stack adjustment in number of bytes in R4. This will not 9963 // clober any other registers (other than the obvious lr). 9964 // 9965 // Although, technically, IP should be considered a register which may be 9966 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9967 // thumb-2 environment, so there is no interworking required. As a result, we 9968 // do not expect a veneer to be emitted by the linker, clobbering IP. 9969 // 9970 // Each module receives its own copy of __chkstk, so no import thunk is 9971 // required, again, ensuring that IP is not clobbered. 9972 // 9973 // Finally, although some linkers may theoretically provide a trampoline for 9974 // out of range calls (which is quite common due to a 32M range limitation of 9975 // branches for Thumb), we can generate the long-call version via 9976 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9977 // IP. 9978 9979 switch (TM.getCodeModel()) { 9980 case CodeModel::Tiny: 9981 llvm_unreachable("Tiny code model not available on ARM."); 9982 case CodeModel::Small: 9983 case CodeModel::Medium: 9984 case CodeModel::Kernel: 9985 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9986 .add(predOps(ARMCC::AL)) 9987 .addExternalSymbol("__chkstk") 9988 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9989 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9990 .addReg(ARM::R12, 9991 RegState::Implicit | RegState::Define | RegState::Dead) 9992 .addReg(ARM::CPSR, 9993 RegState::Implicit | RegState::Define | RegState::Dead); 9994 break; 9995 case CodeModel::Large: { 9996 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9997 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9998 9999 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 10000 .addExternalSymbol("__chkstk"); 10001 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 10002 .add(predOps(ARMCC::AL)) 10003 .addReg(Reg, RegState::Kill) 10004 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 10005 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 10006 .addReg(ARM::R12, 10007 RegState::Implicit | RegState::Define | RegState::Dead) 10008 .addReg(ARM::CPSR, 10009 RegState::Implicit | RegState::Define | RegState::Dead); 10010 break; 10011 } 10012 } 10013 10014 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 10015 .addReg(ARM::SP, RegState::Kill) 10016 .addReg(ARM::R4, RegState::Kill) 10017 .setMIFlags(MachineInstr::FrameSetup) 10018 .add(predOps(ARMCC::AL)) 10019 .add(condCodeOp()); 10020 10021 MI.eraseFromParent(); 10022 return MBB; 10023 } 10024 10025 MachineBasicBlock * 10026 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 10027 MachineBasicBlock *MBB) const { 10028 DebugLoc DL = MI.getDebugLoc(); 10029 MachineFunction *MF = MBB->getParent(); 10030 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10031 10032 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 10033 MF->insert(++MBB->getIterator(), ContBB); 10034 ContBB->splice(ContBB->begin(), MBB, 10035 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10036 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 10037 MBB->addSuccessor(ContBB); 10038 10039 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 10040 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 10041 MF->push_back(TrapBB); 10042 MBB->addSuccessor(TrapBB); 10043 10044 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 10045 .addReg(MI.getOperand(0).getReg()) 10046 .addImm(0) 10047 .add(predOps(ARMCC::AL)); 10048 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 10049 .addMBB(TrapBB) 10050 .addImm(ARMCC::EQ) 10051 .addReg(ARM::CPSR); 10052 10053 MI.eraseFromParent(); 10054 return ContBB; 10055 } 10056 10057 // The CPSR operand of SelectItr might be missing a kill marker 10058 // because there were multiple uses of CPSR, and ISel didn't know 10059 // which to mark. Figure out whether SelectItr should have had a 10060 // kill marker, and set it if it should. Returns the correct kill 10061 // marker value. 10062 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 10063 MachineBasicBlock* BB, 10064 const TargetRegisterInfo* TRI) { 10065 // Scan forward through BB for a use/def of CPSR. 10066 MachineBasicBlock::iterator miI(std::next(SelectItr)); 10067 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 10068 const MachineInstr& mi = *miI; 10069 if (mi.readsRegister(ARM::CPSR)) 10070 return false; 10071 if (mi.definesRegister(ARM::CPSR)) 10072 break; // Should have kill-flag - update below. 10073 } 10074 10075 // If we hit the end of the block, check whether CPSR is live into a 10076 // successor. 10077 if (miI == BB->end()) { 10078 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10079 sEnd = BB->succ_end(); 10080 sItr != sEnd; ++sItr) { 10081 MachineBasicBlock* succ = *sItr; 10082 if (succ->isLiveIn(ARM::CPSR)) 10083 return false; 10084 } 10085 } 10086 10087 // We found a def, or hit the end of the basic block and CPSR wasn't live 10088 // out. SelectMI should have a kill flag on CPSR. 10089 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10090 return true; 10091 } 10092 10093 MachineBasicBlock * 10094 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10095 MachineBasicBlock *BB) const { 10096 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10097 DebugLoc dl = MI.getDebugLoc(); 10098 bool isThumb2 = Subtarget->isThumb2(); 10099 switch (MI.getOpcode()) { 10100 default: { 10101 MI.print(errs()); 10102 llvm_unreachable("Unexpected instr type to insert"); 10103 } 10104 10105 // Thumb1 post-indexed loads are really just single-register LDMs. 10106 case ARM::tLDR_postidx: { 10107 MachineOperand Def(MI.getOperand(1)); 10108 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 10109 .add(Def) // Rn_wb 10110 .add(MI.getOperand(2)) // Rn 10111 .add(MI.getOperand(3)) // PredImm 10112 .add(MI.getOperand(4)) // PredReg 10113 .add(MI.getOperand(0)) // Rt 10114 .cloneMemRefs(MI); 10115 MI.eraseFromParent(); 10116 return BB; 10117 } 10118 10119 // The Thumb2 pre-indexed stores have the same MI operands, they just 10120 // define them differently in the .td files from the isel patterns, so 10121 // they need pseudos. 10122 case ARM::t2STR_preidx: 10123 MI.setDesc(TII->get(ARM::t2STR_PRE)); 10124 return BB; 10125 case ARM::t2STRB_preidx: 10126 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 10127 return BB; 10128 case ARM::t2STRH_preidx: 10129 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 10130 return BB; 10131 10132 case ARM::STRi_preidx: 10133 case ARM::STRBi_preidx: { 10134 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 10135 : ARM::STRB_PRE_IMM; 10136 // Decode the offset. 10137 unsigned Offset = MI.getOperand(4).getImm(); 10138 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 10139 Offset = ARM_AM::getAM2Offset(Offset); 10140 if (isSub) 10141 Offset = -Offset; 10142 10143 MachineMemOperand *MMO = *MI.memoperands_begin(); 10144 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 10145 .add(MI.getOperand(0)) // Rn_wb 10146 .add(MI.getOperand(1)) // Rt 10147 .add(MI.getOperand(2)) // Rn 10148 .addImm(Offset) // offset (skip GPR==zero_reg) 10149 .add(MI.getOperand(5)) // pred 10150 .add(MI.getOperand(6)) 10151 .addMemOperand(MMO); 10152 MI.eraseFromParent(); 10153 return BB; 10154 } 10155 case ARM::STRr_preidx: 10156 case ARM::STRBr_preidx: 10157 case ARM::STRH_preidx: { 10158 unsigned NewOpc; 10159 switch (MI.getOpcode()) { 10160 default: llvm_unreachable("unexpected opcode!"); 10161 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 10162 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 10163 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 10164 } 10165 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 10166 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 10167 MIB.add(MI.getOperand(i)); 10168 MI.eraseFromParent(); 10169 return BB; 10170 } 10171 10172 case ARM::tMOVCCr_pseudo: { 10173 // To "insert" a SELECT_CC instruction, we actually have to insert the 10174 // diamond control-flow pattern. The incoming instruction knows the 10175 // destination vreg to set, the condition code register to branch on, the 10176 // true/false values to select between, and a branch opcode to use. 10177 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10178 MachineFunction::iterator It = ++BB->getIterator(); 10179 10180 // thisMBB: 10181 // ... 10182 // TrueVal = ... 10183 // cmpTY ccX, r1, r2 10184 // bCC copy1MBB 10185 // fallthrough --> copy0MBB 10186 MachineBasicBlock *thisMBB = BB; 10187 MachineFunction *F = BB->getParent(); 10188 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10189 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10190 F->insert(It, copy0MBB); 10191 F->insert(It, sinkMBB); 10192 10193 // Check whether CPSR is live past the tMOVCCr_pseudo. 10194 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10195 if (!MI.killsRegister(ARM::CPSR) && 10196 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 10197 copy0MBB->addLiveIn(ARM::CPSR); 10198 sinkMBB->addLiveIn(ARM::CPSR); 10199 } 10200 10201 // Transfer the remainder of BB and its successor edges to sinkMBB. 10202 sinkMBB->splice(sinkMBB->begin(), BB, 10203 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10204 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10205 10206 BB->addSuccessor(copy0MBB); 10207 BB->addSuccessor(sinkMBB); 10208 10209 BuildMI(BB, dl, TII->get(ARM::tBcc)) 10210 .addMBB(sinkMBB) 10211 .addImm(MI.getOperand(3).getImm()) 10212 .addReg(MI.getOperand(4).getReg()); 10213 10214 // copy0MBB: 10215 // %FalseValue = ... 10216 // # fallthrough to sinkMBB 10217 BB = copy0MBB; 10218 10219 // Update machine-CFG edges 10220 BB->addSuccessor(sinkMBB); 10221 10222 // sinkMBB: 10223 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10224 // ... 10225 BB = sinkMBB; 10226 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 10227 .addReg(MI.getOperand(1).getReg()) 10228 .addMBB(copy0MBB) 10229 .addReg(MI.getOperand(2).getReg()) 10230 .addMBB(thisMBB); 10231 10232 MI.eraseFromParent(); // The pseudo instruction is gone now. 10233 return BB; 10234 } 10235 10236 case ARM::BCCi64: 10237 case ARM::BCCZi64: { 10238 // If there is an unconditional branch to the other successor, remove it. 10239 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10240 10241 // Compare both parts that make up the double comparison separately for 10242 // equality. 10243 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 10244 10245 Register LHS1 = MI.getOperand(1).getReg(); 10246 Register LHS2 = MI.getOperand(2).getReg(); 10247 if (RHSisZero) { 10248 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10249 .addReg(LHS1) 10250 .addImm(0) 10251 .add(predOps(ARMCC::AL)); 10252 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10253 .addReg(LHS2).addImm(0) 10254 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10255 } else { 10256 Register RHS1 = MI.getOperand(3).getReg(); 10257 Register RHS2 = MI.getOperand(4).getReg(); 10258 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10259 .addReg(LHS1) 10260 .addReg(RHS1) 10261 .add(predOps(ARMCC::AL)); 10262 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10263 .addReg(LHS2).addReg(RHS2) 10264 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10265 } 10266 10267 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 10268 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 10269 if (MI.getOperand(0).getImm() == ARMCC::NE) 10270 std::swap(destMBB, exitMBB); 10271 10272 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10273 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 10274 if (isThumb2) 10275 BuildMI(BB, dl, TII->get(ARM::t2B)) 10276 .addMBB(exitMBB) 10277 .add(predOps(ARMCC::AL)); 10278 else 10279 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 10280 10281 MI.eraseFromParent(); // The pseudo instruction is gone now. 10282 return BB; 10283 } 10284 10285 case ARM::Int_eh_sjlj_setjmp: 10286 case ARM::Int_eh_sjlj_setjmp_nofp: 10287 case ARM::tInt_eh_sjlj_setjmp: 10288 case ARM::t2Int_eh_sjlj_setjmp: 10289 case ARM::t2Int_eh_sjlj_setjmp_nofp: 10290 return BB; 10291 10292 case ARM::Int_eh_sjlj_setup_dispatch: 10293 EmitSjLjDispatchBlock(MI, BB); 10294 return BB; 10295 10296 case ARM::ABS: 10297 case ARM::t2ABS: { 10298 // To insert an ABS instruction, we have to insert the 10299 // diamond control-flow pattern. The incoming instruction knows the 10300 // source vreg to test against 0, the destination vreg to set, 10301 // the condition code register to branch on, the 10302 // true/false values to select between, and a branch opcode to use. 10303 // It transforms 10304 // V1 = ABS V0 10305 // into 10306 // V2 = MOVS V0 10307 // BCC (branch to SinkBB if V0 >= 0) 10308 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 10309 // SinkBB: V1 = PHI(V2, V3) 10310 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10311 MachineFunction::iterator BBI = ++BB->getIterator(); 10312 MachineFunction *Fn = BB->getParent(); 10313 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10314 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10315 Fn->insert(BBI, RSBBB); 10316 Fn->insert(BBI, SinkBB); 10317 10318 Register ABSSrcReg = MI.getOperand(1).getReg(); 10319 Register ABSDstReg = MI.getOperand(0).getReg(); 10320 bool ABSSrcKIll = MI.getOperand(1).isKill(); 10321 bool isThumb2 = Subtarget->isThumb2(); 10322 MachineRegisterInfo &MRI = Fn->getRegInfo(); 10323 // In Thumb mode S must not be specified if source register is the SP or 10324 // PC and if destination register is the SP, so restrict register class 10325 Register NewRsbDstReg = MRI.createVirtualRegister( 10326 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 10327 10328 // Transfer the remainder of BB and its successor edges to sinkMBB. 10329 SinkBB->splice(SinkBB->begin(), BB, 10330 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10331 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 10332 10333 BB->addSuccessor(RSBBB); 10334 BB->addSuccessor(SinkBB); 10335 10336 // fall through to SinkMBB 10337 RSBBB->addSuccessor(SinkBB); 10338 10339 // insert a cmp at the end of BB 10340 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10341 .addReg(ABSSrcReg) 10342 .addImm(0) 10343 .add(predOps(ARMCC::AL)); 10344 10345 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 10346 BuildMI(BB, dl, 10347 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 10348 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 10349 10350 // insert rsbri in RSBBB 10351 // Note: BCC and rsbri will be converted into predicated rsbmi 10352 // by if-conversion pass 10353 BuildMI(*RSBBB, RSBBB->begin(), dl, 10354 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 10355 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 10356 .addImm(0) 10357 .add(predOps(ARMCC::AL)) 10358 .add(condCodeOp()); 10359 10360 // insert PHI in SinkBB, 10361 // reuse ABSDstReg to not change uses of ABS instruction 10362 BuildMI(*SinkBB, SinkBB->begin(), dl, 10363 TII->get(ARM::PHI), ABSDstReg) 10364 .addReg(NewRsbDstReg).addMBB(RSBBB) 10365 .addReg(ABSSrcReg).addMBB(BB); 10366 10367 // remove ABS instruction 10368 MI.eraseFromParent(); 10369 10370 // return last added BB 10371 return SinkBB; 10372 } 10373 case ARM::COPY_STRUCT_BYVAL_I32: 10374 ++NumLoopByVals; 10375 return EmitStructByval(MI, BB); 10376 case ARM::WIN__CHKSTK: 10377 return EmitLowered__chkstk(MI, BB); 10378 case ARM::WIN__DBZCHK: 10379 return EmitLowered__dbzchk(MI, BB); 10380 } 10381 } 10382 10383 /// Attaches vregs to MEMCPY that it will use as scratch registers 10384 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 10385 /// instead of as a custom inserter because we need the use list from the SDNode. 10386 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 10387 MachineInstr &MI, const SDNode *Node) { 10388 bool isThumb1 = Subtarget->isThumb1Only(); 10389 10390 DebugLoc DL = MI.getDebugLoc(); 10391 MachineFunction *MF = MI.getParent()->getParent(); 10392 MachineRegisterInfo &MRI = MF->getRegInfo(); 10393 MachineInstrBuilder MIB(*MF, MI); 10394 10395 // If the new dst/src is unused mark it as dead. 10396 if (!Node->hasAnyUseOfValue(0)) { 10397 MI.getOperand(0).setIsDead(true); 10398 } 10399 if (!Node->hasAnyUseOfValue(1)) { 10400 MI.getOperand(1).setIsDead(true); 10401 } 10402 10403 // The MEMCPY both defines and kills the scratch registers. 10404 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 10405 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 10406 : &ARM::GPRRegClass); 10407 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 10408 } 10409 } 10410 10411 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10412 SDNode *Node) const { 10413 if (MI.getOpcode() == ARM::MEMCPY) { 10414 attachMEMCPYScratchRegs(Subtarget, MI, Node); 10415 return; 10416 } 10417 10418 const MCInstrDesc *MCID = &MI.getDesc(); 10419 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 10420 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 10421 // operand is still set to noreg. If needed, set the optional operand's 10422 // register to CPSR, and remove the redundant implicit def. 10423 // 10424 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 10425 10426 // Rename pseudo opcodes. 10427 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 10428 unsigned ccOutIdx; 10429 if (NewOpc) { 10430 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 10431 MCID = &TII->get(NewOpc); 10432 10433 assert(MCID->getNumOperands() == 10434 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 10435 && "converted opcode should be the same except for cc_out" 10436 " (and, on Thumb1, pred)"); 10437 10438 MI.setDesc(*MCID); 10439 10440 // Add the optional cc_out operand 10441 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 10442 10443 // On Thumb1, move all input operands to the end, then add the predicate 10444 if (Subtarget->isThumb1Only()) { 10445 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 10446 MI.addOperand(MI.getOperand(1)); 10447 MI.RemoveOperand(1); 10448 } 10449 10450 // Restore the ties 10451 for (unsigned i = MI.getNumOperands(); i--;) { 10452 const MachineOperand& op = MI.getOperand(i); 10453 if (op.isReg() && op.isUse()) { 10454 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 10455 if (DefIdx != -1) 10456 MI.tieOperands(DefIdx, i); 10457 } 10458 } 10459 10460 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 10461 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 10462 ccOutIdx = 1; 10463 } else 10464 ccOutIdx = MCID->getNumOperands() - 1; 10465 } else 10466 ccOutIdx = MCID->getNumOperands() - 1; 10467 10468 // Any ARM instruction that sets the 's' bit should specify an optional 10469 // "cc_out" operand in the last operand position. 10470 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 10471 assert(!NewOpc && "Optional cc_out operand required"); 10472 return; 10473 } 10474 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 10475 // since we already have an optional CPSR def. 10476 bool definesCPSR = false; 10477 bool deadCPSR = false; 10478 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 10479 ++i) { 10480 const MachineOperand &MO = MI.getOperand(i); 10481 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 10482 definesCPSR = true; 10483 if (MO.isDead()) 10484 deadCPSR = true; 10485 MI.RemoveOperand(i); 10486 break; 10487 } 10488 } 10489 if (!definesCPSR) { 10490 assert(!NewOpc && "Optional cc_out operand required"); 10491 return; 10492 } 10493 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 10494 if (deadCPSR) { 10495 assert(!MI.getOperand(ccOutIdx).getReg() && 10496 "expect uninitialized optional cc_out operand"); 10497 // Thumb1 instructions must have the S bit even if the CPSR is dead. 10498 if (!Subtarget->isThumb1Only()) 10499 return; 10500 } 10501 10502 // If this instruction was defined with an optional CPSR def and its dag node 10503 // had a live implicit CPSR def, then activate the optional CPSR def. 10504 MachineOperand &MO = MI.getOperand(ccOutIdx); 10505 MO.setReg(ARM::CPSR); 10506 MO.setIsDef(true); 10507 } 10508 10509 //===----------------------------------------------------------------------===// 10510 // ARM Optimization Hooks 10511 //===----------------------------------------------------------------------===// 10512 10513 // Helper function that checks if N is a null or all ones constant. 10514 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 10515 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 10516 } 10517 10518 // Return true if N is conditionally 0 or all ones. 10519 // Detects these expressions where cc is an i1 value: 10520 // 10521 // (select cc 0, y) [AllOnes=0] 10522 // (select cc y, 0) [AllOnes=0] 10523 // (zext cc) [AllOnes=0] 10524 // (sext cc) [AllOnes=0/1] 10525 // (select cc -1, y) [AllOnes=1] 10526 // (select cc y, -1) [AllOnes=1] 10527 // 10528 // Invert is set when N is the null/all ones constant when CC is false. 10529 // OtherOp is set to the alternative value of N. 10530 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 10531 SDValue &CC, bool &Invert, 10532 SDValue &OtherOp, 10533 SelectionDAG &DAG) { 10534 switch (N->getOpcode()) { 10535 default: return false; 10536 case ISD::SELECT: { 10537 CC = N->getOperand(0); 10538 SDValue N1 = N->getOperand(1); 10539 SDValue N2 = N->getOperand(2); 10540 if (isZeroOrAllOnes(N1, AllOnes)) { 10541 Invert = false; 10542 OtherOp = N2; 10543 return true; 10544 } 10545 if (isZeroOrAllOnes(N2, AllOnes)) { 10546 Invert = true; 10547 OtherOp = N1; 10548 return true; 10549 } 10550 return false; 10551 } 10552 case ISD::ZERO_EXTEND: 10553 // (zext cc) can never be the all ones value. 10554 if (AllOnes) 10555 return false; 10556 LLVM_FALLTHROUGH; 10557 case ISD::SIGN_EXTEND: { 10558 SDLoc dl(N); 10559 EVT VT = N->getValueType(0); 10560 CC = N->getOperand(0); 10561 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 10562 return false; 10563 Invert = !AllOnes; 10564 if (AllOnes) 10565 // When looking for an AllOnes constant, N is an sext, and the 'other' 10566 // value is 0. 10567 OtherOp = DAG.getConstant(0, dl, VT); 10568 else if (N->getOpcode() == ISD::ZERO_EXTEND) 10569 // When looking for a 0 constant, N can be zext or sext. 10570 OtherOp = DAG.getConstant(1, dl, VT); 10571 else 10572 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 10573 VT); 10574 return true; 10575 } 10576 } 10577 } 10578 10579 // Combine a constant select operand into its use: 10580 // 10581 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10582 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10583 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 10584 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10585 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10586 // 10587 // The transform is rejected if the select doesn't have a constant operand that 10588 // is null, or all ones when AllOnes is set. 10589 // 10590 // Also recognize sext/zext from i1: 10591 // 10592 // (add (zext cc), x) -> (select cc (add x, 1), x) 10593 // (add (sext cc), x) -> (select cc (add x, -1), x) 10594 // 10595 // These transformations eventually create predicated instructions. 10596 // 10597 // @param N The node to transform. 10598 // @param Slct The N operand that is a select. 10599 // @param OtherOp The other N operand (x above). 10600 // @param DCI Context. 10601 // @param AllOnes Require the select constant to be all ones instead of null. 10602 // @returns The new node, or SDValue() on failure. 10603 static 10604 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 10605 TargetLowering::DAGCombinerInfo &DCI, 10606 bool AllOnes = false) { 10607 SelectionDAG &DAG = DCI.DAG; 10608 EVT VT = N->getValueType(0); 10609 SDValue NonConstantVal; 10610 SDValue CCOp; 10611 bool SwapSelectOps; 10612 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 10613 NonConstantVal, DAG)) 10614 return SDValue(); 10615 10616 // Slct is now know to be the desired identity constant when CC is true. 10617 SDValue TrueVal = OtherOp; 10618 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 10619 OtherOp, NonConstantVal); 10620 // Unless SwapSelectOps says CC should be false. 10621 if (SwapSelectOps) 10622 std::swap(TrueVal, FalseVal); 10623 10624 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 10625 CCOp, TrueVal, FalseVal); 10626 } 10627 10628 // Attempt combineSelectAndUse on each operand of a commutative operator N. 10629 static 10630 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 10631 TargetLowering::DAGCombinerInfo &DCI) { 10632 SDValue N0 = N->getOperand(0); 10633 SDValue N1 = N->getOperand(1); 10634 if (N0.getNode()->hasOneUse()) 10635 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 10636 return Result; 10637 if (N1.getNode()->hasOneUse()) 10638 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 10639 return Result; 10640 return SDValue(); 10641 } 10642 10643 static bool IsVUZPShuffleNode(SDNode *N) { 10644 // VUZP shuffle node. 10645 if (N->getOpcode() == ARMISD::VUZP) 10646 return true; 10647 10648 // "VUZP" on i32 is an alias for VTRN. 10649 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 10650 return true; 10651 10652 return false; 10653 } 10654 10655 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 10656 TargetLowering::DAGCombinerInfo &DCI, 10657 const ARMSubtarget *Subtarget) { 10658 // Look for ADD(VUZP.0, VUZP.1). 10659 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 10660 N0 == N1) 10661 return SDValue(); 10662 10663 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 10664 if (!N->getValueType(0).is64BitVector()) 10665 return SDValue(); 10666 10667 // Generate vpadd. 10668 SelectionDAG &DAG = DCI.DAG; 10669 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10670 SDLoc dl(N); 10671 SDNode *Unzip = N0.getNode(); 10672 EVT VT = N->getValueType(0); 10673 10674 SmallVector<SDValue, 8> Ops; 10675 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 10676 TLI.getPointerTy(DAG.getDataLayout()))); 10677 Ops.push_back(Unzip->getOperand(0)); 10678 Ops.push_back(Unzip->getOperand(1)); 10679 10680 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10681 } 10682 10683 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10684 TargetLowering::DAGCombinerInfo &DCI, 10685 const ARMSubtarget *Subtarget) { 10686 // Check for two extended operands. 10687 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 10688 N1.getOpcode() == ISD::SIGN_EXTEND) && 10689 !(N0.getOpcode() == ISD::ZERO_EXTEND && 10690 N1.getOpcode() == ISD::ZERO_EXTEND)) 10691 return SDValue(); 10692 10693 SDValue N00 = N0.getOperand(0); 10694 SDValue N10 = N1.getOperand(0); 10695 10696 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 10697 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 10698 N00 == N10) 10699 return SDValue(); 10700 10701 // We only recognize Q register paddl here; this can't be reached until 10702 // after type legalization. 10703 if (!N00.getValueType().is64BitVector() || 10704 !N0.getValueType().is128BitVector()) 10705 return SDValue(); 10706 10707 // Generate vpaddl. 10708 SelectionDAG &DAG = DCI.DAG; 10709 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10710 SDLoc dl(N); 10711 EVT VT = N->getValueType(0); 10712 10713 SmallVector<SDValue, 8> Ops; 10714 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 10715 unsigned Opcode; 10716 if (N0.getOpcode() == ISD::SIGN_EXTEND) 10717 Opcode = Intrinsic::arm_neon_vpaddls; 10718 else 10719 Opcode = Intrinsic::arm_neon_vpaddlu; 10720 Ops.push_back(DAG.getConstant(Opcode, dl, 10721 TLI.getPointerTy(DAG.getDataLayout()))); 10722 EVT ElemTy = N00.getValueType().getVectorElementType(); 10723 unsigned NumElts = VT.getVectorNumElements(); 10724 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 10725 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 10726 N00.getOperand(0), N00.getOperand(1)); 10727 Ops.push_back(Concat); 10728 10729 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10730 } 10731 10732 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 10733 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 10734 // much easier to match. 10735 static SDValue 10736 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10737 TargetLowering::DAGCombinerInfo &DCI, 10738 const ARMSubtarget *Subtarget) { 10739 // Only perform optimization if after legalize, and if NEON is available. We 10740 // also expected both operands to be BUILD_VECTORs. 10741 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 10742 || N0.getOpcode() != ISD::BUILD_VECTOR 10743 || N1.getOpcode() != ISD::BUILD_VECTOR) 10744 return SDValue(); 10745 10746 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 10747 EVT VT = N->getValueType(0); 10748 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 10749 return SDValue(); 10750 10751 // Check that the vector operands are of the right form. 10752 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 10753 // operands, where N is the size of the formed vector. 10754 // Each EXTRACT_VECTOR should have the same input vector and odd or even 10755 // index such that we have a pair wise add pattern. 10756 10757 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 10758 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10759 return SDValue(); 10760 SDValue Vec = N0->getOperand(0)->getOperand(0); 10761 SDNode *V = Vec.getNode(); 10762 unsigned nextIndex = 0; 10763 10764 // For each operands to the ADD which are BUILD_VECTORs, 10765 // check to see if each of their operands are an EXTRACT_VECTOR with 10766 // the same vector and appropriate index. 10767 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 10768 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 10769 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10770 10771 SDValue ExtVec0 = N0->getOperand(i); 10772 SDValue ExtVec1 = N1->getOperand(i); 10773 10774 // First operand is the vector, verify its the same. 10775 if (V != ExtVec0->getOperand(0).getNode() || 10776 V != ExtVec1->getOperand(0).getNode()) 10777 return SDValue(); 10778 10779 // Second is the constant, verify its correct. 10780 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 10781 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 10782 10783 // For the constant, we want to see all the even or all the odd. 10784 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 10785 || C1->getZExtValue() != nextIndex+1) 10786 return SDValue(); 10787 10788 // Increment index. 10789 nextIndex+=2; 10790 } else 10791 return SDValue(); 10792 } 10793 10794 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 10795 // we're using the entire input vector, otherwise there's a size/legality 10796 // mismatch somewhere. 10797 if (nextIndex != Vec.getValueType().getVectorNumElements() || 10798 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 10799 return SDValue(); 10800 10801 // Create VPADDL node. 10802 SelectionDAG &DAG = DCI.DAG; 10803 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10804 10805 SDLoc dl(N); 10806 10807 // Build operand list. 10808 SmallVector<SDValue, 8> Ops; 10809 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 10810 TLI.getPointerTy(DAG.getDataLayout()))); 10811 10812 // Input is the vector. 10813 Ops.push_back(Vec); 10814 10815 // Get widened type and narrowed type. 10816 MVT widenType; 10817 unsigned numElem = VT.getVectorNumElements(); 10818 10819 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 10820 switch (inputLaneType.getSimpleVT().SimpleTy) { 10821 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 10822 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 10823 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 10824 default: 10825 llvm_unreachable("Invalid vector element type for padd optimization."); 10826 } 10827 10828 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 10829 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 10830 return DAG.getNode(ExtOp, dl, VT, tmp); 10831 } 10832 10833 static SDValue findMUL_LOHI(SDValue V) { 10834 if (V->getOpcode() == ISD::UMUL_LOHI || 10835 V->getOpcode() == ISD::SMUL_LOHI) 10836 return V; 10837 return SDValue(); 10838 } 10839 10840 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 10841 TargetLowering::DAGCombinerInfo &DCI, 10842 const ARMSubtarget *Subtarget) { 10843 if (Subtarget->isThumb()) { 10844 if (!Subtarget->hasDSP()) 10845 return SDValue(); 10846 } else if (!Subtarget->hasV5TEOps()) 10847 return SDValue(); 10848 10849 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 10850 // accumulates the product into a 64-bit value. The 16-bit values will 10851 // be sign extended somehow or SRA'd into 32-bit values 10852 // (addc (adde (mul 16bit, 16bit), lo), hi) 10853 SDValue Mul = AddcNode->getOperand(0); 10854 SDValue Lo = AddcNode->getOperand(1); 10855 if (Mul.getOpcode() != ISD::MUL) { 10856 Lo = AddcNode->getOperand(0); 10857 Mul = AddcNode->getOperand(1); 10858 if (Mul.getOpcode() != ISD::MUL) 10859 return SDValue(); 10860 } 10861 10862 SDValue SRA = AddeNode->getOperand(0); 10863 SDValue Hi = AddeNode->getOperand(1); 10864 if (SRA.getOpcode() != ISD::SRA) { 10865 SRA = AddeNode->getOperand(1); 10866 Hi = AddeNode->getOperand(0); 10867 if (SRA.getOpcode() != ISD::SRA) 10868 return SDValue(); 10869 } 10870 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10871 if (Const->getZExtValue() != 31) 10872 return SDValue(); 10873 } else 10874 return SDValue(); 10875 10876 if (SRA.getOperand(0) != Mul) 10877 return SDValue(); 10878 10879 SelectionDAG &DAG = DCI.DAG; 10880 SDLoc dl(AddcNode); 10881 unsigned Opcode = 0; 10882 SDValue Op0; 10883 SDValue Op1; 10884 10885 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10886 Opcode = ARMISD::SMLALBB; 10887 Op0 = Mul.getOperand(0); 10888 Op1 = Mul.getOperand(1); 10889 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10890 Opcode = ARMISD::SMLALBT; 10891 Op0 = Mul.getOperand(0); 10892 Op1 = Mul.getOperand(1).getOperand(0); 10893 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10894 Opcode = ARMISD::SMLALTB; 10895 Op0 = Mul.getOperand(0).getOperand(0); 10896 Op1 = Mul.getOperand(1); 10897 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10898 Opcode = ARMISD::SMLALTT; 10899 Op0 = Mul->getOperand(0).getOperand(0); 10900 Op1 = Mul->getOperand(1).getOperand(0); 10901 } 10902 10903 if (!Op0 || !Op1) 10904 return SDValue(); 10905 10906 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10907 Op0, Op1, Lo, Hi); 10908 // Replace the ADDs' nodes uses by the MLA node's values. 10909 SDValue HiMLALResult(SMLAL.getNode(), 1); 10910 SDValue LoMLALResult(SMLAL.getNode(), 0); 10911 10912 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10913 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10914 10915 // Return original node to notify the driver to stop replacing. 10916 SDValue resNode(AddcNode, 0); 10917 return resNode; 10918 } 10919 10920 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10921 TargetLowering::DAGCombinerInfo &DCI, 10922 const ARMSubtarget *Subtarget) { 10923 // Look for multiply add opportunities. 10924 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10925 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10926 // a glue link from the first add to the second add. 10927 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10928 // a S/UMLAL instruction. 10929 // UMUL_LOHI 10930 // / :lo \ :hi 10931 // V \ [no multiline comment] 10932 // loAdd -> ADDC | 10933 // \ :carry / 10934 // V V 10935 // ADDE <- hiAdd 10936 // 10937 // In the special case where only the higher part of a signed result is used 10938 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10939 // a constant with the exact value of 0x80000000, we recognize we are dealing 10940 // with a "rounded multiply and add" (or subtract) and transform it into 10941 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10942 10943 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10944 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10945 "Expect an ADDE or SUBE"); 10946 10947 assert(AddeSubeNode->getNumOperands() == 3 && 10948 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10949 "ADDE node has the wrong inputs"); 10950 10951 // Check that we are chained to the right ADDC or SUBC node. 10952 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10953 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10954 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10955 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10956 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10957 return SDValue(); 10958 10959 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10960 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10961 10962 // Check if the two operands are from the same mul_lohi node. 10963 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10964 return SDValue(); 10965 10966 assert(AddcSubcNode->getNumValues() == 2 && 10967 AddcSubcNode->getValueType(0) == MVT::i32 && 10968 "Expect ADDC with two result values. First: i32"); 10969 10970 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10971 // maybe a SMLAL which multiplies two 16-bit values. 10972 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10973 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10974 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10975 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10976 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10977 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10978 10979 // Check for the triangle shape. 10980 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10981 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10982 10983 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10984 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10985 return SDValue(); 10986 10987 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10988 bool IsLeftOperandMUL = false; 10989 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10990 if (MULOp == SDValue()) 10991 MULOp = findMUL_LOHI(AddeSubeOp1); 10992 else 10993 IsLeftOperandMUL = true; 10994 if (MULOp == SDValue()) 10995 return SDValue(); 10996 10997 // Figure out the right opcode. 10998 unsigned Opc = MULOp->getOpcode(); 10999 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 11000 11001 // Figure out the high and low input values to the MLAL node. 11002 SDValue *HiAddSub = nullptr; 11003 SDValue *LoMul = nullptr; 11004 SDValue *LowAddSub = nullptr; 11005 11006 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 11007 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 11008 return SDValue(); 11009 11010 if (IsLeftOperandMUL) 11011 HiAddSub = &AddeSubeOp1; 11012 else 11013 HiAddSub = &AddeSubeOp0; 11014 11015 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 11016 // whose low result is fed to the ADDC/SUBC we are checking. 11017 11018 if (AddcSubcOp0 == MULOp.getValue(0)) { 11019 LoMul = &AddcSubcOp0; 11020 LowAddSub = &AddcSubcOp1; 11021 } 11022 if (AddcSubcOp1 == MULOp.getValue(0)) { 11023 LoMul = &AddcSubcOp1; 11024 LowAddSub = &AddcSubcOp0; 11025 } 11026 11027 if (!LoMul) 11028 return SDValue(); 11029 11030 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 11031 // the replacement below will create a cycle. 11032 if (AddcSubcNode == HiAddSub->getNode() || 11033 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 11034 return SDValue(); 11035 11036 // Create the merged node. 11037 SelectionDAG &DAG = DCI.DAG; 11038 11039 // Start building operand list. 11040 SmallVector<SDValue, 8> Ops; 11041 Ops.push_back(LoMul->getOperand(0)); 11042 Ops.push_back(LoMul->getOperand(1)); 11043 11044 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 11045 // the case, we must be doing signed multiplication and only use the higher 11046 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 11047 // addition or subtraction with the value of 0x800000. 11048 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 11049 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 11050 LowAddSub->getNode()->getOpcode() == ISD::Constant && 11051 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 11052 0x80000000) { 11053 Ops.push_back(*HiAddSub); 11054 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 11055 FinalOpc = ARMISD::SMMLSR; 11056 } else { 11057 FinalOpc = ARMISD::SMMLAR; 11058 } 11059 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 11060 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 11061 11062 return SDValue(AddeSubeNode, 0); 11063 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 11064 // SMMLS is generated during instruction selection and the rest of this 11065 // function can not handle the case where AddcSubcNode is a SUBC. 11066 return SDValue(); 11067 11068 // Finish building the operand list for {U/S}MLAL 11069 Ops.push_back(*LowAddSub); 11070 Ops.push_back(*HiAddSub); 11071 11072 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11073 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11074 11075 // Replace the ADDs' nodes uses by the MLA node's values. 11076 SDValue HiMLALResult(MLALNode.getNode(), 1); 11077 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11078 11079 SDValue LoMLALResult(MLALNode.getNode(), 0); 11080 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11081 11082 // Return original node to notify the driver to stop replacing. 11083 return SDValue(AddeSubeNode, 0); 11084 } 11085 11086 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11087 TargetLowering::DAGCombinerInfo &DCI, 11088 const ARMSubtarget *Subtarget) { 11089 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11090 // While trying to combine for the other MLAL nodes, first search for the 11091 // chance to use UMAAL. Check if Addc uses a node which has already 11092 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11093 // as the addend, and it's handled in PerformUMLALCombine. 11094 11095 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11096 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11097 11098 // Check that we have a glued ADDC node. 11099 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11100 if (AddcNode->getOpcode() != ARMISD::ADDC) 11101 return SDValue(); 11102 11103 // Find the converted UMAAL or quit if it doesn't exist. 11104 SDNode *UmlalNode = nullptr; 11105 SDValue AddHi; 11106 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11107 UmlalNode = AddcNode->getOperand(0).getNode(); 11108 AddHi = AddcNode->getOperand(1); 11109 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 11110 UmlalNode = AddcNode->getOperand(1).getNode(); 11111 AddHi = AddcNode->getOperand(0); 11112 } else { 11113 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11114 } 11115 11116 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 11117 // the ADDC as well as Zero. 11118 if (!isNullConstant(UmlalNode->getOperand(3))) 11119 return SDValue(); 11120 11121 if ((isNullConstant(AddeNode->getOperand(0)) && 11122 AddeNode->getOperand(1).getNode() == UmlalNode) || 11123 (AddeNode->getOperand(0).getNode() == UmlalNode && 11124 isNullConstant(AddeNode->getOperand(1)))) { 11125 SelectionDAG &DAG = DCI.DAG; 11126 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 11127 UmlalNode->getOperand(2), AddHi }; 11128 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 11129 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11130 11131 // Replace the ADDs' nodes uses by the UMAAL node's values. 11132 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 11133 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 11134 11135 // Return original node to notify the driver to stop replacing. 11136 return SDValue(AddeNode, 0); 11137 } 11138 return SDValue(); 11139 } 11140 11141 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 11142 const ARMSubtarget *Subtarget) { 11143 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11144 return SDValue(); 11145 11146 // Check that we have a pair of ADDC and ADDE as operands. 11147 // Both addends of the ADDE must be zero. 11148 SDNode* AddcNode = N->getOperand(2).getNode(); 11149 SDNode* AddeNode = N->getOperand(3).getNode(); 11150 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 11151 (AddeNode->getOpcode() == ARMISD::ADDE) && 11152 isNullConstant(AddeNode->getOperand(0)) && 11153 isNullConstant(AddeNode->getOperand(1)) && 11154 (AddeNode->getOperand(2).getNode() == AddcNode)) 11155 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 11156 DAG.getVTList(MVT::i32, MVT::i32), 11157 {N->getOperand(0), N->getOperand(1), 11158 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 11159 else 11160 return SDValue(); 11161 } 11162 11163 static SDValue PerformAddcSubcCombine(SDNode *N, 11164 TargetLowering::DAGCombinerInfo &DCI, 11165 const ARMSubtarget *Subtarget) { 11166 SelectionDAG &DAG(DCI.DAG); 11167 11168 if (N->getOpcode() == ARMISD::SUBC) { 11169 // (SUBC (ADDE 0, 0, C), 1) -> C 11170 SDValue LHS = N->getOperand(0); 11171 SDValue RHS = N->getOperand(1); 11172 if (LHS->getOpcode() == ARMISD::ADDE && 11173 isNullConstant(LHS->getOperand(0)) && 11174 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 11175 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 11176 } 11177 } 11178 11179 if (Subtarget->isThumb1Only()) { 11180 SDValue RHS = N->getOperand(1); 11181 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11182 int32_t imm = C->getSExtValue(); 11183 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 11184 SDLoc DL(N); 11185 RHS = DAG.getConstant(-imm, DL, MVT::i32); 11186 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 11187 : ARMISD::ADDC; 11188 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 11189 } 11190 } 11191 } 11192 11193 return SDValue(); 11194 } 11195 11196 static SDValue PerformAddeSubeCombine(SDNode *N, 11197 TargetLowering::DAGCombinerInfo &DCI, 11198 const ARMSubtarget *Subtarget) { 11199 if (Subtarget->isThumb1Only()) { 11200 SelectionDAG &DAG = DCI.DAG; 11201 SDValue RHS = N->getOperand(1); 11202 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11203 int64_t imm = C->getSExtValue(); 11204 if (imm < 0) { 11205 SDLoc DL(N); 11206 11207 // The with-carry-in form matches bitwise not instead of the negation. 11208 // Effectively, the inverse interpretation of the carry flag already 11209 // accounts for part of the negation. 11210 RHS = DAG.getConstant(~imm, DL, MVT::i32); 11211 11212 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 11213 : ARMISD::ADDE; 11214 return DAG.getNode(Opcode, DL, N->getVTList(), 11215 N->getOperand(0), RHS, N->getOperand(2)); 11216 } 11217 } 11218 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 11219 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 11220 } 11221 return SDValue(); 11222 } 11223 11224 static SDValue PerformABSCombine(SDNode *N, 11225 TargetLowering::DAGCombinerInfo &DCI, 11226 const ARMSubtarget *Subtarget) { 11227 SDValue res; 11228 SelectionDAG &DAG = DCI.DAG; 11229 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11230 11231 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 11232 return SDValue(); 11233 11234 if (!TLI.expandABS(N, res, DAG)) 11235 return SDValue(); 11236 11237 return res; 11238 } 11239 11240 /// PerformADDECombine - Target-specific dag combine transform from 11241 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 11242 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 11243 static SDValue PerformADDECombine(SDNode *N, 11244 TargetLowering::DAGCombinerInfo &DCI, 11245 const ARMSubtarget *Subtarget) { 11246 // Only ARM and Thumb2 support UMLAL/SMLAL. 11247 if (Subtarget->isThumb1Only()) 11248 return PerformAddeSubeCombine(N, DCI, Subtarget); 11249 11250 // Only perform the checks after legalize when the pattern is available. 11251 if (DCI.isBeforeLegalize()) return SDValue(); 11252 11253 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 11254 } 11255 11256 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 11257 /// operands N0 and N1. This is a helper for PerformADDCombine that is 11258 /// called with the default operands, and if that fails, with commuted 11259 /// operands. 11260 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 11261 TargetLowering::DAGCombinerInfo &DCI, 11262 const ARMSubtarget *Subtarget){ 11263 // Attempt to create vpadd for this add. 11264 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 11265 return Result; 11266 11267 // Attempt to create vpaddl for this add. 11268 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 11269 return Result; 11270 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 11271 Subtarget)) 11272 return Result; 11273 11274 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11275 if (N0.getNode()->hasOneUse()) 11276 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 11277 return Result; 11278 return SDValue(); 11279 } 11280 11281 bool 11282 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 11283 CombineLevel Level) const { 11284 if (Level == BeforeLegalizeTypes) 11285 return true; 11286 11287 if (N->getOpcode() != ISD::SHL) 11288 return true; 11289 11290 if (Subtarget->isThumb1Only()) { 11291 // Avoid making expensive immediates by commuting shifts. (This logic 11292 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 11293 // for free.) 11294 if (N->getOpcode() != ISD::SHL) 11295 return true; 11296 SDValue N1 = N->getOperand(0); 11297 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 11298 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 11299 return true; 11300 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 11301 if (Const->getAPIntValue().ult(256)) 11302 return false; 11303 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 11304 Const->getAPIntValue().sgt(-256)) 11305 return false; 11306 } 11307 return true; 11308 } 11309 11310 // Turn off commute-with-shift transform after legalization, so it doesn't 11311 // conflict with PerformSHLSimplify. (We could try to detect when 11312 // PerformSHLSimplify would trigger more precisely, but it isn't 11313 // really necessary.) 11314 return false; 11315 } 11316 11317 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 11318 const SDNode *N, CombineLevel Level) const { 11319 if (!Subtarget->isThumb1Only()) 11320 return true; 11321 11322 if (Level == BeforeLegalizeTypes) 11323 return true; 11324 11325 return false; 11326 } 11327 11328 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 11329 if (!Subtarget->hasNEON()) { 11330 if (Subtarget->isThumb1Only()) 11331 return VT.getScalarSizeInBits() <= 32; 11332 return true; 11333 } 11334 return VT.isScalarInteger(); 11335 } 11336 11337 static SDValue PerformSHLSimplify(SDNode *N, 11338 TargetLowering::DAGCombinerInfo &DCI, 11339 const ARMSubtarget *ST) { 11340 // Allow the generic combiner to identify potential bswaps. 11341 if (DCI.isBeforeLegalize()) 11342 return SDValue(); 11343 11344 // DAG combiner will fold: 11345 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 11346 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 11347 // Other code patterns that can be also be modified have the following form: 11348 // b + ((a << 1) | 510) 11349 // b + ((a << 1) & 510) 11350 // b + ((a << 1) ^ 510) 11351 // b + ((a << 1) + 510) 11352 11353 // Many instructions can perform the shift for free, but it requires both 11354 // the operands to be registers. If c1 << c2 is too large, a mov immediate 11355 // instruction will needed. So, unfold back to the original pattern if: 11356 // - if c1 and c2 are small enough that they don't require mov imms. 11357 // - the user(s) of the node can perform an shl 11358 11359 // No shifted operands for 16-bit instructions. 11360 if (ST->isThumb() && ST->isThumb1Only()) 11361 return SDValue(); 11362 11363 // Check that all the users could perform the shl themselves. 11364 for (auto U : N->uses()) { 11365 switch(U->getOpcode()) { 11366 default: 11367 return SDValue(); 11368 case ISD::SUB: 11369 case ISD::ADD: 11370 case ISD::AND: 11371 case ISD::OR: 11372 case ISD::XOR: 11373 case ISD::SETCC: 11374 case ARMISD::CMP: 11375 // Check that the user isn't already using a constant because there 11376 // aren't any instructions that support an immediate operand and a 11377 // shifted operand. 11378 if (isa<ConstantSDNode>(U->getOperand(0)) || 11379 isa<ConstantSDNode>(U->getOperand(1))) 11380 return SDValue(); 11381 11382 // Check that it's not already using a shift. 11383 if (U->getOperand(0).getOpcode() == ISD::SHL || 11384 U->getOperand(1).getOpcode() == ISD::SHL) 11385 return SDValue(); 11386 break; 11387 } 11388 } 11389 11390 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 11391 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 11392 return SDValue(); 11393 11394 if (N->getOperand(0).getOpcode() != ISD::SHL) 11395 return SDValue(); 11396 11397 SDValue SHL = N->getOperand(0); 11398 11399 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11400 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 11401 if (!C1ShlC2 || !C2) 11402 return SDValue(); 11403 11404 APInt C2Int = C2->getAPIntValue(); 11405 APInt C1Int = C1ShlC2->getAPIntValue(); 11406 11407 // Check that performing a lshr will not lose any information. 11408 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 11409 C2Int.getBitWidth() - C2->getZExtValue()); 11410 if ((C1Int & Mask) != C1Int) 11411 return SDValue(); 11412 11413 // Shift the first constant. 11414 C1Int.lshrInPlace(C2Int); 11415 11416 // The immediates are encoded as an 8-bit value that can be rotated. 11417 auto LargeImm = [](const APInt &Imm) { 11418 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 11419 return Imm.getBitWidth() - Zeros > 8; 11420 }; 11421 11422 if (LargeImm(C1Int) || LargeImm(C2Int)) 11423 return SDValue(); 11424 11425 SelectionDAG &DAG = DCI.DAG; 11426 SDLoc dl(N); 11427 SDValue X = SHL.getOperand(0); 11428 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 11429 DAG.getConstant(C1Int, dl, MVT::i32)); 11430 // Shift left to compensate for the lshr of C1Int. 11431 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 11432 11433 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 11434 SHL.dump(); N->dump()); 11435 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 11436 return Res; 11437 } 11438 11439 11440 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 11441 /// 11442 static SDValue PerformADDCombine(SDNode *N, 11443 TargetLowering::DAGCombinerInfo &DCI, 11444 const ARMSubtarget *Subtarget) { 11445 SDValue N0 = N->getOperand(0); 11446 SDValue N1 = N->getOperand(1); 11447 11448 // Only works one way, because it needs an immediate operand. 11449 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11450 return Result; 11451 11452 // First try with the default operand order. 11453 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 11454 return Result; 11455 11456 // If that didn't work, try again with the operands commuted. 11457 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 11458 } 11459 11460 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 11461 /// 11462 static SDValue PerformSUBCombine(SDNode *N, 11463 TargetLowering::DAGCombinerInfo &DCI) { 11464 SDValue N0 = N->getOperand(0); 11465 SDValue N1 = N->getOperand(1); 11466 11467 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11468 if (N1.getNode()->hasOneUse()) 11469 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 11470 return Result; 11471 11472 return SDValue(); 11473 } 11474 11475 /// PerformVMULCombine 11476 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 11477 /// special multiplier accumulator forwarding. 11478 /// vmul d3, d0, d2 11479 /// vmla d3, d1, d2 11480 /// is faster than 11481 /// vadd d3, d0, d1 11482 /// vmul d3, d3, d2 11483 // However, for (A + B) * (A + B), 11484 // vadd d2, d0, d1 11485 // vmul d3, d0, d2 11486 // vmla d3, d1, d2 11487 // is slower than 11488 // vadd d2, d0, d1 11489 // vmul d3, d2, d2 11490 static SDValue PerformVMULCombine(SDNode *N, 11491 TargetLowering::DAGCombinerInfo &DCI, 11492 const ARMSubtarget *Subtarget) { 11493 if (!Subtarget->hasVMLxForwarding()) 11494 return SDValue(); 11495 11496 SelectionDAG &DAG = DCI.DAG; 11497 SDValue N0 = N->getOperand(0); 11498 SDValue N1 = N->getOperand(1); 11499 unsigned Opcode = N0.getOpcode(); 11500 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11501 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 11502 Opcode = N1.getOpcode(); 11503 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11504 Opcode != ISD::FADD && Opcode != ISD::FSUB) 11505 return SDValue(); 11506 std::swap(N0, N1); 11507 } 11508 11509 if (N0 == N1) 11510 return SDValue(); 11511 11512 EVT VT = N->getValueType(0); 11513 SDLoc DL(N); 11514 SDValue N00 = N0->getOperand(0); 11515 SDValue N01 = N0->getOperand(1); 11516 return DAG.getNode(Opcode, DL, VT, 11517 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 11518 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 11519 } 11520 11521 static SDValue PerformMULCombine(SDNode *N, 11522 TargetLowering::DAGCombinerInfo &DCI, 11523 const ARMSubtarget *Subtarget) { 11524 SelectionDAG &DAG = DCI.DAG; 11525 11526 if (Subtarget->isThumb1Only()) 11527 return SDValue(); 11528 11529 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11530 return SDValue(); 11531 11532 EVT VT = N->getValueType(0); 11533 if (VT.is64BitVector() || VT.is128BitVector()) 11534 return PerformVMULCombine(N, DCI, Subtarget); 11535 if (VT != MVT::i32) 11536 return SDValue(); 11537 11538 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11539 if (!C) 11540 return SDValue(); 11541 11542 int64_t MulAmt = C->getSExtValue(); 11543 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 11544 11545 ShiftAmt = ShiftAmt & (32 - 1); 11546 SDValue V = N->getOperand(0); 11547 SDLoc DL(N); 11548 11549 SDValue Res; 11550 MulAmt >>= ShiftAmt; 11551 11552 if (MulAmt >= 0) { 11553 if (isPowerOf2_32(MulAmt - 1)) { 11554 // (mul x, 2^N + 1) => (add (shl x, N), x) 11555 Res = DAG.getNode(ISD::ADD, DL, VT, 11556 V, 11557 DAG.getNode(ISD::SHL, DL, VT, 11558 V, 11559 DAG.getConstant(Log2_32(MulAmt - 1), DL, 11560 MVT::i32))); 11561 } else if (isPowerOf2_32(MulAmt + 1)) { 11562 // (mul x, 2^N - 1) => (sub (shl x, N), x) 11563 Res = DAG.getNode(ISD::SUB, DL, VT, 11564 DAG.getNode(ISD::SHL, DL, VT, 11565 V, 11566 DAG.getConstant(Log2_32(MulAmt + 1), DL, 11567 MVT::i32)), 11568 V); 11569 } else 11570 return SDValue(); 11571 } else { 11572 uint64_t MulAmtAbs = -MulAmt; 11573 if (isPowerOf2_32(MulAmtAbs + 1)) { 11574 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 11575 Res = DAG.getNode(ISD::SUB, DL, VT, 11576 V, 11577 DAG.getNode(ISD::SHL, DL, VT, 11578 V, 11579 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 11580 MVT::i32))); 11581 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 11582 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 11583 Res = DAG.getNode(ISD::ADD, DL, VT, 11584 V, 11585 DAG.getNode(ISD::SHL, DL, VT, 11586 V, 11587 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 11588 MVT::i32))); 11589 Res = DAG.getNode(ISD::SUB, DL, VT, 11590 DAG.getConstant(0, DL, MVT::i32), Res); 11591 } else 11592 return SDValue(); 11593 } 11594 11595 if (ShiftAmt != 0) 11596 Res = DAG.getNode(ISD::SHL, DL, VT, 11597 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 11598 11599 // Do not add new nodes to DAG combiner worklist. 11600 DCI.CombineTo(N, Res, false); 11601 return SDValue(); 11602 } 11603 11604 static SDValue CombineANDShift(SDNode *N, 11605 TargetLowering::DAGCombinerInfo &DCI, 11606 const ARMSubtarget *Subtarget) { 11607 // Allow DAGCombine to pattern-match before we touch the canonical form. 11608 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11609 return SDValue(); 11610 11611 if (N->getValueType(0) != MVT::i32) 11612 return SDValue(); 11613 11614 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11615 if (!N1C) 11616 return SDValue(); 11617 11618 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 11619 // Don't transform uxtb/uxth. 11620 if (C1 == 255 || C1 == 65535) 11621 return SDValue(); 11622 11623 SDNode *N0 = N->getOperand(0).getNode(); 11624 if (!N0->hasOneUse()) 11625 return SDValue(); 11626 11627 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 11628 return SDValue(); 11629 11630 bool LeftShift = N0->getOpcode() == ISD::SHL; 11631 11632 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 11633 if (!N01C) 11634 return SDValue(); 11635 11636 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 11637 if (!C2 || C2 >= 32) 11638 return SDValue(); 11639 11640 // Clear irrelevant bits in the mask. 11641 if (LeftShift) 11642 C1 &= (-1U << C2); 11643 else 11644 C1 &= (-1U >> C2); 11645 11646 SelectionDAG &DAG = DCI.DAG; 11647 SDLoc DL(N); 11648 11649 // We have a pattern of the form "(and (shl x, c2) c1)" or 11650 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 11651 // transform to a pair of shifts, to save materializing c1. 11652 11653 // First pattern: right shift, then mask off leading bits. 11654 // FIXME: Use demanded bits? 11655 if (!LeftShift && isMask_32(C1)) { 11656 uint32_t C3 = countLeadingZeros(C1); 11657 if (C2 < C3) { 11658 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11659 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11660 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11661 DAG.getConstant(C3, DL, MVT::i32)); 11662 } 11663 } 11664 11665 // First pattern, reversed: left shift, then mask off trailing bits. 11666 if (LeftShift && isMask_32(~C1)) { 11667 uint32_t C3 = countTrailingZeros(C1); 11668 if (C2 < C3) { 11669 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11670 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11671 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11672 DAG.getConstant(C3, DL, MVT::i32)); 11673 } 11674 } 11675 11676 // Second pattern: left shift, then mask off leading bits. 11677 // FIXME: Use demanded bits? 11678 if (LeftShift && isShiftedMask_32(C1)) { 11679 uint32_t Trailing = countTrailingZeros(C1); 11680 uint32_t C3 = countLeadingZeros(C1); 11681 if (Trailing == C2 && C2 + C3 < 32) { 11682 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11683 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11684 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11685 DAG.getConstant(C3, DL, MVT::i32)); 11686 } 11687 } 11688 11689 // Second pattern, reversed: right shift, then mask off trailing bits. 11690 // FIXME: Handle other patterns of known/demanded bits. 11691 if (!LeftShift && isShiftedMask_32(C1)) { 11692 uint32_t Leading = countLeadingZeros(C1); 11693 uint32_t C3 = countTrailingZeros(C1); 11694 if (Leading == C2 && C2 + C3 < 32) { 11695 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11696 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11697 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11698 DAG.getConstant(C3, DL, MVT::i32)); 11699 } 11700 } 11701 11702 // FIXME: Transform "(and (shl x, c2) c1)" -> 11703 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 11704 // c1. 11705 return SDValue(); 11706 } 11707 11708 static SDValue PerformANDCombine(SDNode *N, 11709 TargetLowering::DAGCombinerInfo &DCI, 11710 const ARMSubtarget *Subtarget) { 11711 // Attempt to use immediate-form VBIC 11712 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11713 SDLoc dl(N); 11714 EVT VT = N->getValueType(0); 11715 SelectionDAG &DAG = DCI.DAG; 11716 11717 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11718 return SDValue(); 11719 11720 APInt SplatBits, SplatUndef; 11721 unsigned SplatBitSize; 11722 bool HasAnyUndefs; 11723 if (BVN && Subtarget->hasNEON() && 11724 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11725 if (SplatBitSize <= 64) { 11726 EVT VbicVT; 11727 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 11728 SplatUndef.getZExtValue(), SplatBitSize, 11729 DAG, dl, VbicVT, VT.is128BitVector(), 11730 OtherModImm); 11731 if (Val.getNode()) { 11732 SDValue Input = 11733 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 11734 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 11735 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 11736 } 11737 } 11738 } 11739 11740 if (!Subtarget->isThumb1Only()) { 11741 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 11742 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 11743 return Result; 11744 11745 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11746 return Result; 11747 } 11748 11749 if (Subtarget->isThumb1Only()) 11750 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 11751 return Result; 11752 11753 return SDValue(); 11754 } 11755 11756 // Try combining OR nodes to SMULWB, SMULWT. 11757 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 11758 TargetLowering::DAGCombinerInfo &DCI, 11759 const ARMSubtarget *Subtarget) { 11760 if (!Subtarget->hasV6Ops() || 11761 (Subtarget->isThumb() && 11762 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 11763 return SDValue(); 11764 11765 SDValue SRL = OR->getOperand(0); 11766 SDValue SHL = OR->getOperand(1); 11767 11768 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 11769 SRL = OR->getOperand(1); 11770 SHL = OR->getOperand(0); 11771 } 11772 if (!isSRL16(SRL) || !isSHL16(SHL)) 11773 return SDValue(); 11774 11775 // The first operands to the shifts need to be the two results from the 11776 // same smul_lohi node. 11777 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 11778 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 11779 return SDValue(); 11780 11781 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 11782 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 11783 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 11784 return SDValue(); 11785 11786 // Now we have: 11787 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 11788 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 11789 // For SMUWB the 16-bit value will signed extended somehow. 11790 // For SMULWT only the SRA is required. 11791 // Check both sides of SMUL_LOHI 11792 SDValue OpS16 = SMULLOHI->getOperand(0); 11793 SDValue OpS32 = SMULLOHI->getOperand(1); 11794 11795 SelectionDAG &DAG = DCI.DAG; 11796 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 11797 OpS16 = OpS32; 11798 OpS32 = SMULLOHI->getOperand(0); 11799 } 11800 11801 SDLoc dl(OR); 11802 unsigned Opcode = 0; 11803 if (isS16(OpS16, DAG)) 11804 Opcode = ARMISD::SMULWB; 11805 else if (isSRA16(OpS16)) { 11806 Opcode = ARMISD::SMULWT; 11807 OpS16 = OpS16->getOperand(0); 11808 } 11809 else 11810 return SDValue(); 11811 11812 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 11813 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 11814 return SDValue(OR, 0); 11815 } 11816 11817 static SDValue PerformORCombineToBFI(SDNode *N, 11818 TargetLowering::DAGCombinerInfo &DCI, 11819 const ARMSubtarget *Subtarget) { 11820 // BFI is only available on V6T2+ 11821 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 11822 return SDValue(); 11823 11824 EVT VT = N->getValueType(0); 11825 SDValue N0 = N->getOperand(0); 11826 SDValue N1 = N->getOperand(1); 11827 SelectionDAG &DAG = DCI.DAG; 11828 SDLoc DL(N); 11829 // 1) or (and A, mask), val => ARMbfi A, val, mask 11830 // iff (val & mask) == val 11831 // 11832 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11833 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 11834 // && mask == ~mask2 11835 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 11836 // && ~mask == mask2 11837 // (i.e., copy a bitfield value into another bitfield of the same width) 11838 11839 if (VT != MVT::i32) 11840 return SDValue(); 11841 11842 SDValue N00 = N0.getOperand(0); 11843 11844 // The value and the mask need to be constants so we can verify this is 11845 // actually a bitfield set. If the mask is 0xffff, we can do better 11846 // via a movt instruction, so don't use BFI in that case. 11847 SDValue MaskOp = N0.getOperand(1); 11848 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 11849 if (!MaskC) 11850 return SDValue(); 11851 unsigned Mask = MaskC->getZExtValue(); 11852 if (Mask == 0xffff) 11853 return SDValue(); 11854 SDValue Res; 11855 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 11856 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11857 if (N1C) { 11858 unsigned Val = N1C->getZExtValue(); 11859 if ((Val & ~Mask) != Val) 11860 return SDValue(); 11861 11862 if (ARM::isBitFieldInvertedMask(Mask)) { 11863 Val >>= countTrailingZeros(~Mask); 11864 11865 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 11866 DAG.getConstant(Val, DL, MVT::i32), 11867 DAG.getConstant(Mask, DL, MVT::i32)); 11868 11869 DCI.CombineTo(N, Res, false); 11870 // Return value from the original node to inform the combiner than N is 11871 // now dead. 11872 return SDValue(N, 0); 11873 } 11874 } else if (N1.getOpcode() == ISD::AND) { 11875 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11876 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11877 if (!N11C) 11878 return SDValue(); 11879 unsigned Mask2 = N11C->getZExtValue(); 11880 11881 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 11882 // as is to match. 11883 if (ARM::isBitFieldInvertedMask(Mask) && 11884 (Mask == ~Mask2)) { 11885 // The pack halfword instruction works better for masks that fit it, 11886 // so use that when it's available. 11887 if (Subtarget->hasDSP() && 11888 (Mask == 0xffff || Mask == 0xffff0000)) 11889 return SDValue(); 11890 // 2a 11891 unsigned amt = countTrailingZeros(Mask2); 11892 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 11893 DAG.getConstant(amt, DL, MVT::i32)); 11894 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 11895 DAG.getConstant(Mask, DL, MVT::i32)); 11896 DCI.CombineTo(N, Res, false); 11897 // Return value from the original node to inform the combiner than N is 11898 // now dead. 11899 return SDValue(N, 0); 11900 } else if (ARM::isBitFieldInvertedMask(~Mask) && 11901 (~Mask == Mask2)) { 11902 // The pack halfword instruction works better for masks that fit it, 11903 // so use that when it's available. 11904 if (Subtarget->hasDSP() && 11905 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 11906 return SDValue(); 11907 // 2b 11908 unsigned lsb = countTrailingZeros(Mask); 11909 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 11910 DAG.getConstant(lsb, DL, MVT::i32)); 11911 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 11912 DAG.getConstant(Mask2, DL, MVT::i32)); 11913 DCI.CombineTo(N, Res, false); 11914 // Return value from the original node to inform the combiner than N is 11915 // now dead. 11916 return SDValue(N, 0); 11917 } 11918 } 11919 11920 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 11921 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 11922 ARM::isBitFieldInvertedMask(~Mask)) { 11923 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 11924 // where lsb(mask) == #shamt and masked bits of B are known zero. 11925 SDValue ShAmt = N00.getOperand(1); 11926 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 11927 unsigned LSB = countTrailingZeros(Mask); 11928 if (ShAmtC != LSB) 11929 return SDValue(); 11930 11931 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 11932 DAG.getConstant(~Mask, DL, MVT::i32)); 11933 11934 DCI.CombineTo(N, Res, false); 11935 // Return value from the original node to inform the combiner than N is 11936 // now dead. 11937 return SDValue(N, 0); 11938 } 11939 11940 return SDValue(); 11941 } 11942 11943 static bool isValidMVECond(unsigned CC, bool IsFloat) { 11944 switch (CC) { 11945 case ARMCC::EQ: 11946 case ARMCC::NE: 11947 case ARMCC::LE: 11948 case ARMCC::GT: 11949 case ARMCC::GE: 11950 case ARMCC::LT: 11951 return true; 11952 case ARMCC::HS: 11953 case ARMCC::HI: 11954 return !IsFloat; 11955 default: 11956 return false; 11957 }; 11958 } 11959 11960 static SDValue PerformORCombine_i1(SDNode *N, 11961 TargetLowering::DAGCombinerInfo &DCI, 11962 const ARMSubtarget *Subtarget) { 11963 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 11964 // together with predicates 11965 EVT VT = N->getValueType(0); 11966 SDValue N0 = N->getOperand(0); 11967 SDValue N1 = N->getOperand(1); 11968 11969 ARMCC::CondCodes CondCode0 = ARMCC::AL; 11970 ARMCC::CondCodes CondCode1 = ARMCC::AL; 11971 if (N0->getOpcode() == ARMISD::VCMP) 11972 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2)) 11973 ->getZExtValue(); 11974 else if (N0->getOpcode() == ARMISD::VCMPZ) 11975 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1)) 11976 ->getZExtValue(); 11977 if (N1->getOpcode() == ARMISD::VCMP) 11978 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2)) 11979 ->getZExtValue(); 11980 else if (N1->getOpcode() == ARMISD::VCMPZ) 11981 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1)) 11982 ->getZExtValue(); 11983 11984 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL) 11985 return SDValue(); 11986 11987 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0); 11988 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1); 11989 11990 if (!isValidMVECond(Opposite0, 11991 N0->getOperand(0)->getValueType(0).isFloatingPoint()) || 11992 !isValidMVECond(Opposite1, 11993 N1->getOperand(0)->getValueType(0).isFloatingPoint())) 11994 return SDValue(); 11995 11996 SmallVector<SDValue, 4> Ops0; 11997 Ops0.push_back(N0->getOperand(0)); 11998 if (N0->getOpcode() == ARMISD::VCMP) 11999 Ops0.push_back(N0->getOperand(1)); 12000 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32)); 12001 SmallVector<SDValue, 4> Ops1; 12002 Ops1.push_back(N1->getOperand(0)); 12003 if (N1->getOpcode() == ARMISD::VCMP) 12004 Ops1.push_back(N1->getOperand(1)); 12005 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32)); 12006 12007 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0); 12008 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1); 12009 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1); 12010 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And, 12011 DCI.DAG.getAllOnesConstant(SDLoc(N), VT)); 12012 } 12013 12014 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 12015 static SDValue PerformORCombine(SDNode *N, 12016 TargetLowering::DAGCombinerInfo &DCI, 12017 const ARMSubtarget *Subtarget) { 12018 // Attempt to use immediate-form VORR 12019 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 12020 SDLoc dl(N); 12021 EVT VT = N->getValueType(0); 12022 SelectionDAG &DAG = DCI.DAG; 12023 12024 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12025 return SDValue(); 12026 12027 APInt SplatBits, SplatUndef; 12028 unsigned SplatBitSize; 12029 bool HasAnyUndefs; 12030 if (BVN && Subtarget->hasNEON() && 12031 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 12032 if (SplatBitSize <= 64) { 12033 EVT VorrVT; 12034 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 12035 SplatUndef.getZExtValue(), SplatBitSize, 12036 DAG, dl, VorrVT, VT.is128BitVector(), 12037 OtherModImm); 12038 if (Val.getNode()) { 12039 SDValue Input = 12040 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 12041 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 12042 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 12043 } 12044 } 12045 } 12046 12047 if (!Subtarget->isThumb1Only()) { 12048 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 12049 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12050 return Result; 12051 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 12052 return Result; 12053 } 12054 12055 SDValue N0 = N->getOperand(0); 12056 SDValue N1 = N->getOperand(1); 12057 12058 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 12059 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 12060 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 12061 12062 // The code below optimizes (or (and X, Y), Z). 12063 // The AND operand needs to have a single user to make these optimizations 12064 // profitable. 12065 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 12066 return SDValue(); 12067 12068 APInt SplatUndef; 12069 unsigned SplatBitSize; 12070 bool HasAnyUndefs; 12071 12072 APInt SplatBits0, SplatBits1; 12073 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 12074 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 12075 // Ensure that the second operand of both ands are constants 12076 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 12077 HasAnyUndefs) && !HasAnyUndefs) { 12078 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 12079 HasAnyUndefs) && !HasAnyUndefs) { 12080 // Ensure that the bit width of the constants are the same and that 12081 // the splat arguments are logical inverses as per the pattern we 12082 // are trying to simplify. 12083 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 12084 SplatBits0 == ~SplatBits1) { 12085 // Canonicalize the vector type to make instruction selection 12086 // simpler. 12087 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 12088 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 12089 N0->getOperand(1), 12090 N0->getOperand(0), 12091 N1->getOperand(0)); 12092 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 12093 } 12094 } 12095 } 12096 } 12097 12098 if (Subtarget->hasMVEIntegerOps() && 12099 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 12100 return PerformORCombine_i1(N, DCI, Subtarget); 12101 12102 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 12103 // reasonable. 12104 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 12105 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 12106 return Res; 12107 } 12108 12109 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12110 return Result; 12111 12112 return SDValue(); 12113 } 12114 12115 static SDValue PerformXORCombine(SDNode *N, 12116 TargetLowering::DAGCombinerInfo &DCI, 12117 const ARMSubtarget *Subtarget) { 12118 EVT VT = N->getValueType(0); 12119 SelectionDAG &DAG = DCI.DAG; 12120 12121 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12122 return SDValue(); 12123 12124 if (!Subtarget->isThumb1Only()) { 12125 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 12126 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12127 return Result; 12128 12129 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12130 return Result; 12131 } 12132 12133 return SDValue(); 12134 } 12135 12136 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 12137 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 12138 // their position in "to" (Rd). 12139 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 12140 assert(N->getOpcode() == ARMISD::BFI); 12141 12142 SDValue From = N->getOperand(1); 12143 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 12144 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 12145 12146 // If the Base came from a SHR #C, we can deduce that it is really testing bit 12147 // #C in the base of the SHR. 12148 if (From->getOpcode() == ISD::SRL && 12149 isa<ConstantSDNode>(From->getOperand(1))) { 12150 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 12151 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 12152 FromMask <<= Shift.getLimitedValue(31); 12153 From = From->getOperand(0); 12154 } 12155 12156 return From; 12157 } 12158 12159 // If A and B contain one contiguous set of bits, does A | B == A . B? 12160 // 12161 // Neither A nor B must be zero. 12162 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 12163 unsigned LastActiveBitInA = A.countTrailingZeros(); 12164 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 12165 return LastActiveBitInA - 1 == FirstActiveBitInB; 12166 } 12167 12168 static SDValue FindBFIToCombineWith(SDNode *N) { 12169 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 12170 // if one exists. 12171 APInt ToMask, FromMask; 12172 SDValue From = ParseBFI(N, ToMask, FromMask); 12173 SDValue To = N->getOperand(0); 12174 12175 // Now check for a compatible BFI to merge with. We can pass through BFIs that 12176 // aren't compatible, but not if they set the same bit in their destination as 12177 // we do (or that of any BFI we're going to combine with). 12178 SDValue V = To; 12179 APInt CombinedToMask = ToMask; 12180 while (V.getOpcode() == ARMISD::BFI) { 12181 APInt NewToMask, NewFromMask; 12182 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 12183 if (NewFrom != From) { 12184 // This BFI has a different base. Keep going. 12185 CombinedToMask |= NewToMask; 12186 V = V.getOperand(0); 12187 continue; 12188 } 12189 12190 // Do the written bits conflict with any we've seen so far? 12191 if ((NewToMask & CombinedToMask).getBoolValue()) 12192 // Conflicting bits - bail out because going further is unsafe. 12193 return SDValue(); 12194 12195 // Are the new bits contiguous when combined with the old bits? 12196 if (BitsProperlyConcatenate(ToMask, NewToMask) && 12197 BitsProperlyConcatenate(FromMask, NewFromMask)) 12198 return V; 12199 if (BitsProperlyConcatenate(NewToMask, ToMask) && 12200 BitsProperlyConcatenate(NewFromMask, FromMask)) 12201 return V; 12202 12203 // We've seen a write to some bits, so track it. 12204 CombinedToMask |= NewToMask; 12205 // Keep going... 12206 V = V.getOperand(0); 12207 } 12208 12209 return SDValue(); 12210 } 12211 12212 static SDValue PerformBFICombine(SDNode *N, 12213 TargetLowering::DAGCombinerInfo &DCI) { 12214 SDValue N1 = N->getOperand(1); 12215 if (N1.getOpcode() == ISD::AND) { 12216 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 12217 // the bits being cleared by the AND are not demanded by the BFI. 12218 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12219 if (!N11C) 12220 return SDValue(); 12221 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12222 unsigned LSB = countTrailingZeros(~InvMask); 12223 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 12224 assert(Width < 12225 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 12226 "undefined behavior"); 12227 unsigned Mask = (1u << Width) - 1; 12228 unsigned Mask2 = N11C->getZExtValue(); 12229 if ((Mask & (~Mask2)) == 0) 12230 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 12231 N->getOperand(0), N1.getOperand(0), 12232 N->getOperand(2)); 12233 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 12234 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 12235 // Keep track of any consecutive bits set that all come from the same base 12236 // value. We can combine these together into a single BFI. 12237 SDValue CombineBFI = FindBFIToCombineWith(N); 12238 if (CombineBFI == SDValue()) 12239 return SDValue(); 12240 12241 // We've found a BFI. 12242 APInt ToMask1, FromMask1; 12243 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 12244 12245 APInt ToMask2, FromMask2; 12246 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 12247 assert(From1 == From2); 12248 (void)From2; 12249 12250 // First, unlink CombineBFI. 12251 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 12252 // Then create a new BFI, combining the two together. 12253 APInt NewFromMask = FromMask1 | FromMask2; 12254 APInt NewToMask = ToMask1 | ToMask2; 12255 12256 EVT VT = N->getValueType(0); 12257 SDLoc dl(N); 12258 12259 if (NewFromMask[0] == 0) 12260 From1 = DCI.DAG.getNode( 12261 ISD::SRL, dl, VT, From1, 12262 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 12263 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 12264 DCI.DAG.getConstant(~NewToMask, dl, VT)); 12265 } 12266 return SDValue(); 12267 } 12268 12269 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 12270 /// ARMISD::VMOVRRD. 12271 static SDValue PerformVMOVRRDCombine(SDNode *N, 12272 TargetLowering::DAGCombinerInfo &DCI, 12273 const ARMSubtarget *Subtarget) { 12274 // vmovrrd(vmovdrr x, y) -> x,y 12275 SDValue InDouble = N->getOperand(0); 12276 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 12277 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 12278 12279 // vmovrrd(load f64) -> (load i32), (load i32) 12280 SDNode *InNode = InDouble.getNode(); 12281 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 12282 InNode->getValueType(0) == MVT::f64 && 12283 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 12284 !cast<LoadSDNode>(InNode)->isVolatile()) { 12285 // TODO: Should this be done for non-FrameIndex operands? 12286 LoadSDNode *LD = cast<LoadSDNode>(InNode); 12287 12288 SelectionDAG &DAG = DCI.DAG; 12289 SDLoc DL(LD); 12290 SDValue BasePtr = LD->getBasePtr(); 12291 SDValue NewLD1 = 12292 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 12293 LD->getAlignment(), LD->getMemOperand()->getFlags()); 12294 12295 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12296 DAG.getConstant(4, DL, MVT::i32)); 12297 12298 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 12299 LD->getPointerInfo().getWithOffset(4), 12300 std::min(4U, LD->getAlignment()), 12301 LD->getMemOperand()->getFlags()); 12302 12303 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 12304 if (DCI.DAG.getDataLayout().isBigEndian()) 12305 std::swap (NewLD1, NewLD2); 12306 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 12307 return Result; 12308 } 12309 12310 return SDValue(); 12311 } 12312 12313 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 12314 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 12315 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 12316 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 12317 SDValue Op0 = N->getOperand(0); 12318 SDValue Op1 = N->getOperand(1); 12319 if (Op0.getOpcode() == ISD::BITCAST) 12320 Op0 = Op0.getOperand(0); 12321 if (Op1.getOpcode() == ISD::BITCAST) 12322 Op1 = Op1.getOperand(0); 12323 if (Op0.getOpcode() == ARMISD::VMOVRRD && 12324 Op0.getNode() == Op1.getNode() && 12325 Op0.getResNo() == 0 && Op1.getResNo() == 1) 12326 return DAG.getNode(ISD::BITCAST, SDLoc(N), 12327 N->getValueType(0), Op0.getOperand(0)); 12328 return SDValue(); 12329 } 12330 12331 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 12332 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 12333 /// i64 vector to have f64 elements, since the value can then be loaded 12334 /// directly into a VFP register. 12335 static bool hasNormalLoadOperand(SDNode *N) { 12336 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 12337 for (unsigned i = 0; i < NumElts; ++i) { 12338 SDNode *Elt = N->getOperand(i).getNode(); 12339 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 12340 return true; 12341 } 12342 return false; 12343 } 12344 12345 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 12346 /// ISD::BUILD_VECTOR. 12347 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 12348 TargetLowering::DAGCombinerInfo &DCI, 12349 const ARMSubtarget *Subtarget) { 12350 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 12351 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 12352 // into a pair of GPRs, which is fine when the value is used as a scalar, 12353 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 12354 SelectionDAG &DAG = DCI.DAG; 12355 if (N->getNumOperands() == 2) 12356 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 12357 return RV; 12358 12359 // Load i64 elements as f64 values so that type legalization does not split 12360 // them up into i32 values. 12361 EVT VT = N->getValueType(0); 12362 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 12363 return SDValue(); 12364 SDLoc dl(N); 12365 SmallVector<SDValue, 8> Ops; 12366 unsigned NumElts = VT.getVectorNumElements(); 12367 for (unsigned i = 0; i < NumElts; ++i) { 12368 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 12369 Ops.push_back(V); 12370 // Make the DAGCombiner fold the bitcast. 12371 DCI.AddToWorklist(V.getNode()); 12372 } 12373 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 12374 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 12375 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12376 } 12377 12378 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 12379 static SDValue 12380 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12381 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 12382 // At that time, we may have inserted bitcasts from integer to float. 12383 // If these bitcasts have survived DAGCombine, change the lowering of this 12384 // BUILD_VECTOR in something more vector friendly, i.e., that does not 12385 // force to use floating point types. 12386 12387 // Make sure we can change the type of the vector. 12388 // This is possible iff: 12389 // 1. The vector is only used in a bitcast to a integer type. I.e., 12390 // 1.1. Vector is used only once. 12391 // 1.2. Use is a bit convert to an integer type. 12392 // 2. The size of its operands are 32-bits (64-bits are not legal). 12393 EVT VT = N->getValueType(0); 12394 EVT EltVT = VT.getVectorElementType(); 12395 12396 // Check 1.1. and 2. 12397 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 12398 return SDValue(); 12399 12400 // By construction, the input type must be float. 12401 assert(EltVT == MVT::f32 && "Unexpected type!"); 12402 12403 // Check 1.2. 12404 SDNode *Use = *N->use_begin(); 12405 if (Use->getOpcode() != ISD::BITCAST || 12406 Use->getValueType(0).isFloatingPoint()) 12407 return SDValue(); 12408 12409 // Check profitability. 12410 // Model is, if more than half of the relevant operands are bitcast from 12411 // i32, turn the build_vector into a sequence of insert_vector_elt. 12412 // Relevant operands are everything that is not statically 12413 // (i.e., at compile time) bitcasted. 12414 unsigned NumOfBitCastedElts = 0; 12415 unsigned NumElts = VT.getVectorNumElements(); 12416 unsigned NumOfRelevantElts = NumElts; 12417 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 12418 SDValue Elt = N->getOperand(Idx); 12419 if (Elt->getOpcode() == ISD::BITCAST) { 12420 // Assume only bit cast to i32 will go away. 12421 if (Elt->getOperand(0).getValueType() == MVT::i32) 12422 ++NumOfBitCastedElts; 12423 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 12424 // Constants are statically casted, thus do not count them as 12425 // relevant operands. 12426 --NumOfRelevantElts; 12427 } 12428 12429 // Check if more than half of the elements require a non-free bitcast. 12430 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 12431 return SDValue(); 12432 12433 SelectionDAG &DAG = DCI.DAG; 12434 // Create the new vector type. 12435 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 12436 // Check if the type is legal. 12437 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12438 if (!TLI.isTypeLegal(VecVT)) 12439 return SDValue(); 12440 12441 // Combine: 12442 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 12443 // => BITCAST INSERT_VECTOR_ELT 12444 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 12445 // (BITCAST EN), N. 12446 SDValue Vec = DAG.getUNDEF(VecVT); 12447 SDLoc dl(N); 12448 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 12449 SDValue V = N->getOperand(Idx); 12450 if (V.isUndef()) 12451 continue; 12452 if (V.getOpcode() == ISD::BITCAST && 12453 V->getOperand(0).getValueType() == MVT::i32) 12454 // Fold obvious case. 12455 V = V.getOperand(0); 12456 else { 12457 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 12458 // Make the DAGCombiner fold the bitcasts. 12459 DCI.AddToWorklist(V.getNode()); 12460 } 12461 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 12462 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 12463 } 12464 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 12465 // Make the DAGCombiner fold the bitcasts. 12466 DCI.AddToWorklist(Vec.getNode()); 12467 return Vec; 12468 } 12469 12470 /// PerformInsertEltCombine - Target-specific dag combine xforms for 12471 /// ISD::INSERT_VECTOR_ELT. 12472 static SDValue PerformInsertEltCombine(SDNode *N, 12473 TargetLowering::DAGCombinerInfo &DCI) { 12474 // Bitcast an i64 load inserted into a vector to f64. 12475 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12476 EVT VT = N->getValueType(0); 12477 SDNode *Elt = N->getOperand(1).getNode(); 12478 if (VT.getVectorElementType() != MVT::i64 || 12479 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 12480 return SDValue(); 12481 12482 SelectionDAG &DAG = DCI.DAG; 12483 SDLoc dl(N); 12484 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12485 VT.getVectorNumElements()); 12486 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 12487 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 12488 // Make the DAGCombiner fold the bitcasts. 12489 DCI.AddToWorklist(Vec.getNode()); 12490 DCI.AddToWorklist(V.getNode()); 12491 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 12492 Vec, V, N->getOperand(2)); 12493 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 12494 } 12495 12496 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 12497 /// ISD::VECTOR_SHUFFLE. 12498 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 12499 // The LLVM shufflevector instruction does not require the shuffle mask 12500 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 12501 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 12502 // operands do not match the mask length, they are extended by concatenating 12503 // them with undef vectors. That is probably the right thing for other 12504 // targets, but for NEON it is better to concatenate two double-register 12505 // size vector operands into a single quad-register size vector. Do that 12506 // transformation here: 12507 // shuffle(concat(v1, undef), concat(v2, undef)) -> 12508 // shuffle(concat(v1, v2), undef) 12509 SDValue Op0 = N->getOperand(0); 12510 SDValue Op1 = N->getOperand(1); 12511 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 12512 Op1.getOpcode() != ISD::CONCAT_VECTORS || 12513 Op0.getNumOperands() != 2 || 12514 Op1.getNumOperands() != 2) 12515 return SDValue(); 12516 SDValue Concat0Op1 = Op0.getOperand(1); 12517 SDValue Concat1Op1 = Op1.getOperand(1); 12518 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 12519 return SDValue(); 12520 // Skip the transformation if any of the types are illegal. 12521 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12522 EVT VT = N->getValueType(0); 12523 if (!TLI.isTypeLegal(VT) || 12524 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 12525 !TLI.isTypeLegal(Concat1Op1.getValueType())) 12526 return SDValue(); 12527 12528 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12529 Op0.getOperand(0), Op1.getOperand(0)); 12530 // Translate the shuffle mask. 12531 SmallVector<int, 16> NewMask; 12532 unsigned NumElts = VT.getVectorNumElements(); 12533 unsigned HalfElts = NumElts/2; 12534 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12535 for (unsigned n = 0; n < NumElts; ++n) { 12536 int MaskElt = SVN->getMaskElt(n); 12537 int NewElt = -1; 12538 if (MaskElt < (int)HalfElts) 12539 NewElt = MaskElt; 12540 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 12541 NewElt = HalfElts + MaskElt - NumElts; 12542 NewMask.push_back(NewElt); 12543 } 12544 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 12545 DAG.getUNDEF(VT), NewMask); 12546 } 12547 12548 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 12549 /// NEON load/store intrinsics, and generic vector load/stores, to merge 12550 /// base address updates. 12551 /// For generic load/stores, the memory type is assumed to be a vector. 12552 /// The caller is assumed to have checked legality. 12553 static SDValue CombineBaseUpdate(SDNode *N, 12554 TargetLowering::DAGCombinerInfo &DCI) { 12555 SelectionDAG &DAG = DCI.DAG; 12556 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 12557 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 12558 const bool isStore = N->getOpcode() == ISD::STORE; 12559 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 12560 SDValue Addr = N->getOperand(AddrOpIdx); 12561 MemSDNode *MemN = cast<MemSDNode>(N); 12562 SDLoc dl(N); 12563 12564 // Search for a use of the address operand that is an increment. 12565 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 12566 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 12567 SDNode *User = *UI; 12568 if (User->getOpcode() != ISD::ADD || 12569 UI.getUse().getResNo() != Addr.getResNo()) 12570 continue; 12571 12572 // Check that the add is independent of the load/store. Otherwise, folding 12573 // it would create a cycle. We can avoid searching through Addr as it's a 12574 // predecessor to both. 12575 SmallPtrSet<const SDNode *, 32> Visited; 12576 SmallVector<const SDNode *, 16> Worklist; 12577 Visited.insert(Addr.getNode()); 12578 Worklist.push_back(N); 12579 Worklist.push_back(User); 12580 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 12581 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 12582 continue; 12583 12584 // Find the new opcode for the updating load/store. 12585 bool isLoadOp = true; 12586 bool isLaneOp = false; 12587 unsigned NewOpc = 0; 12588 unsigned NumVecs = 0; 12589 if (isIntrinsic) { 12590 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 12591 switch (IntNo) { 12592 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 12593 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 12594 NumVecs = 1; break; 12595 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 12596 NumVecs = 2; break; 12597 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 12598 NumVecs = 3; break; 12599 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 12600 NumVecs = 4; break; 12601 case Intrinsic::arm_neon_vld2dup: 12602 case Intrinsic::arm_neon_vld3dup: 12603 case Intrinsic::arm_neon_vld4dup: 12604 // TODO: Support updating VLDxDUP nodes. For now, we just skip 12605 // combining base updates for such intrinsics. 12606 continue; 12607 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 12608 NumVecs = 2; isLaneOp = true; break; 12609 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 12610 NumVecs = 3; isLaneOp = true; break; 12611 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 12612 NumVecs = 4; isLaneOp = true; break; 12613 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 12614 NumVecs = 1; isLoadOp = false; break; 12615 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 12616 NumVecs = 2; isLoadOp = false; break; 12617 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 12618 NumVecs = 3; isLoadOp = false; break; 12619 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 12620 NumVecs = 4; isLoadOp = false; break; 12621 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 12622 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 12623 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 12624 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 12625 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 12626 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 12627 } 12628 } else { 12629 isLaneOp = true; 12630 switch (N->getOpcode()) { 12631 default: llvm_unreachable("unexpected opcode for Neon base update"); 12632 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 12633 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 12634 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 12635 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 12636 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 12637 NumVecs = 1; isLaneOp = false; break; 12638 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 12639 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 12640 } 12641 } 12642 12643 // Find the size of memory referenced by the load/store. 12644 EVT VecTy; 12645 if (isLoadOp) { 12646 VecTy = N->getValueType(0); 12647 } else if (isIntrinsic) { 12648 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 12649 } else { 12650 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 12651 VecTy = N->getOperand(1).getValueType(); 12652 } 12653 12654 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 12655 if (isLaneOp) 12656 NumBytes /= VecTy.getVectorNumElements(); 12657 12658 // If the increment is a constant, it must match the memory ref size. 12659 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 12660 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 12661 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 12662 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 12663 // separate instructions that make it harder to use a non-constant update. 12664 continue; 12665 } 12666 12667 // OK, we found an ADD we can fold into the base update. 12668 // Now, create a _UPD node, taking care of not breaking alignment. 12669 12670 EVT AlignedVecTy = VecTy; 12671 unsigned Alignment = MemN->getAlignment(); 12672 12673 // If this is a less-than-standard-aligned load/store, change the type to 12674 // match the standard alignment. 12675 // The alignment is overlooked when selecting _UPD variants; and it's 12676 // easier to introduce bitcasts here than fix that. 12677 // There are 3 ways to get to this base-update combine: 12678 // - intrinsics: they are assumed to be properly aligned (to the standard 12679 // alignment of the memory type), so we don't need to do anything. 12680 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 12681 // intrinsics, so, likewise, there's nothing to do. 12682 // - generic load/store instructions: the alignment is specified as an 12683 // explicit operand, rather than implicitly as the standard alignment 12684 // of the memory type (like the intrisics). We need to change the 12685 // memory type to match the explicit alignment. That way, we don't 12686 // generate non-standard-aligned ARMISD::VLDx nodes. 12687 if (isa<LSBaseSDNode>(N)) { 12688 if (Alignment == 0) 12689 Alignment = 1; 12690 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 12691 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 12692 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 12693 assert(!isLaneOp && "Unexpected generic load/store lane."); 12694 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 12695 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 12696 } 12697 // Don't set an explicit alignment on regular load/stores that we want 12698 // to transform to VLD/VST 1_UPD nodes. 12699 // This matches the behavior of regular load/stores, which only get an 12700 // explicit alignment if the MMO alignment is larger than the standard 12701 // alignment of the memory type. 12702 // Intrinsics, however, always get an explicit alignment, set to the 12703 // alignment of the MMO. 12704 Alignment = 1; 12705 } 12706 12707 // Create the new updating load/store node. 12708 // First, create an SDVTList for the new updating node's results. 12709 EVT Tys[6]; 12710 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 12711 unsigned n; 12712 for (n = 0; n < NumResultVecs; ++n) 12713 Tys[n] = AlignedVecTy; 12714 Tys[n++] = MVT::i32; 12715 Tys[n] = MVT::Other; 12716 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 12717 12718 // Then, gather the new node's operands. 12719 SmallVector<SDValue, 8> Ops; 12720 Ops.push_back(N->getOperand(0)); // incoming chain 12721 Ops.push_back(N->getOperand(AddrOpIdx)); 12722 Ops.push_back(Inc); 12723 12724 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 12725 // Try to match the intrinsic's signature 12726 Ops.push_back(StN->getValue()); 12727 } else { 12728 // Loads (and of course intrinsics) match the intrinsics' signature, 12729 // so just add all but the alignment operand. 12730 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 12731 Ops.push_back(N->getOperand(i)); 12732 } 12733 12734 // For all node types, the alignment operand is always the last one. 12735 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 12736 12737 // If this is a non-standard-aligned STORE, the penultimate operand is the 12738 // stored value. Bitcast it to the aligned type. 12739 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 12740 SDValue &StVal = Ops[Ops.size()-2]; 12741 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 12742 } 12743 12744 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 12745 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 12746 MemN->getMemOperand()); 12747 12748 // Update the uses. 12749 SmallVector<SDValue, 5> NewResults; 12750 for (unsigned i = 0; i < NumResultVecs; ++i) 12751 NewResults.push_back(SDValue(UpdN.getNode(), i)); 12752 12753 // If this is an non-standard-aligned LOAD, the first result is the loaded 12754 // value. Bitcast it to the expected result type. 12755 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 12756 SDValue &LdVal = NewResults[0]; 12757 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 12758 } 12759 12760 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 12761 DCI.CombineTo(N, NewResults); 12762 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 12763 12764 break; 12765 } 12766 return SDValue(); 12767 } 12768 12769 static SDValue PerformVLDCombine(SDNode *N, 12770 TargetLowering::DAGCombinerInfo &DCI) { 12771 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12772 return SDValue(); 12773 12774 return CombineBaseUpdate(N, DCI); 12775 } 12776 12777 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 12778 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 12779 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 12780 /// return true. 12781 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12782 SelectionDAG &DAG = DCI.DAG; 12783 EVT VT = N->getValueType(0); 12784 // vldN-dup instructions only support 64-bit vectors for N > 1. 12785 if (!VT.is64BitVector()) 12786 return false; 12787 12788 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 12789 SDNode *VLD = N->getOperand(0).getNode(); 12790 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 12791 return false; 12792 unsigned NumVecs = 0; 12793 unsigned NewOpc = 0; 12794 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 12795 if (IntNo == Intrinsic::arm_neon_vld2lane) { 12796 NumVecs = 2; 12797 NewOpc = ARMISD::VLD2DUP; 12798 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 12799 NumVecs = 3; 12800 NewOpc = ARMISD::VLD3DUP; 12801 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 12802 NumVecs = 4; 12803 NewOpc = ARMISD::VLD4DUP; 12804 } else { 12805 return false; 12806 } 12807 12808 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 12809 // numbers match the load. 12810 unsigned VLDLaneNo = 12811 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 12812 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12813 UI != UE; ++UI) { 12814 // Ignore uses of the chain result. 12815 if (UI.getUse().getResNo() == NumVecs) 12816 continue; 12817 SDNode *User = *UI; 12818 if (User->getOpcode() != ARMISD::VDUPLANE || 12819 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 12820 return false; 12821 } 12822 12823 // Create the vldN-dup node. 12824 EVT Tys[5]; 12825 unsigned n; 12826 for (n = 0; n < NumVecs; ++n) 12827 Tys[n] = VT; 12828 Tys[n] = MVT::Other; 12829 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 12830 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 12831 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 12832 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 12833 Ops, VLDMemInt->getMemoryVT(), 12834 VLDMemInt->getMemOperand()); 12835 12836 // Update the uses. 12837 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12838 UI != UE; ++UI) { 12839 unsigned ResNo = UI.getUse().getResNo(); 12840 // Ignore uses of the chain result. 12841 if (ResNo == NumVecs) 12842 continue; 12843 SDNode *User = *UI; 12844 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 12845 } 12846 12847 // Now the vldN-lane intrinsic is dead except for its chain result. 12848 // Update uses of the chain. 12849 std::vector<SDValue> VLDDupResults; 12850 for (unsigned n = 0; n < NumVecs; ++n) 12851 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 12852 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 12853 DCI.CombineTo(VLD, VLDDupResults); 12854 12855 return true; 12856 } 12857 12858 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 12859 /// ARMISD::VDUPLANE. 12860 static SDValue PerformVDUPLANECombine(SDNode *N, 12861 TargetLowering::DAGCombinerInfo &DCI) { 12862 SDValue Op = N->getOperand(0); 12863 12864 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 12865 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 12866 if (CombineVLDDUP(N, DCI)) 12867 return SDValue(N, 0); 12868 12869 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 12870 // redundant. Ignore bit_converts for now; element sizes are checked below. 12871 while (Op.getOpcode() == ISD::BITCAST) 12872 Op = Op.getOperand(0); 12873 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 12874 return SDValue(); 12875 12876 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 12877 unsigned EltSize = Op.getScalarValueSizeInBits(); 12878 // The canonical VMOV for a zero vector uses a 32-bit element size. 12879 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12880 unsigned EltBits; 12881 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 12882 EltSize = 8; 12883 EVT VT = N->getValueType(0); 12884 if (EltSize > VT.getScalarSizeInBits()) 12885 return SDValue(); 12886 12887 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 12888 } 12889 12890 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 12891 static SDValue PerformVDUPCombine(SDNode *N, 12892 TargetLowering::DAGCombinerInfo &DCI, 12893 const ARMSubtarget *Subtarget) { 12894 SelectionDAG &DAG = DCI.DAG; 12895 SDValue Op = N->getOperand(0); 12896 12897 if (!Subtarget->hasNEON()) 12898 return SDValue(); 12899 12900 // Match VDUP(LOAD) -> VLD1DUP. 12901 // We match this pattern here rather than waiting for isel because the 12902 // transform is only legal for unindexed loads. 12903 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 12904 if (LD && Op.hasOneUse() && LD->isUnindexed() && 12905 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 12906 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 12907 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 12908 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 12909 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 12910 Ops, LD->getMemoryVT(), 12911 LD->getMemOperand()); 12912 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 12913 return VLDDup; 12914 } 12915 12916 return SDValue(); 12917 } 12918 12919 static SDValue PerformLOADCombine(SDNode *N, 12920 TargetLowering::DAGCombinerInfo &DCI) { 12921 EVT VT = N->getValueType(0); 12922 12923 // If this is a legal vector load, try to combine it into a VLD1_UPD. 12924 if (ISD::isNormalLoad(N) && VT.isVector() && 12925 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12926 return CombineBaseUpdate(N, DCI); 12927 12928 return SDValue(); 12929 } 12930 12931 /// PerformSTORECombine - Target-specific dag combine xforms for 12932 /// ISD::STORE. 12933 static SDValue PerformSTORECombine(SDNode *N, 12934 TargetLowering::DAGCombinerInfo &DCI) { 12935 StoreSDNode *St = cast<StoreSDNode>(N); 12936 if (St->isVolatile()) 12937 return SDValue(); 12938 12939 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 12940 // pack all of the elements in one place. Next, store to memory in fewer 12941 // chunks. 12942 SDValue StVal = St->getValue(); 12943 EVT VT = StVal.getValueType(); 12944 if (St->isTruncatingStore() && VT.isVector()) { 12945 SelectionDAG &DAG = DCI.DAG; 12946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12947 EVT StVT = St->getMemoryVT(); 12948 unsigned NumElems = VT.getVectorNumElements(); 12949 assert(StVT != VT && "Cannot truncate to the same type"); 12950 unsigned FromEltSz = VT.getScalarSizeInBits(); 12951 unsigned ToEltSz = StVT.getScalarSizeInBits(); 12952 12953 // From, To sizes and ElemCount must be pow of two 12954 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 12955 12956 // We are going to use the original vector elt for storing. 12957 // Accumulated smaller vector elements must be a multiple of the store size. 12958 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 12959 12960 unsigned SizeRatio = FromEltSz / ToEltSz; 12961 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 12962 12963 // Create a type on which we perform the shuffle. 12964 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 12965 NumElems*SizeRatio); 12966 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 12967 12968 SDLoc DL(St); 12969 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 12970 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 12971 for (unsigned i = 0; i < NumElems; ++i) 12972 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 12973 ? (i + 1) * SizeRatio - 1 12974 : i * SizeRatio; 12975 12976 // Can't shuffle using an illegal type. 12977 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 12978 12979 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 12980 DAG.getUNDEF(WideVec.getValueType()), 12981 ShuffleVec); 12982 // At this point all of the data is stored at the bottom of the 12983 // register. We now need to save it to mem. 12984 12985 // Find the largest store unit 12986 MVT StoreType = MVT::i8; 12987 for (MVT Tp : MVT::integer_valuetypes()) { 12988 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 12989 StoreType = Tp; 12990 } 12991 // Didn't find a legal store type. 12992 if (!TLI.isTypeLegal(StoreType)) 12993 return SDValue(); 12994 12995 // Bitcast the original vector into a vector of store-size units 12996 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 12997 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 12998 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 12999 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 13000 SmallVector<SDValue, 8> Chains; 13001 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 13002 TLI.getPointerTy(DAG.getDataLayout())); 13003 SDValue BasePtr = St->getBasePtr(); 13004 13005 // Perform one or more big stores into memory. 13006 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 13007 for (unsigned I = 0; I < E; I++) { 13008 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 13009 StoreType, ShuffWide, 13010 DAG.getIntPtrConstant(I, DL)); 13011 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 13012 St->getPointerInfo(), St->getAlignment(), 13013 St->getMemOperand()->getFlags()); 13014 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 13015 Increment); 13016 Chains.push_back(Ch); 13017 } 13018 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 13019 } 13020 13021 if (!ISD::isNormalStore(St)) 13022 return SDValue(); 13023 13024 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 13025 // ARM stores of arguments in the same cache line. 13026 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 13027 StVal.getNode()->hasOneUse()) { 13028 SelectionDAG &DAG = DCI.DAG; 13029 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 13030 SDLoc DL(St); 13031 SDValue BasePtr = St->getBasePtr(); 13032 SDValue NewST1 = DAG.getStore( 13033 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 13034 BasePtr, St->getPointerInfo(), St->getAlignment(), 13035 St->getMemOperand()->getFlags()); 13036 13037 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 13038 DAG.getConstant(4, DL, MVT::i32)); 13039 return DAG.getStore(NewST1.getValue(0), DL, 13040 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 13041 OffsetPtr, St->getPointerInfo(), 13042 std::min(4U, St->getAlignment() / 2), 13043 St->getMemOperand()->getFlags()); 13044 } 13045 13046 if (StVal.getValueType() == MVT::i64 && 13047 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13048 13049 // Bitcast an i64 store extracted from a vector to f64. 13050 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13051 SelectionDAG &DAG = DCI.DAG; 13052 SDLoc dl(StVal); 13053 SDValue IntVec = StVal.getOperand(0); 13054 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13055 IntVec.getValueType().getVectorNumElements()); 13056 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 13057 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 13058 Vec, StVal.getOperand(1)); 13059 dl = SDLoc(N); 13060 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 13061 // Make the DAGCombiner fold the bitcasts. 13062 DCI.AddToWorklist(Vec.getNode()); 13063 DCI.AddToWorklist(ExtElt.getNode()); 13064 DCI.AddToWorklist(V.getNode()); 13065 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 13066 St->getPointerInfo(), St->getAlignment(), 13067 St->getMemOperand()->getFlags(), St->getAAInfo()); 13068 } 13069 13070 // If this is a legal vector store, try to combine it into a VST1_UPD. 13071 if (ISD::isNormalStore(N) && VT.isVector() && 13072 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13073 return CombineBaseUpdate(N, DCI); 13074 13075 return SDValue(); 13076 } 13077 13078 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 13079 /// can replace combinations of VMUL and VCVT (floating-point to integer) 13080 /// when the VMUL has a constant operand that is a power of 2. 13081 /// 13082 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13083 /// vmul.f32 d16, d17, d16 13084 /// vcvt.s32.f32 d16, d16 13085 /// becomes: 13086 /// vcvt.s32.f32 d16, d16, #3 13087 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 13088 const ARMSubtarget *Subtarget) { 13089 if (!Subtarget->hasNEON()) 13090 return SDValue(); 13091 13092 SDValue Op = N->getOperand(0); 13093 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 13094 Op.getOpcode() != ISD::FMUL) 13095 return SDValue(); 13096 13097 SDValue ConstVec = Op->getOperand(1); 13098 if (!isa<BuildVectorSDNode>(ConstVec)) 13099 return SDValue(); 13100 13101 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 13102 uint32_t FloatBits = FloatTy.getSizeInBits(); 13103 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 13104 uint32_t IntBits = IntTy.getSizeInBits(); 13105 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13106 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13107 // These instructions only exist converting from f32 to i32. We can handle 13108 // smaller integers by generating an extra truncate, but larger ones would 13109 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13110 // these intructions only support v2i32/v4i32 types. 13111 return SDValue(); 13112 } 13113 13114 BitVector UndefElements; 13115 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13116 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13117 if (C == -1 || C == 0 || C > 32) 13118 return SDValue(); 13119 13120 SDLoc dl(N); 13121 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 13122 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 13123 Intrinsic::arm_neon_vcvtfp2fxu; 13124 SDValue FixConv = DAG.getNode( 13125 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13126 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 13127 DAG.getConstant(C, dl, MVT::i32)); 13128 13129 if (IntBits < FloatBits) 13130 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 13131 13132 return FixConv; 13133 } 13134 13135 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 13136 /// can replace combinations of VCVT (integer to floating-point) and VDIV 13137 /// when the VDIV has a constant operand that is a power of 2. 13138 /// 13139 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13140 /// vcvt.f32.s32 d16, d16 13141 /// vdiv.f32 d16, d17, d16 13142 /// becomes: 13143 /// vcvt.f32.s32 d16, d16, #3 13144 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 13145 const ARMSubtarget *Subtarget) { 13146 if (!Subtarget->hasNEON()) 13147 return SDValue(); 13148 13149 SDValue Op = N->getOperand(0); 13150 unsigned OpOpcode = Op.getNode()->getOpcode(); 13151 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 13152 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 13153 return SDValue(); 13154 13155 SDValue ConstVec = N->getOperand(1); 13156 if (!isa<BuildVectorSDNode>(ConstVec)) 13157 return SDValue(); 13158 13159 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 13160 uint32_t FloatBits = FloatTy.getSizeInBits(); 13161 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 13162 uint32_t IntBits = IntTy.getSizeInBits(); 13163 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13164 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13165 // These instructions only exist converting from i32 to f32. We can handle 13166 // smaller integers by generating an extra extend, but larger ones would 13167 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13168 // these intructions only support v2i32/v4i32 types. 13169 return SDValue(); 13170 } 13171 13172 BitVector UndefElements; 13173 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13174 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13175 if (C == -1 || C == 0 || C > 32) 13176 return SDValue(); 13177 13178 SDLoc dl(N); 13179 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 13180 SDValue ConvInput = Op.getOperand(0); 13181 if (IntBits < FloatBits) 13182 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 13183 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13184 ConvInput); 13185 13186 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 13187 Intrinsic::arm_neon_vcvtfxu2fp; 13188 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 13189 Op.getValueType(), 13190 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 13191 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 13192 } 13193 13194 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 13195 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 13196 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13197 switch (IntNo) { 13198 default: 13199 // Don't do anything for most intrinsics. 13200 break; 13201 13202 // Vector shifts: check for immediate versions and lower them. 13203 // Note: This is done during DAG combining instead of DAG legalizing because 13204 // the build_vectors for 64-bit vector element shift counts are generally 13205 // not legal, and it is hard to see their values after they get legalized to 13206 // loads from a constant pool. 13207 case Intrinsic::arm_neon_vshifts: 13208 case Intrinsic::arm_neon_vshiftu: 13209 case Intrinsic::arm_neon_vrshifts: 13210 case Intrinsic::arm_neon_vrshiftu: 13211 case Intrinsic::arm_neon_vrshiftn: 13212 case Intrinsic::arm_neon_vqshifts: 13213 case Intrinsic::arm_neon_vqshiftu: 13214 case Intrinsic::arm_neon_vqshiftsu: 13215 case Intrinsic::arm_neon_vqshiftns: 13216 case Intrinsic::arm_neon_vqshiftnu: 13217 case Intrinsic::arm_neon_vqshiftnsu: 13218 case Intrinsic::arm_neon_vqrshiftns: 13219 case Intrinsic::arm_neon_vqrshiftnu: 13220 case Intrinsic::arm_neon_vqrshiftnsu: { 13221 EVT VT = N->getOperand(1).getValueType(); 13222 int64_t Cnt; 13223 unsigned VShiftOpc = 0; 13224 13225 switch (IntNo) { 13226 case Intrinsic::arm_neon_vshifts: 13227 case Intrinsic::arm_neon_vshiftu: 13228 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 13229 VShiftOpc = ARMISD::VSHLIMM; 13230 break; 13231 } 13232 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 13233 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 13234 : ARMISD::VSHRuIMM); 13235 break; 13236 } 13237 return SDValue(); 13238 13239 case Intrinsic::arm_neon_vrshifts: 13240 case Intrinsic::arm_neon_vrshiftu: 13241 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 13242 break; 13243 return SDValue(); 13244 13245 case Intrinsic::arm_neon_vqshifts: 13246 case Intrinsic::arm_neon_vqshiftu: 13247 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13248 break; 13249 return SDValue(); 13250 13251 case Intrinsic::arm_neon_vqshiftsu: 13252 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13253 break; 13254 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 13255 13256 case Intrinsic::arm_neon_vrshiftn: 13257 case Intrinsic::arm_neon_vqshiftns: 13258 case Intrinsic::arm_neon_vqshiftnu: 13259 case Intrinsic::arm_neon_vqshiftnsu: 13260 case Intrinsic::arm_neon_vqrshiftns: 13261 case Intrinsic::arm_neon_vqrshiftnu: 13262 case Intrinsic::arm_neon_vqrshiftnsu: 13263 // Narrowing shifts require an immediate right shift. 13264 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 13265 break; 13266 llvm_unreachable("invalid shift count for narrowing vector shift " 13267 "intrinsic"); 13268 13269 default: 13270 llvm_unreachable("unhandled vector shift"); 13271 } 13272 13273 switch (IntNo) { 13274 case Intrinsic::arm_neon_vshifts: 13275 case Intrinsic::arm_neon_vshiftu: 13276 // Opcode already set above. 13277 break; 13278 case Intrinsic::arm_neon_vrshifts: 13279 VShiftOpc = ARMISD::VRSHRsIMM; 13280 break; 13281 case Intrinsic::arm_neon_vrshiftu: 13282 VShiftOpc = ARMISD::VRSHRuIMM; 13283 break; 13284 case Intrinsic::arm_neon_vrshiftn: 13285 VShiftOpc = ARMISD::VRSHRNIMM; 13286 break; 13287 case Intrinsic::arm_neon_vqshifts: 13288 VShiftOpc = ARMISD::VQSHLsIMM; 13289 break; 13290 case Intrinsic::arm_neon_vqshiftu: 13291 VShiftOpc = ARMISD::VQSHLuIMM; 13292 break; 13293 case Intrinsic::arm_neon_vqshiftsu: 13294 VShiftOpc = ARMISD::VQSHLsuIMM; 13295 break; 13296 case Intrinsic::arm_neon_vqshiftns: 13297 VShiftOpc = ARMISD::VQSHRNsIMM; 13298 break; 13299 case Intrinsic::arm_neon_vqshiftnu: 13300 VShiftOpc = ARMISD::VQSHRNuIMM; 13301 break; 13302 case Intrinsic::arm_neon_vqshiftnsu: 13303 VShiftOpc = ARMISD::VQSHRNsuIMM; 13304 break; 13305 case Intrinsic::arm_neon_vqrshiftns: 13306 VShiftOpc = ARMISD::VQRSHRNsIMM; 13307 break; 13308 case Intrinsic::arm_neon_vqrshiftnu: 13309 VShiftOpc = ARMISD::VQRSHRNuIMM; 13310 break; 13311 case Intrinsic::arm_neon_vqrshiftnsu: 13312 VShiftOpc = ARMISD::VQRSHRNsuIMM; 13313 break; 13314 } 13315 13316 SDLoc dl(N); 13317 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 13318 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 13319 } 13320 13321 case Intrinsic::arm_neon_vshiftins: { 13322 EVT VT = N->getOperand(1).getValueType(); 13323 int64_t Cnt; 13324 unsigned VShiftOpc = 0; 13325 13326 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 13327 VShiftOpc = ARMISD::VSLIIMM; 13328 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 13329 VShiftOpc = ARMISD::VSRIIMM; 13330 else { 13331 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 13332 } 13333 13334 SDLoc dl(N); 13335 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 13336 N->getOperand(1), N->getOperand(2), 13337 DAG.getConstant(Cnt, dl, MVT::i32)); 13338 } 13339 13340 case Intrinsic::arm_neon_vqrshifts: 13341 case Intrinsic::arm_neon_vqrshiftu: 13342 // No immediate versions of these to check for. 13343 break; 13344 } 13345 13346 return SDValue(); 13347 } 13348 13349 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 13350 /// lowers them. As with the vector shift intrinsics, this is done during DAG 13351 /// combining instead of DAG legalizing because the build_vectors for 64-bit 13352 /// vector element shift counts are generally not legal, and it is hard to see 13353 /// their values after they get legalized to loads from a constant pool. 13354 static SDValue PerformShiftCombine(SDNode *N, 13355 TargetLowering::DAGCombinerInfo &DCI, 13356 const ARMSubtarget *ST) { 13357 SelectionDAG &DAG = DCI.DAG; 13358 EVT VT = N->getValueType(0); 13359 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 13360 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 13361 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 13362 SDValue N1 = N->getOperand(1); 13363 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 13364 SDValue N0 = N->getOperand(0); 13365 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 13366 DAG.MaskedValueIsZero(N0.getOperand(0), 13367 APInt::getHighBitsSet(32, 16))) 13368 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 13369 } 13370 } 13371 13372 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 13373 N->getOperand(0)->getOpcode() == ISD::AND && 13374 N->getOperand(0)->hasOneUse()) { 13375 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13376 return SDValue(); 13377 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 13378 // usually show up because instcombine prefers to canonicalize it to 13379 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 13380 // out of GEP lowering in some cases. 13381 SDValue N0 = N->getOperand(0); 13382 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13383 if (!ShiftAmtNode) 13384 return SDValue(); 13385 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 13386 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13387 if (!AndMaskNode) 13388 return SDValue(); 13389 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 13390 // Don't transform uxtb/uxth. 13391 if (AndMask == 255 || AndMask == 65535) 13392 return SDValue(); 13393 if (isMask_32(AndMask)) { 13394 uint32_t MaskedBits = countLeadingZeros(AndMask); 13395 if (MaskedBits > ShiftAmt) { 13396 SDLoc DL(N); 13397 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 13398 DAG.getConstant(MaskedBits, DL, MVT::i32)); 13399 return DAG.getNode( 13400 ISD::SRL, DL, MVT::i32, SHL, 13401 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 13402 } 13403 } 13404 } 13405 13406 // Nothing to be done for scalar shifts. 13407 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13408 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 13409 return SDValue(); 13410 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 13411 return SDValue(); 13412 13413 int64_t Cnt; 13414 13415 switch (N->getOpcode()) { 13416 default: llvm_unreachable("unexpected shift opcode"); 13417 13418 case ISD::SHL: 13419 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 13420 SDLoc dl(N); 13421 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 13422 DAG.getConstant(Cnt, dl, MVT::i32)); 13423 } 13424 break; 13425 13426 case ISD::SRA: 13427 case ISD::SRL: 13428 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 13429 unsigned VShiftOpc = 13430 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 13431 SDLoc dl(N); 13432 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 13433 DAG.getConstant(Cnt, dl, MVT::i32)); 13434 } 13435 } 13436 return SDValue(); 13437 } 13438 13439 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 13440 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 13441 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 13442 const ARMSubtarget *ST) { 13443 SDValue N0 = N->getOperand(0); 13444 13445 // Check for sign- and zero-extensions of vector extract operations of 8- 13446 // and 16-bit vector elements. NEON supports these directly. They are 13447 // handled during DAG combining because type legalization will promote them 13448 // to 32-bit types and it is messy to recognize the operations after that. 13449 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13450 SDValue Vec = N0.getOperand(0); 13451 SDValue Lane = N0.getOperand(1); 13452 EVT VT = N->getValueType(0); 13453 EVT EltVT = N0.getValueType(); 13454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13455 13456 if (VT == MVT::i32 && 13457 (EltVT == MVT::i8 || EltVT == MVT::i16) && 13458 TLI.isTypeLegal(Vec.getValueType()) && 13459 isa<ConstantSDNode>(Lane)) { 13460 13461 unsigned Opc = 0; 13462 switch (N->getOpcode()) { 13463 default: llvm_unreachable("unexpected opcode"); 13464 case ISD::SIGN_EXTEND: 13465 Opc = ARMISD::VGETLANEs; 13466 break; 13467 case ISD::ZERO_EXTEND: 13468 case ISD::ANY_EXTEND: 13469 Opc = ARMISD::VGETLANEu; 13470 break; 13471 } 13472 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 13473 } 13474 } 13475 13476 return SDValue(); 13477 } 13478 13479 static const APInt *isPowerOf2Constant(SDValue V) { 13480 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 13481 if (!C) 13482 return nullptr; 13483 const APInt *CV = &C->getAPIntValue(); 13484 return CV->isPowerOf2() ? CV : nullptr; 13485 } 13486 13487 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 13488 // If we have a CMOV, OR and AND combination such as: 13489 // if (x & CN) 13490 // y |= CM; 13491 // 13492 // And: 13493 // * CN is a single bit; 13494 // * All bits covered by CM are known zero in y 13495 // 13496 // Then we can convert this into a sequence of BFI instructions. This will 13497 // always be a win if CM is a single bit, will always be no worse than the 13498 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 13499 // three bits (due to the extra IT instruction). 13500 13501 SDValue Op0 = CMOV->getOperand(0); 13502 SDValue Op1 = CMOV->getOperand(1); 13503 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 13504 auto CC = CCNode->getAPIntValue().getLimitedValue(); 13505 SDValue CmpZ = CMOV->getOperand(4); 13506 13507 // The compare must be against zero. 13508 if (!isNullConstant(CmpZ->getOperand(1))) 13509 return SDValue(); 13510 13511 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 13512 SDValue And = CmpZ->getOperand(0); 13513 if (And->getOpcode() != ISD::AND) 13514 return SDValue(); 13515 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 13516 if (!AndC) 13517 return SDValue(); 13518 SDValue X = And->getOperand(0); 13519 13520 if (CC == ARMCC::EQ) { 13521 // We're performing an "equal to zero" compare. Swap the operands so we 13522 // canonicalize on a "not equal to zero" compare. 13523 std::swap(Op0, Op1); 13524 } else { 13525 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 13526 } 13527 13528 if (Op1->getOpcode() != ISD::OR) 13529 return SDValue(); 13530 13531 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 13532 if (!OrC) 13533 return SDValue(); 13534 SDValue Y = Op1->getOperand(0); 13535 13536 if (Op0 != Y) 13537 return SDValue(); 13538 13539 // Now, is it profitable to continue? 13540 APInt OrCI = OrC->getAPIntValue(); 13541 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 13542 if (OrCI.countPopulation() > Heuristic) 13543 return SDValue(); 13544 13545 // Lastly, can we determine that the bits defined by OrCI 13546 // are zero in Y? 13547 KnownBits Known = DAG.computeKnownBits(Y); 13548 if ((OrCI & Known.Zero) != OrCI) 13549 return SDValue(); 13550 13551 // OK, we can do the combine. 13552 SDValue V = Y; 13553 SDLoc dl(X); 13554 EVT VT = X.getValueType(); 13555 unsigned BitInX = AndC->logBase2(); 13556 13557 if (BitInX != 0) { 13558 // We must shift X first. 13559 X = DAG.getNode(ISD::SRL, dl, VT, X, 13560 DAG.getConstant(BitInX, dl, VT)); 13561 } 13562 13563 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 13564 BitInY < NumActiveBits; ++BitInY) { 13565 if (OrCI[BitInY] == 0) 13566 continue; 13567 APInt Mask(VT.getSizeInBits(), 0); 13568 Mask.setBit(BitInY); 13569 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 13570 // Confusingly, the operand is an *inverted* mask. 13571 DAG.getConstant(~Mask, dl, VT)); 13572 } 13573 13574 return V; 13575 } 13576 13577 // Given N, the value controlling the conditional branch, search for the loop 13578 // intrinsic, returning it, along with how the value is used. We need to handle 13579 // patterns such as the following: 13580 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 13581 // (brcond (setcc (loop.decrement), 0, eq), exit) 13582 // (brcond (setcc (loop.decrement), 0, ne), header) 13583 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 13584 bool &Negate) { 13585 switch (N->getOpcode()) { 13586 default: 13587 break; 13588 case ISD::XOR: { 13589 if (!isa<ConstantSDNode>(N.getOperand(1))) 13590 return SDValue(); 13591 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 13592 return SDValue(); 13593 Negate = !Negate; 13594 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 13595 } 13596 case ISD::SETCC: { 13597 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 13598 if (!Const) 13599 return SDValue(); 13600 if (Const->isNullValue()) 13601 Imm = 0; 13602 else if (Const->isOne()) 13603 Imm = 1; 13604 else 13605 return SDValue(); 13606 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 13607 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 13608 } 13609 case ISD::INTRINSIC_W_CHAIN: { 13610 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 13611 if (IntOp != Intrinsic::test_set_loop_iterations && 13612 IntOp != Intrinsic::loop_decrement_reg) 13613 return SDValue(); 13614 return N; 13615 } 13616 } 13617 return SDValue(); 13618 } 13619 13620 static SDValue PerformHWLoopCombine(SDNode *N, 13621 TargetLowering::DAGCombinerInfo &DCI, 13622 const ARMSubtarget *ST) { 13623 13624 // The hwloop intrinsics that we're interested are used for control-flow, 13625 // either for entering or exiting the loop: 13626 // - test.set.loop.iterations will test whether its operand is zero. If it 13627 // is zero, the proceeding branch should not enter the loop. 13628 // - loop.decrement.reg also tests whether its operand is zero. If it is 13629 // zero, the proceeding branch should not branch back to the beginning of 13630 // the loop. 13631 // So here, we need to check that how the brcond is using the result of each 13632 // of the intrinsics to ensure that we're branching to the right place at the 13633 // right time. 13634 13635 ISD::CondCode CC; 13636 SDValue Cond; 13637 int Imm = 1; 13638 bool Negate = false; 13639 SDValue Chain = N->getOperand(0); 13640 SDValue Dest; 13641 13642 if (N->getOpcode() == ISD::BRCOND) { 13643 CC = ISD::SETEQ; 13644 Cond = N->getOperand(1); 13645 Dest = N->getOperand(2); 13646 } else { 13647 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 13648 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13649 Cond = N->getOperand(2); 13650 Dest = N->getOperand(4); 13651 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 13652 if (!Const->isOne() && !Const->isNullValue()) 13653 return SDValue(); 13654 Imm = Const->getZExtValue(); 13655 } else 13656 return SDValue(); 13657 } 13658 13659 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 13660 if (!Int) 13661 return SDValue(); 13662 13663 if (Negate) 13664 CC = ISD::getSetCCInverse(CC, true); 13665 13666 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 13667 return (CC == ISD::SETEQ && Imm == 0) || 13668 (CC == ISD::SETNE && Imm == 1) || 13669 (CC == ISD::SETLT && Imm == 1) || 13670 (CC == ISD::SETULT && Imm == 1); 13671 }; 13672 13673 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 13674 return (CC == ISD::SETEQ && Imm == 1) || 13675 (CC == ISD::SETNE && Imm == 0) || 13676 (CC == ISD::SETGT && Imm == 0) || 13677 (CC == ISD::SETUGT && Imm == 0) || 13678 (CC == ISD::SETGE && Imm == 1) || 13679 (CC == ISD::SETUGE && Imm == 1); 13680 }; 13681 13682 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 13683 "unsupported condition"); 13684 13685 SDLoc dl(Int); 13686 SelectionDAG &DAG = DCI.DAG; 13687 SDValue Elements = Int.getOperand(2); 13688 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 13689 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 13690 && "expected single br user"); 13691 SDNode *Br = *N->use_begin(); 13692 SDValue OtherTarget = Br->getOperand(1); 13693 13694 // Update the unconditional branch to branch to the given Dest. 13695 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 13696 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 13697 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 13698 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 13699 }; 13700 13701 if (IntOp == Intrinsic::test_set_loop_iterations) { 13702 SDValue Res; 13703 // We expect this 'instruction' to branch when the counter is zero. 13704 if (IsTrueIfZero(CC, Imm)) { 13705 SDValue Ops[] = { Chain, Elements, Dest }; 13706 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 13707 } else { 13708 // The logic is the reverse of what we need for WLS, so find the other 13709 // basic block target: the target of the proceeding br. 13710 UpdateUncondBr(Br, Dest, DAG); 13711 13712 SDValue Ops[] = { Chain, Elements, OtherTarget }; 13713 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 13714 } 13715 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 13716 return Res; 13717 } else { 13718 SDValue Size = DAG.getTargetConstant( 13719 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 13720 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 13721 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 13722 DAG.getVTList(MVT::i32, MVT::Other), Args); 13723 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 13724 13725 // We expect this instruction to branch when the count is not zero. 13726 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 13727 13728 // Update the unconditional branch to target the loop preheader if we've 13729 // found the condition has been reversed. 13730 if (Target == OtherTarget) 13731 UpdateUncondBr(Br, Dest, DAG); 13732 13733 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13734 SDValue(LoopDec.getNode(), 1), Chain); 13735 13736 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 13737 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 13738 } 13739 return SDValue(); 13740 } 13741 13742 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 13743 SDValue 13744 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 13745 SDValue Cmp = N->getOperand(4); 13746 if (Cmp.getOpcode() != ARMISD::CMPZ) 13747 // Only looking at NE cases. 13748 return SDValue(); 13749 13750 EVT VT = N->getValueType(0); 13751 SDLoc dl(N); 13752 SDValue LHS = Cmp.getOperand(0); 13753 SDValue RHS = Cmp.getOperand(1); 13754 SDValue Chain = N->getOperand(0); 13755 SDValue BB = N->getOperand(1); 13756 SDValue ARMcc = N->getOperand(2); 13757 ARMCC::CondCodes CC = 13758 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13759 13760 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 13761 // -> (brcond Chain BB CC CPSR Cmp) 13762 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 13763 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 13764 LHS->getOperand(0)->hasOneUse()) { 13765 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 13766 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 13767 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13768 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13769 if ((LHS00C && LHS00C->getZExtValue() == 0) && 13770 (LHS01C && LHS01C->getZExtValue() == 1) && 13771 (LHS1C && LHS1C->getZExtValue() == 1) && 13772 (RHSC && RHSC->getZExtValue() == 0)) { 13773 return DAG.getNode( 13774 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 13775 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 13776 } 13777 } 13778 13779 return SDValue(); 13780 } 13781 13782 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 13783 SDValue 13784 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 13785 SDValue Cmp = N->getOperand(4); 13786 if (Cmp.getOpcode() != ARMISD::CMPZ) 13787 // Only looking at EQ and NE cases. 13788 return SDValue(); 13789 13790 EVT VT = N->getValueType(0); 13791 SDLoc dl(N); 13792 SDValue LHS = Cmp.getOperand(0); 13793 SDValue RHS = Cmp.getOperand(1); 13794 SDValue FalseVal = N->getOperand(0); 13795 SDValue TrueVal = N->getOperand(1); 13796 SDValue ARMcc = N->getOperand(2); 13797 ARMCC::CondCodes CC = 13798 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13799 13800 // BFI is only available on V6T2+. 13801 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 13802 SDValue R = PerformCMOVToBFICombine(N, DAG); 13803 if (R) 13804 return R; 13805 } 13806 13807 // Simplify 13808 // mov r1, r0 13809 // cmp r1, x 13810 // mov r0, y 13811 // moveq r0, x 13812 // to 13813 // cmp r0, x 13814 // movne r0, y 13815 // 13816 // mov r1, r0 13817 // cmp r1, x 13818 // mov r0, x 13819 // movne r0, y 13820 // to 13821 // cmp r0, x 13822 // movne r0, y 13823 /// FIXME: Turn this into a target neutral optimization? 13824 SDValue Res; 13825 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 13826 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 13827 N->getOperand(3), Cmp); 13828 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 13829 SDValue ARMcc; 13830 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 13831 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 13832 N->getOperand(3), NewCmp); 13833 } 13834 13835 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 13836 // -> (cmov F T CC CPSR Cmp) 13837 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 13838 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 13839 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13840 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13841 if ((LHS0C && LHS0C->getZExtValue() == 0) && 13842 (LHS1C && LHS1C->getZExtValue() == 1) && 13843 (RHSC && RHSC->getZExtValue() == 0)) { 13844 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 13845 LHS->getOperand(2), LHS->getOperand(3), 13846 LHS->getOperand(4)); 13847 } 13848 } 13849 13850 if (!VT.isInteger()) 13851 return SDValue(); 13852 13853 // Materialize a boolean comparison for integers so we can avoid branching. 13854 if (isNullConstant(FalseVal)) { 13855 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 13856 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 13857 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 13858 // right 5 bits will make that 32 be 1, otherwise it will be 0. 13859 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 13860 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13861 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 13862 DAG.getConstant(5, dl, MVT::i32)); 13863 } else { 13864 // CMOV 0, 1, ==, (CMPZ x, y) -> 13865 // (ADDCARRY (SUB x, y), t:0, t:1) 13866 // where t = (SUBCARRY 0, (SUB x, y), 0) 13867 // 13868 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 13869 // x != y. In other words, a carry C == 1 when x == y, C == 0 13870 // otherwise. 13871 // The final ADDCARRY computes 13872 // x - y + (0 - (x - y)) + C == C 13873 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13874 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13875 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 13876 // ISD::SUBCARRY returns a borrow but we want the carry here 13877 // actually. 13878 SDValue Carry = 13879 DAG.getNode(ISD::SUB, dl, MVT::i32, 13880 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 13881 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 13882 } 13883 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 13884 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 13885 // This seems pointless but will allow us to combine it further below. 13886 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13887 SDValue Sub = 13888 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13889 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13890 Sub.getValue(1), SDValue()); 13891 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 13892 N->getOperand(3), CPSRGlue.getValue(1)); 13893 FalseVal = Sub; 13894 } 13895 } else if (isNullConstant(TrueVal)) { 13896 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 13897 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 13898 // This seems pointless but will allow us to combine it further below 13899 // Note that we change == for != as this is the dual for the case above. 13900 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13901 SDValue Sub = 13902 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13903 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13904 Sub.getValue(1), SDValue()); 13905 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 13906 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 13907 N->getOperand(3), CPSRGlue.getValue(1)); 13908 FalseVal = Sub; 13909 } 13910 } 13911 13912 // On Thumb1, the DAG above may be further combined if z is a power of 2 13913 // (z == 2 ^ K). 13914 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 13915 // t1 = (USUBO (SUB x, y), 1) 13916 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 13917 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13918 // 13919 // This also handles the special case of comparing against zero; it's 13920 // essentially, the same pattern, except there's no SUBS: 13921 // CMOV x, z, !=, (CMPZ x, 0) -> 13922 // t1 = (USUBO x, 1) 13923 // t2 = (SUBCARRY x, t1:0, t1:1) 13924 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13925 const APInt *TrueConst; 13926 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 13927 ((FalseVal.getOpcode() == ARMISD::SUBS && 13928 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 13929 (FalseVal == LHS && isNullConstant(RHS))) && 13930 (TrueConst = isPowerOf2Constant(TrueVal))) { 13931 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13932 unsigned ShiftAmount = TrueConst->logBase2(); 13933 if (ShiftAmount) 13934 TrueVal = DAG.getConstant(1, dl, VT); 13935 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 13936 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 13937 13938 if (ShiftAmount) 13939 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 13940 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 13941 } 13942 13943 if (Res.getNode()) { 13944 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 13945 // Capture demanded bits information that would be otherwise lost. 13946 if (Known.Zero == 0xfffffffe) 13947 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13948 DAG.getValueType(MVT::i1)); 13949 else if (Known.Zero == 0xffffff00) 13950 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13951 DAG.getValueType(MVT::i8)); 13952 else if (Known.Zero == 0xffff0000) 13953 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13954 DAG.getValueType(MVT::i16)); 13955 } 13956 13957 return Res; 13958 } 13959 13960 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 13961 DAGCombinerInfo &DCI) const { 13962 switch (N->getOpcode()) { 13963 default: break; 13964 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 13965 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 13966 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 13967 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 13968 case ISD::SUB: return PerformSUBCombine(N, DCI); 13969 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 13970 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 13971 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 13972 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 13973 case ISD::BRCOND: 13974 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 13975 case ARMISD::ADDC: 13976 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 13977 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 13978 case ARMISD::BFI: return PerformBFICombine(N, DCI); 13979 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 13980 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 13981 case ISD::STORE: return PerformSTORECombine(N, DCI); 13982 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 13983 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 13984 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 13985 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 13986 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 13987 case ISD::FP_TO_SINT: 13988 case ISD::FP_TO_UINT: 13989 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 13990 case ISD::FDIV: 13991 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 13992 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 13993 case ISD::SHL: 13994 case ISD::SRA: 13995 case ISD::SRL: 13996 return PerformShiftCombine(N, DCI, Subtarget); 13997 case ISD::SIGN_EXTEND: 13998 case ISD::ZERO_EXTEND: 13999 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 14000 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 14001 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 14002 case ISD::LOAD: return PerformLOADCombine(N, DCI); 14003 case ARMISD::VLD1DUP: 14004 case ARMISD::VLD2DUP: 14005 case ARMISD::VLD3DUP: 14006 case ARMISD::VLD4DUP: 14007 return PerformVLDCombine(N, DCI); 14008 case ARMISD::BUILD_VECTOR: 14009 return PerformARMBUILD_VECTORCombine(N, DCI); 14010 case ARMISD::SMULWB: { 14011 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14012 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 14013 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 14014 return SDValue(); 14015 break; 14016 } 14017 case ARMISD::SMULWT: { 14018 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14019 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 14020 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 14021 return SDValue(); 14022 break; 14023 } 14024 case ARMISD::SMLALBB: { 14025 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14026 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 14027 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 14028 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 14029 return SDValue(); 14030 break; 14031 } 14032 case ARMISD::SMLALBT: { 14033 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 14034 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 14035 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 14036 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 14037 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 14038 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 14039 return SDValue(); 14040 break; 14041 } 14042 case ARMISD::SMLALTB: { 14043 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 14044 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 14045 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 14046 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 14047 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 14048 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 14049 return SDValue(); 14050 break; 14051 } 14052 case ARMISD::SMLALTT: { 14053 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14054 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 14055 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 14056 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 14057 return SDValue(); 14058 break; 14059 } 14060 case ISD::INTRINSIC_VOID: 14061 case ISD::INTRINSIC_W_CHAIN: 14062 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14063 case Intrinsic::arm_neon_vld1: 14064 case Intrinsic::arm_neon_vld1x2: 14065 case Intrinsic::arm_neon_vld1x3: 14066 case Intrinsic::arm_neon_vld1x4: 14067 case Intrinsic::arm_neon_vld2: 14068 case Intrinsic::arm_neon_vld3: 14069 case Intrinsic::arm_neon_vld4: 14070 case Intrinsic::arm_neon_vld2lane: 14071 case Intrinsic::arm_neon_vld3lane: 14072 case Intrinsic::arm_neon_vld4lane: 14073 case Intrinsic::arm_neon_vld2dup: 14074 case Intrinsic::arm_neon_vld3dup: 14075 case Intrinsic::arm_neon_vld4dup: 14076 case Intrinsic::arm_neon_vst1: 14077 case Intrinsic::arm_neon_vst1x2: 14078 case Intrinsic::arm_neon_vst1x3: 14079 case Intrinsic::arm_neon_vst1x4: 14080 case Intrinsic::arm_neon_vst2: 14081 case Intrinsic::arm_neon_vst3: 14082 case Intrinsic::arm_neon_vst4: 14083 case Intrinsic::arm_neon_vst2lane: 14084 case Intrinsic::arm_neon_vst3lane: 14085 case Intrinsic::arm_neon_vst4lane: 14086 return PerformVLDCombine(N, DCI); 14087 default: break; 14088 } 14089 break; 14090 } 14091 return SDValue(); 14092 } 14093 14094 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 14095 EVT VT) const { 14096 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 14097 } 14098 14099 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 14100 unsigned Alignment, 14101 MachineMemOperand::Flags, 14102 bool *Fast) const { 14103 // Depends what it gets converted into if the type is weird. 14104 if (!VT.isSimple()) 14105 return false; 14106 14107 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 14108 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 14109 auto Ty = VT.getSimpleVT().SimpleTy; 14110 14111 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 14112 // Unaligned access can use (for example) LRDB, LRDH, LDR 14113 if (AllowsUnaligned) { 14114 if (Fast) 14115 *Fast = Subtarget->hasV7Ops(); 14116 return true; 14117 } 14118 } 14119 14120 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 14121 // For any little-endian targets with neon, we can support unaligned ld/st 14122 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 14123 // A big-endian target may also explicitly support unaligned accesses 14124 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 14125 if (Fast) 14126 *Fast = true; 14127 return true; 14128 } 14129 } 14130 14131 if (!Subtarget->hasMVEIntegerOps()) 14132 return false; 14133 14134 // These are for predicates 14135 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 14136 if (Fast) 14137 *Fast = true; 14138 return true; 14139 } 14140 14141 // These are for truncated stores/narrowing loads. They are fine so long as 14142 // the alignment is at least the size of the item being loaded 14143 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 14144 Alignment >= VT.getScalarSizeInBits() / 8) { 14145 if (Fast) 14146 *Fast = true; 14147 return true; 14148 } 14149 14150 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 14151 // VSTRW.U32 all store the vector register in exactly the same format, and 14152 // differ only in the range of their immediate offset field and the required 14153 // alignment. So there is always a store that can be used, regardless of 14154 // actual type. 14155 // 14156 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 14157 // VREV64.8) pair and get the same effect. This will likely be better than 14158 // aligning the vector through the stack. 14159 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 14160 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 14161 Ty == MVT::v2f64) { 14162 if (Fast) 14163 *Fast = true; 14164 return true; 14165 } 14166 14167 return false; 14168 } 14169 14170 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 14171 unsigned AlignCheck) { 14172 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 14173 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 14174 } 14175 14176 EVT ARMTargetLowering::getOptimalMemOpType( 14177 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14178 bool ZeroMemset, bool MemcpyStrSrc, 14179 const AttributeList &FuncAttributes) const { 14180 // See if we can use NEON instructions for this... 14181 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 14182 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14183 bool Fast; 14184 if (Size >= 16 && 14185 (memOpAlign(SrcAlign, DstAlign, 16) || 14186 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 14187 MachineMemOperand::MONone, &Fast) && 14188 Fast))) { 14189 return MVT::v2f64; 14190 } else if (Size >= 8 && 14191 (memOpAlign(SrcAlign, DstAlign, 8) || 14192 (allowsMisalignedMemoryAccesses( 14193 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 14194 Fast))) { 14195 return MVT::f64; 14196 } 14197 } 14198 14199 // Let the target-independent logic figure it out. 14200 return MVT::Other; 14201 } 14202 14203 // 64-bit integers are split into their high and low parts and held in two 14204 // different registers, so the trunc is free since the low register can just 14205 // be used. 14206 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 14207 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 14208 return false; 14209 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 14210 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 14211 return (SrcBits == 64 && DestBits == 32); 14212 } 14213 14214 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 14215 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 14216 !DstVT.isInteger()) 14217 return false; 14218 unsigned SrcBits = SrcVT.getSizeInBits(); 14219 unsigned DestBits = DstVT.getSizeInBits(); 14220 return (SrcBits == 64 && DestBits == 32); 14221 } 14222 14223 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14224 if (Val.getOpcode() != ISD::LOAD) 14225 return false; 14226 14227 EVT VT1 = Val.getValueType(); 14228 if (!VT1.isSimple() || !VT1.isInteger() || 14229 !VT2.isSimple() || !VT2.isInteger()) 14230 return false; 14231 14232 switch (VT1.getSimpleVT().SimpleTy) { 14233 default: break; 14234 case MVT::i1: 14235 case MVT::i8: 14236 case MVT::i16: 14237 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 14238 return true; 14239 } 14240 14241 return false; 14242 } 14243 14244 bool ARMTargetLowering::isFNegFree(EVT VT) const { 14245 if (!VT.isSimple()) 14246 return false; 14247 14248 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 14249 // negate values directly (fneg is free). So, we don't want to let the DAG 14250 // combiner rewrite fneg into xors and some other instructions. For f16 and 14251 // FullFP16 argument passing, some bitcast nodes may be introduced, 14252 // triggering this DAG combine rewrite, so we are avoiding that with this. 14253 switch (VT.getSimpleVT().SimpleTy) { 14254 default: break; 14255 case MVT::f16: 14256 return Subtarget->hasFullFP16(); 14257 } 14258 14259 return false; 14260 } 14261 14262 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 14263 /// of the vector elements. 14264 static bool areExtractExts(Value *Ext1, Value *Ext2) { 14265 auto areExtDoubled = [](Instruction *Ext) { 14266 return Ext->getType()->getScalarSizeInBits() == 14267 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 14268 }; 14269 14270 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 14271 !match(Ext2, m_ZExtOrSExt(m_Value())) || 14272 !areExtDoubled(cast<Instruction>(Ext1)) || 14273 !areExtDoubled(cast<Instruction>(Ext2))) 14274 return false; 14275 14276 return true; 14277 } 14278 14279 /// Check if sinking \p I's operands to I's basic block is profitable, because 14280 /// the operands can be folded into a target instruction, e.g. 14281 /// sext/zext can be folded into vsubl. 14282 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 14283 SmallVectorImpl<Use *> &Ops) const { 14284 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy()) 14285 return false; 14286 14287 switch (I->getOpcode()) { 14288 case Instruction::Sub: 14289 case Instruction::Add: { 14290 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 14291 return false; 14292 Ops.push_back(&I->getOperandUse(0)); 14293 Ops.push_back(&I->getOperandUse(1)); 14294 return true; 14295 } 14296 default: 14297 return false; 14298 } 14299 return false; 14300 } 14301 14302 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 14303 EVT VT = ExtVal.getValueType(); 14304 14305 if (!isTypeLegal(VT)) 14306 return false; 14307 14308 // Don't create a loadext if we can fold the extension into a wide/long 14309 // instruction. 14310 // If there's more than one user instruction, the loadext is desirable no 14311 // matter what. There can be two uses by the same instruction. 14312 if (ExtVal->use_empty() || 14313 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 14314 return true; 14315 14316 SDNode *U = *ExtVal->use_begin(); 14317 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 14318 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 14319 return false; 14320 14321 return true; 14322 } 14323 14324 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 14325 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14326 return false; 14327 14328 if (!isTypeLegal(EVT::getEVT(Ty1))) 14329 return false; 14330 14331 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 14332 14333 // Assuming the caller doesn't have a zeroext or signext return parameter, 14334 // truncation all the way down to i1 is valid. 14335 return true; 14336 } 14337 14338 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 14339 const AddrMode &AM, Type *Ty, 14340 unsigned AS) const { 14341 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 14342 if (Subtarget->hasFPAO()) 14343 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 14344 return 0; 14345 } 14346 return -1; 14347 } 14348 14349 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 14350 if (V < 0) 14351 return false; 14352 14353 unsigned Scale = 1; 14354 switch (VT.getSimpleVT().SimpleTy) { 14355 case MVT::i1: 14356 case MVT::i8: 14357 // Scale == 1; 14358 break; 14359 case MVT::i16: 14360 // Scale == 2; 14361 Scale = 2; 14362 break; 14363 default: 14364 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 14365 // Scale == 4; 14366 Scale = 4; 14367 break; 14368 } 14369 14370 if ((V & (Scale - 1)) != 0) 14371 return false; 14372 return isUInt<5>(V / Scale); 14373 } 14374 14375 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 14376 const ARMSubtarget *Subtarget) { 14377 if (!VT.isInteger() && !VT.isFloatingPoint()) 14378 return false; 14379 if (VT.isVector() && Subtarget->hasNEON()) 14380 return false; 14381 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 14382 !Subtarget->hasMVEFloatOps()) 14383 return false; 14384 14385 bool IsNeg = false; 14386 if (V < 0) { 14387 IsNeg = true; 14388 V = -V; 14389 } 14390 14391 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U); 14392 14393 // MVE: size * imm7 14394 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 14395 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 14396 case MVT::i32: 14397 case MVT::f32: 14398 return isShiftedUInt<7,2>(V); 14399 case MVT::i16: 14400 case MVT::f16: 14401 return isShiftedUInt<7,1>(V); 14402 case MVT::i8: 14403 return isUInt<7>(V); 14404 default: 14405 return false; 14406 } 14407 } 14408 14409 // half VLDR: 2 * imm8 14410 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 14411 return isShiftedUInt<8, 1>(V); 14412 // VLDR and LDRD: 4 * imm8 14413 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 14414 return isShiftedUInt<8, 2>(V); 14415 14416 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 14417 // + imm12 or - imm8 14418 if (IsNeg) 14419 return isUInt<8>(V); 14420 return isUInt<12>(V); 14421 } 14422 14423 return false; 14424 } 14425 14426 /// isLegalAddressImmediate - Return true if the integer value can be used 14427 /// as the offset of the target addressing mode for load / store of the 14428 /// given type. 14429 static bool isLegalAddressImmediate(int64_t V, EVT VT, 14430 const ARMSubtarget *Subtarget) { 14431 if (V == 0) 14432 return true; 14433 14434 if (!VT.isSimple()) 14435 return false; 14436 14437 if (Subtarget->isThumb1Only()) 14438 return isLegalT1AddressImmediate(V, VT); 14439 else if (Subtarget->isThumb2()) 14440 return isLegalT2AddressImmediate(V, VT, Subtarget); 14441 14442 // ARM mode. 14443 if (V < 0) 14444 V = - V; 14445 switch (VT.getSimpleVT().SimpleTy) { 14446 default: return false; 14447 case MVT::i1: 14448 case MVT::i8: 14449 case MVT::i32: 14450 // +- imm12 14451 return isUInt<12>(V); 14452 case MVT::i16: 14453 // +- imm8 14454 return isUInt<8>(V); 14455 case MVT::f32: 14456 case MVT::f64: 14457 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 14458 return false; 14459 return isShiftedUInt<8, 2>(V); 14460 } 14461 } 14462 14463 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 14464 EVT VT) const { 14465 int Scale = AM.Scale; 14466 if (Scale < 0) 14467 return false; 14468 14469 switch (VT.getSimpleVT().SimpleTy) { 14470 default: return false; 14471 case MVT::i1: 14472 case MVT::i8: 14473 case MVT::i16: 14474 case MVT::i32: 14475 if (Scale == 1) 14476 return true; 14477 // r + r << imm 14478 Scale = Scale & ~1; 14479 return Scale == 2 || Scale == 4 || Scale == 8; 14480 case MVT::i64: 14481 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 14482 // version in Thumb mode. 14483 // r + r 14484 if (Scale == 1) 14485 return true; 14486 // r * 2 (this can be lowered to r + r). 14487 if (!AM.HasBaseReg && Scale == 2) 14488 return true; 14489 return false; 14490 case MVT::isVoid: 14491 // Note, we allow "void" uses (basically, uses that aren't loads or 14492 // stores), because arm allows folding a scale into many arithmetic 14493 // operations. This should be made more precise and revisited later. 14494 14495 // Allow r << imm, but the imm has to be a multiple of two. 14496 if (Scale & 1) return false; 14497 return isPowerOf2_32(Scale); 14498 } 14499 } 14500 14501 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 14502 EVT VT) const { 14503 const int Scale = AM.Scale; 14504 14505 // Negative scales are not supported in Thumb1. 14506 if (Scale < 0) 14507 return false; 14508 14509 // Thumb1 addressing modes do not support register scaling excepting the 14510 // following cases: 14511 // 1. Scale == 1 means no scaling. 14512 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 14513 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 14514 } 14515 14516 /// isLegalAddressingMode - Return true if the addressing mode represented 14517 /// by AM is legal for this target, for a load/store of the specified type. 14518 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14519 const AddrMode &AM, Type *Ty, 14520 unsigned AS, Instruction *I) const { 14521 EVT VT = getValueType(DL, Ty, true); 14522 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 14523 return false; 14524 14525 // Can never fold addr of global into load/store. 14526 if (AM.BaseGV) 14527 return false; 14528 14529 switch (AM.Scale) { 14530 case 0: // no scale reg, must be "r+i" or "r", or "i". 14531 break; 14532 default: 14533 // ARM doesn't support any R+R*scale+imm addr modes. 14534 if (AM.BaseOffs) 14535 return false; 14536 14537 if (!VT.isSimple()) 14538 return false; 14539 14540 if (Subtarget->isThumb1Only()) 14541 return isLegalT1ScaledAddressingMode(AM, VT); 14542 14543 if (Subtarget->isThumb2()) 14544 return isLegalT2ScaledAddressingMode(AM, VT); 14545 14546 int Scale = AM.Scale; 14547 switch (VT.getSimpleVT().SimpleTy) { 14548 default: return false; 14549 case MVT::i1: 14550 case MVT::i8: 14551 case MVT::i32: 14552 if (Scale < 0) Scale = -Scale; 14553 if (Scale == 1) 14554 return true; 14555 // r + r << imm 14556 return isPowerOf2_32(Scale & ~1); 14557 case MVT::i16: 14558 case MVT::i64: 14559 // r +/- r 14560 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 14561 return true; 14562 // r * 2 (this can be lowered to r + r). 14563 if (!AM.HasBaseReg && Scale == 2) 14564 return true; 14565 return false; 14566 14567 case MVT::isVoid: 14568 // Note, we allow "void" uses (basically, uses that aren't loads or 14569 // stores), because arm allows folding a scale into many arithmetic 14570 // operations. This should be made more precise and revisited later. 14571 14572 // Allow r << imm, but the imm has to be a multiple of two. 14573 if (Scale & 1) return false; 14574 return isPowerOf2_32(Scale); 14575 } 14576 } 14577 return true; 14578 } 14579 14580 /// isLegalICmpImmediate - Return true if the specified immediate is legal 14581 /// icmp immediate, that is the target has icmp instructions which can compare 14582 /// a register against the immediate without having to materialize the 14583 /// immediate into a register. 14584 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14585 // Thumb2 and ARM modes can use cmn for negative immediates. 14586 if (!Subtarget->isThumb()) 14587 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 14588 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 14589 if (Subtarget->isThumb2()) 14590 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 14591 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 14592 // Thumb1 doesn't have cmn, and only 8-bit immediates. 14593 return Imm >= 0 && Imm <= 255; 14594 } 14595 14596 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 14597 /// *or sub* immediate, that is the target has add or sub instructions which can 14598 /// add a register with the immediate without having to materialize the 14599 /// immediate into a register. 14600 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14601 // Same encoding for add/sub, just flip the sign. 14602 int64_t AbsImm = std::abs(Imm); 14603 if (!Subtarget->isThumb()) 14604 return ARM_AM::getSOImmVal(AbsImm) != -1; 14605 if (Subtarget->isThumb2()) 14606 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 14607 // Thumb1 only has 8-bit unsigned immediate. 14608 return AbsImm >= 0 && AbsImm <= 255; 14609 } 14610 14611 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 14612 bool isSEXTLoad, SDValue &Base, 14613 SDValue &Offset, bool &isInc, 14614 SelectionDAG &DAG) { 14615 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14616 return false; 14617 14618 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 14619 // AddressingMode 3 14620 Base = Ptr->getOperand(0); 14621 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14622 int RHSC = (int)RHS->getZExtValue(); 14623 if (RHSC < 0 && RHSC > -256) { 14624 assert(Ptr->getOpcode() == ISD::ADD); 14625 isInc = false; 14626 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14627 return true; 14628 } 14629 } 14630 isInc = (Ptr->getOpcode() == ISD::ADD); 14631 Offset = Ptr->getOperand(1); 14632 return true; 14633 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 14634 // AddressingMode 2 14635 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14636 int RHSC = (int)RHS->getZExtValue(); 14637 if (RHSC < 0 && RHSC > -0x1000) { 14638 assert(Ptr->getOpcode() == ISD::ADD); 14639 isInc = false; 14640 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14641 Base = Ptr->getOperand(0); 14642 return true; 14643 } 14644 } 14645 14646 if (Ptr->getOpcode() == ISD::ADD) { 14647 isInc = true; 14648 ARM_AM::ShiftOpc ShOpcVal= 14649 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 14650 if (ShOpcVal != ARM_AM::no_shift) { 14651 Base = Ptr->getOperand(1); 14652 Offset = Ptr->getOperand(0); 14653 } else { 14654 Base = Ptr->getOperand(0); 14655 Offset = Ptr->getOperand(1); 14656 } 14657 return true; 14658 } 14659 14660 isInc = (Ptr->getOpcode() == ISD::ADD); 14661 Base = Ptr->getOperand(0); 14662 Offset = Ptr->getOperand(1); 14663 return true; 14664 } 14665 14666 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 14667 return false; 14668 } 14669 14670 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 14671 bool isSEXTLoad, SDValue &Base, 14672 SDValue &Offset, bool &isInc, 14673 SelectionDAG &DAG) { 14674 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14675 return false; 14676 14677 Base = Ptr->getOperand(0); 14678 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14679 int RHSC = (int)RHS->getZExtValue(); 14680 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 14681 assert(Ptr->getOpcode() == ISD::ADD); 14682 isInc = false; 14683 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14684 return true; 14685 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 14686 isInc = Ptr->getOpcode() == ISD::ADD; 14687 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14688 return true; 14689 } 14690 } 14691 14692 return false; 14693 } 14694 14695 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align, 14696 bool isSEXTLoad, bool isLE, SDValue &Base, 14697 SDValue &Offset, bool &isInc, 14698 SelectionDAG &DAG) { 14699 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14700 return false; 14701 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 14702 return false; 14703 14704 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 14705 int RHSC = (int)RHS->getZExtValue(); 14706 14707 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 14708 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 14709 assert(Ptr->getOpcode() == ISD::ADD); 14710 isInc = false; 14711 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14712 return true; 14713 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 14714 isInc = Ptr->getOpcode() == ISD::ADD; 14715 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14716 return true; 14717 } 14718 return false; 14719 }; 14720 14721 // Try to find a matching instruction based on s/zext, Alignment, Offset and 14722 // (in BE) type. 14723 Base = Ptr->getOperand(0); 14724 if (VT == MVT::v4i16) { 14725 if (Align >= 2 && IsInRange(RHSC, 0x80, 2)) 14726 return true; 14727 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 14728 if (IsInRange(RHSC, 0x80, 1)) 14729 return true; 14730 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) && 14731 IsInRange(RHSC, 0x80, 4)) 14732 return true; 14733 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) && 14734 IsInRange(RHSC, 0x80, 2)) 14735 return true; 14736 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 14737 return true; 14738 return false; 14739 } 14740 14741 /// getPreIndexedAddressParts - returns true by value, base pointer and 14742 /// offset pointer and addressing mode by reference if the node's address 14743 /// can be legally represented as pre-indexed load / store address. 14744 bool 14745 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 14746 SDValue &Offset, 14747 ISD::MemIndexedMode &AM, 14748 SelectionDAG &DAG) const { 14749 if (Subtarget->isThumb1Only()) 14750 return false; 14751 14752 EVT VT; 14753 SDValue Ptr; 14754 unsigned Align; 14755 bool isSEXTLoad = false; 14756 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 14757 Ptr = LD->getBasePtr(); 14758 VT = LD->getMemoryVT(); 14759 Align = LD->getAlignment(); 14760 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 14761 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 14762 Ptr = ST->getBasePtr(); 14763 VT = ST->getMemoryVT(); 14764 Align = ST->getAlignment(); 14765 } else 14766 return false; 14767 14768 bool isInc; 14769 bool isLegal = false; 14770 if (VT.isVector()) 14771 isLegal = Subtarget->hasMVEIntegerOps() && 14772 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad, 14773 Subtarget->isLittle(), Base, Offset, 14774 isInc, DAG); 14775 else { 14776 if (Subtarget->isThumb2()) 14777 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 14778 Offset, isInc, DAG); 14779 else 14780 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 14781 Offset, isInc, DAG); 14782 } 14783 if (!isLegal) 14784 return false; 14785 14786 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 14787 return true; 14788 } 14789 14790 /// getPostIndexedAddressParts - returns true by value, base pointer and 14791 /// offset pointer and addressing mode by reference if this node can be 14792 /// combined with a load / store to form a post-indexed load / store. 14793 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 14794 SDValue &Base, 14795 SDValue &Offset, 14796 ISD::MemIndexedMode &AM, 14797 SelectionDAG &DAG) const { 14798 EVT VT; 14799 SDValue Ptr; 14800 unsigned Align; 14801 bool isSEXTLoad = false, isNonExt; 14802 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 14803 VT = LD->getMemoryVT(); 14804 Ptr = LD->getBasePtr(); 14805 Align = LD->getAlignment(); 14806 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 14807 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 14808 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 14809 VT = ST->getMemoryVT(); 14810 Ptr = ST->getBasePtr(); 14811 Align = ST->getAlignment(); 14812 isNonExt = !ST->isTruncatingStore(); 14813 } else 14814 return false; 14815 14816 if (Subtarget->isThumb1Only()) { 14817 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 14818 // must be non-extending/truncating, i32, with an offset of 4. 14819 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 14820 if (Op->getOpcode() != ISD::ADD || !isNonExt) 14821 return false; 14822 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 14823 if (!RHS || RHS->getZExtValue() != 4) 14824 return false; 14825 14826 Offset = Op->getOperand(1); 14827 Base = Op->getOperand(0); 14828 AM = ISD::POST_INC; 14829 return true; 14830 } 14831 14832 bool isInc; 14833 bool isLegal = false; 14834 if (VT.isVector()) 14835 isLegal = Subtarget->hasMVEIntegerOps() && 14836 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad, 14837 Subtarget->isLittle(), Base, Offset, 14838 isInc, DAG); 14839 else { 14840 if (Subtarget->isThumb2()) 14841 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14842 isInc, DAG); 14843 else 14844 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14845 isInc, DAG); 14846 } 14847 if (!isLegal) 14848 return false; 14849 14850 if (Ptr != Base) { 14851 // Swap base ptr and offset to catch more post-index load / store when 14852 // it's legal. In Thumb2 mode, offset must be an immediate. 14853 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 14854 !Subtarget->isThumb2()) 14855 std::swap(Base, Offset); 14856 14857 // Post-indexed load / store update the base pointer. 14858 if (Ptr != Base) 14859 return false; 14860 } 14861 14862 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 14863 return true; 14864 } 14865 14866 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14867 KnownBits &Known, 14868 const APInt &DemandedElts, 14869 const SelectionDAG &DAG, 14870 unsigned Depth) const { 14871 unsigned BitWidth = Known.getBitWidth(); 14872 Known.resetAll(); 14873 switch (Op.getOpcode()) { 14874 default: break; 14875 case ARMISD::ADDC: 14876 case ARMISD::ADDE: 14877 case ARMISD::SUBC: 14878 case ARMISD::SUBE: 14879 // Special cases when we convert a carry to a boolean. 14880 if (Op.getResNo() == 0) { 14881 SDValue LHS = Op.getOperand(0); 14882 SDValue RHS = Op.getOperand(1); 14883 // (ADDE 0, 0, C) will give us a single bit. 14884 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 14885 isNullConstant(RHS)) { 14886 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 14887 return; 14888 } 14889 } 14890 break; 14891 case ARMISD::CMOV: { 14892 // Bits are known zero/one if known on the LHS and RHS. 14893 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 14894 if (Known.isUnknown()) 14895 return; 14896 14897 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 14898 Known.Zero &= KnownRHS.Zero; 14899 Known.One &= KnownRHS.One; 14900 return; 14901 } 14902 case ISD::INTRINSIC_W_CHAIN: { 14903 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 14904 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 14905 switch (IntID) { 14906 default: return; 14907 case Intrinsic::arm_ldaex: 14908 case Intrinsic::arm_ldrex: { 14909 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 14910 unsigned MemBits = VT.getScalarSizeInBits(); 14911 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 14912 return; 14913 } 14914 } 14915 } 14916 case ARMISD::BFI: { 14917 // Conservatively, we can recurse down the first operand 14918 // and just mask out all affected bits. 14919 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 14920 14921 // The operand to BFI is already a mask suitable for removing the bits it 14922 // sets. 14923 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 14924 const APInt &Mask = CI->getAPIntValue(); 14925 Known.Zero &= Mask; 14926 Known.One &= Mask; 14927 return; 14928 } 14929 case ARMISD::VGETLANEs: 14930 case ARMISD::VGETLANEu: { 14931 const SDValue &SrcSV = Op.getOperand(0); 14932 EVT VecVT = SrcSV.getValueType(); 14933 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 14934 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 14935 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 14936 assert(Pos->getAPIntValue().ult(NumSrcElts) && 14937 "VGETLANE index out of bounds"); 14938 unsigned Idx = Pos->getZExtValue(); 14939 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 14940 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 14941 14942 EVT VT = Op.getValueType(); 14943 const unsigned DstSz = VT.getScalarSizeInBits(); 14944 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 14945 (void)SrcSz; 14946 assert(SrcSz == Known.getBitWidth()); 14947 assert(DstSz > SrcSz); 14948 if (Op.getOpcode() == ARMISD::VGETLANEs) 14949 Known = Known.sext(DstSz); 14950 else { 14951 Known = Known.zext(DstSz, true /* extended bits are known zero */); 14952 } 14953 assert(DstSz == Known.getBitWidth()); 14954 break; 14955 } 14956 } 14957 } 14958 14959 bool 14960 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 14961 const APInt &DemandedAPInt, 14962 TargetLoweringOpt &TLO) const { 14963 // Delay optimization, so we don't have to deal with illegal types, or block 14964 // optimizations. 14965 if (!TLO.LegalOps) 14966 return false; 14967 14968 // Only optimize AND for now. 14969 if (Op.getOpcode() != ISD::AND) 14970 return false; 14971 14972 EVT VT = Op.getValueType(); 14973 14974 // Ignore vectors. 14975 if (VT.isVector()) 14976 return false; 14977 14978 assert(VT == MVT::i32 && "Unexpected integer type"); 14979 14980 // Make sure the RHS really is a constant. 14981 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14982 if (!C) 14983 return false; 14984 14985 unsigned Mask = C->getZExtValue(); 14986 14987 unsigned Demanded = DemandedAPInt.getZExtValue(); 14988 unsigned ShrunkMask = Mask & Demanded; 14989 unsigned ExpandedMask = Mask | ~Demanded; 14990 14991 // If the mask is all zeros, let the target-independent code replace the 14992 // result with zero. 14993 if (ShrunkMask == 0) 14994 return false; 14995 14996 // If the mask is all ones, erase the AND. (Currently, the target-independent 14997 // code won't do this, so we have to do it explicitly to avoid an infinite 14998 // loop in obscure cases.) 14999 if (ExpandedMask == ~0U) 15000 return TLO.CombineTo(Op, Op.getOperand(0)); 15001 15002 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 15003 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 15004 }; 15005 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 15006 if (NewMask == Mask) 15007 return true; 15008 SDLoc DL(Op); 15009 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 15010 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 15011 return TLO.CombineTo(Op, NewOp); 15012 }; 15013 15014 // Prefer uxtb mask. 15015 if (IsLegalMask(0xFF)) 15016 return UseMask(0xFF); 15017 15018 // Prefer uxth mask. 15019 if (IsLegalMask(0xFFFF)) 15020 return UseMask(0xFFFF); 15021 15022 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 15023 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 15024 if (ShrunkMask < 256) 15025 return UseMask(ShrunkMask); 15026 15027 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 15028 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 15029 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 15030 return UseMask(ExpandedMask); 15031 15032 // Potential improvements: 15033 // 15034 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 15035 // We could try to prefer Thumb1 immediates which can be lowered to a 15036 // two-instruction sequence. 15037 // We could try to recognize more legal ARM/Thumb2 immediates here. 15038 15039 return false; 15040 } 15041 15042 15043 //===----------------------------------------------------------------------===// 15044 // ARM Inline Assembly Support 15045 //===----------------------------------------------------------------------===// 15046 15047 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 15048 // Looking for "rev" which is V6+. 15049 if (!Subtarget->hasV6Ops()) 15050 return false; 15051 15052 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 15053 std::string AsmStr = IA->getAsmString(); 15054 SmallVector<StringRef, 4> AsmPieces; 15055 SplitString(AsmStr, AsmPieces, ";\n"); 15056 15057 switch (AsmPieces.size()) { 15058 default: return false; 15059 case 1: 15060 AsmStr = AsmPieces[0]; 15061 AsmPieces.clear(); 15062 SplitString(AsmStr, AsmPieces, " \t,"); 15063 15064 // rev $0, $1 15065 if (AsmPieces.size() == 3 && 15066 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 15067 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 15068 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 15069 if (Ty && Ty->getBitWidth() == 32) 15070 return IntrinsicLowering::LowerToByteSwap(CI); 15071 } 15072 break; 15073 } 15074 15075 return false; 15076 } 15077 15078 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 15079 // At this point, we have to lower this constraint to something else, so we 15080 // lower it to an "r" or "w". However, by doing this we will force the result 15081 // to be in register, while the X constraint is much more permissive. 15082 // 15083 // Although we are correct (we are free to emit anything, without 15084 // constraints), we might break use cases that would expect us to be more 15085 // efficient and emit something else. 15086 if (!Subtarget->hasVFP2Base()) 15087 return "r"; 15088 if (ConstraintVT.isFloatingPoint()) 15089 return "w"; 15090 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 15091 (ConstraintVT.getSizeInBits() == 64 || 15092 ConstraintVT.getSizeInBits() == 128)) 15093 return "w"; 15094 15095 return "r"; 15096 } 15097 15098 /// getConstraintType - Given a constraint letter, return the type of 15099 /// constraint it is for this target. 15100 ARMTargetLowering::ConstraintType 15101 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 15102 unsigned S = Constraint.size(); 15103 if (S == 1) { 15104 switch (Constraint[0]) { 15105 default: break; 15106 case 'l': return C_RegisterClass; 15107 case 'w': return C_RegisterClass; 15108 case 'h': return C_RegisterClass; 15109 case 'x': return C_RegisterClass; 15110 case 't': return C_RegisterClass; 15111 case 'j': return C_Immediate; // Constant for movw. 15112 // An address with a single base register. Due to the way we 15113 // currently handle addresses it is the same as an 'r' memory constraint. 15114 case 'Q': return C_Memory; 15115 } 15116 } else if (S == 2) { 15117 switch (Constraint[0]) { 15118 default: break; 15119 case 'T': return C_RegisterClass; 15120 // All 'U+' constraints are addresses. 15121 case 'U': return C_Memory; 15122 } 15123 } 15124 return TargetLowering::getConstraintType(Constraint); 15125 } 15126 15127 /// Examine constraint type and operand type and determine a weight value. 15128 /// This object must already have been set up with the operand type 15129 /// and the current alternative constraint selected. 15130 TargetLowering::ConstraintWeight 15131 ARMTargetLowering::getSingleConstraintMatchWeight( 15132 AsmOperandInfo &info, const char *constraint) const { 15133 ConstraintWeight weight = CW_Invalid; 15134 Value *CallOperandVal = info.CallOperandVal; 15135 // If we don't have a value, we can't do a match, 15136 // but allow it at the lowest weight. 15137 if (!CallOperandVal) 15138 return CW_Default; 15139 Type *type = CallOperandVal->getType(); 15140 // Look at the constraint type. 15141 switch (*constraint) { 15142 default: 15143 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15144 break; 15145 case 'l': 15146 if (type->isIntegerTy()) { 15147 if (Subtarget->isThumb()) 15148 weight = CW_SpecificReg; 15149 else 15150 weight = CW_Register; 15151 } 15152 break; 15153 case 'w': 15154 if (type->isFloatingPointTy()) 15155 weight = CW_Register; 15156 break; 15157 } 15158 return weight; 15159 } 15160 15161 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 15162 15163 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 15164 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 15165 switch (Constraint.size()) { 15166 case 1: 15167 // GCC ARM Constraint Letters 15168 switch (Constraint[0]) { 15169 case 'l': // Low regs or general regs. 15170 if (Subtarget->isThumb()) 15171 return RCPair(0U, &ARM::tGPRRegClass); 15172 return RCPair(0U, &ARM::GPRRegClass); 15173 case 'h': // High regs or no regs. 15174 if (Subtarget->isThumb()) 15175 return RCPair(0U, &ARM::hGPRRegClass); 15176 break; 15177 case 'r': 15178 if (Subtarget->isThumb1Only()) 15179 return RCPair(0U, &ARM::tGPRRegClass); 15180 return RCPair(0U, &ARM::GPRRegClass); 15181 case 'w': 15182 if (VT == MVT::Other) 15183 break; 15184 if (VT == MVT::f32) 15185 return RCPair(0U, &ARM::SPRRegClass); 15186 if (VT.getSizeInBits() == 64) 15187 return RCPair(0U, &ARM::DPRRegClass); 15188 if (VT.getSizeInBits() == 128) 15189 return RCPair(0U, &ARM::QPRRegClass); 15190 break; 15191 case 'x': 15192 if (VT == MVT::Other) 15193 break; 15194 if (VT == MVT::f32) 15195 return RCPair(0U, &ARM::SPR_8RegClass); 15196 if (VT.getSizeInBits() == 64) 15197 return RCPair(0U, &ARM::DPR_8RegClass); 15198 if (VT.getSizeInBits() == 128) 15199 return RCPair(0U, &ARM::QPR_8RegClass); 15200 break; 15201 case 't': 15202 if (VT == MVT::Other) 15203 break; 15204 if (VT == MVT::f32 || VT == MVT::i32) 15205 return RCPair(0U, &ARM::SPRRegClass); 15206 if (VT.getSizeInBits() == 64) 15207 return RCPair(0U, &ARM::DPR_VFP2RegClass); 15208 if (VT.getSizeInBits() == 128) 15209 return RCPair(0U, &ARM::QPR_VFP2RegClass); 15210 break; 15211 } 15212 break; 15213 15214 case 2: 15215 if (Constraint[0] == 'T') { 15216 switch (Constraint[1]) { 15217 default: 15218 break; 15219 case 'e': 15220 return RCPair(0U, &ARM::tGPREvenRegClass); 15221 case 'o': 15222 return RCPair(0U, &ARM::tGPROddRegClass); 15223 } 15224 } 15225 break; 15226 15227 default: 15228 break; 15229 } 15230 15231 if (StringRef("{cc}").equals_lower(Constraint)) 15232 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 15233 15234 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15235 } 15236 15237 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15238 /// vector. If it is invalid, don't add anything to Ops. 15239 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15240 std::string &Constraint, 15241 std::vector<SDValue>&Ops, 15242 SelectionDAG &DAG) const { 15243 SDValue Result; 15244 15245 // Currently only support length 1 constraints. 15246 if (Constraint.length() != 1) return; 15247 15248 char ConstraintLetter = Constraint[0]; 15249 switch (ConstraintLetter) { 15250 default: break; 15251 case 'j': 15252 case 'I': case 'J': case 'K': case 'L': 15253 case 'M': case 'N': case 'O': 15254 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 15255 if (!C) 15256 return; 15257 15258 int64_t CVal64 = C->getSExtValue(); 15259 int CVal = (int) CVal64; 15260 // None of these constraints allow values larger than 32 bits. Check 15261 // that the value fits in an int. 15262 if (CVal != CVal64) 15263 return; 15264 15265 switch (ConstraintLetter) { 15266 case 'j': 15267 // Constant suitable for movw, must be between 0 and 15268 // 65535. 15269 if (Subtarget->hasV6T2Ops()) 15270 if (CVal >= 0 && CVal <= 65535) 15271 break; 15272 return; 15273 case 'I': 15274 if (Subtarget->isThumb1Only()) { 15275 // This must be a constant between 0 and 255, for ADD 15276 // immediates. 15277 if (CVal >= 0 && CVal <= 255) 15278 break; 15279 } else if (Subtarget->isThumb2()) { 15280 // A constant that can be used as an immediate value in a 15281 // data-processing instruction. 15282 if (ARM_AM::getT2SOImmVal(CVal) != -1) 15283 break; 15284 } else { 15285 // A constant that can be used as an immediate value in a 15286 // data-processing instruction. 15287 if (ARM_AM::getSOImmVal(CVal) != -1) 15288 break; 15289 } 15290 return; 15291 15292 case 'J': 15293 if (Subtarget->isThumb1Only()) { 15294 // This must be a constant between -255 and -1, for negated ADD 15295 // immediates. This can be used in GCC with an "n" modifier that 15296 // prints the negated value, for use with SUB instructions. It is 15297 // not useful otherwise but is implemented for compatibility. 15298 if (CVal >= -255 && CVal <= -1) 15299 break; 15300 } else { 15301 // This must be a constant between -4095 and 4095. It is not clear 15302 // what this constraint is intended for. Implemented for 15303 // compatibility with GCC. 15304 if (CVal >= -4095 && CVal <= 4095) 15305 break; 15306 } 15307 return; 15308 15309 case 'K': 15310 if (Subtarget->isThumb1Only()) { 15311 // A 32-bit value where only one byte has a nonzero value. Exclude 15312 // zero to match GCC. This constraint is used by GCC internally for 15313 // constants that can be loaded with a move/shift combination. 15314 // It is not useful otherwise but is implemented for compatibility. 15315 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 15316 break; 15317 } else if (Subtarget->isThumb2()) { 15318 // A constant whose bitwise inverse can be used as an immediate 15319 // value in a data-processing instruction. This can be used in GCC 15320 // with a "B" modifier that prints the inverted value, for use with 15321 // BIC and MVN instructions. It is not useful otherwise but is 15322 // implemented for compatibility. 15323 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 15324 break; 15325 } else { 15326 // A constant whose bitwise inverse can be used as an immediate 15327 // value in a data-processing instruction. This can be used in GCC 15328 // with a "B" modifier that prints the inverted value, for use with 15329 // BIC and MVN instructions. It is not useful otherwise but is 15330 // implemented for compatibility. 15331 if (ARM_AM::getSOImmVal(~CVal) != -1) 15332 break; 15333 } 15334 return; 15335 15336 case 'L': 15337 if (Subtarget->isThumb1Only()) { 15338 // This must be a constant between -7 and 7, 15339 // for 3-operand ADD/SUB immediate instructions. 15340 if (CVal >= -7 && CVal < 7) 15341 break; 15342 } else if (Subtarget->isThumb2()) { 15343 // A constant whose negation can be used as an immediate value in a 15344 // data-processing instruction. This can be used in GCC with an "n" 15345 // modifier that prints the negated value, for use with SUB 15346 // instructions. It is not useful otherwise but is implemented for 15347 // compatibility. 15348 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 15349 break; 15350 } else { 15351 // A constant whose negation can be used as an immediate value in a 15352 // data-processing instruction. This can be used in GCC with an "n" 15353 // modifier that prints the negated value, for use with SUB 15354 // instructions. It is not useful otherwise but is implemented for 15355 // compatibility. 15356 if (ARM_AM::getSOImmVal(-CVal) != -1) 15357 break; 15358 } 15359 return; 15360 15361 case 'M': 15362 if (Subtarget->isThumb1Only()) { 15363 // This must be a multiple of 4 between 0 and 1020, for 15364 // ADD sp + immediate. 15365 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 15366 break; 15367 } else { 15368 // A power of two or a constant between 0 and 32. This is used in 15369 // GCC for the shift amount on shifted register operands, but it is 15370 // useful in general for any shift amounts. 15371 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 15372 break; 15373 } 15374 return; 15375 15376 case 'N': 15377 if (Subtarget->isThumb()) { // FIXME thumb2 15378 // This must be a constant between 0 and 31, for shift amounts. 15379 if (CVal >= 0 && CVal <= 31) 15380 break; 15381 } 15382 return; 15383 15384 case 'O': 15385 if (Subtarget->isThumb()) { // FIXME thumb2 15386 // This must be a multiple of 4 between -508 and 508, for 15387 // ADD/SUB sp = sp + immediate. 15388 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 15389 break; 15390 } 15391 return; 15392 } 15393 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 15394 break; 15395 } 15396 15397 if (Result.getNode()) { 15398 Ops.push_back(Result); 15399 return; 15400 } 15401 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15402 } 15403 15404 static RTLIB::Libcall getDivRemLibcall( 15405 const SDNode *N, MVT::SimpleValueType SVT) { 15406 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 15407 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 15408 "Unhandled Opcode in getDivRemLibcall"); 15409 bool isSigned = N->getOpcode() == ISD::SDIVREM || 15410 N->getOpcode() == ISD::SREM; 15411 RTLIB::Libcall LC; 15412 switch (SVT) { 15413 default: llvm_unreachable("Unexpected request for libcall!"); 15414 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 15415 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 15416 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 15417 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 15418 } 15419 return LC; 15420 } 15421 15422 static TargetLowering::ArgListTy getDivRemArgList( 15423 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 15424 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 15425 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 15426 "Unhandled Opcode in getDivRemArgList"); 15427 bool isSigned = N->getOpcode() == ISD::SDIVREM || 15428 N->getOpcode() == ISD::SREM; 15429 TargetLowering::ArgListTy Args; 15430 TargetLowering::ArgListEntry Entry; 15431 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15432 EVT ArgVT = N->getOperand(i).getValueType(); 15433 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 15434 Entry.Node = N->getOperand(i); 15435 Entry.Ty = ArgTy; 15436 Entry.IsSExt = isSigned; 15437 Entry.IsZExt = !isSigned; 15438 Args.push_back(Entry); 15439 } 15440 if (Subtarget->isTargetWindows() && Args.size() >= 2) 15441 std::swap(Args[0], Args[1]); 15442 return Args; 15443 } 15444 15445 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 15446 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 15447 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 15448 Subtarget->isTargetWindows()) && 15449 "Register-based DivRem lowering only"); 15450 unsigned Opcode = Op->getOpcode(); 15451 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 15452 "Invalid opcode for Div/Rem lowering"); 15453 bool isSigned = (Opcode == ISD::SDIVREM); 15454 EVT VT = Op->getValueType(0); 15455 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 15456 SDLoc dl(Op); 15457 15458 // If the target has hardware divide, use divide + multiply + subtract: 15459 // div = a / b 15460 // rem = a - b * div 15461 // return {div, rem} 15462 // This should be lowered into UDIV/SDIV + MLS later on. 15463 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 15464 : Subtarget->hasDivideInARMMode(); 15465 if (hasDivide && Op->getValueType(0).isSimple() && 15466 Op->getSimpleValueType(0) == MVT::i32) { 15467 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 15468 const SDValue Dividend = Op->getOperand(0); 15469 const SDValue Divisor = Op->getOperand(1); 15470 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 15471 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 15472 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 15473 15474 SDValue Values[2] = {Div, Rem}; 15475 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 15476 } 15477 15478 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 15479 VT.getSimpleVT().SimpleTy); 15480 SDValue InChain = DAG.getEntryNode(); 15481 15482 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 15483 DAG.getContext(), 15484 Subtarget); 15485 15486 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 15487 getPointerTy(DAG.getDataLayout())); 15488 15489 Type *RetTy = StructType::get(Ty, Ty); 15490 15491 if (Subtarget->isTargetWindows()) 15492 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 15493 15494 TargetLowering::CallLoweringInfo CLI(DAG); 15495 CLI.setDebugLoc(dl).setChain(InChain) 15496 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 15497 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 15498 15499 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 15500 return CallInfo.first; 15501 } 15502 15503 // Lowers REM using divmod helpers 15504 // see RTABI section 4.2/4.3 15505 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 15506 // Build return types (div and rem) 15507 std::vector<Type*> RetTyParams; 15508 Type *RetTyElement; 15509 15510 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 15511 default: llvm_unreachable("Unexpected request for libcall!"); 15512 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 15513 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 15514 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 15515 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 15516 } 15517 15518 RetTyParams.push_back(RetTyElement); 15519 RetTyParams.push_back(RetTyElement); 15520 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 15521 Type *RetTy = StructType::get(*DAG.getContext(), ret); 15522 15523 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 15524 SimpleTy); 15525 SDValue InChain = DAG.getEntryNode(); 15526 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 15527 Subtarget); 15528 bool isSigned = N->getOpcode() == ISD::SREM; 15529 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 15530 getPointerTy(DAG.getDataLayout())); 15531 15532 if (Subtarget->isTargetWindows()) 15533 InChain = WinDBZCheckDenominator(DAG, N, InChain); 15534 15535 // Lower call 15536 CallLoweringInfo CLI(DAG); 15537 CLI.setChain(InChain) 15538 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 15539 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 15540 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 15541 15542 // Return second (rem) result operand (first contains div) 15543 SDNode *ResNode = CallResult.first.getNode(); 15544 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 15545 return ResNode->getOperand(1); 15546 } 15547 15548 SDValue 15549 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 15550 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 15551 SDLoc DL(Op); 15552 15553 // Get the inputs. 15554 SDValue Chain = Op.getOperand(0); 15555 SDValue Size = Op.getOperand(1); 15556 15557 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 15558 "no-stack-arg-probe")) { 15559 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 15560 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 15561 Chain = SP.getValue(1); 15562 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 15563 if (Align) 15564 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 15565 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 15566 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 15567 SDValue Ops[2] = { SP, Chain }; 15568 return DAG.getMergeValues(Ops, DL); 15569 } 15570 15571 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 15572 DAG.getConstant(2, DL, MVT::i32)); 15573 15574 SDValue Flag; 15575 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 15576 Flag = Chain.getValue(1); 15577 15578 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 15579 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 15580 15581 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 15582 Chain = NewSP.getValue(1); 15583 15584 SDValue Ops[2] = { NewSP, Chain }; 15585 return DAG.getMergeValues(Ops, DL); 15586 } 15587 15588 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 15589 SDValue SrcVal = Op.getOperand(0); 15590 const unsigned DstSz = Op.getValueType().getSizeInBits(); 15591 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 15592 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 15593 "Unexpected type for custom-lowering FP_EXTEND"); 15594 15595 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 15596 "With both FP DP and 16, any FP conversion is legal!"); 15597 15598 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 15599 "With FP16, 16 to 32 conversion is legal!"); 15600 15601 // Either we are converting from 16 -> 64, without FP16 and/or 15602 // FP.double-precision or without Armv8-fp. So we must do it in two 15603 // steps. 15604 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 15605 // without FP16. So we must do a function call. 15606 SDLoc Loc(Op); 15607 RTLIB::Libcall LC; 15608 if (SrcSz == 16) { 15609 // Instruction from 16 -> 32 15610 if (Subtarget->hasFP16()) 15611 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal); 15612 // Lib call from 16 -> 32 15613 else { 15614 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32); 15615 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15616 "Unexpected type for custom-lowering FP_EXTEND"); 15617 SrcVal = 15618 makeLibCall(DAG, LC, MVT::f32, SrcVal, /*isSigned*/ false, Loc).first; 15619 } 15620 } 15621 15622 if (DstSz != 64) 15623 return SrcVal; 15624 // For sure now SrcVal is 32 bits 15625 if (Subtarget->hasFP64()) // Instruction from 32 -> 64 15626 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal); 15627 15628 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64); 15629 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15630 "Unexpected type for custom-lowering FP_EXTEND"); 15631 return makeLibCall(DAG, LC, MVT::f64, SrcVal, /*isSigned*/ false, Loc).first; 15632 } 15633 15634 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 15635 SDValue SrcVal = Op.getOperand(0); 15636 EVT SrcVT = SrcVal.getValueType(); 15637 EVT DstVT = Op.getValueType(); 15638 const unsigned DstSz = Op.getValueType().getSizeInBits(); 15639 const unsigned SrcSz = SrcVT.getSizeInBits(); 15640 (void)DstSz; 15641 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 15642 "Unexpected type for custom-lowering FP_ROUND"); 15643 15644 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 15645 "With both FP DP and 16, any FP conversion is legal!"); 15646 15647 SDLoc Loc(Op); 15648 15649 // Instruction from 32 -> 16 if hasFP16 is valid 15650 if (SrcSz == 32 && Subtarget->hasFP16()) 15651 return Op; 15652 15653 // Lib call from 32 -> 16 / 64 -> [32, 16] 15654 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 15655 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15656 "Unexpected type for custom-lowering FP_ROUND"); 15657 return makeLibCall(DAG, LC, DstVT, SrcVal, /*isSigned*/ false, Loc).first; 15658 } 15659 15660 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 15661 SelectionDAG &DAG) const { 15662 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 15663 MVT HalfT = MVT::i32; 15664 SDLoc dl(N); 15665 SDValue Hi, Lo, Tmp; 15666 15667 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 15668 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 15669 return ; 15670 15671 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 15672 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 15673 15674 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 15675 DAG.getConstant(0, dl, HalfT)); 15676 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 15677 DAG.getConstant(1, dl, HalfT)); 15678 15679 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 15680 DAG.getConstant(OpTypeBits - 1, dl, 15681 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 15682 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 15683 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 15684 SDValue(Lo.getNode(), 1)); 15685 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 15686 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 15687 15688 Results.push_back(Lo); 15689 Results.push_back(Hi); 15690 } 15691 15692 bool 15693 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15694 // The ARM target isn't yet aware of offsets. 15695 return false; 15696 } 15697 15698 bool ARM::isBitFieldInvertedMask(unsigned v) { 15699 if (v == 0xffffffff) 15700 return false; 15701 15702 // there can be 1's on either or both "outsides", all the "inside" 15703 // bits must be 0's 15704 return isShiftedMask_32(~v); 15705 } 15706 15707 /// isFPImmLegal - Returns true if the target can instruction select the 15708 /// specified FP immediate natively. If false, the legalizer will 15709 /// materialize the FP immediate as a load from a constant pool. 15710 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15711 bool ForCodeSize) const { 15712 if (!Subtarget->hasVFP3Base()) 15713 return false; 15714 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 15715 return ARM_AM::getFP16Imm(Imm) != -1; 15716 if (VT == MVT::f32) 15717 return ARM_AM::getFP32Imm(Imm) != -1; 15718 if (VT == MVT::f64 && Subtarget->hasFP64()) 15719 return ARM_AM::getFP64Imm(Imm) != -1; 15720 return false; 15721 } 15722 15723 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 15724 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 15725 /// specified in the intrinsic calls. 15726 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15727 const CallInst &I, 15728 MachineFunction &MF, 15729 unsigned Intrinsic) const { 15730 switch (Intrinsic) { 15731 case Intrinsic::arm_neon_vld1: 15732 case Intrinsic::arm_neon_vld2: 15733 case Intrinsic::arm_neon_vld3: 15734 case Intrinsic::arm_neon_vld4: 15735 case Intrinsic::arm_neon_vld2lane: 15736 case Intrinsic::arm_neon_vld3lane: 15737 case Intrinsic::arm_neon_vld4lane: 15738 case Intrinsic::arm_neon_vld2dup: 15739 case Intrinsic::arm_neon_vld3dup: 15740 case Intrinsic::arm_neon_vld4dup: { 15741 Info.opc = ISD::INTRINSIC_W_CHAIN; 15742 // Conservatively set memVT to the entire set of vectors loaded. 15743 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15744 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 15745 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15746 Info.ptrVal = I.getArgOperand(0); 15747 Info.offset = 0; 15748 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 15749 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 15750 // volatile loads with NEON intrinsics not supported 15751 Info.flags = MachineMemOperand::MOLoad; 15752 return true; 15753 } 15754 case Intrinsic::arm_neon_vld1x2: 15755 case Intrinsic::arm_neon_vld1x3: 15756 case Intrinsic::arm_neon_vld1x4: { 15757 Info.opc = ISD::INTRINSIC_W_CHAIN; 15758 // Conservatively set memVT to the entire set of vectors loaded. 15759 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15760 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 15761 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15762 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 15763 Info.offset = 0; 15764 Info.align.reset(); 15765 // volatile loads with NEON intrinsics not supported 15766 Info.flags = MachineMemOperand::MOLoad; 15767 return true; 15768 } 15769 case Intrinsic::arm_neon_vst1: 15770 case Intrinsic::arm_neon_vst2: 15771 case Intrinsic::arm_neon_vst3: 15772 case Intrinsic::arm_neon_vst4: 15773 case Intrinsic::arm_neon_vst2lane: 15774 case Intrinsic::arm_neon_vst3lane: 15775 case Intrinsic::arm_neon_vst4lane: { 15776 Info.opc = ISD::INTRINSIC_VOID; 15777 // Conservatively set memVT to the entire set of vectors stored. 15778 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15779 unsigned NumElts = 0; 15780 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 15781 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 15782 if (!ArgTy->isVectorTy()) 15783 break; 15784 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 15785 } 15786 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15787 Info.ptrVal = I.getArgOperand(0); 15788 Info.offset = 0; 15789 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 15790 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 15791 // volatile stores with NEON intrinsics not supported 15792 Info.flags = MachineMemOperand::MOStore; 15793 return true; 15794 } 15795 case Intrinsic::arm_neon_vst1x2: 15796 case Intrinsic::arm_neon_vst1x3: 15797 case Intrinsic::arm_neon_vst1x4: { 15798 Info.opc = ISD::INTRINSIC_VOID; 15799 // Conservatively set memVT to the entire set of vectors stored. 15800 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15801 unsigned NumElts = 0; 15802 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 15803 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 15804 if (!ArgTy->isVectorTy()) 15805 break; 15806 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 15807 } 15808 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15809 Info.ptrVal = I.getArgOperand(0); 15810 Info.offset = 0; 15811 Info.align.reset(); 15812 // volatile stores with NEON intrinsics not supported 15813 Info.flags = MachineMemOperand::MOStore; 15814 return true; 15815 } 15816 case Intrinsic::arm_ldaex: 15817 case Intrinsic::arm_ldrex: { 15818 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15819 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 15820 Info.opc = ISD::INTRINSIC_W_CHAIN; 15821 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15822 Info.ptrVal = I.getArgOperand(0); 15823 Info.offset = 0; 15824 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 15825 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15826 return true; 15827 } 15828 case Intrinsic::arm_stlex: 15829 case Intrinsic::arm_strex: { 15830 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15831 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 15832 Info.opc = ISD::INTRINSIC_W_CHAIN; 15833 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15834 Info.ptrVal = I.getArgOperand(1); 15835 Info.offset = 0; 15836 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 15837 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15838 return true; 15839 } 15840 case Intrinsic::arm_stlexd: 15841 case Intrinsic::arm_strexd: 15842 Info.opc = ISD::INTRINSIC_W_CHAIN; 15843 Info.memVT = MVT::i64; 15844 Info.ptrVal = I.getArgOperand(2); 15845 Info.offset = 0; 15846 Info.align = Align(8); 15847 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15848 return true; 15849 15850 case Intrinsic::arm_ldaexd: 15851 case Intrinsic::arm_ldrexd: 15852 Info.opc = ISD::INTRINSIC_W_CHAIN; 15853 Info.memVT = MVT::i64; 15854 Info.ptrVal = I.getArgOperand(0); 15855 Info.offset = 0; 15856 Info.align = Align(8); 15857 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15858 return true; 15859 15860 default: 15861 break; 15862 } 15863 15864 return false; 15865 } 15866 15867 /// Returns true if it is beneficial to convert a load of a constant 15868 /// to just the constant itself. 15869 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15870 Type *Ty) const { 15871 assert(Ty->isIntegerTy()); 15872 15873 unsigned Bits = Ty->getPrimitiveSizeInBits(); 15874 if (Bits == 0 || Bits > 32) 15875 return false; 15876 return true; 15877 } 15878 15879 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 15880 unsigned Index) const { 15881 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 15882 return false; 15883 15884 return (Index == 0 || Index == ResVT.getVectorNumElements()); 15885 } 15886 15887 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 15888 ARM_MB::MemBOpt Domain) const { 15889 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15890 15891 // First, if the target has no DMB, see what fallback we can use. 15892 if (!Subtarget->hasDataBarrier()) { 15893 // Some ARMv6 cpus can support data barriers with an mcr instruction. 15894 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 15895 // here. 15896 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 15897 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 15898 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 15899 Builder.getInt32(0), Builder.getInt32(7), 15900 Builder.getInt32(10), Builder.getInt32(5)}; 15901 return Builder.CreateCall(MCR, args); 15902 } else { 15903 // Instead of using barriers, atomic accesses on these subtargets use 15904 // libcalls. 15905 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 15906 } 15907 } else { 15908 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 15909 // Only a full system barrier exists in the M-class architectures. 15910 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 15911 Constant *CDomain = Builder.getInt32(Domain); 15912 return Builder.CreateCall(DMB, CDomain); 15913 } 15914 } 15915 15916 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 15917 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 15918 Instruction *Inst, 15919 AtomicOrdering Ord) const { 15920 switch (Ord) { 15921 case AtomicOrdering::NotAtomic: 15922 case AtomicOrdering::Unordered: 15923 llvm_unreachable("Invalid fence: unordered/non-atomic"); 15924 case AtomicOrdering::Monotonic: 15925 case AtomicOrdering::Acquire: 15926 return nullptr; // Nothing to do 15927 case AtomicOrdering::SequentiallyConsistent: 15928 if (!Inst->hasAtomicStore()) 15929 return nullptr; // Nothing to do 15930 LLVM_FALLTHROUGH; 15931 case AtomicOrdering::Release: 15932 case AtomicOrdering::AcquireRelease: 15933 if (Subtarget->preferISHSTBarriers()) 15934 return makeDMB(Builder, ARM_MB::ISHST); 15935 // FIXME: add a comment with a link to documentation justifying this. 15936 else 15937 return makeDMB(Builder, ARM_MB::ISH); 15938 } 15939 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 15940 } 15941 15942 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 15943 Instruction *Inst, 15944 AtomicOrdering Ord) const { 15945 switch (Ord) { 15946 case AtomicOrdering::NotAtomic: 15947 case AtomicOrdering::Unordered: 15948 llvm_unreachable("Invalid fence: unordered/not-atomic"); 15949 case AtomicOrdering::Monotonic: 15950 case AtomicOrdering::Release: 15951 return nullptr; // Nothing to do 15952 case AtomicOrdering::Acquire: 15953 case AtomicOrdering::AcquireRelease: 15954 case AtomicOrdering::SequentiallyConsistent: 15955 return makeDMB(Builder, ARM_MB::ISH); 15956 } 15957 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 15958 } 15959 15960 // Loads and stores less than 64-bits are already atomic; ones above that 15961 // are doomed anyway, so defer to the default libcall and blame the OS when 15962 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15963 // anything for those. 15964 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 15965 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 15966 return (Size == 64) && !Subtarget->isMClass(); 15967 } 15968 15969 // Loads and stores less than 64-bits are already atomic; ones above that 15970 // are doomed anyway, so defer to the default libcall and blame the OS when 15971 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15972 // anything for those. 15973 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 15974 // guarantee, see DDI0406C ARM architecture reference manual, 15975 // sections A8.8.72-74 LDRD) 15976 TargetLowering::AtomicExpansionKind 15977 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 15978 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 15979 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 15980 : AtomicExpansionKind::None; 15981 } 15982 15983 // For the real atomic operations, we have ldrex/strex up to 32 bits, 15984 // and up to 64 bits on the non-M profiles 15985 TargetLowering::AtomicExpansionKind 15986 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 15987 if (AI->isFloatingPointOperation()) 15988 return AtomicExpansionKind::CmpXChg; 15989 15990 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 15991 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 15992 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 15993 ? AtomicExpansionKind::LLSC 15994 : AtomicExpansionKind::None; 15995 } 15996 15997 TargetLowering::AtomicExpansionKind 15998 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 15999 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 16000 // implement cmpxchg without spilling. If the address being exchanged is also 16001 // on the stack and close enough to the spill slot, this can lead to a 16002 // situation where the monitor always gets cleared and the atomic operation 16003 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 16004 bool HasAtomicCmpXchg = 16005 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 16006 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 16007 return AtomicExpansionKind::LLSC; 16008 return AtomicExpansionKind::None; 16009 } 16010 16011 bool ARMTargetLowering::shouldInsertFencesForAtomic( 16012 const Instruction *I) const { 16013 return InsertFencesForAtomic; 16014 } 16015 16016 // This has so far only been implemented for MachO. 16017 bool ARMTargetLowering::useLoadStackGuardNode() const { 16018 return Subtarget->isTargetMachO(); 16019 } 16020 16021 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 16022 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16023 return TargetLowering::insertSSPDeclarations(M); 16024 16025 // MSVC CRT has a global variable holding security cookie. 16026 M.getOrInsertGlobal("__security_cookie", 16027 Type::getInt8PtrTy(M.getContext())); 16028 16029 // MSVC CRT has a function to validate security cookie. 16030 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 16031 "__security_check_cookie", Type::getVoidTy(M.getContext()), 16032 Type::getInt8PtrTy(M.getContext())); 16033 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 16034 F->addAttribute(1, Attribute::AttrKind::InReg); 16035 } 16036 16037 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 16038 // MSVC CRT has a global variable holding security cookie. 16039 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16040 return M.getGlobalVariable("__security_cookie"); 16041 return TargetLowering::getSDagStackGuard(M); 16042 } 16043 16044 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 16045 // MSVC CRT has a function to validate security cookie. 16046 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16047 return M.getFunction("__security_check_cookie"); 16048 return TargetLowering::getSSPStackGuardCheck(M); 16049 } 16050 16051 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 16052 unsigned &Cost) const { 16053 // If we do not have NEON, vector types are not natively supported. 16054 if (!Subtarget->hasNEON()) 16055 return false; 16056 16057 // Floating point values and vector values map to the same register file. 16058 // Therefore, although we could do a store extract of a vector type, this is 16059 // better to leave at float as we have more freedom in the addressing mode for 16060 // those. 16061 if (VectorTy->isFPOrFPVectorTy()) 16062 return false; 16063 16064 // If the index is unknown at compile time, this is very expensive to lower 16065 // and it is not possible to combine the store with the extract. 16066 if (!isa<ConstantInt>(Idx)) 16067 return false; 16068 16069 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 16070 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 16071 // We can do a store + vector extract on any vector that fits perfectly in a D 16072 // or Q register. 16073 if (BitWidth == 64 || BitWidth == 128) { 16074 Cost = 0; 16075 return true; 16076 } 16077 return false; 16078 } 16079 16080 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 16081 return Subtarget->hasV6T2Ops(); 16082 } 16083 16084 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 16085 return Subtarget->hasV6T2Ops(); 16086 } 16087 16088 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 16089 return !Subtarget->hasMinSize(); 16090 } 16091 16092 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 16093 AtomicOrdering Ord) const { 16094 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16095 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 16096 bool IsAcquire = isAcquireOrStronger(Ord); 16097 16098 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 16099 // intrinsic must return {i32, i32} and we have to recombine them into a 16100 // single i64 here. 16101 if (ValTy->getPrimitiveSizeInBits() == 64) { 16102 Intrinsic::ID Int = 16103 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 16104 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 16105 16106 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16107 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 16108 16109 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 16110 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 16111 if (!Subtarget->isLittle()) 16112 std::swap (Lo, Hi); 16113 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 16114 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 16115 return Builder.CreateOr( 16116 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 16117 } 16118 16119 Type *Tys[] = { Addr->getType() }; 16120 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 16121 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 16122 16123 return Builder.CreateTruncOrBitCast( 16124 Builder.CreateCall(Ldrex, Addr), 16125 cast<PointerType>(Addr->getType())->getElementType()); 16126 } 16127 16128 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 16129 IRBuilder<> &Builder) const { 16130 if (!Subtarget->hasV7Ops()) 16131 return; 16132 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16133 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 16134 } 16135 16136 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 16137 Value *Addr, 16138 AtomicOrdering Ord) const { 16139 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16140 bool IsRelease = isReleaseOrStronger(Ord); 16141 16142 // Since the intrinsics must have legal type, the i64 intrinsics take two 16143 // parameters: "i32, i32". We must marshal Val into the appropriate form 16144 // before the call. 16145 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 16146 Intrinsic::ID Int = 16147 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 16148 Function *Strex = Intrinsic::getDeclaration(M, Int); 16149 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 16150 16151 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 16152 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 16153 if (!Subtarget->isLittle()) 16154 std::swap(Lo, Hi); 16155 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16156 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 16157 } 16158 16159 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 16160 Type *Tys[] = { Addr->getType() }; 16161 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 16162 16163 return Builder.CreateCall( 16164 Strex, {Builder.CreateZExtOrBitCast( 16165 Val, Strex->getFunctionType()->getParamType(0)), 16166 Addr}); 16167 } 16168 16169 16170 bool ARMTargetLowering::alignLoopsWithOptSize() const { 16171 return Subtarget->isMClass(); 16172 } 16173 16174 /// A helper function for determining the number of interleaved accesses we 16175 /// will generate when lowering accesses of the given type. 16176 unsigned 16177 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 16178 const DataLayout &DL) const { 16179 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 16180 } 16181 16182 bool ARMTargetLowering::isLegalInterleavedAccessType( 16183 VectorType *VecTy, const DataLayout &DL) const { 16184 16185 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 16186 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 16187 16188 // Ensure the vector doesn't have f16 elements. Even though we could do an 16189 // i16 vldN, we can't hold the f16 vectors and will end up converting via 16190 // f32. 16191 if (VecTy->getElementType()->isHalfTy()) 16192 return false; 16193 16194 // Ensure the number of vector elements is greater than 1. 16195 if (VecTy->getNumElements() < 2) 16196 return false; 16197 16198 // Ensure the element type is legal. 16199 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 16200 return false; 16201 16202 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 16203 // 128 will be split into multiple interleaved accesses. 16204 return VecSize == 64 || VecSize % 128 == 0; 16205 } 16206 16207 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const { 16208 if (Subtarget->hasNEON()) 16209 return 4; 16210 return TargetLoweringBase::getMaxSupportedInterleaveFactor(); 16211 } 16212 16213 /// Lower an interleaved load into a vldN intrinsic. 16214 /// 16215 /// E.g. Lower an interleaved load (Factor = 2): 16216 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 16217 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 16218 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 16219 /// 16220 /// Into: 16221 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 16222 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 16223 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 16224 bool ARMTargetLowering::lowerInterleavedLoad( 16225 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 16226 ArrayRef<unsigned> Indices, unsigned Factor) const { 16227 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 16228 "Invalid interleave factor"); 16229 assert(!Shuffles.empty() && "Empty shufflevector input"); 16230 assert(Shuffles.size() == Indices.size() && 16231 "Unmatched number of shufflevectors and indices"); 16232 16233 VectorType *VecTy = Shuffles[0]->getType(); 16234 Type *EltTy = VecTy->getVectorElementType(); 16235 16236 const DataLayout &DL = LI->getModule()->getDataLayout(); 16237 16238 // Skip if we do not have NEON and skip illegal vector types. We can 16239 // "legalize" wide vector types into multiple interleaved accesses as long as 16240 // the vector types are divisible by 128. 16241 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 16242 return false; 16243 16244 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 16245 16246 // A pointer vector can not be the return type of the ldN intrinsics. Need to 16247 // load integer vectors first and then convert to pointer vectors. 16248 if (EltTy->isPointerTy()) 16249 VecTy = 16250 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 16251 16252 IRBuilder<> Builder(LI); 16253 16254 // The base address of the load. 16255 Value *BaseAddr = LI->getPointerOperand(); 16256 16257 if (NumLoads > 1) { 16258 // If we're going to generate more than one load, reset the sub-vector type 16259 // to something legal. 16260 VecTy = VectorType::get(VecTy->getVectorElementType(), 16261 VecTy->getVectorNumElements() / NumLoads); 16262 16263 // We will compute the pointer operand of each load from the original base 16264 // address using GEPs. Cast the base address to a pointer to the scalar 16265 // element type. 16266 BaseAddr = Builder.CreateBitCast( 16267 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 16268 LI->getPointerAddressSpace())); 16269 } 16270 16271 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 16272 16273 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 16274 Type *Tys[] = {VecTy, Int8Ptr}; 16275 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 16276 Intrinsic::arm_neon_vld3, 16277 Intrinsic::arm_neon_vld4}; 16278 Function *VldnFunc = 16279 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 16280 16281 // Holds sub-vectors extracted from the load intrinsic return values. The 16282 // sub-vectors are associated with the shufflevector instructions they will 16283 // replace. 16284 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 16285 16286 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 16287 // If we're generating more than one load, compute the base address of 16288 // subsequent loads as an offset from the previous. 16289 if (LoadCount > 0) 16290 BaseAddr = 16291 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 16292 VecTy->getVectorNumElements() * Factor); 16293 16294 SmallVector<Value *, 2> Ops; 16295 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 16296 Ops.push_back(Builder.getInt32(LI->getAlignment())); 16297 16298 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 16299 16300 // Replace uses of each shufflevector with the corresponding vector loaded 16301 // by ldN. 16302 for (unsigned i = 0; i < Shuffles.size(); i++) { 16303 ShuffleVectorInst *SV = Shuffles[i]; 16304 unsigned Index = Indices[i]; 16305 16306 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 16307 16308 // Convert the integer vector to pointer vector if the element is pointer. 16309 if (EltTy->isPointerTy()) 16310 SubVec = Builder.CreateIntToPtr( 16311 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 16312 VecTy->getVectorNumElements())); 16313 16314 SubVecs[SV].push_back(SubVec); 16315 } 16316 } 16317 16318 // Replace uses of the shufflevector instructions with the sub-vectors 16319 // returned by the load intrinsic. If a shufflevector instruction is 16320 // associated with more than one sub-vector, those sub-vectors will be 16321 // concatenated into a single wide vector. 16322 for (ShuffleVectorInst *SVI : Shuffles) { 16323 auto &SubVec = SubVecs[SVI]; 16324 auto *WideVec = 16325 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 16326 SVI->replaceAllUsesWith(WideVec); 16327 } 16328 16329 return true; 16330 } 16331 16332 /// Lower an interleaved store into a vstN intrinsic. 16333 /// 16334 /// E.g. Lower an interleaved store (Factor = 3): 16335 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 16336 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 16337 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 16338 /// 16339 /// Into: 16340 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 16341 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 16342 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 16343 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 16344 /// 16345 /// Note that the new shufflevectors will be removed and we'll only generate one 16346 /// vst3 instruction in CodeGen. 16347 /// 16348 /// Example for a more general valid mask (Factor 3). Lower: 16349 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 16350 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 16351 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 16352 /// 16353 /// Into: 16354 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 16355 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 16356 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 16357 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 16358 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 16359 ShuffleVectorInst *SVI, 16360 unsigned Factor) const { 16361 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 16362 "Invalid interleave factor"); 16363 16364 VectorType *VecTy = SVI->getType(); 16365 assert(VecTy->getVectorNumElements() % Factor == 0 && 16366 "Invalid interleaved store"); 16367 16368 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 16369 Type *EltTy = VecTy->getVectorElementType(); 16370 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 16371 16372 const DataLayout &DL = SI->getModule()->getDataLayout(); 16373 16374 // Skip if we do not have NEON and skip illegal vector types. We can 16375 // "legalize" wide vector types into multiple interleaved accesses as long as 16376 // the vector types are divisible by 128. 16377 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 16378 return false; 16379 16380 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 16381 16382 Value *Op0 = SVI->getOperand(0); 16383 Value *Op1 = SVI->getOperand(1); 16384 IRBuilder<> Builder(SI); 16385 16386 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 16387 // vectors to integer vectors. 16388 if (EltTy->isPointerTy()) { 16389 Type *IntTy = DL.getIntPtrType(EltTy); 16390 16391 // Convert to the corresponding integer vector. 16392 Type *IntVecTy = 16393 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 16394 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 16395 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 16396 16397 SubVecTy = VectorType::get(IntTy, LaneLen); 16398 } 16399 16400 // The base address of the store. 16401 Value *BaseAddr = SI->getPointerOperand(); 16402 16403 if (NumStores > 1) { 16404 // If we're going to generate more than one store, reset the lane length 16405 // and sub-vector type to something legal. 16406 LaneLen /= NumStores; 16407 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 16408 16409 // We will compute the pointer operand of each store from the original base 16410 // address using GEPs. Cast the base address to a pointer to the scalar 16411 // element type. 16412 BaseAddr = Builder.CreateBitCast( 16413 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 16414 SI->getPointerAddressSpace())); 16415 } 16416 16417 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 16418 16419 auto Mask = SVI->getShuffleMask(); 16420 16421 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 16422 Type *Tys[] = {Int8Ptr, SubVecTy}; 16423 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 16424 Intrinsic::arm_neon_vst3, 16425 Intrinsic::arm_neon_vst4}; 16426 16427 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 16428 // If we generating more than one store, we compute the base address of 16429 // subsequent stores as an offset from the previous. 16430 if (StoreCount > 0) 16431 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 16432 BaseAddr, LaneLen * Factor); 16433 16434 SmallVector<Value *, 6> Ops; 16435 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 16436 16437 Function *VstNFunc = 16438 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 16439 16440 // Split the shufflevector operands into sub vectors for the new vstN call. 16441 for (unsigned i = 0; i < Factor; i++) { 16442 unsigned IdxI = StoreCount * LaneLen * Factor + i; 16443 if (Mask[IdxI] >= 0) { 16444 Ops.push_back(Builder.CreateShuffleVector( 16445 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 16446 } else { 16447 unsigned StartMask = 0; 16448 for (unsigned j = 1; j < LaneLen; j++) { 16449 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 16450 if (Mask[IdxJ * Factor + IdxI] >= 0) { 16451 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 16452 break; 16453 } 16454 } 16455 // Note: If all elements in a chunk are undefs, StartMask=0! 16456 // Note: Filling undef gaps with random elements is ok, since 16457 // those elements were being written anyway (with undefs). 16458 // In the case of all undefs we're defaulting to using elems from 0 16459 // Note: StartMask cannot be negative, it's checked in 16460 // isReInterleaveMask 16461 Ops.push_back(Builder.CreateShuffleVector( 16462 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 16463 } 16464 } 16465 16466 Ops.push_back(Builder.getInt32(SI->getAlignment())); 16467 Builder.CreateCall(VstNFunc, Ops); 16468 } 16469 return true; 16470 } 16471 16472 enum HABaseType { 16473 HA_UNKNOWN = 0, 16474 HA_FLOAT, 16475 HA_DOUBLE, 16476 HA_VECT64, 16477 HA_VECT128 16478 }; 16479 16480 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 16481 uint64_t &Members) { 16482 if (auto *ST = dyn_cast<StructType>(Ty)) { 16483 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 16484 uint64_t SubMembers = 0; 16485 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 16486 return false; 16487 Members += SubMembers; 16488 } 16489 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 16490 uint64_t SubMembers = 0; 16491 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 16492 return false; 16493 Members += SubMembers * AT->getNumElements(); 16494 } else if (Ty->isFloatTy()) { 16495 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 16496 return false; 16497 Members = 1; 16498 Base = HA_FLOAT; 16499 } else if (Ty->isDoubleTy()) { 16500 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 16501 return false; 16502 Members = 1; 16503 Base = HA_DOUBLE; 16504 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 16505 Members = 1; 16506 switch (Base) { 16507 case HA_FLOAT: 16508 case HA_DOUBLE: 16509 return false; 16510 case HA_VECT64: 16511 return VT->getBitWidth() == 64; 16512 case HA_VECT128: 16513 return VT->getBitWidth() == 128; 16514 case HA_UNKNOWN: 16515 switch (VT->getBitWidth()) { 16516 case 64: 16517 Base = HA_VECT64; 16518 return true; 16519 case 128: 16520 Base = HA_VECT128; 16521 return true; 16522 default: 16523 return false; 16524 } 16525 } 16526 } 16527 16528 return (Members > 0 && Members <= 4); 16529 } 16530 16531 /// Return the correct alignment for the current calling convention. 16532 unsigned 16533 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 16534 DataLayout DL) const { 16535 if (!ArgTy->isVectorTy()) 16536 return DL.getABITypeAlignment(ArgTy); 16537 16538 // Avoid over-aligning vector parameters. It would require realigning the 16539 // stack and waste space for no real benefit. 16540 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 16541 } 16542 16543 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 16544 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 16545 /// passing according to AAPCS rules. 16546 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 16547 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 16548 if (getEffectiveCallingConv(CallConv, isVarArg) != 16549 CallingConv::ARM_AAPCS_VFP) 16550 return false; 16551 16552 HABaseType Base = HA_UNKNOWN; 16553 uint64_t Members = 0; 16554 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 16555 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 16556 16557 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 16558 return IsHA || IsIntArray; 16559 } 16560 16561 unsigned ARMTargetLowering::getExceptionPointerRegister( 16562 const Constant *PersonalityFn) const { 16563 // Platforms which do not use SjLj EH may return values in these registers 16564 // via the personality function. 16565 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 16566 } 16567 16568 unsigned ARMTargetLowering::getExceptionSelectorRegister( 16569 const Constant *PersonalityFn) const { 16570 // Platforms which do not use SjLj EH may return values in these registers 16571 // via the personality function. 16572 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 16573 } 16574 16575 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 16576 // Update IsSplitCSR in ARMFunctionInfo. 16577 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 16578 AFI->setIsSplitCSR(true); 16579 } 16580 16581 void ARMTargetLowering::insertCopiesSplitCSR( 16582 MachineBasicBlock *Entry, 16583 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 16584 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 16585 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 16586 if (!IStart) 16587 return; 16588 16589 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 16590 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 16591 MachineBasicBlock::iterator MBBI = Entry->begin(); 16592 for (const MCPhysReg *I = IStart; *I; ++I) { 16593 const TargetRegisterClass *RC = nullptr; 16594 if (ARM::GPRRegClass.contains(*I)) 16595 RC = &ARM::GPRRegClass; 16596 else if (ARM::DPRRegClass.contains(*I)) 16597 RC = &ARM::DPRRegClass; 16598 else 16599 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 16600 16601 Register NewVR = MRI->createVirtualRegister(RC); 16602 // Create copy from CSR to a virtual register. 16603 // FIXME: this currently does not emit CFI pseudo-instructions, it works 16604 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 16605 // nounwind. If we want to generalize this later, we may need to emit 16606 // CFI pseudo-instructions. 16607 assert(Entry->getParent()->getFunction().hasFnAttribute( 16608 Attribute::NoUnwind) && 16609 "Function should be nounwind in insertCopiesSplitCSR!"); 16610 Entry->addLiveIn(*I); 16611 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 16612 .addReg(*I); 16613 16614 // Insert the copy-back instructions right before the terminator. 16615 for (auto *Exit : Exits) 16616 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 16617 TII->get(TargetOpcode::COPY), *I) 16618 .addReg(NewVR); 16619 } 16620 } 16621 16622 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 16623 MF.getFrameInfo().computeMaxCallFrameSize(MF); 16624 TargetLoweringBase::finalizeLowering(MF); 16625 } 16626