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 if (!HasMVEFP) { 271 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 272 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 273 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 274 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 275 } 276 277 // Pre and Post inc are supported on loads and stores 278 for (unsigned im = (unsigned)ISD::PRE_INC; 279 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 280 setIndexedLoadAction(im, VT, Legal); 281 setIndexedStoreAction(im, VT, Legal); 282 } 283 } 284 285 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 286 for (auto VT : FloatTypes) { 287 addRegisterClass(VT, &ARM::QPRRegClass); 288 if (!HasMVEFP) 289 setAllExpand(VT); 290 291 // These are legal or custom whether we have MVE.fp or not 292 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 293 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 294 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 295 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 296 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 297 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 298 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 299 setOperationAction(ISD::SETCC, VT, Custom); 300 301 // Pre and Post inc are supported on loads and stores 302 for (unsigned im = (unsigned)ISD::PRE_INC; 303 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 304 setIndexedLoadAction(im, VT, Legal); 305 setIndexedStoreAction(im, VT, Legal); 306 } 307 308 if (HasMVEFP) { 309 setOperationAction(ISD::FMINNUM, VT, Legal); 310 setOperationAction(ISD::FMAXNUM, VT, Legal); 311 setOperationAction(ISD::FROUND, VT, Legal); 312 313 // No native support for these. 314 setOperationAction(ISD::FDIV, VT, Expand); 315 setOperationAction(ISD::FREM, VT, Expand); 316 setOperationAction(ISD::FSQRT, VT, Expand); 317 setOperationAction(ISD::FSIN, VT, Expand); 318 setOperationAction(ISD::FCOS, VT, Expand); 319 setOperationAction(ISD::FPOW, VT, Expand); 320 setOperationAction(ISD::FLOG, VT, Expand); 321 setOperationAction(ISD::FLOG2, VT, Expand); 322 setOperationAction(ISD::FLOG10, VT, Expand); 323 setOperationAction(ISD::FEXP, VT, Expand); 324 setOperationAction(ISD::FEXP2, VT, Expand); 325 setOperationAction(ISD::FNEARBYINT, VT, Expand); 326 } 327 } 328 329 // We 'support' these types up to bitcast/load/store level, regardless of 330 // MVE integer-only / float support. Only doing FP data processing on the FP 331 // vector types is inhibited at integer-only level. 332 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 333 for (auto VT : LongTypes) { 334 addRegisterClass(VT, &ARM::QPRRegClass); 335 setAllExpand(VT); 336 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 338 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 339 } 340 // We can do bitwise operations on v2i64 vectors 341 setOperationAction(ISD::AND, MVT::v2i64, Legal); 342 setOperationAction(ISD::OR, MVT::v2i64, Legal); 343 setOperationAction(ISD::XOR, MVT::v2i64, Legal); 344 345 // It is legal to extload from v4i8 to v4i16 or v4i32. 346 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 347 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 348 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 349 350 // Some truncating stores are legal too. 351 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 352 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 353 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 354 355 // Pre and Post inc on these are legal, given the correct extends 356 for (unsigned im = (unsigned)ISD::PRE_INC; 357 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 358 setIndexedLoadAction(im, MVT::v8i8, Legal); 359 setIndexedStoreAction(im, MVT::v8i8, Legal); 360 setIndexedLoadAction(im, MVT::v4i8, Legal); 361 setIndexedStoreAction(im, MVT::v4i8, Legal); 362 setIndexedLoadAction(im, MVT::v4i16, Legal); 363 setIndexedStoreAction(im, MVT::v4i16, Legal); 364 } 365 366 // Predicate types 367 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1}; 368 for (auto VT : pTypes) { 369 addRegisterClass(VT, &ARM::VCCRRegClass); 370 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 371 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 372 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 373 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 374 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 375 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 376 setOperationAction(ISD::SETCC, VT, Custom); 377 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 378 } 379 } 380 381 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 382 const ARMSubtarget &STI) 383 : TargetLowering(TM), Subtarget(&STI) { 384 RegInfo = Subtarget->getRegisterInfo(); 385 Itins = Subtarget->getInstrItineraryData(); 386 387 setBooleanContents(ZeroOrOneBooleanContent); 388 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 389 390 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 391 !Subtarget->isTargetWatchOS()) { 392 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 393 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 394 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 395 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 396 : CallingConv::ARM_AAPCS); 397 } 398 399 if (Subtarget->isTargetMachO()) { 400 // Uses VFP for Thumb libfuncs if available. 401 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 402 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 403 static const struct { 404 const RTLIB::Libcall Op; 405 const char * const Name; 406 const ISD::CondCode Cond; 407 } LibraryCalls[] = { 408 // Single-precision floating-point arithmetic. 409 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 410 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 411 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 412 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 413 414 // Double-precision floating-point arithmetic. 415 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 416 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 417 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 418 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 419 420 // Single-precision comparisons. 421 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 422 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 423 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 424 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 425 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 426 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 427 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 428 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 429 430 // Double-precision comparisons. 431 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 432 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 433 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 434 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 435 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 436 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 437 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 438 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 439 440 // Floating-point to integer conversions. 441 // i64 conversions are done via library routines even when generating VFP 442 // instructions, so use the same ones. 443 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 444 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 445 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 446 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 447 448 // Conversions between floating types. 449 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 450 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 451 452 // Integer to floating-point conversions. 453 // i64 conversions are done via library routines even when generating VFP 454 // instructions, so use the same ones. 455 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 456 // e.g., __floatunsidf vs. __floatunssidfvfp. 457 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 458 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 459 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 460 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 461 }; 462 463 for (const auto &LC : LibraryCalls) { 464 setLibcallName(LC.Op, LC.Name); 465 if (LC.Cond != ISD::SETCC_INVALID) 466 setCmpLibcallCC(LC.Op, LC.Cond); 467 } 468 } 469 } 470 471 // These libcalls are not available in 32-bit. 472 setLibcallName(RTLIB::SHL_I128, nullptr); 473 setLibcallName(RTLIB::SRL_I128, nullptr); 474 setLibcallName(RTLIB::SRA_I128, nullptr); 475 476 // RTLIB 477 if (Subtarget->isAAPCS_ABI() && 478 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 479 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 480 static const struct { 481 const RTLIB::Libcall Op; 482 const char * const Name; 483 const CallingConv::ID CC; 484 const ISD::CondCode Cond; 485 } LibraryCalls[] = { 486 // Double-precision floating-point arithmetic helper functions 487 // RTABI chapter 4.1.2, Table 2 488 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 489 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 490 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 491 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 492 493 // Double-precision floating-point comparison helper functions 494 // RTABI chapter 4.1.2, Table 3 495 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 496 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 497 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 498 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 499 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 500 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 501 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 502 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 503 504 // Single-precision floating-point arithmetic helper functions 505 // RTABI chapter 4.1.2, Table 4 506 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 507 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 508 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 509 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 510 511 // Single-precision floating-point comparison helper functions 512 // RTABI chapter 4.1.2, Table 5 513 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 514 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 515 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 516 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 517 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 518 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 519 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 520 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 521 522 // Floating-point to integer conversions. 523 // RTABI chapter 4.1.2, Table 6 524 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 525 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 526 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 527 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 528 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 529 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 530 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 531 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 532 533 // Conversions between floating types. 534 // RTABI chapter 4.1.2, Table 7 535 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 536 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 537 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 538 539 // Integer to floating-point conversions. 540 // RTABI chapter 4.1.2, Table 8 541 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 542 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 543 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 544 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 545 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 546 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 547 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 548 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 549 550 // Long long helper functions 551 // RTABI chapter 4.2, Table 9 552 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 553 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 554 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 555 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 556 557 // Integer division functions 558 // RTABI chapter 4.3.1 559 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 560 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 561 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 562 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 563 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 564 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 565 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 566 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 567 }; 568 569 for (const auto &LC : LibraryCalls) { 570 setLibcallName(LC.Op, LC.Name); 571 setLibcallCallingConv(LC.Op, LC.CC); 572 if (LC.Cond != ISD::SETCC_INVALID) 573 setCmpLibcallCC(LC.Op, LC.Cond); 574 } 575 576 // EABI dependent RTLIB 577 if (TM.Options.EABIVersion == EABI::EABI4 || 578 TM.Options.EABIVersion == EABI::EABI5) { 579 static const struct { 580 const RTLIB::Libcall Op; 581 const char *const Name; 582 const CallingConv::ID CC; 583 const ISD::CondCode Cond; 584 } MemOpsLibraryCalls[] = { 585 // Memory operations 586 // RTABI chapter 4.3.4 587 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 588 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 589 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 590 }; 591 592 for (const auto &LC : MemOpsLibraryCalls) { 593 setLibcallName(LC.Op, LC.Name); 594 setLibcallCallingConv(LC.Op, LC.CC); 595 if (LC.Cond != ISD::SETCC_INVALID) 596 setCmpLibcallCC(LC.Op, LC.Cond); 597 } 598 } 599 } 600 601 if (Subtarget->isTargetWindows()) { 602 static const struct { 603 const RTLIB::Libcall Op; 604 const char * const Name; 605 const CallingConv::ID CC; 606 } LibraryCalls[] = { 607 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 608 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 609 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 610 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 611 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 612 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 613 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 614 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 615 }; 616 617 for (const auto &LC : LibraryCalls) { 618 setLibcallName(LC.Op, LC.Name); 619 setLibcallCallingConv(LC.Op, LC.CC); 620 } 621 } 622 623 // Use divmod compiler-rt calls for iOS 5.0 and later. 624 if (Subtarget->isTargetMachO() && 625 !(Subtarget->isTargetIOS() && 626 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 627 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 628 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 629 } 630 631 // The half <-> float conversion functions are always soft-float on 632 // non-watchos platforms, but are needed for some targets which use a 633 // hard-float calling convention by default. 634 if (!Subtarget->isTargetWatchABI()) { 635 if (Subtarget->isAAPCS_ABI()) { 636 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 637 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 638 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 639 } else { 640 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 641 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 642 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 643 } 644 } 645 646 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 647 // a __gnu_ prefix (which is the default). 648 if (Subtarget->isTargetAEABI()) { 649 static const struct { 650 const RTLIB::Libcall Op; 651 const char * const Name; 652 const CallingConv::ID CC; 653 } LibraryCalls[] = { 654 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 655 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 656 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 657 }; 658 659 for (const auto &LC : LibraryCalls) { 660 setLibcallName(LC.Op, LC.Name); 661 setLibcallCallingConv(LC.Op, LC.CC); 662 } 663 } 664 665 if (Subtarget->isThumb1Only()) 666 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 667 else 668 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 669 670 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 671 Subtarget->hasFPRegs()) { 672 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 673 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 674 if (!Subtarget->hasVFP2Base()) 675 setAllExpand(MVT::f32); 676 if (!Subtarget->hasFP64()) 677 setAllExpand(MVT::f64); 678 } 679 680 if (Subtarget->hasFullFP16()) { 681 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 682 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 683 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 684 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 685 686 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 687 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 688 } 689 690 for (MVT VT : MVT::vector_valuetypes()) { 691 for (MVT InnerVT : MVT::vector_valuetypes()) { 692 setTruncStoreAction(VT, InnerVT, Expand); 693 addAllExtLoads(VT, InnerVT, Expand); 694 } 695 696 setOperationAction(ISD::MULHS, VT, Expand); 697 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 698 setOperationAction(ISD::MULHU, VT, Expand); 699 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 700 701 setOperationAction(ISD::BSWAP, VT, Expand); 702 } 703 704 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 705 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 706 707 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 708 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 709 710 if (Subtarget->hasMVEIntegerOps()) 711 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 712 713 // Combine low-overhead loop intrinsics so that we can lower i1 types. 714 if (Subtarget->hasLOB()) { 715 setTargetDAGCombine(ISD::BRCOND); 716 setTargetDAGCombine(ISD::BR_CC); 717 } 718 719 if (Subtarget->hasNEON()) { 720 addDRTypeForNEON(MVT::v2f32); 721 addDRTypeForNEON(MVT::v8i8); 722 addDRTypeForNEON(MVT::v4i16); 723 addDRTypeForNEON(MVT::v2i32); 724 addDRTypeForNEON(MVT::v1i64); 725 726 addQRTypeForNEON(MVT::v4f32); 727 addQRTypeForNEON(MVT::v2f64); 728 addQRTypeForNEON(MVT::v16i8); 729 addQRTypeForNEON(MVT::v8i16); 730 addQRTypeForNEON(MVT::v4i32); 731 addQRTypeForNEON(MVT::v2i64); 732 733 if (Subtarget->hasFullFP16()) { 734 addQRTypeForNEON(MVT::v8f16); 735 addDRTypeForNEON(MVT::v4f16); 736 } 737 } 738 739 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 740 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 741 // none of Neon, MVE or VFP supports any arithmetic operations on it. 742 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 743 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 744 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 745 // FIXME: Code duplication: FDIV and FREM are expanded always, see 746 // ARMTargetLowering::addTypeForNEON method for details. 747 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 748 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 749 // FIXME: Create unittest. 750 // In another words, find a way when "copysign" appears in DAG with vector 751 // operands. 752 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 753 // FIXME: Code duplication: SETCC has custom operation action, see 754 // ARMTargetLowering::addTypeForNEON method for details. 755 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 756 // FIXME: Create unittest for FNEG and for FABS. 757 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 758 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 759 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 760 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 761 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 762 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 763 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 764 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 765 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 766 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 767 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 768 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 769 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 770 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 771 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 772 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 773 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 774 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 775 } 776 777 if (Subtarget->hasNEON()) { 778 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 779 // supported for v4f32. 780 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 781 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 782 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 783 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 784 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 785 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 786 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 787 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 788 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 789 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 790 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 791 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 792 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 793 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 794 795 // Mark v2f32 intrinsics. 796 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 797 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 798 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 799 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 800 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 801 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 802 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 803 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 804 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 805 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 806 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 807 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 808 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 809 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 810 811 // Neon does not support some operations on v1i64 and v2i64 types. 812 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 813 // Custom handling for some quad-vector types to detect VMULL. 814 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 815 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 816 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 817 // Custom handling for some vector types to avoid expensive expansions 818 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 819 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 820 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 821 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 822 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 823 // a destination type that is wider than the source, and nor does 824 // it have a FP_TO_[SU]INT instruction with a narrower destination than 825 // source. 826 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 827 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 828 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 829 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 830 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 831 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 832 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 833 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 834 835 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 836 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 837 838 // NEON does not have single instruction CTPOP for vectors with element 839 // types wider than 8-bits. However, custom lowering can leverage the 840 // v8i8/v16i8 vcnt instruction. 841 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 842 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 843 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 844 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 845 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 846 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 847 848 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 849 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 850 851 // NEON does not have single instruction CTTZ for vectors. 852 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 853 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 854 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 855 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 856 857 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 858 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 859 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 860 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 861 862 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 863 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 864 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 865 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 866 867 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 868 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 869 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 870 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 871 872 // NEON only has FMA instructions as of VFP4. 873 if (!Subtarget->hasVFP4Base()) { 874 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 875 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 876 } 877 878 setTargetDAGCombine(ISD::INTRINSIC_VOID); 879 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 880 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 881 setTargetDAGCombine(ISD::SHL); 882 setTargetDAGCombine(ISD::SRL); 883 setTargetDAGCombine(ISD::SRA); 884 setTargetDAGCombine(ISD::SIGN_EXTEND); 885 setTargetDAGCombine(ISD::ZERO_EXTEND); 886 setTargetDAGCombine(ISD::ANY_EXTEND); 887 setTargetDAGCombine(ISD::STORE); 888 setTargetDAGCombine(ISD::FP_TO_SINT); 889 setTargetDAGCombine(ISD::FP_TO_UINT); 890 setTargetDAGCombine(ISD::FDIV); 891 setTargetDAGCombine(ISD::LOAD); 892 893 // It is legal to extload from v4i8 to v4i16 or v4i32. 894 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 895 MVT::v2i32}) { 896 for (MVT VT : MVT::integer_vector_valuetypes()) { 897 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 898 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 899 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 900 } 901 } 902 } 903 904 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 905 setTargetDAGCombine(ISD::BUILD_VECTOR); 906 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 907 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 908 } 909 910 if (!Subtarget->hasFP64()) { 911 // When targeting a floating-point unit with only single-precision 912 // operations, f64 is legal for the few double-precision instructions which 913 // are present However, no double-precision operations other than moves, 914 // loads and stores are provided by the hardware. 915 setOperationAction(ISD::FADD, MVT::f64, Expand); 916 setOperationAction(ISD::FSUB, MVT::f64, Expand); 917 setOperationAction(ISD::FMUL, MVT::f64, Expand); 918 setOperationAction(ISD::FMA, MVT::f64, Expand); 919 setOperationAction(ISD::FDIV, MVT::f64, Expand); 920 setOperationAction(ISD::FREM, MVT::f64, Expand); 921 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 922 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 923 setOperationAction(ISD::FNEG, MVT::f64, Expand); 924 setOperationAction(ISD::FABS, MVT::f64, Expand); 925 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 926 setOperationAction(ISD::FSIN, MVT::f64, Expand); 927 setOperationAction(ISD::FCOS, MVT::f64, Expand); 928 setOperationAction(ISD::FPOW, MVT::f64, Expand); 929 setOperationAction(ISD::FLOG, MVT::f64, Expand); 930 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 931 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 932 setOperationAction(ISD::FEXP, MVT::f64, Expand); 933 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 934 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 935 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 936 setOperationAction(ISD::FRINT, MVT::f64, Expand); 937 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 938 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 939 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 940 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 941 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 942 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 943 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 944 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 945 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 946 } 947 948 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 949 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 950 if (Subtarget->hasFullFP16()) 951 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 952 } 953 954 if (!Subtarget->hasFP16()) 955 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 956 957 if (!Subtarget->hasFP64()) 958 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 959 960 computeRegisterProperties(Subtarget->getRegisterInfo()); 961 962 // ARM does not have floating-point extending loads. 963 for (MVT VT : MVT::fp_valuetypes()) { 964 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 965 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 966 } 967 968 // ... or truncating stores 969 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 970 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 971 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 972 973 // ARM does not have i1 sign extending load. 974 for (MVT VT : MVT::integer_valuetypes()) 975 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 976 977 // ARM supports all 4 flavors of integer indexed load / store. 978 if (!Subtarget->isThumb1Only()) { 979 for (unsigned im = (unsigned)ISD::PRE_INC; 980 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 981 setIndexedLoadAction(im, MVT::i1, Legal); 982 setIndexedLoadAction(im, MVT::i8, Legal); 983 setIndexedLoadAction(im, MVT::i16, Legal); 984 setIndexedLoadAction(im, MVT::i32, Legal); 985 setIndexedStoreAction(im, MVT::i1, Legal); 986 setIndexedStoreAction(im, MVT::i8, Legal); 987 setIndexedStoreAction(im, MVT::i16, Legal); 988 setIndexedStoreAction(im, MVT::i32, Legal); 989 } 990 } else { 991 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 992 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 993 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 994 } 995 996 setOperationAction(ISD::SADDO, MVT::i32, Custom); 997 setOperationAction(ISD::UADDO, MVT::i32, Custom); 998 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 999 setOperationAction(ISD::USUBO, MVT::i32, Custom); 1000 1001 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 1002 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 1003 1004 // i64 operation support. 1005 setOperationAction(ISD::MUL, MVT::i64, Expand); 1006 setOperationAction(ISD::MULHU, MVT::i32, Expand); 1007 if (Subtarget->isThumb1Only()) { 1008 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 1009 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 1010 } 1011 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 1012 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 1013 setOperationAction(ISD::MULHS, MVT::i32, Expand); 1014 1015 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 1016 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 1017 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 1018 setOperationAction(ISD::SRL, MVT::i64, Custom); 1019 setOperationAction(ISD::SRA, MVT::i64, Custom); 1020 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 1021 1022 // MVE lowers 64 bit shifts to lsll and lsrl 1023 // assuming that ISD::SRL and SRA of i64 are already marked custom 1024 if (Subtarget->hasMVEIntegerOps()) 1025 setOperationAction(ISD::SHL, MVT::i64, Custom); 1026 1027 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1028 if (Subtarget->isThumb1Only()) { 1029 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1030 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1031 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1032 } 1033 1034 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1035 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1036 1037 // ARM does not have ROTL. 1038 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1039 for (MVT VT : MVT::vector_valuetypes()) { 1040 setOperationAction(ISD::ROTL, VT, Expand); 1041 setOperationAction(ISD::ROTR, VT, Expand); 1042 } 1043 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1044 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1045 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1046 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1047 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1048 } 1049 1050 // @llvm.readcyclecounter requires the Performance Monitors extension. 1051 // Default to the 0 expansion on unsupported platforms. 1052 // FIXME: Technically there are older ARM CPUs that have 1053 // implementation-specific ways of obtaining this information. 1054 if (Subtarget->hasPerfMon()) 1055 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1056 1057 // Only ARMv6 has BSWAP. 1058 if (!Subtarget->hasV6Ops()) 1059 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1060 1061 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1062 : Subtarget->hasDivideInARMMode(); 1063 if (!hasDivide) { 1064 // These are expanded into libcalls if the cpu doesn't have HW divider. 1065 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1066 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1067 } 1068 1069 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1070 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1071 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1072 1073 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1074 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1075 } 1076 1077 setOperationAction(ISD::SREM, MVT::i32, Expand); 1078 setOperationAction(ISD::UREM, MVT::i32, Expand); 1079 1080 // Register based DivRem for AEABI (RTABI 4.2) 1081 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1082 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1083 Subtarget->isTargetWindows()) { 1084 setOperationAction(ISD::SREM, MVT::i64, Custom); 1085 setOperationAction(ISD::UREM, MVT::i64, Custom); 1086 HasStandaloneRem = false; 1087 1088 if (Subtarget->isTargetWindows()) { 1089 const struct { 1090 const RTLIB::Libcall Op; 1091 const char * const Name; 1092 const CallingConv::ID CC; 1093 } LibraryCalls[] = { 1094 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1095 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1096 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1097 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1098 1099 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1100 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1101 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1102 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1103 }; 1104 1105 for (const auto &LC : LibraryCalls) { 1106 setLibcallName(LC.Op, LC.Name); 1107 setLibcallCallingConv(LC.Op, LC.CC); 1108 } 1109 } else { 1110 const struct { 1111 const RTLIB::Libcall Op; 1112 const char * const Name; 1113 const CallingConv::ID CC; 1114 } LibraryCalls[] = { 1115 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1116 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1117 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1118 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1119 1120 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1121 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1122 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1123 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1124 }; 1125 1126 for (const auto &LC : LibraryCalls) { 1127 setLibcallName(LC.Op, LC.Name); 1128 setLibcallCallingConv(LC.Op, LC.CC); 1129 } 1130 } 1131 1132 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1133 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1134 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1135 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1136 } else { 1137 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1138 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1139 } 1140 1141 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 1142 for (auto &VT : {MVT::f32, MVT::f64}) 1143 setOperationAction(ISD::FPOWI, VT, Custom); 1144 1145 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1146 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1147 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1148 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1149 1150 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1151 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1152 1153 // Use the default implementation. 1154 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1155 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1156 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1157 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1158 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1159 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1160 1161 if (Subtarget->isTargetWindows()) 1162 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1163 else 1164 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1165 1166 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1167 // the default expansion. 1168 InsertFencesForAtomic = false; 1169 if (Subtarget->hasAnyDataBarrier() && 1170 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1171 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1172 // to ldrex/strex loops already. 1173 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1174 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1175 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1176 1177 // On v8, we have particularly efficient implementations of atomic fences 1178 // if they can be combined with nearby atomic loads and stores. 1179 if (!Subtarget->hasAcquireRelease() || 1180 getTargetMachine().getOptLevel() == 0) { 1181 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1182 InsertFencesForAtomic = true; 1183 } 1184 } else { 1185 // If there's anything we can use as a barrier, go through custom lowering 1186 // for ATOMIC_FENCE. 1187 // If target has DMB in thumb, Fences can be inserted. 1188 if (Subtarget->hasDataBarrier()) 1189 InsertFencesForAtomic = true; 1190 1191 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1192 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1193 1194 // Set them all for expansion, which will force libcalls. 1195 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1196 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1197 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1198 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1199 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1200 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1201 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1202 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1203 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1204 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1205 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1206 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1207 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1208 // Unordered/Monotonic case. 1209 if (!InsertFencesForAtomic) { 1210 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1211 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1212 } 1213 } 1214 1215 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1216 1217 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1218 if (!Subtarget->hasV6Ops()) { 1219 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1220 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1221 } 1222 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1223 1224 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1225 !Subtarget->isThumb1Only()) { 1226 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1227 // iff target supports vfp2. 1228 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1229 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1230 } 1231 1232 // We want to custom lower some of our intrinsics. 1233 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1234 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1235 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1236 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1237 if (Subtarget->useSjLjEH()) 1238 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1239 1240 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1241 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1242 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1243 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1244 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1245 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1246 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1247 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1248 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1249 if (Subtarget->hasFullFP16()) { 1250 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1251 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1252 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1253 } 1254 1255 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1256 1257 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1258 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1259 if (Subtarget->hasFullFP16()) 1260 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1261 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1262 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1263 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1264 1265 // We don't support sin/cos/fmod/copysign/pow 1266 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1267 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1268 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1269 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1270 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1271 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1272 setOperationAction(ISD::FREM, MVT::f64, Expand); 1273 setOperationAction(ISD::FREM, MVT::f32, Expand); 1274 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1275 !Subtarget->isThumb1Only()) { 1276 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1277 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1278 } 1279 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1280 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1281 1282 if (!Subtarget->hasVFP4Base()) { 1283 setOperationAction(ISD::FMA, MVT::f64, Expand); 1284 setOperationAction(ISD::FMA, MVT::f32, Expand); 1285 } 1286 1287 // Various VFP goodness 1288 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1289 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1290 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1291 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1292 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1293 } 1294 1295 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1296 if (!Subtarget->hasFP16()) { 1297 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1298 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1299 } 1300 } 1301 1302 // Use __sincos_stret if available. 1303 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1304 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1305 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1306 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1307 } 1308 1309 // FP-ARMv8 implements a lot of rounding-like FP operations. 1310 if (Subtarget->hasFPARMv8Base()) { 1311 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1312 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1313 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1314 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1315 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1316 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1317 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1318 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1319 if (Subtarget->hasNEON()) { 1320 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1321 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1322 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1323 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1324 } 1325 1326 if (Subtarget->hasFP64()) { 1327 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1328 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1329 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1330 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1331 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1332 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1333 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1334 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1335 } 1336 } 1337 1338 // FP16 often need to be promoted to call lib functions 1339 if (Subtarget->hasFullFP16()) { 1340 setOperationAction(ISD::FREM, MVT::f16, Promote); 1341 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1342 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1343 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1344 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1345 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1346 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1347 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1348 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1349 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1350 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1351 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1352 1353 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1354 } 1355 1356 if (Subtarget->hasNEON()) { 1357 // vmin and vmax aren't available in a scalar form, so we use 1358 // a NEON instruction with an undef lane instead. 1359 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1360 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1361 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1362 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1363 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1364 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1365 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1366 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1367 1368 if (Subtarget->hasFullFP16()) { 1369 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1370 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1371 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1372 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1373 1374 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1375 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1376 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1377 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1378 } 1379 } 1380 1381 // We have target-specific dag combine patterns for the following nodes: 1382 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1383 setTargetDAGCombine(ISD::ADD); 1384 setTargetDAGCombine(ISD::SUB); 1385 setTargetDAGCombine(ISD::MUL); 1386 setTargetDAGCombine(ISD::AND); 1387 setTargetDAGCombine(ISD::OR); 1388 setTargetDAGCombine(ISD::XOR); 1389 1390 if (Subtarget->hasV6Ops()) 1391 setTargetDAGCombine(ISD::SRL); 1392 if (Subtarget->isThumb1Only()) 1393 setTargetDAGCombine(ISD::SHL); 1394 1395 setStackPointerRegisterToSaveRestore(ARM::SP); 1396 1397 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1398 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1399 setSchedulingPreference(Sched::RegPressure); 1400 else 1401 setSchedulingPreference(Sched::Hybrid); 1402 1403 //// temporary - rewrite interface to use type 1404 MaxStoresPerMemset = 8; 1405 MaxStoresPerMemsetOptSize = 4; 1406 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1407 MaxStoresPerMemcpyOptSize = 2; 1408 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1409 MaxStoresPerMemmoveOptSize = 2; 1410 1411 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1412 // are at least 4 bytes aligned. 1413 setMinStackArgumentAlignment(4); 1414 1415 // Prefer likely predicted branches to selects on out-of-order cores. 1416 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1417 1418 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment()); 1419 1420 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1421 1422 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1423 setTargetDAGCombine(ISD::ABS); 1424 } 1425 1426 bool ARMTargetLowering::useSoftFloat() const { 1427 return Subtarget->useSoftFloat(); 1428 } 1429 1430 // FIXME: It might make sense to define the representative register class as the 1431 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1432 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1433 // SPR's representative would be DPR_VFP2. This should work well if register 1434 // pressure tracking were modified such that a register use would increment the 1435 // pressure of the register class's representative and all of it's super 1436 // classes' representatives transitively. We have not implemented this because 1437 // of the difficulty prior to coalescing of modeling operand register classes 1438 // due to the common occurrence of cross class copies and subregister insertions 1439 // and extractions. 1440 std::pair<const TargetRegisterClass *, uint8_t> 1441 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1442 MVT VT) const { 1443 const TargetRegisterClass *RRC = nullptr; 1444 uint8_t Cost = 1; 1445 switch (VT.SimpleTy) { 1446 default: 1447 return TargetLowering::findRepresentativeClass(TRI, VT); 1448 // Use DPR as representative register class for all floating point 1449 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1450 // the cost is 1 for both f32 and f64. 1451 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1452 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1453 RRC = &ARM::DPRRegClass; 1454 // When NEON is used for SP, only half of the register file is available 1455 // because operations that define both SP and DP results will be constrained 1456 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1457 // coalescing by double-counting the SP regs. See the FIXME above. 1458 if (Subtarget->useNEONForSinglePrecisionFP()) 1459 Cost = 2; 1460 break; 1461 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1462 case MVT::v4f32: case MVT::v2f64: 1463 RRC = &ARM::DPRRegClass; 1464 Cost = 2; 1465 break; 1466 case MVT::v4i64: 1467 RRC = &ARM::DPRRegClass; 1468 Cost = 4; 1469 break; 1470 case MVT::v8i64: 1471 RRC = &ARM::DPRRegClass; 1472 Cost = 8; 1473 break; 1474 } 1475 return std::make_pair(RRC, Cost); 1476 } 1477 1478 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1479 switch ((ARMISD::NodeType)Opcode) { 1480 case ARMISD::FIRST_NUMBER: break; 1481 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1482 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1483 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1484 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1485 case ARMISD::CALL: return "ARMISD::CALL"; 1486 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1487 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1488 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1489 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1490 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1491 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1492 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1493 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1494 case ARMISD::CMP: return "ARMISD::CMP"; 1495 case ARMISD::CMN: return "ARMISD::CMN"; 1496 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1497 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1498 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1499 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1500 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1501 1502 case ARMISD::CMOV: return "ARMISD::CMOV"; 1503 case ARMISD::SUBS: return "ARMISD::SUBS"; 1504 1505 case ARMISD::SSAT: return "ARMISD::SSAT"; 1506 case ARMISD::USAT: return "ARMISD::USAT"; 1507 1508 case ARMISD::ASRL: return "ARMISD::ASRL"; 1509 case ARMISD::LSRL: return "ARMISD::LSRL"; 1510 case ARMISD::LSLL: return "ARMISD::LSLL"; 1511 1512 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1513 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1514 case ARMISD::RRX: return "ARMISD::RRX"; 1515 1516 case ARMISD::ADDC: return "ARMISD::ADDC"; 1517 case ARMISD::ADDE: return "ARMISD::ADDE"; 1518 case ARMISD::SUBC: return "ARMISD::SUBC"; 1519 case ARMISD::SUBE: return "ARMISD::SUBE"; 1520 case ARMISD::LSLS: return "ARMISD::LSLS"; 1521 1522 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1523 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1524 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1525 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1526 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1527 1528 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1529 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1530 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1531 1532 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1533 1534 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1535 1536 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1537 1538 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1539 1540 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1541 1542 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1543 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1544 1545 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST"; 1546 case ARMISD::VCMP: return "ARMISD::VCMP"; 1547 case ARMISD::VCMPZ: return "ARMISD::VCMPZ"; 1548 case ARMISD::VTST: return "ARMISD::VTST"; 1549 1550 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1551 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1552 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1553 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1554 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1555 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1556 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1557 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1558 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1559 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1560 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1561 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1562 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1563 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1564 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1565 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1566 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1567 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1568 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1569 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1570 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1571 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1572 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1573 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1574 case ARMISD::VDUP: return "ARMISD::VDUP"; 1575 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1576 case ARMISD::VEXT: return "ARMISD::VEXT"; 1577 case ARMISD::VREV64: return "ARMISD::VREV64"; 1578 case ARMISD::VREV32: return "ARMISD::VREV32"; 1579 case ARMISD::VREV16: return "ARMISD::VREV16"; 1580 case ARMISD::VZIP: return "ARMISD::VZIP"; 1581 case ARMISD::VUZP: return "ARMISD::VUZP"; 1582 case ARMISD::VTRN: return "ARMISD::VTRN"; 1583 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1584 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1585 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1586 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1587 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1588 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1589 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1590 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1591 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1592 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1593 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1594 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1595 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1596 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1597 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1598 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1599 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1600 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1601 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1602 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1603 case ARMISD::BFI: return "ARMISD::BFI"; 1604 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1605 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1606 case ARMISD::VBSL: return "ARMISD::VBSL"; 1607 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1608 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1609 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1610 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1611 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1612 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1613 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1614 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1615 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1616 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1617 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1618 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1619 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1620 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1621 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1622 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1623 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1624 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1625 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1626 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1627 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1628 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1629 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1630 case ARMISD::WLS: return "ARMISD::WLS"; 1631 case ARMISD::LE: return "ARMISD::LE"; 1632 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1633 } 1634 return nullptr; 1635 } 1636 1637 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1638 EVT VT) const { 1639 if (!VT.isVector()) 1640 return getPointerTy(DL); 1641 1642 // MVE has a predicate register. 1643 if (Subtarget->hasMVEIntegerOps() && 1644 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1645 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1646 return VT.changeVectorElementTypeToInteger(); 1647 } 1648 1649 /// getRegClassFor - Return the register class that should be used for the 1650 /// specified value type. 1651 const TargetRegisterClass * 1652 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1653 (void)isDivergent; 1654 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1655 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1656 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1657 // MVE Q registers. 1658 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1659 if (VT == MVT::v4i64) 1660 return &ARM::QQPRRegClass; 1661 if (VT == MVT::v8i64) 1662 return &ARM::QQQQPRRegClass; 1663 } 1664 return TargetLowering::getRegClassFor(VT); 1665 } 1666 1667 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1668 // source/dest is aligned and the copy size is large enough. We therefore want 1669 // to align such objects passed to memory intrinsics. 1670 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1671 unsigned &PrefAlign) const { 1672 if (!isa<MemIntrinsic>(CI)) 1673 return false; 1674 MinSize = 8; 1675 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1676 // cycle faster than 4-byte aligned LDM. 1677 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1678 return true; 1679 } 1680 1681 // Create a fast isel object. 1682 FastISel * 1683 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1684 const TargetLibraryInfo *libInfo) const { 1685 return ARM::createFastISel(funcInfo, libInfo); 1686 } 1687 1688 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1689 unsigned NumVals = N->getNumValues(); 1690 if (!NumVals) 1691 return Sched::RegPressure; 1692 1693 for (unsigned i = 0; i != NumVals; ++i) { 1694 EVT VT = N->getValueType(i); 1695 if (VT == MVT::Glue || VT == MVT::Other) 1696 continue; 1697 if (VT.isFloatingPoint() || VT.isVector()) 1698 return Sched::ILP; 1699 } 1700 1701 if (!N->isMachineOpcode()) 1702 return Sched::RegPressure; 1703 1704 // Load are scheduled for latency even if there instruction itinerary 1705 // is not available. 1706 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1707 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1708 1709 if (MCID.getNumDefs() == 0) 1710 return Sched::RegPressure; 1711 if (!Itins->isEmpty() && 1712 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1713 return Sched::ILP; 1714 1715 return Sched::RegPressure; 1716 } 1717 1718 //===----------------------------------------------------------------------===// 1719 // Lowering Code 1720 //===----------------------------------------------------------------------===// 1721 1722 static bool isSRL16(const SDValue &Op) { 1723 if (Op.getOpcode() != ISD::SRL) 1724 return false; 1725 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1726 return Const->getZExtValue() == 16; 1727 return false; 1728 } 1729 1730 static bool isSRA16(const SDValue &Op) { 1731 if (Op.getOpcode() != ISD::SRA) 1732 return false; 1733 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1734 return Const->getZExtValue() == 16; 1735 return false; 1736 } 1737 1738 static bool isSHL16(const SDValue &Op) { 1739 if (Op.getOpcode() != ISD::SHL) 1740 return false; 1741 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1742 return Const->getZExtValue() == 16; 1743 return false; 1744 } 1745 1746 // Check for a signed 16-bit value. We special case SRA because it makes it 1747 // more simple when also looking for SRAs that aren't sign extending a 1748 // smaller value. Without the check, we'd need to take extra care with 1749 // checking order for some operations. 1750 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1751 if (isSRA16(Op)) 1752 return isSHL16(Op.getOperand(0)); 1753 return DAG.ComputeNumSignBits(Op) == 17; 1754 } 1755 1756 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1757 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1758 switch (CC) { 1759 default: llvm_unreachable("Unknown condition code!"); 1760 case ISD::SETNE: return ARMCC::NE; 1761 case ISD::SETEQ: return ARMCC::EQ; 1762 case ISD::SETGT: return ARMCC::GT; 1763 case ISD::SETGE: return ARMCC::GE; 1764 case ISD::SETLT: return ARMCC::LT; 1765 case ISD::SETLE: return ARMCC::LE; 1766 case ISD::SETUGT: return ARMCC::HI; 1767 case ISD::SETUGE: return ARMCC::HS; 1768 case ISD::SETULT: return ARMCC::LO; 1769 case ISD::SETULE: return ARMCC::LS; 1770 } 1771 } 1772 1773 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1774 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1775 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1776 CondCode2 = ARMCC::AL; 1777 InvalidOnQNaN = true; 1778 switch (CC) { 1779 default: llvm_unreachable("Unknown FP condition!"); 1780 case ISD::SETEQ: 1781 case ISD::SETOEQ: 1782 CondCode = ARMCC::EQ; 1783 InvalidOnQNaN = false; 1784 break; 1785 case ISD::SETGT: 1786 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1787 case ISD::SETGE: 1788 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1789 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1790 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1791 case ISD::SETONE: 1792 CondCode = ARMCC::MI; 1793 CondCode2 = ARMCC::GT; 1794 InvalidOnQNaN = false; 1795 break; 1796 case ISD::SETO: CondCode = ARMCC::VC; break; 1797 case ISD::SETUO: CondCode = ARMCC::VS; break; 1798 case ISD::SETUEQ: 1799 CondCode = ARMCC::EQ; 1800 CondCode2 = ARMCC::VS; 1801 InvalidOnQNaN = false; 1802 break; 1803 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1804 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1805 case ISD::SETLT: 1806 case ISD::SETULT: CondCode = ARMCC::LT; break; 1807 case ISD::SETLE: 1808 case ISD::SETULE: CondCode = ARMCC::LE; break; 1809 case ISD::SETNE: 1810 case ISD::SETUNE: 1811 CondCode = ARMCC::NE; 1812 InvalidOnQNaN = false; 1813 break; 1814 } 1815 } 1816 1817 //===----------------------------------------------------------------------===// 1818 // Calling Convention Implementation 1819 //===----------------------------------------------------------------------===// 1820 1821 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1822 /// account presence of floating point hardware and calling convention 1823 /// limitations, such as support for variadic functions. 1824 CallingConv::ID 1825 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1826 bool isVarArg) const { 1827 switch (CC) { 1828 default: 1829 report_fatal_error("Unsupported calling convention"); 1830 case CallingConv::ARM_AAPCS: 1831 case CallingConv::ARM_APCS: 1832 case CallingConv::GHC: 1833 return CC; 1834 case CallingConv::PreserveMost: 1835 return CallingConv::PreserveMost; 1836 case CallingConv::ARM_AAPCS_VFP: 1837 case CallingConv::Swift: 1838 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1839 case CallingConv::C: 1840 if (!Subtarget->isAAPCS_ABI()) 1841 return CallingConv::ARM_APCS; 1842 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1843 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1844 !isVarArg) 1845 return CallingConv::ARM_AAPCS_VFP; 1846 else 1847 return CallingConv::ARM_AAPCS; 1848 case CallingConv::Fast: 1849 case CallingConv::CXX_FAST_TLS: 1850 if (!Subtarget->isAAPCS_ABI()) { 1851 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 1852 return CallingConv::Fast; 1853 return CallingConv::ARM_APCS; 1854 } else if (Subtarget->hasVFP2Base() && 1855 !Subtarget->isThumb1Only() && !isVarArg) 1856 return CallingConv::ARM_AAPCS_VFP; 1857 else 1858 return CallingConv::ARM_AAPCS; 1859 } 1860 } 1861 1862 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1863 bool isVarArg) const { 1864 return CCAssignFnForNode(CC, false, isVarArg); 1865 } 1866 1867 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1868 bool isVarArg) const { 1869 return CCAssignFnForNode(CC, true, isVarArg); 1870 } 1871 1872 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1873 /// CallingConvention. 1874 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1875 bool Return, 1876 bool isVarArg) const { 1877 switch (getEffectiveCallingConv(CC, isVarArg)) { 1878 default: 1879 report_fatal_error("Unsupported calling convention"); 1880 case CallingConv::ARM_APCS: 1881 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1882 case CallingConv::ARM_AAPCS: 1883 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1884 case CallingConv::ARM_AAPCS_VFP: 1885 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1886 case CallingConv::Fast: 1887 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1888 case CallingConv::GHC: 1889 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1890 case CallingConv::PreserveMost: 1891 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1892 } 1893 } 1894 1895 /// LowerCallResult - Lower the result values of a call into the 1896 /// appropriate copies out of appropriate physical registers. 1897 SDValue ARMTargetLowering::LowerCallResult( 1898 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1899 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1900 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1901 SDValue ThisVal) const { 1902 // Assign locations to each value returned by this call. 1903 SmallVector<CCValAssign, 16> RVLocs; 1904 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1905 *DAG.getContext()); 1906 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1907 1908 // Copy all of the result registers out of their specified physreg. 1909 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1910 CCValAssign VA = RVLocs[i]; 1911 1912 // Pass 'this' value directly from the argument to return value, to avoid 1913 // reg unit interference 1914 if (i == 0 && isThisReturn) { 1915 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1916 "unexpected return calling convention register assignment"); 1917 InVals.push_back(ThisVal); 1918 continue; 1919 } 1920 1921 SDValue Val; 1922 if (VA.needsCustom()) { 1923 // Handle f64 or half of a v2f64. 1924 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1925 InFlag); 1926 Chain = Lo.getValue(1); 1927 InFlag = Lo.getValue(2); 1928 VA = RVLocs[++i]; // skip ahead to next loc 1929 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1930 InFlag); 1931 Chain = Hi.getValue(1); 1932 InFlag = Hi.getValue(2); 1933 if (!Subtarget->isLittle()) 1934 std::swap (Lo, Hi); 1935 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1936 1937 if (VA.getLocVT() == MVT::v2f64) { 1938 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1939 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1940 DAG.getConstant(0, dl, MVT::i32)); 1941 1942 VA = RVLocs[++i]; // skip ahead to next loc 1943 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1944 Chain = Lo.getValue(1); 1945 InFlag = Lo.getValue(2); 1946 VA = RVLocs[++i]; // skip ahead to next loc 1947 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1948 Chain = Hi.getValue(1); 1949 InFlag = Hi.getValue(2); 1950 if (!Subtarget->isLittle()) 1951 std::swap (Lo, Hi); 1952 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1953 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1954 DAG.getConstant(1, dl, MVT::i32)); 1955 } 1956 } else { 1957 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1958 InFlag); 1959 Chain = Val.getValue(1); 1960 InFlag = Val.getValue(2); 1961 } 1962 1963 switch (VA.getLocInfo()) { 1964 default: llvm_unreachable("Unknown loc info!"); 1965 case CCValAssign::Full: break; 1966 case CCValAssign::BCvt: 1967 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1968 break; 1969 } 1970 1971 InVals.push_back(Val); 1972 } 1973 1974 return Chain; 1975 } 1976 1977 /// LowerMemOpCallTo - Store the argument to the stack. 1978 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1979 SDValue Arg, const SDLoc &dl, 1980 SelectionDAG &DAG, 1981 const CCValAssign &VA, 1982 ISD::ArgFlagsTy Flags) const { 1983 unsigned LocMemOffset = VA.getLocMemOffset(); 1984 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1985 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1986 StackPtr, PtrOff); 1987 return DAG.getStore( 1988 Chain, dl, Arg, PtrOff, 1989 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1990 } 1991 1992 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1993 SDValue Chain, SDValue &Arg, 1994 RegsToPassVector &RegsToPass, 1995 CCValAssign &VA, CCValAssign &NextVA, 1996 SDValue &StackPtr, 1997 SmallVectorImpl<SDValue> &MemOpChains, 1998 ISD::ArgFlagsTy Flags) const { 1999 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2000 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2001 unsigned id = Subtarget->isLittle() ? 0 : 1; 2002 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 2003 2004 if (NextVA.isRegLoc()) 2005 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 2006 else { 2007 assert(NextVA.isMemLoc()); 2008 if (!StackPtr.getNode()) 2009 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 2010 getPointerTy(DAG.getDataLayout())); 2011 2012 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 2013 dl, DAG, NextVA, 2014 Flags)); 2015 } 2016 } 2017 2018 /// LowerCall - Lowering a call into a callseq_start <- 2019 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 2020 /// nodes. 2021 SDValue 2022 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2023 SmallVectorImpl<SDValue> &InVals) const { 2024 SelectionDAG &DAG = CLI.DAG; 2025 SDLoc &dl = CLI.DL; 2026 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2027 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2028 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2029 SDValue Chain = CLI.Chain; 2030 SDValue Callee = CLI.Callee; 2031 bool &isTailCall = CLI.IsTailCall; 2032 CallingConv::ID CallConv = CLI.CallConv; 2033 bool doesNotRet = CLI.DoesNotReturn; 2034 bool isVarArg = CLI.IsVarArg; 2035 2036 MachineFunction &MF = DAG.getMachineFunction(); 2037 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2038 bool isThisReturn = false; 2039 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 2040 bool PreferIndirect = false; 2041 2042 // Disable tail calls if they're not supported. 2043 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 2044 isTailCall = false; 2045 2046 if (isa<GlobalAddressSDNode>(Callee)) { 2047 // If we're optimizing for minimum size and the function is called three or 2048 // more times in this block, we can improve codesize by calling indirectly 2049 // as BLXr has a 16-bit encoding. 2050 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2051 if (CLI.CS) { 2052 auto *BB = CLI.CS.getParent(); 2053 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2054 count_if(GV->users(), [&BB](const User *U) { 2055 return isa<Instruction>(U) && 2056 cast<Instruction>(U)->getParent() == BB; 2057 }) > 2; 2058 } 2059 } 2060 if (isTailCall) { 2061 // Check if it's really possible to do a tail call. 2062 isTailCall = IsEligibleForTailCallOptimization( 2063 Callee, CallConv, isVarArg, isStructRet, 2064 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2065 PreferIndirect); 2066 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 2067 report_fatal_error("failed to perform tail call elimination on a call " 2068 "site marked musttail"); 2069 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2070 // detected sibcalls. 2071 if (isTailCall) 2072 ++NumTailCalls; 2073 } 2074 2075 // Analyze operands of the call, assigning locations to each operand. 2076 SmallVector<CCValAssign, 16> ArgLocs; 2077 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2078 *DAG.getContext()); 2079 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2080 2081 // Get a count of how many bytes are to be pushed on the stack. 2082 unsigned NumBytes = CCInfo.getNextStackOffset(); 2083 2084 if (isTailCall) { 2085 // For tail calls, memory operands are available in our caller's stack. 2086 NumBytes = 0; 2087 } else { 2088 // Adjust the stack pointer for the new arguments... 2089 // These operations are automatically eliminated by the prolog/epilog pass 2090 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2091 } 2092 2093 SDValue StackPtr = 2094 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2095 2096 RegsToPassVector RegsToPass; 2097 SmallVector<SDValue, 8> MemOpChains; 2098 2099 // Walk the register/memloc assignments, inserting copies/loads. In the case 2100 // of tail call optimization, arguments are handled later. 2101 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2102 i != e; 2103 ++i, ++realArgIdx) { 2104 CCValAssign &VA = ArgLocs[i]; 2105 SDValue Arg = OutVals[realArgIdx]; 2106 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2107 bool isByVal = Flags.isByVal(); 2108 2109 // Promote the value if needed. 2110 switch (VA.getLocInfo()) { 2111 default: llvm_unreachable("Unknown loc info!"); 2112 case CCValAssign::Full: break; 2113 case CCValAssign::SExt: 2114 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2115 break; 2116 case CCValAssign::ZExt: 2117 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2118 break; 2119 case CCValAssign::AExt: 2120 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2121 break; 2122 case CCValAssign::BCvt: 2123 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2124 break; 2125 } 2126 2127 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2128 if (VA.needsCustom()) { 2129 if (VA.getLocVT() == MVT::v2f64) { 2130 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2131 DAG.getConstant(0, dl, MVT::i32)); 2132 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2133 DAG.getConstant(1, dl, MVT::i32)); 2134 2135 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 2136 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2137 2138 VA = ArgLocs[++i]; // skip ahead to next loc 2139 if (VA.isRegLoc()) { 2140 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 2141 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2142 } else { 2143 assert(VA.isMemLoc()); 2144 2145 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 2146 dl, DAG, VA, Flags)); 2147 } 2148 } else { 2149 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2150 StackPtr, MemOpChains, Flags); 2151 } 2152 } else if (VA.isRegLoc()) { 2153 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2154 Outs[0].VT == MVT::i32) { 2155 assert(VA.getLocVT() == MVT::i32 && 2156 "unexpected calling convention register assignment"); 2157 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2158 "unexpected use of 'returned'"); 2159 isThisReturn = true; 2160 } 2161 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2162 } else if (isByVal) { 2163 assert(VA.isMemLoc()); 2164 unsigned offset = 0; 2165 2166 // True if this byval aggregate will be split between registers 2167 // and memory. 2168 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2169 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2170 2171 if (CurByValIdx < ByValArgsCount) { 2172 2173 unsigned RegBegin, RegEnd; 2174 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2175 2176 EVT PtrVT = 2177 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2178 unsigned int i, j; 2179 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2180 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2181 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2182 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 2183 MachinePointerInfo(), 2184 DAG.InferPtrAlignment(AddArg)); 2185 MemOpChains.push_back(Load.getValue(1)); 2186 RegsToPass.push_back(std::make_pair(j, Load)); 2187 } 2188 2189 // If parameter size outsides register area, "offset" value 2190 // helps us to calculate stack slot for remained part properly. 2191 offset = RegEnd - RegBegin; 2192 2193 CCInfo.nextInRegsParam(); 2194 } 2195 2196 if (Flags.getByValSize() > 4*offset) { 2197 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2198 unsigned LocMemOffset = VA.getLocMemOffset(); 2199 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2200 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2201 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2202 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2203 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2204 MVT::i32); 2205 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 2206 MVT::i32); 2207 2208 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2209 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2210 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2211 Ops)); 2212 } 2213 } else if (!isTailCall) { 2214 assert(VA.isMemLoc()); 2215 2216 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2217 dl, DAG, VA, Flags)); 2218 } 2219 } 2220 2221 if (!MemOpChains.empty()) 2222 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2223 2224 // Build a sequence of copy-to-reg nodes chained together with token chain 2225 // and flag operands which copy the outgoing args into the appropriate regs. 2226 SDValue InFlag; 2227 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2228 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2229 RegsToPass[i].second, InFlag); 2230 InFlag = Chain.getValue(1); 2231 } 2232 2233 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2234 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2235 // node so that legalize doesn't hack it. 2236 bool isDirect = false; 2237 2238 const TargetMachine &TM = getTargetMachine(); 2239 const Module *Mod = MF.getFunction().getParent(); 2240 const GlobalValue *GV = nullptr; 2241 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2242 GV = G->getGlobal(); 2243 bool isStub = 2244 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2245 2246 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2247 bool isLocalARMFunc = false; 2248 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2249 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2250 2251 if (Subtarget->genLongCalls()) { 2252 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2253 "long-calls codegen is not position independent!"); 2254 // Handle a global address or an external symbol. If it's not one of 2255 // those, the target's already in a register, so we don't need to do 2256 // anything extra. 2257 if (isa<GlobalAddressSDNode>(Callee)) { 2258 // Create a constant pool entry for the callee address 2259 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2260 ARMConstantPoolValue *CPV = 2261 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2262 2263 // Get the address of the callee into a register 2264 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2265 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2266 Callee = DAG.getLoad( 2267 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2268 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2269 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2270 const char *Sym = S->getSymbol(); 2271 2272 // Create a constant pool entry for the callee address 2273 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2274 ARMConstantPoolValue *CPV = 2275 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2276 ARMPCLabelIndex, 0); 2277 // Get the address of the callee into a register 2278 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2279 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2280 Callee = DAG.getLoad( 2281 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2282 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2283 } 2284 } else if (isa<GlobalAddressSDNode>(Callee)) { 2285 if (!PreferIndirect) { 2286 isDirect = true; 2287 bool isDef = GV->isStrongDefinitionForLinker(); 2288 2289 // ARM call to a local ARM function is predicable. 2290 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2291 // tBX takes a register source operand. 2292 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2293 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2294 Callee = DAG.getNode( 2295 ARMISD::WrapperPIC, dl, PtrVt, 2296 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2297 Callee = DAG.getLoad( 2298 PtrVt, dl, DAG.getEntryNode(), Callee, 2299 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2300 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2301 MachineMemOperand::MOInvariant); 2302 } else if (Subtarget->isTargetCOFF()) { 2303 assert(Subtarget->isTargetWindows() && 2304 "Windows is the only supported COFF target"); 2305 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2306 ? ARMII::MO_DLLIMPORT 2307 : ARMII::MO_NO_FLAG; 2308 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2309 TargetFlags); 2310 if (GV->hasDLLImportStorageClass()) 2311 Callee = 2312 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2313 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2314 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2315 } else { 2316 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2317 } 2318 } 2319 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2320 isDirect = true; 2321 // tBX takes a register source operand. 2322 const char *Sym = S->getSymbol(); 2323 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2324 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2325 ARMConstantPoolValue *CPV = 2326 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2327 ARMPCLabelIndex, 4); 2328 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2329 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2330 Callee = DAG.getLoad( 2331 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2332 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2333 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2334 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2335 } else { 2336 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2337 } 2338 } 2339 2340 // FIXME: handle tail calls differently. 2341 unsigned CallOpc; 2342 if (Subtarget->isThumb()) { 2343 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2344 CallOpc = ARMISD::CALL_NOLINK; 2345 else 2346 CallOpc = ARMISD::CALL; 2347 } else { 2348 if (!isDirect && !Subtarget->hasV5TOps()) 2349 CallOpc = ARMISD::CALL_NOLINK; 2350 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2351 // Emit regular call when code size is the priority 2352 !Subtarget->hasMinSize()) 2353 // "mov lr, pc; b _foo" to avoid confusing the RSP 2354 CallOpc = ARMISD::CALL_NOLINK; 2355 else 2356 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2357 } 2358 2359 std::vector<SDValue> Ops; 2360 Ops.push_back(Chain); 2361 Ops.push_back(Callee); 2362 2363 // Add argument registers to the end of the list so that they are known live 2364 // into the call. 2365 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2366 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2367 RegsToPass[i].second.getValueType())); 2368 2369 // Add a register mask operand representing the call-preserved registers. 2370 if (!isTailCall) { 2371 const uint32_t *Mask; 2372 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2373 if (isThisReturn) { 2374 // For 'this' returns, use the R0-preserving mask if applicable 2375 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2376 if (!Mask) { 2377 // Set isThisReturn to false if the calling convention is not one that 2378 // allows 'returned' to be modeled in this way, so LowerCallResult does 2379 // not try to pass 'this' straight through 2380 isThisReturn = false; 2381 Mask = ARI->getCallPreservedMask(MF, CallConv); 2382 } 2383 } else 2384 Mask = ARI->getCallPreservedMask(MF, CallConv); 2385 2386 assert(Mask && "Missing call preserved mask for calling convention"); 2387 Ops.push_back(DAG.getRegisterMask(Mask)); 2388 } 2389 2390 if (InFlag.getNode()) 2391 Ops.push_back(InFlag); 2392 2393 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2394 if (isTailCall) { 2395 MF.getFrameInfo().setHasTailCall(); 2396 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2397 } 2398 2399 // Returns a chain and a flag for retval copy to use. 2400 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2401 InFlag = Chain.getValue(1); 2402 2403 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2404 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2405 if (!Ins.empty()) 2406 InFlag = Chain.getValue(1); 2407 2408 // Handle result values, copying them out of physregs into vregs that we 2409 // return. 2410 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2411 InVals, isThisReturn, 2412 isThisReturn ? OutVals[0] : SDValue()); 2413 } 2414 2415 /// HandleByVal - Every parameter *after* a byval parameter is passed 2416 /// on the stack. Remember the next parameter register to allocate, 2417 /// and then confiscate the rest of the parameter registers to insure 2418 /// this. 2419 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2420 unsigned Align) const { 2421 // Byval (as with any stack) slots are always at least 4 byte aligned. 2422 Align = std::max(Align, 4U); 2423 2424 unsigned Reg = State->AllocateReg(GPRArgRegs); 2425 if (!Reg) 2426 return; 2427 2428 unsigned AlignInRegs = Align / 4; 2429 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2430 for (unsigned i = 0; i < Waste; ++i) 2431 Reg = State->AllocateReg(GPRArgRegs); 2432 2433 if (!Reg) 2434 return; 2435 2436 unsigned Excess = 4 * (ARM::R4 - Reg); 2437 2438 // Special case when NSAA != SP and parameter size greater than size of 2439 // all remained GPR regs. In that case we can't split parameter, we must 2440 // send it to stack. We also must set NCRN to R4, so waste all 2441 // remained registers. 2442 const unsigned NSAAOffset = State->getNextStackOffset(); 2443 if (NSAAOffset != 0 && Size > Excess) { 2444 while (State->AllocateReg(GPRArgRegs)) 2445 ; 2446 return; 2447 } 2448 2449 // First register for byval parameter is the first register that wasn't 2450 // allocated before this method call, so it would be "reg". 2451 // If parameter is small enough to be saved in range [reg, r4), then 2452 // the end (first after last) register would be reg + param-size-in-regs, 2453 // else parameter would be splitted between registers and stack, 2454 // end register would be r4 in this case. 2455 unsigned ByValRegBegin = Reg; 2456 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2457 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2458 // Note, first register is allocated in the beginning of function already, 2459 // allocate remained amount of registers we need. 2460 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2461 State->AllocateReg(GPRArgRegs); 2462 // A byval parameter that is split between registers and memory needs its 2463 // size truncated here. 2464 // In the case where the entire structure fits in registers, we set the 2465 // size in memory to zero. 2466 Size = std::max<int>(Size - Excess, 0); 2467 } 2468 2469 /// MatchingStackOffset - Return true if the given stack call argument is 2470 /// already available in the same position (relatively) of the caller's 2471 /// incoming argument stack. 2472 static 2473 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2474 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2475 const TargetInstrInfo *TII) { 2476 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2477 int FI = std::numeric_limits<int>::max(); 2478 if (Arg.getOpcode() == ISD::CopyFromReg) { 2479 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2480 if (!Register::isVirtualRegister(VR)) 2481 return false; 2482 MachineInstr *Def = MRI->getVRegDef(VR); 2483 if (!Def) 2484 return false; 2485 if (!Flags.isByVal()) { 2486 if (!TII->isLoadFromStackSlot(*Def, FI)) 2487 return false; 2488 } else { 2489 return false; 2490 } 2491 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2492 if (Flags.isByVal()) 2493 // ByVal argument is passed in as a pointer but it's now being 2494 // dereferenced. e.g. 2495 // define @foo(%struct.X* %A) { 2496 // tail call @bar(%struct.X* byval %A) 2497 // } 2498 return false; 2499 SDValue Ptr = Ld->getBasePtr(); 2500 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2501 if (!FINode) 2502 return false; 2503 FI = FINode->getIndex(); 2504 } else 2505 return false; 2506 2507 assert(FI != std::numeric_limits<int>::max()); 2508 if (!MFI.isFixedObjectIndex(FI)) 2509 return false; 2510 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2511 } 2512 2513 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2514 /// for tail call optimization. Targets which want to do tail call 2515 /// optimization should implement this function. 2516 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2517 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2518 bool isCalleeStructRet, bool isCallerStructRet, 2519 const SmallVectorImpl<ISD::OutputArg> &Outs, 2520 const SmallVectorImpl<SDValue> &OutVals, 2521 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2522 const bool isIndirect) const { 2523 MachineFunction &MF = DAG.getMachineFunction(); 2524 const Function &CallerF = MF.getFunction(); 2525 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2526 2527 assert(Subtarget->supportsTailCall()); 2528 2529 // Indirect tail calls cannot be optimized for Thumb1 if the args 2530 // to the call take up r0-r3. The reason is that there are no legal registers 2531 // left to hold the pointer to the function to be called. 2532 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2533 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2534 return false; 2535 2536 // Look for obvious safe cases to perform tail call optimization that do not 2537 // require ABI changes. This is what gcc calls sibcall. 2538 2539 // Exception-handling functions need a special set of instructions to indicate 2540 // a return to the hardware. Tail-calling another function would probably 2541 // break this. 2542 if (CallerF.hasFnAttribute("interrupt")) 2543 return false; 2544 2545 // Also avoid sibcall optimization if either caller or callee uses struct 2546 // return semantics. 2547 if (isCalleeStructRet || isCallerStructRet) 2548 return false; 2549 2550 // Externally-defined functions with weak linkage should not be 2551 // tail-called on ARM when the OS does not support dynamic 2552 // pre-emption of symbols, as the AAELF spec requires normal calls 2553 // to undefined weak functions to be replaced with a NOP or jump to the 2554 // next instruction. The behaviour of branch instructions in this 2555 // situation (as used for tail calls) is implementation-defined, so we 2556 // cannot rely on the linker replacing the tail call with a return. 2557 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2558 const GlobalValue *GV = G->getGlobal(); 2559 const Triple &TT = getTargetMachine().getTargetTriple(); 2560 if (GV->hasExternalWeakLinkage() && 2561 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2562 return false; 2563 } 2564 2565 // Check that the call results are passed in the same way. 2566 LLVMContext &C = *DAG.getContext(); 2567 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2568 CCAssignFnForReturn(CalleeCC, isVarArg), 2569 CCAssignFnForReturn(CallerCC, isVarArg))) 2570 return false; 2571 // The callee has to preserve all registers the caller needs to preserve. 2572 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2573 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2574 if (CalleeCC != CallerCC) { 2575 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2576 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2577 return false; 2578 } 2579 2580 // If Caller's vararg or byval argument has been split between registers and 2581 // stack, do not perform tail call, since part of the argument is in caller's 2582 // local frame. 2583 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2584 if (AFI_Caller->getArgRegsSaveSize()) 2585 return false; 2586 2587 // If the callee takes no arguments then go on to check the results of the 2588 // call. 2589 if (!Outs.empty()) { 2590 // Check if stack adjustment is needed. For now, do not do this if any 2591 // argument is passed on the stack. 2592 SmallVector<CCValAssign, 16> ArgLocs; 2593 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2594 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2595 if (CCInfo.getNextStackOffset()) { 2596 // Check if the arguments are already laid out in the right way as 2597 // the caller's fixed stack objects. 2598 MachineFrameInfo &MFI = MF.getFrameInfo(); 2599 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2600 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2601 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2602 i != e; 2603 ++i, ++realArgIdx) { 2604 CCValAssign &VA = ArgLocs[i]; 2605 EVT RegVT = VA.getLocVT(); 2606 SDValue Arg = OutVals[realArgIdx]; 2607 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2608 if (VA.getLocInfo() == CCValAssign::Indirect) 2609 return false; 2610 if (VA.needsCustom()) { 2611 // f64 and vector types are split into multiple registers or 2612 // register/stack-slot combinations. The types will not match 2613 // the registers; give up on memory f64 refs until we figure 2614 // out what to do about this. 2615 if (!VA.isRegLoc()) 2616 return false; 2617 if (!ArgLocs[++i].isRegLoc()) 2618 return false; 2619 if (RegVT == MVT::v2f64) { 2620 if (!ArgLocs[++i].isRegLoc()) 2621 return false; 2622 if (!ArgLocs[++i].isRegLoc()) 2623 return false; 2624 } 2625 } else if (!VA.isRegLoc()) { 2626 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2627 MFI, MRI, TII)) 2628 return false; 2629 } 2630 } 2631 } 2632 2633 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2634 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2635 return false; 2636 } 2637 2638 return true; 2639 } 2640 2641 bool 2642 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2643 MachineFunction &MF, bool isVarArg, 2644 const SmallVectorImpl<ISD::OutputArg> &Outs, 2645 LLVMContext &Context) const { 2646 SmallVector<CCValAssign, 16> RVLocs; 2647 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2648 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2649 } 2650 2651 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2652 const SDLoc &DL, SelectionDAG &DAG) { 2653 const MachineFunction &MF = DAG.getMachineFunction(); 2654 const Function &F = MF.getFunction(); 2655 2656 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2657 2658 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2659 // version of the "preferred return address". These offsets affect the return 2660 // instruction if this is a return from PL1 without hypervisor extensions. 2661 // IRQ/FIQ: +4 "subs pc, lr, #4" 2662 // SWI: 0 "subs pc, lr, #0" 2663 // ABORT: +4 "subs pc, lr, #4" 2664 // UNDEF: +4/+2 "subs pc, lr, #0" 2665 // UNDEF varies depending on where the exception came from ARM or Thumb 2666 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2667 2668 int64_t LROffset; 2669 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2670 IntKind == "ABORT") 2671 LROffset = 4; 2672 else if (IntKind == "SWI" || IntKind == "UNDEF") 2673 LROffset = 0; 2674 else 2675 report_fatal_error("Unsupported interrupt attribute. If present, value " 2676 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2677 2678 RetOps.insert(RetOps.begin() + 1, 2679 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2680 2681 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2682 } 2683 2684 SDValue 2685 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2686 bool isVarArg, 2687 const SmallVectorImpl<ISD::OutputArg> &Outs, 2688 const SmallVectorImpl<SDValue> &OutVals, 2689 const SDLoc &dl, SelectionDAG &DAG) const { 2690 // CCValAssign - represent the assignment of the return value to a location. 2691 SmallVector<CCValAssign, 16> RVLocs; 2692 2693 // CCState - Info about the registers and stack slots. 2694 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2695 *DAG.getContext()); 2696 2697 // Analyze outgoing return values. 2698 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2699 2700 SDValue Flag; 2701 SmallVector<SDValue, 4> RetOps; 2702 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2703 bool isLittleEndian = Subtarget->isLittle(); 2704 2705 MachineFunction &MF = DAG.getMachineFunction(); 2706 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2707 AFI->setReturnRegsCount(RVLocs.size()); 2708 2709 // Copy the result values into the output registers. 2710 for (unsigned i = 0, realRVLocIdx = 0; 2711 i != RVLocs.size(); 2712 ++i, ++realRVLocIdx) { 2713 CCValAssign &VA = RVLocs[i]; 2714 assert(VA.isRegLoc() && "Can only return in registers!"); 2715 2716 SDValue Arg = OutVals[realRVLocIdx]; 2717 bool ReturnF16 = false; 2718 2719 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2720 // Half-precision return values can be returned like this: 2721 // 2722 // t11 f16 = fadd ... 2723 // t12: i16 = bitcast t11 2724 // t13: i32 = zero_extend t12 2725 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2726 // 2727 // to avoid code generation for bitcasts, we simply set Arg to the node 2728 // that produces the f16 value, t11 in this case. 2729 // 2730 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2731 SDValue ZE = Arg.getOperand(0); 2732 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2733 SDValue BC = ZE.getOperand(0); 2734 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2735 Arg = BC.getOperand(0); 2736 ReturnF16 = true; 2737 } 2738 } 2739 } 2740 } 2741 2742 switch (VA.getLocInfo()) { 2743 default: llvm_unreachable("Unknown loc info!"); 2744 case CCValAssign::Full: break; 2745 case CCValAssign::BCvt: 2746 if (!ReturnF16) 2747 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2748 break; 2749 } 2750 2751 if (VA.needsCustom()) { 2752 if (VA.getLocVT() == MVT::v2f64) { 2753 // Extract the first half and return it in two registers. 2754 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2755 DAG.getConstant(0, dl, MVT::i32)); 2756 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2757 DAG.getVTList(MVT::i32, MVT::i32), Half); 2758 2759 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2760 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2761 Flag); 2762 Flag = Chain.getValue(1); 2763 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2764 VA = RVLocs[++i]; // skip ahead to next loc 2765 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2766 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2767 Flag); 2768 Flag = Chain.getValue(1); 2769 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2770 VA = RVLocs[++i]; // skip ahead to next loc 2771 2772 // Extract the 2nd half and fall through to handle it as an f64 value. 2773 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2774 DAG.getConstant(1, dl, MVT::i32)); 2775 } 2776 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2777 // available. 2778 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2779 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2780 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2781 fmrrd.getValue(isLittleEndian ? 0 : 1), 2782 Flag); 2783 Flag = Chain.getValue(1); 2784 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2785 VA = RVLocs[++i]; // skip ahead to next loc 2786 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2787 fmrrd.getValue(isLittleEndian ? 1 : 0), 2788 Flag); 2789 } else 2790 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2791 2792 // Guarantee that all emitted copies are 2793 // stuck together, avoiding something bad. 2794 Flag = Chain.getValue(1); 2795 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2796 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2797 } 2798 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2799 const MCPhysReg *I = 2800 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2801 if (I) { 2802 for (; *I; ++I) { 2803 if (ARM::GPRRegClass.contains(*I)) 2804 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2805 else if (ARM::DPRRegClass.contains(*I)) 2806 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2807 else 2808 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2809 } 2810 } 2811 2812 // Update chain and glue. 2813 RetOps[0] = Chain; 2814 if (Flag.getNode()) 2815 RetOps.push_back(Flag); 2816 2817 // CPUs which aren't M-class use a special sequence to return from 2818 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2819 // though we use "subs pc, lr, #N"). 2820 // 2821 // M-class CPUs actually use a normal return sequence with a special 2822 // (hardware-provided) value in LR, so the normal code path works. 2823 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2824 !Subtarget->isMClass()) { 2825 if (Subtarget->isThumb1Only()) 2826 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2827 return LowerInterruptReturn(RetOps, dl, DAG); 2828 } 2829 2830 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2831 } 2832 2833 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2834 if (N->getNumValues() != 1) 2835 return false; 2836 if (!N->hasNUsesOfValue(1, 0)) 2837 return false; 2838 2839 SDValue TCChain = Chain; 2840 SDNode *Copy = *N->use_begin(); 2841 if (Copy->getOpcode() == ISD::CopyToReg) { 2842 // If the copy has a glue operand, we conservatively assume it isn't safe to 2843 // perform a tail call. 2844 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2845 return false; 2846 TCChain = Copy->getOperand(0); 2847 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2848 SDNode *VMov = Copy; 2849 // f64 returned in a pair of GPRs. 2850 SmallPtrSet<SDNode*, 2> Copies; 2851 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2852 UI != UE; ++UI) { 2853 if (UI->getOpcode() != ISD::CopyToReg) 2854 return false; 2855 Copies.insert(*UI); 2856 } 2857 if (Copies.size() > 2) 2858 return false; 2859 2860 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2861 UI != UE; ++UI) { 2862 SDValue UseChain = UI->getOperand(0); 2863 if (Copies.count(UseChain.getNode())) 2864 // Second CopyToReg 2865 Copy = *UI; 2866 else { 2867 // We are at the top of this chain. 2868 // If the copy has a glue operand, we conservatively assume it 2869 // isn't safe to perform a tail call. 2870 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2871 return false; 2872 // First CopyToReg 2873 TCChain = UseChain; 2874 } 2875 } 2876 } else if (Copy->getOpcode() == ISD::BITCAST) { 2877 // f32 returned in a single GPR. 2878 if (!Copy->hasOneUse()) 2879 return false; 2880 Copy = *Copy->use_begin(); 2881 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2882 return false; 2883 // If the copy has a glue operand, we conservatively assume it isn't safe to 2884 // perform a tail call. 2885 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2886 return false; 2887 TCChain = Copy->getOperand(0); 2888 } else { 2889 return false; 2890 } 2891 2892 bool HasRet = false; 2893 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2894 UI != UE; ++UI) { 2895 if (UI->getOpcode() != ARMISD::RET_FLAG && 2896 UI->getOpcode() != ARMISD::INTRET_FLAG) 2897 return false; 2898 HasRet = true; 2899 } 2900 2901 if (!HasRet) 2902 return false; 2903 2904 Chain = TCChain; 2905 return true; 2906 } 2907 2908 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2909 if (!Subtarget->supportsTailCall()) 2910 return false; 2911 2912 auto Attr = 2913 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2914 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2915 return false; 2916 2917 return true; 2918 } 2919 2920 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2921 // and pass the lower and high parts through. 2922 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2923 SDLoc DL(Op); 2924 SDValue WriteValue = Op->getOperand(2); 2925 2926 // This function is only supposed to be called for i64 type argument. 2927 assert(WriteValue.getValueType() == MVT::i64 2928 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2929 2930 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2931 DAG.getConstant(0, DL, MVT::i32)); 2932 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2933 DAG.getConstant(1, DL, MVT::i32)); 2934 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2935 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2936 } 2937 2938 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2939 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2940 // one of the above mentioned nodes. It has to be wrapped because otherwise 2941 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2942 // be used to form addressing mode. These wrapped nodes will be selected 2943 // into MOVi. 2944 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2945 SelectionDAG &DAG) const { 2946 EVT PtrVT = Op.getValueType(); 2947 // FIXME there is no actual debug info here 2948 SDLoc dl(Op); 2949 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2950 SDValue Res; 2951 2952 // When generating execute-only code Constant Pools must be promoted to the 2953 // global data section. It's a bit ugly that we can't share them across basic 2954 // blocks, but this way we guarantee that execute-only behaves correct with 2955 // position-independent addressing modes. 2956 if (Subtarget->genExecuteOnly()) { 2957 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2958 auto T = const_cast<Type*>(CP->getType()); 2959 auto C = const_cast<Constant*>(CP->getConstVal()); 2960 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2961 getFunction().getParent()); 2962 auto GV = new GlobalVariable( 2963 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 2964 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2965 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2966 Twine(AFI->createPICLabelUId()) 2967 ); 2968 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2969 dl, PtrVT); 2970 return LowerGlobalAddress(GA, DAG); 2971 } 2972 2973 if (CP->isMachineConstantPoolEntry()) 2974 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2975 CP->getAlignment()); 2976 else 2977 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2978 CP->getAlignment()); 2979 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2980 } 2981 2982 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2983 return MachineJumpTableInfo::EK_Inline; 2984 } 2985 2986 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2987 SelectionDAG &DAG) const { 2988 MachineFunction &MF = DAG.getMachineFunction(); 2989 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2990 unsigned ARMPCLabelIndex = 0; 2991 SDLoc DL(Op); 2992 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2993 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2994 SDValue CPAddr; 2995 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2996 if (!IsPositionIndependent) { 2997 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2998 } else { 2999 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3000 ARMPCLabelIndex = AFI->createPICLabelUId(); 3001 ARMConstantPoolValue *CPV = 3002 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 3003 ARMCP::CPBlockAddress, PCAdj); 3004 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3005 } 3006 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 3007 SDValue Result = DAG.getLoad( 3008 PtrVT, DL, DAG.getEntryNode(), CPAddr, 3009 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3010 if (!IsPositionIndependent) 3011 return Result; 3012 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 3013 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 3014 } 3015 3016 /// Convert a TLS address reference into the correct sequence of loads 3017 /// and calls to compute the variable's address for Darwin, and return an 3018 /// SDValue containing the final node. 3019 3020 /// Darwin only has one TLS scheme which must be capable of dealing with the 3021 /// fully general situation, in the worst case. This means: 3022 /// + "extern __thread" declaration. 3023 /// + Defined in a possibly unknown dynamic library. 3024 /// 3025 /// The general system is that each __thread variable has a [3 x i32] descriptor 3026 /// which contains information used by the runtime to calculate the address. The 3027 /// only part of this the compiler needs to know about is the first word, which 3028 /// contains a function pointer that must be called with the address of the 3029 /// entire descriptor in "r0". 3030 /// 3031 /// Since this descriptor may be in a different unit, in general access must 3032 /// proceed along the usual ARM rules. A common sequence to produce is: 3033 /// 3034 /// movw rT1, :lower16:_var$non_lazy_ptr 3035 /// movt rT1, :upper16:_var$non_lazy_ptr 3036 /// ldr r0, [rT1] 3037 /// ldr rT2, [r0] 3038 /// blx rT2 3039 /// [...address now in r0...] 3040 SDValue 3041 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3042 SelectionDAG &DAG) const { 3043 assert(Subtarget->isTargetDarwin() && 3044 "This function expects a Darwin target"); 3045 SDLoc DL(Op); 3046 3047 // First step is to get the address of the actua global symbol. This is where 3048 // the TLS descriptor lives. 3049 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3050 3051 // The first entry in the descriptor is a function pointer that we must call 3052 // to obtain the address of the variable. 3053 SDValue Chain = DAG.getEntryNode(); 3054 SDValue FuncTLVGet = DAG.getLoad( 3055 MVT::i32, DL, Chain, DescAddr, 3056 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3057 /* Alignment = */ 4, 3058 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3059 MachineMemOperand::MOInvariant); 3060 Chain = FuncTLVGet.getValue(1); 3061 3062 MachineFunction &F = DAG.getMachineFunction(); 3063 MachineFrameInfo &MFI = F.getFrameInfo(); 3064 MFI.setAdjustsStack(true); 3065 3066 // TLS calls preserve all registers except those that absolutely must be 3067 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3068 // silly). 3069 auto TRI = 3070 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3071 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3072 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3073 3074 // Finally, we can make the call. This is just a degenerate version of a 3075 // normal AArch64 call node: r0 takes the address of the descriptor, and 3076 // returns the address of the variable in this thread. 3077 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3078 Chain = 3079 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3080 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3081 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3082 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3083 } 3084 3085 SDValue 3086 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3087 SelectionDAG &DAG) const { 3088 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3089 3090 SDValue Chain = DAG.getEntryNode(); 3091 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3092 SDLoc DL(Op); 3093 3094 // Load the current TEB (thread environment block) 3095 SDValue Ops[] = {Chain, 3096 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3097 DAG.getConstant(15, DL, MVT::i32), 3098 DAG.getConstant(0, DL, MVT::i32), 3099 DAG.getConstant(13, DL, MVT::i32), 3100 DAG.getConstant(0, DL, MVT::i32), 3101 DAG.getConstant(2, DL, MVT::i32)}; 3102 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3103 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3104 3105 SDValue TEB = CurrentTEB.getValue(0); 3106 Chain = CurrentTEB.getValue(1); 3107 3108 // Load the ThreadLocalStoragePointer from the TEB 3109 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3110 SDValue TLSArray = 3111 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3112 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3113 3114 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3115 // offset into the TLSArray. 3116 3117 // Load the TLS index from the C runtime 3118 SDValue TLSIndex = 3119 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3120 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3121 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3122 3123 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3124 DAG.getConstant(2, DL, MVT::i32)); 3125 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3126 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3127 MachinePointerInfo()); 3128 3129 // Get the offset of the start of the .tls section (section base) 3130 const auto *GA = cast<GlobalAddressSDNode>(Op); 3131 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3132 SDValue Offset = DAG.getLoad( 3133 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3134 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 3135 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3136 3137 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3138 } 3139 3140 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3141 SDValue 3142 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3143 SelectionDAG &DAG) const { 3144 SDLoc dl(GA); 3145 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3146 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3147 MachineFunction &MF = DAG.getMachineFunction(); 3148 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3149 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3150 ARMConstantPoolValue *CPV = 3151 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3152 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3153 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3154 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3155 Argument = DAG.getLoad( 3156 PtrVT, dl, DAG.getEntryNode(), Argument, 3157 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3158 SDValue Chain = Argument.getValue(1); 3159 3160 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3161 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3162 3163 // call __tls_get_addr. 3164 ArgListTy Args; 3165 ArgListEntry Entry; 3166 Entry.Node = Argument; 3167 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3168 Args.push_back(Entry); 3169 3170 // FIXME: is there useful debug info available here? 3171 TargetLowering::CallLoweringInfo CLI(DAG); 3172 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3173 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3174 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3175 3176 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3177 return CallResult.first; 3178 } 3179 3180 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3181 // "local exec" model. 3182 SDValue 3183 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3184 SelectionDAG &DAG, 3185 TLSModel::Model model) const { 3186 const GlobalValue *GV = GA->getGlobal(); 3187 SDLoc dl(GA); 3188 SDValue Offset; 3189 SDValue Chain = DAG.getEntryNode(); 3190 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3191 // Get the Thread Pointer 3192 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3193 3194 if (model == TLSModel::InitialExec) { 3195 MachineFunction &MF = DAG.getMachineFunction(); 3196 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3197 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3198 // Initial exec model. 3199 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3200 ARMConstantPoolValue *CPV = 3201 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3202 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3203 true); 3204 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3205 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3206 Offset = DAG.getLoad( 3207 PtrVT, dl, Chain, Offset, 3208 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3209 Chain = Offset.getValue(1); 3210 3211 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3212 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3213 3214 Offset = DAG.getLoad( 3215 PtrVT, dl, Chain, Offset, 3216 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3217 } else { 3218 // local exec model 3219 assert(model == TLSModel::LocalExec); 3220 ARMConstantPoolValue *CPV = 3221 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3222 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3223 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3224 Offset = DAG.getLoad( 3225 PtrVT, dl, Chain, Offset, 3226 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3227 } 3228 3229 // The address of the thread local variable is the add of the thread 3230 // pointer with the offset of the variable. 3231 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3232 } 3233 3234 SDValue 3235 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3236 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3237 if (DAG.getTarget().useEmulatedTLS()) 3238 return LowerToTLSEmulatedModel(GA, DAG); 3239 3240 if (Subtarget->isTargetDarwin()) 3241 return LowerGlobalTLSAddressDarwin(Op, DAG); 3242 3243 if (Subtarget->isTargetWindows()) 3244 return LowerGlobalTLSAddressWindows(Op, DAG); 3245 3246 // TODO: implement the "local dynamic" model 3247 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3248 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3249 3250 switch (model) { 3251 case TLSModel::GeneralDynamic: 3252 case TLSModel::LocalDynamic: 3253 return LowerToTLSGeneralDynamicModel(GA, DAG); 3254 case TLSModel::InitialExec: 3255 case TLSModel::LocalExec: 3256 return LowerToTLSExecModels(GA, DAG, model); 3257 } 3258 llvm_unreachable("bogus TLS model"); 3259 } 3260 3261 /// Return true if all users of V are within function F, looking through 3262 /// ConstantExprs. 3263 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3264 SmallVector<const User*,4> Worklist; 3265 for (auto *U : V->users()) 3266 Worklist.push_back(U); 3267 while (!Worklist.empty()) { 3268 auto *U = Worklist.pop_back_val(); 3269 if (isa<ConstantExpr>(U)) { 3270 for (auto *UU : U->users()) 3271 Worklist.push_back(UU); 3272 continue; 3273 } 3274 3275 auto *I = dyn_cast<Instruction>(U); 3276 if (!I || I->getParent()->getParent() != F) 3277 return false; 3278 } 3279 return true; 3280 } 3281 3282 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3283 const GlobalValue *GV, SelectionDAG &DAG, 3284 EVT PtrVT, const SDLoc &dl) { 3285 // If we're creating a pool entry for a constant global with unnamed address, 3286 // and the global is small enough, we can emit it inline into the constant pool 3287 // to save ourselves an indirection. 3288 // 3289 // This is a win if the constant is only used in one function (so it doesn't 3290 // need to be duplicated) or duplicating the constant wouldn't increase code 3291 // size (implying the constant is no larger than 4 bytes). 3292 const Function &F = DAG.getMachineFunction().getFunction(); 3293 3294 // We rely on this decision to inline being idemopotent and unrelated to the 3295 // use-site. We know that if we inline a variable at one use site, we'll 3296 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3297 // doesn't know about this optimization, so bail out if it's enabled else 3298 // we could decide to inline here (and thus never emit the GV) but require 3299 // the GV from fast-isel generated code. 3300 if (!EnableConstpoolPromotion || 3301 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3302 return SDValue(); 3303 3304 auto *GVar = dyn_cast<GlobalVariable>(GV); 3305 if (!GVar || !GVar->hasInitializer() || 3306 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3307 !GVar->hasLocalLinkage()) 3308 return SDValue(); 3309 3310 // If we inline a value that contains relocations, we move the relocations 3311 // from .data to .text. This is not allowed in position-independent code. 3312 auto *Init = GVar->getInitializer(); 3313 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3314 Init->needsRelocation()) 3315 return SDValue(); 3316 3317 // The constant islands pass can only really deal with alignment requests 3318 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3319 // any type wanting greater alignment requirements than 4 bytes. We also 3320 // can only promote constants that are multiples of 4 bytes in size or 3321 // are paddable to a multiple of 4. Currently we only try and pad constants 3322 // that are strings for simplicity. 3323 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3324 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3325 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3326 unsigned RequiredPadding = 4 - (Size % 4); 3327 bool PaddingPossible = 3328 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3329 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3330 Size == 0) 3331 return SDValue(); 3332 3333 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3334 MachineFunction &MF = DAG.getMachineFunction(); 3335 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3336 3337 // We can't bloat the constant pool too much, else the ConstantIslands pass 3338 // may fail to converge. If we haven't promoted this global yet (it may have 3339 // multiple uses), and promoting it would increase the constant pool size (Sz 3340 // > 4), ensure we have space to do so up to MaxTotal. 3341 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3342 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3343 ConstpoolPromotionMaxTotal) 3344 return SDValue(); 3345 3346 // This is only valid if all users are in a single function; we can't clone 3347 // the constant in general. The LLVM IR unnamed_addr allows merging 3348 // constants, but not cloning them. 3349 // 3350 // We could potentially allow cloning if we could prove all uses of the 3351 // constant in the current function don't care about the address, like 3352 // printf format strings. But that isn't implemented for now. 3353 if (!allUsersAreInFunction(GVar, &F)) 3354 return SDValue(); 3355 3356 // We're going to inline this global. Pad it out if needed. 3357 if (RequiredPadding != 4) { 3358 StringRef S = CDAInit->getAsString(); 3359 3360 SmallVector<uint8_t,16> V(S.size()); 3361 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3362 while (RequiredPadding--) 3363 V.push_back(0); 3364 Init = ConstantDataArray::get(*DAG.getContext(), V); 3365 } 3366 3367 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3368 SDValue CPAddr = 3369 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3370 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3371 AFI->markGlobalAsPromotedToConstantPool(GVar); 3372 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3373 PaddedSize - 4); 3374 } 3375 ++NumConstpoolPromoted; 3376 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3377 } 3378 3379 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3380 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3381 if (!(GV = GA->getBaseObject())) 3382 return false; 3383 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3384 return V->isConstant(); 3385 return isa<Function>(GV); 3386 } 3387 3388 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3389 SelectionDAG &DAG) const { 3390 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3391 default: llvm_unreachable("unknown object format"); 3392 case Triple::COFF: 3393 return LowerGlobalAddressWindows(Op, DAG); 3394 case Triple::ELF: 3395 return LowerGlobalAddressELF(Op, DAG); 3396 case Triple::MachO: 3397 return LowerGlobalAddressDarwin(Op, DAG); 3398 } 3399 } 3400 3401 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3402 SelectionDAG &DAG) const { 3403 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3404 SDLoc dl(Op); 3405 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3406 const TargetMachine &TM = getTargetMachine(); 3407 bool IsRO = isReadOnly(GV); 3408 3409 // promoteToConstantPool only if not generating XO text section 3410 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3411 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3412 return V; 3413 3414 if (isPositionIndependent()) { 3415 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3416 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3417 UseGOT_PREL ? ARMII::MO_GOT : 0); 3418 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3419 if (UseGOT_PREL) 3420 Result = 3421 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3422 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3423 return Result; 3424 } else if (Subtarget->isROPI() && IsRO) { 3425 // PC-relative. 3426 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3427 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3428 return Result; 3429 } else if (Subtarget->isRWPI() && !IsRO) { 3430 // SB-relative. 3431 SDValue RelAddr; 3432 if (Subtarget->useMovt()) { 3433 ++NumMovwMovt; 3434 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3435 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3436 } else { // use literal pool for address constant 3437 ARMConstantPoolValue *CPV = 3438 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3439 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3440 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3441 RelAddr = DAG.getLoad( 3442 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3443 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3444 } 3445 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3446 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3447 return Result; 3448 } 3449 3450 // If we have T2 ops, we can materialize the address directly via movt/movw 3451 // pair. This is always cheaper. 3452 if (Subtarget->useMovt()) { 3453 ++NumMovwMovt; 3454 // FIXME: Once remat is capable of dealing with instructions with register 3455 // operands, expand this into two nodes. 3456 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3457 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3458 } else { 3459 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3460 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3461 return DAG.getLoad( 3462 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3463 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3464 } 3465 } 3466 3467 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3468 SelectionDAG &DAG) const { 3469 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3470 "ROPI/RWPI not currently supported for Darwin"); 3471 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3472 SDLoc dl(Op); 3473 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3474 3475 if (Subtarget->useMovt()) 3476 ++NumMovwMovt; 3477 3478 // FIXME: Once remat is capable of dealing with instructions with register 3479 // operands, expand this into multiple nodes 3480 unsigned Wrapper = 3481 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3482 3483 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3484 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3485 3486 if (Subtarget->isGVIndirectSymbol(GV)) 3487 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3488 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3489 return Result; 3490 } 3491 3492 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3493 SelectionDAG &DAG) const { 3494 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3495 assert(Subtarget->useMovt() && 3496 "Windows on ARM expects to use movw/movt"); 3497 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3498 "ROPI/RWPI not currently supported for Windows"); 3499 3500 const TargetMachine &TM = getTargetMachine(); 3501 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3502 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3503 if (GV->hasDLLImportStorageClass()) 3504 TargetFlags = ARMII::MO_DLLIMPORT; 3505 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3506 TargetFlags = ARMII::MO_COFFSTUB; 3507 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3508 SDValue Result; 3509 SDLoc DL(Op); 3510 3511 ++NumMovwMovt; 3512 3513 // FIXME: Once remat is capable of dealing with instructions with register 3514 // operands, expand this into two nodes. 3515 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3516 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3517 TargetFlags)); 3518 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3519 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3520 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3521 return Result; 3522 } 3523 3524 SDValue 3525 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3526 SDLoc dl(Op); 3527 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3528 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3529 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3530 Op.getOperand(1), Val); 3531 } 3532 3533 SDValue 3534 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3535 SDLoc dl(Op); 3536 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3537 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3538 } 3539 3540 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3541 SelectionDAG &DAG) const { 3542 SDLoc dl(Op); 3543 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3544 Op.getOperand(0)); 3545 } 3546 3547 SDValue 3548 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3549 const ARMSubtarget *Subtarget) const { 3550 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3551 SDLoc dl(Op); 3552 switch (IntNo) { 3553 default: return SDValue(); // Don't custom lower most intrinsics. 3554 case Intrinsic::thread_pointer: { 3555 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3556 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3557 } 3558 case Intrinsic::eh_sjlj_lsda: { 3559 MachineFunction &MF = DAG.getMachineFunction(); 3560 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3561 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3562 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3563 SDValue CPAddr; 3564 bool IsPositionIndependent = isPositionIndependent(); 3565 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3566 ARMConstantPoolValue *CPV = 3567 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3568 ARMCP::CPLSDA, PCAdj); 3569 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3570 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3571 SDValue Result = DAG.getLoad( 3572 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3573 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3574 3575 if (IsPositionIndependent) { 3576 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3577 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3578 } 3579 return Result; 3580 } 3581 case Intrinsic::arm_neon_vabs: 3582 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3583 Op.getOperand(1)); 3584 case Intrinsic::arm_neon_vmulls: 3585 case Intrinsic::arm_neon_vmullu: { 3586 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3587 ? ARMISD::VMULLs : ARMISD::VMULLu; 3588 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3589 Op.getOperand(1), Op.getOperand(2)); 3590 } 3591 case Intrinsic::arm_neon_vminnm: 3592 case Intrinsic::arm_neon_vmaxnm: { 3593 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3594 ? ISD::FMINNUM : ISD::FMAXNUM; 3595 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3596 Op.getOperand(1), Op.getOperand(2)); 3597 } 3598 case Intrinsic::arm_neon_vminu: 3599 case Intrinsic::arm_neon_vmaxu: { 3600 if (Op.getValueType().isFloatingPoint()) 3601 return SDValue(); 3602 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3603 ? ISD::UMIN : ISD::UMAX; 3604 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3605 Op.getOperand(1), Op.getOperand(2)); 3606 } 3607 case Intrinsic::arm_neon_vmins: 3608 case Intrinsic::arm_neon_vmaxs: { 3609 // v{min,max}s is overloaded between signed integers and floats. 3610 if (!Op.getValueType().isFloatingPoint()) { 3611 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3612 ? ISD::SMIN : ISD::SMAX; 3613 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3614 Op.getOperand(1), Op.getOperand(2)); 3615 } 3616 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3617 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3618 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3619 Op.getOperand(1), Op.getOperand(2)); 3620 } 3621 case Intrinsic::arm_neon_vtbl1: 3622 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3623 Op.getOperand(1), Op.getOperand(2)); 3624 case Intrinsic::arm_neon_vtbl2: 3625 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3626 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3627 } 3628 } 3629 3630 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3631 const ARMSubtarget *Subtarget) { 3632 SDLoc dl(Op); 3633 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3634 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3635 if (SSID == SyncScope::SingleThread) 3636 return Op; 3637 3638 if (!Subtarget->hasDataBarrier()) { 3639 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3640 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3641 // here. 3642 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3643 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3644 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3645 DAG.getConstant(0, dl, MVT::i32)); 3646 } 3647 3648 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3649 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3650 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3651 if (Subtarget->isMClass()) { 3652 // Only a full system barrier exists in the M-class architectures. 3653 Domain = ARM_MB::SY; 3654 } else if (Subtarget->preferISHSTBarriers() && 3655 Ord == AtomicOrdering::Release) { 3656 // Swift happens to implement ISHST barriers in a way that's compatible with 3657 // Release semantics but weaker than ISH so we'd be fools not to use 3658 // it. Beware: other processors probably don't! 3659 Domain = ARM_MB::ISHST; 3660 } 3661 3662 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3663 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3664 DAG.getConstant(Domain, dl, MVT::i32)); 3665 } 3666 3667 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3668 const ARMSubtarget *Subtarget) { 3669 // ARM pre v5TE and Thumb1 does not have preload instructions. 3670 if (!(Subtarget->isThumb2() || 3671 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3672 // Just preserve the chain. 3673 return Op.getOperand(0); 3674 3675 SDLoc dl(Op); 3676 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3677 if (!isRead && 3678 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3679 // ARMv7 with MP extension has PLDW. 3680 return Op.getOperand(0); 3681 3682 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3683 if (Subtarget->isThumb()) { 3684 // Invert the bits. 3685 isRead = ~isRead & 1; 3686 isData = ~isData & 1; 3687 } 3688 3689 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3690 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3691 DAG.getConstant(isData, dl, MVT::i32)); 3692 } 3693 3694 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3695 MachineFunction &MF = DAG.getMachineFunction(); 3696 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3697 3698 // vastart just stores the address of the VarArgsFrameIndex slot into the 3699 // memory location argument. 3700 SDLoc dl(Op); 3701 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3702 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3703 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3704 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3705 MachinePointerInfo(SV)); 3706 } 3707 3708 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3709 CCValAssign &NextVA, 3710 SDValue &Root, 3711 SelectionDAG &DAG, 3712 const SDLoc &dl) const { 3713 MachineFunction &MF = DAG.getMachineFunction(); 3714 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3715 3716 const TargetRegisterClass *RC; 3717 if (AFI->isThumb1OnlyFunction()) 3718 RC = &ARM::tGPRRegClass; 3719 else 3720 RC = &ARM::GPRRegClass; 3721 3722 // Transform the arguments stored in physical registers into virtual ones. 3723 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3724 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3725 3726 SDValue ArgValue2; 3727 if (NextVA.isMemLoc()) { 3728 MachineFrameInfo &MFI = MF.getFrameInfo(); 3729 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3730 3731 // Create load node to retrieve arguments from the stack. 3732 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3733 ArgValue2 = DAG.getLoad( 3734 MVT::i32, dl, Root, FIN, 3735 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3736 } else { 3737 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3738 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3739 } 3740 if (!Subtarget->isLittle()) 3741 std::swap (ArgValue, ArgValue2); 3742 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3743 } 3744 3745 // The remaining GPRs hold either the beginning of variable-argument 3746 // data, or the beginning of an aggregate passed by value (usually 3747 // byval). Either way, we allocate stack slots adjacent to the data 3748 // provided by our caller, and store the unallocated registers there. 3749 // If this is a variadic function, the va_list pointer will begin with 3750 // these values; otherwise, this reassembles a (byval) structure that 3751 // was split between registers and memory. 3752 // Return: The frame index registers were stored into. 3753 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3754 const SDLoc &dl, SDValue &Chain, 3755 const Value *OrigArg, 3756 unsigned InRegsParamRecordIdx, 3757 int ArgOffset, unsigned ArgSize) const { 3758 // Currently, two use-cases possible: 3759 // Case #1. Non-var-args function, and we meet first byval parameter. 3760 // Setup first unallocated register as first byval register; 3761 // eat all remained registers 3762 // (these two actions are performed by HandleByVal method). 3763 // Then, here, we initialize stack frame with 3764 // "store-reg" instructions. 3765 // Case #2. Var-args function, that doesn't contain byval parameters. 3766 // The same: eat all remained unallocated registers, 3767 // initialize stack frame. 3768 3769 MachineFunction &MF = DAG.getMachineFunction(); 3770 MachineFrameInfo &MFI = MF.getFrameInfo(); 3771 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3772 unsigned RBegin, REnd; 3773 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3774 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3775 } else { 3776 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3777 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3778 REnd = ARM::R4; 3779 } 3780 3781 if (REnd != RBegin) 3782 ArgOffset = -4 * (ARM::R4 - RBegin); 3783 3784 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3785 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3786 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3787 3788 SmallVector<SDValue, 4> MemOps; 3789 const TargetRegisterClass *RC = 3790 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3791 3792 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3793 unsigned VReg = MF.addLiveIn(Reg, RC); 3794 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3795 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3796 MachinePointerInfo(OrigArg, 4 * i)); 3797 MemOps.push_back(Store); 3798 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3799 } 3800 3801 if (!MemOps.empty()) 3802 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3803 return FrameIndex; 3804 } 3805 3806 // Setup stack frame, the va_list pointer will start from. 3807 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3808 const SDLoc &dl, SDValue &Chain, 3809 unsigned ArgOffset, 3810 unsigned TotalArgRegsSaveSize, 3811 bool ForceMutable) const { 3812 MachineFunction &MF = DAG.getMachineFunction(); 3813 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3814 3815 // Try to store any remaining integer argument regs 3816 // to their spots on the stack so that they may be loaded by dereferencing 3817 // the result of va_next. 3818 // If there is no regs to be stored, just point address after last 3819 // argument passed via stack. 3820 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3821 CCInfo.getInRegsParamsCount(), 3822 CCInfo.getNextStackOffset(), 3823 std::max(4U, TotalArgRegsSaveSize)); 3824 AFI->setVarArgsFrameIndex(FrameIndex); 3825 } 3826 3827 SDValue ARMTargetLowering::LowerFormalArguments( 3828 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3829 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3830 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3831 MachineFunction &MF = DAG.getMachineFunction(); 3832 MachineFrameInfo &MFI = MF.getFrameInfo(); 3833 3834 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3835 3836 // Assign locations to all of the incoming arguments. 3837 SmallVector<CCValAssign, 16> ArgLocs; 3838 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3839 *DAG.getContext()); 3840 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3841 3842 SmallVector<SDValue, 16> ArgValues; 3843 SDValue ArgValue; 3844 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3845 unsigned CurArgIdx = 0; 3846 3847 // Initially ArgRegsSaveSize is zero. 3848 // Then we increase this value each time we meet byval parameter. 3849 // We also increase this value in case of varargs function. 3850 AFI->setArgRegsSaveSize(0); 3851 3852 // Calculate the amount of stack space that we need to allocate to store 3853 // byval and variadic arguments that are passed in registers. 3854 // We need to know this before we allocate the first byval or variadic 3855 // argument, as they will be allocated a stack slot below the CFA (Canonical 3856 // Frame Address, the stack pointer at entry to the function). 3857 unsigned ArgRegBegin = ARM::R4; 3858 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3859 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3860 break; 3861 3862 CCValAssign &VA = ArgLocs[i]; 3863 unsigned Index = VA.getValNo(); 3864 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3865 if (!Flags.isByVal()) 3866 continue; 3867 3868 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3869 unsigned RBegin, REnd; 3870 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3871 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3872 3873 CCInfo.nextInRegsParam(); 3874 } 3875 CCInfo.rewindByValRegsInfo(); 3876 3877 int lastInsIndex = -1; 3878 if (isVarArg && MFI.hasVAStart()) { 3879 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3880 if (RegIdx != array_lengthof(GPRArgRegs)) 3881 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3882 } 3883 3884 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3885 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3886 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3887 3888 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3889 CCValAssign &VA = ArgLocs[i]; 3890 if (Ins[VA.getValNo()].isOrigArg()) { 3891 std::advance(CurOrigArg, 3892 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3893 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3894 } 3895 // Arguments stored in registers. 3896 if (VA.isRegLoc()) { 3897 EVT RegVT = VA.getLocVT(); 3898 3899 if (VA.needsCustom()) { 3900 // f64 and vector types are split up into multiple registers or 3901 // combinations of registers and stack slots. 3902 if (VA.getLocVT() == MVT::v2f64) { 3903 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3904 Chain, DAG, dl); 3905 VA = ArgLocs[++i]; // skip ahead to next loc 3906 SDValue ArgValue2; 3907 if (VA.isMemLoc()) { 3908 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3909 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3910 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3911 MachinePointerInfo::getFixedStack( 3912 DAG.getMachineFunction(), FI)); 3913 } else { 3914 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3915 Chain, DAG, dl); 3916 } 3917 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3918 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3919 ArgValue, ArgValue1, 3920 DAG.getIntPtrConstant(0, dl)); 3921 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3922 ArgValue, ArgValue2, 3923 DAG.getIntPtrConstant(1, dl)); 3924 } else 3925 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3926 } else { 3927 const TargetRegisterClass *RC; 3928 3929 3930 if (RegVT == MVT::f16) 3931 RC = &ARM::HPRRegClass; 3932 else if (RegVT == MVT::f32) 3933 RC = &ARM::SPRRegClass; 3934 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3935 RC = &ARM::DPRRegClass; 3936 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3937 RC = &ARM::QPRRegClass; 3938 else if (RegVT == MVT::i32) 3939 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3940 : &ARM::GPRRegClass; 3941 else 3942 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3943 3944 // Transform the arguments in physical registers into virtual ones. 3945 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3946 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3947 3948 // If this value is passed in r0 and has the returned attribute (e.g. 3949 // C++ 'structors), record this fact for later use. 3950 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 3951 AFI->setPreservesR0(); 3952 } 3953 } 3954 3955 // If this is an 8 or 16-bit value, it is really passed promoted 3956 // to 32 bits. Insert an assert[sz]ext to capture this, then 3957 // truncate to the right size. 3958 switch (VA.getLocInfo()) { 3959 default: llvm_unreachable("Unknown loc info!"); 3960 case CCValAssign::Full: break; 3961 case CCValAssign::BCvt: 3962 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3963 break; 3964 case CCValAssign::SExt: 3965 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3966 DAG.getValueType(VA.getValVT())); 3967 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3968 break; 3969 case CCValAssign::ZExt: 3970 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3971 DAG.getValueType(VA.getValVT())); 3972 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3973 break; 3974 } 3975 3976 InVals.push_back(ArgValue); 3977 } else { // VA.isRegLoc() 3978 // sanity check 3979 assert(VA.isMemLoc()); 3980 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3981 3982 int index = VA.getValNo(); 3983 3984 // Some Ins[] entries become multiple ArgLoc[] entries. 3985 // Process them only once. 3986 if (index != lastInsIndex) 3987 { 3988 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3989 // FIXME: For now, all byval parameter objects are marked mutable. 3990 // This can be changed with more analysis. 3991 // In case of tail call optimization mark all arguments mutable. 3992 // Since they could be overwritten by lowering of arguments in case of 3993 // a tail call. 3994 if (Flags.isByVal()) { 3995 assert(Ins[index].isOrigArg() && 3996 "Byval arguments cannot be implicit"); 3997 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3998 3999 int FrameIndex = StoreByValRegs( 4000 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 4001 VA.getLocMemOffset(), Flags.getByValSize()); 4002 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 4003 CCInfo.nextInRegsParam(); 4004 } else { 4005 unsigned FIOffset = VA.getLocMemOffset(); 4006 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 4007 FIOffset, true); 4008 4009 // Create load nodes to retrieve arguments from the stack. 4010 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4011 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 4012 MachinePointerInfo::getFixedStack( 4013 DAG.getMachineFunction(), FI))); 4014 } 4015 lastInsIndex = index; 4016 } 4017 } 4018 } 4019 4020 // varargs 4021 if (isVarArg && MFI.hasVAStart()) 4022 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 4023 CCInfo.getNextStackOffset(), 4024 TotalArgRegsSaveSize); 4025 4026 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4027 4028 return Chain; 4029 } 4030 4031 /// isFloatingPointZero - Return true if this is +0.0. 4032 static bool isFloatingPointZero(SDValue Op) { 4033 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4034 return CFP->getValueAPF().isPosZero(); 4035 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4036 // Maybe this has already been legalized into the constant pool? 4037 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4038 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4039 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4040 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4041 return CFP->getValueAPF().isPosZero(); 4042 } 4043 } else if (Op->getOpcode() == ISD::BITCAST && 4044 Op->getValueType(0) == MVT::f64) { 4045 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4046 // created by LowerConstantFP(). 4047 SDValue BitcastOp = Op->getOperand(0); 4048 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4049 isNullConstant(BitcastOp->getOperand(0))) 4050 return true; 4051 } 4052 return false; 4053 } 4054 4055 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4056 /// the given operands. 4057 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4058 SDValue &ARMcc, SelectionDAG &DAG, 4059 const SDLoc &dl) const { 4060 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4061 unsigned C = RHSC->getZExtValue(); 4062 if (!isLegalICmpImmediate((int32_t)C)) { 4063 // Constant does not fit, try adjusting it by one. 4064 switch (CC) { 4065 default: break; 4066 case ISD::SETLT: 4067 case ISD::SETGE: 4068 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4069 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4070 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4071 } 4072 break; 4073 case ISD::SETULT: 4074 case ISD::SETUGE: 4075 if (C != 0 && isLegalICmpImmediate(C-1)) { 4076 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4077 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4078 } 4079 break; 4080 case ISD::SETLE: 4081 case ISD::SETGT: 4082 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4083 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4084 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4085 } 4086 break; 4087 case ISD::SETULE: 4088 case ISD::SETUGT: 4089 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4090 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4091 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4092 } 4093 break; 4094 } 4095 } 4096 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4097 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4098 // In ARM and Thumb-2, the compare instructions can shift their second 4099 // operand. 4100 CC = ISD::getSetCCSwappedOperands(CC); 4101 std::swap(LHS, RHS); 4102 } 4103 4104 // Thumb1 has very limited immediate modes, so turning an "and" into a 4105 // shift can save multiple instructions. 4106 // 4107 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4108 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4109 // own. If it's the operand to an unsigned comparison with an immediate, 4110 // we can eliminate one of the shifts: we transform 4111 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4112 // 4113 // We avoid transforming cases which aren't profitable due to encoding 4114 // details: 4115 // 4116 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4117 // would not; in that case, we're essentially trading one immediate load for 4118 // another. 4119 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4120 // 3. C2 is zero; we have other code for this special case. 4121 // 4122 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4123 // instruction, since the AND is always one instruction anyway, but we could 4124 // use narrow instructions in some cases. 4125 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4126 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4127 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4128 !isSignedIntSetCC(CC)) { 4129 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4130 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4131 uint64_t RHSV = RHSC->getZExtValue(); 4132 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4133 unsigned ShiftBits = countLeadingZeros(Mask); 4134 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4135 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4136 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4137 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4138 } 4139 } 4140 } 4141 4142 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4143 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4144 // way a cmp would. 4145 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4146 // some tweaks to the heuristics for the previous and->shift transform. 4147 // FIXME: Optimize cases where the LHS isn't a shift. 4148 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4149 isa<ConstantSDNode>(RHS) && 4150 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4151 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4152 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4153 unsigned ShiftAmt = 4154 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4155 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4156 DAG.getVTList(MVT::i32, MVT::i32), 4157 LHS.getOperand(0), 4158 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4159 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4160 Shift.getValue(1), SDValue()); 4161 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4162 return Chain.getValue(1); 4163 } 4164 4165 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4166 4167 // If the RHS is a constant zero then the V (overflow) flag will never be 4168 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4169 // simpler for other passes (like the peephole optimiser) to deal with. 4170 if (isNullConstant(RHS)) { 4171 switch (CondCode) { 4172 default: break; 4173 case ARMCC::GE: 4174 CondCode = ARMCC::PL; 4175 break; 4176 case ARMCC::LT: 4177 CondCode = ARMCC::MI; 4178 break; 4179 } 4180 } 4181 4182 ARMISD::NodeType CompareType; 4183 switch (CondCode) { 4184 default: 4185 CompareType = ARMISD::CMP; 4186 break; 4187 case ARMCC::EQ: 4188 case ARMCC::NE: 4189 // Uses only Z Flag 4190 CompareType = ARMISD::CMPZ; 4191 break; 4192 } 4193 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4194 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4195 } 4196 4197 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4198 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4199 SelectionDAG &DAG, const SDLoc &dl, 4200 bool InvalidOnQNaN) const { 4201 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4202 SDValue Cmp; 4203 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 4204 if (!isFloatingPointZero(RHS)) 4205 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 4206 else 4207 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 4208 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4209 } 4210 4211 /// duplicateCmp - Glue values can have only one use, so this function 4212 /// duplicates a comparison node. 4213 SDValue 4214 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4215 unsigned Opc = Cmp.getOpcode(); 4216 SDLoc DL(Cmp); 4217 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4218 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4219 4220 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4221 Cmp = Cmp.getOperand(0); 4222 Opc = Cmp.getOpcode(); 4223 if (Opc == ARMISD::CMPFP) 4224 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4225 Cmp.getOperand(1), Cmp.getOperand(2)); 4226 else { 4227 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4228 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4229 Cmp.getOperand(1)); 4230 } 4231 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4232 } 4233 4234 // This function returns three things: the arithmetic computation itself 4235 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4236 // comparison and the condition code define the case in which the arithmetic 4237 // computation *does not* overflow. 4238 std::pair<SDValue, SDValue> 4239 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4240 SDValue &ARMcc) const { 4241 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4242 4243 SDValue Value, OverflowCmp; 4244 SDValue LHS = Op.getOperand(0); 4245 SDValue RHS = Op.getOperand(1); 4246 SDLoc dl(Op); 4247 4248 // FIXME: We are currently always generating CMPs because we don't support 4249 // generating CMN through the backend. This is not as good as the natural 4250 // CMP case because it causes a register dependency and cannot be folded 4251 // later. 4252 4253 switch (Op.getOpcode()) { 4254 default: 4255 llvm_unreachable("Unknown overflow instruction!"); 4256 case ISD::SADDO: 4257 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4258 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4259 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4260 break; 4261 case ISD::UADDO: 4262 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4263 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4264 // We do not use it in the USUBO case as Value may not be used. 4265 Value = DAG.getNode(ARMISD::ADDC, dl, 4266 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4267 .getValue(0); 4268 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4269 break; 4270 case ISD::SSUBO: 4271 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4272 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4273 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4274 break; 4275 case ISD::USUBO: 4276 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4277 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4278 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4279 break; 4280 case ISD::UMULO: 4281 // We generate a UMUL_LOHI and then check if the high word is 0. 4282 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4283 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4284 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4285 LHS, RHS); 4286 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4287 DAG.getConstant(0, dl, MVT::i32)); 4288 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4289 break; 4290 case ISD::SMULO: 4291 // We generate a SMUL_LOHI and then check if all the bits of the high word 4292 // are the same as the sign bit of the low word. 4293 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4294 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4295 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4296 LHS, RHS); 4297 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4298 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4299 Value.getValue(0), 4300 DAG.getConstant(31, dl, MVT::i32))); 4301 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4302 break; 4303 } // switch (...) 4304 4305 return std::make_pair(Value, OverflowCmp); 4306 } 4307 4308 SDValue 4309 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4310 // Let legalize expand this if it isn't a legal type yet. 4311 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4312 return SDValue(); 4313 4314 SDValue Value, OverflowCmp; 4315 SDValue ARMcc; 4316 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4317 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4318 SDLoc dl(Op); 4319 // We use 0 and 1 as false and true values. 4320 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4321 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4322 EVT VT = Op.getValueType(); 4323 4324 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4325 ARMcc, CCR, OverflowCmp); 4326 4327 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4328 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4329 } 4330 4331 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4332 SelectionDAG &DAG) { 4333 SDLoc DL(BoolCarry); 4334 EVT CarryVT = BoolCarry.getValueType(); 4335 4336 // This converts the boolean value carry into the carry flag by doing 4337 // ARMISD::SUBC Carry, 1 4338 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4339 DAG.getVTList(CarryVT, MVT::i32), 4340 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4341 return Carry.getValue(1); 4342 } 4343 4344 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4345 SelectionDAG &DAG) { 4346 SDLoc DL(Flags); 4347 4348 // Now convert the carry flag into a boolean carry. We do this 4349 // using ARMISD:ADDE 0, 0, Carry 4350 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4351 DAG.getConstant(0, DL, MVT::i32), 4352 DAG.getConstant(0, DL, MVT::i32), Flags); 4353 } 4354 4355 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4356 SelectionDAG &DAG) const { 4357 // Let legalize expand this if it isn't a legal type yet. 4358 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4359 return SDValue(); 4360 4361 SDValue LHS = Op.getOperand(0); 4362 SDValue RHS = Op.getOperand(1); 4363 SDLoc dl(Op); 4364 4365 EVT VT = Op.getValueType(); 4366 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4367 SDValue Value; 4368 SDValue Overflow; 4369 switch (Op.getOpcode()) { 4370 default: 4371 llvm_unreachable("Unknown overflow instruction!"); 4372 case ISD::UADDO: 4373 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4374 // Convert the carry flag into a boolean value. 4375 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4376 break; 4377 case ISD::USUBO: { 4378 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4379 // Convert the carry flag into a boolean value. 4380 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4381 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4382 // value. So compute 1 - C. 4383 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4384 DAG.getConstant(1, dl, MVT::i32), Overflow); 4385 break; 4386 } 4387 } 4388 4389 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4390 } 4391 4392 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4393 SDValue Cond = Op.getOperand(0); 4394 SDValue SelectTrue = Op.getOperand(1); 4395 SDValue SelectFalse = Op.getOperand(2); 4396 SDLoc dl(Op); 4397 unsigned Opc = Cond.getOpcode(); 4398 4399 if (Cond.getResNo() == 1 && 4400 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4401 Opc == ISD::USUBO)) { 4402 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4403 return SDValue(); 4404 4405 SDValue Value, OverflowCmp; 4406 SDValue ARMcc; 4407 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4408 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4409 EVT VT = Op.getValueType(); 4410 4411 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4412 OverflowCmp, DAG); 4413 } 4414 4415 // Convert: 4416 // 4417 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4418 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4419 // 4420 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4421 const ConstantSDNode *CMOVTrue = 4422 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4423 const ConstantSDNode *CMOVFalse = 4424 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4425 4426 if (CMOVTrue && CMOVFalse) { 4427 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4428 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4429 4430 SDValue True; 4431 SDValue False; 4432 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4433 True = SelectTrue; 4434 False = SelectFalse; 4435 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4436 True = SelectFalse; 4437 False = SelectTrue; 4438 } 4439 4440 if (True.getNode() && False.getNode()) { 4441 EVT VT = Op.getValueType(); 4442 SDValue ARMcc = Cond.getOperand(2); 4443 SDValue CCR = Cond.getOperand(3); 4444 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4445 assert(True.getValueType() == VT); 4446 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4447 } 4448 } 4449 } 4450 4451 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4452 // undefined bits before doing a full-word comparison with zero. 4453 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4454 DAG.getConstant(1, dl, Cond.getValueType())); 4455 4456 return DAG.getSelectCC(dl, Cond, 4457 DAG.getConstant(0, dl, Cond.getValueType()), 4458 SelectTrue, SelectFalse, ISD::SETNE); 4459 } 4460 4461 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4462 bool &swpCmpOps, bool &swpVselOps) { 4463 // Start by selecting the GE condition code for opcodes that return true for 4464 // 'equality' 4465 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4466 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4467 CondCode = ARMCC::GE; 4468 4469 // and GT for opcodes that return false for 'equality'. 4470 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4471 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4472 CondCode = ARMCC::GT; 4473 4474 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4475 // to swap the compare operands. 4476 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4477 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4478 swpCmpOps = true; 4479 4480 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4481 // If we have an unordered opcode, we need to swap the operands to the VSEL 4482 // instruction (effectively negating the condition). 4483 // 4484 // This also has the effect of swapping which one of 'less' or 'greater' 4485 // returns true, so we also swap the compare operands. It also switches 4486 // whether we return true for 'equality', so we compensate by picking the 4487 // opposite condition code to our original choice. 4488 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4489 CC == ISD::SETUGT) { 4490 swpCmpOps = !swpCmpOps; 4491 swpVselOps = !swpVselOps; 4492 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4493 } 4494 4495 // 'ordered' is 'anything but unordered', so use the VS condition code and 4496 // swap the VSEL operands. 4497 if (CC == ISD::SETO) { 4498 CondCode = ARMCC::VS; 4499 swpVselOps = true; 4500 } 4501 4502 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4503 // code and swap the VSEL operands. Also do this if we don't care about the 4504 // unordered case. 4505 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4506 CondCode = ARMCC::EQ; 4507 swpVselOps = true; 4508 } 4509 } 4510 4511 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4512 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4513 SDValue Cmp, SelectionDAG &DAG) const { 4514 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4515 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4516 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4517 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4518 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4519 4520 SDValue TrueLow = TrueVal.getValue(0); 4521 SDValue TrueHigh = TrueVal.getValue(1); 4522 SDValue FalseLow = FalseVal.getValue(0); 4523 SDValue FalseHigh = FalseVal.getValue(1); 4524 4525 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4526 ARMcc, CCR, Cmp); 4527 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4528 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4529 4530 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4531 } else { 4532 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4533 Cmp); 4534 } 4535 } 4536 4537 static bool isGTorGE(ISD::CondCode CC) { 4538 return CC == ISD::SETGT || CC == ISD::SETGE; 4539 } 4540 4541 static bool isLTorLE(ISD::CondCode CC) { 4542 return CC == ISD::SETLT || CC == ISD::SETLE; 4543 } 4544 4545 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4546 // All of these conditions (and their <= and >= counterparts) will do: 4547 // x < k ? k : x 4548 // x > k ? x : k 4549 // k < x ? x : k 4550 // k > x ? k : x 4551 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4552 const SDValue TrueVal, const SDValue FalseVal, 4553 const ISD::CondCode CC, const SDValue K) { 4554 return (isGTorGE(CC) && 4555 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4556 (isLTorLE(CC) && 4557 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4558 } 4559 4560 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4561 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4562 const SDValue TrueVal, const SDValue FalseVal, 4563 const ISD::CondCode CC, const SDValue K) { 4564 return (isGTorGE(CC) && 4565 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4566 (isLTorLE(CC) && 4567 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4568 } 4569 4570 // Check if two chained conditionals could be converted into SSAT or USAT. 4571 // 4572 // SSAT can replace a set of two conditional selectors that bound a number to an 4573 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4574 // 4575 // x < -k ? -k : (x > k ? k : x) 4576 // x < -k ? -k : (x < k ? x : k) 4577 // x > -k ? (x > k ? k : x) : -k 4578 // x < k ? (x < -k ? -k : x) : k 4579 // etc. 4580 // 4581 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4582 // a power of 2. 4583 // 4584 // It returns true if the conversion can be done, false otherwise. 4585 // Additionally, the variable is returned in parameter V, the constant in K and 4586 // usat is set to true if the conditional represents an unsigned saturation 4587 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4588 uint64_t &K, bool &usat) { 4589 SDValue LHS1 = Op.getOperand(0); 4590 SDValue RHS1 = Op.getOperand(1); 4591 SDValue TrueVal1 = Op.getOperand(2); 4592 SDValue FalseVal1 = Op.getOperand(3); 4593 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4594 4595 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4596 if (Op2.getOpcode() != ISD::SELECT_CC) 4597 return false; 4598 4599 SDValue LHS2 = Op2.getOperand(0); 4600 SDValue RHS2 = Op2.getOperand(1); 4601 SDValue TrueVal2 = Op2.getOperand(2); 4602 SDValue FalseVal2 = Op2.getOperand(3); 4603 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4604 4605 // Find out which are the constants and which are the variables 4606 // in each conditional 4607 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4608 ? &RHS1 4609 : nullptr; 4610 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4611 ? &RHS2 4612 : nullptr; 4613 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4614 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4615 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4616 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4617 4618 // We must detect cases where the original operations worked with 16- or 4619 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4620 // must work with sign-extended values but the select operations return 4621 // the original non-extended value. 4622 SDValue V2TmpReg = V2Tmp; 4623 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4624 V2TmpReg = V2Tmp->getOperand(0); 4625 4626 // Check that the registers and the constants have the correct values 4627 // in both conditionals 4628 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4629 V2TmpReg != V2) 4630 return false; 4631 4632 // Figure out which conditional is saturating the lower/upper bound. 4633 const SDValue *LowerCheckOp = 4634 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4635 ? &Op 4636 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4637 ? &Op2 4638 : nullptr; 4639 const SDValue *UpperCheckOp = 4640 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4641 ? &Op 4642 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4643 ? &Op2 4644 : nullptr; 4645 4646 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4647 return false; 4648 4649 // Check that the constant in the lower-bound check is 4650 // the opposite of the constant in the upper-bound check 4651 // in 1's complement. 4652 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4653 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4654 int64_t PosVal = std::max(Val1, Val2); 4655 int64_t NegVal = std::min(Val1, Val2); 4656 4657 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4658 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4659 isPowerOf2_64(PosVal + 1)) { 4660 4661 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4662 if (Val1 == ~Val2) 4663 usat = false; 4664 else if (NegVal == 0) 4665 usat = true; 4666 else 4667 return false; 4668 4669 V = V2; 4670 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4671 4672 return true; 4673 } 4674 4675 return false; 4676 } 4677 4678 // Check if a condition of the type x < k ? k : x can be converted into a 4679 // bit operation instead of conditional moves. 4680 // Currently this is allowed given: 4681 // - The conditions and values match up 4682 // - k is 0 or -1 (all ones) 4683 // This function will not check the last condition, thats up to the caller 4684 // It returns true if the transformation can be made, and in such case 4685 // returns x in V, and k in SatK. 4686 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4687 SDValue &SatK) 4688 { 4689 SDValue LHS = Op.getOperand(0); 4690 SDValue RHS = Op.getOperand(1); 4691 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4692 SDValue TrueVal = Op.getOperand(2); 4693 SDValue FalseVal = Op.getOperand(3); 4694 4695 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4696 ? &RHS 4697 : nullptr; 4698 4699 // No constant operation in comparison, early out 4700 if (!K) 4701 return false; 4702 4703 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4704 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4705 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4706 4707 // If the constant on left and right side, or variable on left and right, 4708 // does not match, early out 4709 if (*K != KTmp || V != VTmp) 4710 return false; 4711 4712 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4713 SatK = *K; 4714 return true; 4715 } 4716 4717 return false; 4718 } 4719 4720 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 4721 if (VT == MVT::f32) 4722 return !Subtarget->hasVFP2Base(); 4723 if (VT == MVT::f64) 4724 return !Subtarget->hasFP64(); 4725 if (VT == MVT::f16) 4726 return !Subtarget->hasFullFP16(); 4727 return false; 4728 } 4729 4730 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4731 EVT VT = Op.getValueType(); 4732 SDLoc dl(Op); 4733 4734 // Try to convert two saturating conditional selects into a single SSAT 4735 SDValue SatValue; 4736 uint64_t SatConstant; 4737 bool SatUSat; 4738 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4739 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4740 if (SatUSat) 4741 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4742 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4743 else 4744 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4745 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4746 } 4747 4748 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4749 // into more efficient bit operations, which is possible when k is 0 or -1 4750 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4751 // single instructions. On Thumb the shift and the bit operation will be two 4752 // instructions. 4753 // Only allow this transformation on full-width (32-bit) operations 4754 SDValue LowerSatConstant; 4755 if (VT == MVT::i32 && 4756 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4757 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4758 DAG.getConstant(31, dl, VT)); 4759 if (isNullConstant(LowerSatConstant)) { 4760 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4761 DAG.getAllOnesConstant(dl, VT)); 4762 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4763 } else if (isAllOnesConstant(LowerSatConstant)) 4764 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4765 } 4766 4767 SDValue LHS = Op.getOperand(0); 4768 SDValue RHS = Op.getOperand(1); 4769 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4770 SDValue TrueVal = Op.getOperand(2); 4771 SDValue FalseVal = Op.getOperand(3); 4772 4773 if (isUnsupportedFloatingType(LHS.getValueType())) { 4774 DAG.getTargetLoweringInfo().softenSetCCOperands( 4775 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 4776 4777 // If softenSetCCOperands only returned one value, we should compare it to 4778 // zero. 4779 if (!RHS.getNode()) { 4780 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4781 CC = ISD::SETNE; 4782 } 4783 } 4784 4785 if (LHS.getValueType() == MVT::i32) { 4786 // Try to generate VSEL on ARMv8. 4787 // The VSEL instruction can't use all the usual ARM condition 4788 // codes: it only has two bits to select the condition code, so it's 4789 // constrained to use only GE, GT, VS and EQ. 4790 // 4791 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4792 // swap the operands of the previous compare instruction (effectively 4793 // inverting the compare condition, swapping 'less' and 'greater') and 4794 // sometimes need to swap the operands to the VSEL (which inverts the 4795 // condition in the sense of firing whenever the previous condition didn't) 4796 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 4797 TrueVal.getValueType() == MVT::f32 || 4798 TrueVal.getValueType() == MVT::f64)) { 4799 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4800 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4801 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4802 CC = ISD::getSetCCInverse(CC, true); 4803 std::swap(TrueVal, FalseVal); 4804 } 4805 } 4806 4807 SDValue ARMcc; 4808 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4809 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4810 // Choose GE over PL, which vsel does now support 4811 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 4812 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 4813 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4814 } 4815 4816 ARMCC::CondCodes CondCode, CondCode2; 4817 bool InvalidOnQNaN; 4818 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4819 4820 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 4821 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 4822 // must use VSEL (limited condition codes), due to not having conditional f16 4823 // moves. 4824 if (Subtarget->hasFPARMv8Base() && 4825 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 4826 (TrueVal.getValueType() == MVT::f16 || 4827 TrueVal.getValueType() == MVT::f32 || 4828 TrueVal.getValueType() == MVT::f64)) { 4829 bool swpCmpOps = false; 4830 bool swpVselOps = false; 4831 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4832 4833 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4834 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4835 if (swpCmpOps) 4836 std::swap(LHS, RHS); 4837 if (swpVselOps) 4838 std::swap(TrueVal, FalseVal); 4839 } 4840 } 4841 4842 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4843 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4844 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4845 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4846 if (CondCode2 != ARMCC::AL) { 4847 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4848 // FIXME: Needs another CMP because flag can have but one use. 4849 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4850 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4851 } 4852 return Result; 4853 } 4854 4855 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4856 /// to morph to an integer compare sequence. 4857 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4858 const ARMSubtarget *Subtarget) { 4859 SDNode *N = Op.getNode(); 4860 if (!N->hasOneUse()) 4861 // Otherwise it requires moving the value from fp to integer registers. 4862 return false; 4863 if (!N->getNumValues()) 4864 return false; 4865 EVT VT = Op.getValueType(); 4866 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4867 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4868 // vmrs are very slow, e.g. cortex-a8. 4869 return false; 4870 4871 if (isFloatingPointZero(Op)) { 4872 SeenZero = true; 4873 return true; 4874 } 4875 return ISD::isNormalLoad(N); 4876 } 4877 4878 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4879 if (isFloatingPointZero(Op)) 4880 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4881 4882 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4883 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4884 Ld->getPointerInfo(), Ld->getAlignment(), 4885 Ld->getMemOperand()->getFlags()); 4886 4887 llvm_unreachable("Unknown VFP cmp argument!"); 4888 } 4889 4890 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4891 SDValue &RetVal1, SDValue &RetVal2) { 4892 SDLoc dl(Op); 4893 4894 if (isFloatingPointZero(Op)) { 4895 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4896 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4897 return; 4898 } 4899 4900 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4901 SDValue Ptr = Ld->getBasePtr(); 4902 RetVal1 = 4903 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4904 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4905 4906 EVT PtrType = Ptr.getValueType(); 4907 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4908 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4909 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4910 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4911 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4912 Ld->getMemOperand()->getFlags()); 4913 return; 4914 } 4915 4916 llvm_unreachable("Unknown VFP cmp argument!"); 4917 } 4918 4919 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4920 /// f32 and even f64 comparisons to integer ones. 4921 SDValue 4922 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4923 SDValue Chain = Op.getOperand(0); 4924 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4925 SDValue LHS = Op.getOperand(2); 4926 SDValue RHS = Op.getOperand(3); 4927 SDValue Dest = Op.getOperand(4); 4928 SDLoc dl(Op); 4929 4930 bool LHSSeenZero = false; 4931 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4932 bool RHSSeenZero = false; 4933 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4934 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4935 // If unsafe fp math optimization is enabled and there are no other uses of 4936 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4937 // to an integer comparison. 4938 if (CC == ISD::SETOEQ) 4939 CC = ISD::SETEQ; 4940 else if (CC == ISD::SETUNE) 4941 CC = ISD::SETNE; 4942 4943 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4944 SDValue ARMcc; 4945 if (LHS.getValueType() == MVT::f32) { 4946 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4947 bitcastf32Toi32(LHS, DAG), Mask); 4948 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4949 bitcastf32Toi32(RHS, DAG), Mask); 4950 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4951 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4952 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4953 Chain, Dest, ARMcc, CCR, Cmp); 4954 } 4955 4956 SDValue LHS1, LHS2; 4957 SDValue RHS1, RHS2; 4958 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4959 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4960 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4961 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4962 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4963 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4964 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4965 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4966 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4967 } 4968 4969 return SDValue(); 4970 } 4971 4972 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4973 SDValue Chain = Op.getOperand(0); 4974 SDValue Cond = Op.getOperand(1); 4975 SDValue Dest = Op.getOperand(2); 4976 SDLoc dl(Op); 4977 4978 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4979 // instruction. 4980 unsigned Opc = Cond.getOpcode(); 4981 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4982 !Subtarget->isThumb1Only(); 4983 if (Cond.getResNo() == 1 && 4984 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4985 Opc == ISD::USUBO || OptimizeMul)) { 4986 // Only lower legal XALUO ops. 4987 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4988 return SDValue(); 4989 4990 // The actual operation with overflow check. 4991 SDValue Value, OverflowCmp; 4992 SDValue ARMcc; 4993 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4994 4995 // Reverse the condition code. 4996 ARMCC::CondCodes CondCode = 4997 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4998 CondCode = ARMCC::getOppositeCondition(CondCode); 4999 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5000 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5001 5002 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5003 OverflowCmp); 5004 } 5005 5006 return SDValue(); 5007 } 5008 5009 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5010 SDValue Chain = Op.getOperand(0); 5011 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5012 SDValue LHS = Op.getOperand(2); 5013 SDValue RHS = Op.getOperand(3); 5014 SDValue Dest = Op.getOperand(4); 5015 SDLoc dl(Op); 5016 5017 if (isUnsupportedFloatingType(LHS.getValueType())) { 5018 DAG.getTargetLoweringInfo().softenSetCCOperands( 5019 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 5020 5021 // If softenSetCCOperands only returned one value, we should compare it to 5022 // zero. 5023 if (!RHS.getNode()) { 5024 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5025 CC = ISD::SETNE; 5026 } 5027 } 5028 5029 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5030 // instruction. 5031 unsigned Opc = LHS.getOpcode(); 5032 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5033 !Subtarget->isThumb1Only(); 5034 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5035 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5036 Opc == ISD::USUBO || OptimizeMul) && 5037 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5038 // Only lower legal XALUO ops. 5039 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5040 return SDValue(); 5041 5042 // The actual operation with overflow check. 5043 SDValue Value, OverflowCmp; 5044 SDValue ARMcc; 5045 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5046 5047 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5048 // Reverse the condition code. 5049 ARMCC::CondCodes CondCode = 5050 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5051 CondCode = ARMCC::getOppositeCondition(CondCode); 5052 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5053 } 5054 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5055 5056 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5057 OverflowCmp); 5058 } 5059 5060 if (LHS.getValueType() == MVT::i32) { 5061 SDValue ARMcc; 5062 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5063 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5064 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5065 Chain, Dest, ARMcc, CCR, Cmp); 5066 } 5067 5068 if (getTargetMachine().Options.UnsafeFPMath && 5069 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5070 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5071 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5072 return Result; 5073 } 5074 5075 ARMCC::CondCodes CondCode, CondCode2; 5076 bool InvalidOnQNaN; 5077 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 5078 5079 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5080 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 5081 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5082 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5083 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5084 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5085 if (CondCode2 != ARMCC::AL) { 5086 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5087 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5088 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5089 } 5090 return Res; 5091 } 5092 5093 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5094 SDValue Chain = Op.getOperand(0); 5095 SDValue Table = Op.getOperand(1); 5096 SDValue Index = Op.getOperand(2); 5097 SDLoc dl(Op); 5098 5099 EVT PTy = getPointerTy(DAG.getDataLayout()); 5100 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5101 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5102 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5103 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5104 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5105 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5106 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5107 // which does another jump to the destination. This also makes it easier 5108 // to translate it to TBB / TBH later (Thumb2 only). 5109 // FIXME: This might not work if the function is extremely large. 5110 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5111 Addr, Op.getOperand(2), JTI); 5112 } 5113 if (isPositionIndependent() || Subtarget->isROPI()) { 5114 Addr = 5115 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5116 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5117 Chain = Addr.getValue(1); 5118 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5119 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5120 } else { 5121 Addr = 5122 DAG.getLoad(PTy, dl, Chain, Addr, 5123 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5124 Chain = Addr.getValue(1); 5125 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5126 } 5127 } 5128 5129 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5130 EVT VT = Op.getValueType(); 5131 SDLoc dl(Op); 5132 5133 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5134 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5135 return Op; 5136 return DAG.UnrollVectorOp(Op.getNode()); 5137 } 5138 5139 const bool HasFullFP16 = 5140 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5141 5142 EVT NewTy; 5143 const EVT OpTy = Op.getOperand(0).getValueType(); 5144 if (OpTy == MVT::v4f32) 5145 NewTy = MVT::v4i32; 5146 else if (OpTy == MVT::v4f16 && HasFullFP16) 5147 NewTy = MVT::v4i16; 5148 else if (OpTy == MVT::v8f16 && HasFullFP16) 5149 NewTy = MVT::v8i16; 5150 else 5151 llvm_unreachable("Invalid type for custom lowering!"); 5152 5153 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5154 return DAG.UnrollVectorOp(Op.getNode()); 5155 5156 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5157 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5158 } 5159 5160 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5161 EVT VT = Op.getValueType(); 5162 if (VT.isVector()) 5163 return LowerVectorFP_TO_INT(Op, DAG); 5164 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) { 5165 RTLIB::Libcall LC; 5166 if (Op.getOpcode() == ISD::FP_TO_SINT) 5167 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 5168 Op.getValueType()); 5169 else 5170 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 5171 Op.getValueType()); 5172 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5173 /*isSigned*/ false, SDLoc(Op)).first; 5174 } 5175 5176 return Op; 5177 } 5178 5179 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5180 EVT VT = Op.getValueType(); 5181 SDLoc dl(Op); 5182 5183 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5184 if (VT.getVectorElementType() == MVT::f32) 5185 return Op; 5186 return DAG.UnrollVectorOp(Op.getNode()); 5187 } 5188 5189 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5190 Op.getOperand(0).getValueType() == MVT::v8i16) && 5191 "Invalid type for custom lowering!"); 5192 5193 const bool HasFullFP16 = 5194 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5195 5196 EVT DestVecType; 5197 if (VT == MVT::v4f32) 5198 DestVecType = MVT::v4i32; 5199 else if (VT == MVT::v4f16 && HasFullFP16) 5200 DestVecType = MVT::v4i16; 5201 else if (VT == MVT::v8f16 && HasFullFP16) 5202 DestVecType = MVT::v8i16; 5203 else 5204 return DAG.UnrollVectorOp(Op.getNode()); 5205 5206 unsigned CastOpc; 5207 unsigned Opc; 5208 switch (Op.getOpcode()) { 5209 default: llvm_unreachable("Invalid opcode!"); 5210 case ISD::SINT_TO_FP: 5211 CastOpc = ISD::SIGN_EXTEND; 5212 Opc = ISD::SINT_TO_FP; 5213 break; 5214 case ISD::UINT_TO_FP: 5215 CastOpc = ISD::ZERO_EXTEND; 5216 Opc = ISD::UINT_TO_FP; 5217 break; 5218 } 5219 5220 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5221 return DAG.getNode(Opc, dl, VT, Op); 5222 } 5223 5224 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5225 EVT VT = Op.getValueType(); 5226 if (VT.isVector()) 5227 return LowerVectorINT_TO_FP(Op, DAG); 5228 if (isUnsupportedFloatingType(VT)) { 5229 RTLIB::Libcall LC; 5230 if (Op.getOpcode() == ISD::SINT_TO_FP) 5231 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5232 Op.getValueType()); 5233 else 5234 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5235 Op.getValueType()); 5236 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5237 /*isSigned*/ false, SDLoc(Op)).first; 5238 } 5239 5240 return Op; 5241 } 5242 5243 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5244 // Implement fcopysign with a fabs and a conditional fneg. 5245 SDValue Tmp0 = Op.getOperand(0); 5246 SDValue Tmp1 = Op.getOperand(1); 5247 SDLoc dl(Op); 5248 EVT VT = Op.getValueType(); 5249 EVT SrcVT = Tmp1.getValueType(); 5250 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5251 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5252 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5253 5254 if (UseNEON) { 5255 // Use VBSL to copy the sign bit. 5256 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5257 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5258 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5259 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5260 if (VT == MVT::f64) 5261 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5262 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5263 DAG.getConstant(32, dl, MVT::i32)); 5264 else /*if (VT == MVT::f32)*/ 5265 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5266 if (SrcVT == MVT::f32) { 5267 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5268 if (VT == MVT::f64) 5269 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5270 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5271 DAG.getConstant(32, dl, MVT::i32)); 5272 } else if (VT == MVT::f32) 5273 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5274 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5275 DAG.getConstant(32, dl, MVT::i32)); 5276 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5277 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5278 5279 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5280 dl, MVT::i32); 5281 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5282 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5283 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5284 5285 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5286 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5287 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5288 if (VT == MVT::f32) { 5289 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5290 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5291 DAG.getConstant(0, dl, MVT::i32)); 5292 } else { 5293 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5294 } 5295 5296 return Res; 5297 } 5298 5299 // Bitcast operand 1 to i32. 5300 if (SrcVT == MVT::f64) 5301 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5302 Tmp1).getValue(1); 5303 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5304 5305 // Or in the signbit with integer operations. 5306 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5307 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5308 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5309 if (VT == MVT::f32) { 5310 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5311 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5312 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5313 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5314 } 5315 5316 // f64: Or the high part with signbit and then combine two parts. 5317 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5318 Tmp0); 5319 SDValue Lo = Tmp0.getValue(0); 5320 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5321 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5322 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5323 } 5324 5325 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5326 MachineFunction &MF = DAG.getMachineFunction(); 5327 MachineFrameInfo &MFI = MF.getFrameInfo(); 5328 MFI.setReturnAddressIsTaken(true); 5329 5330 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5331 return SDValue(); 5332 5333 EVT VT = Op.getValueType(); 5334 SDLoc dl(Op); 5335 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5336 if (Depth) { 5337 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5338 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5339 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5340 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5341 MachinePointerInfo()); 5342 } 5343 5344 // Return LR, which contains the return address. Mark it an implicit live-in. 5345 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5346 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5347 } 5348 5349 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5350 const ARMBaseRegisterInfo &ARI = 5351 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5352 MachineFunction &MF = DAG.getMachineFunction(); 5353 MachineFrameInfo &MFI = MF.getFrameInfo(); 5354 MFI.setFrameAddressIsTaken(true); 5355 5356 EVT VT = Op.getValueType(); 5357 SDLoc dl(Op); // FIXME probably not meaningful 5358 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5359 unsigned FrameReg = ARI.getFrameRegister(MF); 5360 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5361 while (Depth--) 5362 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5363 MachinePointerInfo()); 5364 return FrameAddr; 5365 } 5366 5367 // FIXME? Maybe this could be a TableGen attribute on some registers and 5368 // this table could be generated automatically from RegInfo. 5369 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5370 SelectionDAG &DAG) const { 5371 unsigned Reg = StringSwitch<unsigned>(RegName) 5372 .Case("sp", ARM::SP) 5373 .Default(0); 5374 if (Reg) 5375 return Reg; 5376 report_fatal_error(Twine("Invalid register name \"" 5377 + StringRef(RegName) + "\".")); 5378 } 5379 5380 // Result is 64 bit value so split into two 32 bit values and return as a 5381 // pair of values. 5382 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5383 SelectionDAG &DAG) { 5384 SDLoc DL(N); 5385 5386 // This function is only supposed to be called for i64 type destination. 5387 assert(N->getValueType(0) == MVT::i64 5388 && "ExpandREAD_REGISTER called for non-i64 type result."); 5389 5390 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5391 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5392 N->getOperand(0), 5393 N->getOperand(1)); 5394 5395 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5396 Read.getValue(1))); 5397 Results.push_back(Read.getOperand(0)); 5398 } 5399 5400 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5401 /// When \p DstVT, the destination type of \p BC, is on the vector 5402 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5403 /// it might be possible to combine them, such that everything stays on the 5404 /// vector register bank. 5405 /// \p return The node that would replace \p BT, if the combine 5406 /// is possible. 5407 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5408 SelectionDAG &DAG) { 5409 SDValue Op = BC->getOperand(0); 5410 EVT DstVT = BC->getValueType(0); 5411 5412 // The only vector instruction that can produce a scalar (remember, 5413 // since the bitcast was about to be turned into VMOVDRR, the source 5414 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5415 // Moreover, we can do this combine only if there is one use. 5416 // Finally, if the destination type is not a vector, there is not 5417 // much point on forcing everything on the vector bank. 5418 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5419 !Op.hasOneUse()) 5420 return SDValue(); 5421 5422 // If the index is not constant, we will introduce an additional 5423 // multiply that will stick. 5424 // Give up in that case. 5425 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5426 if (!Index) 5427 return SDValue(); 5428 unsigned DstNumElt = DstVT.getVectorNumElements(); 5429 5430 // Compute the new index. 5431 const APInt &APIntIndex = Index->getAPIntValue(); 5432 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5433 NewIndex *= APIntIndex; 5434 // Check if the new constant index fits into i32. 5435 if (NewIndex.getBitWidth() > 32) 5436 return SDValue(); 5437 5438 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5439 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5440 SDLoc dl(Op); 5441 SDValue ExtractSrc = Op.getOperand(0); 5442 EVT VecVT = EVT::getVectorVT( 5443 *DAG.getContext(), DstVT.getScalarType(), 5444 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5445 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5446 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5447 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5448 } 5449 5450 /// ExpandBITCAST - If the target supports VFP, this function is called to 5451 /// expand a bit convert where either the source or destination type is i64 to 5452 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5453 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5454 /// vectors), since the legalizer won't know what to do with that. 5455 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5456 const ARMSubtarget *Subtarget) { 5457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5458 SDLoc dl(N); 5459 SDValue Op = N->getOperand(0); 5460 5461 // This function is only supposed to be called for i64 types, either as the 5462 // source or destination of the bit convert. 5463 EVT SrcVT = Op.getValueType(); 5464 EVT DstVT = N->getValueType(0); 5465 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5466 5467 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5468 // FullFP16: half values are passed in S-registers, and we don't 5469 // need any of the bitcast and moves: 5470 // 5471 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5472 // t5: i32 = bitcast t2 5473 // t18: f16 = ARMISD::VMOVhr t5 5474 if (Op.getOpcode() != ISD::CopyFromReg || 5475 Op.getValueType() != MVT::f32) 5476 return SDValue(); 5477 5478 auto Move = N->use_begin(); 5479 if (Move->getOpcode() != ARMISD::VMOVhr) 5480 return SDValue(); 5481 5482 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5483 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5484 DAG.ReplaceAllUsesWith(*Move, &Copy); 5485 return Copy; 5486 } 5487 5488 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5489 if (!HasFullFP16) 5490 return SDValue(); 5491 // SoftFP: read half-precision arguments: 5492 // 5493 // t2: i32,ch = ... 5494 // t7: i16 = truncate t2 <~~~~ Op 5495 // t8: f16 = bitcast t7 <~~~~ N 5496 // 5497 if (Op.getOperand(0).getValueType() == MVT::i32) 5498 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5499 MVT::f16, Op.getOperand(0)); 5500 5501 return SDValue(); 5502 } 5503 5504 // Half-precision return values 5505 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5506 if (!HasFullFP16) 5507 return SDValue(); 5508 // 5509 // t11: f16 = fadd t8, t10 5510 // t12: i16 = bitcast t11 <~~~ SDNode N 5511 // t13: i32 = zero_extend t12 5512 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5513 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5514 // 5515 // transform this into: 5516 // 5517 // t20: i32 = ARMISD::VMOVrh t11 5518 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5519 // 5520 auto ZeroExtend = N->use_begin(); 5521 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5522 ZeroExtend->getValueType(0) != MVT::i32) 5523 return SDValue(); 5524 5525 auto Copy = ZeroExtend->use_begin(); 5526 if (Copy->getOpcode() == ISD::CopyToReg && 5527 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5528 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5529 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5530 return Cvt; 5531 } 5532 return SDValue(); 5533 } 5534 5535 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5536 return SDValue(); 5537 5538 // Turn i64->f64 into VMOVDRR. 5539 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5540 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5541 // if we can combine the bitcast with its source. 5542 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5543 return Val; 5544 5545 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5546 DAG.getConstant(0, dl, MVT::i32)); 5547 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5548 DAG.getConstant(1, dl, MVT::i32)); 5549 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5550 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5551 } 5552 5553 // Turn f64->i64 into VMOVRRD. 5554 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5555 SDValue Cvt; 5556 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5557 SrcVT.getVectorNumElements() > 1) 5558 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5559 DAG.getVTList(MVT::i32, MVT::i32), 5560 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5561 else 5562 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5563 DAG.getVTList(MVT::i32, MVT::i32), Op); 5564 // Merge the pieces into a single i64 value. 5565 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5566 } 5567 5568 return SDValue(); 5569 } 5570 5571 /// getZeroVector - Returns a vector of specified type with all zero elements. 5572 /// Zero vectors are used to represent vector negation and in those cases 5573 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5574 /// not support i64 elements, so sometimes the zero vectors will need to be 5575 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5576 /// zero vector. 5577 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5578 assert(VT.isVector() && "Expected a vector type"); 5579 // The canonical modified immediate encoding of a zero vector is....0! 5580 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5581 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5582 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5583 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5584 } 5585 5586 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5587 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5588 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5589 SelectionDAG &DAG) const { 5590 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5591 EVT VT = Op.getValueType(); 5592 unsigned VTBits = VT.getSizeInBits(); 5593 SDLoc dl(Op); 5594 SDValue ShOpLo = Op.getOperand(0); 5595 SDValue ShOpHi = Op.getOperand(1); 5596 SDValue ShAmt = Op.getOperand(2); 5597 SDValue ARMcc; 5598 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5599 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5600 5601 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5602 5603 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5604 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5605 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5606 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5607 DAG.getConstant(VTBits, dl, MVT::i32)); 5608 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5609 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5610 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5611 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5612 ISD::SETGE, ARMcc, DAG, dl); 5613 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5614 ARMcc, CCR, CmpLo); 5615 5616 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5617 SDValue HiBigShift = Opc == ISD::SRA 5618 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5619 DAG.getConstant(VTBits - 1, dl, VT)) 5620 : DAG.getConstant(0, dl, VT); 5621 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5622 ISD::SETGE, ARMcc, DAG, dl); 5623 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5624 ARMcc, CCR, CmpHi); 5625 5626 SDValue Ops[2] = { Lo, Hi }; 5627 return DAG.getMergeValues(Ops, dl); 5628 } 5629 5630 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5631 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5632 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5633 SelectionDAG &DAG) const { 5634 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5635 EVT VT = Op.getValueType(); 5636 unsigned VTBits = VT.getSizeInBits(); 5637 SDLoc dl(Op); 5638 SDValue ShOpLo = Op.getOperand(0); 5639 SDValue ShOpHi = Op.getOperand(1); 5640 SDValue ShAmt = Op.getOperand(2); 5641 SDValue ARMcc; 5642 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5643 5644 assert(Op.getOpcode() == ISD::SHL_PARTS); 5645 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5646 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5647 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5648 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5649 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5650 5651 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5652 DAG.getConstant(VTBits, dl, MVT::i32)); 5653 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5654 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5655 ISD::SETGE, ARMcc, DAG, dl); 5656 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5657 ARMcc, CCR, CmpHi); 5658 5659 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5660 ISD::SETGE, ARMcc, DAG, dl); 5661 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5662 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5663 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5664 5665 SDValue Ops[2] = { Lo, Hi }; 5666 return DAG.getMergeValues(Ops, dl); 5667 } 5668 5669 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5670 SelectionDAG &DAG) const { 5671 // The rounding mode is in bits 23:22 of the FPSCR. 5672 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5673 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5674 // so that the shift + and get folded into a bitfield extract. 5675 SDLoc dl(Op); 5676 SDValue Ops[] = { DAG.getEntryNode(), 5677 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5678 5679 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5680 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5681 DAG.getConstant(1U << 22, dl, MVT::i32)); 5682 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5683 DAG.getConstant(22, dl, MVT::i32)); 5684 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5685 DAG.getConstant(3, dl, MVT::i32)); 5686 } 5687 5688 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5689 const ARMSubtarget *ST) { 5690 SDLoc dl(N); 5691 EVT VT = N->getValueType(0); 5692 if (VT.isVector()) { 5693 assert(ST->hasNEON()); 5694 5695 // Compute the least significant set bit: LSB = X & -X 5696 SDValue X = N->getOperand(0); 5697 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5698 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5699 5700 EVT ElemTy = VT.getVectorElementType(); 5701 5702 if (ElemTy == MVT::i8) { 5703 // Compute with: cttz(x) = ctpop(lsb - 1) 5704 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5705 DAG.getTargetConstant(1, dl, ElemTy)); 5706 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5707 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5708 } 5709 5710 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5711 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5712 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5713 unsigned NumBits = ElemTy.getSizeInBits(); 5714 SDValue WidthMinus1 = 5715 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5716 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5717 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5718 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5719 } 5720 5721 // Compute with: cttz(x) = ctpop(lsb - 1) 5722 5723 // Compute LSB - 1. 5724 SDValue Bits; 5725 if (ElemTy == MVT::i64) { 5726 // Load constant 0xffff'ffff'ffff'ffff to register. 5727 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5728 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5729 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5730 } else { 5731 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5732 DAG.getTargetConstant(1, dl, ElemTy)); 5733 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5734 } 5735 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5736 } 5737 5738 if (!ST->hasV6T2Ops()) 5739 return SDValue(); 5740 5741 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5742 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5743 } 5744 5745 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5746 const ARMSubtarget *ST) { 5747 EVT VT = N->getValueType(0); 5748 SDLoc DL(N); 5749 5750 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5751 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5752 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5753 "Unexpected type for custom ctpop lowering"); 5754 5755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5756 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5757 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 5758 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 5759 5760 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5761 unsigned EltSize = 8; 5762 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5763 while (EltSize != VT.getScalarSizeInBits()) { 5764 SmallVector<SDValue, 8> Ops; 5765 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 5766 TLI.getPointerTy(DAG.getDataLayout()))); 5767 Ops.push_back(Res); 5768 5769 EltSize *= 2; 5770 NumElts /= 2; 5771 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5772 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 5773 } 5774 5775 return Res; 5776 } 5777 5778 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 5779 /// operand of a vector shift operation, where all the elements of the 5780 /// build_vector must have the same constant integer value. 5781 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 5782 // Ignore bit_converts. 5783 while (Op.getOpcode() == ISD::BITCAST) 5784 Op = Op.getOperand(0); 5785 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 5786 APInt SplatBits, SplatUndef; 5787 unsigned SplatBitSize; 5788 bool HasAnyUndefs; 5789 if (!BVN || 5790 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 5791 ElementBits) || 5792 SplatBitSize > ElementBits) 5793 return false; 5794 Cnt = SplatBits.getSExtValue(); 5795 return true; 5796 } 5797 5798 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 5799 /// operand of a vector shift left operation. That value must be in the range: 5800 /// 0 <= Value < ElementBits for a left shift; or 5801 /// 0 <= Value <= ElementBits for a long left shift. 5802 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 5803 assert(VT.isVector() && "vector shift count is not a vector type"); 5804 int64_t ElementBits = VT.getScalarSizeInBits(); 5805 if (!getVShiftImm(Op, ElementBits, Cnt)) 5806 return false; 5807 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 5808 } 5809 5810 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 5811 /// operand of a vector shift right operation. For a shift opcode, the value 5812 /// is positive, but for an intrinsic the value count must be negative. The 5813 /// absolute value must be in the range: 5814 /// 1 <= |Value| <= ElementBits for a right shift; or 5815 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 5816 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 5817 int64_t &Cnt) { 5818 assert(VT.isVector() && "vector shift count is not a vector type"); 5819 int64_t ElementBits = VT.getScalarSizeInBits(); 5820 if (!getVShiftImm(Op, ElementBits, Cnt)) 5821 return false; 5822 if (!isIntrinsic) 5823 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 5824 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 5825 Cnt = -Cnt; 5826 return true; 5827 } 5828 return false; 5829 } 5830 5831 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5832 const ARMSubtarget *ST) { 5833 EVT VT = N->getValueType(0); 5834 SDLoc dl(N); 5835 int64_t Cnt; 5836 5837 if (!VT.isVector()) 5838 return SDValue(); 5839 5840 // We essentially have two forms here. Shift by an immediate and shift by a 5841 // vector register (there are also shift by a gpr, but that is just handled 5842 // with a tablegen pattern). We cannot easily match shift by an immediate in 5843 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 5844 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 5845 // signed or unsigned, and a negative shift indicates a shift right). 5846 if (N->getOpcode() == ISD::SHL) { 5847 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 5848 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 5849 DAG.getConstant(Cnt, dl, MVT::i32)); 5850 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 5851 N->getOperand(1)); 5852 } 5853 5854 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 5855 "unexpected vector shift opcode"); 5856 5857 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 5858 unsigned VShiftOpc = 5859 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 5860 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 5861 DAG.getConstant(Cnt, dl, MVT::i32)); 5862 } 5863 5864 // Other right shifts we don't have operations for (we use a shift left by a 5865 // negative number). 5866 EVT ShiftVT = N->getOperand(1).getValueType(); 5867 SDValue NegatedCount = DAG.getNode( 5868 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 5869 unsigned VShiftOpc = 5870 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 5871 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 5872 } 5873 5874 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5875 const ARMSubtarget *ST) { 5876 EVT VT = N->getValueType(0); 5877 SDLoc dl(N); 5878 5879 // We can get here for a node like i32 = ISD::SHL i32, i64 5880 if (VT != MVT::i64) 5881 return SDValue(); 5882 5883 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 5884 N->getOpcode() == ISD::SHL) && 5885 "Unknown shift to lower!"); 5886 5887 unsigned ShOpc = N->getOpcode(); 5888 if (ST->hasMVEIntegerOps()) { 5889 SDValue ShAmt = N->getOperand(1); 5890 unsigned ShPartsOpc = ARMISD::LSLL; 5891 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 5892 5893 // If the shift amount is greater than 32 then do the default optimisation 5894 if (Con && Con->getZExtValue() > 32) 5895 return SDValue(); 5896 5897 // Extract the lower 32 bits of the shift amount if it's an i64 5898 if (ShAmt->getValueType(0) == MVT::i64) 5899 ShAmt = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, ShAmt, 5900 DAG.getConstant(0, dl, MVT::i32)); 5901 5902 if (ShOpc == ISD::SRL) { 5903 if (!Con) 5904 // There is no t2LSRLr instruction so negate and perform an lsll if the 5905 // shift amount is in a register, emulating a right shift. 5906 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5907 DAG.getConstant(0, dl, MVT::i32), ShAmt); 5908 else 5909 // Else generate an lsrl on the immediate shift amount 5910 ShPartsOpc = ARMISD::LSRL; 5911 } else if (ShOpc == ISD::SRA) 5912 ShPartsOpc = ARMISD::ASRL; 5913 5914 // Lower 32 bits of the destination/source 5915 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5916 DAG.getConstant(0, dl, MVT::i32)); 5917 // Upper 32 bits of the destination/source 5918 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5919 DAG.getConstant(1, dl, MVT::i32)); 5920 5921 // Generate the shift operation as computed above 5922 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 5923 ShAmt); 5924 // The upper 32 bits come from the second return value of lsll 5925 Hi = SDValue(Lo.getNode(), 1); 5926 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5927 } 5928 5929 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5930 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 5931 return SDValue(); 5932 5933 // If we are in thumb mode, we don't have RRX. 5934 if (ST->isThumb1Only()) 5935 return SDValue(); 5936 5937 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5938 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5939 DAG.getConstant(0, dl, MVT::i32)); 5940 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5941 DAG.getConstant(1, dl, MVT::i32)); 5942 5943 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5944 // captures the result into a carry flag. 5945 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5946 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5947 5948 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5949 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5950 5951 // Merge the pieces into a single i64 value. 5952 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5953 } 5954 5955 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 5956 const ARMSubtarget *ST) { 5957 bool Invert = false; 5958 bool Swap = false; 5959 unsigned Opc = ARMCC::AL; 5960 5961 SDValue Op0 = Op.getOperand(0); 5962 SDValue Op1 = Op.getOperand(1); 5963 SDValue CC = Op.getOperand(2); 5964 EVT VT = Op.getValueType(); 5965 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5966 SDLoc dl(Op); 5967 5968 EVT CmpVT; 5969 if (ST->hasNEON()) 5970 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5971 else { 5972 assert(ST->hasMVEIntegerOps() && 5973 "No hardware support for integer vector comparison!"); 5974 5975 if (Op.getValueType().getVectorElementType() != MVT::i1) 5976 return SDValue(); 5977 5978 // Make sure we expand floating point setcc to scalar if we do not have 5979 // mve.fp, so that we can handle them from there. 5980 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 5981 return SDValue(); 5982 5983 CmpVT = VT; 5984 } 5985 5986 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5987 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5988 // Special-case integer 64-bit equality comparisons. They aren't legal, 5989 // but they can be lowered with a few vector instructions. 5990 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5991 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5992 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5993 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5994 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5995 DAG.getCondCode(ISD::SETEQ)); 5996 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5997 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5998 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5999 if (SetCCOpcode == ISD::SETNE) 6000 Merged = DAG.getNOT(dl, Merged, CmpVT); 6001 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 6002 return Merged; 6003 } 6004 6005 if (CmpVT.getVectorElementType() == MVT::i64) 6006 // 64-bit comparisons are not legal in general. 6007 return SDValue(); 6008 6009 if (Op1.getValueType().isFloatingPoint()) { 6010 switch (SetCCOpcode) { 6011 default: llvm_unreachable("Illegal FP comparison"); 6012 case ISD::SETUNE: 6013 case ISD::SETNE: 6014 if (ST->hasMVEFloatOps()) { 6015 Opc = ARMCC::NE; break; 6016 } else { 6017 Invert = true; LLVM_FALLTHROUGH; 6018 } 6019 case ISD::SETOEQ: 6020 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6021 case ISD::SETOLT: 6022 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6023 case ISD::SETOGT: 6024 case ISD::SETGT: Opc = ARMCC::GT; break; 6025 case ISD::SETOLE: 6026 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6027 case ISD::SETOGE: 6028 case ISD::SETGE: Opc = ARMCC::GE; break; 6029 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6030 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6031 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6032 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6033 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6034 case ISD::SETONE: { 6035 // Expand this to (OLT | OGT). 6036 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6037 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6038 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6039 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6040 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6041 if (Invert) 6042 Result = DAG.getNOT(dl, Result, VT); 6043 return Result; 6044 } 6045 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6046 case ISD::SETO: { 6047 // Expand this to (OLT | OGE). 6048 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6049 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6050 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6051 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6052 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6053 if (Invert) 6054 Result = DAG.getNOT(dl, Result, VT); 6055 return Result; 6056 } 6057 } 6058 } else { 6059 // Integer comparisons. 6060 switch (SetCCOpcode) { 6061 default: llvm_unreachable("Illegal integer comparison"); 6062 case ISD::SETNE: 6063 if (ST->hasMVEIntegerOps()) { 6064 Opc = ARMCC::NE; break; 6065 } else { 6066 Invert = true; LLVM_FALLTHROUGH; 6067 } 6068 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6069 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6070 case ISD::SETGT: Opc = ARMCC::GT; break; 6071 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6072 case ISD::SETGE: Opc = ARMCC::GE; break; 6073 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6074 case ISD::SETUGT: Opc = ARMCC::HI; break; 6075 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6076 case ISD::SETUGE: Opc = ARMCC::HS; break; 6077 } 6078 6079 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6080 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6081 SDValue AndOp; 6082 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6083 AndOp = Op0; 6084 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6085 AndOp = Op1; 6086 6087 // Ignore bitconvert. 6088 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6089 AndOp = AndOp.getOperand(0); 6090 6091 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6092 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6093 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6094 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6095 if (!Invert) 6096 Result = DAG.getNOT(dl, Result, VT); 6097 return Result; 6098 } 6099 } 6100 } 6101 6102 if (Swap) 6103 std::swap(Op0, Op1); 6104 6105 // If one of the operands is a constant vector zero, attempt to fold the 6106 // comparison to a specialized compare-against-zero form. 6107 SDValue SingleOp; 6108 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6109 SingleOp = Op0; 6110 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6111 if (Opc == ARMCC::GE) 6112 Opc = ARMCC::LE; 6113 else if (Opc == ARMCC::GT) 6114 Opc = ARMCC::LT; 6115 SingleOp = Op1; 6116 } 6117 6118 SDValue Result; 6119 if (SingleOp.getNode()) { 6120 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6121 DAG.getConstant(Opc, dl, MVT::i32)); 6122 } else { 6123 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6124 DAG.getConstant(Opc, dl, MVT::i32)); 6125 } 6126 6127 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6128 6129 if (Invert) 6130 Result = DAG.getNOT(dl, Result, VT); 6131 6132 return Result; 6133 } 6134 6135 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6136 SDValue LHS = Op.getOperand(0); 6137 SDValue RHS = Op.getOperand(1); 6138 SDValue Carry = Op.getOperand(2); 6139 SDValue Cond = Op.getOperand(3); 6140 SDLoc DL(Op); 6141 6142 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6143 6144 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6145 // have to invert the carry first. 6146 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6147 DAG.getConstant(1, DL, MVT::i32), Carry); 6148 // This converts the boolean value carry into the carry flag. 6149 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6150 6151 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6152 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6153 6154 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6155 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6156 SDValue ARMcc = DAG.getConstant( 6157 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6158 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6159 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6160 Cmp.getValue(1), SDValue()); 6161 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6162 CCR, Chain.getValue(1)); 6163 } 6164 6165 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6166 /// valid vector constant for a NEON or MVE instruction with a "modified 6167 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6168 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6169 unsigned SplatBitSize, SelectionDAG &DAG, 6170 const SDLoc &dl, EVT &VT, bool is128Bits, 6171 VMOVModImmType type) { 6172 unsigned OpCmode, Imm; 6173 6174 // SplatBitSize is set to the smallest size that splats the vector, so a 6175 // zero vector will always have SplatBitSize == 8. However, NEON modified 6176 // immediate instructions others than VMOV do not support the 8-bit encoding 6177 // of a zero vector, and the default encoding of zero is supposed to be the 6178 // 32-bit version. 6179 if (SplatBits == 0) 6180 SplatBitSize = 32; 6181 6182 switch (SplatBitSize) { 6183 case 8: 6184 if (type != VMOVModImm) 6185 return SDValue(); 6186 // Any 1-byte value is OK. Op=0, Cmode=1110. 6187 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6188 OpCmode = 0xe; 6189 Imm = SplatBits; 6190 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6191 break; 6192 6193 case 16: 6194 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6195 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6196 if ((SplatBits & ~0xff) == 0) { 6197 // Value = 0x00nn: Op=x, Cmode=100x. 6198 OpCmode = 0x8; 6199 Imm = SplatBits; 6200 break; 6201 } 6202 if ((SplatBits & ~0xff00) == 0) { 6203 // Value = 0xnn00: Op=x, Cmode=101x. 6204 OpCmode = 0xa; 6205 Imm = SplatBits >> 8; 6206 break; 6207 } 6208 return SDValue(); 6209 6210 case 32: 6211 // NEON's 32-bit VMOV supports splat values where: 6212 // * only one byte is nonzero, or 6213 // * the least significant byte is 0xff and the second byte is nonzero, or 6214 // * the least significant 2 bytes are 0xff and the third is nonzero. 6215 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6216 if ((SplatBits & ~0xff) == 0) { 6217 // Value = 0x000000nn: Op=x, Cmode=000x. 6218 OpCmode = 0; 6219 Imm = SplatBits; 6220 break; 6221 } 6222 if ((SplatBits & ~0xff00) == 0) { 6223 // Value = 0x0000nn00: Op=x, Cmode=001x. 6224 OpCmode = 0x2; 6225 Imm = SplatBits >> 8; 6226 break; 6227 } 6228 if ((SplatBits & ~0xff0000) == 0) { 6229 // Value = 0x00nn0000: Op=x, Cmode=010x. 6230 OpCmode = 0x4; 6231 Imm = SplatBits >> 16; 6232 break; 6233 } 6234 if ((SplatBits & ~0xff000000) == 0) { 6235 // Value = 0xnn000000: Op=x, Cmode=011x. 6236 OpCmode = 0x6; 6237 Imm = SplatBits >> 24; 6238 break; 6239 } 6240 6241 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6242 if (type == OtherModImm) return SDValue(); 6243 6244 if ((SplatBits & ~0xffff) == 0 && 6245 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6246 // Value = 0x0000nnff: Op=x, Cmode=1100. 6247 OpCmode = 0xc; 6248 Imm = SplatBits >> 8; 6249 break; 6250 } 6251 6252 // cmode == 0b1101 is not supported for MVE VMVN 6253 if (type == MVEVMVNModImm) 6254 return SDValue(); 6255 6256 if ((SplatBits & ~0xffffff) == 0 && 6257 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6258 // Value = 0x00nnffff: Op=x, Cmode=1101. 6259 OpCmode = 0xd; 6260 Imm = SplatBits >> 16; 6261 break; 6262 } 6263 6264 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6265 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6266 // VMOV.I32. A (very) minor optimization would be to replicate the value 6267 // and fall through here to test for a valid 64-bit splat. But, then the 6268 // caller would also need to check and handle the change in size. 6269 return SDValue(); 6270 6271 case 64: { 6272 if (type != VMOVModImm) 6273 return SDValue(); 6274 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6275 uint64_t BitMask = 0xff; 6276 uint64_t Val = 0; 6277 unsigned ImmMask = 1; 6278 Imm = 0; 6279 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6280 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6281 Val |= BitMask; 6282 Imm |= ImmMask; 6283 } else if ((SplatBits & BitMask) != 0) { 6284 return SDValue(); 6285 } 6286 BitMask <<= 8; 6287 ImmMask <<= 1; 6288 } 6289 6290 if (DAG.getDataLayout().isBigEndian()) 6291 // swap higher and lower 32 bit word 6292 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 6293 6294 // Op=1, Cmode=1110. 6295 OpCmode = 0x1e; 6296 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6297 break; 6298 } 6299 6300 default: 6301 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6302 } 6303 6304 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6305 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6306 } 6307 6308 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6309 const ARMSubtarget *ST) const { 6310 EVT VT = Op.getValueType(); 6311 bool IsDouble = (VT == MVT::f64); 6312 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6313 const APFloat &FPVal = CFP->getValueAPF(); 6314 6315 // Prevent floating-point constants from using literal loads 6316 // when execute-only is enabled. 6317 if (ST->genExecuteOnly()) { 6318 // If we can represent the constant as an immediate, don't lower it 6319 if (isFPImmLegal(FPVal, VT)) 6320 return Op; 6321 // Otherwise, construct as integer, and move to float register 6322 APInt INTVal = FPVal.bitcastToAPInt(); 6323 SDLoc DL(CFP); 6324 switch (VT.getSimpleVT().SimpleTy) { 6325 default: 6326 llvm_unreachable("Unknown floating point type!"); 6327 break; 6328 case MVT::f64: { 6329 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6330 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6331 if (!ST->isLittle()) 6332 std::swap(Lo, Hi); 6333 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6334 } 6335 case MVT::f32: 6336 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6337 DAG.getConstant(INTVal, DL, MVT::i32)); 6338 } 6339 } 6340 6341 if (!ST->hasVFP3Base()) 6342 return SDValue(); 6343 6344 // Use the default (constant pool) lowering for double constants when we have 6345 // an SP-only FPU 6346 if (IsDouble && !Subtarget->hasFP64()) 6347 return SDValue(); 6348 6349 // Try splatting with a VMOV.f32... 6350 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6351 6352 if (ImmVal != -1) { 6353 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6354 // We have code in place to select a valid ConstantFP already, no need to 6355 // do any mangling. 6356 return Op; 6357 } 6358 6359 // It's a float and we are trying to use NEON operations where 6360 // possible. Lower it to a splat followed by an extract. 6361 SDLoc DL(Op); 6362 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6363 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6364 NewVal); 6365 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6366 DAG.getConstant(0, DL, MVT::i32)); 6367 } 6368 6369 // The rest of our options are NEON only, make sure that's allowed before 6370 // proceeding.. 6371 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6372 return SDValue(); 6373 6374 EVT VMovVT; 6375 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6376 6377 // It wouldn't really be worth bothering for doubles except for one very 6378 // important value, which does happen to match: 0.0. So make sure we don't do 6379 // anything stupid. 6380 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6381 return SDValue(); 6382 6383 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6384 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6385 VMovVT, false, VMOVModImm); 6386 if (NewVal != SDValue()) { 6387 SDLoc DL(Op); 6388 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6389 NewVal); 6390 if (IsDouble) 6391 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6392 6393 // It's a float: cast and extract a vector element. 6394 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6395 VecConstant); 6396 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6397 DAG.getConstant(0, DL, MVT::i32)); 6398 } 6399 6400 // Finally, try a VMVN.i32 6401 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6402 false, VMVNModImm); 6403 if (NewVal != SDValue()) { 6404 SDLoc DL(Op); 6405 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6406 6407 if (IsDouble) 6408 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6409 6410 // It's a float: cast and extract a vector element. 6411 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6412 VecConstant); 6413 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6414 DAG.getConstant(0, DL, MVT::i32)); 6415 } 6416 6417 return SDValue(); 6418 } 6419 6420 // check if an VEXT instruction can handle the shuffle mask when the 6421 // vector sources of the shuffle are the same. 6422 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6423 unsigned NumElts = VT.getVectorNumElements(); 6424 6425 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6426 if (M[0] < 0) 6427 return false; 6428 6429 Imm = M[0]; 6430 6431 // If this is a VEXT shuffle, the immediate value is the index of the first 6432 // element. The other shuffle indices must be the successive elements after 6433 // the first one. 6434 unsigned ExpectedElt = Imm; 6435 for (unsigned i = 1; i < NumElts; ++i) { 6436 // Increment the expected index. If it wraps around, just follow it 6437 // back to index zero and keep going. 6438 ++ExpectedElt; 6439 if (ExpectedElt == NumElts) 6440 ExpectedElt = 0; 6441 6442 if (M[i] < 0) continue; // ignore UNDEF indices 6443 if (ExpectedElt != static_cast<unsigned>(M[i])) 6444 return false; 6445 } 6446 6447 return true; 6448 } 6449 6450 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6451 bool &ReverseVEXT, unsigned &Imm) { 6452 unsigned NumElts = VT.getVectorNumElements(); 6453 ReverseVEXT = false; 6454 6455 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6456 if (M[0] < 0) 6457 return false; 6458 6459 Imm = M[0]; 6460 6461 // If this is a VEXT shuffle, the immediate value is the index of the first 6462 // element. The other shuffle indices must be the successive elements after 6463 // the first one. 6464 unsigned ExpectedElt = Imm; 6465 for (unsigned i = 1; i < NumElts; ++i) { 6466 // Increment the expected index. If it wraps around, it may still be 6467 // a VEXT but the source vectors must be swapped. 6468 ExpectedElt += 1; 6469 if (ExpectedElt == NumElts * 2) { 6470 ExpectedElt = 0; 6471 ReverseVEXT = true; 6472 } 6473 6474 if (M[i] < 0) continue; // ignore UNDEF indices 6475 if (ExpectedElt != static_cast<unsigned>(M[i])) 6476 return false; 6477 } 6478 6479 // Adjust the index value if the source operands will be swapped. 6480 if (ReverseVEXT) 6481 Imm -= NumElts; 6482 6483 return true; 6484 } 6485 6486 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6487 /// instruction with the specified blocksize. (The order of the elements 6488 /// within each block of the vector is reversed.) 6489 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6490 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6491 "Only possible block sizes for VREV are: 16, 32, 64"); 6492 6493 unsigned EltSz = VT.getScalarSizeInBits(); 6494 if (EltSz == 64) 6495 return false; 6496 6497 unsigned NumElts = VT.getVectorNumElements(); 6498 unsigned BlockElts = M[0] + 1; 6499 // If the first shuffle index is UNDEF, be optimistic. 6500 if (M[0] < 0) 6501 BlockElts = BlockSize / EltSz; 6502 6503 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6504 return false; 6505 6506 for (unsigned i = 0; i < NumElts; ++i) { 6507 if (M[i] < 0) continue; // ignore UNDEF indices 6508 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6509 return false; 6510 } 6511 6512 return true; 6513 } 6514 6515 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6516 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6517 // range, then 0 is placed into the resulting vector. So pretty much any mask 6518 // of 8 elements can work here. 6519 return VT == MVT::v8i8 && M.size() == 8; 6520 } 6521 6522 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6523 unsigned Index) { 6524 if (Mask.size() == Elements * 2) 6525 return Index / Elements; 6526 return Mask[Index] == 0 ? 0 : 1; 6527 } 6528 6529 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6530 // checking that pairs of elements in the shuffle mask represent the same index 6531 // in each vector, incrementing the expected index by 2 at each step. 6532 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6533 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6534 // v2={e,f,g,h} 6535 // WhichResult gives the offset for each element in the mask based on which 6536 // of the two results it belongs to. 6537 // 6538 // The transpose can be represented either as: 6539 // result1 = shufflevector v1, v2, result1_shuffle_mask 6540 // result2 = shufflevector v1, v2, result2_shuffle_mask 6541 // where v1/v2 and the shuffle masks have the same number of elements 6542 // (here WhichResult (see below) indicates which result is being checked) 6543 // 6544 // or as: 6545 // results = shufflevector v1, v2, shuffle_mask 6546 // where both results are returned in one vector and the shuffle mask has twice 6547 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6548 // want to check the low half and high half of the shuffle mask as if it were 6549 // the other case 6550 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6551 unsigned EltSz = VT.getScalarSizeInBits(); 6552 if (EltSz == 64) 6553 return false; 6554 6555 unsigned NumElts = VT.getVectorNumElements(); 6556 if (M.size() != NumElts && M.size() != NumElts*2) 6557 return false; 6558 6559 // If the mask is twice as long as the input vector then we need to check the 6560 // upper and lower parts of the mask with a matching value for WhichResult 6561 // FIXME: A mask with only even values will be rejected in case the first 6562 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6563 // M[0] is used to determine WhichResult 6564 for (unsigned i = 0; i < M.size(); i += NumElts) { 6565 WhichResult = SelectPairHalf(NumElts, M, i); 6566 for (unsigned j = 0; j < NumElts; j += 2) { 6567 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6568 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6569 return false; 6570 } 6571 } 6572 6573 if (M.size() == NumElts*2) 6574 WhichResult = 0; 6575 6576 return true; 6577 } 6578 6579 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6580 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6581 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6582 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6583 unsigned EltSz = VT.getScalarSizeInBits(); 6584 if (EltSz == 64) 6585 return false; 6586 6587 unsigned NumElts = VT.getVectorNumElements(); 6588 if (M.size() != NumElts && M.size() != NumElts*2) 6589 return false; 6590 6591 for (unsigned i = 0; i < M.size(); i += NumElts) { 6592 WhichResult = SelectPairHalf(NumElts, M, i); 6593 for (unsigned j = 0; j < NumElts; j += 2) { 6594 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6595 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6596 return false; 6597 } 6598 } 6599 6600 if (M.size() == NumElts*2) 6601 WhichResult = 0; 6602 6603 return true; 6604 } 6605 6606 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6607 // that the mask elements are either all even and in steps of size 2 or all odd 6608 // and in steps of size 2. 6609 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6610 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6611 // v2={e,f,g,h} 6612 // Requires similar checks to that of isVTRNMask with 6613 // respect the how results are returned. 6614 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6615 unsigned EltSz = VT.getScalarSizeInBits(); 6616 if (EltSz == 64) 6617 return false; 6618 6619 unsigned NumElts = VT.getVectorNumElements(); 6620 if (M.size() != NumElts && M.size() != NumElts*2) 6621 return false; 6622 6623 for (unsigned i = 0; i < M.size(); i += NumElts) { 6624 WhichResult = SelectPairHalf(NumElts, M, i); 6625 for (unsigned j = 0; j < NumElts; ++j) { 6626 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6627 return false; 6628 } 6629 } 6630 6631 if (M.size() == NumElts*2) 6632 WhichResult = 0; 6633 6634 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6635 if (VT.is64BitVector() && EltSz == 32) 6636 return false; 6637 6638 return true; 6639 } 6640 6641 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6642 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6643 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6644 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6645 unsigned EltSz = VT.getScalarSizeInBits(); 6646 if (EltSz == 64) 6647 return false; 6648 6649 unsigned NumElts = VT.getVectorNumElements(); 6650 if (M.size() != NumElts && M.size() != NumElts*2) 6651 return false; 6652 6653 unsigned Half = NumElts / 2; 6654 for (unsigned i = 0; i < M.size(); i += NumElts) { 6655 WhichResult = SelectPairHalf(NumElts, M, i); 6656 for (unsigned j = 0; j < NumElts; j += Half) { 6657 unsigned Idx = WhichResult; 6658 for (unsigned k = 0; k < Half; ++k) { 6659 int MIdx = M[i + j + k]; 6660 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6661 return false; 6662 Idx += 2; 6663 } 6664 } 6665 } 6666 6667 if (M.size() == NumElts*2) 6668 WhichResult = 0; 6669 6670 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6671 if (VT.is64BitVector() && EltSz == 32) 6672 return false; 6673 6674 return true; 6675 } 6676 6677 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6678 // that pairs of elements of the shufflemask represent the same index in each 6679 // vector incrementing sequentially through the vectors. 6680 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6681 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6682 // v2={e,f,g,h} 6683 // Requires similar checks to that of isVTRNMask with respect the how results 6684 // are returned. 6685 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6686 unsigned EltSz = VT.getScalarSizeInBits(); 6687 if (EltSz == 64) 6688 return false; 6689 6690 unsigned NumElts = VT.getVectorNumElements(); 6691 if (M.size() != NumElts && M.size() != NumElts*2) 6692 return false; 6693 6694 for (unsigned i = 0; i < M.size(); i += NumElts) { 6695 WhichResult = SelectPairHalf(NumElts, M, i); 6696 unsigned Idx = WhichResult * NumElts / 2; 6697 for (unsigned j = 0; j < NumElts; j += 2) { 6698 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6699 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6700 return false; 6701 Idx += 1; 6702 } 6703 } 6704 6705 if (M.size() == NumElts*2) 6706 WhichResult = 0; 6707 6708 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6709 if (VT.is64BitVector() && EltSz == 32) 6710 return false; 6711 6712 return true; 6713 } 6714 6715 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6716 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6717 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6718 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6719 unsigned EltSz = VT.getScalarSizeInBits(); 6720 if (EltSz == 64) 6721 return false; 6722 6723 unsigned NumElts = VT.getVectorNumElements(); 6724 if (M.size() != NumElts && M.size() != NumElts*2) 6725 return false; 6726 6727 for (unsigned i = 0; i < M.size(); i += NumElts) { 6728 WhichResult = SelectPairHalf(NumElts, M, i); 6729 unsigned Idx = WhichResult * NumElts / 2; 6730 for (unsigned j = 0; j < NumElts; j += 2) { 6731 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6732 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6733 return false; 6734 Idx += 1; 6735 } 6736 } 6737 6738 if (M.size() == NumElts*2) 6739 WhichResult = 0; 6740 6741 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6742 if (VT.is64BitVector() && EltSz == 32) 6743 return false; 6744 6745 return true; 6746 } 6747 6748 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6749 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6750 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6751 unsigned &WhichResult, 6752 bool &isV_UNDEF) { 6753 isV_UNDEF = false; 6754 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6755 return ARMISD::VTRN; 6756 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6757 return ARMISD::VUZP; 6758 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6759 return ARMISD::VZIP; 6760 6761 isV_UNDEF = true; 6762 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6763 return ARMISD::VTRN; 6764 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6765 return ARMISD::VUZP; 6766 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6767 return ARMISD::VZIP; 6768 6769 return 0; 6770 } 6771 6772 /// \return true if this is a reverse operation on an vector. 6773 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6774 unsigned NumElts = VT.getVectorNumElements(); 6775 // Make sure the mask has the right size. 6776 if (NumElts != M.size()) 6777 return false; 6778 6779 // Look for <15, ..., 3, -1, 1, 0>. 6780 for (unsigned i = 0; i != NumElts; ++i) 6781 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6782 return false; 6783 6784 return true; 6785 } 6786 6787 // If N is an integer constant that can be moved into a register in one 6788 // instruction, return an SDValue of such a constant (will become a MOV 6789 // instruction). Otherwise return null. 6790 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6791 const ARMSubtarget *ST, const SDLoc &dl) { 6792 uint64_t Val; 6793 if (!isa<ConstantSDNode>(N)) 6794 return SDValue(); 6795 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6796 6797 if (ST->isThumb1Only()) { 6798 if (Val <= 255 || ~Val <= 255) 6799 return DAG.getConstant(Val, dl, MVT::i32); 6800 } else { 6801 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6802 return DAG.getConstant(Val, dl, MVT::i32); 6803 } 6804 return SDValue(); 6805 } 6806 6807 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 6808 const ARMSubtarget *ST) { 6809 SDLoc dl(Op); 6810 EVT VT = Op.getValueType(); 6811 6812 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 6813 6814 unsigned NumElts = VT.getVectorNumElements(); 6815 unsigned BoolMask; 6816 unsigned BitsPerBool; 6817 if (NumElts == 4) { 6818 BitsPerBool = 4; 6819 BoolMask = 0xf; 6820 } else if (NumElts == 8) { 6821 BitsPerBool = 2; 6822 BoolMask = 0x3; 6823 } else if (NumElts == 16) { 6824 BitsPerBool = 1; 6825 BoolMask = 0x1; 6826 } else 6827 return SDValue(); 6828 6829 // First create base with bits set where known 6830 unsigned Bits32 = 0; 6831 for (unsigned i = 0; i < NumElts; ++i) { 6832 SDValue V = Op.getOperand(i); 6833 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 6834 continue; 6835 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 6836 if (BitSet) 6837 Bits32 |= BoolMask << (i * BitsPerBool); 6838 } 6839 6840 // Add in unknown nodes 6841 // FIXME: Handle splats of the same value better. 6842 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 6843 DAG.getConstant(Bits32, dl, MVT::i32)); 6844 for (unsigned i = 0; i < NumElts; ++i) { 6845 SDValue V = Op.getOperand(i); 6846 if (isa<ConstantSDNode>(V) || V.isUndef()) 6847 continue; 6848 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 6849 DAG.getConstant(i, dl, MVT::i32)); 6850 } 6851 6852 return Base; 6853 } 6854 6855 // If this is a case we can't handle, return null and let the default 6856 // expansion code take care of it. 6857 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6858 const ARMSubtarget *ST) const { 6859 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6860 SDLoc dl(Op); 6861 EVT VT = Op.getValueType(); 6862 6863 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 6864 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 6865 6866 APInt SplatBits, SplatUndef; 6867 unsigned SplatBitSize; 6868 bool HasAnyUndefs; 6869 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6870 if (SplatUndef.isAllOnesValue()) 6871 return DAG.getUNDEF(VT); 6872 6873 if ((ST->hasNEON() && SplatBitSize <= 64) || 6874 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) { 6875 // Check if an immediate VMOV works. 6876 EVT VmovVT; 6877 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 6878 SplatUndef.getZExtValue(), SplatBitSize, 6879 DAG, dl, VmovVT, VT.is128BitVector(), 6880 VMOVModImm); 6881 6882 if (Val.getNode()) { 6883 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6884 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6885 } 6886 6887 // Try an immediate VMVN. 6888 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6889 Val = isVMOVModifiedImm( 6890 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, 6891 DAG, dl, VmovVT, VT.is128BitVector(), 6892 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 6893 if (Val.getNode()) { 6894 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6895 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6896 } 6897 6898 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6899 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6900 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6901 if (ImmVal != -1) { 6902 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6903 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6904 } 6905 } 6906 } 6907 } 6908 6909 // Scan through the operands to see if only one value is used. 6910 // 6911 // As an optimisation, even if more than one value is used it may be more 6912 // profitable to splat with one value then change some lanes. 6913 // 6914 // Heuristically we decide to do this if the vector has a "dominant" value, 6915 // defined as splatted to more than half of the lanes. 6916 unsigned NumElts = VT.getVectorNumElements(); 6917 bool isOnlyLowElement = true; 6918 bool usesOnlyOneValue = true; 6919 bool hasDominantValue = false; 6920 bool isConstant = true; 6921 6922 // Map of the number of times a particular SDValue appears in the 6923 // element list. 6924 DenseMap<SDValue, unsigned> ValueCounts; 6925 SDValue Value; 6926 for (unsigned i = 0; i < NumElts; ++i) { 6927 SDValue V = Op.getOperand(i); 6928 if (V.isUndef()) 6929 continue; 6930 if (i > 0) 6931 isOnlyLowElement = false; 6932 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6933 isConstant = false; 6934 6935 ValueCounts.insert(std::make_pair(V, 0)); 6936 unsigned &Count = ValueCounts[V]; 6937 6938 // Is this value dominant? (takes up more than half of the lanes) 6939 if (++Count > (NumElts / 2)) { 6940 hasDominantValue = true; 6941 Value = V; 6942 } 6943 } 6944 if (ValueCounts.size() != 1) 6945 usesOnlyOneValue = false; 6946 if (!Value.getNode() && !ValueCounts.empty()) 6947 Value = ValueCounts.begin()->first; 6948 6949 if (ValueCounts.empty()) 6950 return DAG.getUNDEF(VT); 6951 6952 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6953 // Keep going if we are hitting this case. 6954 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6955 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6956 6957 unsigned EltSize = VT.getScalarSizeInBits(); 6958 6959 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6960 // i32 and try again. 6961 if (hasDominantValue && EltSize <= 32) { 6962 if (!isConstant) { 6963 SDValue N; 6964 6965 // If we are VDUPing a value that comes directly from a vector, that will 6966 // cause an unnecessary move to and from a GPR, where instead we could 6967 // just use VDUPLANE. We can only do this if the lane being extracted 6968 // is at a constant index, as the VDUP from lane instructions only have 6969 // constant-index forms. 6970 ConstantSDNode *constIndex; 6971 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6972 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6973 // We need to create a new undef vector to use for the VDUPLANE if the 6974 // size of the vector from which we get the value is different than the 6975 // size of the vector that we need to create. We will insert the element 6976 // such that the register coalescer will remove unnecessary copies. 6977 if (VT != Value->getOperand(0).getValueType()) { 6978 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6979 VT.getVectorNumElements(); 6980 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6981 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6982 Value, DAG.getConstant(index, dl, MVT::i32)), 6983 DAG.getConstant(index, dl, MVT::i32)); 6984 } else 6985 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6986 Value->getOperand(0), Value->getOperand(1)); 6987 } else 6988 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6989 6990 if (!usesOnlyOneValue) { 6991 // The dominant value was splatted as 'N', but we now have to insert 6992 // all differing elements. 6993 for (unsigned I = 0; I < NumElts; ++I) { 6994 if (Op.getOperand(I) == Value) 6995 continue; 6996 SmallVector<SDValue, 3> Ops; 6997 Ops.push_back(N); 6998 Ops.push_back(Op.getOperand(I)); 6999 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 7000 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 7001 } 7002 } 7003 return N; 7004 } 7005 if (VT.getVectorElementType().isFloatingPoint()) { 7006 SmallVector<SDValue, 8> Ops; 7007 MVT FVT = VT.getVectorElementType().getSimpleVT(); 7008 assert(FVT == MVT::f32 || FVT == MVT::f16); 7009 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 7010 for (unsigned i = 0; i < NumElts; ++i) 7011 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 7012 Op.getOperand(i))); 7013 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 7014 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7015 Val = LowerBUILD_VECTOR(Val, DAG, ST); 7016 if (Val.getNode()) 7017 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7018 } 7019 if (usesOnlyOneValue) { 7020 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 7021 if (isConstant && Val.getNode()) 7022 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 7023 } 7024 } 7025 7026 // If all elements are constants and the case above didn't get hit, fall back 7027 // to the default expansion, which will generate a load from the constant 7028 // pool. 7029 if (isConstant) 7030 return SDValue(); 7031 7032 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 7033 if (NumElts >= 4) { 7034 SDValue shuffle = ReconstructShuffle(Op, DAG); 7035 if (shuffle != SDValue()) 7036 return shuffle; 7037 } 7038 7039 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7040 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7041 // into two 64-bit vectors; we might discover a better way to lower it. 7042 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7043 EVT ExtVT = VT.getVectorElementType(); 7044 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7045 SDValue Lower = 7046 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7047 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7048 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7049 SDValue Upper = DAG.getBuildVector( 7050 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7051 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7052 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7053 if (Lower && Upper) 7054 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7055 } 7056 7057 // Vectors with 32- or 64-bit elements can be built by directly assigning 7058 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7059 // will be legalized. 7060 if (EltSize >= 32) { 7061 // Do the expansion with floating-point types, since that is what the VFP 7062 // registers are defined to use, and since i64 is not legal. 7063 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7064 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7065 SmallVector<SDValue, 8> Ops; 7066 for (unsigned i = 0; i < NumElts; ++i) 7067 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7068 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7069 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7070 } 7071 7072 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7073 // know the default expansion would otherwise fall back on something even 7074 // worse. For a vector with one or two non-undef values, that's 7075 // scalar_to_vector for the elements followed by a shuffle (provided the 7076 // shuffle is valid for the target) and materialization element by element 7077 // on the stack followed by a load for everything else. 7078 if (!isConstant && !usesOnlyOneValue) { 7079 SDValue Vec = DAG.getUNDEF(VT); 7080 for (unsigned i = 0 ; i < NumElts; ++i) { 7081 SDValue V = Op.getOperand(i); 7082 if (V.isUndef()) 7083 continue; 7084 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7085 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7086 } 7087 return Vec; 7088 } 7089 7090 return SDValue(); 7091 } 7092 7093 // Gather data to see if the operation can be modelled as a 7094 // shuffle in combination with VEXTs. 7095 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7096 SelectionDAG &DAG) const { 7097 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7098 SDLoc dl(Op); 7099 EVT VT = Op.getValueType(); 7100 unsigned NumElts = VT.getVectorNumElements(); 7101 7102 struct ShuffleSourceInfo { 7103 SDValue Vec; 7104 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7105 unsigned MaxElt = 0; 7106 7107 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7108 // be compatible with the shuffle we intend to construct. As a result 7109 // ShuffleVec will be some sliding window into the original Vec. 7110 SDValue ShuffleVec; 7111 7112 // Code should guarantee that element i in Vec starts at element "WindowBase 7113 // + i * WindowScale in ShuffleVec". 7114 int WindowBase = 0; 7115 int WindowScale = 1; 7116 7117 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7118 7119 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7120 }; 7121 7122 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7123 // node. 7124 SmallVector<ShuffleSourceInfo, 2> Sources; 7125 for (unsigned i = 0; i < NumElts; ++i) { 7126 SDValue V = Op.getOperand(i); 7127 if (V.isUndef()) 7128 continue; 7129 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7130 // A shuffle can only come from building a vector from various 7131 // elements of other vectors. 7132 return SDValue(); 7133 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7134 // Furthermore, shuffles require a constant mask, whereas extractelts 7135 // accept variable indices. 7136 return SDValue(); 7137 } 7138 7139 // Add this element source to the list if it's not already there. 7140 SDValue SourceVec = V.getOperand(0); 7141 auto Source = llvm::find(Sources, SourceVec); 7142 if (Source == Sources.end()) 7143 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7144 7145 // Update the minimum and maximum lane number seen. 7146 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7147 Source->MinElt = std::min(Source->MinElt, EltNo); 7148 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7149 } 7150 7151 // Currently only do something sane when at most two source vectors 7152 // are involved. 7153 if (Sources.size() > 2) 7154 return SDValue(); 7155 7156 // Find out the smallest element size among result and two sources, and use 7157 // it as element size to build the shuffle_vector. 7158 EVT SmallestEltTy = VT.getVectorElementType(); 7159 for (auto &Source : Sources) { 7160 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7161 if (SrcEltTy.bitsLT(SmallestEltTy)) 7162 SmallestEltTy = SrcEltTy; 7163 } 7164 unsigned ResMultiplier = 7165 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7166 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7167 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7168 7169 // If the source vector is too wide or too narrow, we may nevertheless be able 7170 // to construct a compatible shuffle either by concatenating it with UNDEF or 7171 // extracting a suitable range of elements. 7172 for (auto &Src : Sources) { 7173 EVT SrcVT = Src.ShuffleVec.getValueType(); 7174 7175 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 7176 continue; 7177 7178 // This stage of the search produces a source with the same element type as 7179 // the original, but with a total width matching the BUILD_VECTOR output. 7180 EVT EltVT = SrcVT.getVectorElementType(); 7181 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 7182 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7183 7184 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 7185 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 7186 return SDValue(); 7187 // We can pad out the smaller vector for free, so if it's part of a 7188 // shuffle... 7189 Src.ShuffleVec = 7190 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7191 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7192 continue; 7193 } 7194 7195 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 7196 return SDValue(); 7197 7198 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7199 // Span too large for a VEXT to cope 7200 return SDValue(); 7201 } 7202 7203 if (Src.MinElt >= NumSrcElts) { 7204 // The extraction can just take the second half 7205 Src.ShuffleVec = 7206 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7207 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7208 Src.WindowBase = -NumSrcElts; 7209 } else if (Src.MaxElt < NumSrcElts) { 7210 // The extraction can just take the first half 7211 Src.ShuffleVec = 7212 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7213 DAG.getConstant(0, dl, MVT::i32)); 7214 } else { 7215 // An actual VEXT is needed 7216 SDValue VEXTSrc1 = 7217 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7218 DAG.getConstant(0, dl, MVT::i32)); 7219 SDValue VEXTSrc2 = 7220 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7221 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7222 7223 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7224 VEXTSrc2, 7225 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7226 Src.WindowBase = -Src.MinElt; 7227 } 7228 } 7229 7230 // Another possible incompatibility occurs from the vector element types. We 7231 // can fix this by bitcasting the source vectors to the same type we intend 7232 // for the shuffle. 7233 for (auto &Src : Sources) { 7234 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7235 if (SrcEltTy == SmallestEltTy) 7236 continue; 7237 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7238 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 7239 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7240 Src.WindowBase *= Src.WindowScale; 7241 } 7242 7243 // Final sanity check before we try to actually produce a shuffle. 7244 LLVM_DEBUG(for (auto Src 7245 : Sources) 7246 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7247 7248 // The stars all align, our next step is to produce the mask for the shuffle. 7249 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7250 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7251 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7252 SDValue Entry = Op.getOperand(i); 7253 if (Entry.isUndef()) 7254 continue; 7255 7256 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7257 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7258 7259 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7260 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7261 // segment. 7262 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7263 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 7264 VT.getScalarSizeInBits()); 7265 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7266 7267 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7268 // starting at the appropriate offset. 7269 int *LaneMask = &Mask[i * ResMultiplier]; 7270 7271 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7272 ExtractBase += NumElts * (Src - Sources.begin()); 7273 for (int j = 0; j < LanesDefined; ++j) 7274 LaneMask[j] = ExtractBase + j; 7275 } 7276 7277 // Final check before we try to produce nonsense... 7278 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 7279 return SDValue(); 7280 7281 // We can't handle more than two sources. This should have already 7282 // been checked before this point. 7283 assert(Sources.size() <= 2 && "Too many sources!"); 7284 7285 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7286 for (unsigned i = 0; i < Sources.size(); ++i) 7287 ShuffleOps[i] = Sources[i].ShuffleVec; 7288 7289 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7290 ShuffleOps[1], Mask); 7291 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 7292 } 7293 7294 enum ShuffleOpCodes { 7295 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7296 OP_VREV, 7297 OP_VDUP0, 7298 OP_VDUP1, 7299 OP_VDUP2, 7300 OP_VDUP3, 7301 OP_VEXT1, 7302 OP_VEXT2, 7303 OP_VEXT3, 7304 OP_VUZPL, // VUZP, left result 7305 OP_VUZPR, // VUZP, right result 7306 OP_VZIPL, // VZIP, left result 7307 OP_VZIPR, // VZIP, right result 7308 OP_VTRNL, // VTRN, left result 7309 OP_VTRNR // VTRN, right result 7310 }; 7311 7312 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7313 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7314 switch (OpNum) { 7315 case OP_COPY: 7316 case OP_VREV: 7317 case OP_VDUP0: 7318 case OP_VDUP1: 7319 case OP_VDUP2: 7320 case OP_VDUP3: 7321 return true; 7322 } 7323 return false; 7324 } 7325 7326 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7327 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7328 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7329 /// are assumed to be legal. 7330 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7331 if (VT.getVectorNumElements() == 4 && 7332 (VT.is128BitVector() || VT.is64BitVector())) { 7333 unsigned PFIndexes[4]; 7334 for (unsigned i = 0; i != 4; ++i) { 7335 if (M[i] < 0) 7336 PFIndexes[i] = 8; 7337 else 7338 PFIndexes[i] = M[i]; 7339 } 7340 7341 // Compute the index in the perfect shuffle table. 7342 unsigned PFTableIndex = 7343 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7344 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7345 unsigned Cost = (PFEntry >> 30); 7346 7347 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7348 return true; 7349 } 7350 7351 bool ReverseVEXT, isV_UNDEF; 7352 unsigned Imm, WhichResult; 7353 7354 unsigned EltSize = VT.getScalarSizeInBits(); 7355 if (EltSize >= 32 || 7356 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7357 isVREVMask(M, VT, 64) || 7358 isVREVMask(M, VT, 32) || 7359 isVREVMask(M, VT, 16)) 7360 return true; 7361 else if (Subtarget->hasNEON() && 7362 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7363 isVTBLMask(M, VT) || 7364 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7365 return true; 7366 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7367 isReverseMask(M, VT)) 7368 return true; 7369 else 7370 return false; 7371 } 7372 7373 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7374 /// the specified operations to build the shuffle. 7375 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7376 SDValue RHS, SelectionDAG &DAG, 7377 const SDLoc &dl) { 7378 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7379 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7380 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7381 7382 if (OpNum == OP_COPY) { 7383 if (LHSID == (1*9+2)*9+3) return LHS; 7384 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7385 return RHS; 7386 } 7387 7388 SDValue OpLHS, OpRHS; 7389 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7390 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7391 EVT VT = OpLHS.getValueType(); 7392 7393 switch (OpNum) { 7394 default: llvm_unreachable("Unknown shuffle opcode!"); 7395 case OP_VREV: 7396 // VREV divides the vector in half and swaps within the half. 7397 if (VT.getVectorElementType() == MVT::i32 || 7398 VT.getVectorElementType() == MVT::f32) 7399 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7400 // vrev <4 x i16> -> VREV32 7401 if (VT.getVectorElementType() == MVT::i16) 7402 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7403 // vrev <4 x i8> -> VREV16 7404 assert(VT.getVectorElementType() == MVT::i8); 7405 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 7406 case OP_VDUP0: 7407 case OP_VDUP1: 7408 case OP_VDUP2: 7409 case OP_VDUP3: 7410 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7411 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 7412 case OP_VEXT1: 7413 case OP_VEXT2: 7414 case OP_VEXT3: 7415 return DAG.getNode(ARMISD::VEXT, dl, VT, 7416 OpLHS, OpRHS, 7417 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 7418 case OP_VUZPL: 7419 case OP_VUZPR: 7420 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7421 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7422 case OP_VZIPL: 7423 case OP_VZIPR: 7424 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7425 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7426 case OP_VTRNL: 7427 case OP_VTRNR: 7428 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7429 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7430 } 7431 } 7432 7433 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7434 ArrayRef<int> ShuffleMask, 7435 SelectionDAG &DAG) { 7436 // Check to see if we can use the VTBL instruction. 7437 SDValue V1 = Op.getOperand(0); 7438 SDValue V2 = Op.getOperand(1); 7439 SDLoc DL(Op); 7440 7441 SmallVector<SDValue, 8> VTBLMask; 7442 for (ArrayRef<int>::iterator 7443 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7444 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7445 7446 if (V2.getNode()->isUndef()) 7447 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7448 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7449 7450 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7451 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7452 } 7453 7454 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7455 SelectionDAG &DAG) { 7456 SDLoc DL(Op); 7457 SDValue OpLHS = Op.getOperand(0); 7458 EVT VT = OpLHS.getValueType(); 7459 7460 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7461 "Expect an v8i16/v16i8 type"); 7462 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7463 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7464 // extract the first 8 bytes into the top double word and the last 8 bytes 7465 // into the bottom double word. The v8i16 case is similar. 7466 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7467 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7468 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7469 } 7470 7471 static EVT getVectorTyFromPredicateVector(EVT VT) { 7472 switch (VT.getSimpleVT().SimpleTy) { 7473 case MVT::v4i1: 7474 return MVT::v4i32; 7475 case MVT::v8i1: 7476 return MVT::v8i16; 7477 case MVT::v16i1: 7478 return MVT::v16i8; 7479 default: 7480 llvm_unreachable("Unexpected vector predicate type"); 7481 } 7482 } 7483 7484 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 7485 SelectionDAG &DAG) { 7486 // Converting from boolean predicates to integers involves creating a vector 7487 // of all ones or all zeroes and selecting the lanes based upon the real 7488 // predicate. 7489 SDValue AllOnes = 7490 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 7491 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 7492 7493 SDValue AllZeroes = 7494 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 7495 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 7496 7497 // Get full vector type from predicate type 7498 EVT NewVT = getVectorTyFromPredicateVector(VT); 7499 7500 SDValue RecastV1; 7501 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 7502 // this to a v16i1. This cannot be done with an ordinary bitcast because the 7503 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 7504 // since we know in hardware the sizes are really the same. 7505 if (VT != MVT::v16i1) 7506 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 7507 else 7508 RecastV1 = Pred; 7509 7510 // Select either all ones or zeroes depending upon the real predicate bits. 7511 SDValue PredAsVector = 7512 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 7513 7514 // Recast our new predicate-as-integer v16i8 vector into something 7515 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 7516 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 7517 } 7518 7519 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 7520 const ARMSubtarget *ST) { 7521 EVT VT = Op.getValueType(); 7522 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7523 ArrayRef<int> ShuffleMask = SVN->getMask(); 7524 7525 assert(ST->hasMVEIntegerOps() && 7526 "No support for vector shuffle of boolean predicates"); 7527 7528 SDValue V1 = Op.getOperand(0); 7529 SDLoc dl(Op); 7530 if (isReverseMask(ShuffleMask, VT)) { 7531 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 7532 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 7533 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 7534 DAG.getConstant(16, dl, MVT::i32)); 7535 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 7536 } 7537 7538 // Until we can come up with optimised cases for every single vector 7539 // shuffle in existence we have chosen the least painful strategy. This is 7540 // to essentially promote the boolean predicate to a 8-bit integer, where 7541 // each predicate represents a byte. Then we fall back on a normal integer 7542 // vector shuffle and convert the result back into a predicate vector. In 7543 // many cases the generated code might be even better than scalar code 7544 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 7545 // fields in a register into 8 other arbitrary 2-bit fields! 7546 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 7547 EVT NewVT = PredAsVector.getValueType(); 7548 7549 // Do the shuffle! 7550 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 7551 DAG.getUNDEF(NewVT), ShuffleMask); 7552 7553 // Now return the result of comparing the shuffled vector with zero, 7554 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7555 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 7556 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7557 } 7558 7559 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 7560 const ARMSubtarget *ST) { 7561 SDValue V1 = Op.getOperand(0); 7562 SDValue V2 = Op.getOperand(1); 7563 SDLoc dl(Op); 7564 EVT VT = Op.getValueType(); 7565 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7566 unsigned EltSize = VT.getScalarSizeInBits(); 7567 7568 if (ST->hasMVEIntegerOps() && EltSize == 1) 7569 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 7570 7571 // Convert shuffles that are directly supported on NEON to target-specific 7572 // DAG nodes, instead of keeping them as shuffles and matching them again 7573 // during code selection. This is more efficient and avoids the possibility 7574 // of inconsistencies between legalization and selection. 7575 // FIXME: floating-point vectors should be canonicalized to integer vectors 7576 // of the same time so that they get CSEd properly. 7577 ArrayRef<int> ShuffleMask = SVN->getMask(); 7578 7579 if (EltSize <= 32) { 7580 if (SVN->isSplat()) { 7581 int Lane = SVN->getSplatIndex(); 7582 // If this is undef splat, generate it via "just" vdup, if possible. 7583 if (Lane == -1) Lane = 0; 7584 7585 // Test if V1 is a SCALAR_TO_VECTOR. 7586 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7587 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7588 } 7589 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7590 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7591 // reaches it). 7592 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7593 !isa<ConstantSDNode>(V1.getOperand(0))) { 7594 bool IsScalarToVector = true; 7595 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7596 if (!V1.getOperand(i).isUndef()) { 7597 IsScalarToVector = false; 7598 break; 7599 } 7600 if (IsScalarToVector) 7601 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7602 } 7603 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7604 DAG.getConstant(Lane, dl, MVT::i32)); 7605 } 7606 7607 bool ReverseVEXT = false; 7608 unsigned Imm = 0; 7609 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7610 if (ReverseVEXT) 7611 std::swap(V1, V2); 7612 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7613 DAG.getConstant(Imm, dl, MVT::i32)); 7614 } 7615 7616 if (isVREVMask(ShuffleMask, VT, 64)) 7617 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7618 if (isVREVMask(ShuffleMask, VT, 32)) 7619 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7620 if (isVREVMask(ShuffleMask, VT, 16)) 7621 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7622 7623 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7624 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7625 DAG.getConstant(Imm, dl, MVT::i32)); 7626 } 7627 7628 // Check for Neon shuffles that modify both input vectors in place. 7629 // If both results are used, i.e., if there are two shuffles with the same 7630 // source operands and with masks corresponding to both results of one of 7631 // these operations, DAG memoization will ensure that a single node is 7632 // used for both shuffles. 7633 unsigned WhichResult = 0; 7634 bool isV_UNDEF = false; 7635 if (ST->hasNEON()) { 7636 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7637 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7638 if (isV_UNDEF) 7639 V2 = V1; 7640 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7641 .getValue(WhichResult); 7642 } 7643 } 7644 7645 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7646 // shuffles that produce a result larger than their operands with: 7647 // shuffle(concat(v1, undef), concat(v2, undef)) 7648 // -> 7649 // shuffle(concat(v1, v2), undef) 7650 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7651 // 7652 // This is useful in the general case, but there are special cases where 7653 // native shuffles produce larger results: the two-result ops. 7654 // 7655 // Look through the concat when lowering them: 7656 // shuffle(concat(v1, v2), undef) 7657 // -> 7658 // concat(VZIP(v1, v2):0, :1) 7659 // 7660 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7661 SDValue SubV1 = V1->getOperand(0); 7662 SDValue SubV2 = V1->getOperand(1); 7663 EVT SubVT = SubV1.getValueType(); 7664 7665 // We expect these to have been canonicalized to -1. 7666 assert(llvm::all_of(ShuffleMask, [&](int i) { 7667 return i < (int)VT.getVectorNumElements(); 7668 }) && "Unexpected shuffle index into UNDEF operand!"); 7669 7670 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7671 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7672 if (isV_UNDEF) 7673 SubV2 = SubV1; 7674 assert((WhichResult == 0) && 7675 "In-place shuffle of concat can only have one result!"); 7676 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7677 SubV1, SubV2); 7678 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7679 Res.getValue(1)); 7680 } 7681 } 7682 } 7683 7684 // If the shuffle is not directly supported and it has 4 elements, use 7685 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7686 unsigned NumElts = VT.getVectorNumElements(); 7687 if (NumElts == 4) { 7688 unsigned PFIndexes[4]; 7689 for (unsigned i = 0; i != 4; ++i) { 7690 if (ShuffleMask[i] < 0) 7691 PFIndexes[i] = 8; 7692 else 7693 PFIndexes[i] = ShuffleMask[i]; 7694 } 7695 7696 // Compute the index in the perfect shuffle table. 7697 unsigned PFTableIndex = 7698 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7699 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7700 unsigned Cost = (PFEntry >> 30); 7701 7702 if (Cost <= 4) { 7703 if (ST->hasNEON()) 7704 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7705 else if (isLegalMVEShuffleOp(PFEntry)) { 7706 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7707 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7708 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 7709 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 7710 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 7711 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7712 } 7713 } 7714 } 7715 7716 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7717 if (EltSize >= 32) { 7718 // Do the expansion with floating-point types, since that is what the VFP 7719 // registers are defined to use, and since i64 is not legal. 7720 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7721 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7722 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7723 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7724 SmallVector<SDValue, 8> Ops; 7725 for (unsigned i = 0; i < NumElts; ++i) { 7726 if (ShuffleMask[i] < 0) 7727 Ops.push_back(DAG.getUNDEF(EltVT)); 7728 else 7729 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7730 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7731 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7732 dl, MVT::i32))); 7733 } 7734 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7735 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7736 } 7737 7738 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7739 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7740 7741 if (ST->hasNEON() && VT == MVT::v8i8) 7742 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7743 return NewOp; 7744 7745 return SDValue(); 7746 } 7747 7748 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 7749 const ARMSubtarget *ST) { 7750 EVT VecVT = Op.getOperand(0).getValueType(); 7751 SDLoc dl(Op); 7752 7753 assert(ST->hasMVEIntegerOps() && 7754 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 7755 7756 SDValue Conv = 7757 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 7758 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 7759 unsigned LaneWidth = 7760 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 7761 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 7762 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 7763 Op.getOperand(1), DAG.getValueType(MVT::i1)); 7764 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 7765 DAG.getConstant(~Mask, dl, MVT::i32)); 7766 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 7767 } 7768 7769 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 7770 SelectionDAG &DAG) const { 7771 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7772 SDValue Lane = Op.getOperand(2); 7773 if (!isa<ConstantSDNode>(Lane)) 7774 return SDValue(); 7775 7776 SDValue Elt = Op.getOperand(1); 7777 EVT EltVT = Elt.getValueType(); 7778 7779 if (Subtarget->hasMVEIntegerOps() && 7780 Op.getValueType().getScalarSizeInBits() == 1) 7781 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 7782 7783 if (getTypeAction(*DAG.getContext(), EltVT) == 7784 TargetLowering::TypePromoteFloat) { 7785 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 7786 // but the type system will try to do that if we don't intervene. 7787 // Reinterpret any such vector-element insertion as one with the 7788 // corresponding integer types. 7789 7790 SDLoc dl(Op); 7791 7792 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 7793 assert(getTypeAction(*DAG.getContext(), IEltVT) != 7794 TargetLowering::TypePromoteFloat); 7795 7796 SDValue VecIn = Op.getOperand(0); 7797 EVT VecVT = VecIn.getValueType(); 7798 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 7799 VecVT.getVectorNumElements()); 7800 7801 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 7802 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 7803 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 7804 IVecIn, IElt, Lane); 7805 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 7806 } 7807 7808 return Op; 7809 } 7810 7811 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 7812 const ARMSubtarget *ST) { 7813 EVT VecVT = Op.getOperand(0).getValueType(); 7814 SDLoc dl(Op); 7815 7816 assert(ST->hasMVEIntegerOps() && 7817 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 7818 7819 SDValue Conv = 7820 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 7821 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7822 unsigned LaneWidth = 7823 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 7824 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 7825 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 7826 return Shift; 7827 } 7828 7829 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 7830 const ARMSubtarget *ST) { 7831 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7832 SDValue Lane = Op.getOperand(1); 7833 if (!isa<ConstantSDNode>(Lane)) 7834 return SDValue(); 7835 7836 SDValue Vec = Op.getOperand(0); 7837 EVT VT = Vec.getValueType(); 7838 7839 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7840 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 7841 7842 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7843 SDLoc dl(Op); 7844 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7845 } 7846 7847 return Op; 7848 } 7849 7850 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 7851 const ARMSubtarget *ST) { 7852 SDValue V1 = Op.getOperand(0); 7853 SDValue V2 = Op.getOperand(1); 7854 SDLoc dl(Op); 7855 EVT VT = Op.getValueType(); 7856 EVT Op1VT = V1.getValueType(); 7857 EVT Op2VT = V2.getValueType(); 7858 unsigned NumElts = VT.getVectorNumElements(); 7859 7860 assert(Op1VT == Op2VT && "Operand types don't match!"); 7861 assert(VT.getScalarSizeInBits() == 1 && 7862 "Unexpected custom CONCAT_VECTORS lowering"); 7863 assert(ST->hasMVEIntegerOps() && 7864 "CONCAT_VECTORS lowering only supported for MVE"); 7865 7866 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 7867 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 7868 7869 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 7870 // promoted to v8i16, etc. 7871 7872 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 7873 7874 // Extract the vector elements from Op1 and Op2 one by one and truncate them 7875 // to be the right size for the destination. For example, if Op1 is v4i1 then 7876 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 7877 // which when promoted is v8i16. That means each i32 element from Op1 needs 7878 // truncating to i16 and inserting in the result. 7879 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 7880 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 7881 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 7882 EVT NewVT = NewV.getValueType(); 7883 EVT ConcatVT = ConVec.getValueType(); 7884 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 7885 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 7886 DAG.getIntPtrConstant(i, dl)); 7887 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 7888 DAG.getConstant(j, dl, MVT::i32)); 7889 } 7890 return ConVec; 7891 }; 7892 unsigned j = 0; 7893 ConVec = ExractInto(NewV1, ConVec, j); 7894 ConVec = ExractInto(NewV2, ConVec, j); 7895 7896 // Now return the result of comparing the subvector with zero, 7897 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7898 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 7899 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7900 } 7901 7902 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 7903 const ARMSubtarget *ST) { 7904 EVT VT = Op->getValueType(0); 7905 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7906 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 7907 7908 // The only time a CONCAT_VECTORS operation can have legal types is when 7909 // two 64-bit vectors are concatenated to a 128-bit vector. 7910 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7911 "unexpected CONCAT_VECTORS"); 7912 SDLoc dl(Op); 7913 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7914 SDValue Op0 = Op.getOperand(0); 7915 SDValue Op1 = Op.getOperand(1); 7916 if (!Op0.isUndef()) 7917 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7918 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7919 DAG.getIntPtrConstant(0, dl)); 7920 if (!Op1.isUndef()) 7921 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7922 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7923 DAG.getIntPtrConstant(1, dl)); 7924 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7925 } 7926 7927 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 7928 const ARMSubtarget *ST) { 7929 SDValue V1 = Op.getOperand(0); 7930 SDValue V2 = Op.getOperand(1); 7931 SDLoc dl(Op); 7932 EVT VT = Op.getValueType(); 7933 EVT Op1VT = V1.getValueType(); 7934 unsigned NumElts = VT.getVectorNumElements(); 7935 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 7936 7937 assert(VT.getScalarSizeInBits() == 1 && 7938 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 7939 assert(ST->hasMVEIntegerOps() && 7940 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 7941 7942 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 7943 7944 // We now have Op1 promoted to a vector of integers, where v8i1 gets 7945 // promoted to v8i16, etc. 7946 7947 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 7948 7949 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 7950 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 7951 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 7952 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 7953 DAG.getIntPtrConstant(i, dl)); 7954 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 7955 DAG.getConstant(j, dl, MVT::i32)); 7956 } 7957 7958 // Now return the result of comparing the subvector with zero, 7959 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7960 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 7961 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7962 } 7963 7964 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7965 /// element has been zero/sign-extended, depending on the isSigned parameter, 7966 /// from an integer type half its size. 7967 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7968 bool isSigned) { 7969 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7970 EVT VT = N->getValueType(0); 7971 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7972 SDNode *BVN = N->getOperand(0).getNode(); 7973 if (BVN->getValueType(0) != MVT::v4i32 || 7974 BVN->getOpcode() != ISD::BUILD_VECTOR) 7975 return false; 7976 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7977 unsigned HiElt = 1 - LoElt; 7978 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7979 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7980 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7981 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7982 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7983 return false; 7984 if (isSigned) { 7985 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7986 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7987 return true; 7988 } else { 7989 if (Hi0->isNullValue() && Hi1->isNullValue()) 7990 return true; 7991 } 7992 return false; 7993 } 7994 7995 if (N->getOpcode() != ISD::BUILD_VECTOR) 7996 return false; 7997 7998 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7999 SDNode *Elt = N->getOperand(i).getNode(); 8000 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 8001 unsigned EltSize = VT.getScalarSizeInBits(); 8002 unsigned HalfSize = EltSize / 2; 8003 if (isSigned) { 8004 if (!isIntN(HalfSize, C->getSExtValue())) 8005 return false; 8006 } else { 8007 if (!isUIntN(HalfSize, C->getZExtValue())) 8008 return false; 8009 } 8010 continue; 8011 } 8012 return false; 8013 } 8014 8015 return true; 8016 } 8017 8018 /// isSignExtended - Check if a node is a vector value that is sign-extended 8019 /// or a constant BUILD_VECTOR with sign-extended elements. 8020 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 8021 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 8022 return true; 8023 if (isExtendedBUILD_VECTOR(N, DAG, true)) 8024 return true; 8025 return false; 8026 } 8027 8028 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8029 /// or a constant BUILD_VECTOR with zero-extended elements. 8030 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8031 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8032 return true; 8033 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8034 return true; 8035 return false; 8036 } 8037 8038 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8039 if (OrigVT.getSizeInBits() >= 64) 8040 return OrigVT; 8041 8042 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8043 8044 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8045 switch (OrigSimpleTy) { 8046 default: llvm_unreachable("Unexpected Vector Type"); 8047 case MVT::v2i8: 8048 case MVT::v2i16: 8049 return MVT::v2i32; 8050 case MVT::v4i8: 8051 return MVT::v4i16; 8052 } 8053 } 8054 8055 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8056 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8057 /// We insert the required extension here to get the vector to fill a D register. 8058 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8059 const EVT &OrigTy, 8060 const EVT &ExtTy, 8061 unsigned ExtOpcode) { 8062 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8063 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8064 // 64-bits we need to insert a new extension so that it will be 64-bits. 8065 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8066 if (OrigTy.getSizeInBits() >= 64) 8067 return N; 8068 8069 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8070 EVT NewVT = getExtensionTo64Bits(OrigTy); 8071 8072 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8073 } 8074 8075 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8076 /// does not do any sign/zero extension. If the original vector is less 8077 /// than 64 bits, an appropriate extension will be added after the load to 8078 /// reach a total size of 64 bits. We have to add the extension separately 8079 /// because ARM does not have a sign/zero extending load for vectors. 8080 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8081 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8082 8083 // The load already has the right type. 8084 if (ExtendedTy == LD->getMemoryVT()) 8085 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8086 LD->getBasePtr(), LD->getPointerInfo(), 8087 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8088 8089 // We need to create a zextload/sextload. We cannot just create a load 8090 // followed by a zext/zext node because LowerMUL is also run during normal 8091 // operation legalization where we can't create illegal types. 8092 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8093 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8094 LD->getMemoryVT(), LD->getAlignment(), 8095 LD->getMemOperand()->getFlags()); 8096 } 8097 8098 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8099 /// extending load, or BUILD_VECTOR with extended elements, return the 8100 /// unextended value. The unextended vector should be 64 bits so that it can 8101 /// be used as an operand to a VMULL instruction. If the original vector size 8102 /// before extension is less than 64 bits we add a an extension to resize 8103 /// the vector to 64 bits. 8104 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8105 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8106 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8107 N->getOperand(0)->getValueType(0), 8108 N->getValueType(0), 8109 N->getOpcode()); 8110 8111 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8112 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8113 "Expected extending load"); 8114 8115 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8116 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8117 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8118 SDValue extLoad = 8119 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8120 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8121 8122 return newLoad; 8123 } 8124 8125 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8126 // have been legalized as a BITCAST from v4i32. 8127 if (N->getOpcode() == ISD::BITCAST) { 8128 SDNode *BVN = N->getOperand(0).getNode(); 8129 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8130 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8131 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8132 return DAG.getBuildVector( 8133 MVT::v2i32, SDLoc(N), 8134 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8135 } 8136 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8137 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8138 EVT VT = N->getValueType(0); 8139 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8140 unsigned NumElts = VT.getVectorNumElements(); 8141 MVT TruncVT = MVT::getIntegerVT(EltSize); 8142 SmallVector<SDValue, 8> Ops; 8143 SDLoc dl(N); 8144 for (unsigned i = 0; i != NumElts; ++i) { 8145 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8146 const APInt &CInt = C->getAPIntValue(); 8147 // Element types smaller than 32 bits are not legal, so use i32 elements. 8148 // The values are implicitly truncated so sext vs. zext doesn't matter. 8149 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8150 } 8151 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8152 } 8153 8154 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8155 unsigned Opcode = N->getOpcode(); 8156 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8157 SDNode *N0 = N->getOperand(0).getNode(); 8158 SDNode *N1 = N->getOperand(1).getNode(); 8159 return N0->hasOneUse() && N1->hasOneUse() && 8160 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8161 } 8162 return false; 8163 } 8164 8165 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8166 unsigned Opcode = N->getOpcode(); 8167 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8168 SDNode *N0 = N->getOperand(0).getNode(); 8169 SDNode *N1 = N->getOperand(1).getNode(); 8170 return N0->hasOneUse() && N1->hasOneUse() && 8171 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8172 } 8173 return false; 8174 } 8175 8176 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8177 // Multiplications are only custom-lowered for 128-bit vectors so that 8178 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8179 EVT VT = Op.getValueType(); 8180 assert(VT.is128BitVector() && VT.isInteger() && 8181 "unexpected type for custom-lowering ISD::MUL"); 8182 SDNode *N0 = Op.getOperand(0).getNode(); 8183 SDNode *N1 = Op.getOperand(1).getNode(); 8184 unsigned NewOpc = 0; 8185 bool isMLA = false; 8186 bool isN0SExt = isSignExtended(N0, DAG); 8187 bool isN1SExt = isSignExtended(N1, DAG); 8188 if (isN0SExt && isN1SExt) 8189 NewOpc = ARMISD::VMULLs; 8190 else { 8191 bool isN0ZExt = isZeroExtended(N0, DAG); 8192 bool isN1ZExt = isZeroExtended(N1, DAG); 8193 if (isN0ZExt && isN1ZExt) 8194 NewOpc = ARMISD::VMULLu; 8195 else if (isN1SExt || isN1ZExt) { 8196 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8197 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8198 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8199 NewOpc = ARMISD::VMULLs; 8200 isMLA = true; 8201 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8202 NewOpc = ARMISD::VMULLu; 8203 isMLA = true; 8204 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8205 std::swap(N0, N1); 8206 NewOpc = ARMISD::VMULLu; 8207 isMLA = true; 8208 } 8209 } 8210 8211 if (!NewOpc) { 8212 if (VT == MVT::v2i64) 8213 // Fall through to expand this. It is not legal. 8214 return SDValue(); 8215 else 8216 // Other vector multiplications are legal. 8217 return Op; 8218 } 8219 } 8220 8221 // Legalize to a VMULL instruction. 8222 SDLoc DL(Op); 8223 SDValue Op0; 8224 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8225 if (!isMLA) { 8226 Op0 = SkipExtensionForVMULL(N0, DAG); 8227 assert(Op0.getValueType().is64BitVector() && 8228 Op1.getValueType().is64BitVector() && 8229 "unexpected types for extended operands to VMULL"); 8230 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8231 } 8232 8233 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8234 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8235 // vmull q0, d4, d6 8236 // vmlal q0, d5, d6 8237 // is faster than 8238 // vaddl q0, d4, d5 8239 // vmovl q1, d6 8240 // vmul q0, q0, q1 8241 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8242 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8243 EVT Op1VT = Op1.getValueType(); 8244 return DAG.getNode(N0->getOpcode(), DL, VT, 8245 DAG.getNode(NewOpc, DL, VT, 8246 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8247 DAG.getNode(NewOpc, DL, VT, 8248 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8249 } 8250 8251 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8252 SelectionDAG &DAG) { 8253 // TODO: Should this propagate fast-math-flags? 8254 8255 // Convert to float 8256 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8257 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8258 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8259 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8260 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8261 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8262 // Get reciprocal estimate. 8263 // float4 recip = vrecpeq_f32(yf); 8264 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8265 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8266 Y); 8267 // Because char has a smaller range than uchar, we can actually get away 8268 // without any newton steps. This requires that we use a weird bias 8269 // of 0xb000, however (again, this has been exhaustively tested). 8270 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8271 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8272 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8273 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8274 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8275 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8276 // Convert back to short. 8277 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8278 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8279 return X; 8280 } 8281 8282 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8283 SelectionDAG &DAG) { 8284 // TODO: Should this propagate fast-math-flags? 8285 8286 SDValue N2; 8287 // Convert to float. 8288 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8289 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8290 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8291 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8292 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8293 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8294 8295 // Use reciprocal estimate and one refinement step. 8296 // float4 recip = vrecpeq_f32(yf); 8297 // recip *= vrecpsq_f32(yf, recip); 8298 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8299 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8300 N1); 8301 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8302 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8303 N1, N2); 8304 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8305 // Because short has a smaller range than ushort, we can actually get away 8306 // with only a single newton step. This requires that we use a weird bias 8307 // of 89, however (again, this has been exhaustively tested). 8308 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 8309 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8310 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8311 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 8312 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8313 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8314 // Convert back to integer and return. 8315 // return vmovn_s32(vcvt_s32_f32(result)); 8316 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8317 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8318 return N0; 8319 } 8320 8321 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 8322 const ARMSubtarget *ST) { 8323 EVT VT = Op.getValueType(); 8324 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8325 "unexpected type for custom-lowering ISD::SDIV"); 8326 8327 SDLoc dl(Op); 8328 SDValue N0 = Op.getOperand(0); 8329 SDValue N1 = Op.getOperand(1); 8330 SDValue N2, N3; 8331 8332 if (VT == MVT::v8i8) { 8333 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 8334 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 8335 8336 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8337 DAG.getIntPtrConstant(4, dl)); 8338 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8339 DAG.getIntPtrConstant(4, dl)); 8340 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8341 DAG.getIntPtrConstant(0, dl)); 8342 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8343 DAG.getIntPtrConstant(0, dl)); 8344 8345 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 8346 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 8347 8348 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8349 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8350 8351 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 8352 return N0; 8353 } 8354 return LowerSDIV_v4i16(N0, N1, dl, DAG); 8355 } 8356 8357 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 8358 const ARMSubtarget *ST) { 8359 // TODO: Should this propagate fast-math-flags? 8360 EVT VT = Op.getValueType(); 8361 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8362 "unexpected type for custom-lowering ISD::UDIV"); 8363 8364 SDLoc dl(Op); 8365 SDValue N0 = Op.getOperand(0); 8366 SDValue N1 = Op.getOperand(1); 8367 SDValue N2, N3; 8368 8369 if (VT == MVT::v8i8) { 8370 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 8371 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 8372 8373 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8374 DAG.getIntPtrConstant(4, dl)); 8375 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8376 DAG.getIntPtrConstant(4, dl)); 8377 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8378 DAG.getIntPtrConstant(0, dl)); 8379 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8380 DAG.getIntPtrConstant(0, dl)); 8381 8382 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 8383 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 8384 8385 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8386 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8387 8388 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 8389 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 8390 MVT::i32), 8391 N0); 8392 return N0; 8393 } 8394 8395 // v4i16 sdiv ... Convert to float. 8396 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 8397 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 8398 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 8399 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 8400 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8401 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8402 8403 // Use reciprocal estimate and two refinement steps. 8404 // float4 recip = vrecpeq_f32(yf); 8405 // recip *= vrecpsq_f32(yf, recip); 8406 // recip *= vrecpsq_f32(yf, recip); 8407 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8408 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8409 BN1); 8410 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8411 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8412 BN1, N2); 8413 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8414 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8415 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8416 BN1, N2); 8417 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8418 // Simply multiplying by the reciprocal estimate can leave us a few ulps 8419 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 8420 // and that it will never cause us to return an answer too large). 8421 // float4 result = as_float4(as_int4(xf*recip) + 2); 8422 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8423 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8424 N1 = DAG.getConstant(2, dl, MVT::v4i32); 8425 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8426 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8427 // Convert back to integer and return. 8428 // return vmovn_u32(vcvt_s32_f32(result)); 8429 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8430 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8431 return N0; 8432 } 8433 8434 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 8435 SDNode *N = Op.getNode(); 8436 EVT VT = N->getValueType(0); 8437 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 8438 8439 SDValue Carry = Op.getOperand(2); 8440 8441 SDLoc DL(Op); 8442 8443 SDValue Result; 8444 if (Op.getOpcode() == ISD::ADDCARRY) { 8445 // This converts the boolean value carry into the carry flag. 8446 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8447 8448 // Do the addition proper using the carry flag we wanted. 8449 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 8450 Op.getOperand(1), Carry); 8451 8452 // Now convert the carry flag into a boolean value. 8453 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8454 } else { 8455 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 8456 // have to invert the carry first. 8457 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8458 DAG.getConstant(1, DL, MVT::i32), Carry); 8459 // This converts the boolean value carry into the carry flag. 8460 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8461 8462 // Do the subtraction proper using the carry flag we wanted. 8463 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 8464 Op.getOperand(1), Carry); 8465 8466 // Now convert the carry flag into a boolean value. 8467 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8468 // But the carry returned by ARMISD::SUBE is not a borrow as expected 8469 // by ISD::SUBCARRY, so compute 1 - C. 8470 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8471 DAG.getConstant(1, DL, MVT::i32), Carry); 8472 } 8473 8474 // Return both values. 8475 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 8476 } 8477 8478 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 8479 assert(Subtarget->isTargetDarwin()); 8480 8481 // For iOS, we want to call an alternative entry point: __sincos_stret, 8482 // return values are passed via sret. 8483 SDLoc dl(Op); 8484 SDValue Arg = Op.getOperand(0); 8485 EVT ArgVT = Arg.getValueType(); 8486 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 8487 auto PtrVT = getPointerTy(DAG.getDataLayout()); 8488 8489 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8490 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8491 8492 // Pair of floats / doubles used to pass the result. 8493 Type *RetTy = StructType::get(ArgTy, ArgTy); 8494 auto &DL = DAG.getDataLayout(); 8495 8496 ArgListTy Args; 8497 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 8498 SDValue SRet; 8499 if (ShouldUseSRet) { 8500 // Create stack object for sret. 8501 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 8502 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 8503 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 8504 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 8505 8506 ArgListEntry Entry; 8507 Entry.Node = SRet; 8508 Entry.Ty = RetTy->getPointerTo(); 8509 Entry.IsSExt = false; 8510 Entry.IsZExt = false; 8511 Entry.IsSRet = true; 8512 Args.push_back(Entry); 8513 RetTy = Type::getVoidTy(*DAG.getContext()); 8514 } 8515 8516 ArgListEntry Entry; 8517 Entry.Node = Arg; 8518 Entry.Ty = ArgTy; 8519 Entry.IsSExt = false; 8520 Entry.IsZExt = false; 8521 Args.push_back(Entry); 8522 8523 RTLIB::Libcall LC = 8524 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 8525 const char *LibcallName = getLibcallName(LC); 8526 CallingConv::ID CC = getLibcallCallingConv(LC); 8527 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 8528 8529 TargetLowering::CallLoweringInfo CLI(DAG); 8530 CLI.setDebugLoc(dl) 8531 .setChain(DAG.getEntryNode()) 8532 .setCallee(CC, RetTy, Callee, std::move(Args)) 8533 .setDiscardResult(ShouldUseSRet); 8534 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8535 8536 if (!ShouldUseSRet) 8537 return CallResult.first; 8538 8539 SDValue LoadSin = 8540 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 8541 8542 // Address of cos field. 8543 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 8544 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 8545 SDValue LoadCos = 8546 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 8547 8548 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 8549 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 8550 LoadSin.getValue(0), LoadCos.getValue(0)); 8551 } 8552 8553 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 8554 bool Signed, 8555 SDValue &Chain) const { 8556 EVT VT = Op.getValueType(); 8557 assert((VT == MVT::i32 || VT == MVT::i64) && 8558 "unexpected type for custom lowering DIV"); 8559 SDLoc dl(Op); 8560 8561 const auto &DL = DAG.getDataLayout(); 8562 const auto &TLI = DAG.getTargetLoweringInfo(); 8563 8564 const char *Name = nullptr; 8565 if (Signed) 8566 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 8567 else 8568 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 8569 8570 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 8571 8572 ARMTargetLowering::ArgListTy Args; 8573 8574 for (auto AI : {1, 0}) { 8575 ArgListEntry Arg; 8576 Arg.Node = Op.getOperand(AI); 8577 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 8578 Args.push_back(Arg); 8579 } 8580 8581 CallLoweringInfo CLI(DAG); 8582 CLI.setDebugLoc(dl) 8583 .setChain(Chain) 8584 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 8585 ES, std::move(Args)); 8586 8587 return LowerCallTo(CLI).first; 8588 } 8589 8590 // This is a code size optimisation: return the original SDIV node to 8591 // DAGCombiner when we don't want to expand SDIV into a sequence of 8592 // instructions, and an empty node otherwise which will cause the 8593 // SDIV to be expanded in DAGCombine. 8594 SDValue 8595 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8596 SelectionDAG &DAG, 8597 SmallVectorImpl<SDNode *> &Created) const { 8598 // TODO: Support SREM 8599 if (N->getOpcode() != ISD::SDIV) 8600 return SDValue(); 8601 8602 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 8603 const bool MinSize = ST.hasMinSize(); 8604 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 8605 : ST.hasDivideInARMMode(); 8606 8607 // Don't touch vector types; rewriting this may lead to scalarizing 8608 // the int divs. 8609 if (N->getOperand(0).getValueType().isVector()) 8610 return SDValue(); 8611 8612 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 8613 // hwdiv support for this to be really profitable. 8614 if (!(MinSize && HasDivide)) 8615 return SDValue(); 8616 8617 // ARM mode is a bit simpler than Thumb: we can handle large power 8618 // of 2 immediates with 1 mov instruction; no further checks required, 8619 // just return the sdiv node. 8620 if (!ST.isThumb()) 8621 return SDValue(N, 0); 8622 8623 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 8624 // and thus lose the code size benefits of a MOVS that requires only 2. 8625 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 8626 // but as it's doing exactly this, it's not worth the trouble to get TTI. 8627 if (Divisor.sgt(128)) 8628 return SDValue(); 8629 8630 return SDValue(N, 0); 8631 } 8632 8633 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 8634 bool Signed) const { 8635 assert(Op.getValueType() == MVT::i32 && 8636 "unexpected type for custom lowering DIV"); 8637 SDLoc dl(Op); 8638 8639 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 8640 DAG.getEntryNode(), Op.getOperand(1)); 8641 8642 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8643 } 8644 8645 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 8646 SDLoc DL(N); 8647 SDValue Op = N->getOperand(1); 8648 if (N->getValueType(0) == MVT::i32) 8649 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 8650 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8651 DAG.getConstant(0, DL, MVT::i32)); 8652 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8653 DAG.getConstant(1, DL, MVT::i32)); 8654 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 8655 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 8656 } 8657 8658 void ARMTargetLowering::ExpandDIV_Windows( 8659 SDValue Op, SelectionDAG &DAG, bool Signed, 8660 SmallVectorImpl<SDValue> &Results) const { 8661 const auto &DL = DAG.getDataLayout(); 8662 const auto &TLI = DAG.getTargetLoweringInfo(); 8663 8664 assert(Op.getValueType() == MVT::i64 && 8665 "unexpected type for custom lowering DIV"); 8666 SDLoc dl(Op); 8667 8668 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 8669 8670 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8671 8672 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 8673 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 8674 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 8675 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 8676 8677 Results.push_back(Lower); 8678 Results.push_back(Upper); 8679 } 8680 8681 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 8682 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 8683 // Acquire/Release load/store is not legal for targets without a dmb or 8684 // equivalent available. 8685 return SDValue(); 8686 8687 // Monotonic load/store is legal for all targets. 8688 return Op; 8689 } 8690 8691 static void ReplaceREADCYCLECOUNTER(SDNode *N, 8692 SmallVectorImpl<SDValue> &Results, 8693 SelectionDAG &DAG, 8694 const ARMSubtarget *Subtarget) { 8695 SDLoc DL(N); 8696 // Under Power Management extensions, the cycle-count is: 8697 // mrc p15, #0, <Rt>, c9, c13, #0 8698 SDValue Ops[] = { N->getOperand(0), // Chain 8699 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 8700 DAG.getConstant(15, DL, MVT::i32), 8701 DAG.getConstant(0, DL, MVT::i32), 8702 DAG.getConstant(9, DL, MVT::i32), 8703 DAG.getConstant(13, DL, MVT::i32), 8704 DAG.getConstant(0, DL, MVT::i32) 8705 }; 8706 8707 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 8708 DAG.getVTList(MVT::i32, MVT::Other), Ops); 8709 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 8710 DAG.getConstant(0, DL, MVT::i32))); 8711 Results.push_back(Cycles32.getValue(1)); 8712 } 8713 8714 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 8715 SDLoc dl(V.getNode()); 8716 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 8717 SDValue VHi = DAG.getAnyExtOrTrunc( 8718 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 8719 dl, MVT::i32); 8720 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8721 if (isBigEndian) 8722 std::swap (VLo, VHi); 8723 SDValue RegClass = 8724 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 8725 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 8726 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 8727 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 8728 return SDValue( 8729 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 8730 } 8731 8732 static void ReplaceCMP_SWAP_64Results(SDNode *N, 8733 SmallVectorImpl<SDValue> & Results, 8734 SelectionDAG &DAG) { 8735 assert(N->getValueType(0) == MVT::i64 && 8736 "AtomicCmpSwap on types less than 64 should be legal"); 8737 SDValue Ops[] = {N->getOperand(1), 8738 createGPRPairNode(DAG, N->getOperand(2)), 8739 createGPRPairNode(DAG, N->getOperand(3)), 8740 N->getOperand(0)}; 8741 SDNode *CmpSwap = DAG.getMachineNode( 8742 ARM::CMP_SWAP_64, SDLoc(N), 8743 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 8744 8745 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 8746 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 8747 8748 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8749 8750 Results.push_back( 8751 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 8752 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8753 Results.push_back( 8754 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 8755 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8756 Results.push_back(SDValue(CmpSwap, 2)); 8757 } 8758 8759 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 8760 SelectionDAG &DAG) { 8761 const auto &TLI = DAG.getTargetLoweringInfo(); 8762 8763 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 8764 "Custom lowering is MSVCRT specific!"); 8765 8766 SDLoc dl(Op); 8767 SDValue Val = Op.getOperand(0); 8768 MVT Ty = Val->getSimpleValueType(0); 8769 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 8770 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 8771 TLI.getPointerTy(DAG.getDataLayout())); 8772 8773 TargetLowering::ArgListTy Args; 8774 TargetLowering::ArgListEntry Entry; 8775 8776 Entry.Node = Val; 8777 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8778 Entry.IsZExt = true; 8779 Args.push_back(Entry); 8780 8781 Entry.Node = Exponent; 8782 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8783 Entry.IsZExt = true; 8784 Args.push_back(Entry); 8785 8786 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8787 8788 // In the in-chain to the call is the entry node If we are emitting a 8789 // tailcall, the chain will be mutated if the node has a non-entry input 8790 // chain. 8791 SDValue InChain = DAG.getEntryNode(); 8792 SDValue TCChain = InChain; 8793 8794 const Function &F = DAG.getMachineFunction().getFunction(); 8795 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8796 F.getReturnType() == LCRTy; 8797 if (IsTC) 8798 InChain = TCChain; 8799 8800 TargetLowering::CallLoweringInfo CLI(DAG); 8801 CLI.setDebugLoc(dl) 8802 .setChain(InChain) 8803 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8804 .setTailCall(IsTC); 8805 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8806 8807 // Return the chain (the DAG root) if it is a tail call 8808 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8809 } 8810 8811 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8812 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8813 switch (Op.getOpcode()) { 8814 default: llvm_unreachable("Don't know how to custom lower this!"); 8815 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8816 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8817 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8818 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8819 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8820 case ISD::SELECT: return LowerSELECT(Op, DAG); 8821 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8822 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8823 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8824 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8825 case ISD::VASTART: return LowerVASTART(Op, DAG); 8826 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8827 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8828 case ISD::SINT_TO_FP: 8829 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8830 case ISD::FP_TO_SINT: 8831 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8832 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8833 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8834 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8835 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8836 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8837 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8838 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8839 Subtarget); 8840 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8841 case ISD::SHL: 8842 case ISD::SRL: 8843 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8844 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8845 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8846 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8847 case ISD::SRL_PARTS: 8848 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8849 case ISD::CTTZ: 8850 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8851 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8852 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 8853 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8854 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8855 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8856 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 8857 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 8858 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8859 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 8860 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 8861 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8862 case ISD::MUL: return LowerMUL(Op, DAG); 8863 case ISD::SDIV: 8864 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8865 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8866 return LowerSDIV(Op, DAG, Subtarget); 8867 case ISD::UDIV: 8868 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8869 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8870 return LowerUDIV(Op, DAG, Subtarget); 8871 case ISD::ADDCARRY: 8872 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8873 case ISD::SADDO: 8874 case ISD::SSUBO: 8875 return LowerSignedALUO(Op, DAG); 8876 case ISD::UADDO: 8877 case ISD::USUBO: 8878 return LowerUnsignedALUO(Op, DAG); 8879 case ISD::ATOMIC_LOAD: 8880 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8881 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8882 case ISD::SDIVREM: 8883 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8884 case ISD::DYNAMIC_STACKALLOC: 8885 if (Subtarget->isTargetWindows()) 8886 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8887 llvm_unreachable("Don't know how to custom lower this!"); 8888 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8889 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8890 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8891 case ARMISD::WIN__DBZCHK: return SDValue(); 8892 } 8893 } 8894 8895 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8896 SelectionDAG &DAG) { 8897 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8898 unsigned Opc = 0; 8899 if (IntNo == Intrinsic::arm_smlald) 8900 Opc = ARMISD::SMLALD; 8901 else if (IntNo == Intrinsic::arm_smlaldx) 8902 Opc = ARMISD::SMLALDX; 8903 else if (IntNo == Intrinsic::arm_smlsld) 8904 Opc = ARMISD::SMLSLD; 8905 else if (IntNo == Intrinsic::arm_smlsldx) 8906 Opc = ARMISD::SMLSLDX; 8907 else 8908 return; 8909 8910 SDLoc dl(N); 8911 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8912 N->getOperand(3), 8913 DAG.getConstant(0, dl, MVT::i32)); 8914 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8915 N->getOperand(3), 8916 DAG.getConstant(1, dl, MVT::i32)); 8917 8918 SDValue LongMul = DAG.getNode(Opc, dl, 8919 DAG.getVTList(MVT::i32, MVT::i32), 8920 N->getOperand(1), N->getOperand(2), 8921 Lo, Hi); 8922 Results.push_back(LongMul.getValue(0)); 8923 Results.push_back(LongMul.getValue(1)); 8924 } 8925 8926 /// ReplaceNodeResults - Replace the results of node with an illegal result 8927 /// type with new values built out of custom code. 8928 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8929 SmallVectorImpl<SDValue> &Results, 8930 SelectionDAG &DAG) const { 8931 SDValue Res; 8932 switch (N->getOpcode()) { 8933 default: 8934 llvm_unreachable("Don't know how to custom expand this!"); 8935 case ISD::READ_REGISTER: 8936 ExpandREAD_REGISTER(N, Results, DAG); 8937 break; 8938 case ISD::BITCAST: 8939 Res = ExpandBITCAST(N, DAG, Subtarget); 8940 break; 8941 case ISD::SRL: 8942 case ISD::SRA: 8943 case ISD::SHL: 8944 Res = Expand64BitShift(N, DAG, Subtarget); 8945 break; 8946 case ISD::SREM: 8947 case ISD::UREM: 8948 Res = LowerREM(N, DAG); 8949 break; 8950 case ISD::SDIVREM: 8951 case ISD::UDIVREM: 8952 Res = LowerDivRem(SDValue(N, 0), DAG); 8953 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8954 Results.push_back(Res.getValue(0)); 8955 Results.push_back(Res.getValue(1)); 8956 return; 8957 case ISD::READCYCLECOUNTER: 8958 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8959 return; 8960 case ISD::UDIV: 8961 case ISD::SDIV: 8962 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8963 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8964 Results); 8965 case ISD::ATOMIC_CMP_SWAP: 8966 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8967 return; 8968 case ISD::INTRINSIC_WO_CHAIN: 8969 return ReplaceLongIntrinsic(N, Results, DAG); 8970 case ISD::ABS: 8971 lowerABS(N, Results, DAG); 8972 return ; 8973 8974 } 8975 if (Res.getNode()) 8976 Results.push_back(Res); 8977 } 8978 8979 //===----------------------------------------------------------------------===// 8980 // ARM Scheduler Hooks 8981 //===----------------------------------------------------------------------===// 8982 8983 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8984 /// registers the function context. 8985 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8986 MachineBasicBlock *MBB, 8987 MachineBasicBlock *DispatchBB, 8988 int FI) const { 8989 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8990 "ROPI/RWPI not currently supported with SjLj"); 8991 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8992 DebugLoc dl = MI.getDebugLoc(); 8993 MachineFunction *MF = MBB->getParent(); 8994 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8995 MachineConstantPool *MCP = MF->getConstantPool(); 8996 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8997 const Function &F = MF->getFunction(); 8998 8999 bool isThumb = Subtarget->isThumb(); 9000 bool isThumb2 = Subtarget->isThumb2(); 9001 9002 unsigned PCLabelId = AFI->createPICLabelUId(); 9003 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 9004 ARMConstantPoolValue *CPV = 9005 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 9006 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 9007 9008 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 9009 : &ARM::GPRRegClass; 9010 9011 // Grab constant pool and fixed stack memory operands. 9012 MachineMemOperand *CPMMO = 9013 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9014 MachineMemOperand::MOLoad, 4, 4); 9015 9016 MachineMemOperand *FIMMOSt = 9017 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 9018 MachineMemOperand::MOStore, 4, 4); 9019 9020 // Load the address of the dispatch MBB into the jump buffer. 9021 if (isThumb2) { 9022 // Incoming value: jbuf 9023 // ldr.n r5, LCPI1_1 9024 // orr r5, r5, #1 9025 // add r5, pc 9026 // str r5, [$jbuf, #+4] ; &jbuf[1] 9027 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9028 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9029 .addConstantPoolIndex(CPI) 9030 .addMemOperand(CPMMO) 9031 .add(predOps(ARMCC::AL)); 9032 // Set the low bit because of thumb mode. 9033 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 9034 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9035 .addReg(NewVReg1, RegState::Kill) 9036 .addImm(0x01) 9037 .add(predOps(ARMCC::AL)) 9038 .add(condCodeOp()); 9039 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9040 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9041 .addReg(NewVReg2, RegState::Kill) 9042 .addImm(PCLabelId); 9043 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9044 .addReg(NewVReg3, RegState::Kill) 9045 .addFrameIndex(FI) 9046 .addImm(36) // &jbuf[1] :: pc 9047 .addMemOperand(FIMMOSt) 9048 .add(predOps(ARMCC::AL)); 9049 } else if (isThumb) { 9050 // Incoming value: jbuf 9051 // ldr.n r1, LCPI1_4 9052 // add r1, pc 9053 // mov r2, #1 9054 // orrs r1, r2 9055 // add r2, $jbuf, #+4 ; &jbuf[1] 9056 // str r1, [r2] 9057 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9058 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 9059 .addConstantPoolIndex(CPI) 9060 .addMemOperand(CPMMO) 9061 .add(predOps(ARMCC::AL)); 9062 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 9063 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 9064 .addReg(NewVReg1, RegState::Kill) 9065 .addImm(PCLabelId); 9066 // Set the low bit because of thumb mode. 9067 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9068 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 9069 .addReg(ARM::CPSR, RegState::Define) 9070 .addImm(1) 9071 .add(predOps(ARMCC::AL)); 9072 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 9073 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 9074 .addReg(ARM::CPSR, RegState::Define) 9075 .addReg(NewVReg2, RegState::Kill) 9076 .addReg(NewVReg3, RegState::Kill) 9077 .add(predOps(ARMCC::AL)); 9078 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 9079 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 9080 .addFrameIndex(FI) 9081 .addImm(36); // &jbuf[1] :: pc 9082 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 9083 .addReg(NewVReg4, RegState::Kill) 9084 .addReg(NewVReg5, RegState::Kill) 9085 .addImm(0) 9086 .addMemOperand(FIMMOSt) 9087 .add(predOps(ARMCC::AL)); 9088 } else { 9089 // Incoming value: jbuf 9090 // ldr r1, LCPI1_1 9091 // add r1, pc, r1 9092 // str r1, [$jbuf, #+4] ; &jbuf[1] 9093 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9094 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 9095 .addConstantPoolIndex(CPI) 9096 .addImm(0) 9097 .addMemOperand(CPMMO) 9098 .add(predOps(ARMCC::AL)); 9099 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 9100 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 9101 .addReg(NewVReg1, RegState::Kill) 9102 .addImm(PCLabelId) 9103 .add(predOps(ARMCC::AL)); 9104 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 9105 .addReg(NewVReg2, RegState::Kill) 9106 .addFrameIndex(FI) 9107 .addImm(36) // &jbuf[1] :: pc 9108 .addMemOperand(FIMMOSt) 9109 .add(predOps(ARMCC::AL)); 9110 } 9111 } 9112 9113 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 9114 MachineBasicBlock *MBB) const { 9115 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9116 DebugLoc dl = MI.getDebugLoc(); 9117 MachineFunction *MF = MBB->getParent(); 9118 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9119 MachineFrameInfo &MFI = MF->getFrameInfo(); 9120 int FI = MFI.getFunctionContextIndex(); 9121 9122 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 9123 : &ARM::GPRnopcRegClass; 9124 9125 // Get a mapping of the call site numbers to all of the landing pads they're 9126 // associated with. 9127 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 9128 unsigned MaxCSNum = 0; 9129 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 9130 ++BB) { 9131 if (!BB->isEHPad()) continue; 9132 9133 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 9134 // pad. 9135 for (MachineBasicBlock::iterator 9136 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 9137 if (!II->isEHLabel()) continue; 9138 9139 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 9140 if (!MF->hasCallSiteLandingPad(Sym)) continue; 9141 9142 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 9143 for (SmallVectorImpl<unsigned>::iterator 9144 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 9145 CSI != CSE; ++CSI) { 9146 CallSiteNumToLPad[*CSI].push_back(&*BB); 9147 MaxCSNum = std::max(MaxCSNum, *CSI); 9148 } 9149 break; 9150 } 9151 } 9152 9153 // Get an ordered list of the machine basic blocks for the jump table. 9154 std::vector<MachineBasicBlock*> LPadList; 9155 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 9156 LPadList.reserve(CallSiteNumToLPad.size()); 9157 for (unsigned I = 1; I <= MaxCSNum; ++I) { 9158 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 9159 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9160 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 9161 LPadList.push_back(*II); 9162 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 9163 } 9164 } 9165 9166 assert(!LPadList.empty() && 9167 "No landing pad destinations for the dispatch jump table!"); 9168 9169 // Create the jump table and associated information. 9170 MachineJumpTableInfo *JTI = 9171 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 9172 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 9173 9174 // Create the MBBs for the dispatch code. 9175 9176 // Shove the dispatch's address into the return slot in the function context. 9177 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 9178 DispatchBB->setIsEHPad(); 9179 9180 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9181 unsigned trap_opcode; 9182 if (Subtarget->isThumb()) 9183 trap_opcode = ARM::tTRAP; 9184 else 9185 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 9186 9187 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 9188 DispatchBB->addSuccessor(TrapBB); 9189 9190 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 9191 DispatchBB->addSuccessor(DispContBB); 9192 9193 // Insert and MBBs. 9194 MF->insert(MF->end(), DispatchBB); 9195 MF->insert(MF->end(), DispContBB); 9196 MF->insert(MF->end(), TrapBB); 9197 9198 // Insert code into the entry block that creates and registers the function 9199 // context. 9200 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 9201 9202 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 9203 MachinePointerInfo::getFixedStack(*MF, FI), 9204 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 9205 9206 MachineInstrBuilder MIB; 9207 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 9208 9209 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 9210 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 9211 9212 // Add a register mask with no preserved registers. This results in all 9213 // registers being marked as clobbered. This can't work if the dispatch block 9214 // is in a Thumb1 function and is linked with ARM code which uses the FP 9215 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 9216 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 9217 9218 bool IsPositionIndependent = isPositionIndependent(); 9219 unsigned NumLPads = LPadList.size(); 9220 if (Subtarget->isThumb2()) { 9221 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9222 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 9223 .addFrameIndex(FI) 9224 .addImm(4) 9225 .addMemOperand(FIMMOLd) 9226 .add(predOps(ARMCC::AL)); 9227 9228 if (NumLPads < 256) { 9229 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 9230 .addReg(NewVReg1) 9231 .addImm(LPadList.size()) 9232 .add(predOps(ARMCC::AL)); 9233 } else { 9234 unsigned VReg1 = MRI->createVirtualRegister(TRC); 9235 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 9236 .addImm(NumLPads & 0xFFFF) 9237 .add(predOps(ARMCC::AL)); 9238 9239 unsigned VReg2 = VReg1; 9240 if ((NumLPads & 0xFFFF0000) != 0) { 9241 VReg2 = MRI->createVirtualRegister(TRC); 9242 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 9243 .addReg(VReg1) 9244 .addImm(NumLPads >> 16) 9245 .add(predOps(ARMCC::AL)); 9246 } 9247 9248 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 9249 .addReg(NewVReg1) 9250 .addReg(VReg2) 9251 .add(predOps(ARMCC::AL)); 9252 } 9253 9254 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 9255 .addMBB(TrapBB) 9256 .addImm(ARMCC::HI) 9257 .addReg(ARM::CPSR); 9258 9259 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9260 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 9261 .addJumpTableIndex(MJTI) 9262 .add(predOps(ARMCC::AL)); 9263 9264 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 9265 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 9266 .addReg(NewVReg3, RegState::Kill) 9267 .addReg(NewVReg1) 9268 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9269 .add(predOps(ARMCC::AL)) 9270 .add(condCodeOp()); 9271 9272 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 9273 .addReg(NewVReg4, RegState::Kill) 9274 .addReg(NewVReg1) 9275 .addJumpTableIndex(MJTI); 9276 } else if (Subtarget->isThumb()) { 9277 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9278 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 9279 .addFrameIndex(FI) 9280 .addImm(1) 9281 .addMemOperand(FIMMOLd) 9282 .add(predOps(ARMCC::AL)); 9283 9284 if (NumLPads < 256) { 9285 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 9286 .addReg(NewVReg1) 9287 .addImm(NumLPads) 9288 .add(predOps(ARMCC::AL)); 9289 } else { 9290 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9291 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9292 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9293 9294 // MachineConstantPool wants an explicit alignment. 9295 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9296 if (Align == 0) 9297 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9298 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9299 9300 unsigned VReg1 = MRI->createVirtualRegister(TRC); 9301 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 9302 .addReg(VReg1, RegState::Define) 9303 .addConstantPoolIndex(Idx) 9304 .add(predOps(ARMCC::AL)); 9305 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 9306 .addReg(NewVReg1) 9307 .addReg(VReg1) 9308 .add(predOps(ARMCC::AL)); 9309 } 9310 9311 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 9312 .addMBB(TrapBB) 9313 .addImm(ARMCC::HI) 9314 .addReg(ARM::CPSR); 9315 9316 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 9317 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 9318 .addReg(ARM::CPSR, RegState::Define) 9319 .addReg(NewVReg1) 9320 .addImm(2) 9321 .add(predOps(ARMCC::AL)); 9322 9323 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9324 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 9325 .addJumpTableIndex(MJTI) 9326 .add(predOps(ARMCC::AL)); 9327 9328 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 9329 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 9330 .addReg(ARM::CPSR, RegState::Define) 9331 .addReg(NewVReg2, RegState::Kill) 9332 .addReg(NewVReg3) 9333 .add(predOps(ARMCC::AL)); 9334 9335 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9336 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9337 9338 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 9339 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 9340 .addReg(NewVReg4, RegState::Kill) 9341 .addImm(0) 9342 .addMemOperand(JTMMOLd) 9343 .add(predOps(ARMCC::AL)); 9344 9345 unsigned NewVReg6 = NewVReg5; 9346 if (IsPositionIndependent) { 9347 NewVReg6 = MRI->createVirtualRegister(TRC); 9348 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 9349 .addReg(ARM::CPSR, RegState::Define) 9350 .addReg(NewVReg5, RegState::Kill) 9351 .addReg(NewVReg3) 9352 .add(predOps(ARMCC::AL)); 9353 } 9354 9355 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 9356 .addReg(NewVReg6, RegState::Kill) 9357 .addJumpTableIndex(MJTI); 9358 } else { 9359 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9360 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 9361 .addFrameIndex(FI) 9362 .addImm(4) 9363 .addMemOperand(FIMMOLd) 9364 .add(predOps(ARMCC::AL)); 9365 9366 if (NumLPads < 256) { 9367 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 9368 .addReg(NewVReg1) 9369 .addImm(NumLPads) 9370 .add(predOps(ARMCC::AL)); 9371 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 9372 unsigned VReg1 = MRI->createVirtualRegister(TRC); 9373 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 9374 .addImm(NumLPads & 0xFFFF) 9375 .add(predOps(ARMCC::AL)); 9376 9377 unsigned VReg2 = VReg1; 9378 if ((NumLPads & 0xFFFF0000) != 0) { 9379 VReg2 = MRI->createVirtualRegister(TRC); 9380 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 9381 .addReg(VReg1) 9382 .addImm(NumLPads >> 16) 9383 .add(predOps(ARMCC::AL)); 9384 } 9385 9386 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9387 .addReg(NewVReg1) 9388 .addReg(VReg2) 9389 .add(predOps(ARMCC::AL)); 9390 } else { 9391 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9392 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9393 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9394 9395 // MachineConstantPool wants an explicit alignment. 9396 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9397 if (Align == 0) 9398 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9399 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9400 9401 unsigned VReg1 = MRI->createVirtualRegister(TRC); 9402 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 9403 .addReg(VReg1, RegState::Define) 9404 .addConstantPoolIndex(Idx) 9405 .addImm(0) 9406 .add(predOps(ARMCC::AL)); 9407 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9408 .addReg(NewVReg1) 9409 .addReg(VReg1, RegState::Kill) 9410 .add(predOps(ARMCC::AL)); 9411 } 9412 9413 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 9414 .addMBB(TrapBB) 9415 .addImm(ARMCC::HI) 9416 .addReg(ARM::CPSR); 9417 9418 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9419 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 9420 .addReg(NewVReg1) 9421 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9422 .add(predOps(ARMCC::AL)) 9423 .add(condCodeOp()); 9424 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 9425 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 9426 .addJumpTableIndex(MJTI) 9427 .add(predOps(ARMCC::AL)); 9428 9429 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9430 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9431 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 9432 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 9433 .addReg(NewVReg3, RegState::Kill) 9434 .addReg(NewVReg4) 9435 .addImm(0) 9436 .addMemOperand(JTMMOLd) 9437 .add(predOps(ARMCC::AL)); 9438 9439 if (IsPositionIndependent) { 9440 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 9441 .addReg(NewVReg5, RegState::Kill) 9442 .addReg(NewVReg4) 9443 .addJumpTableIndex(MJTI); 9444 } else { 9445 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 9446 .addReg(NewVReg5, RegState::Kill) 9447 .addJumpTableIndex(MJTI); 9448 } 9449 } 9450 9451 // Add the jump table entries as successors to the MBB. 9452 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 9453 for (std::vector<MachineBasicBlock*>::iterator 9454 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 9455 MachineBasicBlock *CurMBB = *I; 9456 if (SeenMBBs.insert(CurMBB).second) 9457 DispContBB->addSuccessor(CurMBB); 9458 } 9459 9460 // N.B. the order the invoke BBs are processed in doesn't matter here. 9461 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 9462 SmallVector<MachineBasicBlock*, 64> MBBLPads; 9463 for (MachineBasicBlock *BB : InvokeBBs) { 9464 9465 // Remove the landing pad successor from the invoke block and replace it 9466 // with the new dispatch block. 9467 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 9468 BB->succ_end()); 9469 while (!Successors.empty()) { 9470 MachineBasicBlock *SMBB = Successors.pop_back_val(); 9471 if (SMBB->isEHPad()) { 9472 BB->removeSuccessor(SMBB); 9473 MBBLPads.push_back(SMBB); 9474 } 9475 } 9476 9477 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 9478 BB->normalizeSuccProbs(); 9479 9480 // Find the invoke call and mark all of the callee-saved registers as 9481 // 'implicit defined' so that they're spilled. This prevents code from 9482 // moving instructions to before the EH block, where they will never be 9483 // executed. 9484 for (MachineBasicBlock::reverse_iterator 9485 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 9486 if (!II->isCall()) continue; 9487 9488 DenseMap<unsigned, bool> DefRegs; 9489 for (MachineInstr::mop_iterator 9490 OI = II->operands_begin(), OE = II->operands_end(); 9491 OI != OE; ++OI) { 9492 if (!OI->isReg()) continue; 9493 DefRegs[OI->getReg()] = true; 9494 } 9495 9496 MachineInstrBuilder MIB(*MF, &*II); 9497 9498 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 9499 unsigned Reg = SavedRegs[i]; 9500 if (Subtarget->isThumb2() && 9501 !ARM::tGPRRegClass.contains(Reg) && 9502 !ARM::hGPRRegClass.contains(Reg)) 9503 continue; 9504 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 9505 continue; 9506 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 9507 continue; 9508 if (!DefRegs[Reg]) 9509 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 9510 } 9511 9512 break; 9513 } 9514 } 9515 9516 // Mark all former landing pads as non-landing pads. The dispatch is the only 9517 // landing pad now. 9518 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9519 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 9520 (*I)->setIsEHPad(false); 9521 9522 // The instruction is gone now. 9523 MI.eraseFromParent(); 9524 } 9525 9526 static 9527 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 9528 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 9529 E = MBB->succ_end(); I != E; ++I) 9530 if (*I != Succ) 9531 return *I; 9532 llvm_unreachable("Expecting a BB with two successors!"); 9533 } 9534 9535 /// Return the load opcode for a given load size. If load size >= 8, 9536 /// neon opcode will be returned. 9537 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 9538 if (LdSize >= 8) 9539 return LdSize == 16 ? ARM::VLD1q32wb_fixed 9540 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 9541 if (IsThumb1) 9542 return LdSize == 4 ? ARM::tLDRi 9543 : LdSize == 2 ? ARM::tLDRHi 9544 : LdSize == 1 ? ARM::tLDRBi : 0; 9545 if (IsThumb2) 9546 return LdSize == 4 ? ARM::t2LDR_POST 9547 : LdSize == 2 ? ARM::t2LDRH_POST 9548 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 9549 return LdSize == 4 ? ARM::LDR_POST_IMM 9550 : LdSize == 2 ? ARM::LDRH_POST 9551 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 9552 } 9553 9554 /// Return the store opcode for a given store size. If store size >= 8, 9555 /// neon opcode will be returned. 9556 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 9557 if (StSize >= 8) 9558 return StSize == 16 ? ARM::VST1q32wb_fixed 9559 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 9560 if (IsThumb1) 9561 return StSize == 4 ? ARM::tSTRi 9562 : StSize == 2 ? ARM::tSTRHi 9563 : StSize == 1 ? ARM::tSTRBi : 0; 9564 if (IsThumb2) 9565 return StSize == 4 ? ARM::t2STR_POST 9566 : StSize == 2 ? ARM::t2STRH_POST 9567 : StSize == 1 ? ARM::t2STRB_POST : 0; 9568 return StSize == 4 ? ARM::STR_POST_IMM 9569 : StSize == 2 ? ARM::STRH_POST 9570 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 9571 } 9572 9573 /// Emit a post-increment load operation with given size. The instructions 9574 /// will be added to BB at Pos. 9575 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9576 const TargetInstrInfo *TII, const DebugLoc &dl, 9577 unsigned LdSize, unsigned Data, unsigned AddrIn, 9578 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9579 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 9580 assert(LdOpc != 0 && "Should have a load opcode"); 9581 if (LdSize >= 8) { 9582 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9583 .addReg(AddrOut, RegState::Define) 9584 .addReg(AddrIn) 9585 .addImm(0) 9586 .add(predOps(ARMCC::AL)); 9587 } else if (IsThumb1) { 9588 // load + update AddrIn 9589 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9590 .addReg(AddrIn) 9591 .addImm(0) 9592 .add(predOps(ARMCC::AL)); 9593 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9594 .add(t1CondCodeOp()) 9595 .addReg(AddrIn) 9596 .addImm(LdSize) 9597 .add(predOps(ARMCC::AL)); 9598 } else if (IsThumb2) { 9599 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9600 .addReg(AddrOut, RegState::Define) 9601 .addReg(AddrIn) 9602 .addImm(LdSize) 9603 .add(predOps(ARMCC::AL)); 9604 } else { // arm 9605 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9606 .addReg(AddrOut, RegState::Define) 9607 .addReg(AddrIn) 9608 .addReg(0) 9609 .addImm(LdSize) 9610 .add(predOps(ARMCC::AL)); 9611 } 9612 } 9613 9614 /// Emit a post-increment store operation with given size. The instructions 9615 /// will be added to BB at Pos. 9616 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9617 const TargetInstrInfo *TII, const DebugLoc &dl, 9618 unsigned StSize, unsigned Data, unsigned AddrIn, 9619 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9620 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 9621 assert(StOpc != 0 && "Should have a store opcode"); 9622 if (StSize >= 8) { 9623 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9624 .addReg(AddrIn) 9625 .addImm(0) 9626 .addReg(Data) 9627 .add(predOps(ARMCC::AL)); 9628 } else if (IsThumb1) { 9629 // store + update AddrIn 9630 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 9631 .addReg(Data) 9632 .addReg(AddrIn) 9633 .addImm(0) 9634 .add(predOps(ARMCC::AL)); 9635 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9636 .add(t1CondCodeOp()) 9637 .addReg(AddrIn) 9638 .addImm(StSize) 9639 .add(predOps(ARMCC::AL)); 9640 } else if (IsThumb2) { 9641 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9642 .addReg(Data) 9643 .addReg(AddrIn) 9644 .addImm(StSize) 9645 .add(predOps(ARMCC::AL)); 9646 } else { // arm 9647 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9648 .addReg(Data) 9649 .addReg(AddrIn) 9650 .addReg(0) 9651 .addImm(StSize) 9652 .add(predOps(ARMCC::AL)); 9653 } 9654 } 9655 9656 MachineBasicBlock * 9657 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 9658 MachineBasicBlock *BB) const { 9659 // This pseudo instruction has 3 operands: dst, src, size 9660 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 9661 // Otherwise, we will generate unrolled scalar copies. 9662 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9663 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9664 MachineFunction::iterator It = ++BB->getIterator(); 9665 9666 unsigned dest = MI.getOperand(0).getReg(); 9667 unsigned src = MI.getOperand(1).getReg(); 9668 unsigned SizeVal = MI.getOperand(2).getImm(); 9669 unsigned Align = MI.getOperand(3).getImm(); 9670 DebugLoc dl = MI.getDebugLoc(); 9671 9672 MachineFunction *MF = BB->getParent(); 9673 MachineRegisterInfo &MRI = MF->getRegInfo(); 9674 unsigned UnitSize = 0; 9675 const TargetRegisterClass *TRC = nullptr; 9676 const TargetRegisterClass *VecTRC = nullptr; 9677 9678 bool IsThumb1 = Subtarget->isThumb1Only(); 9679 bool IsThumb2 = Subtarget->isThumb2(); 9680 bool IsThumb = Subtarget->isThumb(); 9681 9682 if (Align & 1) { 9683 UnitSize = 1; 9684 } else if (Align & 2) { 9685 UnitSize = 2; 9686 } else { 9687 // Check whether we can use NEON instructions. 9688 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 9689 Subtarget->hasNEON()) { 9690 if ((Align % 16 == 0) && SizeVal >= 16) 9691 UnitSize = 16; 9692 else if ((Align % 8 == 0) && SizeVal >= 8) 9693 UnitSize = 8; 9694 } 9695 // Can't use NEON instructions. 9696 if (UnitSize == 0) 9697 UnitSize = 4; 9698 } 9699 9700 // Select the correct opcode and register class for unit size load/store 9701 bool IsNeon = UnitSize >= 8; 9702 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 9703 if (IsNeon) 9704 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 9705 : UnitSize == 8 ? &ARM::DPRRegClass 9706 : nullptr; 9707 9708 unsigned BytesLeft = SizeVal % UnitSize; 9709 unsigned LoopSize = SizeVal - BytesLeft; 9710 9711 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 9712 // Use LDR and STR to copy. 9713 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 9714 // [destOut] = STR_POST(scratch, destIn, UnitSize) 9715 unsigned srcIn = src; 9716 unsigned destIn = dest; 9717 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 9718 unsigned srcOut = MRI.createVirtualRegister(TRC); 9719 unsigned destOut = MRI.createVirtualRegister(TRC); 9720 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9721 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 9722 IsThumb1, IsThumb2); 9723 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 9724 IsThumb1, IsThumb2); 9725 srcIn = srcOut; 9726 destIn = destOut; 9727 } 9728 9729 // Handle the leftover bytes with LDRB and STRB. 9730 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 9731 // [destOut] = STRB_POST(scratch, destIn, 1) 9732 for (unsigned i = 0; i < BytesLeft; i++) { 9733 unsigned srcOut = MRI.createVirtualRegister(TRC); 9734 unsigned destOut = MRI.createVirtualRegister(TRC); 9735 unsigned scratch = MRI.createVirtualRegister(TRC); 9736 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 9737 IsThumb1, IsThumb2); 9738 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 9739 IsThumb1, IsThumb2); 9740 srcIn = srcOut; 9741 destIn = destOut; 9742 } 9743 MI.eraseFromParent(); // The instruction is gone now. 9744 return BB; 9745 } 9746 9747 // Expand the pseudo op to a loop. 9748 // thisMBB: 9749 // ... 9750 // movw varEnd, # --> with thumb2 9751 // movt varEnd, # 9752 // ldrcp varEnd, idx --> without thumb2 9753 // fallthrough --> loopMBB 9754 // loopMBB: 9755 // PHI varPhi, varEnd, varLoop 9756 // PHI srcPhi, src, srcLoop 9757 // PHI destPhi, dst, destLoop 9758 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9759 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 9760 // subs varLoop, varPhi, #UnitSize 9761 // bne loopMBB 9762 // fallthrough --> exitMBB 9763 // exitMBB: 9764 // epilogue to handle left-over bytes 9765 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9766 // [destOut] = STRB_POST(scratch, destLoop, 1) 9767 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9768 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9769 MF->insert(It, loopMBB); 9770 MF->insert(It, exitMBB); 9771 9772 // Transfer the remainder of BB and its successor edges to exitMBB. 9773 exitMBB->splice(exitMBB->begin(), BB, 9774 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9775 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9776 9777 // Load an immediate to varEnd. 9778 unsigned varEnd = MRI.createVirtualRegister(TRC); 9779 if (Subtarget->useMovt()) { 9780 unsigned Vtmp = varEnd; 9781 if ((LoopSize & 0xFFFF0000) != 0) 9782 Vtmp = MRI.createVirtualRegister(TRC); 9783 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 9784 .addImm(LoopSize & 0xFFFF) 9785 .add(predOps(ARMCC::AL)); 9786 9787 if ((LoopSize & 0xFFFF0000) != 0) 9788 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9789 .addReg(Vtmp) 9790 .addImm(LoopSize >> 16) 9791 .add(predOps(ARMCC::AL)); 9792 } else { 9793 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9794 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9795 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9796 9797 // MachineConstantPool wants an explicit alignment. 9798 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9799 if (Align == 0) 9800 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9801 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9802 MachineMemOperand *CPMMO = 9803 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9804 MachineMemOperand::MOLoad, 4, 4); 9805 9806 if (IsThumb) 9807 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9808 .addReg(varEnd, RegState::Define) 9809 .addConstantPoolIndex(Idx) 9810 .add(predOps(ARMCC::AL)) 9811 .addMemOperand(CPMMO); 9812 else 9813 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9814 .addReg(varEnd, RegState::Define) 9815 .addConstantPoolIndex(Idx) 9816 .addImm(0) 9817 .add(predOps(ARMCC::AL)) 9818 .addMemOperand(CPMMO); 9819 } 9820 BB->addSuccessor(loopMBB); 9821 9822 // Generate the loop body: 9823 // varPhi = PHI(varLoop, varEnd) 9824 // srcPhi = PHI(srcLoop, src) 9825 // destPhi = PHI(destLoop, dst) 9826 MachineBasicBlock *entryBB = BB; 9827 BB = loopMBB; 9828 unsigned varLoop = MRI.createVirtualRegister(TRC); 9829 unsigned varPhi = MRI.createVirtualRegister(TRC); 9830 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9831 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9832 unsigned destLoop = MRI.createVirtualRegister(TRC); 9833 unsigned destPhi = MRI.createVirtualRegister(TRC); 9834 9835 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9836 .addReg(varLoop).addMBB(loopMBB) 9837 .addReg(varEnd).addMBB(entryBB); 9838 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9839 .addReg(srcLoop).addMBB(loopMBB) 9840 .addReg(src).addMBB(entryBB); 9841 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9842 .addReg(destLoop).addMBB(loopMBB) 9843 .addReg(dest).addMBB(entryBB); 9844 9845 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9846 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9847 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9848 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9849 IsThumb1, IsThumb2); 9850 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9851 IsThumb1, IsThumb2); 9852 9853 // Decrement loop variable by UnitSize. 9854 if (IsThumb1) { 9855 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9856 .add(t1CondCodeOp()) 9857 .addReg(varPhi) 9858 .addImm(UnitSize) 9859 .add(predOps(ARMCC::AL)); 9860 } else { 9861 MachineInstrBuilder MIB = 9862 BuildMI(*BB, BB->end(), dl, 9863 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9864 MIB.addReg(varPhi) 9865 .addImm(UnitSize) 9866 .add(predOps(ARMCC::AL)) 9867 .add(condCodeOp()); 9868 MIB->getOperand(5).setReg(ARM::CPSR); 9869 MIB->getOperand(5).setIsDef(true); 9870 } 9871 BuildMI(*BB, BB->end(), dl, 9872 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9873 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9874 9875 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9876 BB->addSuccessor(loopMBB); 9877 BB->addSuccessor(exitMBB); 9878 9879 // Add epilogue to handle BytesLeft. 9880 BB = exitMBB; 9881 auto StartOfExit = exitMBB->begin(); 9882 9883 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9884 // [destOut] = STRB_POST(scratch, destLoop, 1) 9885 unsigned srcIn = srcLoop; 9886 unsigned destIn = destLoop; 9887 for (unsigned i = 0; i < BytesLeft; i++) { 9888 unsigned srcOut = MRI.createVirtualRegister(TRC); 9889 unsigned destOut = MRI.createVirtualRegister(TRC); 9890 unsigned scratch = MRI.createVirtualRegister(TRC); 9891 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9892 IsThumb1, IsThumb2); 9893 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9894 IsThumb1, IsThumb2); 9895 srcIn = srcOut; 9896 destIn = destOut; 9897 } 9898 9899 MI.eraseFromParent(); // The instruction is gone now. 9900 return BB; 9901 } 9902 9903 MachineBasicBlock * 9904 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9905 MachineBasicBlock *MBB) const { 9906 const TargetMachine &TM = getTargetMachine(); 9907 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9908 DebugLoc DL = MI.getDebugLoc(); 9909 9910 assert(Subtarget->isTargetWindows() && 9911 "__chkstk is only supported on Windows"); 9912 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9913 9914 // __chkstk takes the number of words to allocate on the stack in R4, and 9915 // returns the stack adjustment in number of bytes in R4. This will not 9916 // clober any other registers (other than the obvious lr). 9917 // 9918 // Although, technically, IP should be considered a register which may be 9919 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9920 // thumb-2 environment, so there is no interworking required. As a result, we 9921 // do not expect a veneer to be emitted by the linker, clobbering IP. 9922 // 9923 // Each module receives its own copy of __chkstk, so no import thunk is 9924 // required, again, ensuring that IP is not clobbered. 9925 // 9926 // Finally, although some linkers may theoretically provide a trampoline for 9927 // out of range calls (which is quite common due to a 32M range limitation of 9928 // branches for Thumb), we can generate the long-call version via 9929 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9930 // IP. 9931 9932 switch (TM.getCodeModel()) { 9933 case CodeModel::Tiny: 9934 llvm_unreachable("Tiny code model not available on ARM."); 9935 case CodeModel::Small: 9936 case CodeModel::Medium: 9937 case CodeModel::Kernel: 9938 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9939 .add(predOps(ARMCC::AL)) 9940 .addExternalSymbol("__chkstk") 9941 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9942 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9943 .addReg(ARM::R12, 9944 RegState::Implicit | RegState::Define | RegState::Dead) 9945 .addReg(ARM::CPSR, 9946 RegState::Implicit | RegState::Define | RegState::Dead); 9947 break; 9948 case CodeModel::Large: { 9949 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9950 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9951 9952 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9953 .addExternalSymbol("__chkstk"); 9954 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9955 .add(predOps(ARMCC::AL)) 9956 .addReg(Reg, RegState::Kill) 9957 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9958 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9959 .addReg(ARM::R12, 9960 RegState::Implicit | RegState::Define | RegState::Dead) 9961 .addReg(ARM::CPSR, 9962 RegState::Implicit | RegState::Define | RegState::Dead); 9963 break; 9964 } 9965 } 9966 9967 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9968 .addReg(ARM::SP, RegState::Kill) 9969 .addReg(ARM::R4, RegState::Kill) 9970 .setMIFlags(MachineInstr::FrameSetup) 9971 .add(predOps(ARMCC::AL)) 9972 .add(condCodeOp()); 9973 9974 MI.eraseFromParent(); 9975 return MBB; 9976 } 9977 9978 MachineBasicBlock * 9979 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9980 MachineBasicBlock *MBB) const { 9981 DebugLoc DL = MI.getDebugLoc(); 9982 MachineFunction *MF = MBB->getParent(); 9983 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9984 9985 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9986 MF->insert(++MBB->getIterator(), ContBB); 9987 ContBB->splice(ContBB->begin(), MBB, 9988 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9989 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9990 MBB->addSuccessor(ContBB); 9991 9992 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9993 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9994 MF->push_back(TrapBB); 9995 MBB->addSuccessor(TrapBB); 9996 9997 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9998 .addReg(MI.getOperand(0).getReg()) 9999 .addImm(0) 10000 .add(predOps(ARMCC::AL)); 10001 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 10002 .addMBB(TrapBB) 10003 .addImm(ARMCC::EQ) 10004 .addReg(ARM::CPSR); 10005 10006 MI.eraseFromParent(); 10007 return ContBB; 10008 } 10009 10010 // The CPSR operand of SelectItr might be missing a kill marker 10011 // because there were multiple uses of CPSR, and ISel didn't know 10012 // which to mark. Figure out whether SelectItr should have had a 10013 // kill marker, and set it if it should. Returns the correct kill 10014 // marker value. 10015 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 10016 MachineBasicBlock* BB, 10017 const TargetRegisterInfo* TRI) { 10018 // Scan forward through BB for a use/def of CPSR. 10019 MachineBasicBlock::iterator miI(std::next(SelectItr)); 10020 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 10021 const MachineInstr& mi = *miI; 10022 if (mi.readsRegister(ARM::CPSR)) 10023 return false; 10024 if (mi.definesRegister(ARM::CPSR)) 10025 break; // Should have kill-flag - update below. 10026 } 10027 10028 // If we hit the end of the block, check whether CPSR is live into a 10029 // successor. 10030 if (miI == BB->end()) { 10031 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10032 sEnd = BB->succ_end(); 10033 sItr != sEnd; ++sItr) { 10034 MachineBasicBlock* succ = *sItr; 10035 if (succ->isLiveIn(ARM::CPSR)) 10036 return false; 10037 } 10038 } 10039 10040 // We found a def, or hit the end of the basic block and CPSR wasn't live 10041 // out. SelectMI should have a kill flag on CPSR. 10042 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10043 return true; 10044 } 10045 10046 MachineBasicBlock * 10047 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10048 MachineBasicBlock *BB) const { 10049 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10050 DebugLoc dl = MI.getDebugLoc(); 10051 bool isThumb2 = Subtarget->isThumb2(); 10052 switch (MI.getOpcode()) { 10053 default: { 10054 MI.print(errs()); 10055 llvm_unreachable("Unexpected instr type to insert"); 10056 } 10057 10058 // Thumb1 post-indexed loads are really just single-register LDMs. 10059 case ARM::tLDR_postidx: { 10060 MachineOperand Def(MI.getOperand(1)); 10061 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 10062 .add(Def) // Rn_wb 10063 .add(MI.getOperand(2)) // Rn 10064 .add(MI.getOperand(3)) // PredImm 10065 .add(MI.getOperand(4)) // PredReg 10066 .add(MI.getOperand(0)) // Rt 10067 .cloneMemRefs(MI); 10068 MI.eraseFromParent(); 10069 return BB; 10070 } 10071 10072 // The Thumb2 pre-indexed stores have the same MI operands, they just 10073 // define them differently in the .td files from the isel patterns, so 10074 // they need pseudos. 10075 case ARM::t2STR_preidx: 10076 MI.setDesc(TII->get(ARM::t2STR_PRE)); 10077 return BB; 10078 case ARM::t2STRB_preidx: 10079 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 10080 return BB; 10081 case ARM::t2STRH_preidx: 10082 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 10083 return BB; 10084 10085 case ARM::STRi_preidx: 10086 case ARM::STRBi_preidx: { 10087 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 10088 : ARM::STRB_PRE_IMM; 10089 // Decode the offset. 10090 unsigned Offset = MI.getOperand(4).getImm(); 10091 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 10092 Offset = ARM_AM::getAM2Offset(Offset); 10093 if (isSub) 10094 Offset = -Offset; 10095 10096 MachineMemOperand *MMO = *MI.memoperands_begin(); 10097 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 10098 .add(MI.getOperand(0)) // Rn_wb 10099 .add(MI.getOperand(1)) // Rt 10100 .add(MI.getOperand(2)) // Rn 10101 .addImm(Offset) // offset (skip GPR==zero_reg) 10102 .add(MI.getOperand(5)) // pred 10103 .add(MI.getOperand(6)) 10104 .addMemOperand(MMO); 10105 MI.eraseFromParent(); 10106 return BB; 10107 } 10108 case ARM::STRr_preidx: 10109 case ARM::STRBr_preidx: 10110 case ARM::STRH_preidx: { 10111 unsigned NewOpc; 10112 switch (MI.getOpcode()) { 10113 default: llvm_unreachable("unexpected opcode!"); 10114 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 10115 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 10116 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 10117 } 10118 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 10119 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 10120 MIB.add(MI.getOperand(i)); 10121 MI.eraseFromParent(); 10122 return BB; 10123 } 10124 10125 case ARM::tMOVCCr_pseudo: { 10126 // To "insert" a SELECT_CC instruction, we actually have to insert the 10127 // diamond control-flow pattern. The incoming instruction knows the 10128 // destination vreg to set, the condition code register to branch on, the 10129 // true/false values to select between, and a branch opcode to use. 10130 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10131 MachineFunction::iterator It = ++BB->getIterator(); 10132 10133 // thisMBB: 10134 // ... 10135 // TrueVal = ... 10136 // cmpTY ccX, r1, r2 10137 // bCC copy1MBB 10138 // fallthrough --> copy0MBB 10139 MachineBasicBlock *thisMBB = BB; 10140 MachineFunction *F = BB->getParent(); 10141 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10142 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10143 F->insert(It, copy0MBB); 10144 F->insert(It, sinkMBB); 10145 10146 // Check whether CPSR is live past the tMOVCCr_pseudo. 10147 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10148 if (!MI.killsRegister(ARM::CPSR) && 10149 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 10150 copy0MBB->addLiveIn(ARM::CPSR); 10151 sinkMBB->addLiveIn(ARM::CPSR); 10152 } 10153 10154 // Transfer the remainder of BB and its successor edges to sinkMBB. 10155 sinkMBB->splice(sinkMBB->begin(), BB, 10156 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10157 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10158 10159 BB->addSuccessor(copy0MBB); 10160 BB->addSuccessor(sinkMBB); 10161 10162 BuildMI(BB, dl, TII->get(ARM::tBcc)) 10163 .addMBB(sinkMBB) 10164 .addImm(MI.getOperand(3).getImm()) 10165 .addReg(MI.getOperand(4).getReg()); 10166 10167 // copy0MBB: 10168 // %FalseValue = ... 10169 // # fallthrough to sinkMBB 10170 BB = copy0MBB; 10171 10172 // Update machine-CFG edges 10173 BB->addSuccessor(sinkMBB); 10174 10175 // sinkMBB: 10176 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10177 // ... 10178 BB = sinkMBB; 10179 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 10180 .addReg(MI.getOperand(1).getReg()) 10181 .addMBB(copy0MBB) 10182 .addReg(MI.getOperand(2).getReg()) 10183 .addMBB(thisMBB); 10184 10185 MI.eraseFromParent(); // The pseudo instruction is gone now. 10186 return BB; 10187 } 10188 10189 case ARM::BCCi64: 10190 case ARM::BCCZi64: { 10191 // If there is an unconditional branch to the other successor, remove it. 10192 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10193 10194 // Compare both parts that make up the double comparison separately for 10195 // equality. 10196 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 10197 10198 unsigned LHS1 = MI.getOperand(1).getReg(); 10199 unsigned LHS2 = MI.getOperand(2).getReg(); 10200 if (RHSisZero) { 10201 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10202 .addReg(LHS1) 10203 .addImm(0) 10204 .add(predOps(ARMCC::AL)); 10205 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10206 .addReg(LHS2).addImm(0) 10207 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10208 } else { 10209 unsigned RHS1 = MI.getOperand(3).getReg(); 10210 unsigned RHS2 = MI.getOperand(4).getReg(); 10211 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10212 .addReg(LHS1) 10213 .addReg(RHS1) 10214 .add(predOps(ARMCC::AL)); 10215 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10216 .addReg(LHS2).addReg(RHS2) 10217 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10218 } 10219 10220 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 10221 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 10222 if (MI.getOperand(0).getImm() == ARMCC::NE) 10223 std::swap(destMBB, exitMBB); 10224 10225 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10226 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 10227 if (isThumb2) 10228 BuildMI(BB, dl, TII->get(ARM::t2B)) 10229 .addMBB(exitMBB) 10230 .add(predOps(ARMCC::AL)); 10231 else 10232 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 10233 10234 MI.eraseFromParent(); // The pseudo instruction is gone now. 10235 return BB; 10236 } 10237 10238 case ARM::Int_eh_sjlj_setjmp: 10239 case ARM::Int_eh_sjlj_setjmp_nofp: 10240 case ARM::tInt_eh_sjlj_setjmp: 10241 case ARM::t2Int_eh_sjlj_setjmp: 10242 case ARM::t2Int_eh_sjlj_setjmp_nofp: 10243 return BB; 10244 10245 case ARM::Int_eh_sjlj_setup_dispatch: 10246 EmitSjLjDispatchBlock(MI, BB); 10247 return BB; 10248 10249 case ARM::ABS: 10250 case ARM::t2ABS: { 10251 // To insert an ABS instruction, we have to insert the 10252 // diamond control-flow pattern. The incoming instruction knows the 10253 // source vreg to test against 0, the destination vreg to set, 10254 // the condition code register to branch on, the 10255 // true/false values to select between, and a branch opcode to use. 10256 // It transforms 10257 // V1 = ABS V0 10258 // into 10259 // V2 = MOVS V0 10260 // BCC (branch to SinkBB if V0 >= 0) 10261 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 10262 // SinkBB: V1 = PHI(V2, V3) 10263 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10264 MachineFunction::iterator BBI = ++BB->getIterator(); 10265 MachineFunction *Fn = BB->getParent(); 10266 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10267 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10268 Fn->insert(BBI, RSBBB); 10269 Fn->insert(BBI, SinkBB); 10270 10271 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 10272 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 10273 bool ABSSrcKIll = MI.getOperand(1).isKill(); 10274 bool isThumb2 = Subtarget->isThumb2(); 10275 MachineRegisterInfo &MRI = Fn->getRegInfo(); 10276 // In Thumb mode S must not be specified if source register is the SP or 10277 // PC and if destination register is the SP, so restrict register class 10278 unsigned NewRsbDstReg = 10279 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 10280 10281 // Transfer the remainder of BB and its successor edges to sinkMBB. 10282 SinkBB->splice(SinkBB->begin(), BB, 10283 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10284 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 10285 10286 BB->addSuccessor(RSBBB); 10287 BB->addSuccessor(SinkBB); 10288 10289 // fall through to SinkMBB 10290 RSBBB->addSuccessor(SinkBB); 10291 10292 // insert a cmp at the end of BB 10293 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10294 .addReg(ABSSrcReg) 10295 .addImm(0) 10296 .add(predOps(ARMCC::AL)); 10297 10298 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 10299 BuildMI(BB, dl, 10300 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 10301 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 10302 10303 // insert rsbri in RSBBB 10304 // Note: BCC and rsbri will be converted into predicated rsbmi 10305 // by if-conversion pass 10306 BuildMI(*RSBBB, RSBBB->begin(), dl, 10307 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 10308 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 10309 .addImm(0) 10310 .add(predOps(ARMCC::AL)) 10311 .add(condCodeOp()); 10312 10313 // insert PHI in SinkBB, 10314 // reuse ABSDstReg to not change uses of ABS instruction 10315 BuildMI(*SinkBB, SinkBB->begin(), dl, 10316 TII->get(ARM::PHI), ABSDstReg) 10317 .addReg(NewRsbDstReg).addMBB(RSBBB) 10318 .addReg(ABSSrcReg).addMBB(BB); 10319 10320 // remove ABS instruction 10321 MI.eraseFromParent(); 10322 10323 // return last added BB 10324 return SinkBB; 10325 } 10326 case ARM::COPY_STRUCT_BYVAL_I32: 10327 ++NumLoopByVals; 10328 return EmitStructByval(MI, BB); 10329 case ARM::WIN__CHKSTK: 10330 return EmitLowered__chkstk(MI, BB); 10331 case ARM::WIN__DBZCHK: 10332 return EmitLowered__dbzchk(MI, BB); 10333 } 10334 } 10335 10336 /// Attaches vregs to MEMCPY that it will use as scratch registers 10337 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 10338 /// instead of as a custom inserter because we need the use list from the SDNode. 10339 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 10340 MachineInstr &MI, const SDNode *Node) { 10341 bool isThumb1 = Subtarget->isThumb1Only(); 10342 10343 DebugLoc DL = MI.getDebugLoc(); 10344 MachineFunction *MF = MI.getParent()->getParent(); 10345 MachineRegisterInfo &MRI = MF->getRegInfo(); 10346 MachineInstrBuilder MIB(*MF, MI); 10347 10348 // If the new dst/src is unused mark it as dead. 10349 if (!Node->hasAnyUseOfValue(0)) { 10350 MI.getOperand(0).setIsDead(true); 10351 } 10352 if (!Node->hasAnyUseOfValue(1)) { 10353 MI.getOperand(1).setIsDead(true); 10354 } 10355 10356 // The MEMCPY both defines and kills the scratch registers. 10357 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 10358 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 10359 : &ARM::GPRRegClass); 10360 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 10361 } 10362 } 10363 10364 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10365 SDNode *Node) const { 10366 if (MI.getOpcode() == ARM::MEMCPY) { 10367 attachMEMCPYScratchRegs(Subtarget, MI, Node); 10368 return; 10369 } 10370 10371 const MCInstrDesc *MCID = &MI.getDesc(); 10372 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 10373 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 10374 // operand is still set to noreg. If needed, set the optional operand's 10375 // register to CPSR, and remove the redundant implicit def. 10376 // 10377 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 10378 10379 // Rename pseudo opcodes. 10380 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 10381 unsigned ccOutIdx; 10382 if (NewOpc) { 10383 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 10384 MCID = &TII->get(NewOpc); 10385 10386 assert(MCID->getNumOperands() == 10387 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 10388 && "converted opcode should be the same except for cc_out" 10389 " (and, on Thumb1, pred)"); 10390 10391 MI.setDesc(*MCID); 10392 10393 // Add the optional cc_out operand 10394 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 10395 10396 // On Thumb1, move all input operands to the end, then add the predicate 10397 if (Subtarget->isThumb1Only()) { 10398 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 10399 MI.addOperand(MI.getOperand(1)); 10400 MI.RemoveOperand(1); 10401 } 10402 10403 // Restore the ties 10404 for (unsigned i = MI.getNumOperands(); i--;) { 10405 const MachineOperand& op = MI.getOperand(i); 10406 if (op.isReg() && op.isUse()) { 10407 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 10408 if (DefIdx != -1) 10409 MI.tieOperands(DefIdx, i); 10410 } 10411 } 10412 10413 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 10414 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 10415 ccOutIdx = 1; 10416 } else 10417 ccOutIdx = MCID->getNumOperands() - 1; 10418 } else 10419 ccOutIdx = MCID->getNumOperands() - 1; 10420 10421 // Any ARM instruction that sets the 's' bit should specify an optional 10422 // "cc_out" operand in the last operand position. 10423 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 10424 assert(!NewOpc && "Optional cc_out operand required"); 10425 return; 10426 } 10427 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 10428 // since we already have an optional CPSR def. 10429 bool definesCPSR = false; 10430 bool deadCPSR = false; 10431 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 10432 ++i) { 10433 const MachineOperand &MO = MI.getOperand(i); 10434 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 10435 definesCPSR = true; 10436 if (MO.isDead()) 10437 deadCPSR = true; 10438 MI.RemoveOperand(i); 10439 break; 10440 } 10441 } 10442 if (!definesCPSR) { 10443 assert(!NewOpc && "Optional cc_out operand required"); 10444 return; 10445 } 10446 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 10447 if (deadCPSR) { 10448 assert(!MI.getOperand(ccOutIdx).getReg() && 10449 "expect uninitialized optional cc_out operand"); 10450 // Thumb1 instructions must have the S bit even if the CPSR is dead. 10451 if (!Subtarget->isThumb1Only()) 10452 return; 10453 } 10454 10455 // If this instruction was defined with an optional CPSR def and its dag node 10456 // had a live implicit CPSR def, then activate the optional CPSR def. 10457 MachineOperand &MO = MI.getOperand(ccOutIdx); 10458 MO.setReg(ARM::CPSR); 10459 MO.setIsDef(true); 10460 } 10461 10462 //===----------------------------------------------------------------------===// 10463 // ARM Optimization Hooks 10464 //===----------------------------------------------------------------------===// 10465 10466 // Helper function that checks if N is a null or all ones constant. 10467 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 10468 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 10469 } 10470 10471 // Return true if N is conditionally 0 or all ones. 10472 // Detects these expressions where cc is an i1 value: 10473 // 10474 // (select cc 0, y) [AllOnes=0] 10475 // (select cc y, 0) [AllOnes=0] 10476 // (zext cc) [AllOnes=0] 10477 // (sext cc) [AllOnes=0/1] 10478 // (select cc -1, y) [AllOnes=1] 10479 // (select cc y, -1) [AllOnes=1] 10480 // 10481 // Invert is set when N is the null/all ones constant when CC is false. 10482 // OtherOp is set to the alternative value of N. 10483 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 10484 SDValue &CC, bool &Invert, 10485 SDValue &OtherOp, 10486 SelectionDAG &DAG) { 10487 switch (N->getOpcode()) { 10488 default: return false; 10489 case ISD::SELECT: { 10490 CC = N->getOperand(0); 10491 SDValue N1 = N->getOperand(1); 10492 SDValue N2 = N->getOperand(2); 10493 if (isZeroOrAllOnes(N1, AllOnes)) { 10494 Invert = false; 10495 OtherOp = N2; 10496 return true; 10497 } 10498 if (isZeroOrAllOnes(N2, AllOnes)) { 10499 Invert = true; 10500 OtherOp = N1; 10501 return true; 10502 } 10503 return false; 10504 } 10505 case ISD::ZERO_EXTEND: 10506 // (zext cc) can never be the all ones value. 10507 if (AllOnes) 10508 return false; 10509 LLVM_FALLTHROUGH; 10510 case ISD::SIGN_EXTEND: { 10511 SDLoc dl(N); 10512 EVT VT = N->getValueType(0); 10513 CC = N->getOperand(0); 10514 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 10515 return false; 10516 Invert = !AllOnes; 10517 if (AllOnes) 10518 // When looking for an AllOnes constant, N is an sext, and the 'other' 10519 // value is 0. 10520 OtherOp = DAG.getConstant(0, dl, VT); 10521 else if (N->getOpcode() == ISD::ZERO_EXTEND) 10522 // When looking for a 0 constant, N can be zext or sext. 10523 OtherOp = DAG.getConstant(1, dl, VT); 10524 else 10525 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 10526 VT); 10527 return true; 10528 } 10529 } 10530 } 10531 10532 // Combine a constant select operand into its use: 10533 // 10534 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10535 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10536 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 10537 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10538 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10539 // 10540 // The transform is rejected if the select doesn't have a constant operand that 10541 // is null, or all ones when AllOnes is set. 10542 // 10543 // Also recognize sext/zext from i1: 10544 // 10545 // (add (zext cc), x) -> (select cc (add x, 1), x) 10546 // (add (sext cc), x) -> (select cc (add x, -1), x) 10547 // 10548 // These transformations eventually create predicated instructions. 10549 // 10550 // @param N The node to transform. 10551 // @param Slct The N operand that is a select. 10552 // @param OtherOp The other N operand (x above). 10553 // @param DCI Context. 10554 // @param AllOnes Require the select constant to be all ones instead of null. 10555 // @returns The new node, or SDValue() on failure. 10556 static 10557 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 10558 TargetLowering::DAGCombinerInfo &DCI, 10559 bool AllOnes = false) { 10560 SelectionDAG &DAG = DCI.DAG; 10561 EVT VT = N->getValueType(0); 10562 SDValue NonConstantVal; 10563 SDValue CCOp; 10564 bool SwapSelectOps; 10565 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 10566 NonConstantVal, DAG)) 10567 return SDValue(); 10568 10569 // Slct is now know to be the desired identity constant when CC is true. 10570 SDValue TrueVal = OtherOp; 10571 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 10572 OtherOp, NonConstantVal); 10573 // Unless SwapSelectOps says CC should be false. 10574 if (SwapSelectOps) 10575 std::swap(TrueVal, FalseVal); 10576 10577 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 10578 CCOp, TrueVal, FalseVal); 10579 } 10580 10581 // Attempt combineSelectAndUse on each operand of a commutative operator N. 10582 static 10583 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 10584 TargetLowering::DAGCombinerInfo &DCI) { 10585 SDValue N0 = N->getOperand(0); 10586 SDValue N1 = N->getOperand(1); 10587 if (N0.getNode()->hasOneUse()) 10588 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 10589 return Result; 10590 if (N1.getNode()->hasOneUse()) 10591 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 10592 return Result; 10593 return SDValue(); 10594 } 10595 10596 static bool IsVUZPShuffleNode(SDNode *N) { 10597 // VUZP shuffle node. 10598 if (N->getOpcode() == ARMISD::VUZP) 10599 return true; 10600 10601 // "VUZP" on i32 is an alias for VTRN. 10602 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 10603 return true; 10604 10605 return false; 10606 } 10607 10608 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 10609 TargetLowering::DAGCombinerInfo &DCI, 10610 const ARMSubtarget *Subtarget) { 10611 // Look for ADD(VUZP.0, VUZP.1). 10612 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 10613 N0 == N1) 10614 return SDValue(); 10615 10616 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 10617 if (!N->getValueType(0).is64BitVector()) 10618 return SDValue(); 10619 10620 // Generate vpadd. 10621 SelectionDAG &DAG = DCI.DAG; 10622 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10623 SDLoc dl(N); 10624 SDNode *Unzip = N0.getNode(); 10625 EVT VT = N->getValueType(0); 10626 10627 SmallVector<SDValue, 8> Ops; 10628 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 10629 TLI.getPointerTy(DAG.getDataLayout()))); 10630 Ops.push_back(Unzip->getOperand(0)); 10631 Ops.push_back(Unzip->getOperand(1)); 10632 10633 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10634 } 10635 10636 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10637 TargetLowering::DAGCombinerInfo &DCI, 10638 const ARMSubtarget *Subtarget) { 10639 // Check for two extended operands. 10640 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 10641 N1.getOpcode() == ISD::SIGN_EXTEND) && 10642 !(N0.getOpcode() == ISD::ZERO_EXTEND && 10643 N1.getOpcode() == ISD::ZERO_EXTEND)) 10644 return SDValue(); 10645 10646 SDValue N00 = N0.getOperand(0); 10647 SDValue N10 = N1.getOperand(0); 10648 10649 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 10650 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 10651 N00 == N10) 10652 return SDValue(); 10653 10654 // We only recognize Q register paddl here; this can't be reached until 10655 // after type legalization. 10656 if (!N00.getValueType().is64BitVector() || 10657 !N0.getValueType().is128BitVector()) 10658 return SDValue(); 10659 10660 // Generate vpaddl. 10661 SelectionDAG &DAG = DCI.DAG; 10662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10663 SDLoc dl(N); 10664 EVT VT = N->getValueType(0); 10665 10666 SmallVector<SDValue, 8> Ops; 10667 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 10668 unsigned Opcode; 10669 if (N0.getOpcode() == ISD::SIGN_EXTEND) 10670 Opcode = Intrinsic::arm_neon_vpaddls; 10671 else 10672 Opcode = Intrinsic::arm_neon_vpaddlu; 10673 Ops.push_back(DAG.getConstant(Opcode, dl, 10674 TLI.getPointerTy(DAG.getDataLayout()))); 10675 EVT ElemTy = N00.getValueType().getVectorElementType(); 10676 unsigned NumElts = VT.getVectorNumElements(); 10677 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 10678 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 10679 N00.getOperand(0), N00.getOperand(1)); 10680 Ops.push_back(Concat); 10681 10682 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10683 } 10684 10685 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 10686 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 10687 // much easier to match. 10688 static SDValue 10689 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10690 TargetLowering::DAGCombinerInfo &DCI, 10691 const ARMSubtarget *Subtarget) { 10692 // Only perform optimization if after legalize, and if NEON is available. We 10693 // also expected both operands to be BUILD_VECTORs. 10694 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 10695 || N0.getOpcode() != ISD::BUILD_VECTOR 10696 || N1.getOpcode() != ISD::BUILD_VECTOR) 10697 return SDValue(); 10698 10699 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 10700 EVT VT = N->getValueType(0); 10701 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 10702 return SDValue(); 10703 10704 // Check that the vector operands are of the right form. 10705 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 10706 // operands, where N is the size of the formed vector. 10707 // Each EXTRACT_VECTOR should have the same input vector and odd or even 10708 // index such that we have a pair wise add pattern. 10709 10710 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 10711 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10712 return SDValue(); 10713 SDValue Vec = N0->getOperand(0)->getOperand(0); 10714 SDNode *V = Vec.getNode(); 10715 unsigned nextIndex = 0; 10716 10717 // For each operands to the ADD which are BUILD_VECTORs, 10718 // check to see if each of their operands are an EXTRACT_VECTOR with 10719 // the same vector and appropriate index. 10720 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 10721 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 10722 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10723 10724 SDValue ExtVec0 = N0->getOperand(i); 10725 SDValue ExtVec1 = N1->getOperand(i); 10726 10727 // First operand is the vector, verify its the same. 10728 if (V != ExtVec0->getOperand(0).getNode() || 10729 V != ExtVec1->getOperand(0).getNode()) 10730 return SDValue(); 10731 10732 // Second is the constant, verify its correct. 10733 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 10734 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 10735 10736 // For the constant, we want to see all the even or all the odd. 10737 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 10738 || C1->getZExtValue() != nextIndex+1) 10739 return SDValue(); 10740 10741 // Increment index. 10742 nextIndex+=2; 10743 } else 10744 return SDValue(); 10745 } 10746 10747 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 10748 // we're using the entire input vector, otherwise there's a size/legality 10749 // mismatch somewhere. 10750 if (nextIndex != Vec.getValueType().getVectorNumElements() || 10751 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 10752 return SDValue(); 10753 10754 // Create VPADDL node. 10755 SelectionDAG &DAG = DCI.DAG; 10756 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10757 10758 SDLoc dl(N); 10759 10760 // Build operand list. 10761 SmallVector<SDValue, 8> Ops; 10762 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 10763 TLI.getPointerTy(DAG.getDataLayout()))); 10764 10765 // Input is the vector. 10766 Ops.push_back(Vec); 10767 10768 // Get widened type and narrowed type. 10769 MVT widenType; 10770 unsigned numElem = VT.getVectorNumElements(); 10771 10772 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 10773 switch (inputLaneType.getSimpleVT().SimpleTy) { 10774 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 10775 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 10776 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 10777 default: 10778 llvm_unreachable("Invalid vector element type for padd optimization."); 10779 } 10780 10781 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 10782 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 10783 return DAG.getNode(ExtOp, dl, VT, tmp); 10784 } 10785 10786 static SDValue findMUL_LOHI(SDValue V) { 10787 if (V->getOpcode() == ISD::UMUL_LOHI || 10788 V->getOpcode() == ISD::SMUL_LOHI) 10789 return V; 10790 return SDValue(); 10791 } 10792 10793 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 10794 TargetLowering::DAGCombinerInfo &DCI, 10795 const ARMSubtarget *Subtarget) { 10796 if (Subtarget->isThumb()) { 10797 if (!Subtarget->hasDSP()) 10798 return SDValue(); 10799 } else if (!Subtarget->hasV5TEOps()) 10800 return SDValue(); 10801 10802 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 10803 // accumulates the product into a 64-bit value. The 16-bit values will 10804 // be sign extended somehow or SRA'd into 32-bit values 10805 // (addc (adde (mul 16bit, 16bit), lo), hi) 10806 SDValue Mul = AddcNode->getOperand(0); 10807 SDValue Lo = AddcNode->getOperand(1); 10808 if (Mul.getOpcode() != ISD::MUL) { 10809 Lo = AddcNode->getOperand(0); 10810 Mul = AddcNode->getOperand(1); 10811 if (Mul.getOpcode() != ISD::MUL) 10812 return SDValue(); 10813 } 10814 10815 SDValue SRA = AddeNode->getOperand(0); 10816 SDValue Hi = AddeNode->getOperand(1); 10817 if (SRA.getOpcode() != ISD::SRA) { 10818 SRA = AddeNode->getOperand(1); 10819 Hi = AddeNode->getOperand(0); 10820 if (SRA.getOpcode() != ISD::SRA) 10821 return SDValue(); 10822 } 10823 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10824 if (Const->getZExtValue() != 31) 10825 return SDValue(); 10826 } else 10827 return SDValue(); 10828 10829 if (SRA.getOperand(0) != Mul) 10830 return SDValue(); 10831 10832 SelectionDAG &DAG = DCI.DAG; 10833 SDLoc dl(AddcNode); 10834 unsigned Opcode = 0; 10835 SDValue Op0; 10836 SDValue Op1; 10837 10838 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10839 Opcode = ARMISD::SMLALBB; 10840 Op0 = Mul.getOperand(0); 10841 Op1 = Mul.getOperand(1); 10842 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10843 Opcode = ARMISD::SMLALBT; 10844 Op0 = Mul.getOperand(0); 10845 Op1 = Mul.getOperand(1).getOperand(0); 10846 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10847 Opcode = ARMISD::SMLALTB; 10848 Op0 = Mul.getOperand(0).getOperand(0); 10849 Op1 = Mul.getOperand(1); 10850 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10851 Opcode = ARMISD::SMLALTT; 10852 Op0 = Mul->getOperand(0).getOperand(0); 10853 Op1 = Mul->getOperand(1).getOperand(0); 10854 } 10855 10856 if (!Op0 || !Op1) 10857 return SDValue(); 10858 10859 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10860 Op0, Op1, Lo, Hi); 10861 // Replace the ADDs' nodes uses by the MLA node's values. 10862 SDValue HiMLALResult(SMLAL.getNode(), 1); 10863 SDValue LoMLALResult(SMLAL.getNode(), 0); 10864 10865 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10866 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10867 10868 // Return original node to notify the driver to stop replacing. 10869 SDValue resNode(AddcNode, 0); 10870 return resNode; 10871 } 10872 10873 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10874 TargetLowering::DAGCombinerInfo &DCI, 10875 const ARMSubtarget *Subtarget) { 10876 // Look for multiply add opportunities. 10877 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10878 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10879 // a glue link from the first add to the second add. 10880 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10881 // a S/UMLAL instruction. 10882 // UMUL_LOHI 10883 // / :lo \ :hi 10884 // V \ [no multiline comment] 10885 // loAdd -> ADDC | 10886 // \ :carry / 10887 // V V 10888 // ADDE <- hiAdd 10889 // 10890 // In the special case where only the higher part of a signed result is used 10891 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10892 // a constant with the exact value of 0x80000000, we recognize we are dealing 10893 // with a "rounded multiply and add" (or subtract) and transform it into 10894 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10895 10896 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10897 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10898 "Expect an ADDE or SUBE"); 10899 10900 assert(AddeSubeNode->getNumOperands() == 3 && 10901 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10902 "ADDE node has the wrong inputs"); 10903 10904 // Check that we are chained to the right ADDC or SUBC node. 10905 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10906 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10907 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10908 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10909 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10910 return SDValue(); 10911 10912 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10913 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10914 10915 // Check if the two operands are from the same mul_lohi node. 10916 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10917 return SDValue(); 10918 10919 assert(AddcSubcNode->getNumValues() == 2 && 10920 AddcSubcNode->getValueType(0) == MVT::i32 && 10921 "Expect ADDC with two result values. First: i32"); 10922 10923 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10924 // maybe a SMLAL which multiplies two 16-bit values. 10925 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10926 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10927 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10928 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10929 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10930 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10931 10932 // Check for the triangle shape. 10933 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10934 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10935 10936 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10937 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10938 return SDValue(); 10939 10940 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10941 bool IsLeftOperandMUL = false; 10942 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10943 if (MULOp == SDValue()) 10944 MULOp = findMUL_LOHI(AddeSubeOp1); 10945 else 10946 IsLeftOperandMUL = true; 10947 if (MULOp == SDValue()) 10948 return SDValue(); 10949 10950 // Figure out the right opcode. 10951 unsigned Opc = MULOp->getOpcode(); 10952 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10953 10954 // Figure out the high and low input values to the MLAL node. 10955 SDValue *HiAddSub = nullptr; 10956 SDValue *LoMul = nullptr; 10957 SDValue *LowAddSub = nullptr; 10958 10959 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10960 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10961 return SDValue(); 10962 10963 if (IsLeftOperandMUL) 10964 HiAddSub = &AddeSubeOp1; 10965 else 10966 HiAddSub = &AddeSubeOp0; 10967 10968 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10969 // whose low result is fed to the ADDC/SUBC we are checking. 10970 10971 if (AddcSubcOp0 == MULOp.getValue(0)) { 10972 LoMul = &AddcSubcOp0; 10973 LowAddSub = &AddcSubcOp1; 10974 } 10975 if (AddcSubcOp1 == MULOp.getValue(0)) { 10976 LoMul = &AddcSubcOp1; 10977 LowAddSub = &AddcSubcOp0; 10978 } 10979 10980 if (!LoMul) 10981 return SDValue(); 10982 10983 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10984 // the replacement below will create a cycle. 10985 if (AddcSubcNode == HiAddSub->getNode() || 10986 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10987 return SDValue(); 10988 10989 // Create the merged node. 10990 SelectionDAG &DAG = DCI.DAG; 10991 10992 // Start building operand list. 10993 SmallVector<SDValue, 8> Ops; 10994 Ops.push_back(LoMul->getOperand(0)); 10995 Ops.push_back(LoMul->getOperand(1)); 10996 10997 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10998 // the case, we must be doing signed multiplication and only use the higher 10999 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 11000 // addition or subtraction with the value of 0x800000. 11001 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 11002 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 11003 LowAddSub->getNode()->getOpcode() == ISD::Constant && 11004 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 11005 0x80000000) { 11006 Ops.push_back(*HiAddSub); 11007 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 11008 FinalOpc = ARMISD::SMMLSR; 11009 } else { 11010 FinalOpc = ARMISD::SMMLAR; 11011 } 11012 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 11013 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 11014 11015 return SDValue(AddeSubeNode, 0); 11016 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 11017 // SMMLS is generated during instruction selection and the rest of this 11018 // function can not handle the case where AddcSubcNode is a SUBC. 11019 return SDValue(); 11020 11021 // Finish building the operand list for {U/S}MLAL 11022 Ops.push_back(*LowAddSub); 11023 Ops.push_back(*HiAddSub); 11024 11025 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11026 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11027 11028 // Replace the ADDs' nodes uses by the MLA node's values. 11029 SDValue HiMLALResult(MLALNode.getNode(), 1); 11030 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11031 11032 SDValue LoMLALResult(MLALNode.getNode(), 0); 11033 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11034 11035 // Return original node to notify the driver to stop replacing. 11036 return SDValue(AddeSubeNode, 0); 11037 } 11038 11039 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11040 TargetLowering::DAGCombinerInfo &DCI, 11041 const ARMSubtarget *Subtarget) { 11042 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11043 // While trying to combine for the other MLAL nodes, first search for the 11044 // chance to use UMAAL. Check if Addc uses a node which has already 11045 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11046 // as the addend, and it's handled in PerformUMLALCombine. 11047 11048 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11049 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11050 11051 // Check that we have a glued ADDC node. 11052 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11053 if (AddcNode->getOpcode() != ARMISD::ADDC) 11054 return SDValue(); 11055 11056 // Find the converted UMAAL or quit if it doesn't exist. 11057 SDNode *UmlalNode = nullptr; 11058 SDValue AddHi; 11059 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11060 UmlalNode = AddcNode->getOperand(0).getNode(); 11061 AddHi = AddcNode->getOperand(1); 11062 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 11063 UmlalNode = AddcNode->getOperand(1).getNode(); 11064 AddHi = AddcNode->getOperand(0); 11065 } else { 11066 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11067 } 11068 11069 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 11070 // the ADDC as well as Zero. 11071 if (!isNullConstant(UmlalNode->getOperand(3))) 11072 return SDValue(); 11073 11074 if ((isNullConstant(AddeNode->getOperand(0)) && 11075 AddeNode->getOperand(1).getNode() == UmlalNode) || 11076 (AddeNode->getOperand(0).getNode() == UmlalNode && 11077 isNullConstant(AddeNode->getOperand(1)))) { 11078 SelectionDAG &DAG = DCI.DAG; 11079 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 11080 UmlalNode->getOperand(2), AddHi }; 11081 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 11082 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11083 11084 // Replace the ADDs' nodes uses by the UMAAL node's values. 11085 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 11086 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 11087 11088 // Return original node to notify the driver to stop replacing. 11089 return SDValue(AddeNode, 0); 11090 } 11091 return SDValue(); 11092 } 11093 11094 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 11095 const ARMSubtarget *Subtarget) { 11096 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11097 return SDValue(); 11098 11099 // Check that we have a pair of ADDC and ADDE as operands. 11100 // Both addends of the ADDE must be zero. 11101 SDNode* AddcNode = N->getOperand(2).getNode(); 11102 SDNode* AddeNode = N->getOperand(3).getNode(); 11103 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 11104 (AddeNode->getOpcode() == ARMISD::ADDE) && 11105 isNullConstant(AddeNode->getOperand(0)) && 11106 isNullConstant(AddeNode->getOperand(1)) && 11107 (AddeNode->getOperand(2).getNode() == AddcNode)) 11108 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 11109 DAG.getVTList(MVT::i32, MVT::i32), 11110 {N->getOperand(0), N->getOperand(1), 11111 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 11112 else 11113 return SDValue(); 11114 } 11115 11116 static SDValue PerformAddcSubcCombine(SDNode *N, 11117 TargetLowering::DAGCombinerInfo &DCI, 11118 const ARMSubtarget *Subtarget) { 11119 SelectionDAG &DAG(DCI.DAG); 11120 11121 if (N->getOpcode() == ARMISD::SUBC) { 11122 // (SUBC (ADDE 0, 0, C), 1) -> C 11123 SDValue LHS = N->getOperand(0); 11124 SDValue RHS = N->getOperand(1); 11125 if (LHS->getOpcode() == ARMISD::ADDE && 11126 isNullConstant(LHS->getOperand(0)) && 11127 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 11128 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 11129 } 11130 } 11131 11132 if (Subtarget->isThumb1Only()) { 11133 SDValue RHS = N->getOperand(1); 11134 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11135 int32_t imm = C->getSExtValue(); 11136 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 11137 SDLoc DL(N); 11138 RHS = DAG.getConstant(-imm, DL, MVT::i32); 11139 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 11140 : ARMISD::ADDC; 11141 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 11142 } 11143 } 11144 } 11145 11146 return SDValue(); 11147 } 11148 11149 static SDValue PerformAddeSubeCombine(SDNode *N, 11150 TargetLowering::DAGCombinerInfo &DCI, 11151 const ARMSubtarget *Subtarget) { 11152 if (Subtarget->isThumb1Only()) { 11153 SelectionDAG &DAG = DCI.DAG; 11154 SDValue RHS = N->getOperand(1); 11155 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11156 int64_t imm = C->getSExtValue(); 11157 if (imm < 0) { 11158 SDLoc DL(N); 11159 11160 // The with-carry-in form matches bitwise not instead of the negation. 11161 // Effectively, the inverse interpretation of the carry flag already 11162 // accounts for part of the negation. 11163 RHS = DAG.getConstant(~imm, DL, MVT::i32); 11164 11165 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 11166 : ARMISD::ADDE; 11167 return DAG.getNode(Opcode, DL, N->getVTList(), 11168 N->getOperand(0), RHS, N->getOperand(2)); 11169 } 11170 } 11171 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 11172 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 11173 } 11174 return SDValue(); 11175 } 11176 11177 static SDValue PerformABSCombine(SDNode *N, 11178 TargetLowering::DAGCombinerInfo &DCI, 11179 const ARMSubtarget *Subtarget) { 11180 SDValue res; 11181 SelectionDAG &DAG = DCI.DAG; 11182 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11183 11184 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 11185 return SDValue(); 11186 11187 if (!TLI.expandABS(N, res, DAG)) 11188 return SDValue(); 11189 11190 return res; 11191 } 11192 11193 /// PerformADDECombine - Target-specific dag combine transform from 11194 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 11195 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 11196 static SDValue PerformADDECombine(SDNode *N, 11197 TargetLowering::DAGCombinerInfo &DCI, 11198 const ARMSubtarget *Subtarget) { 11199 // Only ARM and Thumb2 support UMLAL/SMLAL. 11200 if (Subtarget->isThumb1Only()) 11201 return PerformAddeSubeCombine(N, DCI, Subtarget); 11202 11203 // Only perform the checks after legalize when the pattern is available. 11204 if (DCI.isBeforeLegalize()) return SDValue(); 11205 11206 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 11207 } 11208 11209 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 11210 /// operands N0 and N1. This is a helper for PerformADDCombine that is 11211 /// called with the default operands, and if that fails, with commuted 11212 /// operands. 11213 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 11214 TargetLowering::DAGCombinerInfo &DCI, 11215 const ARMSubtarget *Subtarget){ 11216 // Attempt to create vpadd for this add. 11217 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 11218 return Result; 11219 11220 // Attempt to create vpaddl for this add. 11221 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 11222 return Result; 11223 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 11224 Subtarget)) 11225 return Result; 11226 11227 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11228 if (N0.getNode()->hasOneUse()) 11229 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 11230 return Result; 11231 return SDValue(); 11232 } 11233 11234 bool 11235 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 11236 CombineLevel Level) const { 11237 if (Level == BeforeLegalizeTypes) 11238 return true; 11239 11240 if (N->getOpcode() != ISD::SHL) 11241 return true; 11242 11243 if (Subtarget->isThumb1Only()) { 11244 // Avoid making expensive immediates by commuting shifts. (This logic 11245 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 11246 // for free.) 11247 if (N->getOpcode() != ISD::SHL) 11248 return true; 11249 SDValue N1 = N->getOperand(0); 11250 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 11251 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 11252 return true; 11253 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 11254 if (Const->getAPIntValue().ult(256)) 11255 return false; 11256 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 11257 Const->getAPIntValue().sgt(-256)) 11258 return false; 11259 } 11260 return true; 11261 } 11262 11263 // Turn off commute-with-shift transform after legalization, so it doesn't 11264 // conflict with PerformSHLSimplify. (We could try to detect when 11265 // PerformSHLSimplify would trigger more precisely, but it isn't 11266 // really necessary.) 11267 return false; 11268 } 11269 11270 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 11271 const SDNode *N, CombineLevel Level) const { 11272 if (!Subtarget->isThumb1Only()) 11273 return true; 11274 11275 if (Level == BeforeLegalizeTypes) 11276 return true; 11277 11278 return false; 11279 } 11280 11281 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 11282 if (!Subtarget->hasNEON()) { 11283 if (Subtarget->isThumb1Only()) 11284 return VT.getScalarSizeInBits() <= 32; 11285 return true; 11286 } 11287 return VT.isScalarInteger(); 11288 } 11289 11290 static SDValue PerformSHLSimplify(SDNode *N, 11291 TargetLowering::DAGCombinerInfo &DCI, 11292 const ARMSubtarget *ST) { 11293 // Allow the generic combiner to identify potential bswaps. 11294 if (DCI.isBeforeLegalize()) 11295 return SDValue(); 11296 11297 // DAG combiner will fold: 11298 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 11299 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 11300 // Other code patterns that can be also be modified have the following form: 11301 // b + ((a << 1) | 510) 11302 // b + ((a << 1) & 510) 11303 // b + ((a << 1) ^ 510) 11304 // b + ((a << 1) + 510) 11305 11306 // Many instructions can perform the shift for free, but it requires both 11307 // the operands to be registers. If c1 << c2 is too large, a mov immediate 11308 // instruction will needed. So, unfold back to the original pattern if: 11309 // - if c1 and c2 are small enough that they don't require mov imms. 11310 // - the user(s) of the node can perform an shl 11311 11312 // No shifted operands for 16-bit instructions. 11313 if (ST->isThumb() && ST->isThumb1Only()) 11314 return SDValue(); 11315 11316 // Check that all the users could perform the shl themselves. 11317 for (auto U : N->uses()) { 11318 switch(U->getOpcode()) { 11319 default: 11320 return SDValue(); 11321 case ISD::SUB: 11322 case ISD::ADD: 11323 case ISD::AND: 11324 case ISD::OR: 11325 case ISD::XOR: 11326 case ISD::SETCC: 11327 case ARMISD::CMP: 11328 // Check that the user isn't already using a constant because there 11329 // aren't any instructions that support an immediate operand and a 11330 // shifted operand. 11331 if (isa<ConstantSDNode>(U->getOperand(0)) || 11332 isa<ConstantSDNode>(U->getOperand(1))) 11333 return SDValue(); 11334 11335 // Check that it's not already using a shift. 11336 if (U->getOperand(0).getOpcode() == ISD::SHL || 11337 U->getOperand(1).getOpcode() == ISD::SHL) 11338 return SDValue(); 11339 break; 11340 } 11341 } 11342 11343 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 11344 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 11345 return SDValue(); 11346 11347 if (N->getOperand(0).getOpcode() != ISD::SHL) 11348 return SDValue(); 11349 11350 SDValue SHL = N->getOperand(0); 11351 11352 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11353 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 11354 if (!C1ShlC2 || !C2) 11355 return SDValue(); 11356 11357 APInt C2Int = C2->getAPIntValue(); 11358 APInt C1Int = C1ShlC2->getAPIntValue(); 11359 11360 // Check that performing a lshr will not lose any information. 11361 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 11362 C2Int.getBitWidth() - C2->getZExtValue()); 11363 if ((C1Int & Mask) != C1Int) 11364 return SDValue(); 11365 11366 // Shift the first constant. 11367 C1Int.lshrInPlace(C2Int); 11368 11369 // The immediates are encoded as an 8-bit value that can be rotated. 11370 auto LargeImm = [](const APInt &Imm) { 11371 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 11372 return Imm.getBitWidth() - Zeros > 8; 11373 }; 11374 11375 if (LargeImm(C1Int) || LargeImm(C2Int)) 11376 return SDValue(); 11377 11378 SelectionDAG &DAG = DCI.DAG; 11379 SDLoc dl(N); 11380 SDValue X = SHL.getOperand(0); 11381 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 11382 DAG.getConstant(C1Int, dl, MVT::i32)); 11383 // Shift left to compensate for the lshr of C1Int. 11384 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 11385 11386 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 11387 SHL.dump(); N->dump()); 11388 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 11389 return Res; 11390 } 11391 11392 11393 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 11394 /// 11395 static SDValue PerformADDCombine(SDNode *N, 11396 TargetLowering::DAGCombinerInfo &DCI, 11397 const ARMSubtarget *Subtarget) { 11398 SDValue N0 = N->getOperand(0); 11399 SDValue N1 = N->getOperand(1); 11400 11401 // Only works one way, because it needs an immediate operand. 11402 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11403 return Result; 11404 11405 // First try with the default operand order. 11406 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 11407 return Result; 11408 11409 // If that didn't work, try again with the operands commuted. 11410 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 11411 } 11412 11413 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 11414 /// 11415 static SDValue PerformSUBCombine(SDNode *N, 11416 TargetLowering::DAGCombinerInfo &DCI) { 11417 SDValue N0 = N->getOperand(0); 11418 SDValue N1 = N->getOperand(1); 11419 11420 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11421 if (N1.getNode()->hasOneUse()) 11422 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 11423 return Result; 11424 11425 return SDValue(); 11426 } 11427 11428 /// PerformVMULCombine 11429 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 11430 /// special multiplier accumulator forwarding. 11431 /// vmul d3, d0, d2 11432 /// vmla d3, d1, d2 11433 /// is faster than 11434 /// vadd d3, d0, d1 11435 /// vmul d3, d3, d2 11436 // However, for (A + B) * (A + B), 11437 // vadd d2, d0, d1 11438 // vmul d3, d0, d2 11439 // vmla d3, d1, d2 11440 // is slower than 11441 // vadd d2, d0, d1 11442 // vmul d3, d2, d2 11443 static SDValue PerformVMULCombine(SDNode *N, 11444 TargetLowering::DAGCombinerInfo &DCI, 11445 const ARMSubtarget *Subtarget) { 11446 if (!Subtarget->hasVMLxForwarding()) 11447 return SDValue(); 11448 11449 SelectionDAG &DAG = DCI.DAG; 11450 SDValue N0 = N->getOperand(0); 11451 SDValue N1 = N->getOperand(1); 11452 unsigned Opcode = N0.getOpcode(); 11453 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11454 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 11455 Opcode = N1.getOpcode(); 11456 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11457 Opcode != ISD::FADD && Opcode != ISD::FSUB) 11458 return SDValue(); 11459 std::swap(N0, N1); 11460 } 11461 11462 if (N0 == N1) 11463 return SDValue(); 11464 11465 EVT VT = N->getValueType(0); 11466 SDLoc DL(N); 11467 SDValue N00 = N0->getOperand(0); 11468 SDValue N01 = N0->getOperand(1); 11469 return DAG.getNode(Opcode, DL, VT, 11470 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 11471 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 11472 } 11473 11474 static SDValue PerformMULCombine(SDNode *N, 11475 TargetLowering::DAGCombinerInfo &DCI, 11476 const ARMSubtarget *Subtarget) { 11477 SelectionDAG &DAG = DCI.DAG; 11478 11479 if (Subtarget->isThumb1Only()) 11480 return SDValue(); 11481 11482 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11483 return SDValue(); 11484 11485 EVT VT = N->getValueType(0); 11486 if (VT.is64BitVector() || VT.is128BitVector()) 11487 return PerformVMULCombine(N, DCI, Subtarget); 11488 if (VT != MVT::i32) 11489 return SDValue(); 11490 11491 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11492 if (!C) 11493 return SDValue(); 11494 11495 int64_t MulAmt = C->getSExtValue(); 11496 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 11497 11498 ShiftAmt = ShiftAmt & (32 - 1); 11499 SDValue V = N->getOperand(0); 11500 SDLoc DL(N); 11501 11502 SDValue Res; 11503 MulAmt >>= ShiftAmt; 11504 11505 if (MulAmt >= 0) { 11506 if (isPowerOf2_32(MulAmt - 1)) { 11507 // (mul x, 2^N + 1) => (add (shl x, N), x) 11508 Res = DAG.getNode(ISD::ADD, DL, VT, 11509 V, 11510 DAG.getNode(ISD::SHL, DL, VT, 11511 V, 11512 DAG.getConstant(Log2_32(MulAmt - 1), DL, 11513 MVT::i32))); 11514 } else if (isPowerOf2_32(MulAmt + 1)) { 11515 // (mul x, 2^N - 1) => (sub (shl x, N), x) 11516 Res = DAG.getNode(ISD::SUB, DL, VT, 11517 DAG.getNode(ISD::SHL, DL, VT, 11518 V, 11519 DAG.getConstant(Log2_32(MulAmt + 1), DL, 11520 MVT::i32)), 11521 V); 11522 } else 11523 return SDValue(); 11524 } else { 11525 uint64_t MulAmtAbs = -MulAmt; 11526 if (isPowerOf2_32(MulAmtAbs + 1)) { 11527 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 11528 Res = DAG.getNode(ISD::SUB, DL, VT, 11529 V, 11530 DAG.getNode(ISD::SHL, DL, VT, 11531 V, 11532 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 11533 MVT::i32))); 11534 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 11535 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 11536 Res = DAG.getNode(ISD::ADD, DL, VT, 11537 V, 11538 DAG.getNode(ISD::SHL, DL, VT, 11539 V, 11540 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 11541 MVT::i32))); 11542 Res = DAG.getNode(ISD::SUB, DL, VT, 11543 DAG.getConstant(0, DL, MVT::i32), Res); 11544 } else 11545 return SDValue(); 11546 } 11547 11548 if (ShiftAmt != 0) 11549 Res = DAG.getNode(ISD::SHL, DL, VT, 11550 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 11551 11552 // Do not add new nodes to DAG combiner worklist. 11553 DCI.CombineTo(N, Res, false); 11554 return SDValue(); 11555 } 11556 11557 static SDValue CombineANDShift(SDNode *N, 11558 TargetLowering::DAGCombinerInfo &DCI, 11559 const ARMSubtarget *Subtarget) { 11560 // Allow DAGCombine to pattern-match before we touch the canonical form. 11561 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11562 return SDValue(); 11563 11564 if (N->getValueType(0) != MVT::i32) 11565 return SDValue(); 11566 11567 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11568 if (!N1C) 11569 return SDValue(); 11570 11571 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 11572 // Don't transform uxtb/uxth. 11573 if (C1 == 255 || C1 == 65535) 11574 return SDValue(); 11575 11576 SDNode *N0 = N->getOperand(0).getNode(); 11577 if (!N0->hasOneUse()) 11578 return SDValue(); 11579 11580 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 11581 return SDValue(); 11582 11583 bool LeftShift = N0->getOpcode() == ISD::SHL; 11584 11585 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 11586 if (!N01C) 11587 return SDValue(); 11588 11589 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 11590 if (!C2 || C2 >= 32) 11591 return SDValue(); 11592 11593 // Clear irrelevant bits in the mask. 11594 if (LeftShift) 11595 C1 &= (-1U << C2); 11596 else 11597 C1 &= (-1U >> C2); 11598 11599 SelectionDAG &DAG = DCI.DAG; 11600 SDLoc DL(N); 11601 11602 // We have a pattern of the form "(and (shl x, c2) c1)" or 11603 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 11604 // transform to a pair of shifts, to save materializing c1. 11605 11606 // First pattern: right shift, then mask off leading bits. 11607 // FIXME: Use demanded bits? 11608 if (!LeftShift && isMask_32(C1)) { 11609 uint32_t C3 = countLeadingZeros(C1); 11610 if (C2 < C3) { 11611 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11612 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11613 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11614 DAG.getConstant(C3, DL, MVT::i32)); 11615 } 11616 } 11617 11618 // First pattern, reversed: left shift, then mask off trailing bits. 11619 if (LeftShift && isMask_32(~C1)) { 11620 uint32_t C3 = countTrailingZeros(C1); 11621 if (C2 < C3) { 11622 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11623 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11624 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11625 DAG.getConstant(C3, DL, MVT::i32)); 11626 } 11627 } 11628 11629 // Second pattern: left shift, then mask off leading bits. 11630 // FIXME: Use demanded bits? 11631 if (LeftShift && isShiftedMask_32(C1)) { 11632 uint32_t Trailing = countTrailingZeros(C1); 11633 uint32_t C3 = countLeadingZeros(C1); 11634 if (Trailing == C2 && C2 + C3 < 32) { 11635 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11636 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11637 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11638 DAG.getConstant(C3, DL, MVT::i32)); 11639 } 11640 } 11641 11642 // Second pattern, reversed: right shift, then mask off trailing bits. 11643 // FIXME: Handle other patterns of known/demanded bits. 11644 if (!LeftShift && isShiftedMask_32(C1)) { 11645 uint32_t Leading = countLeadingZeros(C1); 11646 uint32_t C3 = countTrailingZeros(C1); 11647 if (Leading == C2 && C2 + C3 < 32) { 11648 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11649 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11650 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11651 DAG.getConstant(C3, DL, MVT::i32)); 11652 } 11653 } 11654 11655 // FIXME: Transform "(and (shl x, c2) c1)" -> 11656 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 11657 // c1. 11658 return SDValue(); 11659 } 11660 11661 static SDValue PerformANDCombine(SDNode *N, 11662 TargetLowering::DAGCombinerInfo &DCI, 11663 const ARMSubtarget *Subtarget) { 11664 // Attempt to use immediate-form VBIC 11665 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11666 SDLoc dl(N); 11667 EVT VT = N->getValueType(0); 11668 SelectionDAG &DAG = DCI.DAG; 11669 11670 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11671 return SDValue(); 11672 11673 APInt SplatBits, SplatUndef; 11674 unsigned SplatBitSize; 11675 bool HasAnyUndefs; 11676 if (BVN && Subtarget->hasNEON() && 11677 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11678 if (SplatBitSize <= 64) { 11679 EVT VbicVT; 11680 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 11681 SplatUndef.getZExtValue(), SplatBitSize, 11682 DAG, dl, VbicVT, VT.is128BitVector(), 11683 OtherModImm); 11684 if (Val.getNode()) { 11685 SDValue Input = 11686 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 11687 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 11688 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 11689 } 11690 } 11691 } 11692 11693 if (!Subtarget->isThumb1Only()) { 11694 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 11695 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 11696 return Result; 11697 11698 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11699 return Result; 11700 } 11701 11702 if (Subtarget->isThumb1Only()) 11703 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 11704 return Result; 11705 11706 return SDValue(); 11707 } 11708 11709 // Try combining OR nodes to SMULWB, SMULWT. 11710 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 11711 TargetLowering::DAGCombinerInfo &DCI, 11712 const ARMSubtarget *Subtarget) { 11713 if (!Subtarget->hasV6Ops() || 11714 (Subtarget->isThumb() && 11715 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 11716 return SDValue(); 11717 11718 SDValue SRL = OR->getOperand(0); 11719 SDValue SHL = OR->getOperand(1); 11720 11721 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 11722 SRL = OR->getOperand(1); 11723 SHL = OR->getOperand(0); 11724 } 11725 if (!isSRL16(SRL) || !isSHL16(SHL)) 11726 return SDValue(); 11727 11728 // The first operands to the shifts need to be the two results from the 11729 // same smul_lohi node. 11730 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 11731 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 11732 return SDValue(); 11733 11734 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 11735 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 11736 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 11737 return SDValue(); 11738 11739 // Now we have: 11740 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 11741 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 11742 // For SMUWB the 16-bit value will signed extended somehow. 11743 // For SMULWT only the SRA is required. 11744 // Check both sides of SMUL_LOHI 11745 SDValue OpS16 = SMULLOHI->getOperand(0); 11746 SDValue OpS32 = SMULLOHI->getOperand(1); 11747 11748 SelectionDAG &DAG = DCI.DAG; 11749 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 11750 OpS16 = OpS32; 11751 OpS32 = SMULLOHI->getOperand(0); 11752 } 11753 11754 SDLoc dl(OR); 11755 unsigned Opcode = 0; 11756 if (isS16(OpS16, DAG)) 11757 Opcode = ARMISD::SMULWB; 11758 else if (isSRA16(OpS16)) { 11759 Opcode = ARMISD::SMULWT; 11760 OpS16 = OpS16->getOperand(0); 11761 } 11762 else 11763 return SDValue(); 11764 11765 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 11766 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 11767 return SDValue(OR, 0); 11768 } 11769 11770 static SDValue PerformORCombineToBFI(SDNode *N, 11771 TargetLowering::DAGCombinerInfo &DCI, 11772 const ARMSubtarget *Subtarget) { 11773 // BFI is only available on V6T2+ 11774 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 11775 return SDValue(); 11776 11777 EVT VT = N->getValueType(0); 11778 SDValue N0 = N->getOperand(0); 11779 SDValue N1 = N->getOperand(1); 11780 SelectionDAG &DAG = DCI.DAG; 11781 SDLoc DL(N); 11782 // 1) or (and A, mask), val => ARMbfi A, val, mask 11783 // iff (val & mask) == val 11784 // 11785 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11786 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 11787 // && mask == ~mask2 11788 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 11789 // && ~mask == mask2 11790 // (i.e., copy a bitfield value into another bitfield of the same width) 11791 11792 if (VT != MVT::i32) 11793 return SDValue(); 11794 11795 SDValue N00 = N0.getOperand(0); 11796 11797 // The value and the mask need to be constants so we can verify this is 11798 // actually a bitfield set. If the mask is 0xffff, we can do better 11799 // via a movt instruction, so don't use BFI in that case. 11800 SDValue MaskOp = N0.getOperand(1); 11801 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 11802 if (!MaskC) 11803 return SDValue(); 11804 unsigned Mask = MaskC->getZExtValue(); 11805 if (Mask == 0xffff) 11806 return SDValue(); 11807 SDValue Res; 11808 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 11809 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11810 if (N1C) { 11811 unsigned Val = N1C->getZExtValue(); 11812 if ((Val & ~Mask) != Val) 11813 return SDValue(); 11814 11815 if (ARM::isBitFieldInvertedMask(Mask)) { 11816 Val >>= countTrailingZeros(~Mask); 11817 11818 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 11819 DAG.getConstant(Val, DL, MVT::i32), 11820 DAG.getConstant(Mask, DL, MVT::i32)); 11821 11822 DCI.CombineTo(N, Res, false); 11823 // Return value from the original node to inform the combiner than N is 11824 // now dead. 11825 return SDValue(N, 0); 11826 } 11827 } else if (N1.getOpcode() == ISD::AND) { 11828 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11829 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11830 if (!N11C) 11831 return SDValue(); 11832 unsigned Mask2 = N11C->getZExtValue(); 11833 11834 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 11835 // as is to match. 11836 if (ARM::isBitFieldInvertedMask(Mask) && 11837 (Mask == ~Mask2)) { 11838 // The pack halfword instruction works better for masks that fit it, 11839 // so use that when it's available. 11840 if (Subtarget->hasDSP() && 11841 (Mask == 0xffff || Mask == 0xffff0000)) 11842 return SDValue(); 11843 // 2a 11844 unsigned amt = countTrailingZeros(Mask2); 11845 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 11846 DAG.getConstant(amt, DL, MVT::i32)); 11847 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 11848 DAG.getConstant(Mask, DL, MVT::i32)); 11849 DCI.CombineTo(N, Res, false); 11850 // Return value from the original node to inform the combiner than N is 11851 // now dead. 11852 return SDValue(N, 0); 11853 } else if (ARM::isBitFieldInvertedMask(~Mask) && 11854 (~Mask == Mask2)) { 11855 // The pack halfword instruction works better for masks that fit it, 11856 // so use that when it's available. 11857 if (Subtarget->hasDSP() && 11858 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 11859 return SDValue(); 11860 // 2b 11861 unsigned lsb = countTrailingZeros(Mask); 11862 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 11863 DAG.getConstant(lsb, DL, MVT::i32)); 11864 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 11865 DAG.getConstant(Mask2, DL, MVT::i32)); 11866 DCI.CombineTo(N, Res, false); 11867 // Return value from the original node to inform the combiner than N is 11868 // now dead. 11869 return SDValue(N, 0); 11870 } 11871 } 11872 11873 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 11874 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 11875 ARM::isBitFieldInvertedMask(~Mask)) { 11876 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 11877 // where lsb(mask) == #shamt and masked bits of B are known zero. 11878 SDValue ShAmt = N00.getOperand(1); 11879 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 11880 unsigned LSB = countTrailingZeros(Mask); 11881 if (ShAmtC != LSB) 11882 return SDValue(); 11883 11884 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 11885 DAG.getConstant(~Mask, DL, MVT::i32)); 11886 11887 DCI.CombineTo(N, Res, false); 11888 // Return value from the original node to inform the combiner than N is 11889 // now dead. 11890 return SDValue(N, 0); 11891 } 11892 11893 return SDValue(); 11894 } 11895 11896 static bool isValidMVECond(unsigned CC, bool IsFloat) { 11897 switch (CC) { 11898 case ARMCC::EQ: 11899 case ARMCC::NE: 11900 case ARMCC::LE: 11901 case ARMCC::GT: 11902 case ARMCC::GE: 11903 case ARMCC::LT: 11904 return true; 11905 case ARMCC::HS: 11906 case ARMCC::HI: 11907 return !IsFloat; 11908 default: 11909 return false; 11910 }; 11911 } 11912 11913 static SDValue PerformORCombine_i1(SDNode *N, 11914 TargetLowering::DAGCombinerInfo &DCI, 11915 const ARMSubtarget *Subtarget) { 11916 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 11917 // together with predicates 11918 EVT VT = N->getValueType(0); 11919 SDValue N0 = N->getOperand(0); 11920 SDValue N1 = N->getOperand(1); 11921 11922 ARMCC::CondCodes CondCode0 = ARMCC::AL; 11923 ARMCC::CondCodes CondCode1 = ARMCC::AL; 11924 if (N0->getOpcode() == ARMISD::VCMP) 11925 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2)) 11926 ->getZExtValue(); 11927 else if (N0->getOpcode() == ARMISD::VCMPZ) 11928 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1)) 11929 ->getZExtValue(); 11930 if (N1->getOpcode() == ARMISD::VCMP) 11931 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2)) 11932 ->getZExtValue(); 11933 else if (N1->getOpcode() == ARMISD::VCMPZ) 11934 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1)) 11935 ->getZExtValue(); 11936 11937 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL) 11938 return SDValue(); 11939 11940 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0); 11941 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1); 11942 11943 if (!isValidMVECond(Opposite0, 11944 N0->getOperand(0)->getValueType(0).isFloatingPoint()) || 11945 !isValidMVECond(Opposite1, 11946 N1->getOperand(0)->getValueType(0).isFloatingPoint())) 11947 return SDValue(); 11948 11949 SmallVector<SDValue, 4> Ops0; 11950 Ops0.push_back(N0->getOperand(0)); 11951 if (N0->getOpcode() == ARMISD::VCMP) 11952 Ops0.push_back(N0->getOperand(1)); 11953 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32)); 11954 SmallVector<SDValue, 4> Ops1; 11955 Ops1.push_back(N1->getOperand(0)); 11956 if (N1->getOpcode() == ARMISD::VCMP) 11957 Ops1.push_back(N1->getOperand(1)); 11958 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32)); 11959 11960 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0); 11961 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1); 11962 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1); 11963 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And, 11964 DCI.DAG.getAllOnesConstant(SDLoc(N), VT)); 11965 } 11966 11967 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 11968 static SDValue PerformORCombine(SDNode *N, 11969 TargetLowering::DAGCombinerInfo &DCI, 11970 const ARMSubtarget *Subtarget) { 11971 // Attempt to use immediate-form VORR 11972 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11973 SDLoc dl(N); 11974 EVT VT = N->getValueType(0); 11975 SelectionDAG &DAG = DCI.DAG; 11976 11977 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11978 return SDValue(); 11979 11980 APInt SplatBits, SplatUndef; 11981 unsigned SplatBitSize; 11982 bool HasAnyUndefs; 11983 if (BVN && Subtarget->hasNEON() && 11984 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11985 if (SplatBitSize <= 64) { 11986 EVT VorrVT; 11987 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 11988 SplatUndef.getZExtValue(), SplatBitSize, 11989 DAG, dl, VorrVT, VT.is128BitVector(), 11990 OtherModImm); 11991 if (Val.getNode()) { 11992 SDValue Input = 11993 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 11994 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 11995 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 11996 } 11997 } 11998 } 11999 12000 if (!Subtarget->isThumb1Only()) { 12001 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 12002 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12003 return Result; 12004 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 12005 return Result; 12006 } 12007 12008 SDValue N0 = N->getOperand(0); 12009 SDValue N1 = N->getOperand(1); 12010 12011 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 12012 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 12013 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 12014 12015 // The code below optimizes (or (and X, Y), Z). 12016 // The AND operand needs to have a single user to make these optimizations 12017 // profitable. 12018 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 12019 return SDValue(); 12020 12021 APInt SplatUndef; 12022 unsigned SplatBitSize; 12023 bool HasAnyUndefs; 12024 12025 APInt SplatBits0, SplatBits1; 12026 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 12027 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 12028 // Ensure that the second operand of both ands are constants 12029 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 12030 HasAnyUndefs) && !HasAnyUndefs) { 12031 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 12032 HasAnyUndefs) && !HasAnyUndefs) { 12033 // Ensure that the bit width of the constants are the same and that 12034 // the splat arguments are logical inverses as per the pattern we 12035 // are trying to simplify. 12036 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 12037 SplatBits0 == ~SplatBits1) { 12038 // Canonicalize the vector type to make instruction selection 12039 // simpler. 12040 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 12041 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 12042 N0->getOperand(1), 12043 N0->getOperand(0), 12044 N1->getOperand(0)); 12045 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 12046 } 12047 } 12048 } 12049 } 12050 12051 if (Subtarget->hasMVEIntegerOps() && 12052 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 12053 return PerformORCombine_i1(N, DCI, Subtarget); 12054 12055 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 12056 // reasonable. 12057 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 12058 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 12059 return Res; 12060 } 12061 12062 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12063 return Result; 12064 12065 return SDValue(); 12066 } 12067 12068 static SDValue PerformXORCombine(SDNode *N, 12069 TargetLowering::DAGCombinerInfo &DCI, 12070 const ARMSubtarget *Subtarget) { 12071 EVT VT = N->getValueType(0); 12072 SelectionDAG &DAG = DCI.DAG; 12073 12074 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12075 return SDValue(); 12076 12077 if (!Subtarget->isThumb1Only()) { 12078 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 12079 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12080 return Result; 12081 12082 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12083 return Result; 12084 } 12085 12086 return SDValue(); 12087 } 12088 12089 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 12090 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 12091 // their position in "to" (Rd). 12092 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 12093 assert(N->getOpcode() == ARMISD::BFI); 12094 12095 SDValue From = N->getOperand(1); 12096 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 12097 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 12098 12099 // If the Base came from a SHR #C, we can deduce that it is really testing bit 12100 // #C in the base of the SHR. 12101 if (From->getOpcode() == ISD::SRL && 12102 isa<ConstantSDNode>(From->getOperand(1))) { 12103 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 12104 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 12105 FromMask <<= Shift.getLimitedValue(31); 12106 From = From->getOperand(0); 12107 } 12108 12109 return From; 12110 } 12111 12112 // If A and B contain one contiguous set of bits, does A | B == A . B? 12113 // 12114 // Neither A nor B must be zero. 12115 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 12116 unsigned LastActiveBitInA = A.countTrailingZeros(); 12117 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 12118 return LastActiveBitInA - 1 == FirstActiveBitInB; 12119 } 12120 12121 static SDValue FindBFIToCombineWith(SDNode *N) { 12122 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 12123 // if one exists. 12124 APInt ToMask, FromMask; 12125 SDValue From = ParseBFI(N, ToMask, FromMask); 12126 SDValue To = N->getOperand(0); 12127 12128 // Now check for a compatible BFI to merge with. We can pass through BFIs that 12129 // aren't compatible, but not if they set the same bit in their destination as 12130 // we do (or that of any BFI we're going to combine with). 12131 SDValue V = To; 12132 APInt CombinedToMask = ToMask; 12133 while (V.getOpcode() == ARMISD::BFI) { 12134 APInt NewToMask, NewFromMask; 12135 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 12136 if (NewFrom != From) { 12137 // This BFI has a different base. Keep going. 12138 CombinedToMask |= NewToMask; 12139 V = V.getOperand(0); 12140 continue; 12141 } 12142 12143 // Do the written bits conflict with any we've seen so far? 12144 if ((NewToMask & CombinedToMask).getBoolValue()) 12145 // Conflicting bits - bail out because going further is unsafe. 12146 return SDValue(); 12147 12148 // Are the new bits contiguous when combined with the old bits? 12149 if (BitsProperlyConcatenate(ToMask, NewToMask) && 12150 BitsProperlyConcatenate(FromMask, NewFromMask)) 12151 return V; 12152 if (BitsProperlyConcatenate(NewToMask, ToMask) && 12153 BitsProperlyConcatenate(NewFromMask, FromMask)) 12154 return V; 12155 12156 // We've seen a write to some bits, so track it. 12157 CombinedToMask |= NewToMask; 12158 // Keep going... 12159 V = V.getOperand(0); 12160 } 12161 12162 return SDValue(); 12163 } 12164 12165 static SDValue PerformBFICombine(SDNode *N, 12166 TargetLowering::DAGCombinerInfo &DCI) { 12167 SDValue N1 = N->getOperand(1); 12168 if (N1.getOpcode() == ISD::AND) { 12169 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 12170 // the bits being cleared by the AND are not demanded by the BFI. 12171 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12172 if (!N11C) 12173 return SDValue(); 12174 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12175 unsigned LSB = countTrailingZeros(~InvMask); 12176 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 12177 assert(Width < 12178 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 12179 "undefined behavior"); 12180 unsigned Mask = (1u << Width) - 1; 12181 unsigned Mask2 = N11C->getZExtValue(); 12182 if ((Mask & (~Mask2)) == 0) 12183 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 12184 N->getOperand(0), N1.getOperand(0), 12185 N->getOperand(2)); 12186 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 12187 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 12188 // Keep track of any consecutive bits set that all come from the same base 12189 // value. We can combine these together into a single BFI. 12190 SDValue CombineBFI = FindBFIToCombineWith(N); 12191 if (CombineBFI == SDValue()) 12192 return SDValue(); 12193 12194 // We've found a BFI. 12195 APInt ToMask1, FromMask1; 12196 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 12197 12198 APInt ToMask2, FromMask2; 12199 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 12200 assert(From1 == From2); 12201 (void)From2; 12202 12203 // First, unlink CombineBFI. 12204 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 12205 // Then create a new BFI, combining the two together. 12206 APInt NewFromMask = FromMask1 | FromMask2; 12207 APInt NewToMask = ToMask1 | ToMask2; 12208 12209 EVT VT = N->getValueType(0); 12210 SDLoc dl(N); 12211 12212 if (NewFromMask[0] == 0) 12213 From1 = DCI.DAG.getNode( 12214 ISD::SRL, dl, VT, From1, 12215 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 12216 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 12217 DCI.DAG.getConstant(~NewToMask, dl, VT)); 12218 } 12219 return SDValue(); 12220 } 12221 12222 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 12223 /// ARMISD::VMOVRRD. 12224 static SDValue PerformVMOVRRDCombine(SDNode *N, 12225 TargetLowering::DAGCombinerInfo &DCI, 12226 const ARMSubtarget *Subtarget) { 12227 // vmovrrd(vmovdrr x, y) -> x,y 12228 SDValue InDouble = N->getOperand(0); 12229 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 12230 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 12231 12232 // vmovrrd(load f64) -> (load i32), (load i32) 12233 SDNode *InNode = InDouble.getNode(); 12234 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 12235 InNode->getValueType(0) == MVT::f64 && 12236 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 12237 !cast<LoadSDNode>(InNode)->isVolatile()) { 12238 // TODO: Should this be done for non-FrameIndex operands? 12239 LoadSDNode *LD = cast<LoadSDNode>(InNode); 12240 12241 SelectionDAG &DAG = DCI.DAG; 12242 SDLoc DL(LD); 12243 SDValue BasePtr = LD->getBasePtr(); 12244 SDValue NewLD1 = 12245 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 12246 LD->getAlignment(), LD->getMemOperand()->getFlags()); 12247 12248 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12249 DAG.getConstant(4, DL, MVT::i32)); 12250 12251 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 12252 LD->getPointerInfo().getWithOffset(4), 12253 std::min(4U, LD->getAlignment()), 12254 LD->getMemOperand()->getFlags()); 12255 12256 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 12257 if (DCI.DAG.getDataLayout().isBigEndian()) 12258 std::swap (NewLD1, NewLD2); 12259 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 12260 return Result; 12261 } 12262 12263 return SDValue(); 12264 } 12265 12266 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 12267 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 12268 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 12269 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 12270 SDValue Op0 = N->getOperand(0); 12271 SDValue Op1 = N->getOperand(1); 12272 if (Op0.getOpcode() == ISD::BITCAST) 12273 Op0 = Op0.getOperand(0); 12274 if (Op1.getOpcode() == ISD::BITCAST) 12275 Op1 = Op1.getOperand(0); 12276 if (Op0.getOpcode() == ARMISD::VMOVRRD && 12277 Op0.getNode() == Op1.getNode() && 12278 Op0.getResNo() == 0 && Op1.getResNo() == 1) 12279 return DAG.getNode(ISD::BITCAST, SDLoc(N), 12280 N->getValueType(0), Op0.getOperand(0)); 12281 return SDValue(); 12282 } 12283 12284 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 12285 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 12286 /// i64 vector to have f64 elements, since the value can then be loaded 12287 /// directly into a VFP register. 12288 static bool hasNormalLoadOperand(SDNode *N) { 12289 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 12290 for (unsigned i = 0; i < NumElts; ++i) { 12291 SDNode *Elt = N->getOperand(i).getNode(); 12292 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 12293 return true; 12294 } 12295 return false; 12296 } 12297 12298 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 12299 /// ISD::BUILD_VECTOR. 12300 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 12301 TargetLowering::DAGCombinerInfo &DCI, 12302 const ARMSubtarget *Subtarget) { 12303 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 12304 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 12305 // into a pair of GPRs, which is fine when the value is used as a scalar, 12306 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 12307 SelectionDAG &DAG = DCI.DAG; 12308 if (N->getNumOperands() == 2) 12309 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 12310 return RV; 12311 12312 // Load i64 elements as f64 values so that type legalization does not split 12313 // them up into i32 values. 12314 EVT VT = N->getValueType(0); 12315 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 12316 return SDValue(); 12317 SDLoc dl(N); 12318 SmallVector<SDValue, 8> Ops; 12319 unsigned NumElts = VT.getVectorNumElements(); 12320 for (unsigned i = 0; i < NumElts; ++i) { 12321 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 12322 Ops.push_back(V); 12323 // Make the DAGCombiner fold the bitcast. 12324 DCI.AddToWorklist(V.getNode()); 12325 } 12326 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 12327 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 12328 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12329 } 12330 12331 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 12332 static SDValue 12333 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12334 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 12335 // At that time, we may have inserted bitcasts from integer to float. 12336 // If these bitcasts have survived DAGCombine, change the lowering of this 12337 // BUILD_VECTOR in something more vector friendly, i.e., that does not 12338 // force to use floating point types. 12339 12340 // Make sure we can change the type of the vector. 12341 // This is possible iff: 12342 // 1. The vector is only used in a bitcast to a integer type. I.e., 12343 // 1.1. Vector is used only once. 12344 // 1.2. Use is a bit convert to an integer type. 12345 // 2. The size of its operands are 32-bits (64-bits are not legal). 12346 EVT VT = N->getValueType(0); 12347 EVT EltVT = VT.getVectorElementType(); 12348 12349 // Check 1.1. and 2. 12350 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 12351 return SDValue(); 12352 12353 // By construction, the input type must be float. 12354 assert(EltVT == MVT::f32 && "Unexpected type!"); 12355 12356 // Check 1.2. 12357 SDNode *Use = *N->use_begin(); 12358 if (Use->getOpcode() != ISD::BITCAST || 12359 Use->getValueType(0).isFloatingPoint()) 12360 return SDValue(); 12361 12362 // Check profitability. 12363 // Model is, if more than half of the relevant operands are bitcast from 12364 // i32, turn the build_vector into a sequence of insert_vector_elt. 12365 // Relevant operands are everything that is not statically 12366 // (i.e., at compile time) bitcasted. 12367 unsigned NumOfBitCastedElts = 0; 12368 unsigned NumElts = VT.getVectorNumElements(); 12369 unsigned NumOfRelevantElts = NumElts; 12370 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 12371 SDValue Elt = N->getOperand(Idx); 12372 if (Elt->getOpcode() == ISD::BITCAST) { 12373 // Assume only bit cast to i32 will go away. 12374 if (Elt->getOperand(0).getValueType() == MVT::i32) 12375 ++NumOfBitCastedElts; 12376 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 12377 // Constants are statically casted, thus do not count them as 12378 // relevant operands. 12379 --NumOfRelevantElts; 12380 } 12381 12382 // Check if more than half of the elements require a non-free bitcast. 12383 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 12384 return SDValue(); 12385 12386 SelectionDAG &DAG = DCI.DAG; 12387 // Create the new vector type. 12388 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 12389 // Check if the type is legal. 12390 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12391 if (!TLI.isTypeLegal(VecVT)) 12392 return SDValue(); 12393 12394 // Combine: 12395 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 12396 // => BITCAST INSERT_VECTOR_ELT 12397 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 12398 // (BITCAST EN), N. 12399 SDValue Vec = DAG.getUNDEF(VecVT); 12400 SDLoc dl(N); 12401 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 12402 SDValue V = N->getOperand(Idx); 12403 if (V.isUndef()) 12404 continue; 12405 if (V.getOpcode() == ISD::BITCAST && 12406 V->getOperand(0).getValueType() == MVT::i32) 12407 // Fold obvious case. 12408 V = V.getOperand(0); 12409 else { 12410 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 12411 // Make the DAGCombiner fold the bitcasts. 12412 DCI.AddToWorklist(V.getNode()); 12413 } 12414 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 12415 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 12416 } 12417 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 12418 // Make the DAGCombiner fold the bitcasts. 12419 DCI.AddToWorklist(Vec.getNode()); 12420 return Vec; 12421 } 12422 12423 /// PerformInsertEltCombine - Target-specific dag combine xforms for 12424 /// ISD::INSERT_VECTOR_ELT. 12425 static SDValue PerformInsertEltCombine(SDNode *N, 12426 TargetLowering::DAGCombinerInfo &DCI) { 12427 // Bitcast an i64 load inserted into a vector to f64. 12428 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12429 EVT VT = N->getValueType(0); 12430 SDNode *Elt = N->getOperand(1).getNode(); 12431 if (VT.getVectorElementType() != MVT::i64 || 12432 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 12433 return SDValue(); 12434 12435 SelectionDAG &DAG = DCI.DAG; 12436 SDLoc dl(N); 12437 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12438 VT.getVectorNumElements()); 12439 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 12440 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 12441 // Make the DAGCombiner fold the bitcasts. 12442 DCI.AddToWorklist(Vec.getNode()); 12443 DCI.AddToWorklist(V.getNode()); 12444 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 12445 Vec, V, N->getOperand(2)); 12446 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 12447 } 12448 12449 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 12450 /// ISD::VECTOR_SHUFFLE. 12451 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 12452 // The LLVM shufflevector instruction does not require the shuffle mask 12453 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 12454 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 12455 // operands do not match the mask length, they are extended by concatenating 12456 // them with undef vectors. That is probably the right thing for other 12457 // targets, but for NEON it is better to concatenate two double-register 12458 // size vector operands into a single quad-register size vector. Do that 12459 // transformation here: 12460 // shuffle(concat(v1, undef), concat(v2, undef)) -> 12461 // shuffle(concat(v1, v2), undef) 12462 SDValue Op0 = N->getOperand(0); 12463 SDValue Op1 = N->getOperand(1); 12464 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 12465 Op1.getOpcode() != ISD::CONCAT_VECTORS || 12466 Op0.getNumOperands() != 2 || 12467 Op1.getNumOperands() != 2) 12468 return SDValue(); 12469 SDValue Concat0Op1 = Op0.getOperand(1); 12470 SDValue Concat1Op1 = Op1.getOperand(1); 12471 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 12472 return SDValue(); 12473 // Skip the transformation if any of the types are illegal. 12474 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12475 EVT VT = N->getValueType(0); 12476 if (!TLI.isTypeLegal(VT) || 12477 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 12478 !TLI.isTypeLegal(Concat1Op1.getValueType())) 12479 return SDValue(); 12480 12481 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12482 Op0.getOperand(0), Op1.getOperand(0)); 12483 // Translate the shuffle mask. 12484 SmallVector<int, 16> NewMask; 12485 unsigned NumElts = VT.getVectorNumElements(); 12486 unsigned HalfElts = NumElts/2; 12487 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12488 for (unsigned n = 0; n < NumElts; ++n) { 12489 int MaskElt = SVN->getMaskElt(n); 12490 int NewElt = -1; 12491 if (MaskElt < (int)HalfElts) 12492 NewElt = MaskElt; 12493 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 12494 NewElt = HalfElts + MaskElt - NumElts; 12495 NewMask.push_back(NewElt); 12496 } 12497 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 12498 DAG.getUNDEF(VT), NewMask); 12499 } 12500 12501 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 12502 /// NEON load/store intrinsics, and generic vector load/stores, to merge 12503 /// base address updates. 12504 /// For generic load/stores, the memory type is assumed to be a vector. 12505 /// The caller is assumed to have checked legality. 12506 static SDValue CombineBaseUpdate(SDNode *N, 12507 TargetLowering::DAGCombinerInfo &DCI) { 12508 SelectionDAG &DAG = DCI.DAG; 12509 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 12510 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 12511 const bool isStore = N->getOpcode() == ISD::STORE; 12512 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 12513 SDValue Addr = N->getOperand(AddrOpIdx); 12514 MemSDNode *MemN = cast<MemSDNode>(N); 12515 SDLoc dl(N); 12516 12517 // Search for a use of the address operand that is an increment. 12518 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 12519 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 12520 SDNode *User = *UI; 12521 if (User->getOpcode() != ISD::ADD || 12522 UI.getUse().getResNo() != Addr.getResNo()) 12523 continue; 12524 12525 // Check that the add is independent of the load/store. Otherwise, folding 12526 // it would create a cycle. We can avoid searching through Addr as it's a 12527 // predecessor to both. 12528 SmallPtrSet<const SDNode *, 32> Visited; 12529 SmallVector<const SDNode *, 16> Worklist; 12530 Visited.insert(Addr.getNode()); 12531 Worklist.push_back(N); 12532 Worklist.push_back(User); 12533 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 12534 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 12535 continue; 12536 12537 // Find the new opcode for the updating load/store. 12538 bool isLoadOp = true; 12539 bool isLaneOp = false; 12540 unsigned NewOpc = 0; 12541 unsigned NumVecs = 0; 12542 if (isIntrinsic) { 12543 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 12544 switch (IntNo) { 12545 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 12546 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 12547 NumVecs = 1; break; 12548 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 12549 NumVecs = 2; break; 12550 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 12551 NumVecs = 3; break; 12552 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 12553 NumVecs = 4; break; 12554 case Intrinsic::arm_neon_vld2dup: 12555 case Intrinsic::arm_neon_vld3dup: 12556 case Intrinsic::arm_neon_vld4dup: 12557 // TODO: Support updating VLDxDUP nodes. For now, we just skip 12558 // combining base updates for such intrinsics. 12559 continue; 12560 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 12561 NumVecs = 2; isLaneOp = true; break; 12562 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 12563 NumVecs = 3; isLaneOp = true; break; 12564 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 12565 NumVecs = 4; isLaneOp = true; break; 12566 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 12567 NumVecs = 1; isLoadOp = false; break; 12568 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 12569 NumVecs = 2; isLoadOp = false; break; 12570 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 12571 NumVecs = 3; isLoadOp = false; break; 12572 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 12573 NumVecs = 4; isLoadOp = false; break; 12574 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 12575 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 12576 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 12577 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 12578 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 12579 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 12580 } 12581 } else { 12582 isLaneOp = true; 12583 switch (N->getOpcode()) { 12584 default: llvm_unreachable("unexpected opcode for Neon base update"); 12585 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 12586 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 12587 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 12588 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 12589 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 12590 NumVecs = 1; isLaneOp = false; break; 12591 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 12592 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 12593 } 12594 } 12595 12596 // Find the size of memory referenced by the load/store. 12597 EVT VecTy; 12598 if (isLoadOp) { 12599 VecTy = N->getValueType(0); 12600 } else if (isIntrinsic) { 12601 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 12602 } else { 12603 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 12604 VecTy = N->getOperand(1).getValueType(); 12605 } 12606 12607 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 12608 if (isLaneOp) 12609 NumBytes /= VecTy.getVectorNumElements(); 12610 12611 // If the increment is a constant, it must match the memory ref size. 12612 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 12613 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 12614 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 12615 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 12616 // separate instructions that make it harder to use a non-constant update. 12617 continue; 12618 } 12619 12620 // OK, we found an ADD we can fold into the base update. 12621 // Now, create a _UPD node, taking care of not breaking alignment. 12622 12623 EVT AlignedVecTy = VecTy; 12624 unsigned Alignment = MemN->getAlignment(); 12625 12626 // If this is a less-than-standard-aligned load/store, change the type to 12627 // match the standard alignment. 12628 // The alignment is overlooked when selecting _UPD variants; and it's 12629 // easier to introduce bitcasts here than fix that. 12630 // There are 3 ways to get to this base-update combine: 12631 // - intrinsics: they are assumed to be properly aligned (to the standard 12632 // alignment of the memory type), so we don't need to do anything. 12633 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 12634 // intrinsics, so, likewise, there's nothing to do. 12635 // - generic load/store instructions: the alignment is specified as an 12636 // explicit operand, rather than implicitly as the standard alignment 12637 // of the memory type (like the intrisics). We need to change the 12638 // memory type to match the explicit alignment. That way, we don't 12639 // generate non-standard-aligned ARMISD::VLDx nodes. 12640 if (isa<LSBaseSDNode>(N)) { 12641 if (Alignment == 0) 12642 Alignment = 1; 12643 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 12644 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 12645 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 12646 assert(!isLaneOp && "Unexpected generic load/store lane."); 12647 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 12648 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 12649 } 12650 // Don't set an explicit alignment on regular load/stores that we want 12651 // to transform to VLD/VST 1_UPD nodes. 12652 // This matches the behavior of regular load/stores, which only get an 12653 // explicit alignment if the MMO alignment is larger than the standard 12654 // alignment of the memory type. 12655 // Intrinsics, however, always get an explicit alignment, set to the 12656 // alignment of the MMO. 12657 Alignment = 1; 12658 } 12659 12660 // Create the new updating load/store node. 12661 // First, create an SDVTList for the new updating node's results. 12662 EVT Tys[6]; 12663 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 12664 unsigned n; 12665 for (n = 0; n < NumResultVecs; ++n) 12666 Tys[n] = AlignedVecTy; 12667 Tys[n++] = MVT::i32; 12668 Tys[n] = MVT::Other; 12669 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 12670 12671 // Then, gather the new node's operands. 12672 SmallVector<SDValue, 8> Ops; 12673 Ops.push_back(N->getOperand(0)); // incoming chain 12674 Ops.push_back(N->getOperand(AddrOpIdx)); 12675 Ops.push_back(Inc); 12676 12677 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 12678 // Try to match the intrinsic's signature 12679 Ops.push_back(StN->getValue()); 12680 } else { 12681 // Loads (and of course intrinsics) match the intrinsics' signature, 12682 // so just add all but the alignment operand. 12683 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 12684 Ops.push_back(N->getOperand(i)); 12685 } 12686 12687 // For all node types, the alignment operand is always the last one. 12688 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 12689 12690 // If this is a non-standard-aligned STORE, the penultimate operand is the 12691 // stored value. Bitcast it to the aligned type. 12692 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 12693 SDValue &StVal = Ops[Ops.size()-2]; 12694 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 12695 } 12696 12697 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 12698 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 12699 MemN->getMemOperand()); 12700 12701 // Update the uses. 12702 SmallVector<SDValue, 5> NewResults; 12703 for (unsigned i = 0; i < NumResultVecs; ++i) 12704 NewResults.push_back(SDValue(UpdN.getNode(), i)); 12705 12706 // If this is an non-standard-aligned LOAD, the first result is the loaded 12707 // value. Bitcast it to the expected result type. 12708 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 12709 SDValue &LdVal = NewResults[0]; 12710 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 12711 } 12712 12713 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 12714 DCI.CombineTo(N, NewResults); 12715 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 12716 12717 break; 12718 } 12719 return SDValue(); 12720 } 12721 12722 static SDValue PerformVLDCombine(SDNode *N, 12723 TargetLowering::DAGCombinerInfo &DCI) { 12724 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12725 return SDValue(); 12726 12727 return CombineBaseUpdate(N, DCI); 12728 } 12729 12730 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 12731 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 12732 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 12733 /// return true. 12734 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12735 SelectionDAG &DAG = DCI.DAG; 12736 EVT VT = N->getValueType(0); 12737 // vldN-dup instructions only support 64-bit vectors for N > 1. 12738 if (!VT.is64BitVector()) 12739 return false; 12740 12741 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 12742 SDNode *VLD = N->getOperand(0).getNode(); 12743 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 12744 return false; 12745 unsigned NumVecs = 0; 12746 unsigned NewOpc = 0; 12747 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 12748 if (IntNo == Intrinsic::arm_neon_vld2lane) { 12749 NumVecs = 2; 12750 NewOpc = ARMISD::VLD2DUP; 12751 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 12752 NumVecs = 3; 12753 NewOpc = ARMISD::VLD3DUP; 12754 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 12755 NumVecs = 4; 12756 NewOpc = ARMISD::VLD4DUP; 12757 } else { 12758 return false; 12759 } 12760 12761 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 12762 // numbers match the load. 12763 unsigned VLDLaneNo = 12764 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 12765 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12766 UI != UE; ++UI) { 12767 // Ignore uses of the chain result. 12768 if (UI.getUse().getResNo() == NumVecs) 12769 continue; 12770 SDNode *User = *UI; 12771 if (User->getOpcode() != ARMISD::VDUPLANE || 12772 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 12773 return false; 12774 } 12775 12776 // Create the vldN-dup node. 12777 EVT Tys[5]; 12778 unsigned n; 12779 for (n = 0; n < NumVecs; ++n) 12780 Tys[n] = VT; 12781 Tys[n] = MVT::Other; 12782 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 12783 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 12784 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 12785 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 12786 Ops, VLDMemInt->getMemoryVT(), 12787 VLDMemInt->getMemOperand()); 12788 12789 // Update the uses. 12790 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12791 UI != UE; ++UI) { 12792 unsigned ResNo = UI.getUse().getResNo(); 12793 // Ignore uses of the chain result. 12794 if (ResNo == NumVecs) 12795 continue; 12796 SDNode *User = *UI; 12797 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 12798 } 12799 12800 // Now the vldN-lane intrinsic is dead except for its chain result. 12801 // Update uses of the chain. 12802 std::vector<SDValue> VLDDupResults; 12803 for (unsigned n = 0; n < NumVecs; ++n) 12804 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 12805 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 12806 DCI.CombineTo(VLD, VLDDupResults); 12807 12808 return true; 12809 } 12810 12811 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 12812 /// ARMISD::VDUPLANE. 12813 static SDValue PerformVDUPLANECombine(SDNode *N, 12814 TargetLowering::DAGCombinerInfo &DCI) { 12815 SDValue Op = N->getOperand(0); 12816 12817 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 12818 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 12819 if (CombineVLDDUP(N, DCI)) 12820 return SDValue(N, 0); 12821 12822 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 12823 // redundant. Ignore bit_converts for now; element sizes are checked below. 12824 while (Op.getOpcode() == ISD::BITCAST) 12825 Op = Op.getOperand(0); 12826 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 12827 return SDValue(); 12828 12829 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 12830 unsigned EltSize = Op.getScalarValueSizeInBits(); 12831 // The canonical VMOV for a zero vector uses a 32-bit element size. 12832 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12833 unsigned EltBits; 12834 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 12835 EltSize = 8; 12836 EVT VT = N->getValueType(0); 12837 if (EltSize > VT.getScalarSizeInBits()) 12838 return SDValue(); 12839 12840 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 12841 } 12842 12843 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 12844 static SDValue PerformVDUPCombine(SDNode *N, 12845 TargetLowering::DAGCombinerInfo &DCI, 12846 const ARMSubtarget *Subtarget) { 12847 SelectionDAG &DAG = DCI.DAG; 12848 SDValue Op = N->getOperand(0); 12849 12850 if (!Subtarget->hasNEON()) 12851 return SDValue(); 12852 12853 // Match VDUP(LOAD) -> VLD1DUP. 12854 // We match this pattern here rather than waiting for isel because the 12855 // transform is only legal for unindexed loads. 12856 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 12857 if (LD && Op.hasOneUse() && LD->isUnindexed() && 12858 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 12859 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 12860 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 12861 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 12862 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 12863 Ops, LD->getMemoryVT(), 12864 LD->getMemOperand()); 12865 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 12866 return VLDDup; 12867 } 12868 12869 return SDValue(); 12870 } 12871 12872 static SDValue PerformLOADCombine(SDNode *N, 12873 TargetLowering::DAGCombinerInfo &DCI) { 12874 EVT VT = N->getValueType(0); 12875 12876 // If this is a legal vector load, try to combine it into a VLD1_UPD. 12877 if (ISD::isNormalLoad(N) && VT.isVector() && 12878 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12879 return CombineBaseUpdate(N, DCI); 12880 12881 return SDValue(); 12882 } 12883 12884 /// PerformSTORECombine - Target-specific dag combine xforms for 12885 /// ISD::STORE. 12886 static SDValue PerformSTORECombine(SDNode *N, 12887 TargetLowering::DAGCombinerInfo &DCI) { 12888 StoreSDNode *St = cast<StoreSDNode>(N); 12889 if (St->isVolatile()) 12890 return SDValue(); 12891 12892 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 12893 // pack all of the elements in one place. Next, store to memory in fewer 12894 // chunks. 12895 SDValue StVal = St->getValue(); 12896 EVT VT = StVal.getValueType(); 12897 if (St->isTruncatingStore() && VT.isVector()) { 12898 SelectionDAG &DAG = DCI.DAG; 12899 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12900 EVT StVT = St->getMemoryVT(); 12901 unsigned NumElems = VT.getVectorNumElements(); 12902 assert(StVT != VT && "Cannot truncate to the same type"); 12903 unsigned FromEltSz = VT.getScalarSizeInBits(); 12904 unsigned ToEltSz = StVT.getScalarSizeInBits(); 12905 12906 // From, To sizes and ElemCount must be pow of two 12907 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 12908 12909 // We are going to use the original vector elt for storing. 12910 // Accumulated smaller vector elements must be a multiple of the store size. 12911 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 12912 12913 unsigned SizeRatio = FromEltSz / ToEltSz; 12914 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 12915 12916 // Create a type on which we perform the shuffle. 12917 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 12918 NumElems*SizeRatio); 12919 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 12920 12921 SDLoc DL(St); 12922 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 12923 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 12924 for (unsigned i = 0; i < NumElems; ++i) 12925 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 12926 ? (i + 1) * SizeRatio - 1 12927 : i * SizeRatio; 12928 12929 // Can't shuffle using an illegal type. 12930 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 12931 12932 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 12933 DAG.getUNDEF(WideVec.getValueType()), 12934 ShuffleVec); 12935 // At this point all of the data is stored at the bottom of the 12936 // register. We now need to save it to mem. 12937 12938 // Find the largest store unit 12939 MVT StoreType = MVT::i8; 12940 for (MVT Tp : MVT::integer_valuetypes()) { 12941 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 12942 StoreType = Tp; 12943 } 12944 // Didn't find a legal store type. 12945 if (!TLI.isTypeLegal(StoreType)) 12946 return SDValue(); 12947 12948 // Bitcast the original vector into a vector of store-size units 12949 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 12950 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 12951 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 12952 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 12953 SmallVector<SDValue, 8> Chains; 12954 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 12955 TLI.getPointerTy(DAG.getDataLayout())); 12956 SDValue BasePtr = St->getBasePtr(); 12957 12958 // Perform one or more big stores into memory. 12959 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 12960 for (unsigned I = 0; I < E; I++) { 12961 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 12962 StoreType, ShuffWide, 12963 DAG.getIntPtrConstant(I, DL)); 12964 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 12965 St->getPointerInfo(), St->getAlignment(), 12966 St->getMemOperand()->getFlags()); 12967 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 12968 Increment); 12969 Chains.push_back(Ch); 12970 } 12971 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 12972 } 12973 12974 if (!ISD::isNormalStore(St)) 12975 return SDValue(); 12976 12977 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 12978 // ARM stores of arguments in the same cache line. 12979 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 12980 StVal.getNode()->hasOneUse()) { 12981 SelectionDAG &DAG = DCI.DAG; 12982 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 12983 SDLoc DL(St); 12984 SDValue BasePtr = St->getBasePtr(); 12985 SDValue NewST1 = DAG.getStore( 12986 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 12987 BasePtr, St->getPointerInfo(), St->getAlignment(), 12988 St->getMemOperand()->getFlags()); 12989 12990 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12991 DAG.getConstant(4, DL, MVT::i32)); 12992 return DAG.getStore(NewST1.getValue(0), DL, 12993 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 12994 OffsetPtr, St->getPointerInfo(), 12995 std::min(4U, St->getAlignment() / 2), 12996 St->getMemOperand()->getFlags()); 12997 } 12998 12999 if (StVal.getValueType() == MVT::i64 && 13000 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13001 13002 // Bitcast an i64 store extracted from a vector to f64. 13003 // Otherwise, the i64 value will be legalized to a pair of i32 values. 13004 SelectionDAG &DAG = DCI.DAG; 13005 SDLoc dl(StVal); 13006 SDValue IntVec = StVal.getOperand(0); 13007 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 13008 IntVec.getValueType().getVectorNumElements()); 13009 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 13010 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 13011 Vec, StVal.getOperand(1)); 13012 dl = SDLoc(N); 13013 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 13014 // Make the DAGCombiner fold the bitcasts. 13015 DCI.AddToWorklist(Vec.getNode()); 13016 DCI.AddToWorklist(ExtElt.getNode()); 13017 DCI.AddToWorklist(V.getNode()); 13018 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 13019 St->getPointerInfo(), St->getAlignment(), 13020 St->getMemOperand()->getFlags(), St->getAAInfo()); 13021 } 13022 13023 // If this is a legal vector store, try to combine it into a VST1_UPD. 13024 if (ISD::isNormalStore(N) && VT.isVector() && 13025 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13026 return CombineBaseUpdate(N, DCI); 13027 13028 return SDValue(); 13029 } 13030 13031 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 13032 /// can replace combinations of VMUL and VCVT (floating-point to integer) 13033 /// when the VMUL has a constant operand that is a power of 2. 13034 /// 13035 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13036 /// vmul.f32 d16, d17, d16 13037 /// vcvt.s32.f32 d16, d16 13038 /// becomes: 13039 /// vcvt.s32.f32 d16, d16, #3 13040 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 13041 const ARMSubtarget *Subtarget) { 13042 if (!Subtarget->hasNEON()) 13043 return SDValue(); 13044 13045 SDValue Op = N->getOperand(0); 13046 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 13047 Op.getOpcode() != ISD::FMUL) 13048 return SDValue(); 13049 13050 SDValue ConstVec = Op->getOperand(1); 13051 if (!isa<BuildVectorSDNode>(ConstVec)) 13052 return SDValue(); 13053 13054 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 13055 uint32_t FloatBits = FloatTy.getSizeInBits(); 13056 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 13057 uint32_t IntBits = IntTy.getSizeInBits(); 13058 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13059 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13060 // These instructions only exist converting from f32 to i32. We can handle 13061 // smaller integers by generating an extra truncate, but larger ones would 13062 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13063 // these intructions only support v2i32/v4i32 types. 13064 return SDValue(); 13065 } 13066 13067 BitVector UndefElements; 13068 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13069 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13070 if (C == -1 || C == 0 || C > 32) 13071 return SDValue(); 13072 13073 SDLoc dl(N); 13074 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 13075 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 13076 Intrinsic::arm_neon_vcvtfp2fxu; 13077 SDValue FixConv = DAG.getNode( 13078 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13079 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 13080 DAG.getConstant(C, dl, MVT::i32)); 13081 13082 if (IntBits < FloatBits) 13083 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 13084 13085 return FixConv; 13086 } 13087 13088 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 13089 /// can replace combinations of VCVT (integer to floating-point) and VDIV 13090 /// when the VDIV has a constant operand that is a power of 2. 13091 /// 13092 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13093 /// vcvt.f32.s32 d16, d16 13094 /// vdiv.f32 d16, d17, d16 13095 /// becomes: 13096 /// vcvt.f32.s32 d16, d16, #3 13097 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 13098 const ARMSubtarget *Subtarget) { 13099 if (!Subtarget->hasNEON()) 13100 return SDValue(); 13101 13102 SDValue Op = N->getOperand(0); 13103 unsigned OpOpcode = Op.getNode()->getOpcode(); 13104 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 13105 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 13106 return SDValue(); 13107 13108 SDValue ConstVec = N->getOperand(1); 13109 if (!isa<BuildVectorSDNode>(ConstVec)) 13110 return SDValue(); 13111 13112 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 13113 uint32_t FloatBits = FloatTy.getSizeInBits(); 13114 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 13115 uint32_t IntBits = IntTy.getSizeInBits(); 13116 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13117 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13118 // These instructions only exist converting from i32 to f32. We can handle 13119 // smaller integers by generating an extra extend, but larger ones would 13120 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13121 // these intructions only support v2i32/v4i32 types. 13122 return SDValue(); 13123 } 13124 13125 BitVector UndefElements; 13126 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13127 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13128 if (C == -1 || C == 0 || C > 32) 13129 return SDValue(); 13130 13131 SDLoc dl(N); 13132 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 13133 SDValue ConvInput = Op.getOperand(0); 13134 if (IntBits < FloatBits) 13135 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 13136 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13137 ConvInput); 13138 13139 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 13140 Intrinsic::arm_neon_vcvtfxu2fp; 13141 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 13142 Op.getValueType(), 13143 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 13144 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 13145 } 13146 13147 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 13148 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 13149 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13150 switch (IntNo) { 13151 default: 13152 // Don't do anything for most intrinsics. 13153 break; 13154 13155 // Vector shifts: check for immediate versions and lower them. 13156 // Note: This is done during DAG combining instead of DAG legalizing because 13157 // the build_vectors for 64-bit vector element shift counts are generally 13158 // not legal, and it is hard to see their values after they get legalized to 13159 // loads from a constant pool. 13160 case Intrinsic::arm_neon_vshifts: 13161 case Intrinsic::arm_neon_vshiftu: 13162 case Intrinsic::arm_neon_vrshifts: 13163 case Intrinsic::arm_neon_vrshiftu: 13164 case Intrinsic::arm_neon_vrshiftn: 13165 case Intrinsic::arm_neon_vqshifts: 13166 case Intrinsic::arm_neon_vqshiftu: 13167 case Intrinsic::arm_neon_vqshiftsu: 13168 case Intrinsic::arm_neon_vqshiftns: 13169 case Intrinsic::arm_neon_vqshiftnu: 13170 case Intrinsic::arm_neon_vqshiftnsu: 13171 case Intrinsic::arm_neon_vqrshiftns: 13172 case Intrinsic::arm_neon_vqrshiftnu: 13173 case Intrinsic::arm_neon_vqrshiftnsu: { 13174 EVT VT = N->getOperand(1).getValueType(); 13175 int64_t Cnt; 13176 unsigned VShiftOpc = 0; 13177 13178 switch (IntNo) { 13179 case Intrinsic::arm_neon_vshifts: 13180 case Intrinsic::arm_neon_vshiftu: 13181 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 13182 VShiftOpc = ARMISD::VSHLIMM; 13183 break; 13184 } 13185 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 13186 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 13187 : ARMISD::VSHRuIMM); 13188 break; 13189 } 13190 return SDValue(); 13191 13192 case Intrinsic::arm_neon_vrshifts: 13193 case Intrinsic::arm_neon_vrshiftu: 13194 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 13195 break; 13196 return SDValue(); 13197 13198 case Intrinsic::arm_neon_vqshifts: 13199 case Intrinsic::arm_neon_vqshiftu: 13200 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13201 break; 13202 return SDValue(); 13203 13204 case Intrinsic::arm_neon_vqshiftsu: 13205 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13206 break; 13207 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 13208 13209 case Intrinsic::arm_neon_vrshiftn: 13210 case Intrinsic::arm_neon_vqshiftns: 13211 case Intrinsic::arm_neon_vqshiftnu: 13212 case Intrinsic::arm_neon_vqshiftnsu: 13213 case Intrinsic::arm_neon_vqrshiftns: 13214 case Intrinsic::arm_neon_vqrshiftnu: 13215 case Intrinsic::arm_neon_vqrshiftnsu: 13216 // Narrowing shifts require an immediate right shift. 13217 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 13218 break; 13219 llvm_unreachable("invalid shift count for narrowing vector shift " 13220 "intrinsic"); 13221 13222 default: 13223 llvm_unreachable("unhandled vector shift"); 13224 } 13225 13226 switch (IntNo) { 13227 case Intrinsic::arm_neon_vshifts: 13228 case Intrinsic::arm_neon_vshiftu: 13229 // Opcode already set above. 13230 break; 13231 case Intrinsic::arm_neon_vrshifts: 13232 VShiftOpc = ARMISD::VRSHRsIMM; 13233 break; 13234 case Intrinsic::arm_neon_vrshiftu: 13235 VShiftOpc = ARMISD::VRSHRuIMM; 13236 break; 13237 case Intrinsic::arm_neon_vrshiftn: 13238 VShiftOpc = ARMISD::VRSHRNIMM; 13239 break; 13240 case Intrinsic::arm_neon_vqshifts: 13241 VShiftOpc = ARMISD::VQSHLsIMM; 13242 break; 13243 case Intrinsic::arm_neon_vqshiftu: 13244 VShiftOpc = ARMISD::VQSHLuIMM; 13245 break; 13246 case Intrinsic::arm_neon_vqshiftsu: 13247 VShiftOpc = ARMISD::VQSHLsuIMM; 13248 break; 13249 case Intrinsic::arm_neon_vqshiftns: 13250 VShiftOpc = ARMISD::VQSHRNsIMM; 13251 break; 13252 case Intrinsic::arm_neon_vqshiftnu: 13253 VShiftOpc = ARMISD::VQSHRNuIMM; 13254 break; 13255 case Intrinsic::arm_neon_vqshiftnsu: 13256 VShiftOpc = ARMISD::VQSHRNsuIMM; 13257 break; 13258 case Intrinsic::arm_neon_vqrshiftns: 13259 VShiftOpc = ARMISD::VQRSHRNsIMM; 13260 break; 13261 case Intrinsic::arm_neon_vqrshiftnu: 13262 VShiftOpc = ARMISD::VQRSHRNuIMM; 13263 break; 13264 case Intrinsic::arm_neon_vqrshiftnsu: 13265 VShiftOpc = ARMISD::VQRSHRNsuIMM; 13266 break; 13267 } 13268 13269 SDLoc dl(N); 13270 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 13271 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 13272 } 13273 13274 case Intrinsic::arm_neon_vshiftins: { 13275 EVT VT = N->getOperand(1).getValueType(); 13276 int64_t Cnt; 13277 unsigned VShiftOpc = 0; 13278 13279 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 13280 VShiftOpc = ARMISD::VSLIIMM; 13281 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 13282 VShiftOpc = ARMISD::VSRIIMM; 13283 else { 13284 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 13285 } 13286 13287 SDLoc dl(N); 13288 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 13289 N->getOperand(1), N->getOperand(2), 13290 DAG.getConstant(Cnt, dl, MVT::i32)); 13291 } 13292 13293 case Intrinsic::arm_neon_vqrshifts: 13294 case Intrinsic::arm_neon_vqrshiftu: 13295 // No immediate versions of these to check for. 13296 break; 13297 } 13298 13299 return SDValue(); 13300 } 13301 13302 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 13303 /// lowers them. As with the vector shift intrinsics, this is done during DAG 13304 /// combining instead of DAG legalizing because the build_vectors for 64-bit 13305 /// vector element shift counts are generally not legal, and it is hard to see 13306 /// their values after they get legalized to loads from a constant pool. 13307 static SDValue PerformShiftCombine(SDNode *N, 13308 TargetLowering::DAGCombinerInfo &DCI, 13309 const ARMSubtarget *ST) { 13310 SelectionDAG &DAG = DCI.DAG; 13311 EVT VT = N->getValueType(0); 13312 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 13313 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 13314 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 13315 SDValue N1 = N->getOperand(1); 13316 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 13317 SDValue N0 = N->getOperand(0); 13318 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 13319 DAG.MaskedValueIsZero(N0.getOperand(0), 13320 APInt::getHighBitsSet(32, 16))) 13321 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 13322 } 13323 } 13324 13325 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 13326 N->getOperand(0)->getOpcode() == ISD::AND && 13327 N->getOperand(0)->hasOneUse()) { 13328 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13329 return SDValue(); 13330 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 13331 // usually show up because instcombine prefers to canonicalize it to 13332 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 13333 // out of GEP lowering in some cases. 13334 SDValue N0 = N->getOperand(0); 13335 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13336 if (!ShiftAmtNode) 13337 return SDValue(); 13338 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 13339 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13340 if (!AndMaskNode) 13341 return SDValue(); 13342 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 13343 // Don't transform uxtb/uxth. 13344 if (AndMask == 255 || AndMask == 65535) 13345 return SDValue(); 13346 if (isMask_32(AndMask)) { 13347 uint32_t MaskedBits = countLeadingZeros(AndMask); 13348 if (MaskedBits > ShiftAmt) { 13349 SDLoc DL(N); 13350 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 13351 DAG.getConstant(MaskedBits, DL, MVT::i32)); 13352 return DAG.getNode( 13353 ISD::SRL, DL, MVT::i32, SHL, 13354 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 13355 } 13356 } 13357 } 13358 13359 // Nothing to be done for scalar shifts. 13360 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13361 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 13362 return SDValue(); 13363 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 13364 return SDValue(); 13365 13366 int64_t Cnt; 13367 13368 switch (N->getOpcode()) { 13369 default: llvm_unreachable("unexpected shift opcode"); 13370 13371 case ISD::SHL: 13372 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 13373 SDLoc dl(N); 13374 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 13375 DAG.getConstant(Cnt, dl, MVT::i32)); 13376 } 13377 break; 13378 13379 case ISD::SRA: 13380 case ISD::SRL: 13381 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 13382 unsigned VShiftOpc = 13383 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 13384 SDLoc dl(N); 13385 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 13386 DAG.getConstant(Cnt, dl, MVT::i32)); 13387 } 13388 } 13389 return SDValue(); 13390 } 13391 13392 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 13393 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 13394 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 13395 const ARMSubtarget *ST) { 13396 SDValue N0 = N->getOperand(0); 13397 13398 // Check for sign- and zero-extensions of vector extract operations of 8- 13399 // and 16-bit vector elements. NEON supports these directly. They are 13400 // handled during DAG combining because type legalization will promote them 13401 // to 32-bit types and it is messy to recognize the operations after that. 13402 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13403 SDValue Vec = N0.getOperand(0); 13404 SDValue Lane = N0.getOperand(1); 13405 EVT VT = N->getValueType(0); 13406 EVT EltVT = N0.getValueType(); 13407 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13408 13409 if (VT == MVT::i32 && 13410 (EltVT == MVT::i8 || EltVT == MVT::i16) && 13411 TLI.isTypeLegal(Vec.getValueType()) && 13412 isa<ConstantSDNode>(Lane)) { 13413 13414 unsigned Opc = 0; 13415 switch (N->getOpcode()) { 13416 default: llvm_unreachable("unexpected opcode"); 13417 case ISD::SIGN_EXTEND: 13418 Opc = ARMISD::VGETLANEs; 13419 break; 13420 case ISD::ZERO_EXTEND: 13421 case ISD::ANY_EXTEND: 13422 Opc = ARMISD::VGETLANEu; 13423 break; 13424 } 13425 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 13426 } 13427 } 13428 13429 return SDValue(); 13430 } 13431 13432 static const APInt *isPowerOf2Constant(SDValue V) { 13433 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 13434 if (!C) 13435 return nullptr; 13436 const APInt *CV = &C->getAPIntValue(); 13437 return CV->isPowerOf2() ? CV : nullptr; 13438 } 13439 13440 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 13441 // If we have a CMOV, OR and AND combination such as: 13442 // if (x & CN) 13443 // y |= CM; 13444 // 13445 // And: 13446 // * CN is a single bit; 13447 // * All bits covered by CM are known zero in y 13448 // 13449 // Then we can convert this into a sequence of BFI instructions. This will 13450 // always be a win if CM is a single bit, will always be no worse than the 13451 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 13452 // three bits (due to the extra IT instruction). 13453 13454 SDValue Op0 = CMOV->getOperand(0); 13455 SDValue Op1 = CMOV->getOperand(1); 13456 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 13457 auto CC = CCNode->getAPIntValue().getLimitedValue(); 13458 SDValue CmpZ = CMOV->getOperand(4); 13459 13460 // The compare must be against zero. 13461 if (!isNullConstant(CmpZ->getOperand(1))) 13462 return SDValue(); 13463 13464 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 13465 SDValue And = CmpZ->getOperand(0); 13466 if (And->getOpcode() != ISD::AND) 13467 return SDValue(); 13468 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 13469 if (!AndC) 13470 return SDValue(); 13471 SDValue X = And->getOperand(0); 13472 13473 if (CC == ARMCC::EQ) { 13474 // We're performing an "equal to zero" compare. Swap the operands so we 13475 // canonicalize on a "not equal to zero" compare. 13476 std::swap(Op0, Op1); 13477 } else { 13478 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 13479 } 13480 13481 if (Op1->getOpcode() != ISD::OR) 13482 return SDValue(); 13483 13484 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 13485 if (!OrC) 13486 return SDValue(); 13487 SDValue Y = Op1->getOperand(0); 13488 13489 if (Op0 != Y) 13490 return SDValue(); 13491 13492 // Now, is it profitable to continue? 13493 APInt OrCI = OrC->getAPIntValue(); 13494 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 13495 if (OrCI.countPopulation() > Heuristic) 13496 return SDValue(); 13497 13498 // Lastly, can we determine that the bits defined by OrCI 13499 // are zero in Y? 13500 KnownBits Known = DAG.computeKnownBits(Y); 13501 if ((OrCI & Known.Zero) != OrCI) 13502 return SDValue(); 13503 13504 // OK, we can do the combine. 13505 SDValue V = Y; 13506 SDLoc dl(X); 13507 EVT VT = X.getValueType(); 13508 unsigned BitInX = AndC->logBase2(); 13509 13510 if (BitInX != 0) { 13511 // We must shift X first. 13512 X = DAG.getNode(ISD::SRL, dl, VT, X, 13513 DAG.getConstant(BitInX, dl, VT)); 13514 } 13515 13516 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 13517 BitInY < NumActiveBits; ++BitInY) { 13518 if (OrCI[BitInY] == 0) 13519 continue; 13520 APInt Mask(VT.getSizeInBits(), 0); 13521 Mask.setBit(BitInY); 13522 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 13523 // Confusingly, the operand is an *inverted* mask. 13524 DAG.getConstant(~Mask, dl, VT)); 13525 } 13526 13527 return V; 13528 } 13529 13530 // Given N, the value controlling the conditional branch, search for the loop 13531 // intrinsic, returning it, along with how the value is used. We need to handle 13532 // patterns such as the following: 13533 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 13534 // (brcond (setcc (loop.decrement), 0, eq), exit) 13535 // (brcond (setcc (loop.decrement), 0, ne), header) 13536 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 13537 bool &Negate) { 13538 switch (N->getOpcode()) { 13539 default: 13540 break; 13541 case ISD::XOR: { 13542 if (!isa<ConstantSDNode>(N.getOperand(1))) 13543 return SDValue(); 13544 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 13545 return SDValue(); 13546 Negate = !Negate; 13547 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 13548 } 13549 case ISD::SETCC: { 13550 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 13551 if (!Const) 13552 return SDValue(); 13553 if (Const->isNullValue()) 13554 Imm = 0; 13555 else if (Const->isOne()) 13556 Imm = 1; 13557 else 13558 return SDValue(); 13559 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 13560 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 13561 } 13562 case ISD::INTRINSIC_W_CHAIN: { 13563 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 13564 if (IntOp != Intrinsic::test_set_loop_iterations && 13565 IntOp != Intrinsic::loop_decrement_reg) 13566 return SDValue(); 13567 return N; 13568 } 13569 } 13570 return SDValue(); 13571 } 13572 13573 static SDValue PerformHWLoopCombine(SDNode *N, 13574 TargetLowering::DAGCombinerInfo &DCI, 13575 const ARMSubtarget *ST) { 13576 13577 // The hwloop intrinsics that we're interested are used for control-flow, 13578 // either for entering or exiting the loop: 13579 // - test.set.loop.iterations will test whether its operand is zero. If it 13580 // is zero, the proceeding branch should not enter the loop. 13581 // - loop.decrement.reg also tests whether its operand is zero. If it is 13582 // zero, the proceeding branch should not branch back to the beginning of 13583 // the loop. 13584 // So here, we need to check that how the brcond is using the result of each 13585 // of the intrinsics to ensure that we're branching to the right place at the 13586 // right time. 13587 13588 ISD::CondCode CC; 13589 SDValue Cond; 13590 int Imm = 1; 13591 bool Negate = false; 13592 SDValue Chain = N->getOperand(0); 13593 SDValue Dest; 13594 13595 if (N->getOpcode() == ISD::BRCOND) { 13596 CC = ISD::SETEQ; 13597 Cond = N->getOperand(1); 13598 Dest = N->getOperand(2); 13599 } else { 13600 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 13601 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13602 Cond = N->getOperand(2); 13603 Dest = N->getOperand(4); 13604 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 13605 if (!Const->isOne() && !Const->isNullValue()) 13606 return SDValue(); 13607 Imm = Const->getZExtValue(); 13608 } else 13609 return SDValue(); 13610 } 13611 13612 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 13613 if (!Int) 13614 return SDValue(); 13615 13616 if (Negate) 13617 CC = ISD::getSetCCInverse(CC, true); 13618 13619 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 13620 return (CC == ISD::SETEQ && Imm == 0) || 13621 (CC == ISD::SETNE && Imm == 1) || 13622 (CC == ISD::SETLT && Imm == 1) || 13623 (CC == ISD::SETULT && Imm == 1); 13624 }; 13625 13626 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 13627 return (CC == ISD::SETEQ && Imm == 1) || 13628 (CC == ISD::SETNE && Imm == 0) || 13629 (CC == ISD::SETGT && Imm == 0) || 13630 (CC == ISD::SETUGT && Imm == 0) || 13631 (CC == ISD::SETGE && Imm == 1) || 13632 (CC == ISD::SETUGE && Imm == 1); 13633 }; 13634 13635 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 13636 "unsupported condition"); 13637 13638 SDLoc dl(Int); 13639 SelectionDAG &DAG = DCI.DAG; 13640 SDValue Elements = Int.getOperand(2); 13641 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 13642 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 13643 && "expected single br user"); 13644 SDNode *Br = *N->use_begin(); 13645 SDValue OtherTarget = Br->getOperand(1); 13646 13647 // Update the unconditional branch to branch to the given Dest. 13648 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 13649 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 13650 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 13651 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 13652 }; 13653 13654 if (IntOp == Intrinsic::test_set_loop_iterations) { 13655 SDValue Res; 13656 // We expect this 'instruction' to branch when the counter is zero. 13657 if (IsTrueIfZero(CC, Imm)) { 13658 SDValue Ops[] = { Chain, Elements, Dest }; 13659 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 13660 } else { 13661 // The logic is the reverse of what we need for WLS, so find the other 13662 // basic block target: the target of the proceeding br. 13663 UpdateUncondBr(Br, Dest, DAG); 13664 13665 SDValue Ops[] = { Chain, Elements, OtherTarget }; 13666 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 13667 } 13668 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 13669 return Res; 13670 } else { 13671 SDValue Size = DAG.getTargetConstant( 13672 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 13673 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 13674 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 13675 DAG.getVTList(MVT::i32, MVT::Other), Args); 13676 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 13677 13678 // We expect this instruction to branch when the count is not zero. 13679 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 13680 13681 // Update the unconditional branch to target the loop preheader if we've 13682 // found the condition has been reversed. 13683 if (Target == OtherTarget) 13684 UpdateUncondBr(Br, Dest, DAG); 13685 13686 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13687 SDValue(LoopDec.getNode(), 1), Chain); 13688 13689 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 13690 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 13691 } 13692 return SDValue(); 13693 } 13694 13695 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 13696 SDValue 13697 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 13698 SDValue Cmp = N->getOperand(4); 13699 if (Cmp.getOpcode() != ARMISD::CMPZ) 13700 // Only looking at NE cases. 13701 return SDValue(); 13702 13703 EVT VT = N->getValueType(0); 13704 SDLoc dl(N); 13705 SDValue LHS = Cmp.getOperand(0); 13706 SDValue RHS = Cmp.getOperand(1); 13707 SDValue Chain = N->getOperand(0); 13708 SDValue BB = N->getOperand(1); 13709 SDValue ARMcc = N->getOperand(2); 13710 ARMCC::CondCodes CC = 13711 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13712 13713 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 13714 // -> (brcond Chain BB CC CPSR Cmp) 13715 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 13716 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 13717 LHS->getOperand(0)->hasOneUse()) { 13718 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 13719 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 13720 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13721 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13722 if ((LHS00C && LHS00C->getZExtValue() == 0) && 13723 (LHS01C && LHS01C->getZExtValue() == 1) && 13724 (LHS1C && LHS1C->getZExtValue() == 1) && 13725 (RHSC && RHSC->getZExtValue() == 0)) { 13726 return DAG.getNode( 13727 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 13728 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 13729 } 13730 } 13731 13732 return SDValue(); 13733 } 13734 13735 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 13736 SDValue 13737 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 13738 SDValue Cmp = N->getOperand(4); 13739 if (Cmp.getOpcode() != ARMISD::CMPZ) 13740 // Only looking at EQ and NE cases. 13741 return SDValue(); 13742 13743 EVT VT = N->getValueType(0); 13744 SDLoc dl(N); 13745 SDValue LHS = Cmp.getOperand(0); 13746 SDValue RHS = Cmp.getOperand(1); 13747 SDValue FalseVal = N->getOperand(0); 13748 SDValue TrueVal = N->getOperand(1); 13749 SDValue ARMcc = N->getOperand(2); 13750 ARMCC::CondCodes CC = 13751 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13752 13753 // BFI is only available on V6T2+. 13754 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 13755 SDValue R = PerformCMOVToBFICombine(N, DAG); 13756 if (R) 13757 return R; 13758 } 13759 13760 // Simplify 13761 // mov r1, r0 13762 // cmp r1, x 13763 // mov r0, y 13764 // moveq r0, x 13765 // to 13766 // cmp r0, x 13767 // movne r0, y 13768 // 13769 // mov r1, r0 13770 // cmp r1, x 13771 // mov r0, x 13772 // movne r0, y 13773 // to 13774 // cmp r0, x 13775 // movne r0, y 13776 /// FIXME: Turn this into a target neutral optimization? 13777 SDValue Res; 13778 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 13779 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 13780 N->getOperand(3), Cmp); 13781 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 13782 SDValue ARMcc; 13783 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 13784 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 13785 N->getOperand(3), NewCmp); 13786 } 13787 13788 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 13789 // -> (cmov F T CC CPSR Cmp) 13790 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 13791 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 13792 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13793 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13794 if ((LHS0C && LHS0C->getZExtValue() == 0) && 13795 (LHS1C && LHS1C->getZExtValue() == 1) && 13796 (RHSC && RHSC->getZExtValue() == 0)) { 13797 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 13798 LHS->getOperand(2), LHS->getOperand(3), 13799 LHS->getOperand(4)); 13800 } 13801 } 13802 13803 if (!VT.isInteger()) 13804 return SDValue(); 13805 13806 // Materialize a boolean comparison for integers so we can avoid branching. 13807 if (isNullConstant(FalseVal)) { 13808 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 13809 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 13810 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 13811 // right 5 bits will make that 32 be 1, otherwise it will be 0. 13812 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 13813 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13814 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 13815 DAG.getConstant(5, dl, MVT::i32)); 13816 } else { 13817 // CMOV 0, 1, ==, (CMPZ x, y) -> 13818 // (ADDCARRY (SUB x, y), t:0, t:1) 13819 // where t = (SUBCARRY 0, (SUB x, y), 0) 13820 // 13821 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 13822 // x != y. In other words, a carry C == 1 when x == y, C == 0 13823 // otherwise. 13824 // The final ADDCARRY computes 13825 // x - y + (0 - (x - y)) + C == C 13826 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13827 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13828 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 13829 // ISD::SUBCARRY returns a borrow but we want the carry here 13830 // actually. 13831 SDValue Carry = 13832 DAG.getNode(ISD::SUB, dl, MVT::i32, 13833 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 13834 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 13835 } 13836 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 13837 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 13838 // This seems pointless but will allow us to combine it further below. 13839 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13840 SDValue Sub = 13841 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13842 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13843 Sub.getValue(1), SDValue()); 13844 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 13845 N->getOperand(3), CPSRGlue.getValue(1)); 13846 FalseVal = Sub; 13847 } 13848 } else if (isNullConstant(TrueVal)) { 13849 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 13850 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 13851 // This seems pointless but will allow us to combine it further below 13852 // Note that we change == for != as this is the dual for the case above. 13853 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13854 SDValue Sub = 13855 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13856 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13857 Sub.getValue(1), SDValue()); 13858 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 13859 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 13860 N->getOperand(3), CPSRGlue.getValue(1)); 13861 FalseVal = Sub; 13862 } 13863 } 13864 13865 // On Thumb1, the DAG above may be further combined if z is a power of 2 13866 // (z == 2 ^ K). 13867 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 13868 // t1 = (USUBO (SUB x, y), 1) 13869 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 13870 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13871 // 13872 // This also handles the special case of comparing against zero; it's 13873 // essentially, the same pattern, except there's no SUBS: 13874 // CMOV x, z, !=, (CMPZ x, 0) -> 13875 // t1 = (USUBO x, 1) 13876 // t2 = (SUBCARRY x, t1:0, t1:1) 13877 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13878 const APInt *TrueConst; 13879 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 13880 ((FalseVal.getOpcode() == ARMISD::SUBS && 13881 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 13882 (FalseVal == LHS && isNullConstant(RHS))) && 13883 (TrueConst = isPowerOf2Constant(TrueVal))) { 13884 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13885 unsigned ShiftAmount = TrueConst->logBase2(); 13886 if (ShiftAmount) 13887 TrueVal = DAG.getConstant(1, dl, VT); 13888 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 13889 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 13890 13891 if (ShiftAmount) 13892 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 13893 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 13894 } 13895 13896 if (Res.getNode()) { 13897 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 13898 // Capture demanded bits information that would be otherwise lost. 13899 if (Known.Zero == 0xfffffffe) 13900 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13901 DAG.getValueType(MVT::i1)); 13902 else if (Known.Zero == 0xffffff00) 13903 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13904 DAG.getValueType(MVT::i8)); 13905 else if (Known.Zero == 0xffff0000) 13906 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13907 DAG.getValueType(MVT::i16)); 13908 } 13909 13910 return Res; 13911 } 13912 13913 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 13914 DAGCombinerInfo &DCI) const { 13915 switch (N->getOpcode()) { 13916 default: break; 13917 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 13918 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 13919 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 13920 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 13921 case ISD::SUB: return PerformSUBCombine(N, DCI); 13922 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 13923 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 13924 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 13925 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 13926 case ISD::BRCOND: 13927 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 13928 case ARMISD::ADDC: 13929 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 13930 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 13931 case ARMISD::BFI: return PerformBFICombine(N, DCI); 13932 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 13933 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 13934 case ISD::STORE: return PerformSTORECombine(N, DCI); 13935 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 13936 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 13937 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 13938 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 13939 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 13940 case ISD::FP_TO_SINT: 13941 case ISD::FP_TO_UINT: 13942 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 13943 case ISD::FDIV: 13944 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 13945 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 13946 case ISD::SHL: 13947 case ISD::SRA: 13948 case ISD::SRL: 13949 return PerformShiftCombine(N, DCI, Subtarget); 13950 case ISD::SIGN_EXTEND: 13951 case ISD::ZERO_EXTEND: 13952 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 13953 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 13954 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 13955 case ISD::LOAD: return PerformLOADCombine(N, DCI); 13956 case ARMISD::VLD1DUP: 13957 case ARMISD::VLD2DUP: 13958 case ARMISD::VLD3DUP: 13959 case ARMISD::VLD4DUP: 13960 return PerformVLDCombine(N, DCI); 13961 case ARMISD::BUILD_VECTOR: 13962 return PerformARMBUILD_VECTORCombine(N, DCI); 13963 case ARMISD::SMULWB: { 13964 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13965 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 13966 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 13967 return SDValue(); 13968 break; 13969 } 13970 case ARMISD::SMULWT: { 13971 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13972 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 13973 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 13974 return SDValue(); 13975 break; 13976 } 13977 case ARMISD::SMLALBB: { 13978 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13979 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 13980 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 13981 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 13982 return SDValue(); 13983 break; 13984 } 13985 case ARMISD::SMLALBT: { 13986 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 13987 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 13988 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 13989 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 13990 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 13991 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 13992 return SDValue(); 13993 break; 13994 } 13995 case ARMISD::SMLALTB: { 13996 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 13997 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 13998 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 13999 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 14000 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 14001 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 14002 return SDValue(); 14003 break; 14004 } 14005 case ARMISD::SMLALTT: { 14006 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 14007 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 14008 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 14009 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 14010 return SDValue(); 14011 break; 14012 } 14013 case ISD::INTRINSIC_VOID: 14014 case ISD::INTRINSIC_W_CHAIN: 14015 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14016 case Intrinsic::arm_neon_vld1: 14017 case Intrinsic::arm_neon_vld1x2: 14018 case Intrinsic::arm_neon_vld1x3: 14019 case Intrinsic::arm_neon_vld1x4: 14020 case Intrinsic::arm_neon_vld2: 14021 case Intrinsic::arm_neon_vld3: 14022 case Intrinsic::arm_neon_vld4: 14023 case Intrinsic::arm_neon_vld2lane: 14024 case Intrinsic::arm_neon_vld3lane: 14025 case Intrinsic::arm_neon_vld4lane: 14026 case Intrinsic::arm_neon_vld2dup: 14027 case Intrinsic::arm_neon_vld3dup: 14028 case Intrinsic::arm_neon_vld4dup: 14029 case Intrinsic::arm_neon_vst1: 14030 case Intrinsic::arm_neon_vst1x2: 14031 case Intrinsic::arm_neon_vst1x3: 14032 case Intrinsic::arm_neon_vst1x4: 14033 case Intrinsic::arm_neon_vst2: 14034 case Intrinsic::arm_neon_vst3: 14035 case Intrinsic::arm_neon_vst4: 14036 case Intrinsic::arm_neon_vst2lane: 14037 case Intrinsic::arm_neon_vst3lane: 14038 case Intrinsic::arm_neon_vst4lane: 14039 return PerformVLDCombine(N, DCI); 14040 default: break; 14041 } 14042 break; 14043 } 14044 return SDValue(); 14045 } 14046 14047 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 14048 EVT VT) const { 14049 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 14050 } 14051 14052 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 14053 unsigned Alignment, 14054 MachineMemOperand::Flags, 14055 bool *Fast) const { 14056 // Depends what it gets converted into if the type is weird. 14057 if (!VT.isSimple()) 14058 return false; 14059 14060 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 14061 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 14062 auto Ty = VT.getSimpleVT().SimpleTy; 14063 14064 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 14065 // Unaligned access can use (for example) LRDB, LRDH, LDR 14066 if (AllowsUnaligned) { 14067 if (Fast) 14068 *Fast = Subtarget->hasV7Ops(); 14069 return true; 14070 } 14071 } 14072 14073 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 14074 // For any little-endian targets with neon, we can support unaligned ld/st 14075 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 14076 // A big-endian target may also explicitly support unaligned accesses 14077 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 14078 if (Fast) 14079 *Fast = true; 14080 return true; 14081 } 14082 } 14083 14084 if (!Subtarget->hasMVEIntegerOps()) 14085 return false; 14086 14087 // These are for predicates 14088 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 14089 if (Fast) 14090 *Fast = true; 14091 return true; 14092 } 14093 14094 // These are for truncated stores/narrowing loads. They are fine so long as 14095 // the alignment is at least the size of the item being loaded 14096 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) && 14097 Alignment >= VT.getScalarSizeInBits() / 8) { 14098 if (Fast) 14099 *Fast = true; 14100 return true; 14101 } 14102 14103 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and 14104 // VSTRW.U32 all store the vector register in exactly the same format, and 14105 // differ only in the range of their immediate offset field and the required 14106 // alignment. So there is always a store that can be used, regardless of 14107 // actual type. 14108 // 14109 // For big endian, that is not the case. But can still emit a (VSTRB.U8; 14110 // VREV64.8) pair and get the same effect. This will likely be better than 14111 // aligning the vector through the stack. 14112 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 || 14113 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 || 14114 Ty == MVT::v2f64) { 14115 if (Fast) 14116 *Fast = true; 14117 return true; 14118 } 14119 14120 return false; 14121 } 14122 14123 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 14124 unsigned AlignCheck) { 14125 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 14126 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 14127 } 14128 14129 EVT ARMTargetLowering::getOptimalMemOpType( 14130 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14131 bool ZeroMemset, bool MemcpyStrSrc, 14132 const AttributeList &FuncAttributes) const { 14133 // See if we can use NEON instructions for this... 14134 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 14135 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14136 bool Fast; 14137 if (Size >= 16 && 14138 (memOpAlign(SrcAlign, DstAlign, 16) || 14139 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 14140 MachineMemOperand::MONone, &Fast) && 14141 Fast))) { 14142 return MVT::v2f64; 14143 } else if (Size >= 8 && 14144 (memOpAlign(SrcAlign, DstAlign, 8) || 14145 (allowsMisalignedMemoryAccesses( 14146 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 14147 Fast))) { 14148 return MVT::f64; 14149 } 14150 } 14151 14152 // Let the target-independent logic figure it out. 14153 return MVT::Other; 14154 } 14155 14156 // 64-bit integers are split into their high and low parts and held in two 14157 // different registers, so the trunc is free since the low register can just 14158 // be used. 14159 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 14160 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 14161 return false; 14162 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 14163 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 14164 return (SrcBits == 64 && DestBits == 32); 14165 } 14166 14167 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 14168 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 14169 !DstVT.isInteger()) 14170 return false; 14171 unsigned SrcBits = SrcVT.getSizeInBits(); 14172 unsigned DestBits = DstVT.getSizeInBits(); 14173 return (SrcBits == 64 && DestBits == 32); 14174 } 14175 14176 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14177 if (Val.getOpcode() != ISD::LOAD) 14178 return false; 14179 14180 EVT VT1 = Val.getValueType(); 14181 if (!VT1.isSimple() || !VT1.isInteger() || 14182 !VT2.isSimple() || !VT2.isInteger()) 14183 return false; 14184 14185 switch (VT1.getSimpleVT().SimpleTy) { 14186 default: break; 14187 case MVT::i1: 14188 case MVT::i8: 14189 case MVT::i16: 14190 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 14191 return true; 14192 } 14193 14194 return false; 14195 } 14196 14197 bool ARMTargetLowering::isFNegFree(EVT VT) const { 14198 if (!VT.isSimple()) 14199 return false; 14200 14201 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 14202 // negate values directly (fneg is free). So, we don't want to let the DAG 14203 // combiner rewrite fneg into xors and some other instructions. For f16 and 14204 // FullFP16 argument passing, some bitcast nodes may be introduced, 14205 // triggering this DAG combine rewrite, so we are avoiding that with this. 14206 switch (VT.getSimpleVT().SimpleTy) { 14207 default: break; 14208 case MVT::f16: 14209 return Subtarget->hasFullFP16(); 14210 } 14211 14212 return false; 14213 } 14214 14215 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 14216 /// of the vector elements. 14217 static bool areExtractExts(Value *Ext1, Value *Ext2) { 14218 auto areExtDoubled = [](Instruction *Ext) { 14219 return Ext->getType()->getScalarSizeInBits() == 14220 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 14221 }; 14222 14223 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 14224 !match(Ext2, m_ZExtOrSExt(m_Value())) || 14225 !areExtDoubled(cast<Instruction>(Ext1)) || 14226 !areExtDoubled(cast<Instruction>(Ext2))) 14227 return false; 14228 14229 return true; 14230 } 14231 14232 /// Check if sinking \p I's operands to I's basic block is profitable, because 14233 /// the operands can be folded into a target instruction, e.g. 14234 /// sext/zext can be folded into vsubl. 14235 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 14236 SmallVectorImpl<Use *> &Ops) const { 14237 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy()) 14238 return false; 14239 14240 switch (I->getOpcode()) { 14241 case Instruction::Sub: 14242 case Instruction::Add: { 14243 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 14244 return false; 14245 Ops.push_back(&I->getOperandUse(0)); 14246 Ops.push_back(&I->getOperandUse(1)); 14247 return true; 14248 } 14249 default: 14250 return false; 14251 } 14252 return false; 14253 } 14254 14255 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 14256 EVT VT = ExtVal.getValueType(); 14257 14258 if (!isTypeLegal(VT)) 14259 return false; 14260 14261 // Don't create a loadext if we can fold the extension into a wide/long 14262 // instruction. 14263 // If there's more than one user instruction, the loadext is desirable no 14264 // matter what. There can be two uses by the same instruction. 14265 if (ExtVal->use_empty() || 14266 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 14267 return true; 14268 14269 SDNode *U = *ExtVal->use_begin(); 14270 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 14271 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 14272 return false; 14273 14274 return true; 14275 } 14276 14277 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 14278 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14279 return false; 14280 14281 if (!isTypeLegal(EVT::getEVT(Ty1))) 14282 return false; 14283 14284 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 14285 14286 // Assuming the caller doesn't have a zeroext or signext return parameter, 14287 // truncation all the way down to i1 is valid. 14288 return true; 14289 } 14290 14291 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 14292 const AddrMode &AM, Type *Ty, 14293 unsigned AS) const { 14294 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 14295 if (Subtarget->hasFPAO()) 14296 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 14297 return 0; 14298 } 14299 return -1; 14300 } 14301 14302 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 14303 if (V < 0) 14304 return false; 14305 14306 unsigned Scale = 1; 14307 switch (VT.getSimpleVT().SimpleTy) { 14308 case MVT::i1: 14309 case MVT::i8: 14310 // Scale == 1; 14311 break; 14312 case MVT::i16: 14313 // Scale == 2; 14314 Scale = 2; 14315 break; 14316 default: 14317 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 14318 // Scale == 4; 14319 Scale = 4; 14320 break; 14321 } 14322 14323 if ((V & (Scale - 1)) != 0) 14324 return false; 14325 return isUInt<5>(V / Scale); 14326 } 14327 14328 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 14329 const ARMSubtarget *Subtarget) { 14330 if (!VT.isInteger() && !VT.isFloatingPoint()) 14331 return false; 14332 if (VT.isVector() && Subtarget->hasNEON()) 14333 return false; 14334 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 14335 !Subtarget->hasMVEFloatOps()) 14336 return false; 14337 14338 bool IsNeg = false; 14339 if (V < 0) { 14340 IsNeg = true; 14341 V = -V; 14342 } 14343 14344 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U); 14345 14346 // MVE: size * imm7 14347 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 14348 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 14349 case MVT::i32: 14350 case MVT::f32: 14351 return isShiftedUInt<7,2>(V); 14352 case MVT::i16: 14353 case MVT::f16: 14354 return isShiftedUInt<7,1>(V); 14355 case MVT::i8: 14356 return isUInt<7>(V); 14357 default: 14358 return false; 14359 } 14360 } 14361 14362 // half VLDR: 2 * imm8 14363 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 14364 return isShiftedUInt<8, 1>(V); 14365 // VLDR and LDRD: 4 * imm8 14366 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 14367 return isShiftedUInt<8, 2>(V); 14368 14369 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 14370 // + imm12 or - imm8 14371 if (IsNeg) 14372 return isUInt<8>(V); 14373 return isUInt<12>(V); 14374 } 14375 14376 return false; 14377 } 14378 14379 /// isLegalAddressImmediate - Return true if the integer value can be used 14380 /// as the offset of the target addressing mode for load / store of the 14381 /// given type. 14382 static bool isLegalAddressImmediate(int64_t V, EVT VT, 14383 const ARMSubtarget *Subtarget) { 14384 if (V == 0) 14385 return true; 14386 14387 if (!VT.isSimple()) 14388 return false; 14389 14390 if (Subtarget->isThumb1Only()) 14391 return isLegalT1AddressImmediate(V, VT); 14392 else if (Subtarget->isThumb2()) 14393 return isLegalT2AddressImmediate(V, VT, Subtarget); 14394 14395 // ARM mode. 14396 if (V < 0) 14397 V = - V; 14398 switch (VT.getSimpleVT().SimpleTy) { 14399 default: return false; 14400 case MVT::i1: 14401 case MVT::i8: 14402 case MVT::i32: 14403 // +- imm12 14404 return isUInt<12>(V); 14405 case MVT::i16: 14406 // +- imm8 14407 return isUInt<8>(V); 14408 case MVT::f32: 14409 case MVT::f64: 14410 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 14411 return false; 14412 return isShiftedUInt<8, 2>(V); 14413 } 14414 } 14415 14416 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 14417 EVT VT) const { 14418 int Scale = AM.Scale; 14419 if (Scale < 0) 14420 return false; 14421 14422 switch (VT.getSimpleVT().SimpleTy) { 14423 default: return false; 14424 case MVT::i1: 14425 case MVT::i8: 14426 case MVT::i16: 14427 case MVT::i32: 14428 if (Scale == 1) 14429 return true; 14430 // r + r << imm 14431 Scale = Scale & ~1; 14432 return Scale == 2 || Scale == 4 || Scale == 8; 14433 case MVT::i64: 14434 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 14435 // version in Thumb mode. 14436 // r + r 14437 if (Scale == 1) 14438 return true; 14439 // r * 2 (this can be lowered to r + r). 14440 if (!AM.HasBaseReg && Scale == 2) 14441 return true; 14442 return false; 14443 case MVT::isVoid: 14444 // Note, we allow "void" uses (basically, uses that aren't loads or 14445 // stores), because arm allows folding a scale into many arithmetic 14446 // operations. This should be made more precise and revisited later. 14447 14448 // Allow r << imm, but the imm has to be a multiple of two. 14449 if (Scale & 1) return false; 14450 return isPowerOf2_32(Scale); 14451 } 14452 } 14453 14454 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 14455 EVT VT) const { 14456 const int Scale = AM.Scale; 14457 14458 // Negative scales are not supported in Thumb1. 14459 if (Scale < 0) 14460 return false; 14461 14462 // Thumb1 addressing modes do not support register scaling excepting the 14463 // following cases: 14464 // 1. Scale == 1 means no scaling. 14465 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 14466 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 14467 } 14468 14469 /// isLegalAddressingMode - Return true if the addressing mode represented 14470 /// by AM is legal for this target, for a load/store of the specified type. 14471 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14472 const AddrMode &AM, Type *Ty, 14473 unsigned AS, Instruction *I) const { 14474 EVT VT = getValueType(DL, Ty, true); 14475 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 14476 return false; 14477 14478 // Can never fold addr of global into load/store. 14479 if (AM.BaseGV) 14480 return false; 14481 14482 switch (AM.Scale) { 14483 case 0: // no scale reg, must be "r+i" or "r", or "i". 14484 break; 14485 default: 14486 // ARM doesn't support any R+R*scale+imm addr modes. 14487 if (AM.BaseOffs) 14488 return false; 14489 14490 if (!VT.isSimple()) 14491 return false; 14492 14493 if (Subtarget->isThumb1Only()) 14494 return isLegalT1ScaledAddressingMode(AM, VT); 14495 14496 if (Subtarget->isThumb2()) 14497 return isLegalT2ScaledAddressingMode(AM, VT); 14498 14499 int Scale = AM.Scale; 14500 switch (VT.getSimpleVT().SimpleTy) { 14501 default: return false; 14502 case MVT::i1: 14503 case MVT::i8: 14504 case MVT::i32: 14505 if (Scale < 0) Scale = -Scale; 14506 if (Scale == 1) 14507 return true; 14508 // r + r << imm 14509 return isPowerOf2_32(Scale & ~1); 14510 case MVT::i16: 14511 case MVT::i64: 14512 // r +/- r 14513 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 14514 return true; 14515 // r * 2 (this can be lowered to r + r). 14516 if (!AM.HasBaseReg && Scale == 2) 14517 return true; 14518 return false; 14519 14520 case MVT::isVoid: 14521 // Note, we allow "void" uses (basically, uses that aren't loads or 14522 // stores), because arm allows folding a scale into many arithmetic 14523 // operations. This should be made more precise and revisited later. 14524 14525 // Allow r << imm, but the imm has to be a multiple of two. 14526 if (Scale & 1) return false; 14527 return isPowerOf2_32(Scale); 14528 } 14529 } 14530 return true; 14531 } 14532 14533 /// isLegalICmpImmediate - Return true if the specified immediate is legal 14534 /// icmp immediate, that is the target has icmp instructions which can compare 14535 /// a register against the immediate without having to materialize the 14536 /// immediate into a register. 14537 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14538 // Thumb2 and ARM modes can use cmn for negative immediates. 14539 if (!Subtarget->isThumb()) 14540 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 14541 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 14542 if (Subtarget->isThumb2()) 14543 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 14544 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 14545 // Thumb1 doesn't have cmn, and only 8-bit immediates. 14546 return Imm >= 0 && Imm <= 255; 14547 } 14548 14549 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 14550 /// *or sub* immediate, that is the target has add or sub instructions which can 14551 /// add a register with the immediate without having to materialize the 14552 /// immediate into a register. 14553 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14554 // Same encoding for add/sub, just flip the sign. 14555 int64_t AbsImm = std::abs(Imm); 14556 if (!Subtarget->isThumb()) 14557 return ARM_AM::getSOImmVal(AbsImm) != -1; 14558 if (Subtarget->isThumb2()) 14559 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 14560 // Thumb1 only has 8-bit unsigned immediate. 14561 return AbsImm >= 0 && AbsImm <= 255; 14562 } 14563 14564 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 14565 bool isSEXTLoad, SDValue &Base, 14566 SDValue &Offset, bool &isInc, 14567 SelectionDAG &DAG) { 14568 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14569 return false; 14570 14571 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 14572 // AddressingMode 3 14573 Base = Ptr->getOperand(0); 14574 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14575 int RHSC = (int)RHS->getZExtValue(); 14576 if (RHSC < 0 && RHSC > -256) { 14577 assert(Ptr->getOpcode() == ISD::ADD); 14578 isInc = false; 14579 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14580 return true; 14581 } 14582 } 14583 isInc = (Ptr->getOpcode() == ISD::ADD); 14584 Offset = Ptr->getOperand(1); 14585 return true; 14586 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 14587 // AddressingMode 2 14588 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14589 int RHSC = (int)RHS->getZExtValue(); 14590 if (RHSC < 0 && RHSC > -0x1000) { 14591 assert(Ptr->getOpcode() == ISD::ADD); 14592 isInc = false; 14593 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14594 Base = Ptr->getOperand(0); 14595 return true; 14596 } 14597 } 14598 14599 if (Ptr->getOpcode() == ISD::ADD) { 14600 isInc = true; 14601 ARM_AM::ShiftOpc ShOpcVal= 14602 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 14603 if (ShOpcVal != ARM_AM::no_shift) { 14604 Base = Ptr->getOperand(1); 14605 Offset = Ptr->getOperand(0); 14606 } else { 14607 Base = Ptr->getOperand(0); 14608 Offset = Ptr->getOperand(1); 14609 } 14610 return true; 14611 } 14612 14613 isInc = (Ptr->getOpcode() == ISD::ADD); 14614 Base = Ptr->getOperand(0); 14615 Offset = Ptr->getOperand(1); 14616 return true; 14617 } 14618 14619 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 14620 return false; 14621 } 14622 14623 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 14624 bool isSEXTLoad, SDValue &Base, 14625 SDValue &Offset, bool &isInc, 14626 SelectionDAG &DAG) { 14627 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14628 return false; 14629 14630 Base = Ptr->getOperand(0); 14631 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14632 int RHSC = (int)RHS->getZExtValue(); 14633 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 14634 assert(Ptr->getOpcode() == ISD::ADD); 14635 isInc = false; 14636 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14637 return true; 14638 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 14639 isInc = Ptr->getOpcode() == ISD::ADD; 14640 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14641 return true; 14642 } 14643 } 14644 14645 return false; 14646 } 14647 14648 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align, 14649 bool isSEXTLoad, bool isLE, SDValue &Base, 14650 SDValue &Offset, bool &isInc, 14651 SelectionDAG &DAG) { 14652 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14653 return false; 14654 if (!isa<ConstantSDNode>(Ptr->getOperand(1))) 14655 return false; 14656 14657 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1)); 14658 int RHSC = (int)RHS->getZExtValue(); 14659 14660 auto IsInRange = [&](int RHSC, int Limit, int Scale) { 14661 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) { 14662 assert(Ptr->getOpcode() == ISD::ADD); 14663 isInc = false; 14664 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14665 return true; 14666 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) { 14667 isInc = Ptr->getOpcode() == ISD::ADD; 14668 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14669 return true; 14670 } 14671 return false; 14672 }; 14673 14674 // Try to find a matching instruction based on s/zext, Alignment, Offset and 14675 // (in BE) type. 14676 Base = Ptr->getOperand(0); 14677 if (VT == MVT::v4i16) { 14678 if (Align >= 2 && IsInRange(RHSC, 0x80, 2)) 14679 return true; 14680 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) { 14681 if (IsInRange(RHSC, 0x80, 1)) 14682 return true; 14683 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) && 14684 IsInRange(RHSC, 0x80, 4)) 14685 return true; 14686 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) && 14687 IsInRange(RHSC, 0x80, 2)) 14688 return true; 14689 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1)) 14690 return true; 14691 return false; 14692 } 14693 14694 /// getPreIndexedAddressParts - returns true by value, base pointer and 14695 /// offset pointer and addressing mode by reference if the node's address 14696 /// can be legally represented as pre-indexed load / store address. 14697 bool 14698 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 14699 SDValue &Offset, 14700 ISD::MemIndexedMode &AM, 14701 SelectionDAG &DAG) const { 14702 if (Subtarget->isThumb1Only()) 14703 return false; 14704 14705 EVT VT; 14706 SDValue Ptr; 14707 unsigned Align; 14708 bool isSEXTLoad = false; 14709 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 14710 Ptr = LD->getBasePtr(); 14711 VT = LD->getMemoryVT(); 14712 Align = LD->getAlignment(); 14713 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 14714 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 14715 Ptr = ST->getBasePtr(); 14716 VT = ST->getMemoryVT(); 14717 Align = ST->getAlignment(); 14718 } else 14719 return false; 14720 14721 bool isInc; 14722 bool isLegal = false; 14723 if (VT.isVector()) 14724 isLegal = Subtarget->hasMVEIntegerOps() && 14725 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad, 14726 Subtarget->isLittle(), Base, Offset, 14727 isInc, DAG); 14728 else { 14729 if (Subtarget->isThumb2()) 14730 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 14731 Offset, isInc, DAG); 14732 else 14733 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 14734 Offset, isInc, DAG); 14735 } 14736 if (!isLegal) 14737 return false; 14738 14739 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 14740 return true; 14741 } 14742 14743 /// getPostIndexedAddressParts - returns true by value, base pointer and 14744 /// offset pointer and addressing mode by reference if this node can be 14745 /// combined with a load / store to form a post-indexed load / store. 14746 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 14747 SDValue &Base, 14748 SDValue &Offset, 14749 ISD::MemIndexedMode &AM, 14750 SelectionDAG &DAG) const { 14751 EVT VT; 14752 SDValue Ptr; 14753 unsigned Align; 14754 bool isSEXTLoad = false, isNonExt; 14755 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 14756 VT = LD->getMemoryVT(); 14757 Ptr = LD->getBasePtr(); 14758 Align = LD->getAlignment(); 14759 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 14760 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 14761 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 14762 VT = ST->getMemoryVT(); 14763 Ptr = ST->getBasePtr(); 14764 Align = ST->getAlignment(); 14765 isNonExt = !ST->isTruncatingStore(); 14766 } else 14767 return false; 14768 14769 if (Subtarget->isThumb1Only()) { 14770 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 14771 // must be non-extending/truncating, i32, with an offset of 4. 14772 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 14773 if (Op->getOpcode() != ISD::ADD || !isNonExt) 14774 return false; 14775 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 14776 if (!RHS || RHS->getZExtValue() != 4) 14777 return false; 14778 14779 Offset = Op->getOperand(1); 14780 Base = Op->getOperand(0); 14781 AM = ISD::POST_INC; 14782 return true; 14783 } 14784 14785 bool isInc; 14786 bool isLegal = false; 14787 if (VT.isVector()) 14788 isLegal = Subtarget->hasMVEIntegerOps() && 14789 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad, 14790 Subtarget->isLittle(), Base, Offset, 14791 isInc, DAG); 14792 else { 14793 if (Subtarget->isThumb2()) 14794 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14795 isInc, DAG); 14796 else 14797 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14798 isInc, DAG); 14799 } 14800 if (!isLegal) 14801 return false; 14802 14803 if (Ptr != Base) { 14804 // Swap base ptr and offset to catch more post-index load / store when 14805 // it's legal. In Thumb2 mode, offset must be an immediate. 14806 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 14807 !Subtarget->isThumb2()) 14808 std::swap(Base, Offset); 14809 14810 // Post-indexed load / store update the base pointer. 14811 if (Ptr != Base) 14812 return false; 14813 } 14814 14815 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 14816 return true; 14817 } 14818 14819 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14820 KnownBits &Known, 14821 const APInt &DemandedElts, 14822 const SelectionDAG &DAG, 14823 unsigned Depth) const { 14824 unsigned BitWidth = Known.getBitWidth(); 14825 Known.resetAll(); 14826 switch (Op.getOpcode()) { 14827 default: break; 14828 case ARMISD::ADDC: 14829 case ARMISD::ADDE: 14830 case ARMISD::SUBC: 14831 case ARMISD::SUBE: 14832 // Special cases when we convert a carry to a boolean. 14833 if (Op.getResNo() == 0) { 14834 SDValue LHS = Op.getOperand(0); 14835 SDValue RHS = Op.getOperand(1); 14836 // (ADDE 0, 0, C) will give us a single bit. 14837 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 14838 isNullConstant(RHS)) { 14839 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 14840 return; 14841 } 14842 } 14843 break; 14844 case ARMISD::CMOV: { 14845 // Bits are known zero/one if known on the LHS and RHS. 14846 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 14847 if (Known.isUnknown()) 14848 return; 14849 14850 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 14851 Known.Zero &= KnownRHS.Zero; 14852 Known.One &= KnownRHS.One; 14853 return; 14854 } 14855 case ISD::INTRINSIC_W_CHAIN: { 14856 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 14857 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 14858 switch (IntID) { 14859 default: return; 14860 case Intrinsic::arm_ldaex: 14861 case Intrinsic::arm_ldrex: { 14862 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 14863 unsigned MemBits = VT.getScalarSizeInBits(); 14864 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 14865 return; 14866 } 14867 } 14868 } 14869 case ARMISD::BFI: { 14870 // Conservatively, we can recurse down the first operand 14871 // and just mask out all affected bits. 14872 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 14873 14874 // The operand to BFI is already a mask suitable for removing the bits it 14875 // sets. 14876 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 14877 const APInt &Mask = CI->getAPIntValue(); 14878 Known.Zero &= Mask; 14879 Known.One &= Mask; 14880 return; 14881 } 14882 case ARMISD::VGETLANEs: 14883 case ARMISD::VGETLANEu: { 14884 const SDValue &SrcSV = Op.getOperand(0); 14885 EVT VecVT = SrcSV.getValueType(); 14886 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 14887 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 14888 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 14889 assert(Pos->getAPIntValue().ult(NumSrcElts) && 14890 "VGETLANE index out of bounds"); 14891 unsigned Idx = Pos->getZExtValue(); 14892 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 14893 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 14894 14895 EVT VT = Op.getValueType(); 14896 const unsigned DstSz = VT.getScalarSizeInBits(); 14897 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 14898 (void)SrcSz; 14899 assert(SrcSz == Known.getBitWidth()); 14900 assert(DstSz > SrcSz); 14901 if (Op.getOpcode() == ARMISD::VGETLANEs) 14902 Known = Known.sext(DstSz); 14903 else { 14904 Known = Known.zext(DstSz, true /* extended bits are known zero */); 14905 } 14906 assert(DstSz == Known.getBitWidth()); 14907 break; 14908 } 14909 } 14910 } 14911 14912 bool 14913 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 14914 const APInt &DemandedAPInt, 14915 TargetLoweringOpt &TLO) const { 14916 // Delay optimization, so we don't have to deal with illegal types, or block 14917 // optimizations. 14918 if (!TLO.LegalOps) 14919 return false; 14920 14921 // Only optimize AND for now. 14922 if (Op.getOpcode() != ISD::AND) 14923 return false; 14924 14925 EVT VT = Op.getValueType(); 14926 14927 // Ignore vectors. 14928 if (VT.isVector()) 14929 return false; 14930 14931 assert(VT == MVT::i32 && "Unexpected integer type"); 14932 14933 // Make sure the RHS really is a constant. 14934 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14935 if (!C) 14936 return false; 14937 14938 unsigned Mask = C->getZExtValue(); 14939 14940 unsigned Demanded = DemandedAPInt.getZExtValue(); 14941 unsigned ShrunkMask = Mask & Demanded; 14942 unsigned ExpandedMask = Mask | ~Demanded; 14943 14944 // If the mask is all zeros, let the target-independent code replace the 14945 // result with zero. 14946 if (ShrunkMask == 0) 14947 return false; 14948 14949 // If the mask is all ones, erase the AND. (Currently, the target-independent 14950 // code won't do this, so we have to do it explicitly to avoid an infinite 14951 // loop in obscure cases.) 14952 if (ExpandedMask == ~0U) 14953 return TLO.CombineTo(Op, Op.getOperand(0)); 14954 14955 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 14956 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 14957 }; 14958 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 14959 if (NewMask == Mask) 14960 return true; 14961 SDLoc DL(Op); 14962 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 14963 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 14964 return TLO.CombineTo(Op, NewOp); 14965 }; 14966 14967 // Prefer uxtb mask. 14968 if (IsLegalMask(0xFF)) 14969 return UseMask(0xFF); 14970 14971 // Prefer uxth mask. 14972 if (IsLegalMask(0xFFFF)) 14973 return UseMask(0xFFFF); 14974 14975 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 14976 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 14977 if (ShrunkMask < 256) 14978 return UseMask(ShrunkMask); 14979 14980 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 14981 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 14982 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 14983 return UseMask(ExpandedMask); 14984 14985 // Potential improvements: 14986 // 14987 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 14988 // We could try to prefer Thumb1 immediates which can be lowered to a 14989 // two-instruction sequence. 14990 // We could try to recognize more legal ARM/Thumb2 immediates here. 14991 14992 return false; 14993 } 14994 14995 14996 //===----------------------------------------------------------------------===// 14997 // ARM Inline Assembly Support 14998 //===----------------------------------------------------------------------===// 14999 15000 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 15001 // Looking for "rev" which is V6+. 15002 if (!Subtarget->hasV6Ops()) 15003 return false; 15004 15005 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 15006 std::string AsmStr = IA->getAsmString(); 15007 SmallVector<StringRef, 4> AsmPieces; 15008 SplitString(AsmStr, AsmPieces, ";\n"); 15009 15010 switch (AsmPieces.size()) { 15011 default: return false; 15012 case 1: 15013 AsmStr = AsmPieces[0]; 15014 AsmPieces.clear(); 15015 SplitString(AsmStr, AsmPieces, " \t,"); 15016 15017 // rev $0, $1 15018 if (AsmPieces.size() == 3 && 15019 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 15020 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 15021 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 15022 if (Ty && Ty->getBitWidth() == 32) 15023 return IntrinsicLowering::LowerToByteSwap(CI); 15024 } 15025 break; 15026 } 15027 15028 return false; 15029 } 15030 15031 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 15032 // At this point, we have to lower this constraint to something else, so we 15033 // lower it to an "r" or "w". However, by doing this we will force the result 15034 // to be in register, while the X constraint is much more permissive. 15035 // 15036 // Although we are correct (we are free to emit anything, without 15037 // constraints), we might break use cases that would expect us to be more 15038 // efficient and emit something else. 15039 if (!Subtarget->hasVFP2Base()) 15040 return "r"; 15041 if (ConstraintVT.isFloatingPoint()) 15042 return "w"; 15043 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 15044 (ConstraintVT.getSizeInBits() == 64 || 15045 ConstraintVT.getSizeInBits() == 128)) 15046 return "w"; 15047 15048 return "r"; 15049 } 15050 15051 /// getConstraintType - Given a constraint letter, return the type of 15052 /// constraint it is for this target. 15053 ARMTargetLowering::ConstraintType 15054 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 15055 unsigned S = Constraint.size(); 15056 if (S == 1) { 15057 switch (Constraint[0]) { 15058 default: break; 15059 case 'l': return C_RegisterClass; 15060 case 'w': return C_RegisterClass; 15061 case 'h': return C_RegisterClass; 15062 case 'x': return C_RegisterClass; 15063 case 't': return C_RegisterClass; 15064 case 'j': return C_Immediate; // Constant for movw. 15065 // An address with a single base register. Due to the way we 15066 // currently handle addresses it is the same as an 'r' memory constraint. 15067 case 'Q': return C_Memory; 15068 } 15069 } else if (S == 2) { 15070 switch (Constraint[0]) { 15071 default: break; 15072 case 'T': return C_RegisterClass; 15073 // All 'U+' constraints are addresses. 15074 case 'U': return C_Memory; 15075 } 15076 } 15077 return TargetLowering::getConstraintType(Constraint); 15078 } 15079 15080 /// Examine constraint type and operand type and determine a weight value. 15081 /// This object must already have been set up with the operand type 15082 /// and the current alternative constraint selected. 15083 TargetLowering::ConstraintWeight 15084 ARMTargetLowering::getSingleConstraintMatchWeight( 15085 AsmOperandInfo &info, const char *constraint) const { 15086 ConstraintWeight weight = CW_Invalid; 15087 Value *CallOperandVal = info.CallOperandVal; 15088 // If we don't have a value, we can't do a match, 15089 // but allow it at the lowest weight. 15090 if (!CallOperandVal) 15091 return CW_Default; 15092 Type *type = CallOperandVal->getType(); 15093 // Look at the constraint type. 15094 switch (*constraint) { 15095 default: 15096 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15097 break; 15098 case 'l': 15099 if (type->isIntegerTy()) { 15100 if (Subtarget->isThumb()) 15101 weight = CW_SpecificReg; 15102 else 15103 weight = CW_Register; 15104 } 15105 break; 15106 case 'w': 15107 if (type->isFloatingPointTy()) 15108 weight = CW_Register; 15109 break; 15110 } 15111 return weight; 15112 } 15113 15114 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 15115 15116 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 15117 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 15118 switch (Constraint.size()) { 15119 case 1: 15120 // GCC ARM Constraint Letters 15121 switch (Constraint[0]) { 15122 case 'l': // Low regs or general regs. 15123 if (Subtarget->isThumb()) 15124 return RCPair(0U, &ARM::tGPRRegClass); 15125 return RCPair(0U, &ARM::GPRRegClass); 15126 case 'h': // High regs or no regs. 15127 if (Subtarget->isThumb()) 15128 return RCPair(0U, &ARM::hGPRRegClass); 15129 break; 15130 case 'r': 15131 if (Subtarget->isThumb1Only()) 15132 return RCPair(0U, &ARM::tGPRRegClass); 15133 return RCPair(0U, &ARM::GPRRegClass); 15134 case 'w': 15135 if (VT == MVT::Other) 15136 break; 15137 if (VT == MVT::f32) 15138 return RCPair(0U, &ARM::SPRRegClass); 15139 if (VT.getSizeInBits() == 64) 15140 return RCPair(0U, &ARM::DPRRegClass); 15141 if (VT.getSizeInBits() == 128) 15142 return RCPair(0U, &ARM::QPRRegClass); 15143 break; 15144 case 'x': 15145 if (VT == MVT::Other) 15146 break; 15147 if (VT == MVT::f32) 15148 return RCPair(0U, &ARM::SPR_8RegClass); 15149 if (VT.getSizeInBits() == 64) 15150 return RCPair(0U, &ARM::DPR_8RegClass); 15151 if (VT.getSizeInBits() == 128) 15152 return RCPair(0U, &ARM::QPR_8RegClass); 15153 break; 15154 case 't': 15155 if (VT == MVT::Other) 15156 break; 15157 if (VT == MVT::f32 || VT == MVT::i32) 15158 return RCPair(0U, &ARM::SPRRegClass); 15159 if (VT.getSizeInBits() == 64) 15160 return RCPair(0U, &ARM::DPR_VFP2RegClass); 15161 if (VT.getSizeInBits() == 128) 15162 return RCPair(0U, &ARM::QPR_VFP2RegClass); 15163 break; 15164 } 15165 break; 15166 15167 case 2: 15168 if (Constraint[0] == 'T') { 15169 switch (Constraint[1]) { 15170 default: 15171 break; 15172 case 'e': 15173 return RCPair(0U, &ARM::tGPREvenRegClass); 15174 case 'o': 15175 return RCPair(0U, &ARM::tGPROddRegClass); 15176 } 15177 } 15178 break; 15179 15180 default: 15181 break; 15182 } 15183 15184 if (StringRef("{cc}").equals_lower(Constraint)) 15185 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 15186 15187 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15188 } 15189 15190 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15191 /// vector. If it is invalid, don't add anything to Ops. 15192 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15193 std::string &Constraint, 15194 std::vector<SDValue>&Ops, 15195 SelectionDAG &DAG) const { 15196 SDValue Result; 15197 15198 // Currently only support length 1 constraints. 15199 if (Constraint.length() != 1) return; 15200 15201 char ConstraintLetter = Constraint[0]; 15202 switch (ConstraintLetter) { 15203 default: break; 15204 case 'j': 15205 case 'I': case 'J': case 'K': case 'L': 15206 case 'M': case 'N': case 'O': 15207 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 15208 if (!C) 15209 return; 15210 15211 int64_t CVal64 = C->getSExtValue(); 15212 int CVal = (int) CVal64; 15213 // None of these constraints allow values larger than 32 bits. Check 15214 // that the value fits in an int. 15215 if (CVal != CVal64) 15216 return; 15217 15218 switch (ConstraintLetter) { 15219 case 'j': 15220 // Constant suitable for movw, must be between 0 and 15221 // 65535. 15222 if (Subtarget->hasV6T2Ops()) 15223 if (CVal >= 0 && CVal <= 65535) 15224 break; 15225 return; 15226 case 'I': 15227 if (Subtarget->isThumb1Only()) { 15228 // This must be a constant between 0 and 255, for ADD 15229 // immediates. 15230 if (CVal >= 0 && CVal <= 255) 15231 break; 15232 } else if (Subtarget->isThumb2()) { 15233 // A constant that can be used as an immediate value in a 15234 // data-processing instruction. 15235 if (ARM_AM::getT2SOImmVal(CVal) != -1) 15236 break; 15237 } else { 15238 // A constant that can be used as an immediate value in a 15239 // data-processing instruction. 15240 if (ARM_AM::getSOImmVal(CVal) != -1) 15241 break; 15242 } 15243 return; 15244 15245 case 'J': 15246 if (Subtarget->isThumb1Only()) { 15247 // This must be a constant between -255 and -1, for negated ADD 15248 // immediates. This can be used in GCC with an "n" modifier that 15249 // prints the negated value, for use with SUB instructions. It is 15250 // not useful otherwise but is implemented for compatibility. 15251 if (CVal >= -255 && CVal <= -1) 15252 break; 15253 } else { 15254 // This must be a constant between -4095 and 4095. It is not clear 15255 // what this constraint is intended for. Implemented for 15256 // compatibility with GCC. 15257 if (CVal >= -4095 && CVal <= 4095) 15258 break; 15259 } 15260 return; 15261 15262 case 'K': 15263 if (Subtarget->isThumb1Only()) { 15264 // A 32-bit value where only one byte has a nonzero value. Exclude 15265 // zero to match GCC. This constraint is used by GCC internally for 15266 // constants that can be loaded with a move/shift combination. 15267 // It is not useful otherwise but is implemented for compatibility. 15268 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 15269 break; 15270 } else if (Subtarget->isThumb2()) { 15271 // A constant whose bitwise inverse can be used as an immediate 15272 // value in a data-processing instruction. This can be used in GCC 15273 // with a "B" modifier that prints the inverted value, for use with 15274 // BIC and MVN instructions. It is not useful otherwise but is 15275 // implemented for compatibility. 15276 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 15277 break; 15278 } else { 15279 // A constant whose bitwise inverse can be used as an immediate 15280 // value in a data-processing instruction. This can be used in GCC 15281 // with a "B" modifier that prints the inverted value, for use with 15282 // BIC and MVN instructions. It is not useful otherwise but is 15283 // implemented for compatibility. 15284 if (ARM_AM::getSOImmVal(~CVal) != -1) 15285 break; 15286 } 15287 return; 15288 15289 case 'L': 15290 if (Subtarget->isThumb1Only()) { 15291 // This must be a constant between -7 and 7, 15292 // for 3-operand ADD/SUB immediate instructions. 15293 if (CVal >= -7 && CVal < 7) 15294 break; 15295 } else if (Subtarget->isThumb2()) { 15296 // A constant whose negation can be used as an immediate value in a 15297 // data-processing instruction. This can be used in GCC with an "n" 15298 // modifier that prints the negated value, for use with SUB 15299 // instructions. It is not useful otherwise but is implemented for 15300 // compatibility. 15301 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 15302 break; 15303 } else { 15304 // A constant whose negation can be used as an immediate value in a 15305 // data-processing instruction. This can be used in GCC with an "n" 15306 // modifier that prints the negated value, for use with SUB 15307 // instructions. It is not useful otherwise but is implemented for 15308 // compatibility. 15309 if (ARM_AM::getSOImmVal(-CVal) != -1) 15310 break; 15311 } 15312 return; 15313 15314 case 'M': 15315 if (Subtarget->isThumb1Only()) { 15316 // This must be a multiple of 4 between 0 and 1020, for 15317 // ADD sp + immediate. 15318 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 15319 break; 15320 } else { 15321 // A power of two or a constant between 0 and 32. This is used in 15322 // GCC for the shift amount on shifted register operands, but it is 15323 // useful in general for any shift amounts. 15324 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 15325 break; 15326 } 15327 return; 15328 15329 case 'N': 15330 if (Subtarget->isThumb()) { // FIXME thumb2 15331 // This must be a constant between 0 and 31, for shift amounts. 15332 if (CVal >= 0 && CVal <= 31) 15333 break; 15334 } 15335 return; 15336 15337 case 'O': 15338 if (Subtarget->isThumb()) { // FIXME thumb2 15339 // This must be a multiple of 4 between -508 and 508, for 15340 // ADD/SUB sp = sp + immediate. 15341 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 15342 break; 15343 } 15344 return; 15345 } 15346 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 15347 break; 15348 } 15349 15350 if (Result.getNode()) { 15351 Ops.push_back(Result); 15352 return; 15353 } 15354 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15355 } 15356 15357 static RTLIB::Libcall getDivRemLibcall( 15358 const SDNode *N, MVT::SimpleValueType SVT) { 15359 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 15360 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 15361 "Unhandled Opcode in getDivRemLibcall"); 15362 bool isSigned = N->getOpcode() == ISD::SDIVREM || 15363 N->getOpcode() == ISD::SREM; 15364 RTLIB::Libcall LC; 15365 switch (SVT) { 15366 default: llvm_unreachable("Unexpected request for libcall!"); 15367 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 15368 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 15369 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 15370 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 15371 } 15372 return LC; 15373 } 15374 15375 static TargetLowering::ArgListTy getDivRemArgList( 15376 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 15377 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 15378 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 15379 "Unhandled Opcode in getDivRemArgList"); 15380 bool isSigned = N->getOpcode() == ISD::SDIVREM || 15381 N->getOpcode() == ISD::SREM; 15382 TargetLowering::ArgListTy Args; 15383 TargetLowering::ArgListEntry Entry; 15384 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15385 EVT ArgVT = N->getOperand(i).getValueType(); 15386 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 15387 Entry.Node = N->getOperand(i); 15388 Entry.Ty = ArgTy; 15389 Entry.IsSExt = isSigned; 15390 Entry.IsZExt = !isSigned; 15391 Args.push_back(Entry); 15392 } 15393 if (Subtarget->isTargetWindows() && Args.size() >= 2) 15394 std::swap(Args[0], Args[1]); 15395 return Args; 15396 } 15397 15398 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 15399 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 15400 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 15401 Subtarget->isTargetWindows()) && 15402 "Register-based DivRem lowering only"); 15403 unsigned Opcode = Op->getOpcode(); 15404 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 15405 "Invalid opcode for Div/Rem lowering"); 15406 bool isSigned = (Opcode == ISD::SDIVREM); 15407 EVT VT = Op->getValueType(0); 15408 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 15409 SDLoc dl(Op); 15410 15411 // If the target has hardware divide, use divide + multiply + subtract: 15412 // div = a / b 15413 // rem = a - b * div 15414 // return {div, rem} 15415 // This should be lowered into UDIV/SDIV + MLS later on. 15416 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 15417 : Subtarget->hasDivideInARMMode(); 15418 if (hasDivide && Op->getValueType(0).isSimple() && 15419 Op->getSimpleValueType(0) == MVT::i32) { 15420 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 15421 const SDValue Dividend = Op->getOperand(0); 15422 const SDValue Divisor = Op->getOperand(1); 15423 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 15424 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 15425 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 15426 15427 SDValue Values[2] = {Div, Rem}; 15428 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 15429 } 15430 15431 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 15432 VT.getSimpleVT().SimpleTy); 15433 SDValue InChain = DAG.getEntryNode(); 15434 15435 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 15436 DAG.getContext(), 15437 Subtarget); 15438 15439 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 15440 getPointerTy(DAG.getDataLayout())); 15441 15442 Type *RetTy = StructType::get(Ty, Ty); 15443 15444 if (Subtarget->isTargetWindows()) 15445 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 15446 15447 TargetLowering::CallLoweringInfo CLI(DAG); 15448 CLI.setDebugLoc(dl).setChain(InChain) 15449 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 15450 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 15451 15452 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 15453 return CallInfo.first; 15454 } 15455 15456 // Lowers REM using divmod helpers 15457 // see RTABI section 4.2/4.3 15458 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 15459 // Build return types (div and rem) 15460 std::vector<Type*> RetTyParams; 15461 Type *RetTyElement; 15462 15463 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 15464 default: llvm_unreachable("Unexpected request for libcall!"); 15465 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 15466 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 15467 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 15468 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 15469 } 15470 15471 RetTyParams.push_back(RetTyElement); 15472 RetTyParams.push_back(RetTyElement); 15473 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 15474 Type *RetTy = StructType::get(*DAG.getContext(), ret); 15475 15476 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 15477 SimpleTy); 15478 SDValue InChain = DAG.getEntryNode(); 15479 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 15480 Subtarget); 15481 bool isSigned = N->getOpcode() == ISD::SREM; 15482 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 15483 getPointerTy(DAG.getDataLayout())); 15484 15485 if (Subtarget->isTargetWindows()) 15486 InChain = WinDBZCheckDenominator(DAG, N, InChain); 15487 15488 // Lower call 15489 CallLoweringInfo CLI(DAG); 15490 CLI.setChain(InChain) 15491 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 15492 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 15493 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 15494 15495 // Return second (rem) result operand (first contains div) 15496 SDNode *ResNode = CallResult.first.getNode(); 15497 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 15498 return ResNode->getOperand(1); 15499 } 15500 15501 SDValue 15502 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 15503 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 15504 SDLoc DL(Op); 15505 15506 // Get the inputs. 15507 SDValue Chain = Op.getOperand(0); 15508 SDValue Size = Op.getOperand(1); 15509 15510 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 15511 "no-stack-arg-probe")) { 15512 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 15513 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 15514 Chain = SP.getValue(1); 15515 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 15516 if (Align) 15517 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 15518 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 15519 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 15520 SDValue Ops[2] = { SP, Chain }; 15521 return DAG.getMergeValues(Ops, DL); 15522 } 15523 15524 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 15525 DAG.getConstant(2, DL, MVT::i32)); 15526 15527 SDValue Flag; 15528 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 15529 Flag = Chain.getValue(1); 15530 15531 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 15532 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 15533 15534 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 15535 Chain = NewSP.getValue(1); 15536 15537 SDValue Ops[2] = { NewSP, Chain }; 15538 return DAG.getMergeValues(Ops, DL); 15539 } 15540 15541 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 15542 SDValue SrcVal = Op.getOperand(0); 15543 const unsigned DstSz = Op.getValueType().getSizeInBits(); 15544 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 15545 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 15546 "Unexpected type for custom-lowering FP_EXTEND"); 15547 15548 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 15549 "With both FP DP and 16, any FP conversion is legal!"); 15550 15551 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 15552 "With FP16, 16 to 32 conversion is legal!"); 15553 15554 // Either we are converting from 16 -> 64, without FP16 and/or 15555 // FP.double-precision or without Armv8-fp. So we must do it in two 15556 // steps. 15557 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 15558 // without FP16. So we must do a function call. 15559 SDLoc Loc(Op); 15560 RTLIB::Libcall LC; 15561 if (SrcSz == 16) { 15562 // Instruction from 16 -> 32 15563 if (Subtarget->hasFP16()) 15564 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal); 15565 // Lib call from 16 -> 32 15566 else { 15567 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32); 15568 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15569 "Unexpected type for custom-lowering FP_EXTEND"); 15570 SrcVal = 15571 makeLibCall(DAG, LC, MVT::f32, SrcVal, /*isSigned*/ false, Loc).first; 15572 } 15573 } 15574 15575 if (DstSz != 64) 15576 return SrcVal; 15577 // For sure now SrcVal is 32 bits 15578 if (Subtarget->hasFP64()) // Instruction from 32 -> 64 15579 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal); 15580 15581 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64); 15582 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15583 "Unexpected type for custom-lowering FP_EXTEND"); 15584 return makeLibCall(DAG, LC, MVT::f64, SrcVal, /*isSigned*/ false, Loc).first; 15585 } 15586 15587 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 15588 SDValue SrcVal = Op.getOperand(0); 15589 EVT SrcVT = SrcVal.getValueType(); 15590 EVT DstVT = Op.getValueType(); 15591 const unsigned DstSz = Op.getValueType().getSizeInBits(); 15592 const unsigned SrcSz = SrcVT.getSizeInBits(); 15593 (void)DstSz; 15594 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 15595 "Unexpected type for custom-lowering FP_ROUND"); 15596 15597 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 15598 "With both FP DP and 16, any FP conversion is legal!"); 15599 15600 SDLoc Loc(Op); 15601 15602 // Instruction from 32 -> 16 if hasFP16 is valid 15603 if (SrcSz == 32 && Subtarget->hasFP16()) 15604 return Op; 15605 15606 // Lib call from 32 -> 16 / 64 -> [32, 16] 15607 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 15608 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15609 "Unexpected type for custom-lowering FP_ROUND"); 15610 return makeLibCall(DAG, LC, DstVT, SrcVal, /*isSigned*/ false, Loc).first; 15611 } 15612 15613 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 15614 SelectionDAG &DAG) const { 15615 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 15616 MVT HalfT = MVT::i32; 15617 SDLoc dl(N); 15618 SDValue Hi, Lo, Tmp; 15619 15620 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 15621 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 15622 return ; 15623 15624 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 15625 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 15626 15627 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 15628 DAG.getConstant(0, dl, HalfT)); 15629 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 15630 DAG.getConstant(1, dl, HalfT)); 15631 15632 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 15633 DAG.getConstant(OpTypeBits - 1, dl, 15634 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 15635 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 15636 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 15637 SDValue(Lo.getNode(), 1)); 15638 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 15639 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 15640 15641 Results.push_back(Lo); 15642 Results.push_back(Hi); 15643 } 15644 15645 bool 15646 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15647 // The ARM target isn't yet aware of offsets. 15648 return false; 15649 } 15650 15651 bool ARM::isBitFieldInvertedMask(unsigned v) { 15652 if (v == 0xffffffff) 15653 return false; 15654 15655 // there can be 1's on either or both "outsides", all the "inside" 15656 // bits must be 0's 15657 return isShiftedMask_32(~v); 15658 } 15659 15660 /// isFPImmLegal - Returns true if the target can instruction select the 15661 /// specified FP immediate natively. If false, the legalizer will 15662 /// materialize the FP immediate as a load from a constant pool. 15663 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15664 bool ForCodeSize) const { 15665 if (!Subtarget->hasVFP3Base()) 15666 return false; 15667 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 15668 return ARM_AM::getFP16Imm(Imm) != -1; 15669 if (VT == MVT::f32) 15670 return ARM_AM::getFP32Imm(Imm) != -1; 15671 if (VT == MVT::f64 && Subtarget->hasFP64()) 15672 return ARM_AM::getFP64Imm(Imm) != -1; 15673 return false; 15674 } 15675 15676 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 15677 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 15678 /// specified in the intrinsic calls. 15679 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15680 const CallInst &I, 15681 MachineFunction &MF, 15682 unsigned Intrinsic) const { 15683 switch (Intrinsic) { 15684 case Intrinsic::arm_neon_vld1: 15685 case Intrinsic::arm_neon_vld2: 15686 case Intrinsic::arm_neon_vld3: 15687 case Intrinsic::arm_neon_vld4: 15688 case Intrinsic::arm_neon_vld2lane: 15689 case Intrinsic::arm_neon_vld3lane: 15690 case Intrinsic::arm_neon_vld4lane: 15691 case Intrinsic::arm_neon_vld2dup: 15692 case Intrinsic::arm_neon_vld3dup: 15693 case Intrinsic::arm_neon_vld4dup: { 15694 Info.opc = ISD::INTRINSIC_W_CHAIN; 15695 // Conservatively set memVT to the entire set of vectors loaded. 15696 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15697 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 15698 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15699 Info.ptrVal = I.getArgOperand(0); 15700 Info.offset = 0; 15701 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 15702 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 15703 // volatile loads with NEON intrinsics not supported 15704 Info.flags = MachineMemOperand::MOLoad; 15705 return true; 15706 } 15707 case Intrinsic::arm_neon_vld1x2: 15708 case Intrinsic::arm_neon_vld1x3: 15709 case Intrinsic::arm_neon_vld1x4: { 15710 Info.opc = ISD::INTRINSIC_W_CHAIN; 15711 // Conservatively set memVT to the entire set of vectors loaded. 15712 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15713 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 15714 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15715 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 15716 Info.offset = 0; 15717 Info.align.reset(); 15718 // volatile loads with NEON intrinsics not supported 15719 Info.flags = MachineMemOperand::MOLoad; 15720 return true; 15721 } 15722 case Intrinsic::arm_neon_vst1: 15723 case Intrinsic::arm_neon_vst2: 15724 case Intrinsic::arm_neon_vst3: 15725 case Intrinsic::arm_neon_vst4: 15726 case Intrinsic::arm_neon_vst2lane: 15727 case Intrinsic::arm_neon_vst3lane: 15728 case Intrinsic::arm_neon_vst4lane: { 15729 Info.opc = ISD::INTRINSIC_VOID; 15730 // Conservatively set memVT to the entire set of vectors stored. 15731 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15732 unsigned NumElts = 0; 15733 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 15734 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 15735 if (!ArgTy->isVectorTy()) 15736 break; 15737 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 15738 } 15739 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15740 Info.ptrVal = I.getArgOperand(0); 15741 Info.offset = 0; 15742 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 15743 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 15744 // volatile stores with NEON intrinsics not supported 15745 Info.flags = MachineMemOperand::MOStore; 15746 return true; 15747 } 15748 case Intrinsic::arm_neon_vst1x2: 15749 case Intrinsic::arm_neon_vst1x3: 15750 case Intrinsic::arm_neon_vst1x4: { 15751 Info.opc = ISD::INTRINSIC_VOID; 15752 // Conservatively set memVT to the entire set of vectors stored. 15753 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15754 unsigned NumElts = 0; 15755 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 15756 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 15757 if (!ArgTy->isVectorTy()) 15758 break; 15759 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 15760 } 15761 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15762 Info.ptrVal = I.getArgOperand(0); 15763 Info.offset = 0; 15764 Info.align.reset(); 15765 // volatile stores with NEON intrinsics not supported 15766 Info.flags = MachineMemOperand::MOStore; 15767 return true; 15768 } 15769 case Intrinsic::arm_ldaex: 15770 case Intrinsic::arm_ldrex: { 15771 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15772 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 15773 Info.opc = ISD::INTRINSIC_W_CHAIN; 15774 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15775 Info.ptrVal = I.getArgOperand(0); 15776 Info.offset = 0; 15777 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 15778 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15779 return true; 15780 } 15781 case Intrinsic::arm_stlex: 15782 case Intrinsic::arm_strex: { 15783 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15784 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 15785 Info.opc = ISD::INTRINSIC_W_CHAIN; 15786 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15787 Info.ptrVal = I.getArgOperand(1); 15788 Info.offset = 0; 15789 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 15790 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15791 return true; 15792 } 15793 case Intrinsic::arm_stlexd: 15794 case Intrinsic::arm_strexd: 15795 Info.opc = ISD::INTRINSIC_W_CHAIN; 15796 Info.memVT = MVT::i64; 15797 Info.ptrVal = I.getArgOperand(2); 15798 Info.offset = 0; 15799 Info.align = Align(8); 15800 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15801 return true; 15802 15803 case Intrinsic::arm_ldaexd: 15804 case Intrinsic::arm_ldrexd: 15805 Info.opc = ISD::INTRINSIC_W_CHAIN; 15806 Info.memVT = MVT::i64; 15807 Info.ptrVal = I.getArgOperand(0); 15808 Info.offset = 0; 15809 Info.align = Align(8); 15810 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15811 return true; 15812 15813 default: 15814 break; 15815 } 15816 15817 return false; 15818 } 15819 15820 /// Returns true if it is beneficial to convert a load of a constant 15821 /// to just the constant itself. 15822 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15823 Type *Ty) const { 15824 assert(Ty->isIntegerTy()); 15825 15826 unsigned Bits = Ty->getPrimitiveSizeInBits(); 15827 if (Bits == 0 || Bits > 32) 15828 return false; 15829 return true; 15830 } 15831 15832 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 15833 unsigned Index) const { 15834 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 15835 return false; 15836 15837 return (Index == 0 || Index == ResVT.getVectorNumElements()); 15838 } 15839 15840 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 15841 ARM_MB::MemBOpt Domain) const { 15842 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15843 15844 // First, if the target has no DMB, see what fallback we can use. 15845 if (!Subtarget->hasDataBarrier()) { 15846 // Some ARMv6 cpus can support data barriers with an mcr instruction. 15847 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 15848 // here. 15849 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 15850 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 15851 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 15852 Builder.getInt32(0), Builder.getInt32(7), 15853 Builder.getInt32(10), Builder.getInt32(5)}; 15854 return Builder.CreateCall(MCR, args); 15855 } else { 15856 // Instead of using barriers, atomic accesses on these subtargets use 15857 // libcalls. 15858 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 15859 } 15860 } else { 15861 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 15862 // Only a full system barrier exists in the M-class architectures. 15863 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 15864 Constant *CDomain = Builder.getInt32(Domain); 15865 return Builder.CreateCall(DMB, CDomain); 15866 } 15867 } 15868 15869 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 15870 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 15871 Instruction *Inst, 15872 AtomicOrdering Ord) const { 15873 switch (Ord) { 15874 case AtomicOrdering::NotAtomic: 15875 case AtomicOrdering::Unordered: 15876 llvm_unreachable("Invalid fence: unordered/non-atomic"); 15877 case AtomicOrdering::Monotonic: 15878 case AtomicOrdering::Acquire: 15879 return nullptr; // Nothing to do 15880 case AtomicOrdering::SequentiallyConsistent: 15881 if (!Inst->hasAtomicStore()) 15882 return nullptr; // Nothing to do 15883 LLVM_FALLTHROUGH; 15884 case AtomicOrdering::Release: 15885 case AtomicOrdering::AcquireRelease: 15886 if (Subtarget->preferISHSTBarriers()) 15887 return makeDMB(Builder, ARM_MB::ISHST); 15888 // FIXME: add a comment with a link to documentation justifying this. 15889 else 15890 return makeDMB(Builder, ARM_MB::ISH); 15891 } 15892 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 15893 } 15894 15895 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 15896 Instruction *Inst, 15897 AtomicOrdering Ord) const { 15898 switch (Ord) { 15899 case AtomicOrdering::NotAtomic: 15900 case AtomicOrdering::Unordered: 15901 llvm_unreachable("Invalid fence: unordered/not-atomic"); 15902 case AtomicOrdering::Monotonic: 15903 case AtomicOrdering::Release: 15904 return nullptr; // Nothing to do 15905 case AtomicOrdering::Acquire: 15906 case AtomicOrdering::AcquireRelease: 15907 case AtomicOrdering::SequentiallyConsistent: 15908 return makeDMB(Builder, ARM_MB::ISH); 15909 } 15910 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 15911 } 15912 15913 // Loads and stores less than 64-bits are already atomic; ones above that 15914 // are doomed anyway, so defer to the default libcall and blame the OS when 15915 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15916 // anything for those. 15917 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 15918 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 15919 return (Size == 64) && !Subtarget->isMClass(); 15920 } 15921 15922 // Loads and stores less than 64-bits are already atomic; ones above that 15923 // are doomed anyway, so defer to the default libcall and blame the OS when 15924 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15925 // anything for those. 15926 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 15927 // guarantee, see DDI0406C ARM architecture reference manual, 15928 // sections A8.8.72-74 LDRD) 15929 TargetLowering::AtomicExpansionKind 15930 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 15931 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 15932 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 15933 : AtomicExpansionKind::None; 15934 } 15935 15936 // For the real atomic operations, we have ldrex/strex up to 32 bits, 15937 // and up to 64 bits on the non-M profiles 15938 TargetLowering::AtomicExpansionKind 15939 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 15940 if (AI->isFloatingPointOperation()) 15941 return AtomicExpansionKind::CmpXChg; 15942 15943 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 15944 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 15945 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 15946 ? AtomicExpansionKind::LLSC 15947 : AtomicExpansionKind::None; 15948 } 15949 15950 TargetLowering::AtomicExpansionKind 15951 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 15952 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 15953 // implement cmpxchg without spilling. If the address being exchanged is also 15954 // on the stack and close enough to the spill slot, this can lead to a 15955 // situation where the monitor always gets cleared and the atomic operation 15956 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 15957 bool HasAtomicCmpXchg = 15958 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 15959 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 15960 return AtomicExpansionKind::LLSC; 15961 return AtomicExpansionKind::None; 15962 } 15963 15964 bool ARMTargetLowering::shouldInsertFencesForAtomic( 15965 const Instruction *I) const { 15966 return InsertFencesForAtomic; 15967 } 15968 15969 // This has so far only been implemented for MachO. 15970 bool ARMTargetLowering::useLoadStackGuardNode() const { 15971 return Subtarget->isTargetMachO(); 15972 } 15973 15974 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 15975 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 15976 return TargetLowering::insertSSPDeclarations(M); 15977 15978 // MSVC CRT has a global variable holding security cookie. 15979 M.getOrInsertGlobal("__security_cookie", 15980 Type::getInt8PtrTy(M.getContext())); 15981 15982 // MSVC CRT has a function to validate security cookie. 15983 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 15984 "__security_check_cookie", Type::getVoidTy(M.getContext()), 15985 Type::getInt8PtrTy(M.getContext())); 15986 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 15987 F->addAttribute(1, Attribute::AttrKind::InReg); 15988 } 15989 15990 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 15991 // MSVC CRT has a global variable holding security cookie. 15992 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 15993 return M.getGlobalVariable("__security_cookie"); 15994 return TargetLowering::getSDagStackGuard(M); 15995 } 15996 15997 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 15998 // MSVC CRT has a function to validate security cookie. 15999 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16000 return M.getFunction("__security_check_cookie"); 16001 return TargetLowering::getSSPStackGuardCheck(M); 16002 } 16003 16004 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 16005 unsigned &Cost) const { 16006 // If we do not have NEON, vector types are not natively supported. 16007 if (!Subtarget->hasNEON()) 16008 return false; 16009 16010 // Floating point values and vector values map to the same register file. 16011 // Therefore, although we could do a store extract of a vector type, this is 16012 // better to leave at float as we have more freedom in the addressing mode for 16013 // those. 16014 if (VectorTy->isFPOrFPVectorTy()) 16015 return false; 16016 16017 // If the index is unknown at compile time, this is very expensive to lower 16018 // and it is not possible to combine the store with the extract. 16019 if (!isa<ConstantInt>(Idx)) 16020 return false; 16021 16022 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 16023 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 16024 // We can do a store + vector extract on any vector that fits perfectly in a D 16025 // or Q register. 16026 if (BitWidth == 64 || BitWidth == 128) { 16027 Cost = 0; 16028 return true; 16029 } 16030 return false; 16031 } 16032 16033 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 16034 return Subtarget->hasV6T2Ops(); 16035 } 16036 16037 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 16038 return Subtarget->hasV6T2Ops(); 16039 } 16040 16041 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 16042 return !Subtarget->hasMinSize(); 16043 } 16044 16045 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 16046 AtomicOrdering Ord) const { 16047 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16048 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 16049 bool IsAcquire = isAcquireOrStronger(Ord); 16050 16051 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 16052 // intrinsic must return {i32, i32} and we have to recombine them into a 16053 // single i64 here. 16054 if (ValTy->getPrimitiveSizeInBits() == 64) { 16055 Intrinsic::ID Int = 16056 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 16057 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 16058 16059 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16060 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 16061 16062 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 16063 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 16064 if (!Subtarget->isLittle()) 16065 std::swap (Lo, Hi); 16066 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 16067 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 16068 return Builder.CreateOr( 16069 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 16070 } 16071 16072 Type *Tys[] = { Addr->getType() }; 16073 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 16074 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 16075 16076 return Builder.CreateTruncOrBitCast( 16077 Builder.CreateCall(Ldrex, Addr), 16078 cast<PointerType>(Addr->getType())->getElementType()); 16079 } 16080 16081 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 16082 IRBuilder<> &Builder) const { 16083 if (!Subtarget->hasV7Ops()) 16084 return; 16085 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16086 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 16087 } 16088 16089 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 16090 Value *Addr, 16091 AtomicOrdering Ord) const { 16092 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16093 bool IsRelease = isReleaseOrStronger(Ord); 16094 16095 // Since the intrinsics must have legal type, the i64 intrinsics take two 16096 // parameters: "i32, i32". We must marshal Val into the appropriate form 16097 // before the call. 16098 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 16099 Intrinsic::ID Int = 16100 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 16101 Function *Strex = Intrinsic::getDeclaration(M, Int); 16102 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 16103 16104 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 16105 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 16106 if (!Subtarget->isLittle()) 16107 std::swap(Lo, Hi); 16108 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16109 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 16110 } 16111 16112 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 16113 Type *Tys[] = { Addr->getType() }; 16114 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 16115 16116 return Builder.CreateCall( 16117 Strex, {Builder.CreateZExtOrBitCast( 16118 Val, Strex->getFunctionType()->getParamType(0)), 16119 Addr}); 16120 } 16121 16122 16123 bool ARMTargetLowering::alignLoopsWithOptSize() const { 16124 return Subtarget->isMClass(); 16125 } 16126 16127 /// A helper function for determining the number of interleaved accesses we 16128 /// will generate when lowering accesses of the given type. 16129 unsigned 16130 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 16131 const DataLayout &DL) const { 16132 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 16133 } 16134 16135 bool ARMTargetLowering::isLegalInterleavedAccessType( 16136 VectorType *VecTy, const DataLayout &DL) const { 16137 16138 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 16139 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 16140 16141 // Ensure the vector doesn't have f16 elements. Even though we could do an 16142 // i16 vldN, we can't hold the f16 vectors and will end up converting via 16143 // f32. 16144 if (VecTy->getElementType()->isHalfTy()) 16145 return false; 16146 16147 // Ensure the number of vector elements is greater than 1. 16148 if (VecTy->getNumElements() < 2) 16149 return false; 16150 16151 // Ensure the element type is legal. 16152 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 16153 return false; 16154 16155 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 16156 // 128 will be split into multiple interleaved accesses. 16157 return VecSize == 64 || VecSize % 128 == 0; 16158 } 16159 16160 /// Lower an interleaved load into a vldN intrinsic. 16161 /// 16162 /// E.g. Lower an interleaved load (Factor = 2): 16163 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 16164 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 16165 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 16166 /// 16167 /// Into: 16168 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 16169 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 16170 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 16171 bool ARMTargetLowering::lowerInterleavedLoad( 16172 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 16173 ArrayRef<unsigned> Indices, unsigned Factor) const { 16174 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 16175 "Invalid interleave factor"); 16176 assert(!Shuffles.empty() && "Empty shufflevector input"); 16177 assert(Shuffles.size() == Indices.size() && 16178 "Unmatched number of shufflevectors and indices"); 16179 16180 VectorType *VecTy = Shuffles[0]->getType(); 16181 Type *EltTy = VecTy->getVectorElementType(); 16182 16183 const DataLayout &DL = LI->getModule()->getDataLayout(); 16184 16185 // Skip if we do not have NEON and skip illegal vector types. We can 16186 // "legalize" wide vector types into multiple interleaved accesses as long as 16187 // the vector types are divisible by 128. 16188 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 16189 return false; 16190 16191 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 16192 16193 // A pointer vector can not be the return type of the ldN intrinsics. Need to 16194 // load integer vectors first and then convert to pointer vectors. 16195 if (EltTy->isPointerTy()) 16196 VecTy = 16197 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 16198 16199 IRBuilder<> Builder(LI); 16200 16201 // The base address of the load. 16202 Value *BaseAddr = LI->getPointerOperand(); 16203 16204 if (NumLoads > 1) { 16205 // If we're going to generate more than one load, reset the sub-vector type 16206 // to something legal. 16207 VecTy = VectorType::get(VecTy->getVectorElementType(), 16208 VecTy->getVectorNumElements() / NumLoads); 16209 16210 // We will compute the pointer operand of each load from the original base 16211 // address using GEPs. Cast the base address to a pointer to the scalar 16212 // element type. 16213 BaseAddr = Builder.CreateBitCast( 16214 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 16215 LI->getPointerAddressSpace())); 16216 } 16217 16218 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 16219 16220 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 16221 Type *Tys[] = {VecTy, Int8Ptr}; 16222 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 16223 Intrinsic::arm_neon_vld3, 16224 Intrinsic::arm_neon_vld4}; 16225 Function *VldnFunc = 16226 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 16227 16228 // Holds sub-vectors extracted from the load intrinsic return values. The 16229 // sub-vectors are associated with the shufflevector instructions they will 16230 // replace. 16231 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 16232 16233 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 16234 // If we're generating more than one load, compute the base address of 16235 // subsequent loads as an offset from the previous. 16236 if (LoadCount > 0) 16237 BaseAddr = 16238 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 16239 VecTy->getVectorNumElements() * Factor); 16240 16241 SmallVector<Value *, 2> Ops; 16242 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 16243 Ops.push_back(Builder.getInt32(LI->getAlignment())); 16244 16245 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 16246 16247 // Replace uses of each shufflevector with the corresponding vector loaded 16248 // by ldN. 16249 for (unsigned i = 0; i < Shuffles.size(); i++) { 16250 ShuffleVectorInst *SV = Shuffles[i]; 16251 unsigned Index = Indices[i]; 16252 16253 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 16254 16255 // Convert the integer vector to pointer vector if the element is pointer. 16256 if (EltTy->isPointerTy()) 16257 SubVec = Builder.CreateIntToPtr( 16258 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 16259 VecTy->getVectorNumElements())); 16260 16261 SubVecs[SV].push_back(SubVec); 16262 } 16263 } 16264 16265 // Replace uses of the shufflevector instructions with the sub-vectors 16266 // returned by the load intrinsic. If a shufflevector instruction is 16267 // associated with more than one sub-vector, those sub-vectors will be 16268 // concatenated into a single wide vector. 16269 for (ShuffleVectorInst *SVI : Shuffles) { 16270 auto &SubVec = SubVecs[SVI]; 16271 auto *WideVec = 16272 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 16273 SVI->replaceAllUsesWith(WideVec); 16274 } 16275 16276 return true; 16277 } 16278 16279 /// Lower an interleaved store into a vstN intrinsic. 16280 /// 16281 /// E.g. Lower an interleaved store (Factor = 3): 16282 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 16283 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 16284 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 16285 /// 16286 /// Into: 16287 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 16288 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 16289 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 16290 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 16291 /// 16292 /// Note that the new shufflevectors will be removed and we'll only generate one 16293 /// vst3 instruction in CodeGen. 16294 /// 16295 /// Example for a more general valid mask (Factor 3). Lower: 16296 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 16297 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 16298 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 16299 /// 16300 /// Into: 16301 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 16302 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 16303 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 16304 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 16305 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 16306 ShuffleVectorInst *SVI, 16307 unsigned Factor) const { 16308 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 16309 "Invalid interleave factor"); 16310 16311 VectorType *VecTy = SVI->getType(); 16312 assert(VecTy->getVectorNumElements() % Factor == 0 && 16313 "Invalid interleaved store"); 16314 16315 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 16316 Type *EltTy = VecTy->getVectorElementType(); 16317 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 16318 16319 const DataLayout &DL = SI->getModule()->getDataLayout(); 16320 16321 // Skip if we do not have NEON and skip illegal vector types. We can 16322 // "legalize" wide vector types into multiple interleaved accesses as long as 16323 // the vector types are divisible by 128. 16324 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 16325 return false; 16326 16327 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 16328 16329 Value *Op0 = SVI->getOperand(0); 16330 Value *Op1 = SVI->getOperand(1); 16331 IRBuilder<> Builder(SI); 16332 16333 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 16334 // vectors to integer vectors. 16335 if (EltTy->isPointerTy()) { 16336 Type *IntTy = DL.getIntPtrType(EltTy); 16337 16338 // Convert to the corresponding integer vector. 16339 Type *IntVecTy = 16340 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 16341 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 16342 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 16343 16344 SubVecTy = VectorType::get(IntTy, LaneLen); 16345 } 16346 16347 // The base address of the store. 16348 Value *BaseAddr = SI->getPointerOperand(); 16349 16350 if (NumStores > 1) { 16351 // If we're going to generate more than one store, reset the lane length 16352 // and sub-vector type to something legal. 16353 LaneLen /= NumStores; 16354 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 16355 16356 // We will compute the pointer operand of each store from the original base 16357 // address using GEPs. Cast the base address to a pointer to the scalar 16358 // element type. 16359 BaseAddr = Builder.CreateBitCast( 16360 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 16361 SI->getPointerAddressSpace())); 16362 } 16363 16364 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 16365 16366 auto Mask = SVI->getShuffleMask(); 16367 16368 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 16369 Type *Tys[] = {Int8Ptr, SubVecTy}; 16370 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 16371 Intrinsic::arm_neon_vst3, 16372 Intrinsic::arm_neon_vst4}; 16373 16374 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 16375 // If we generating more than one store, we compute the base address of 16376 // subsequent stores as an offset from the previous. 16377 if (StoreCount > 0) 16378 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 16379 BaseAddr, LaneLen * Factor); 16380 16381 SmallVector<Value *, 6> Ops; 16382 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 16383 16384 Function *VstNFunc = 16385 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 16386 16387 // Split the shufflevector operands into sub vectors for the new vstN call. 16388 for (unsigned i = 0; i < Factor; i++) { 16389 unsigned IdxI = StoreCount * LaneLen * Factor + i; 16390 if (Mask[IdxI] >= 0) { 16391 Ops.push_back(Builder.CreateShuffleVector( 16392 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 16393 } else { 16394 unsigned StartMask = 0; 16395 for (unsigned j = 1; j < LaneLen; j++) { 16396 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 16397 if (Mask[IdxJ * Factor + IdxI] >= 0) { 16398 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 16399 break; 16400 } 16401 } 16402 // Note: If all elements in a chunk are undefs, StartMask=0! 16403 // Note: Filling undef gaps with random elements is ok, since 16404 // those elements were being written anyway (with undefs). 16405 // In the case of all undefs we're defaulting to using elems from 0 16406 // Note: StartMask cannot be negative, it's checked in 16407 // isReInterleaveMask 16408 Ops.push_back(Builder.CreateShuffleVector( 16409 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 16410 } 16411 } 16412 16413 Ops.push_back(Builder.getInt32(SI->getAlignment())); 16414 Builder.CreateCall(VstNFunc, Ops); 16415 } 16416 return true; 16417 } 16418 16419 enum HABaseType { 16420 HA_UNKNOWN = 0, 16421 HA_FLOAT, 16422 HA_DOUBLE, 16423 HA_VECT64, 16424 HA_VECT128 16425 }; 16426 16427 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 16428 uint64_t &Members) { 16429 if (auto *ST = dyn_cast<StructType>(Ty)) { 16430 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 16431 uint64_t SubMembers = 0; 16432 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 16433 return false; 16434 Members += SubMembers; 16435 } 16436 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 16437 uint64_t SubMembers = 0; 16438 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 16439 return false; 16440 Members += SubMembers * AT->getNumElements(); 16441 } else if (Ty->isFloatTy()) { 16442 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 16443 return false; 16444 Members = 1; 16445 Base = HA_FLOAT; 16446 } else if (Ty->isDoubleTy()) { 16447 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 16448 return false; 16449 Members = 1; 16450 Base = HA_DOUBLE; 16451 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 16452 Members = 1; 16453 switch (Base) { 16454 case HA_FLOAT: 16455 case HA_DOUBLE: 16456 return false; 16457 case HA_VECT64: 16458 return VT->getBitWidth() == 64; 16459 case HA_VECT128: 16460 return VT->getBitWidth() == 128; 16461 case HA_UNKNOWN: 16462 switch (VT->getBitWidth()) { 16463 case 64: 16464 Base = HA_VECT64; 16465 return true; 16466 case 128: 16467 Base = HA_VECT128; 16468 return true; 16469 default: 16470 return false; 16471 } 16472 } 16473 } 16474 16475 return (Members > 0 && Members <= 4); 16476 } 16477 16478 /// Return the correct alignment for the current calling convention. 16479 unsigned 16480 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 16481 DataLayout DL) const { 16482 if (!ArgTy->isVectorTy()) 16483 return DL.getABITypeAlignment(ArgTy); 16484 16485 // Avoid over-aligning vector parameters. It would require realigning the 16486 // stack and waste space for no real benefit. 16487 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 16488 } 16489 16490 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 16491 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 16492 /// passing according to AAPCS rules. 16493 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 16494 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 16495 if (getEffectiveCallingConv(CallConv, isVarArg) != 16496 CallingConv::ARM_AAPCS_VFP) 16497 return false; 16498 16499 HABaseType Base = HA_UNKNOWN; 16500 uint64_t Members = 0; 16501 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 16502 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 16503 16504 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 16505 return IsHA || IsIntArray; 16506 } 16507 16508 unsigned ARMTargetLowering::getExceptionPointerRegister( 16509 const Constant *PersonalityFn) const { 16510 // Platforms which do not use SjLj EH may return values in these registers 16511 // via the personality function. 16512 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 16513 } 16514 16515 unsigned ARMTargetLowering::getExceptionSelectorRegister( 16516 const Constant *PersonalityFn) const { 16517 // Platforms which do not use SjLj EH may return values in these registers 16518 // via the personality function. 16519 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 16520 } 16521 16522 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 16523 // Update IsSplitCSR in ARMFunctionInfo. 16524 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 16525 AFI->setIsSplitCSR(true); 16526 } 16527 16528 void ARMTargetLowering::insertCopiesSplitCSR( 16529 MachineBasicBlock *Entry, 16530 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 16531 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 16532 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 16533 if (!IStart) 16534 return; 16535 16536 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 16537 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 16538 MachineBasicBlock::iterator MBBI = Entry->begin(); 16539 for (const MCPhysReg *I = IStart; *I; ++I) { 16540 const TargetRegisterClass *RC = nullptr; 16541 if (ARM::GPRRegClass.contains(*I)) 16542 RC = &ARM::GPRRegClass; 16543 else if (ARM::DPRRegClass.contains(*I)) 16544 RC = &ARM::DPRRegClass; 16545 else 16546 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 16547 16548 unsigned NewVR = MRI->createVirtualRegister(RC); 16549 // Create copy from CSR to a virtual register. 16550 // FIXME: this currently does not emit CFI pseudo-instructions, it works 16551 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 16552 // nounwind. If we want to generalize this later, we may need to emit 16553 // CFI pseudo-instructions. 16554 assert(Entry->getParent()->getFunction().hasFnAttribute( 16555 Attribute::NoUnwind) && 16556 "Function should be nounwind in insertCopiesSplitCSR!"); 16557 Entry->addLiveIn(*I); 16558 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 16559 .addReg(*I); 16560 16561 // Insert the copy-back instructions right before the terminator. 16562 for (auto *Exit : Exits) 16563 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 16564 TII->get(TargetOpcode::COPY), *I) 16565 .addReg(NewVR); 16566 } 16567 } 16568 16569 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 16570 MF.getFrameInfo().computeMaxCallFrameSize(MF); 16571 TargetLoweringBase::finalizeLowering(MF); 16572 } 16573