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 262 // No native support for these. 263 setOperationAction(ISD::UDIV, VT, Expand); 264 setOperationAction(ISD::SDIV, VT, Expand); 265 setOperationAction(ISD::UREM, VT, Expand); 266 setOperationAction(ISD::SREM, VT, Expand); 267 268 if (!HasMVEFP) { 269 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 270 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 271 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 272 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 273 } 274 } 275 276 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 277 for (auto VT : FloatTypes) { 278 addRegisterClass(VT, &ARM::QPRRegClass); 279 if (!HasMVEFP) 280 setAllExpand(VT); 281 282 // These are legal or custom whether we have MVE.fp or not 283 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 284 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 285 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 286 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 287 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 288 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 289 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 290 291 if (HasMVEFP) { 292 setOperationAction(ISD::FMINNUM, VT, Legal); 293 setOperationAction(ISD::FMAXNUM, VT, Legal); 294 setOperationAction(ISD::FROUND, VT, Legal); 295 296 // No native support for these. 297 setOperationAction(ISD::FDIV, VT, Expand); 298 setOperationAction(ISD::FREM, VT, Expand); 299 setOperationAction(ISD::FSQRT, VT, Expand); 300 setOperationAction(ISD::FSIN, VT, Expand); 301 setOperationAction(ISD::FCOS, VT, Expand); 302 setOperationAction(ISD::FPOW, VT, Expand); 303 setOperationAction(ISD::FLOG, VT, Expand); 304 setOperationAction(ISD::FLOG2, VT, Expand); 305 setOperationAction(ISD::FLOG10, VT, Expand); 306 setOperationAction(ISD::FEXP, VT, Expand); 307 setOperationAction(ISD::FEXP2, VT, Expand); 308 setOperationAction(ISD::FNEARBYINT, VT, Expand); 309 } 310 } 311 312 // We 'support' these types up to bitcast/load/store level, regardless of 313 // MVE integer-only / float support. Only doing FP data processing on the FP 314 // vector types is inhibited at integer-only level. 315 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 316 for (auto VT : LongTypes) { 317 addRegisterClass(VT, &ARM::QPRRegClass); 318 setAllExpand(VT); 319 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 320 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 321 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 322 } 323 // We can do bitwise operations on v2i64 vectors 324 setOperationAction(ISD::AND, MVT::v2i64, Legal); 325 setOperationAction(ISD::OR, MVT::v2i64, Legal); 326 setOperationAction(ISD::XOR, MVT::v2i64, Legal); 327 328 // It is legal to extload from v4i8 to v4i16 or v4i32. 329 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 330 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 331 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 332 333 // Some truncating stores are legal too. 334 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 335 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 336 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 337 } 338 339 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 340 const ARMSubtarget &STI) 341 : TargetLowering(TM), Subtarget(&STI) { 342 RegInfo = Subtarget->getRegisterInfo(); 343 Itins = Subtarget->getInstrItineraryData(); 344 345 setBooleanContents(ZeroOrOneBooleanContent); 346 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 347 348 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 349 !Subtarget->isTargetWatchOS()) { 350 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 351 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 352 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 353 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 354 : CallingConv::ARM_AAPCS); 355 } 356 357 if (Subtarget->isTargetMachO()) { 358 // Uses VFP for Thumb libfuncs if available. 359 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 360 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 361 static const struct { 362 const RTLIB::Libcall Op; 363 const char * const Name; 364 const ISD::CondCode Cond; 365 } LibraryCalls[] = { 366 // Single-precision floating-point arithmetic. 367 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 368 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 369 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 370 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 371 372 // Double-precision floating-point arithmetic. 373 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 374 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 375 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 376 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 377 378 // Single-precision comparisons. 379 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 380 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 381 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 382 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 383 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 384 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 385 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 386 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 387 388 // Double-precision comparisons. 389 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 390 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 391 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 392 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 393 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 394 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 395 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 396 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 397 398 // Floating-point to integer conversions. 399 // i64 conversions are done via library routines even when generating VFP 400 // instructions, so use the same ones. 401 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 402 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 403 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 404 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 405 406 // Conversions between floating types. 407 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 408 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 409 410 // Integer to floating-point conversions. 411 // i64 conversions are done via library routines even when generating VFP 412 // instructions, so use the same ones. 413 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 414 // e.g., __floatunsidf vs. __floatunssidfvfp. 415 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 416 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 417 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 418 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 419 }; 420 421 for (const auto &LC : LibraryCalls) { 422 setLibcallName(LC.Op, LC.Name); 423 if (LC.Cond != ISD::SETCC_INVALID) 424 setCmpLibcallCC(LC.Op, LC.Cond); 425 } 426 } 427 } 428 429 // These libcalls are not available in 32-bit. 430 setLibcallName(RTLIB::SHL_I128, nullptr); 431 setLibcallName(RTLIB::SRL_I128, nullptr); 432 setLibcallName(RTLIB::SRA_I128, nullptr); 433 434 // RTLIB 435 if (Subtarget->isAAPCS_ABI() && 436 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 437 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 438 static const struct { 439 const RTLIB::Libcall Op; 440 const char * const Name; 441 const CallingConv::ID CC; 442 const ISD::CondCode Cond; 443 } LibraryCalls[] = { 444 // Double-precision floating-point arithmetic helper functions 445 // RTABI chapter 4.1.2, Table 2 446 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 447 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 448 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 449 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 450 451 // Double-precision floating-point comparison helper functions 452 // RTABI chapter 4.1.2, Table 3 453 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 454 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 455 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 456 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 457 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 458 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 459 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 460 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 461 462 // Single-precision floating-point arithmetic helper functions 463 // RTABI chapter 4.1.2, Table 4 464 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 465 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 466 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 467 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 468 469 // Single-precision floating-point comparison helper functions 470 // RTABI chapter 4.1.2, Table 5 471 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 472 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 473 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 474 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 475 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 476 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 477 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 478 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 479 480 // Floating-point to integer conversions. 481 // RTABI chapter 4.1.2, Table 6 482 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 483 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 484 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 485 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 486 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 487 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 488 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 489 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 490 491 // Conversions between floating types. 492 // RTABI chapter 4.1.2, Table 7 493 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 494 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 495 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 496 497 // Integer to floating-point conversions. 498 // RTABI chapter 4.1.2, Table 8 499 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 500 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 501 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 502 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 503 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 504 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 505 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 506 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 507 508 // Long long helper functions 509 // RTABI chapter 4.2, Table 9 510 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 511 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 512 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 513 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 514 515 // Integer division functions 516 // RTABI chapter 4.3.1 517 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 518 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 519 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 520 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 521 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 522 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 523 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 524 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 525 }; 526 527 for (const auto &LC : LibraryCalls) { 528 setLibcallName(LC.Op, LC.Name); 529 setLibcallCallingConv(LC.Op, LC.CC); 530 if (LC.Cond != ISD::SETCC_INVALID) 531 setCmpLibcallCC(LC.Op, LC.Cond); 532 } 533 534 // EABI dependent RTLIB 535 if (TM.Options.EABIVersion == EABI::EABI4 || 536 TM.Options.EABIVersion == EABI::EABI5) { 537 static const struct { 538 const RTLIB::Libcall Op; 539 const char *const Name; 540 const CallingConv::ID CC; 541 const ISD::CondCode Cond; 542 } MemOpsLibraryCalls[] = { 543 // Memory operations 544 // RTABI chapter 4.3.4 545 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 546 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 547 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 548 }; 549 550 for (const auto &LC : MemOpsLibraryCalls) { 551 setLibcallName(LC.Op, LC.Name); 552 setLibcallCallingConv(LC.Op, LC.CC); 553 if (LC.Cond != ISD::SETCC_INVALID) 554 setCmpLibcallCC(LC.Op, LC.Cond); 555 } 556 } 557 } 558 559 if (Subtarget->isTargetWindows()) { 560 static const struct { 561 const RTLIB::Libcall Op; 562 const char * const Name; 563 const CallingConv::ID CC; 564 } LibraryCalls[] = { 565 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 566 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 567 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 568 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 569 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 570 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 571 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 572 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 573 }; 574 575 for (const auto &LC : LibraryCalls) { 576 setLibcallName(LC.Op, LC.Name); 577 setLibcallCallingConv(LC.Op, LC.CC); 578 } 579 } 580 581 // Use divmod compiler-rt calls for iOS 5.0 and later. 582 if (Subtarget->isTargetMachO() && 583 !(Subtarget->isTargetIOS() && 584 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 585 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 586 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 587 } 588 589 // The half <-> float conversion functions are always soft-float on 590 // non-watchos platforms, but are needed for some targets which use a 591 // hard-float calling convention by default. 592 if (!Subtarget->isTargetWatchABI()) { 593 if (Subtarget->isAAPCS_ABI()) { 594 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 595 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 596 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 597 } else { 598 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 599 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 600 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 601 } 602 } 603 604 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 605 // a __gnu_ prefix (which is the default). 606 if (Subtarget->isTargetAEABI()) { 607 static const struct { 608 const RTLIB::Libcall Op; 609 const char * const Name; 610 const CallingConv::ID CC; 611 } LibraryCalls[] = { 612 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 613 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 614 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 615 }; 616 617 for (const auto &LC : LibraryCalls) { 618 setLibcallName(LC.Op, LC.Name); 619 setLibcallCallingConv(LC.Op, LC.CC); 620 } 621 } 622 623 if (Subtarget->isThumb1Only()) 624 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 625 else 626 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 627 628 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 629 Subtarget->hasFPRegs()) { 630 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 631 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 632 if (!Subtarget->hasVFP2Base()) 633 setAllExpand(MVT::f32); 634 if (!Subtarget->hasFP64()) 635 setAllExpand(MVT::f64); 636 } 637 638 if (Subtarget->hasFullFP16()) { 639 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 640 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 641 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 642 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 643 644 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 645 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 646 } 647 648 for (MVT VT : MVT::vector_valuetypes()) { 649 for (MVT InnerVT : MVT::vector_valuetypes()) { 650 setTruncStoreAction(VT, InnerVT, Expand); 651 addAllExtLoads(VT, InnerVT, Expand); 652 } 653 654 setOperationAction(ISD::MULHS, VT, Expand); 655 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 656 setOperationAction(ISD::MULHU, VT, Expand); 657 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 658 659 setOperationAction(ISD::BSWAP, VT, Expand); 660 } 661 662 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 663 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 664 665 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 666 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 667 668 if (Subtarget->hasMVEIntegerOps()) 669 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 670 671 // Combine low-overhead loop intrinsics so that we can lower i1 types. 672 if (Subtarget->hasLOB()) { 673 setTargetDAGCombine(ISD::BRCOND); 674 setTargetDAGCombine(ISD::BR_CC); 675 } 676 677 if (Subtarget->hasNEON()) { 678 addDRTypeForNEON(MVT::v2f32); 679 addDRTypeForNEON(MVT::v8i8); 680 addDRTypeForNEON(MVT::v4i16); 681 addDRTypeForNEON(MVT::v2i32); 682 addDRTypeForNEON(MVT::v1i64); 683 684 addQRTypeForNEON(MVT::v4f32); 685 addQRTypeForNEON(MVT::v2f64); 686 addQRTypeForNEON(MVT::v16i8); 687 addQRTypeForNEON(MVT::v8i16); 688 addQRTypeForNEON(MVT::v4i32); 689 addQRTypeForNEON(MVT::v2i64); 690 691 if (Subtarget->hasFullFP16()) { 692 addQRTypeForNEON(MVT::v8f16); 693 addDRTypeForNEON(MVT::v4f16); 694 } 695 } 696 697 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 698 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 699 // none of Neon, MVE or VFP supports any arithmetic operations on it. 700 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 701 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 702 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 703 // FIXME: Code duplication: FDIV and FREM are expanded always, see 704 // ARMTargetLowering::addTypeForNEON method for details. 705 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 706 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 707 // FIXME: Create unittest. 708 // In another words, find a way when "copysign" appears in DAG with vector 709 // operands. 710 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 711 // FIXME: Code duplication: SETCC has custom operation action, see 712 // ARMTargetLowering::addTypeForNEON method for details. 713 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 714 // FIXME: Create unittest for FNEG and for FABS. 715 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 716 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 717 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 718 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 719 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 720 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 721 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 722 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 723 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 724 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 725 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 726 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 727 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 728 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 729 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 730 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 731 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 732 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 733 } 734 735 if (Subtarget->hasNEON()) { 736 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 737 // supported for v4f32. 738 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 739 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 740 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 741 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 742 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 743 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 744 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 745 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 746 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 747 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 748 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 749 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 750 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 751 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 752 753 // Mark v2f32 intrinsics. 754 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 755 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 756 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 757 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 758 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 759 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 760 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 761 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 762 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 763 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 764 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 765 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 766 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 767 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 768 769 // Neon does not support some operations on v1i64 and v2i64 types. 770 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 771 // Custom handling for some quad-vector types to detect VMULL. 772 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 773 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 774 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 775 // Custom handling for some vector types to avoid expensive expansions 776 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 777 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 778 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 779 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 780 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 781 // a destination type that is wider than the source, and nor does 782 // it have a FP_TO_[SU]INT instruction with a narrower destination than 783 // source. 784 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 785 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 786 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 787 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 788 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 789 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 790 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 791 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 792 793 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 794 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 795 796 // NEON does not have single instruction CTPOP for vectors with element 797 // types wider than 8-bits. However, custom lowering can leverage the 798 // v8i8/v16i8 vcnt instruction. 799 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 800 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 801 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 802 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 803 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 804 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 805 806 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 807 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 808 809 // NEON does not have single instruction CTTZ for vectors. 810 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 811 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 812 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 813 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 814 815 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 816 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 817 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 818 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 819 820 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 821 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 822 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 823 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 824 825 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 826 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 827 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 828 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 829 830 // NEON only has FMA instructions as of VFP4. 831 if (!Subtarget->hasVFP4Base()) { 832 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 833 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 834 } 835 836 setTargetDAGCombine(ISD::INTRINSIC_VOID); 837 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 838 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 839 setTargetDAGCombine(ISD::SHL); 840 setTargetDAGCombine(ISD::SRL); 841 setTargetDAGCombine(ISD::SRA); 842 setTargetDAGCombine(ISD::SIGN_EXTEND); 843 setTargetDAGCombine(ISD::ZERO_EXTEND); 844 setTargetDAGCombine(ISD::ANY_EXTEND); 845 setTargetDAGCombine(ISD::STORE); 846 setTargetDAGCombine(ISD::FP_TO_SINT); 847 setTargetDAGCombine(ISD::FP_TO_UINT); 848 setTargetDAGCombine(ISD::FDIV); 849 setTargetDAGCombine(ISD::LOAD); 850 851 // It is legal to extload from v4i8 to v4i16 or v4i32. 852 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 853 MVT::v2i32}) { 854 for (MVT VT : MVT::integer_vector_valuetypes()) { 855 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 856 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 857 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 858 } 859 } 860 } 861 862 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 863 setTargetDAGCombine(ISD::BUILD_VECTOR); 864 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 865 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 866 } 867 868 if (!Subtarget->hasFP64()) { 869 // When targeting a floating-point unit with only single-precision 870 // operations, f64 is legal for the few double-precision instructions which 871 // are present However, no double-precision operations other than moves, 872 // loads and stores are provided by the hardware. 873 setOperationAction(ISD::FADD, MVT::f64, Expand); 874 setOperationAction(ISD::FSUB, MVT::f64, Expand); 875 setOperationAction(ISD::FMUL, MVT::f64, Expand); 876 setOperationAction(ISD::FMA, MVT::f64, Expand); 877 setOperationAction(ISD::FDIV, MVT::f64, Expand); 878 setOperationAction(ISD::FREM, MVT::f64, Expand); 879 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 880 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 881 setOperationAction(ISD::FNEG, MVT::f64, Expand); 882 setOperationAction(ISD::FABS, MVT::f64, Expand); 883 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 884 setOperationAction(ISD::FSIN, MVT::f64, Expand); 885 setOperationAction(ISD::FCOS, MVT::f64, Expand); 886 setOperationAction(ISD::FPOW, MVT::f64, Expand); 887 setOperationAction(ISD::FLOG, MVT::f64, Expand); 888 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 889 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 890 setOperationAction(ISD::FEXP, MVT::f64, Expand); 891 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 892 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 893 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 894 setOperationAction(ISD::FRINT, MVT::f64, Expand); 895 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 896 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 897 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 898 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 899 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 900 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 901 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 902 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 903 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 904 } 905 906 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()){ 907 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 908 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 909 } 910 911 if (!Subtarget->hasFP16()) 912 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 913 914 if (!Subtarget->hasFP64()) 915 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 916 917 computeRegisterProperties(Subtarget->getRegisterInfo()); 918 919 // ARM does not have floating-point extending loads. 920 for (MVT VT : MVT::fp_valuetypes()) { 921 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 922 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 923 } 924 925 // ... or truncating stores 926 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 927 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 928 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 929 930 // ARM does not have i1 sign extending load. 931 for (MVT VT : MVT::integer_valuetypes()) 932 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 933 934 // ARM supports all 4 flavors of integer indexed load / store. 935 if (!Subtarget->isThumb1Only()) { 936 for (unsigned im = (unsigned)ISD::PRE_INC; 937 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 938 setIndexedLoadAction(im, MVT::i1, Legal); 939 setIndexedLoadAction(im, MVT::i8, Legal); 940 setIndexedLoadAction(im, MVT::i16, Legal); 941 setIndexedLoadAction(im, MVT::i32, Legal); 942 setIndexedStoreAction(im, MVT::i1, Legal); 943 setIndexedStoreAction(im, MVT::i8, Legal); 944 setIndexedStoreAction(im, MVT::i16, Legal); 945 setIndexedStoreAction(im, MVT::i32, Legal); 946 } 947 } else { 948 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 949 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 950 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 951 } 952 953 setOperationAction(ISD::SADDO, MVT::i32, Custom); 954 setOperationAction(ISD::UADDO, MVT::i32, Custom); 955 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 956 setOperationAction(ISD::USUBO, MVT::i32, Custom); 957 958 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 959 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 960 961 // i64 operation support. 962 setOperationAction(ISD::MUL, MVT::i64, Expand); 963 setOperationAction(ISD::MULHU, MVT::i32, Expand); 964 if (Subtarget->isThumb1Only()) { 965 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 966 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 967 } 968 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 969 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 970 setOperationAction(ISD::MULHS, MVT::i32, Expand); 971 972 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 973 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 974 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 975 setOperationAction(ISD::SRL, MVT::i64, Custom); 976 setOperationAction(ISD::SRA, MVT::i64, Custom); 977 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 978 979 // MVE lowers 64 bit shifts to lsll and lsrl 980 // assuming that ISD::SRL and SRA of i64 are already marked custom 981 if (Subtarget->hasMVEIntegerOps()) 982 setOperationAction(ISD::SHL, MVT::i64, Custom); 983 984 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 985 if (Subtarget->isThumb1Only()) { 986 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 987 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 988 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 989 } 990 991 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 992 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 993 994 // ARM does not have ROTL. 995 setOperationAction(ISD::ROTL, MVT::i32, Expand); 996 for (MVT VT : MVT::vector_valuetypes()) { 997 setOperationAction(ISD::ROTL, VT, Expand); 998 setOperationAction(ISD::ROTR, VT, Expand); 999 } 1000 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1001 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1002 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1003 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1004 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1005 } 1006 1007 // @llvm.readcyclecounter requires the Performance Monitors extension. 1008 // Default to the 0 expansion on unsupported platforms. 1009 // FIXME: Technically there are older ARM CPUs that have 1010 // implementation-specific ways of obtaining this information. 1011 if (Subtarget->hasPerfMon()) 1012 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1013 1014 // Only ARMv6 has BSWAP. 1015 if (!Subtarget->hasV6Ops()) 1016 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1017 1018 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1019 : Subtarget->hasDivideInARMMode(); 1020 if (!hasDivide) { 1021 // These are expanded into libcalls if the cpu doesn't have HW divider. 1022 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1023 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1024 } 1025 1026 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1027 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1028 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1029 1030 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1031 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1032 } 1033 1034 setOperationAction(ISD::SREM, MVT::i32, Expand); 1035 setOperationAction(ISD::UREM, MVT::i32, Expand); 1036 1037 // Register based DivRem for AEABI (RTABI 4.2) 1038 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1039 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1040 Subtarget->isTargetWindows()) { 1041 setOperationAction(ISD::SREM, MVT::i64, Custom); 1042 setOperationAction(ISD::UREM, MVT::i64, Custom); 1043 HasStandaloneRem = false; 1044 1045 if (Subtarget->isTargetWindows()) { 1046 const struct { 1047 const RTLIB::Libcall Op; 1048 const char * const Name; 1049 const CallingConv::ID CC; 1050 } LibraryCalls[] = { 1051 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1052 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1053 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1054 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1055 1056 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1057 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1058 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1059 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1060 }; 1061 1062 for (const auto &LC : LibraryCalls) { 1063 setLibcallName(LC.Op, LC.Name); 1064 setLibcallCallingConv(LC.Op, LC.CC); 1065 } 1066 } else { 1067 const struct { 1068 const RTLIB::Libcall Op; 1069 const char * const Name; 1070 const CallingConv::ID CC; 1071 } LibraryCalls[] = { 1072 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1073 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1074 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1075 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1076 1077 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1078 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1079 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1080 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1081 }; 1082 1083 for (const auto &LC : LibraryCalls) { 1084 setLibcallName(LC.Op, LC.Name); 1085 setLibcallCallingConv(LC.Op, LC.CC); 1086 } 1087 } 1088 1089 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1090 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1091 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1092 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1093 } else { 1094 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1095 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1096 } 1097 1098 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 1099 for (auto &VT : {MVT::f32, MVT::f64}) 1100 setOperationAction(ISD::FPOWI, VT, Custom); 1101 1102 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1103 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1104 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1105 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1106 1107 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1108 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1109 1110 // Use the default implementation. 1111 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1112 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1113 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1114 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1115 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1116 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1117 1118 if (Subtarget->isTargetWindows()) 1119 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1120 else 1121 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1122 1123 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1124 // the default expansion. 1125 InsertFencesForAtomic = false; 1126 if (Subtarget->hasAnyDataBarrier() && 1127 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1128 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1129 // to ldrex/strex loops already. 1130 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1131 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1132 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1133 1134 // On v8, we have particularly efficient implementations of atomic fences 1135 // if they can be combined with nearby atomic loads and stores. 1136 if (!Subtarget->hasAcquireRelease() || 1137 getTargetMachine().getOptLevel() == 0) { 1138 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1139 InsertFencesForAtomic = true; 1140 } 1141 } else { 1142 // If there's anything we can use as a barrier, go through custom lowering 1143 // for ATOMIC_FENCE. 1144 // If target has DMB in thumb, Fences can be inserted. 1145 if (Subtarget->hasDataBarrier()) 1146 InsertFencesForAtomic = true; 1147 1148 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1149 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1150 1151 // Set them all for expansion, which will force libcalls. 1152 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1153 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1154 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1155 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1156 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1157 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1158 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1159 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1160 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1161 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1162 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1163 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1164 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1165 // Unordered/Monotonic case. 1166 if (!InsertFencesForAtomic) { 1167 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1168 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1169 } 1170 } 1171 1172 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1173 1174 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1175 if (!Subtarget->hasV6Ops()) { 1176 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1177 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1178 } 1179 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1180 1181 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1182 !Subtarget->isThumb1Only()) { 1183 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1184 // iff target supports vfp2. 1185 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1186 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1187 } 1188 1189 // We want to custom lower some of our intrinsics. 1190 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1191 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1192 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1193 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1194 if (Subtarget->useSjLjEH()) 1195 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1196 1197 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1198 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1199 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1200 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1201 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1202 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1203 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1204 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1205 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1206 if (Subtarget->hasFullFP16()) { 1207 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1208 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1209 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1210 } 1211 1212 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1213 1214 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1215 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1216 if (Subtarget->hasFullFP16()) 1217 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1218 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1219 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1220 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1221 1222 // We don't support sin/cos/fmod/copysign/pow 1223 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1224 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1225 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1226 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1227 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1228 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1229 setOperationAction(ISD::FREM, MVT::f64, Expand); 1230 setOperationAction(ISD::FREM, MVT::f32, Expand); 1231 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1232 !Subtarget->isThumb1Only()) { 1233 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1234 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1235 } 1236 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1237 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1238 1239 if (!Subtarget->hasVFP4Base()) { 1240 setOperationAction(ISD::FMA, MVT::f64, Expand); 1241 setOperationAction(ISD::FMA, MVT::f32, Expand); 1242 } 1243 1244 // Various VFP goodness 1245 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1246 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1247 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1248 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1249 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1250 } 1251 1252 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1253 if (!Subtarget->hasFP16()) { 1254 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1255 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1256 } 1257 } 1258 1259 // Use __sincos_stret if available. 1260 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1261 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1262 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1263 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1264 } 1265 1266 // FP-ARMv8 implements a lot of rounding-like FP operations. 1267 if (Subtarget->hasFPARMv8Base()) { 1268 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1269 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1270 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1271 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1272 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1273 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1274 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1275 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1276 if (Subtarget->hasNEON()) { 1277 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1278 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1279 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1280 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1281 } 1282 1283 if (Subtarget->hasFP64()) { 1284 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1285 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1286 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1287 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1288 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1289 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1290 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1291 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1292 } 1293 } 1294 1295 // FP16 often need to be promoted to call lib functions 1296 if (Subtarget->hasFullFP16()) { 1297 setOperationAction(ISD::FREM, MVT::f16, Promote); 1298 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1299 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1300 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1301 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1302 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1303 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1304 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1305 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1306 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1307 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1308 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1309 1310 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1311 } 1312 1313 if (Subtarget->hasNEON()) { 1314 // vmin and vmax aren't available in a scalar form, so we use 1315 // a NEON instruction with an undef lane instead. 1316 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1317 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1318 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1319 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1320 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1321 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1322 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1323 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1324 1325 if (Subtarget->hasFullFP16()) { 1326 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1327 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1328 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1329 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1330 1331 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1332 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1333 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1334 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1335 } 1336 } 1337 1338 // We have target-specific dag combine patterns for the following nodes: 1339 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1340 setTargetDAGCombine(ISD::ADD); 1341 setTargetDAGCombine(ISD::SUB); 1342 setTargetDAGCombine(ISD::MUL); 1343 setTargetDAGCombine(ISD::AND); 1344 setTargetDAGCombine(ISD::OR); 1345 setTargetDAGCombine(ISD::XOR); 1346 1347 if (Subtarget->hasV6Ops()) 1348 setTargetDAGCombine(ISD::SRL); 1349 if (Subtarget->isThumb1Only()) 1350 setTargetDAGCombine(ISD::SHL); 1351 1352 setStackPointerRegisterToSaveRestore(ARM::SP); 1353 1354 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1355 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1356 setSchedulingPreference(Sched::RegPressure); 1357 else 1358 setSchedulingPreference(Sched::Hybrid); 1359 1360 //// temporary - rewrite interface to use type 1361 MaxStoresPerMemset = 8; 1362 MaxStoresPerMemsetOptSize = 4; 1363 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1364 MaxStoresPerMemcpyOptSize = 2; 1365 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1366 MaxStoresPerMemmoveOptSize = 2; 1367 1368 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1369 // are at least 4 bytes aligned. 1370 setMinStackArgumentAlignment(4); 1371 1372 // Prefer likely predicted branches to selects on out-of-order cores. 1373 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1374 1375 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment()); 1376 1377 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1378 1379 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1380 setTargetDAGCombine(ISD::ABS); 1381 } 1382 1383 bool ARMTargetLowering::useSoftFloat() const { 1384 return Subtarget->useSoftFloat(); 1385 } 1386 1387 // FIXME: It might make sense to define the representative register class as the 1388 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1389 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1390 // SPR's representative would be DPR_VFP2. This should work well if register 1391 // pressure tracking were modified such that a register use would increment the 1392 // pressure of the register class's representative and all of it's super 1393 // classes' representatives transitively. We have not implemented this because 1394 // of the difficulty prior to coalescing of modeling operand register classes 1395 // due to the common occurrence of cross class copies and subregister insertions 1396 // and extractions. 1397 std::pair<const TargetRegisterClass *, uint8_t> 1398 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1399 MVT VT) const { 1400 const TargetRegisterClass *RRC = nullptr; 1401 uint8_t Cost = 1; 1402 switch (VT.SimpleTy) { 1403 default: 1404 return TargetLowering::findRepresentativeClass(TRI, VT); 1405 // Use DPR as representative register class for all floating point 1406 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1407 // the cost is 1 for both f32 and f64. 1408 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1409 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1410 RRC = &ARM::DPRRegClass; 1411 // When NEON is used for SP, only half of the register file is available 1412 // because operations that define both SP and DP results will be constrained 1413 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1414 // coalescing by double-counting the SP regs. See the FIXME above. 1415 if (Subtarget->useNEONForSinglePrecisionFP()) 1416 Cost = 2; 1417 break; 1418 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1419 case MVT::v4f32: case MVT::v2f64: 1420 RRC = &ARM::DPRRegClass; 1421 Cost = 2; 1422 break; 1423 case MVT::v4i64: 1424 RRC = &ARM::DPRRegClass; 1425 Cost = 4; 1426 break; 1427 case MVT::v8i64: 1428 RRC = &ARM::DPRRegClass; 1429 Cost = 8; 1430 break; 1431 } 1432 return std::make_pair(RRC, Cost); 1433 } 1434 1435 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1436 switch ((ARMISD::NodeType)Opcode) { 1437 case ARMISD::FIRST_NUMBER: break; 1438 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1439 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1440 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1441 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1442 case ARMISD::CALL: return "ARMISD::CALL"; 1443 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1444 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1445 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1446 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1447 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1448 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1449 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1450 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1451 case ARMISD::CMP: return "ARMISD::CMP"; 1452 case ARMISD::CMN: return "ARMISD::CMN"; 1453 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1454 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1455 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1456 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1457 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1458 1459 case ARMISD::CMOV: return "ARMISD::CMOV"; 1460 case ARMISD::SUBS: return "ARMISD::SUBS"; 1461 1462 case ARMISD::SSAT: return "ARMISD::SSAT"; 1463 case ARMISD::USAT: return "ARMISD::USAT"; 1464 1465 case ARMISD::ASRL: return "ARMISD::ASRL"; 1466 case ARMISD::LSRL: return "ARMISD::LSRL"; 1467 case ARMISD::LSLL: return "ARMISD::LSLL"; 1468 1469 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1470 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1471 case ARMISD::RRX: return "ARMISD::RRX"; 1472 1473 case ARMISD::ADDC: return "ARMISD::ADDC"; 1474 case ARMISD::ADDE: return "ARMISD::ADDE"; 1475 case ARMISD::SUBC: return "ARMISD::SUBC"; 1476 case ARMISD::SUBE: return "ARMISD::SUBE"; 1477 1478 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1479 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1480 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1481 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1482 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1483 1484 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1485 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1486 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1487 1488 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1489 1490 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1491 1492 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1493 1494 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1495 1496 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1497 1498 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1499 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1500 1501 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1502 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1503 case ARMISD::VCGE: return "ARMISD::VCGE"; 1504 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1505 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1506 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1507 case ARMISD::VCGT: return "ARMISD::VCGT"; 1508 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1509 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1510 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1511 case ARMISD::VTST: return "ARMISD::VTST"; 1512 1513 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1514 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1515 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1516 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1517 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1518 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1519 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1520 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1521 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1522 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1523 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1524 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1525 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1526 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1527 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1528 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1529 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1530 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1531 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1532 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1533 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1534 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1535 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1536 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1537 case ARMISD::VDUP: return "ARMISD::VDUP"; 1538 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1539 case ARMISD::VEXT: return "ARMISD::VEXT"; 1540 case ARMISD::VREV64: return "ARMISD::VREV64"; 1541 case ARMISD::VREV32: return "ARMISD::VREV32"; 1542 case ARMISD::VREV16: return "ARMISD::VREV16"; 1543 case ARMISD::VZIP: return "ARMISD::VZIP"; 1544 case ARMISD::VUZP: return "ARMISD::VUZP"; 1545 case ARMISD::VTRN: return "ARMISD::VTRN"; 1546 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1547 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1548 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1549 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1550 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1551 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1552 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1553 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1554 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1555 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1556 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1557 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1558 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1559 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1560 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1561 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1562 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1563 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1564 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1565 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1566 case ARMISD::BFI: return "ARMISD::BFI"; 1567 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1568 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1569 case ARMISD::VBSL: return "ARMISD::VBSL"; 1570 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1571 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1572 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1573 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1574 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1575 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1576 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1577 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1578 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1579 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1580 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1581 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1582 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1583 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1584 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1585 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1586 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1587 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1588 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1589 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1590 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1591 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1592 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1593 case ARMISD::WLS: return "ARMISD::WLS"; 1594 case ARMISD::LE: return "ARMISD::LE"; 1595 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1596 } 1597 return nullptr; 1598 } 1599 1600 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1601 EVT VT) const { 1602 if (!VT.isVector()) 1603 return getPointerTy(DL); 1604 return VT.changeVectorElementTypeToInteger(); 1605 } 1606 1607 /// getRegClassFor - Return the register class that should be used for the 1608 /// specified value type. 1609 const TargetRegisterClass * 1610 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1611 (void)isDivergent; 1612 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1613 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1614 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1615 // MVE Q registers. 1616 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1617 if (VT == MVT::v4i64) 1618 return &ARM::QQPRRegClass; 1619 if (VT == MVT::v8i64) 1620 return &ARM::QQQQPRRegClass; 1621 } 1622 return TargetLowering::getRegClassFor(VT); 1623 } 1624 1625 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1626 // source/dest is aligned and the copy size is large enough. We therefore want 1627 // to align such objects passed to memory intrinsics. 1628 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1629 unsigned &PrefAlign) const { 1630 if (!isa<MemIntrinsic>(CI)) 1631 return false; 1632 MinSize = 8; 1633 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1634 // cycle faster than 4-byte aligned LDM. 1635 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1636 return true; 1637 } 1638 1639 // Create a fast isel object. 1640 FastISel * 1641 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1642 const TargetLibraryInfo *libInfo) const { 1643 return ARM::createFastISel(funcInfo, libInfo); 1644 } 1645 1646 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1647 unsigned NumVals = N->getNumValues(); 1648 if (!NumVals) 1649 return Sched::RegPressure; 1650 1651 for (unsigned i = 0; i != NumVals; ++i) { 1652 EVT VT = N->getValueType(i); 1653 if (VT == MVT::Glue || VT == MVT::Other) 1654 continue; 1655 if (VT.isFloatingPoint() || VT.isVector()) 1656 return Sched::ILP; 1657 } 1658 1659 if (!N->isMachineOpcode()) 1660 return Sched::RegPressure; 1661 1662 // Load are scheduled for latency even if there instruction itinerary 1663 // is not available. 1664 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1665 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1666 1667 if (MCID.getNumDefs() == 0) 1668 return Sched::RegPressure; 1669 if (!Itins->isEmpty() && 1670 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1671 return Sched::ILP; 1672 1673 return Sched::RegPressure; 1674 } 1675 1676 //===----------------------------------------------------------------------===// 1677 // Lowering Code 1678 //===----------------------------------------------------------------------===// 1679 1680 static bool isSRL16(const SDValue &Op) { 1681 if (Op.getOpcode() != ISD::SRL) 1682 return false; 1683 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1684 return Const->getZExtValue() == 16; 1685 return false; 1686 } 1687 1688 static bool isSRA16(const SDValue &Op) { 1689 if (Op.getOpcode() != ISD::SRA) 1690 return false; 1691 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1692 return Const->getZExtValue() == 16; 1693 return false; 1694 } 1695 1696 static bool isSHL16(const SDValue &Op) { 1697 if (Op.getOpcode() != ISD::SHL) 1698 return false; 1699 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1700 return Const->getZExtValue() == 16; 1701 return false; 1702 } 1703 1704 // Check for a signed 16-bit value. We special case SRA because it makes it 1705 // more simple when also looking for SRAs that aren't sign extending a 1706 // smaller value. Without the check, we'd need to take extra care with 1707 // checking order for some operations. 1708 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1709 if (isSRA16(Op)) 1710 return isSHL16(Op.getOperand(0)); 1711 return DAG.ComputeNumSignBits(Op) == 17; 1712 } 1713 1714 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1715 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1716 switch (CC) { 1717 default: llvm_unreachable("Unknown condition code!"); 1718 case ISD::SETNE: return ARMCC::NE; 1719 case ISD::SETEQ: return ARMCC::EQ; 1720 case ISD::SETGT: return ARMCC::GT; 1721 case ISD::SETGE: return ARMCC::GE; 1722 case ISD::SETLT: return ARMCC::LT; 1723 case ISD::SETLE: return ARMCC::LE; 1724 case ISD::SETUGT: return ARMCC::HI; 1725 case ISD::SETUGE: return ARMCC::HS; 1726 case ISD::SETULT: return ARMCC::LO; 1727 case ISD::SETULE: return ARMCC::LS; 1728 } 1729 } 1730 1731 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1732 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1733 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1734 CondCode2 = ARMCC::AL; 1735 InvalidOnQNaN = true; 1736 switch (CC) { 1737 default: llvm_unreachable("Unknown FP condition!"); 1738 case ISD::SETEQ: 1739 case ISD::SETOEQ: 1740 CondCode = ARMCC::EQ; 1741 InvalidOnQNaN = false; 1742 break; 1743 case ISD::SETGT: 1744 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1745 case ISD::SETGE: 1746 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1747 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1748 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1749 case ISD::SETONE: 1750 CondCode = ARMCC::MI; 1751 CondCode2 = ARMCC::GT; 1752 InvalidOnQNaN = false; 1753 break; 1754 case ISD::SETO: CondCode = ARMCC::VC; break; 1755 case ISD::SETUO: CondCode = ARMCC::VS; break; 1756 case ISD::SETUEQ: 1757 CondCode = ARMCC::EQ; 1758 CondCode2 = ARMCC::VS; 1759 InvalidOnQNaN = false; 1760 break; 1761 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1762 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1763 case ISD::SETLT: 1764 case ISD::SETULT: CondCode = ARMCC::LT; break; 1765 case ISD::SETLE: 1766 case ISD::SETULE: CondCode = ARMCC::LE; break; 1767 case ISD::SETNE: 1768 case ISD::SETUNE: 1769 CondCode = ARMCC::NE; 1770 InvalidOnQNaN = false; 1771 break; 1772 } 1773 } 1774 1775 //===----------------------------------------------------------------------===// 1776 // Calling Convention Implementation 1777 //===----------------------------------------------------------------------===// 1778 1779 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1780 /// account presence of floating point hardware and calling convention 1781 /// limitations, such as support for variadic functions. 1782 CallingConv::ID 1783 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1784 bool isVarArg) const { 1785 switch (CC) { 1786 default: 1787 report_fatal_error("Unsupported calling convention"); 1788 case CallingConv::ARM_AAPCS: 1789 case CallingConv::ARM_APCS: 1790 case CallingConv::GHC: 1791 return CC; 1792 case CallingConv::PreserveMost: 1793 return CallingConv::PreserveMost; 1794 case CallingConv::ARM_AAPCS_VFP: 1795 case CallingConv::Swift: 1796 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1797 case CallingConv::C: 1798 if (!Subtarget->isAAPCS_ABI()) 1799 return CallingConv::ARM_APCS; 1800 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1801 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1802 !isVarArg) 1803 return CallingConv::ARM_AAPCS_VFP; 1804 else 1805 return CallingConv::ARM_AAPCS; 1806 case CallingConv::Fast: 1807 case CallingConv::CXX_FAST_TLS: 1808 if (!Subtarget->isAAPCS_ABI()) { 1809 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 1810 return CallingConv::Fast; 1811 return CallingConv::ARM_APCS; 1812 } else if (Subtarget->hasVFP2Base() && 1813 !Subtarget->isThumb1Only() && !isVarArg) 1814 return CallingConv::ARM_AAPCS_VFP; 1815 else 1816 return CallingConv::ARM_AAPCS; 1817 } 1818 } 1819 1820 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1821 bool isVarArg) const { 1822 return CCAssignFnForNode(CC, false, isVarArg); 1823 } 1824 1825 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1826 bool isVarArg) const { 1827 return CCAssignFnForNode(CC, true, isVarArg); 1828 } 1829 1830 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1831 /// CallingConvention. 1832 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1833 bool Return, 1834 bool isVarArg) const { 1835 switch (getEffectiveCallingConv(CC, isVarArg)) { 1836 default: 1837 report_fatal_error("Unsupported calling convention"); 1838 case CallingConv::ARM_APCS: 1839 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1840 case CallingConv::ARM_AAPCS: 1841 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1842 case CallingConv::ARM_AAPCS_VFP: 1843 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1844 case CallingConv::Fast: 1845 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1846 case CallingConv::GHC: 1847 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1848 case CallingConv::PreserveMost: 1849 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1850 } 1851 } 1852 1853 /// LowerCallResult - Lower the result values of a call into the 1854 /// appropriate copies out of appropriate physical registers. 1855 SDValue ARMTargetLowering::LowerCallResult( 1856 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1857 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1858 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1859 SDValue ThisVal) const { 1860 // Assign locations to each value returned by this call. 1861 SmallVector<CCValAssign, 16> RVLocs; 1862 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1863 *DAG.getContext()); 1864 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1865 1866 // Copy all of the result registers out of their specified physreg. 1867 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1868 CCValAssign VA = RVLocs[i]; 1869 1870 // Pass 'this' value directly from the argument to return value, to avoid 1871 // reg unit interference 1872 if (i == 0 && isThisReturn) { 1873 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1874 "unexpected return calling convention register assignment"); 1875 InVals.push_back(ThisVal); 1876 continue; 1877 } 1878 1879 SDValue Val; 1880 if (VA.needsCustom()) { 1881 // Handle f64 or half of a v2f64. 1882 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1883 InFlag); 1884 Chain = Lo.getValue(1); 1885 InFlag = Lo.getValue(2); 1886 VA = RVLocs[++i]; // skip ahead to next loc 1887 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1888 InFlag); 1889 Chain = Hi.getValue(1); 1890 InFlag = Hi.getValue(2); 1891 if (!Subtarget->isLittle()) 1892 std::swap (Lo, Hi); 1893 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1894 1895 if (VA.getLocVT() == MVT::v2f64) { 1896 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1897 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1898 DAG.getConstant(0, dl, MVT::i32)); 1899 1900 VA = RVLocs[++i]; // skip ahead to next loc 1901 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1902 Chain = Lo.getValue(1); 1903 InFlag = Lo.getValue(2); 1904 VA = RVLocs[++i]; // skip ahead to next loc 1905 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1906 Chain = Hi.getValue(1); 1907 InFlag = Hi.getValue(2); 1908 if (!Subtarget->isLittle()) 1909 std::swap (Lo, Hi); 1910 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1911 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1912 DAG.getConstant(1, dl, MVT::i32)); 1913 } 1914 } else { 1915 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1916 InFlag); 1917 Chain = Val.getValue(1); 1918 InFlag = Val.getValue(2); 1919 } 1920 1921 switch (VA.getLocInfo()) { 1922 default: llvm_unreachable("Unknown loc info!"); 1923 case CCValAssign::Full: break; 1924 case CCValAssign::BCvt: 1925 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1926 break; 1927 } 1928 1929 InVals.push_back(Val); 1930 } 1931 1932 return Chain; 1933 } 1934 1935 /// LowerMemOpCallTo - Store the argument to the stack. 1936 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1937 SDValue Arg, const SDLoc &dl, 1938 SelectionDAG &DAG, 1939 const CCValAssign &VA, 1940 ISD::ArgFlagsTy Flags) const { 1941 unsigned LocMemOffset = VA.getLocMemOffset(); 1942 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1943 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1944 StackPtr, PtrOff); 1945 return DAG.getStore( 1946 Chain, dl, Arg, PtrOff, 1947 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1948 } 1949 1950 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1951 SDValue Chain, SDValue &Arg, 1952 RegsToPassVector &RegsToPass, 1953 CCValAssign &VA, CCValAssign &NextVA, 1954 SDValue &StackPtr, 1955 SmallVectorImpl<SDValue> &MemOpChains, 1956 ISD::ArgFlagsTy Flags) const { 1957 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1958 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1959 unsigned id = Subtarget->isLittle() ? 0 : 1; 1960 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1961 1962 if (NextVA.isRegLoc()) 1963 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1964 else { 1965 assert(NextVA.isMemLoc()); 1966 if (!StackPtr.getNode()) 1967 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1968 getPointerTy(DAG.getDataLayout())); 1969 1970 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1971 dl, DAG, NextVA, 1972 Flags)); 1973 } 1974 } 1975 1976 /// LowerCall - Lowering a call into a callseq_start <- 1977 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1978 /// nodes. 1979 SDValue 1980 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1981 SmallVectorImpl<SDValue> &InVals) const { 1982 SelectionDAG &DAG = CLI.DAG; 1983 SDLoc &dl = CLI.DL; 1984 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1985 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1986 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1987 SDValue Chain = CLI.Chain; 1988 SDValue Callee = CLI.Callee; 1989 bool &isTailCall = CLI.IsTailCall; 1990 CallingConv::ID CallConv = CLI.CallConv; 1991 bool doesNotRet = CLI.DoesNotReturn; 1992 bool isVarArg = CLI.IsVarArg; 1993 1994 MachineFunction &MF = DAG.getMachineFunction(); 1995 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1996 bool isThisReturn = false; 1997 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1998 bool PreferIndirect = false; 1999 2000 // Disable tail calls if they're not supported. 2001 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 2002 isTailCall = false; 2003 2004 if (isa<GlobalAddressSDNode>(Callee)) { 2005 // If we're optimizing for minimum size and the function is called three or 2006 // more times in this block, we can improve codesize by calling indirectly 2007 // as BLXr has a 16-bit encoding. 2008 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2009 if (CLI.CS) { 2010 auto *BB = CLI.CS.getParent(); 2011 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2012 count_if(GV->users(), [&BB](const User *U) { 2013 return isa<Instruction>(U) && 2014 cast<Instruction>(U)->getParent() == BB; 2015 }) > 2; 2016 } 2017 } 2018 if (isTailCall) { 2019 // Check if it's really possible to do a tail call. 2020 isTailCall = IsEligibleForTailCallOptimization( 2021 Callee, CallConv, isVarArg, isStructRet, 2022 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2023 PreferIndirect); 2024 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 2025 report_fatal_error("failed to perform tail call elimination on a call " 2026 "site marked musttail"); 2027 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2028 // detected sibcalls. 2029 if (isTailCall) 2030 ++NumTailCalls; 2031 } 2032 2033 // Analyze operands of the call, assigning locations to each operand. 2034 SmallVector<CCValAssign, 16> ArgLocs; 2035 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2036 *DAG.getContext()); 2037 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2038 2039 // Get a count of how many bytes are to be pushed on the stack. 2040 unsigned NumBytes = CCInfo.getNextStackOffset(); 2041 2042 if (isTailCall) { 2043 // For tail calls, memory operands are available in our caller's stack. 2044 NumBytes = 0; 2045 } else { 2046 // Adjust the stack pointer for the new arguments... 2047 // These operations are automatically eliminated by the prolog/epilog pass 2048 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2049 } 2050 2051 SDValue StackPtr = 2052 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2053 2054 RegsToPassVector RegsToPass; 2055 SmallVector<SDValue, 8> MemOpChains; 2056 2057 // Walk the register/memloc assignments, inserting copies/loads. In the case 2058 // of tail call optimization, arguments are handled later. 2059 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2060 i != e; 2061 ++i, ++realArgIdx) { 2062 CCValAssign &VA = ArgLocs[i]; 2063 SDValue Arg = OutVals[realArgIdx]; 2064 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2065 bool isByVal = Flags.isByVal(); 2066 2067 // Promote the value if needed. 2068 switch (VA.getLocInfo()) { 2069 default: llvm_unreachable("Unknown loc info!"); 2070 case CCValAssign::Full: break; 2071 case CCValAssign::SExt: 2072 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2073 break; 2074 case CCValAssign::ZExt: 2075 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2076 break; 2077 case CCValAssign::AExt: 2078 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2079 break; 2080 case CCValAssign::BCvt: 2081 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2082 break; 2083 } 2084 2085 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2086 if (VA.needsCustom()) { 2087 if (VA.getLocVT() == MVT::v2f64) { 2088 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2089 DAG.getConstant(0, dl, MVT::i32)); 2090 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2091 DAG.getConstant(1, dl, MVT::i32)); 2092 2093 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 2094 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2095 2096 VA = ArgLocs[++i]; // skip ahead to next loc 2097 if (VA.isRegLoc()) { 2098 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 2099 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2100 } else { 2101 assert(VA.isMemLoc()); 2102 2103 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 2104 dl, DAG, VA, Flags)); 2105 } 2106 } else { 2107 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2108 StackPtr, MemOpChains, Flags); 2109 } 2110 } else if (VA.isRegLoc()) { 2111 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2112 Outs[0].VT == MVT::i32) { 2113 assert(VA.getLocVT() == MVT::i32 && 2114 "unexpected calling convention register assignment"); 2115 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2116 "unexpected use of 'returned'"); 2117 isThisReturn = true; 2118 } 2119 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2120 } else if (isByVal) { 2121 assert(VA.isMemLoc()); 2122 unsigned offset = 0; 2123 2124 // True if this byval aggregate will be split between registers 2125 // and memory. 2126 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2127 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2128 2129 if (CurByValIdx < ByValArgsCount) { 2130 2131 unsigned RegBegin, RegEnd; 2132 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2133 2134 EVT PtrVT = 2135 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2136 unsigned int i, j; 2137 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2138 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2139 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2140 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 2141 MachinePointerInfo(), 2142 DAG.InferPtrAlignment(AddArg)); 2143 MemOpChains.push_back(Load.getValue(1)); 2144 RegsToPass.push_back(std::make_pair(j, Load)); 2145 } 2146 2147 // If parameter size outsides register area, "offset" value 2148 // helps us to calculate stack slot for remained part properly. 2149 offset = RegEnd - RegBegin; 2150 2151 CCInfo.nextInRegsParam(); 2152 } 2153 2154 if (Flags.getByValSize() > 4*offset) { 2155 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2156 unsigned LocMemOffset = VA.getLocMemOffset(); 2157 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2158 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2159 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2160 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2161 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2162 MVT::i32); 2163 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 2164 MVT::i32); 2165 2166 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2167 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2168 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2169 Ops)); 2170 } 2171 } else if (!isTailCall) { 2172 assert(VA.isMemLoc()); 2173 2174 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2175 dl, DAG, VA, Flags)); 2176 } 2177 } 2178 2179 if (!MemOpChains.empty()) 2180 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2181 2182 // Build a sequence of copy-to-reg nodes chained together with token chain 2183 // and flag operands which copy the outgoing args into the appropriate regs. 2184 SDValue InFlag; 2185 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2186 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2187 RegsToPass[i].second, InFlag); 2188 InFlag = Chain.getValue(1); 2189 } 2190 2191 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2192 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2193 // node so that legalize doesn't hack it. 2194 bool isDirect = false; 2195 2196 const TargetMachine &TM = getTargetMachine(); 2197 const Module *Mod = MF.getFunction().getParent(); 2198 const GlobalValue *GV = nullptr; 2199 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2200 GV = G->getGlobal(); 2201 bool isStub = 2202 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2203 2204 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2205 bool isLocalARMFunc = false; 2206 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2207 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2208 2209 if (Subtarget->genLongCalls()) { 2210 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2211 "long-calls codegen is not position independent!"); 2212 // Handle a global address or an external symbol. If it's not one of 2213 // those, the target's already in a register, so we don't need to do 2214 // anything extra. 2215 if (isa<GlobalAddressSDNode>(Callee)) { 2216 // Create a constant pool entry for the callee address 2217 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2218 ARMConstantPoolValue *CPV = 2219 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2220 2221 // Get the address of the callee into a register 2222 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2223 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2224 Callee = DAG.getLoad( 2225 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2226 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2227 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2228 const char *Sym = S->getSymbol(); 2229 2230 // Create a constant pool entry for the callee address 2231 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2232 ARMConstantPoolValue *CPV = 2233 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2234 ARMPCLabelIndex, 0); 2235 // Get the address of the callee into a register 2236 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2237 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2238 Callee = DAG.getLoad( 2239 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2240 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2241 } 2242 } else if (isa<GlobalAddressSDNode>(Callee)) { 2243 if (!PreferIndirect) { 2244 isDirect = true; 2245 bool isDef = GV->isStrongDefinitionForLinker(); 2246 2247 // ARM call to a local ARM function is predicable. 2248 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2249 // tBX takes a register source operand. 2250 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2251 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2252 Callee = DAG.getNode( 2253 ARMISD::WrapperPIC, dl, PtrVt, 2254 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2255 Callee = DAG.getLoad( 2256 PtrVt, dl, DAG.getEntryNode(), Callee, 2257 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2258 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2259 MachineMemOperand::MOInvariant); 2260 } else if (Subtarget->isTargetCOFF()) { 2261 assert(Subtarget->isTargetWindows() && 2262 "Windows is the only supported COFF target"); 2263 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2264 ? ARMII::MO_DLLIMPORT 2265 : ARMII::MO_NO_FLAG; 2266 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2267 TargetFlags); 2268 if (GV->hasDLLImportStorageClass()) 2269 Callee = 2270 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2271 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2272 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2273 } else { 2274 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2275 } 2276 } 2277 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2278 isDirect = true; 2279 // tBX takes a register source operand. 2280 const char *Sym = S->getSymbol(); 2281 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2282 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2283 ARMConstantPoolValue *CPV = 2284 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2285 ARMPCLabelIndex, 4); 2286 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2287 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2288 Callee = DAG.getLoad( 2289 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2290 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2291 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2292 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2293 } else { 2294 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2295 } 2296 } 2297 2298 // FIXME: handle tail calls differently. 2299 unsigned CallOpc; 2300 if (Subtarget->isThumb()) { 2301 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2302 CallOpc = ARMISD::CALL_NOLINK; 2303 else 2304 CallOpc = ARMISD::CALL; 2305 } else { 2306 if (!isDirect && !Subtarget->hasV5TOps()) 2307 CallOpc = ARMISD::CALL_NOLINK; 2308 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2309 // Emit regular call when code size is the priority 2310 !Subtarget->hasMinSize()) 2311 // "mov lr, pc; b _foo" to avoid confusing the RSP 2312 CallOpc = ARMISD::CALL_NOLINK; 2313 else 2314 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2315 } 2316 2317 std::vector<SDValue> Ops; 2318 Ops.push_back(Chain); 2319 Ops.push_back(Callee); 2320 2321 // Add argument registers to the end of the list so that they are known live 2322 // into the call. 2323 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2324 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2325 RegsToPass[i].second.getValueType())); 2326 2327 // Add a register mask operand representing the call-preserved registers. 2328 if (!isTailCall) { 2329 const uint32_t *Mask; 2330 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2331 if (isThisReturn) { 2332 // For 'this' returns, use the R0-preserving mask if applicable 2333 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2334 if (!Mask) { 2335 // Set isThisReturn to false if the calling convention is not one that 2336 // allows 'returned' to be modeled in this way, so LowerCallResult does 2337 // not try to pass 'this' straight through 2338 isThisReturn = false; 2339 Mask = ARI->getCallPreservedMask(MF, CallConv); 2340 } 2341 } else 2342 Mask = ARI->getCallPreservedMask(MF, CallConv); 2343 2344 assert(Mask && "Missing call preserved mask for calling convention"); 2345 Ops.push_back(DAG.getRegisterMask(Mask)); 2346 } 2347 2348 if (InFlag.getNode()) 2349 Ops.push_back(InFlag); 2350 2351 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2352 if (isTailCall) { 2353 MF.getFrameInfo().setHasTailCall(); 2354 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2355 } 2356 2357 // Returns a chain and a flag for retval copy to use. 2358 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2359 InFlag = Chain.getValue(1); 2360 2361 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2362 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2363 if (!Ins.empty()) 2364 InFlag = Chain.getValue(1); 2365 2366 // Handle result values, copying them out of physregs into vregs that we 2367 // return. 2368 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2369 InVals, isThisReturn, 2370 isThisReturn ? OutVals[0] : SDValue()); 2371 } 2372 2373 /// HandleByVal - Every parameter *after* a byval parameter is passed 2374 /// on the stack. Remember the next parameter register to allocate, 2375 /// and then confiscate the rest of the parameter registers to insure 2376 /// this. 2377 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2378 unsigned Align) const { 2379 // Byval (as with any stack) slots are always at least 4 byte aligned. 2380 Align = std::max(Align, 4U); 2381 2382 unsigned Reg = State->AllocateReg(GPRArgRegs); 2383 if (!Reg) 2384 return; 2385 2386 unsigned AlignInRegs = Align / 4; 2387 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2388 for (unsigned i = 0; i < Waste; ++i) 2389 Reg = State->AllocateReg(GPRArgRegs); 2390 2391 if (!Reg) 2392 return; 2393 2394 unsigned Excess = 4 * (ARM::R4 - Reg); 2395 2396 // Special case when NSAA != SP and parameter size greater than size of 2397 // all remained GPR regs. In that case we can't split parameter, we must 2398 // send it to stack. We also must set NCRN to R4, so waste all 2399 // remained registers. 2400 const unsigned NSAAOffset = State->getNextStackOffset(); 2401 if (NSAAOffset != 0 && Size > Excess) { 2402 while (State->AllocateReg(GPRArgRegs)) 2403 ; 2404 return; 2405 } 2406 2407 // First register for byval parameter is the first register that wasn't 2408 // allocated before this method call, so it would be "reg". 2409 // If parameter is small enough to be saved in range [reg, r4), then 2410 // the end (first after last) register would be reg + param-size-in-regs, 2411 // else parameter would be splitted between registers and stack, 2412 // end register would be r4 in this case. 2413 unsigned ByValRegBegin = Reg; 2414 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2415 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2416 // Note, first register is allocated in the beginning of function already, 2417 // allocate remained amount of registers we need. 2418 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2419 State->AllocateReg(GPRArgRegs); 2420 // A byval parameter that is split between registers and memory needs its 2421 // size truncated here. 2422 // In the case where the entire structure fits in registers, we set the 2423 // size in memory to zero. 2424 Size = std::max<int>(Size - Excess, 0); 2425 } 2426 2427 /// MatchingStackOffset - Return true if the given stack call argument is 2428 /// already available in the same position (relatively) of the caller's 2429 /// incoming argument stack. 2430 static 2431 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2432 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2433 const TargetInstrInfo *TII) { 2434 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2435 int FI = std::numeric_limits<int>::max(); 2436 if (Arg.getOpcode() == ISD::CopyFromReg) { 2437 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2438 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2439 return false; 2440 MachineInstr *Def = MRI->getVRegDef(VR); 2441 if (!Def) 2442 return false; 2443 if (!Flags.isByVal()) { 2444 if (!TII->isLoadFromStackSlot(*Def, FI)) 2445 return false; 2446 } else { 2447 return false; 2448 } 2449 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2450 if (Flags.isByVal()) 2451 // ByVal argument is passed in as a pointer but it's now being 2452 // dereferenced. e.g. 2453 // define @foo(%struct.X* %A) { 2454 // tail call @bar(%struct.X* byval %A) 2455 // } 2456 return false; 2457 SDValue Ptr = Ld->getBasePtr(); 2458 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2459 if (!FINode) 2460 return false; 2461 FI = FINode->getIndex(); 2462 } else 2463 return false; 2464 2465 assert(FI != std::numeric_limits<int>::max()); 2466 if (!MFI.isFixedObjectIndex(FI)) 2467 return false; 2468 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2469 } 2470 2471 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2472 /// for tail call optimization. Targets which want to do tail call 2473 /// optimization should implement this function. 2474 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2475 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2476 bool isCalleeStructRet, bool isCallerStructRet, 2477 const SmallVectorImpl<ISD::OutputArg> &Outs, 2478 const SmallVectorImpl<SDValue> &OutVals, 2479 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2480 const bool isIndirect) const { 2481 MachineFunction &MF = DAG.getMachineFunction(); 2482 const Function &CallerF = MF.getFunction(); 2483 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2484 2485 assert(Subtarget->supportsTailCall()); 2486 2487 // Indirect tail calls cannot be optimized for Thumb1 if the args 2488 // to the call take up r0-r3. The reason is that there are no legal registers 2489 // left to hold the pointer to the function to be called. 2490 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2491 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2492 return false; 2493 2494 // Look for obvious safe cases to perform tail call optimization that do not 2495 // require ABI changes. This is what gcc calls sibcall. 2496 2497 // Exception-handling functions need a special set of instructions to indicate 2498 // a return to the hardware. Tail-calling another function would probably 2499 // break this. 2500 if (CallerF.hasFnAttribute("interrupt")) 2501 return false; 2502 2503 // Also avoid sibcall optimization if either caller or callee uses struct 2504 // return semantics. 2505 if (isCalleeStructRet || isCallerStructRet) 2506 return false; 2507 2508 // Externally-defined functions with weak linkage should not be 2509 // tail-called on ARM when the OS does not support dynamic 2510 // pre-emption of symbols, as the AAELF spec requires normal calls 2511 // to undefined weak functions to be replaced with a NOP or jump to the 2512 // next instruction. The behaviour of branch instructions in this 2513 // situation (as used for tail calls) is implementation-defined, so we 2514 // cannot rely on the linker replacing the tail call with a return. 2515 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2516 const GlobalValue *GV = G->getGlobal(); 2517 const Triple &TT = getTargetMachine().getTargetTriple(); 2518 if (GV->hasExternalWeakLinkage() && 2519 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2520 return false; 2521 } 2522 2523 // Check that the call results are passed in the same way. 2524 LLVMContext &C = *DAG.getContext(); 2525 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2526 CCAssignFnForReturn(CalleeCC, isVarArg), 2527 CCAssignFnForReturn(CallerCC, isVarArg))) 2528 return false; 2529 // The callee has to preserve all registers the caller needs to preserve. 2530 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2531 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2532 if (CalleeCC != CallerCC) { 2533 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2534 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2535 return false; 2536 } 2537 2538 // If Caller's vararg or byval argument has been split between registers and 2539 // stack, do not perform tail call, since part of the argument is in caller's 2540 // local frame. 2541 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2542 if (AFI_Caller->getArgRegsSaveSize()) 2543 return false; 2544 2545 // If the callee takes no arguments then go on to check the results of the 2546 // call. 2547 if (!Outs.empty()) { 2548 // Check if stack adjustment is needed. For now, do not do this if any 2549 // argument is passed on the stack. 2550 SmallVector<CCValAssign, 16> ArgLocs; 2551 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2552 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2553 if (CCInfo.getNextStackOffset()) { 2554 // Check if the arguments are already laid out in the right way as 2555 // the caller's fixed stack objects. 2556 MachineFrameInfo &MFI = MF.getFrameInfo(); 2557 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2558 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2559 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2560 i != e; 2561 ++i, ++realArgIdx) { 2562 CCValAssign &VA = ArgLocs[i]; 2563 EVT RegVT = VA.getLocVT(); 2564 SDValue Arg = OutVals[realArgIdx]; 2565 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2566 if (VA.getLocInfo() == CCValAssign::Indirect) 2567 return false; 2568 if (VA.needsCustom()) { 2569 // f64 and vector types are split into multiple registers or 2570 // register/stack-slot combinations. The types will not match 2571 // the registers; give up on memory f64 refs until we figure 2572 // out what to do about this. 2573 if (!VA.isRegLoc()) 2574 return false; 2575 if (!ArgLocs[++i].isRegLoc()) 2576 return false; 2577 if (RegVT == MVT::v2f64) { 2578 if (!ArgLocs[++i].isRegLoc()) 2579 return false; 2580 if (!ArgLocs[++i].isRegLoc()) 2581 return false; 2582 } 2583 } else if (!VA.isRegLoc()) { 2584 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2585 MFI, MRI, TII)) 2586 return false; 2587 } 2588 } 2589 } 2590 2591 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2592 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2593 return false; 2594 } 2595 2596 return true; 2597 } 2598 2599 bool 2600 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2601 MachineFunction &MF, bool isVarArg, 2602 const SmallVectorImpl<ISD::OutputArg> &Outs, 2603 LLVMContext &Context) const { 2604 SmallVector<CCValAssign, 16> RVLocs; 2605 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2606 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2607 } 2608 2609 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2610 const SDLoc &DL, SelectionDAG &DAG) { 2611 const MachineFunction &MF = DAG.getMachineFunction(); 2612 const Function &F = MF.getFunction(); 2613 2614 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2615 2616 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2617 // version of the "preferred return address". These offsets affect the return 2618 // instruction if this is a return from PL1 without hypervisor extensions. 2619 // IRQ/FIQ: +4 "subs pc, lr, #4" 2620 // SWI: 0 "subs pc, lr, #0" 2621 // ABORT: +4 "subs pc, lr, #4" 2622 // UNDEF: +4/+2 "subs pc, lr, #0" 2623 // UNDEF varies depending on where the exception came from ARM or Thumb 2624 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2625 2626 int64_t LROffset; 2627 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2628 IntKind == "ABORT") 2629 LROffset = 4; 2630 else if (IntKind == "SWI" || IntKind == "UNDEF") 2631 LROffset = 0; 2632 else 2633 report_fatal_error("Unsupported interrupt attribute. If present, value " 2634 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2635 2636 RetOps.insert(RetOps.begin() + 1, 2637 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2638 2639 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2640 } 2641 2642 SDValue 2643 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2644 bool isVarArg, 2645 const SmallVectorImpl<ISD::OutputArg> &Outs, 2646 const SmallVectorImpl<SDValue> &OutVals, 2647 const SDLoc &dl, SelectionDAG &DAG) const { 2648 // CCValAssign - represent the assignment of the return value to a location. 2649 SmallVector<CCValAssign, 16> RVLocs; 2650 2651 // CCState - Info about the registers and stack slots. 2652 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2653 *DAG.getContext()); 2654 2655 // Analyze outgoing return values. 2656 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2657 2658 SDValue Flag; 2659 SmallVector<SDValue, 4> RetOps; 2660 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2661 bool isLittleEndian = Subtarget->isLittle(); 2662 2663 MachineFunction &MF = DAG.getMachineFunction(); 2664 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2665 AFI->setReturnRegsCount(RVLocs.size()); 2666 2667 // Copy the result values into the output registers. 2668 for (unsigned i = 0, realRVLocIdx = 0; 2669 i != RVLocs.size(); 2670 ++i, ++realRVLocIdx) { 2671 CCValAssign &VA = RVLocs[i]; 2672 assert(VA.isRegLoc() && "Can only return in registers!"); 2673 2674 SDValue Arg = OutVals[realRVLocIdx]; 2675 bool ReturnF16 = false; 2676 2677 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2678 // Half-precision return values can be returned like this: 2679 // 2680 // t11 f16 = fadd ... 2681 // t12: i16 = bitcast t11 2682 // t13: i32 = zero_extend t12 2683 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2684 // 2685 // to avoid code generation for bitcasts, we simply set Arg to the node 2686 // that produces the f16 value, t11 in this case. 2687 // 2688 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2689 SDValue ZE = Arg.getOperand(0); 2690 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2691 SDValue BC = ZE.getOperand(0); 2692 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2693 Arg = BC.getOperand(0); 2694 ReturnF16 = true; 2695 } 2696 } 2697 } 2698 } 2699 2700 switch (VA.getLocInfo()) { 2701 default: llvm_unreachable("Unknown loc info!"); 2702 case CCValAssign::Full: break; 2703 case CCValAssign::BCvt: 2704 if (!ReturnF16) 2705 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2706 break; 2707 } 2708 2709 if (VA.needsCustom()) { 2710 if (VA.getLocVT() == MVT::v2f64) { 2711 // Extract the first half and return it in two registers. 2712 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2713 DAG.getConstant(0, dl, MVT::i32)); 2714 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2715 DAG.getVTList(MVT::i32, MVT::i32), Half); 2716 2717 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2718 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2719 Flag); 2720 Flag = Chain.getValue(1); 2721 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2722 VA = RVLocs[++i]; // skip ahead to next loc 2723 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2724 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2725 Flag); 2726 Flag = Chain.getValue(1); 2727 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2728 VA = RVLocs[++i]; // skip ahead to next loc 2729 2730 // Extract the 2nd half and fall through to handle it as an f64 value. 2731 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2732 DAG.getConstant(1, dl, MVT::i32)); 2733 } 2734 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2735 // available. 2736 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2737 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2738 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2739 fmrrd.getValue(isLittleEndian ? 0 : 1), 2740 Flag); 2741 Flag = Chain.getValue(1); 2742 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2743 VA = RVLocs[++i]; // skip ahead to next loc 2744 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2745 fmrrd.getValue(isLittleEndian ? 1 : 0), 2746 Flag); 2747 } else 2748 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2749 2750 // Guarantee that all emitted copies are 2751 // stuck together, avoiding something bad. 2752 Flag = Chain.getValue(1); 2753 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2754 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2755 } 2756 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2757 const MCPhysReg *I = 2758 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2759 if (I) { 2760 for (; *I; ++I) { 2761 if (ARM::GPRRegClass.contains(*I)) 2762 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2763 else if (ARM::DPRRegClass.contains(*I)) 2764 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2765 else 2766 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2767 } 2768 } 2769 2770 // Update chain and glue. 2771 RetOps[0] = Chain; 2772 if (Flag.getNode()) 2773 RetOps.push_back(Flag); 2774 2775 // CPUs which aren't M-class use a special sequence to return from 2776 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2777 // though we use "subs pc, lr, #N"). 2778 // 2779 // M-class CPUs actually use a normal return sequence with a special 2780 // (hardware-provided) value in LR, so the normal code path works. 2781 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2782 !Subtarget->isMClass()) { 2783 if (Subtarget->isThumb1Only()) 2784 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2785 return LowerInterruptReturn(RetOps, dl, DAG); 2786 } 2787 2788 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2789 } 2790 2791 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2792 if (N->getNumValues() != 1) 2793 return false; 2794 if (!N->hasNUsesOfValue(1, 0)) 2795 return false; 2796 2797 SDValue TCChain = Chain; 2798 SDNode *Copy = *N->use_begin(); 2799 if (Copy->getOpcode() == ISD::CopyToReg) { 2800 // If the copy has a glue operand, we conservatively assume it isn't safe to 2801 // perform a tail call. 2802 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2803 return false; 2804 TCChain = Copy->getOperand(0); 2805 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2806 SDNode *VMov = Copy; 2807 // f64 returned in a pair of GPRs. 2808 SmallPtrSet<SDNode*, 2> Copies; 2809 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2810 UI != UE; ++UI) { 2811 if (UI->getOpcode() != ISD::CopyToReg) 2812 return false; 2813 Copies.insert(*UI); 2814 } 2815 if (Copies.size() > 2) 2816 return false; 2817 2818 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2819 UI != UE; ++UI) { 2820 SDValue UseChain = UI->getOperand(0); 2821 if (Copies.count(UseChain.getNode())) 2822 // Second CopyToReg 2823 Copy = *UI; 2824 else { 2825 // We are at the top of this chain. 2826 // If the copy has a glue operand, we conservatively assume it 2827 // isn't safe to perform a tail call. 2828 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2829 return false; 2830 // First CopyToReg 2831 TCChain = UseChain; 2832 } 2833 } 2834 } else if (Copy->getOpcode() == ISD::BITCAST) { 2835 // f32 returned in a single GPR. 2836 if (!Copy->hasOneUse()) 2837 return false; 2838 Copy = *Copy->use_begin(); 2839 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2840 return false; 2841 // If the copy has a glue operand, we conservatively assume it isn't safe to 2842 // perform a tail call. 2843 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2844 return false; 2845 TCChain = Copy->getOperand(0); 2846 } else { 2847 return false; 2848 } 2849 2850 bool HasRet = false; 2851 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2852 UI != UE; ++UI) { 2853 if (UI->getOpcode() != ARMISD::RET_FLAG && 2854 UI->getOpcode() != ARMISD::INTRET_FLAG) 2855 return false; 2856 HasRet = true; 2857 } 2858 2859 if (!HasRet) 2860 return false; 2861 2862 Chain = TCChain; 2863 return true; 2864 } 2865 2866 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2867 if (!Subtarget->supportsTailCall()) 2868 return false; 2869 2870 auto Attr = 2871 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2872 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2873 return false; 2874 2875 return true; 2876 } 2877 2878 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2879 // and pass the lower and high parts through. 2880 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2881 SDLoc DL(Op); 2882 SDValue WriteValue = Op->getOperand(2); 2883 2884 // This function is only supposed to be called for i64 type argument. 2885 assert(WriteValue.getValueType() == MVT::i64 2886 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2887 2888 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2889 DAG.getConstant(0, DL, MVT::i32)); 2890 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2891 DAG.getConstant(1, DL, MVT::i32)); 2892 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2893 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2894 } 2895 2896 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2897 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2898 // one of the above mentioned nodes. It has to be wrapped because otherwise 2899 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2900 // be used to form addressing mode. These wrapped nodes will be selected 2901 // into MOVi. 2902 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2903 SelectionDAG &DAG) const { 2904 EVT PtrVT = Op.getValueType(); 2905 // FIXME there is no actual debug info here 2906 SDLoc dl(Op); 2907 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2908 SDValue Res; 2909 2910 // When generating execute-only code Constant Pools must be promoted to the 2911 // global data section. It's a bit ugly that we can't share them across basic 2912 // blocks, but this way we guarantee that execute-only behaves correct with 2913 // position-independent addressing modes. 2914 if (Subtarget->genExecuteOnly()) { 2915 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2916 auto T = const_cast<Type*>(CP->getType()); 2917 auto C = const_cast<Constant*>(CP->getConstVal()); 2918 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2919 getFunction().getParent()); 2920 auto GV = new GlobalVariable( 2921 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 2922 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2923 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2924 Twine(AFI->createPICLabelUId()) 2925 ); 2926 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2927 dl, PtrVT); 2928 return LowerGlobalAddress(GA, DAG); 2929 } 2930 2931 if (CP->isMachineConstantPoolEntry()) 2932 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2933 CP->getAlignment()); 2934 else 2935 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2936 CP->getAlignment()); 2937 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2938 } 2939 2940 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2941 return MachineJumpTableInfo::EK_Inline; 2942 } 2943 2944 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2945 SelectionDAG &DAG) const { 2946 MachineFunction &MF = DAG.getMachineFunction(); 2947 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2948 unsigned ARMPCLabelIndex = 0; 2949 SDLoc DL(Op); 2950 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2951 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2952 SDValue CPAddr; 2953 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2954 if (!IsPositionIndependent) { 2955 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2956 } else { 2957 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2958 ARMPCLabelIndex = AFI->createPICLabelUId(); 2959 ARMConstantPoolValue *CPV = 2960 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2961 ARMCP::CPBlockAddress, PCAdj); 2962 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2963 } 2964 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2965 SDValue Result = DAG.getLoad( 2966 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2967 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2968 if (!IsPositionIndependent) 2969 return Result; 2970 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2971 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2972 } 2973 2974 /// Convert a TLS address reference into the correct sequence of loads 2975 /// and calls to compute the variable's address for Darwin, and return an 2976 /// SDValue containing the final node. 2977 2978 /// Darwin only has one TLS scheme which must be capable of dealing with the 2979 /// fully general situation, in the worst case. This means: 2980 /// + "extern __thread" declaration. 2981 /// + Defined in a possibly unknown dynamic library. 2982 /// 2983 /// The general system is that each __thread variable has a [3 x i32] descriptor 2984 /// which contains information used by the runtime to calculate the address. The 2985 /// only part of this the compiler needs to know about is the first word, which 2986 /// contains a function pointer that must be called with the address of the 2987 /// entire descriptor in "r0". 2988 /// 2989 /// Since this descriptor may be in a different unit, in general access must 2990 /// proceed along the usual ARM rules. A common sequence to produce is: 2991 /// 2992 /// movw rT1, :lower16:_var$non_lazy_ptr 2993 /// movt rT1, :upper16:_var$non_lazy_ptr 2994 /// ldr r0, [rT1] 2995 /// ldr rT2, [r0] 2996 /// blx rT2 2997 /// [...address now in r0...] 2998 SDValue 2999 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3000 SelectionDAG &DAG) const { 3001 assert(Subtarget->isTargetDarwin() && 3002 "This function expects a Darwin target"); 3003 SDLoc DL(Op); 3004 3005 // First step is to get the address of the actua global symbol. This is where 3006 // the TLS descriptor lives. 3007 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3008 3009 // The first entry in the descriptor is a function pointer that we must call 3010 // to obtain the address of the variable. 3011 SDValue Chain = DAG.getEntryNode(); 3012 SDValue FuncTLVGet = DAG.getLoad( 3013 MVT::i32, DL, Chain, DescAddr, 3014 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3015 /* Alignment = */ 4, 3016 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3017 MachineMemOperand::MOInvariant); 3018 Chain = FuncTLVGet.getValue(1); 3019 3020 MachineFunction &F = DAG.getMachineFunction(); 3021 MachineFrameInfo &MFI = F.getFrameInfo(); 3022 MFI.setAdjustsStack(true); 3023 3024 // TLS calls preserve all registers except those that absolutely must be 3025 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3026 // silly). 3027 auto TRI = 3028 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3029 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3030 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3031 3032 // Finally, we can make the call. This is just a degenerate version of a 3033 // normal AArch64 call node: r0 takes the address of the descriptor, and 3034 // returns the address of the variable in this thread. 3035 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3036 Chain = 3037 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3038 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3039 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3040 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3041 } 3042 3043 SDValue 3044 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3045 SelectionDAG &DAG) const { 3046 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3047 3048 SDValue Chain = DAG.getEntryNode(); 3049 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3050 SDLoc DL(Op); 3051 3052 // Load the current TEB (thread environment block) 3053 SDValue Ops[] = {Chain, 3054 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3055 DAG.getConstant(15, DL, MVT::i32), 3056 DAG.getConstant(0, DL, MVT::i32), 3057 DAG.getConstant(13, DL, MVT::i32), 3058 DAG.getConstant(0, DL, MVT::i32), 3059 DAG.getConstant(2, DL, MVT::i32)}; 3060 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3061 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3062 3063 SDValue TEB = CurrentTEB.getValue(0); 3064 Chain = CurrentTEB.getValue(1); 3065 3066 // Load the ThreadLocalStoragePointer from the TEB 3067 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3068 SDValue TLSArray = 3069 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3070 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3071 3072 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3073 // offset into the TLSArray. 3074 3075 // Load the TLS index from the C runtime 3076 SDValue TLSIndex = 3077 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3078 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3079 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3080 3081 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3082 DAG.getConstant(2, DL, MVT::i32)); 3083 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3084 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3085 MachinePointerInfo()); 3086 3087 // Get the offset of the start of the .tls section (section base) 3088 const auto *GA = cast<GlobalAddressSDNode>(Op); 3089 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3090 SDValue Offset = DAG.getLoad( 3091 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3092 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 3093 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3094 3095 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3096 } 3097 3098 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3099 SDValue 3100 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3101 SelectionDAG &DAG) const { 3102 SDLoc dl(GA); 3103 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3104 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3105 MachineFunction &MF = DAG.getMachineFunction(); 3106 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3107 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3108 ARMConstantPoolValue *CPV = 3109 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3110 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3111 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3112 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3113 Argument = DAG.getLoad( 3114 PtrVT, dl, DAG.getEntryNode(), Argument, 3115 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3116 SDValue Chain = Argument.getValue(1); 3117 3118 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3119 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3120 3121 // call __tls_get_addr. 3122 ArgListTy Args; 3123 ArgListEntry Entry; 3124 Entry.Node = Argument; 3125 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3126 Args.push_back(Entry); 3127 3128 // FIXME: is there useful debug info available here? 3129 TargetLowering::CallLoweringInfo CLI(DAG); 3130 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3131 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3132 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3133 3134 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3135 return CallResult.first; 3136 } 3137 3138 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3139 // "local exec" model. 3140 SDValue 3141 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3142 SelectionDAG &DAG, 3143 TLSModel::Model model) const { 3144 const GlobalValue *GV = GA->getGlobal(); 3145 SDLoc dl(GA); 3146 SDValue Offset; 3147 SDValue Chain = DAG.getEntryNode(); 3148 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3149 // Get the Thread Pointer 3150 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3151 3152 if (model == TLSModel::InitialExec) { 3153 MachineFunction &MF = DAG.getMachineFunction(); 3154 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3155 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3156 // Initial exec model. 3157 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3158 ARMConstantPoolValue *CPV = 3159 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3160 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3161 true); 3162 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3163 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3164 Offset = DAG.getLoad( 3165 PtrVT, dl, Chain, Offset, 3166 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3167 Chain = Offset.getValue(1); 3168 3169 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3170 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3171 3172 Offset = DAG.getLoad( 3173 PtrVT, dl, Chain, Offset, 3174 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3175 } else { 3176 // local exec model 3177 assert(model == TLSModel::LocalExec); 3178 ARMConstantPoolValue *CPV = 3179 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3180 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3181 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3182 Offset = DAG.getLoad( 3183 PtrVT, dl, Chain, Offset, 3184 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3185 } 3186 3187 // The address of the thread local variable is the add of the thread 3188 // pointer with the offset of the variable. 3189 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3190 } 3191 3192 SDValue 3193 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3194 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3195 if (DAG.getTarget().useEmulatedTLS()) 3196 return LowerToTLSEmulatedModel(GA, DAG); 3197 3198 if (Subtarget->isTargetDarwin()) 3199 return LowerGlobalTLSAddressDarwin(Op, DAG); 3200 3201 if (Subtarget->isTargetWindows()) 3202 return LowerGlobalTLSAddressWindows(Op, DAG); 3203 3204 // TODO: implement the "local dynamic" model 3205 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3206 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3207 3208 switch (model) { 3209 case TLSModel::GeneralDynamic: 3210 case TLSModel::LocalDynamic: 3211 return LowerToTLSGeneralDynamicModel(GA, DAG); 3212 case TLSModel::InitialExec: 3213 case TLSModel::LocalExec: 3214 return LowerToTLSExecModels(GA, DAG, model); 3215 } 3216 llvm_unreachable("bogus TLS model"); 3217 } 3218 3219 /// Return true if all users of V are within function F, looking through 3220 /// ConstantExprs. 3221 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3222 SmallVector<const User*,4> Worklist; 3223 for (auto *U : V->users()) 3224 Worklist.push_back(U); 3225 while (!Worklist.empty()) { 3226 auto *U = Worklist.pop_back_val(); 3227 if (isa<ConstantExpr>(U)) { 3228 for (auto *UU : U->users()) 3229 Worklist.push_back(UU); 3230 continue; 3231 } 3232 3233 auto *I = dyn_cast<Instruction>(U); 3234 if (!I || I->getParent()->getParent() != F) 3235 return false; 3236 } 3237 return true; 3238 } 3239 3240 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3241 const GlobalValue *GV, SelectionDAG &DAG, 3242 EVT PtrVT, const SDLoc &dl) { 3243 // If we're creating a pool entry for a constant global with unnamed address, 3244 // and the global is small enough, we can emit it inline into the constant pool 3245 // to save ourselves an indirection. 3246 // 3247 // This is a win if the constant is only used in one function (so it doesn't 3248 // need to be duplicated) or duplicating the constant wouldn't increase code 3249 // size (implying the constant is no larger than 4 bytes). 3250 const Function &F = DAG.getMachineFunction().getFunction(); 3251 3252 // We rely on this decision to inline being idemopotent and unrelated to the 3253 // use-site. We know that if we inline a variable at one use site, we'll 3254 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3255 // doesn't know about this optimization, so bail out if it's enabled else 3256 // we could decide to inline here (and thus never emit the GV) but require 3257 // the GV from fast-isel generated code. 3258 if (!EnableConstpoolPromotion || 3259 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3260 return SDValue(); 3261 3262 auto *GVar = dyn_cast<GlobalVariable>(GV); 3263 if (!GVar || !GVar->hasInitializer() || 3264 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3265 !GVar->hasLocalLinkage()) 3266 return SDValue(); 3267 3268 // If we inline a value that contains relocations, we move the relocations 3269 // from .data to .text. This is not allowed in position-independent code. 3270 auto *Init = GVar->getInitializer(); 3271 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3272 Init->needsRelocation()) 3273 return SDValue(); 3274 3275 // The constant islands pass can only really deal with alignment requests 3276 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3277 // any type wanting greater alignment requirements than 4 bytes. We also 3278 // can only promote constants that are multiples of 4 bytes in size or 3279 // are paddable to a multiple of 4. Currently we only try and pad constants 3280 // that are strings for simplicity. 3281 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3282 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3283 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3284 unsigned RequiredPadding = 4 - (Size % 4); 3285 bool PaddingPossible = 3286 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3287 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3288 Size == 0) 3289 return SDValue(); 3290 3291 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3292 MachineFunction &MF = DAG.getMachineFunction(); 3293 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3294 3295 // We can't bloat the constant pool too much, else the ConstantIslands pass 3296 // may fail to converge. If we haven't promoted this global yet (it may have 3297 // multiple uses), and promoting it would increase the constant pool size (Sz 3298 // > 4), ensure we have space to do so up to MaxTotal. 3299 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3300 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3301 ConstpoolPromotionMaxTotal) 3302 return SDValue(); 3303 3304 // This is only valid if all users are in a single function; we can't clone 3305 // the constant in general. The LLVM IR unnamed_addr allows merging 3306 // constants, but not cloning them. 3307 // 3308 // We could potentially allow cloning if we could prove all uses of the 3309 // constant in the current function don't care about the address, like 3310 // printf format strings. But that isn't implemented for now. 3311 if (!allUsersAreInFunction(GVar, &F)) 3312 return SDValue(); 3313 3314 // We're going to inline this global. Pad it out if needed. 3315 if (RequiredPadding != 4) { 3316 StringRef S = CDAInit->getAsString(); 3317 3318 SmallVector<uint8_t,16> V(S.size()); 3319 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3320 while (RequiredPadding--) 3321 V.push_back(0); 3322 Init = ConstantDataArray::get(*DAG.getContext(), V); 3323 } 3324 3325 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3326 SDValue CPAddr = 3327 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3328 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3329 AFI->markGlobalAsPromotedToConstantPool(GVar); 3330 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3331 PaddedSize - 4); 3332 } 3333 ++NumConstpoolPromoted; 3334 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3335 } 3336 3337 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3338 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3339 if (!(GV = GA->getBaseObject())) 3340 return false; 3341 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3342 return V->isConstant(); 3343 return isa<Function>(GV); 3344 } 3345 3346 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3347 SelectionDAG &DAG) const { 3348 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3349 default: llvm_unreachable("unknown object format"); 3350 case Triple::COFF: 3351 return LowerGlobalAddressWindows(Op, DAG); 3352 case Triple::ELF: 3353 return LowerGlobalAddressELF(Op, DAG); 3354 case Triple::MachO: 3355 return LowerGlobalAddressDarwin(Op, DAG); 3356 } 3357 } 3358 3359 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3360 SelectionDAG &DAG) const { 3361 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3362 SDLoc dl(Op); 3363 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3364 const TargetMachine &TM = getTargetMachine(); 3365 bool IsRO = isReadOnly(GV); 3366 3367 // promoteToConstantPool only if not generating XO text section 3368 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3369 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3370 return V; 3371 3372 if (isPositionIndependent()) { 3373 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3374 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3375 UseGOT_PREL ? ARMII::MO_GOT : 0); 3376 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3377 if (UseGOT_PREL) 3378 Result = 3379 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3380 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3381 return Result; 3382 } else if (Subtarget->isROPI() && IsRO) { 3383 // PC-relative. 3384 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3385 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3386 return Result; 3387 } else if (Subtarget->isRWPI() && !IsRO) { 3388 // SB-relative. 3389 SDValue RelAddr; 3390 if (Subtarget->useMovt()) { 3391 ++NumMovwMovt; 3392 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3393 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3394 } else { // use literal pool for address constant 3395 ARMConstantPoolValue *CPV = 3396 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3397 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3398 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3399 RelAddr = DAG.getLoad( 3400 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3401 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3402 } 3403 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3404 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3405 return Result; 3406 } 3407 3408 // If we have T2 ops, we can materialize the address directly via movt/movw 3409 // pair. This is always cheaper. 3410 if (Subtarget->useMovt()) { 3411 ++NumMovwMovt; 3412 // FIXME: Once remat is capable of dealing with instructions with register 3413 // operands, expand this into two nodes. 3414 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3415 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3416 } else { 3417 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3418 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3419 return DAG.getLoad( 3420 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3421 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3422 } 3423 } 3424 3425 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3426 SelectionDAG &DAG) const { 3427 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3428 "ROPI/RWPI not currently supported for Darwin"); 3429 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3430 SDLoc dl(Op); 3431 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3432 3433 if (Subtarget->useMovt()) 3434 ++NumMovwMovt; 3435 3436 // FIXME: Once remat is capable of dealing with instructions with register 3437 // operands, expand this into multiple nodes 3438 unsigned Wrapper = 3439 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3440 3441 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3442 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3443 3444 if (Subtarget->isGVIndirectSymbol(GV)) 3445 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3446 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3447 return Result; 3448 } 3449 3450 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3451 SelectionDAG &DAG) const { 3452 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3453 assert(Subtarget->useMovt() && 3454 "Windows on ARM expects to use movw/movt"); 3455 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3456 "ROPI/RWPI not currently supported for Windows"); 3457 3458 const TargetMachine &TM = getTargetMachine(); 3459 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3460 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3461 if (GV->hasDLLImportStorageClass()) 3462 TargetFlags = ARMII::MO_DLLIMPORT; 3463 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3464 TargetFlags = ARMII::MO_COFFSTUB; 3465 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3466 SDValue Result; 3467 SDLoc DL(Op); 3468 3469 ++NumMovwMovt; 3470 3471 // FIXME: Once remat is capable of dealing with instructions with register 3472 // operands, expand this into two nodes. 3473 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3474 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3475 TargetFlags)); 3476 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3477 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3478 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3479 return Result; 3480 } 3481 3482 SDValue 3483 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3484 SDLoc dl(Op); 3485 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3486 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3487 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3488 Op.getOperand(1), Val); 3489 } 3490 3491 SDValue 3492 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3493 SDLoc dl(Op); 3494 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3495 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3496 } 3497 3498 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3499 SelectionDAG &DAG) const { 3500 SDLoc dl(Op); 3501 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3502 Op.getOperand(0)); 3503 } 3504 3505 SDValue 3506 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3507 const ARMSubtarget *Subtarget) const { 3508 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3509 SDLoc dl(Op); 3510 switch (IntNo) { 3511 default: return SDValue(); // Don't custom lower most intrinsics. 3512 case Intrinsic::thread_pointer: { 3513 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3514 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3515 } 3516 case Intrinsic::eh_sjlj_lsda: { 3517 MachineFunction &MF = DAG.getMachineFunction(); 3518 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3519 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3520 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3521 SDValue CPAddr; 3522 bool IsPositionIndependent = isPositionIndependent(); 3523 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3524 ARMConstantPoolValue *CPV = 3525 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3526 ARMCP::CPLSDA, PCAdj); 3527 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3528 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3529 SDValue Result = DAG.getLoad( 3530 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3531 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3532 3533 if (IsPositionIndependent) { 3534 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3535 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3536 } 3537 return Result; 3538 } 3539 case Intrinsic::arm_neon_vabs: 3540 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3541 Op.getOperand(1)); 3542 case Intrinsic::arm_neon_vmulls: 3543 case Intrinsic::arm_neon_vmullu: { 3544 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3545 ? ARMISD::VMULLs : ARMISD::VMULLu; 3546 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3547 Op.getOperand(1), Op.getOperand(2)); 3548 } 3549 case Intrinsic::arm_neon_vminnm: 3550 case Intrinsic::arm_neon_vmaxnm: { 3551 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3552 ? ISD::FMINNUM : ISD::FMAXNUM; 3553 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3554 Op.getOperand(1), Op.getOperand(2)); 3555 } 3556 case Intrinsic::arm_neon_vminu: 3557 case Intrinsic::arm_neon_vmaxu: { 3558 if (Op.getValueType().isFloatingPoint()) 3559 return SDValue(); 3560 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3561 ? ISD::UMIN : ISD::UMAX; 3562 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3563 Op.getOperand(1), Op.getOperand(2)); 3564 } 3565 case Intrinsic::arm_neon_vmins: 3566 case Intrinsic::arm_neon_vmaxs: { 3567 // v{min,max}s is overloaded between signed integers and floats. 3568 if (!Op.getValueType().isFloatingPoint()) { 3569 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3570 ? ISD::SMIN : ISD::SMAX; 3571 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3572 Op.getOperand(1), Op.getOperand(2)); 3573 } 3574 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3575 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3576 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3577 Op.getOperand(1), Op.getOperand(2)); 3578 } 3579 case Intrinsic::arm_neon_vtbl1: 3580 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3581 Op.getOperand(1), Op.getOperand(2)); 3582 case Intrinsic::arm_neon_vtbl2: 3583 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3584 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3585 } 3586 } 3587 3588 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3589 const ARMSubtarget *Subtarget) { 3590 SDLoc dl(Op); 3591 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3592 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3593 if (SSID == SyncScope::SingleThread) 3594 return Op; 3595 3596 if (!Subtarget->hasDataBarrier()) { 3597 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3598 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3599 // here. 3600 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3601 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3602 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3603 DAG.getConstant(0, dl, MVT::i32)); 3604 } 3605 3606 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3607 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3608 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3609 if (Subtarget->isMClass()) { 3610 // Only a full system barrier exists in the M-class architectures. 3611 Domain = ARM_MB::SY; 3612 } else if (Subtarget->preferISHSTBarriers() && 3613 Ord == AtomicOrdering::Release) { 3614 // Swift happens to implement ISHST barriers in a way that's compatible with 3615 // Release semantics but weaker than ISH so we'd be fools not to use 3616 // it. Beware: other processors probably don't! 3617 Domain = ARM_MB::ISHST; 3618 } 3619 3620 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3621 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3622 DAG.getConstant(Domain, dl, MVT::i32)); 3623 } 3624 3625 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3626 const ARMSubtarget *Subtarget) { 3627 // ARM pre v5TE and Thumb1 does not have preload instructions. 3628 if (!(Subtarget->isThumb2() || 3629 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3630 // Just preserve the chain. 3631 return Op.getOperand(0); 3632 3633 SDLoc dl(Op); 3634 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3635 if (!isRead && 3636 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3637 // ARMv7 with MP extension has PLDW. 3638 return Op.getOperand(0); 3639 3640 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3641 if (Subtarget->isThumb()) { 3642 // Invert the bits. 3643 isRead = ~isRead & 1; 3644 isData = ~isData & 1; 3645 } 3646 3647 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3648 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3649 DAG.getConstant(isData, dl, MVT::i32)); 3650 } 3651 3652 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3653 MachineFunction &MF = DAG.getMachineFunction(); 3654 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3655 3656 // vastart just stores the address of the VarArgsFrameIndex slot into the 3657 // memory location argument. 3658 SDLoc dl(Op); 3659 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3660 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3661 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3662 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3663 MachinePointerInfo(SV)); 3664 } 3665 3666 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3667 CCValAssign &NextVA, 3668 SDValue &Root, 3669 SelectionDAG &DAG, 3670 const SDLoc &dl) const { 3671 MachineFunction &MF = DAG.getMachineFunction(); 3672 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3673 3674 const TargetRegisterClass *RC; 3675 if (AFI->isThumb1OnlyFunction()) 3676 RC = &ARM::tGPRRegClass; 3677 else 3678 RC = &ARM::GPRRegClass; 3679 3680 // Transform the arguments stored in physical registers into virtual ones. 3681 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3682 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3683 3684 SDValue ArgValue2; 3685 if (NextVA.isMemLoc()) { 3686 MachineFrameInfo &MFI = MF.getFrameInfo(); 3687 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3688 3689 // Create load node to retrieve arguments from the stack. 3690 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3691 ArgValue2 = DAG.getLoad( 3692 MVT::i32, dl, Root, FIN, 3693 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3694 } else { 3695 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3696 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3697 } 3698 if (!Subtarget->isLittle()) 3699 std::swap (ArgValue, ArgValue2); 3700 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3701 } 3702 3703 // The remaining GPRs hold either the beginning of variable-argument 3704 // data, or the beginning of an aggregate passed by value (usually 3705 // byval). Either way, we allocate stack slots adjacent to the data 3706 // provided by our caller, and store the unallocated registers there. 3707 // If this is a variadic function, the va_list pointer will begin with 3708 // these values; otherwise, this reassembles a (byval) structure that 3709 // was split between registers and memory. 3710 // Return: The frame index registers were stored into. 3711 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3712 const SDLoc &dl, SDValue &Chain, 3713 const Value *OrigArg, 3714 unsigned InRegsParamRecordIdx, 3715 int ArgOffset, unsigned ArgSize) const { 3716 // Currently, two use-cases possible: 3717 // Case #1. Non-var-args function, and we meet first byval parameter. 3718 // Setup first unallocated register as first byval register; 3719 // eat all remained registers 3720 // (these two actions are performed by HandleByVal method). 3721 // Then, here, we initialize stack frame with 3722 // "store-reg" instructions. 3723 // Case #2. Var-args function, that doesn't contain byval parameters. 3724 // The same: eat all remained unallocated registers, 3725 // initialize stack frame. 3726 3727 MachineFunction &MF = DAG.getMachineFunction(); 3728 MachineFrameInfo &MFI = MF.getFrameInfo(); 3729 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3730 unsigned RBegin, REnd; 3731 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3732 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3733 } else { 3734 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3735 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3736 REnd = ARM::R4; 3737 } 3738 3739 if (REnd != RBegin) 3740 ArgOffset = -4 * (ARM::R4 - RBegin); 3741 3742 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3743 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3744 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3745 3746 SmallVector<SDValue, 4> MemOps; 3747 const TargetRegisterClass *RC = 3748 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3749 3750 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3751 unsigned VReg = MF.addLiveIn(Reg, RC); 3752 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3753 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3754 MachinePointerInfo(OrigArg, 4 * i)); 3755 MemOps.push_back(Store); 3756 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3757 } 3758 3759 if (!MemOps.empty()) 3760 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3761 return FrameIndex; 3762 } 3763 3764 // Setup stack frame, the va_list pointer will start from. 3765 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3766 const SDLoc &dl, SDValue &Chain, 3767 unsigned ArgOffset, 3768 unsigned TotalArgRegsSaveSize, 3769 bool ForceMutable) const { 3770 MachineFunction &MF = DAG.getMachineFunction(); 3771 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3772 3773 // Try to store any remaining integer argument regs 3774 // to their spots on the stack so that they may be loaded by dereferencing 3775 // the result of va_next. 3776 // If there is no regs to be stored, just point address after last 3777 // argument passed via stack. 3778 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3779 CCInfo.getInRegsParamsCount(), 3780 CCInfo.getNextStackOffset(), 3781 std::max(4U, TotalArgRegsSaveSize)); 3782 AFI->setVarArgsFrameIndex(FrameIndex); 3783 } 3784 3785 SDValue ARMTargetLowering::LowerFormalArguments( 3786 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3787 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3788 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3789 MachineFunction &MF = DAG.getMachineFunction(); 3790 MachineFrameInfo &MFI = MF.getFrameInfo(); 3791 3792 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3793 3794 // Assign locations to all of the incoming arguments. 3795 SmallVector<CCValAssign, 16> ArgLocs; 3796 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3797 *DAG.getContext()); 3798 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3799 3800 SmallVector<SDValue, 16> ArgValues; 3801 SDValue ArgValue; 3802 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3803 unsigned CurArgIdx = 0; 3804 3805 // Initially ArgRegsSaveSize is zero. 3806 // Then we increase this value each time we meet byval parameter. 3807 // We also increase this value in case of varargs function. 3808 AFI->setArgRegsSaveSize(0); 3809 3810 // Calculate the amount of stack space that we need to allocate to store 3811 // byval and variadic arguments that are passed in registers. 3812 // We need to know this before we allocate the first byval or variadic 3813 // argument, as they will be allocated a stack slot below the CFA (Canonical 3814 // Frame Address, the stack pointer at entry to the function). 3815 unsigned ArgRegBegin = ARM::R4; 3816 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3817 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3818 break; 3819 3820 CCValAssign &VA = ArgLocs[i]; 3821 unsigned Index = VA.getValNo(); 3822 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3823 if (!Flags.isByVal()) 3824 continue; 3825 3826 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3827 unsigned RBegin, REnd; 3828 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3829 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3830 3831 CCInfo.nextInRegsParam(); 3832 } 3833 CCInfo.rewindByValRegsInfo(); 3834 3835 int lastInsIndex = -1; 3836 if (isVarArg && MFI.hasVAStart()) { 3837 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3838 if (RegIdx != array_lengthof(GPRArgRegs)) 3839 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3840 } 3841 3842 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3843 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3844 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3845 3846 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3847 CCValAssign &VA = ArgLocs[i]; 3848 if (Ins[VA.getValNo()].isOrigArg()) { 3849 std::advance(CurOrigArg, 3850 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3851 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3852 } 3853 // Arguments stored in registers. 3854 if (VA.isRegLoc()) { 3855 EVT RegVT = VA.getLocVT(); 3856 3857 if (VA.needsCustom()) { 3858 // f64 and vector types are split up into multiple registers or 3859 // combinations of registers and stack slots. 3860 if (VA.getLocVT() == MVT::v2f64) { 3861 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3862 Chain, DAG, dl); 3863 VA = ArgLocs[++i]; // skip ahead to next loc 3864 SDValue ArgValue2; 3865 if (VA.isMemLoc()) { 3866 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3867 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3868 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3869 MachinePointerInfo::getFixedStack( 3870 DAG.getMachineFunction(), FI)); 3871 } else { 3872 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3873 Chain, DAG, dl); 3874 } 3875 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3876 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3877 ArgValue, ArgValue1, 3878 DAG.getIntPtrConstant(0, dl)); 3879 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3880 ArgValue, ArgValue2, 3881 DAG.getIntPtrConstant(1, dl)); 3882 } else 3883 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3884 } else { 3885 const TargetRegisterClass *RC; 3886 3887 3888 if (RegVT == MVT::f16) 3889 RC = &ARM::HPRRegClass; 3890 else if (RegVT == MVT::f32) 3891 RC = &ARM::SPRRegClass; 3892 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3893 RC = &ARM::DPRRegClass; 3894 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3895 RC = &ARM::QPRRegClass; 3896 else if (RegVT == MVT::i32) 3897 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3898 : &ARM::GPRRegClass; 3899 else 3900 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3901 3902 // Transform the arguments in physical registers into virtual ones. 3903 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3904 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3905 3906 // If this value is passed in r0 and has the returned attribute (e.g. 3907 // C++ 'structors), record this fact for later use. 3908 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 3909 AFI->setPreservesR0(); 3910 } 3911 } 3912 3913 // If this is an 8 or 16-bit value, it is really passed promoted 3914 // to 32 bits. Insert an assert[sz]ext to capture this, then 3915 // truncate to the right size. 3916 switch (VA.getLocInfo()) { 3917 default: llvm_unreachable("Unknown loc info!"); 3918 case CCValAssign::Full: break; 3919 case CCValAssign::BCvt: 3920 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3921 break; 3922 case CCValAssign::SExt: 3923 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3924 DAG.getValueType(VA.getValVT())); 3925 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3926 break; 3927 case CCValAssign::ZExt: 3928 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3929 DAG.getValueType(VA.getValVT())); 3930 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3931 break; 3932 } 3933 3934 InVals.push_back(ArgValue); 3935 } else { // VA.isRegLoc() 3936 // sanity check 3937 assert(VA.isMemLoc()); 3938 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3939 3940 int index = VA.getValNo(); 3941 3942 // Some Ins[] entries become multiple ArgLoc[] entries. 3943 // Process them only once. 3944 if (index != lastInsIndex) 3945 { 3946 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3947 // FIXME: For now, all byval parameter objects are marked mutable. 3948 // This can be changed with more analysis. 3949 // In case of tail call optimization mark all arguments mutable. 3950 // Since they could be overwritten by lowering of arguments in case of 3951 // a tail call. 3952 if (Flags.isByVal()) { 3953 assert(Ins[index].isOrigArg() && 3954 "Byval arguments cannot be implicit"); 3955 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3956 3957 int FrameIndex = StoreByValRegs( 3958 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3959 VA.getLocMemOffset(), Flags.getByValSize()); 3960 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3961 CCInfo.nextInRegsParam(); 3962 } else { 3963 unsigned FIOffset = VA.getLocMemOffset(); 3964 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3965 FIOffset, true); 3966 3967 // Create load nodes to retrieve arguments from the stack. 3968 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3969 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3970 MachinePointerInfo::getFixedStack( 3971 DAG.getMachineFunction(), FI))); 3972 } 3973 lastInsIndex = index; 3974 } 3975 } 3976 } 3977 3978 // varargs 3979 if (isVarArg && MFI.hasVAStart()) 3980 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3981 CCInfo.getNextStackOffset(), 3982 TotalArgRegsSaveSize); 3983 3984 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3985 3986 return Chain; 3987 } 3988 3989 /// isFloatingPointZero - Return true if this is +0.0. 3990 static bool isFloatingPointZero(SDValue Op) { 3991 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3992 return CFP->getValueAPF().isPosZero(); 3993 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3994 // Maybe this has already been legalized into the constant pool? 3995 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3996 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3997 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3998 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3999 return CFP->getValueAPF().isPosZero(); 4000 } 4001 } else if (Op->getOpcode() == ISD::BITCAST && 4002 Op->getValueType(0) == MVT::f64) { 4003 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4004 // created by LowerConstantFP(). 4005 SDValue BitcastOp = Op->getOperand(0); 4006 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4007 isNullConstant(BitcastOp->getOperand(0))) 4008 return true; 4009 } 4010 return false; 4011 } 4012 4013 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4014 /// the given operands. 4015 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4016 SDValue &ARMcc, SelectionDAG &DAG, 4017 const SDLoc &dl) const { 4018 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4019 unsigned C = RHSC->getZExtValue(); 4020 if (!isLegalICmpImmediate((int32_t)C)) { 4021 // Constant does not fit, try adjusting it by one. 4022 switch (CC) { 4023 default: break; 4024 case ISD::SETLT: 4025 case ISD::SETGE: 4026 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4027 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4028 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4029 } 4030 break; 4031 case ISD::SETULT: 4032 case ISD::SETUGE: 4033 if (C != 0 && isLegalICmpImmediate(C-1)) { 4034 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4035 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4036 } 4037 break; 4038 case ISD::SETLE: 4039 case ISD::SETGT: 4040 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4041 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4042 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4043 } 4044 break; 4045 case ISD::SETULE: 4046 case ISD::SETUGT: 4047 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4048 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4049 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4050 } 4051 break; 4052 } 4053 } 4054 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4055 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4056 // In ARM and Thumb-2, the compare instructions can shift their second 4057 // operand. 4058 CC = ISD::getSetCCSwappedOperands(CC); 4059 std::swap(LHS, RHS); 4060 } 4061 4062 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4063 4064 // If the RHS is a constant zero then the V (overflow) flag will never be 4065 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4066 // simpler for other passes (like the peephole optimiser) to deal with. 4067 if (isNullConstant(RHS)) { 4068 switch (CondCode) { 4069 default: break; 4070 case ARMCC::GE: 4071 CondCode = ARMCC::PL; 4072 break; 4073 case ARMCC::LT: 4074 CondCode = ARMCC::MI; 4075 break; 4076 } 4077 } 4078 4079 ARMISD::NodeType CompareType; 4080 switch (CondCode) { 4081 default: 4082 CompareType = ARMISD::CMP; 4083 break; 4084 case ARMCC::EQ: 4085 case ARMCC::NE: 4086 // Uses only Z Flag 4087 CompareType = ARMISD::CMPZ; 4088 break; 4089 } 4090 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4091 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4092 } 4093 4094 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4095 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4096 SelectionDAG &DAG, const SDLoc &dl, 4097 bool InvalidOnQNaN) const { 4098 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4099 SDValue Cmp; 4100 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 4101 if (!isFloatingPointZero(RHS)) 4102 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 4103 else 4104 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 4105 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4106 } 4107 4108 /// duplicateCmp - Glue values can have only one use, so this function 4109 /// duplicates a comparison node. 4110 SDValue 4111 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4112 unsigned Opc = Cmp.getOpcode(); 4113 SDLoc DL(Cmp); 4114 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4115 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4116 4117 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4118 Cmp = Cmp.getOperand(0); 4119 Opc = Cmp.getOpcode(); 4120 if (Opc == ARMISD::CMPFP) 4121 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4122 Cmp.getOperand(1), Cmp.getOperand(2)); 4123 else { 4124 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4125 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4126 Cmp.getOperand(1)); 4127 } 4128 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4129 } 4130 4131 // This function returns three things: the arithmetic computation itself 4132 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4133 // comparison and the condition code define the case in which the arithmetic 4134 // computation *does not* overflow. 4135 std::pair<SDValue, SDValue> 4136 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4137 SDValue &ARMcc) const { 4138 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4139 4140 SDValue Value, OverflowCmp; 4141 SDValue LHS = Op.getOperand(0); 4142 SDValue RHS = Op.getOperand(1); 4143 SDLoc dl(Op); 4144 4145 // FIXME: We are currently always generating CMPs because we don't support 4146 // generating CMN through the backend. This is not as good as the natural 4147 // CMP case because it causes a register dependency and cannot be folded 4148 // later. 4149 4150 switch (Op.getOpcode()) { 4151 default: 4152 llvm_unreachable("Unknown overflow instruction!"); 4153 case ISD::SADDO: 4154 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4155 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4156 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4157 break; 4158 case ISD::UADDO: 4159 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4160 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4161 // We do not use it in the USUBO case as Value may not be used. 4162 Value = DAG.getNode(ARMISD::ADDC, dl, 4163 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4164 .getValue(0); 4165 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4166 break; 4167 case ISD::SSUBO: 4168 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4169 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4170 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4171 break; 4172 case ISD::USUBO: 4173 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4174 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4175 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4176 break; 4177 case ISD::UMULO: 4178 // We generate a UMUL_LOHI and then check if the high word is 0. 4179 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4180 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4181 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4182 LHS, RHS); 4183 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4184 DAG.getConstant(0, dl, MVT::i32)); 4185 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4186 break; 4187 case ISD::SMULO: 4188 // We generate a SMUL_LOHI and then check if all the bits of the high word 4189 // are the same as the sign bit of the low word. 4190 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4191 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4192 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4193 LHS, RHS); 4194 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4195 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4196 Value.getValue(0), 4197 DAG.getConstant(31, dl, MVT::i32))); 4198 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4199 break; 4200 } // switch (...) 4201 4202 return std::make_pair(Value, OverflowCmp); 4203 } 4204 4205 SDValue 4206 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4207 // Let legalize expand this if it isn't a legal type yet. 4208 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4209 return SDValue(); 4210 4211 SDValue Value, OverflowCmp; 4212 SDValue ARMcc; 4213 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4214 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4215 SDLoc dl(Op); 4216 // We use 0 and 1 as false and true values. 4217 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4218 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4219 EVT VT = Op.getValueType(); 4220 4221 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4222 ARMcc, CCR, OverflowCmp); 4223 4224 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4225 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4226 } 4227 4228 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4229 SelectionDAG &DAG) { 4230 SDLoc DL(BoolCarry); 4231 EVT CarryVT = BoolCarry.getValueType(); 4232 4233 // This converts the boolean value carry into the carry flag by doing 4234 // ARMISD::SUBC Carry, 1 4235 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4236 DAG.getVTList(CarryVT, MVT::i32), 4237 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4238 return Carry.getValue(1); 4239 } 4240 4241 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4242 SelectionDAG &DAG) { 4243 SDLoc DL(Flags); 4244 4245 // Now convert the carry flag into a boolean carry. We do this 4246 // using ARMISD:ADDE 0, 0, Carry 4247 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4248 DAG.getConstant(0, DL, MVT::i32), 4249 DAG.getConstant(0, DL, MVT::i32), Flags); 4250 } 4251 4252 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4253 SelectionDAG &DAG) const { 4254 // Let legalize expand this if it isn't a legal type yet. 4255 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4256 return SDValue(); 4257 4258 SDValue LHS = Op.getOperand(0); 4259 SDValue RHS = Op.getOperand(1); 4260 SDLoc dl(Op); 4261 4262 EVT VT = Op.getValueType(); 4263 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4264 SDValue Value; 4265 SDValue Overflow; 4266 switch (Op.getOpcode()) { 4267 default: 4268 llvm_unreachable("Unknown overflow instruction!"); 4269 case ISD::UADDO: 4270 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4271 // Convert the carry flag into a boolean value. 4272 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4273 break; 4274 case ISD::USUBO: { 4275 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4276 // Convert the carry flag into a boolean value. 4277 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4278 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4279 // value. So compute 1 - C. 4280 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4281 DAG.getConstant(1, dl, MVT::i32), Overflow); 4282 break; 4283 } 4284 } 4285 4286 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4287 } 4288 4289 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4290 SDValue Cond = Op.getOperand(0); 4291 SDValue SelectTrue = Op.getOperand(1); 4292 SDValue SelectFalse = Op.getOperand(2); 4293 SDLoc dl(Op); 4294 unsigned Opc = Cond.getOpcode(); 4295 4296 if (Cond.getResNo() == 1 && 4297 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4298 Opc == ISD::USUBO)) { 4299 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4300 return SDValue(); 4301 4302 SDValue Value, OverflowCmp; 4303 SDValue ARMcc; 4304 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4305 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4306 EVT VT = Op.getValueType(); 4307 4308 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4309 OverflowCmp, DAG); 4310 } 4311 4312 // Convert: 4313 // 4314 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4315 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4316 // 4317 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4318 const ConstantSDNode *CMOVTrue = 4319 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4320 const ConstantSDNode *CMOVFalse = 4321 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4322 4323 if (CMOVTrue && CMOVFalse) { 4324 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4325 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4326 4327 SDValue True; 4328 SDValue False; 4329 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4330 True = SelectTrue; 4331 False = SelectFalse; 4332 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4333 True = SelectFalse; 4334 False = SelectTrue; 4335 } 4336 4337 if (True.getNode() && False.getNode()) { 4338 EVT VT = Op.getValueType(); 4339 SDValue ARMcc = Cond.getOperand(2); 4340 SDValue CCR = Cond.getOperand(3); 4341 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4342 assert(True.getValueType() == VT); 4343 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4344 } 4345 } 4346 } 4347 4348 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4349 // undefined bits before doing a full-word comparison with zero. 4350 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4351 DAG.getConstant(1, dl, Cond.getValueType())); 4352 4353 return DAG.getSelectCC(dl, Cond, 4354 DAG.getConstant(0, dl, Cond.getValueType()), 4355 SelectTrue, SelectFalse, ISD::SETNE); 4356 } 4357 4358 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4359 bool &swpCmpOps, bool &swpVselOps) { 4360 // Start by selecting the GE condition code for opcodes that return true for 4361 // 'equality' 4362 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4363 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4364 CondCode = ARMCC::GE; 4365 4366 // and GT for opcodes that return false for 'equality'. 4367 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4368 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4369 CondCode = ARMCC::GT; 4370 4371 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4372 // to swap the compare operands. 4373 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4374 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4375 swpCmpOps = true; 4376 4377 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4378 // If we have an unordered opcode, we need to swap the operands to the VSEL 4379 // instruction (effectively negating the condition). 4380 // 4381 // This also has the effect of swapping which one of 'less' or 'greater' 4382 // returns true, so we also swap the compare operands. It also switches 4383 // whether we return true for 'equality', so we compensate by picking the 4384 // opposite condition code to our original choice. 4385 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4386 CC == ISD::SETUGT) { 4387 swpCmpOps = !swpCmpOps; 4388 swpVselOps = !swpVselOps; 4389 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4390 } 4391 4392 // 'ordered' is 'anything but unordered', so use the VS condition code and 4393 // swap the VSEL operands. 4394 if (CC == ISD::SETO) { 4395 CondCode = ARMCC::VS; 4396 swpVselOps = true; 4397 } 4398 4399 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4400 // code and swap the VSEL operands. Also do this if we don't care about the 4401 // unordered case. 4402 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4403 CondCode = ARMCC::EQ; 4404 swpVselOps = true; 4405 } 4406 } 4407 4408 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4409 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4410 SDValue Cmp, SelectionDAG &DAG) const { 4411 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4412 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4413 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4414 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4415 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4416 4417 SDValue TrueLow = TrueVal.getValue(0); 4418 SDValue TrueHigh = TrueVal.getValue(1); 4419 SDValue FalseLow = FalseVal.getValue(0); 4420 SDValue FalseHigh = FalseVal.getValue(1); 4421 4422 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4423 ARMcc, CCR, Cmp); 4424 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4425 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4426 4427 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4428 } else { 4429 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4430 Cmp); 4431 } 4432 } 4433 4434 static bool isGTorGE(ISD::CondCode CC) { 4435 return CC == ISD::SETGT || CC == ISD::SETGE; 4436 } 4437 4438 static bool isLTorLE(ISD::CondCode CC) { 4439 return CC == ISD::SETLT || CC == ISD::SETLE; 4440 } 4441 4442 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4443 // All of these conditions (and their <= and >= counterparts) will do: 4444 // x < k ? k : x 4445 // x > k ? x : k 4446 // k < x ? x : k 4447 // k > x ? k : x 4448 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4449 const SDValue TrueVal, const SDValue FalseVal, 4450 const ISD::CondCode CC, const SDValue K) { 4451 return (isGTorGE(CC) && 4452 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4453 (isLTorLE(CC) && 4454 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4455 } 4456 4457 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4458 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4459 const SDValue TrueVal, const SDValue FalseVal, 4460 const ISD::CondCode CC, const SDValue K) { 4461 return (isGTorGE(CC) && 4462 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4463 (isLTorLE(CC) && 4464 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4465 } 4466 4467 // Check if two chained conditionals could be converted into SSAT or USAT. 4468 // 4469 // SSAT can replace a set of two conditional selectors that bound a number to an 4470 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4471 // 4472 // x < -k ? -k : (x > k ? k : x) 4473 // x < -k ? -k : (x < k ? x : k) 4474 // x > -k ? (x > k ? k : x) : -k 4475 // x < k ? (x < -k ? -k : x) : k 4476 // etc. 4477 // 4478 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4479 // a power of 2. 4480 // 4481 // It returns true if the conversion can be done, false otherwise. 4482 // Additionally, the variable is returned in parameter V, the constant in K and 4483 // usat is set to true if the conditional represents an unsigned saturation 4484 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4485 uint64_t &K, bool &usat) { 4486 SDValue LHS1 = Op.getOperand(0); 4487 SDValue RHS1 = Op.getOperand(1); 4488 SDValue TrueVal1 = Op.getOperand(2); 4489 SDValue FalseVal1 = Op.getOperand(3); 4490 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4491 4492 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4493 if (Op2.getOpcode() != ISD::SELECT_CC) 4494 return false; 4495 4496 SDValue LHS2 = Op2.getOperand(0); 4497 SDValue RHS2 = Op2.getOperand(1); 4498 SDValue TrueVal2 = Op2.getOperand(2); 4499 SDValue FalseVal2 = Op2.getOperand(3); 4500 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4501 4502 // Find out which are the constants and which are the variables 4503 // in each conditional 4504 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4505 ? &RHS1 4506 : nullptr; 4507 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4508 ? &RHS2 4509 : nullptr; 4510 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4511 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4512 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4513 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4514 4515 // We must detect cases where the original operations worked with 16- or 4516 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4517 // must work with sign-extended values but the select operations return 4518 // the original non-extended value. 4519 SDValue V2TmpReg = V2Tmp; 4520 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4521 V2TmpReg = V2Tmp->getOperand(0); 4522 4523 // Check that the registers and the constants have the correct values 4524 // in both conditionals 4525 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4526 V2TmpReg != V2) 4527 return false; 4528 4529 // Figure out which conditional is saturating the lower/upper bound. 4530 const SDValue *LowerCheckOp = 4531 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4532 ? &Op 4533 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4534 ? &Op2 4535 : nullptr; 4536 const SDValue *UpperCheckOp = 4537 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4538 ? &Op 4539 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4540 ? &Op2 4541 : nullptr; 4542 4543 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4544 return false; 4545 4546 // Check that the constant in the lower-bound check is 4547 // the opposite of the constant in the upper-bound check 4548 // in 1's complement. 4549 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4550 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4551 int64_t PosVal = std::max(Val1, Val2); 4552 int64_t NegVal = std::min(Val1, Val2); 4553 4554 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4555 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4556 isPowerOf2_64(PosVal + 1)) { 4557 4558 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4559 if (Val1 == ~Val2) 4560 usat = false; 4561 else if (NegVal == 0) 4562 usat = true; 4563 else 4564 return false; 4565 4566 V = V2; 4567 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4568 4569 return true; 4570 } 4571 4572 return false; 4573 } 4574 4575 // Check if a condition of the type x < k ? k : x can be converted into a 4576 // bit operation instead of conditional moves. 4577 // Currently this is allowed given: 4578 // - The conditions and values match up 4579 // - k is 0 or -1 (all ones) 4580 // This function will not check the last condition, thats up to the caller 4581 // It returns true if the transformation can be made, and in such case 4582 // returns x in V, and k in SatK. 4583 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4584 SDValue &SatK) 4585 { 4586 SDValue LHS = Op.getOperand(0); 4587 SDValue RHS = Op.getOperand(1); 4588 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4589 SDValue TrueVal = Op.getOperand(2); 4590 SDValue FalseVal = Op.getOperand(3); 4591 4592 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4593 ? &RHS 4594 : nullptr; 4595 4596 // No constant operation in comparison, early out 4597 if (!K) 4598 return false; 4599 4600 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4601 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4602 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4603 4604 // If the constant on left and right side, or variable on left and right, 4605 // does not match, early out 4606 if (*K != KTmp || V != VTmp) 4607 return false; 4608 4609 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4610 SatK = *K; 4611 return true; 4612 } 4613 4614 return false; 4615 } 4616 4617 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 4618 if (VT == MVT::f32) 4619 return !Subtarget->hasVFP2Base(); 4620 if (VT == MVT::f64) 4621 return !Subtarget->hasFP64(); 4622 if (VT == MVT::f16) 4623 return !Subtarget->hasFullFP16(); 4624 return false; 4625 } 4626 4627 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4628 EVT VT = Op.getValueType(); 4629 SDLoc dl(Op); 4630 4631 // Try to convert two saturating conditional selects into a single SSAT 4632 SDValue SatValue; 4633 uint64_t SatConstant; 4634 bool SatUSat; 4635 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4636 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4637 if (SatUSat) 4638 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4639 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4640 else 4641 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4642 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4643 } 4644 4645 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4646 // into more efficient bit operations, which is possible when k is 0 or -1 4647 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4648 // single instructions. On Thumb the shift and the bit operation will be two 4649 // instructions. 4650 // Only allow this transformation on full-width (32-bit) operations 4651 SDValue LowerSatConstant; 4652 if (VT == MVT::i32 && 4653 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4654 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4655 DAG.getConstant(31, dl, VT)); 4656 if (isNullConstant(LowerSatConstant)) { 4657 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4658 DAG.getAllOnesConstant(dl, VT)); 4659 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4660 } else if (isAllOnesConstant(LowerSatConstant)) 4661 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4662 } 4663 4664 SDValue LHS = Op.getOperand(0); 4665 SDValue RHS = Op.getOperand(1); 4666 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4667 SDValue TrueVal = Op.getOperand(2); 4668 SDValue FalseVal = Op.getOperand(3); 4669 4670 if (isUnsupportedFloatingType(LHS.getValueType())) { 4671 DAG.getTargetLoweringInfo().softenSetCCOperands( 4672 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 4673 4674 // If softenSetCCOperands only returned one value, we should compare it to 4675 // zero. 4676 if (!RHS.getNode()) { 4677 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4678 CC = ISD::SETNE; 4679 } 4680 } 4681 4682 if (LHS.getValueType() == MVT::i32) { 4683 // Try to generate VSEL on ARMv8. 4684 // The VSEL instruction can't use all the usual ARM condition 4685 // codes: it only has two bits to select the condition code, so it's 4686 // constrained to use only GE, GT, VS and EQ. 4687 // 4688 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4689 // swap the operands of the previous compare instruction (effectively 4690 // inverting the compare condition, swapping 'less' and 'greater') and 4691 // sometimes need to swap the operands to the VSEL (which inverts the 4692 // condition in the sense of firing whenever the previous condition didn't) 4693 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 4694 TrueVal.getValueType() == MVT::f32 || 4695 TrueVal.getValueType() == MVT::f64)) { 4696 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4697 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4698 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4699 CC = ISD::getSetCCInverse(CC, true); 4700 std::swap(TrueVal, FalseVal); 4701 } 4702 } 4703 4704 SDValue ARMcc; 4705 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4706 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4707 // Choose GE over PL, which vsel does now support 4708 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 4709 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 4710 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4711 } 4712 4713 ARMCC::CondCodes CondCode, CondCode2; 4714 bool InvalidOnQNaN; 4715 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4716 4717 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 4718 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 4719 // must use VSEL (limited condition codes), due to not having conditional f16 4720 // moves. 4721 if (Subtarget->hasFPARMv8Base() && 4722 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 4723 (TrueVal.getValueType() == MVT::f16 || 4724 TrueVal.getValueType() == MVT::f32 || 4725 TrueVal.getValueType() == MVT::f64)) { 4726 bool swpCmpOps = false; 4727 bool swpVselOps = false; 4728 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4729 4730 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4731 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4732 if (swpCmpOps) 4733 std::swap(LHS, RHS); 4734 if (swpVselOps) 4735 std::swap(TrueVal, FalseVal); 4736 } 4737 } 4738 4739 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4740 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4741 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4742 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4743 if (CondCode2 != ARMCC::AL) { 4744 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4745 // FIXME: Needs another CMP because flag can have but one use. 4746 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4747 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4748 } 4749 return Result; 4750 } 4751 4752 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4753 /// to morph to an integer compare sequence. 4754 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4755 const ARMSubtarget *Subtarget) { 4756 SDNode *N = Op.getNode(); 4757 if (!N->hasOneUse()) 4758 // Otherwise it requires moving the value from fp to integer registers. 4759 return false; 4760 if (!N->getNumValues()) 4761 return false; 4762 EVT VT = Op.getValueType(); 4763 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4764 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4765 // vmrs are very slow, e.g. cortex-a8. 4766 return false; 4767 4768 if (isFloatingPointZero(Op)) { 4769 SeenZero = true; 4770 return true; 4771 } 4772 return ISD::isNormalLoad(N); 4773 } 4774 4775 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4776 if (isFloatingPointZero(Op)) 4777 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4778 4779 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4780 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4781 Ld->getPointerInfo(), Ld->getAlignment(), 4782 Ld->getMemOperand()->getFlags()); 4783 4784 llvm_unreachable("Unknown VFP cmp argument!"); 4785 } 4786 4787 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4788 SDValue &RetVal1, SDValue &RetVal2) { 4789 SDLoc dl(Op); 4790 4791 if (isFloatingPointZero(Op)) { 4792 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4793 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4794 return; 4795 } 4796 4797 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4798 SDValue Ptr = Ld->getBasePtr(); 4799 RetVal1 = 4800 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4801 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4802 4803 EVT PtrType = Ptr.getValueType(); 4804 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4805 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4806 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4807 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4808 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4809 Ld->getMemOperand()->getFlags()); 4810 return; 4811 } 4812 4813 llvm_unreachable("Unknown VFP cmp argument!"); 4814 } 4815 4816 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4817 /// f32 and even f64 comparisons to integer ones. 4818 SDValue 4819 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4820 SDValue Chain = Op.getOperand(0); 4821 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4822 SDValue LHS = Op.getOperand(2); 4823 SDValue RHS = Op.getOperand(3); 4824 SDValue Dest = Op.getOperand(4); 4825 SDLoc dl(Op); 4826 4827 bool LHSSeenZero = false; 4828 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4829 bool RHSSeenZero = false; 4830 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4831 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4832 // If unsafe fp math optimization is enabled and there are no other uses of 4833 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4834 // to an integer comparison. 4835 if (CC == ISD::SETOEQ) 4836 CC = ISD::SETEQ; 4837 else if (CC == ISD::SETUNE) 4838 CC = ISD::SETNE; 4839 4840 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4841 SDValue ARMcc; 4842 if (LHS.getValueType() == MVT::f32) { 4843 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4844 bitcastf32Toi32(LHS, DAG), Mask); 4845 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4846 bitcastf32Toi32(RHS, DAG), Mask); 4847 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4848 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4849 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4850 Chain, Dest, ARMcc, CCR, Cmp); 4851 } 4852 4853 SDValue LHS1, LHS2; 4854 SDValue RHS1, RHS2; 4855 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4856 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4857 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4858 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4859 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4860 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4861 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4862 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4863 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4864 } 4865 4866 return SDValue(); 4867 } 4868 4869 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4870 SDValue Chain = Op.getOperand(0); 4871 SDValue Cond = Op.getOperand(1); 4872 SDValue Dest = Op.getOperand(2); 4873 SDLoc dl(Op); 4874 4875 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4876 // instruction. 4877 unsigned Opc = Cond.getOpcode(); 4878 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4879 !Subtarget->isThumb1Only(); 4880 if (Cond.getResNo() == 1 && 4881 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4882 Opc == ISD::USUBO || OptimizeMul)) { 4883 // Only lower legal XALUO ops. 4884 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4885 return SDValue(); 4886 4887 // The actual operation with overflow check. 4888 SDValue Value, OverflowCmp; 4889 SDValue ARMcc; 4890 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4891 4892 // Reverse the condition code. 4893 ARMCC::CondCodes CondCode = 4894 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4895 CondCode = ARMCC::getOppositeCondition(CondCode); 4896 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4897 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4898 4899 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4900 OverflowCmp); 4901 } 4902 4903 return SDValue(); 4904 } 4905 4906 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4907 SDValue Chain = Op.getOperand(0); 4908 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4909 SDValue LHS = Op.getOperand(2); 4910 SDValue RHS = Op.getOperand(3); 4911 SDValue Dest = Op.getOperand(4); 4912 SDLoc dl(Op); 4913 4914 if (isUnsupportedFloatingType(LHS.getValueType())) { 4915 DAG.getTargetLoweringInfo().softenSetCCOperands( 4916 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 4917 4918 // If softenSetCCOperands only returned one value, we should compare it to 4919 // zero. 4920 if (!RHS.getNode()) { 4921 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4922 CC = ISD::SETNE; 4923 } 4924 } 4925 4926 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4927 // instruction. 4928 unsigned Opc = LHS.getOpcode(); 4929 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4930 !Subtarget->isThumb1Only(); 4931 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4932 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4933 Opc == ISD::USUBO || OptimizeMul) && 4934 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4935 // Only lower legal XALUO ops. 4936 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4937 return SDValue(); 4938 4939 // The actual operation with overflow check. 4940 SDValue Value, OverflowCmp; 4941 SDValue ARMcc; 4942 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4943 4944 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4945 // Reverse the condition code. 4946 ARMCC::CondCodes CondCode = 4947 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4948 CondCode = ARMCC::getOppositeCondition(CondCode); 4949 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4950 } 4951 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4952 4953 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4954 OverflowCmp); 4955 } 4956 4957 if (LHS.getValueType() == MVT::i32) { 4958 SDValue ARMcc; 4959 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4960 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4961 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4962 Chain, Dest, ARMcc, CCR, Cmp); 4963 } 4964 4965 if (getTargetMachine().Options.UnsafeFPMath && 4966 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4967 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4968 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4969 return Result; 4970 } 4971 4972 ARMCC::CondCodes CondCode, CondCode2; 4973 bool InvalidOnQNaN; 4974 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4975 4976 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4977 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4978 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4979 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4980 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4981 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4982 if (CondCode2 != ARMCC::AL) { 4983 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4984 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4985 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4986 } 4987 return Res; 4988 } 4989 4990 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4991 SDValue Chain = Op.getOperand(0); 4992 SDValue Table = Op.getOperand(1); 4993 SDValue Index = Op.getOperand(2); 4994 SDLoc dl(Op); 4995 4996 EVT PTy = getPointerTy(DAG.getDataLayout()); 4997 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4998 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4999 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5000 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5001 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5002 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5003 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5004 // which does another jump to the destination. This also makes it easier 5005 // to translate it to TBB / TBH later (Thumb2 only). 5006 // FIXME: This might not work if the function is extremely large. 5007 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5008 Addr, Op.getOperand(2), JTI); 5009 } 5010 if (isPositionIndependent() || Subtarget->isROPI()) { 5011 Addr = 5012 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5013 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5014 Chain = Addr.getValue(1); 5015 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5016 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5017 } else { 5018 Addr = 5019 DAG.getLoad(PTy, dl, Chain, Addr, 5020 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5021 Chain = Addr.getValue(1); 5022 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5023 } 5024 } 5025 5026 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5027 EVT VT = Op.getValueType(); 5028 SDLoc dl(Op); 5029 5030 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5031 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5032 return Op; 5033 return DAG.UnrollVectorOp(Op.getNode()); 5034 } 5035 5036 const bool HasFullFP16 = 5037 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5038 5039 EVT NewTy; 5040 const EVT OpTy = Op.getOperand(0).getValueType(); 5041 if (OpTy == MVT::v4f32) 5042 NewTy = MVT::v4i32; 5043 else if (OpTy == MVT::v4f16 && HasFullFP16) 5044 NewTy = MVT::v4i16; 5045 else if (OpTy == MVT::v8f16 && HasFullFP16) 5046 NewTy = MVT::v8i16; 5047 else 5048 llvm_unreachable("Invalid type for custom lowering!"); 5049 5050 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5051 return DAG.UnrollVectorOp(Op.getNode()); 5052 5053 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5054 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5055 } 5056 5057 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5058 EVT VT = Op.getValueType(); 5059 if (VT.isVector()) 5060 return LowerVectorFP_TO_INT(Op, DAG); 5061 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) { 5062 RTLIB::Libcall LC; 5063 if (Op.getOpcode() == ISD::FP_TO_SINT) 5064 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 5065 Op.getValueType()); 5066 else 5067 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 5068 Op.getValueType()); 5069 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5070 /*isSigned*/ false, SDLoc(Op)).first; 5071 } 5072 5073 return Op; 5074 } 5075 5076 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5077 EVT VT = Op.getValueType(); 5078 SDLoc dl(Op); 5079 5080 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5081 if (VT.getVectorElementType() == MVT::f32) 5082 return Op; 5083 return DAG.UnrollVectorOp(Op.getNode()); 5084 } 5085 5086 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5087 Op.getOperand(0).getValueType() == MVT::v8i16) && 5088 "Invalid type for custom lowering!"); 5089 5090 const bool HasFullFP16 = 5091 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5092 5093 EVT DestVecType; 5094 if (VT == MVT::v4f32) 5095 DestVecType = MVT::v4i32; 5096 else if (VT == MVT::v4f16 && HasFullFP16) 5097 DestVecType = MVT::v4i16; 5098 else if (VT == MVT::v8f16 && HasFullFP16) 5099 DestVecType = MVT::v8i16; 5100 else 5101 return DAG.UnrollVectorOp(Op.getNode()); 5102 5103 unsigned CastOpc; 5104 unsigned Opc; 5105 switch (Op.getOpcode()) { 5106 default: llvm_unreachable("Invalid opcode!"); 5107 case ISD::SINT_TO_FP: 5108 CastOpc = ISD::SIGN_EXTEND; 5109 Opc = ISD::SINT_TO_FP; 5110 break; 5111 case ISD::UINT_TO_FP: 5112 CastOpc = ISD::ZERO_EXTEND; 5113 Opc = ISD::UINT_TO_FP; 5114 break; 5115 } 5116 5117 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5118 return DAG.getNode(Opc, dl, VT, Op); 5119 } 5120 5121 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5122 EVT VT = Op.getValueType(); 5123 if (VT.isVector()) 5124 return LowerVectorINT_TO_FP(Op, DAG); 5125 if (isUnsupportedFloatingType(VT)) { 5126 RTLIB::Libcall LC; 5127 if (Op.getOpcode() == ISD::SINT_TO_FP) 5128 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5129 Op.getValueType()); 5130 else 5131 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5132 Op.getValueType()); 5133 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5134 /*isSigned*/ false, SDLoc(Op)).first; 5135 } 5136 5137 return Op; 5138 } 5139 5140 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5141 // Implement fcopysign with a fabs and a conditional fneg. 5142 SDValue Tmp0 = Op.getOperand(0); 5143 SDValue Tmp1 = Op.getOperand(1); 5144 SDLoc dl(Op); 5145 EVT VT = Op.getValueType(); 5146 EVT SrcVT = Tmp1.getValueType(); 5147 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5148 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5149 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5150 5151 if (UseNEON) { 5152 // Use VBSL to copy the sign bit. 5153 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5154 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5155 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5156 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5157 if (VT == MVT::f64) 5158 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5159 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5160 DAG.getConstant(32, dl, MVT::i32)); 5161 else /*if (VT == MVT::f32)*/ 5162 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5163 if (SrcVT == MVT::f32) { 5164 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5165 if (VT == MVT::f64) 5166 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5167 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5168 DAG.getConstant(32, dl, MVT::i32)); 5169 } else if (VT == MVT::f32) 5170 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5171 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5172 DAG.getConstant(32, dl, MVT::i32)); 5173 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5174 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5175 5176 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5177 dl, MVT::i32); 5178 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5179 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5180 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5181 5182 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5183 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5184 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5185 if (VT == MVT::f32) { 5186 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5187 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5188 DAG.getConstant(0, dl, MVT::i32)); 5189 } else { 5190 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5191 } 5192 5193 return Res; 5194 } 5195 5196 // Bitcast operand 1 to i32. 5197 if (SrcVT == MVT::f64) 5198 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5199 Tmp1).getValue(1); 5200 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5201 5202 // Or in the signbit with integer operations. 5203 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5204 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5205 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5206 if (VT == MVT::f32) { 5207 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5208 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5209 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5210 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5211 } 5212 5213 // f64: Or the high part with signbit and then combine two parts. 5214 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5215 Tmp0); 5216 SDValue Lo = Tmp0.getValue(0); 5217 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5218 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5219 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5220 } 5221 5222 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5223 MachineFunction &MF = DAG.getMachineFunction(); 5224 MachineFrameInfo &MFI = MF.getFrameInfo(); 5225 MFI.setReturnAddressIsTaken(true); 5226 5227 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5228 return SDValue(); 5229 5230 EVT VT = Op.getValueType(); 5231 SDLoc dl(Op); 5232 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5233 if (Depth) { 5234 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5235 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5236 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5237 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5238 MachinePointerInfo()); 5239 } 5240 5241 // Return LR, which contains the return address. Mark it an implicit live-in. 5242 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5243 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5244 } 5245 5246 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5247 const ARMBaseRegisterInfo &ARI = 5248 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5249 MachineFunction &MF = DAG.getMachineFunction(); 5250 MachineFrameInfo &MFI = MF.getFrameInfo(); 5251 MFI.setFrameAddressIsTaken(true); 5252 5253 EVT VT = Op.getValueType(); 5254 SDLoc dl(Op); // FIXME probably not meaningful 5255 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5256 unsigned FrameReg = ARI.getFrameRegister(MF); 5257 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5258 while (Depth--) 5259 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5260 MachinePointerInfo()); 5261 return FrameAddr; 5262 } 5263 5264 // FIXME? Maybe this could be a TableGen attribute on some registers and 5265 // this table could be generated automatically from RegInfo. 5266 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5267 SelectionDAG &DAG) const { 5268 unsigned Reg = StringSwitch<unsigned>(RegName) 5269 .Case("sp", ARM::SP) 5270 .Default(0); 5271 if (Reg) 5272 return Reg; 5273 report_fatal_error(Twine("Invalid register name \"" 5274 + StringRef(RegName) + "\".")); 5275 } 5276 5277 // Result is 64 bit value so split into two 32 bit values and return as a 5278 // pair of values. 5279 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5280 SelectionDAG &DAG) { 5281 SDLoc DL(N); 5282 5283 // This function is only supposed to be called for i64 type destination. 5284 assert(N->getValueType(0) == MVT::i64 5285 && "ExpandREAD_REGISTER called for non-i64 type result."); 5286 5287 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5288 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5289 N->getOperand(0), 5290 N->getOperand(1)); 5291 5292 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5293 Read.getValue(1))); 5294 Results.push_back(Read.getOperand(0)); 5295 } 5296 5297 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5298 /// When \p DstVT, the destination type of \p BC, is on the vector 5299 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5300 /// it might be possible to combine them, such that everything stays on the 5301 /// vector register bank. 5302 /// \p return The node that would replace \p BT, if the combine 5303 /// is possible. 5304 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5305 SelectionDAG &DAG) { 5306 SDValue Op = BC->getOperand(0); 5307 EVT DstVT = BC->getValueType(0); 5308 5309 // The only vector instruction that can produce a scalar (remember, 5310 // since the bitcast was about to be turned into VMOVDRR, the source 5311 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5312 // Moreover, we can do this combine only if there is one use. 5313 // Finally, if the destination type is not a vector, there is not 5314 // much point on forcing everything on the vector bank. 5315 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5316 !Op.hasOneUse()) 5317 return SDValue(); 5318 5319 // If the index is not constant, we will introduce an additional 5320 // multiply that will stick. 5321 // Give up in that case. 5322 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5323 if (!Index) 5324 return SDValue(); 5325 unsigned DstNumElt = DstVT.getVectorNumElements(); 5326 5327 // Compute the new index. 5328 const APInt &APIntIndex = Index->getAPIntValue(); 5329 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5330 NewIndex *= APIntIndex; 5331 // Check if the new constant index fits into i32. 5332 if (NewIndex.getBitWidth() > 32) 5333 return SDValue(); 5334 5335 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5336 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5337 SDLoc dl(Op); 5338 SDValue ExtractSrc = Op.getOperand(0); 5339 EVT VecVT = EVT::getVectorVT( 5340 *DAG.getContext(), DstVT.getScalarType(), 5341 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5342 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5343 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5344 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5345 } 5346 5347 /// ExpandBITCAST - If the target supports VFP, this function is called to 5348 /// expand a bit convert where either the source or destination type is i64 to 5349 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5350 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5351 /// vectors), since the legalizer won't know what to do with that. 5352 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5353 const ARMSubtarget *Subtarget) { 5354 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5355 SDLoc dl(N); 5356 SDValue Op = N->getOperand(0); 5357 5358 // This function is only supposed to be called for i64 types, either as the 5359 // source or destination of the bit convert. 5360 EVT SrcVT = Op.getValueType(); 5361 EVT DstVT = N->getValueType(0); 5362 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5363 5364 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5365 // FullFP16: half values are passed in S-registers, and we don't 5366 // need any of the bitcast and moves: 5367 // 5368 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5369 // t5: i32 = bitcast t2 5370 // t18: f16 = ARMISD::VMOVhr t5 5371 if (Op.getOpcode() != ISD::CopyFromReg || 5372 Op.getValueType() != MVT::f32) 5373 return SDValue(); 5374 5375 auto Move = N->use_begin(); 5376 if (Move->getOpcode() != ARMISD::VMOVhr) 5377 return SDValue(); 5378 5379 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5380 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5381 DAG.ReplaceAllUsesWith(*Move, &Copy); 5382 return Copy; 5383 } 5384 5385 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5386 if (!HasFullFP16) 5387 return SDValue(); 5388 // SoftFP: read half-precision arguments: 5389 // 5390 // t2: i32,ch = ... 5391 // t7: i16 = truncate t2 <~~~~ Op 5392 // t8: f16 = bitcast t7 <~~~~ N 5393 // 5394 if (Op.getOperand(0).getValueType() == MVT::i32) 5395 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5396 MVT::f16, Op.getOperand(0)); 5397 5398 return SDValue(); 5399 } 5400 5401 // Half-precision return values 5402 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5403 if (!HasFullFP16) 5404 return SDValue(); 5405 // 5406 // t11: f16 = fadd t8, t10 5407 // t12: i16 = bitcast t11 <~~~ SDNode N 5408 // t13: i32 = zero_extend t12 5409 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5410 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5411 // 5412 // transform this into: 5413 // 5414 // t20: i32 = ARMISD::VMOVrh t11 5415 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5416 // 5417 auto ZeroExtend = N->use_begin(); 5418 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5419 ZeroExtend->getValueType(0) != MVT::i32) 5420 return SDValue(); 5421 5422 auto Copy = ZeroExtend->use_begin(); 5423 if (Copy->getOpcode() == ISD::CopyToReg && 5424 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5425 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5426 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5427 return Cvt; 5428 } 5429 return SDValue(); 5430 } 5431 5432 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5433 return SDValue(); 5434 5435 // Turn i64->f64 into VMOVDRR. 5436 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5437 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5438 // if we can combine the bitcast with its source. 5439 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5440 return Val; 5441 5442 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5443 DAG.getConstant(0, dl, MVT::i32)); 5444 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5445 DAG.getConstant(1, dl, MVT::i32)); 5446 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5447 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5448 } 5449 5450 // Turn f64->i64 into VMOVRRD. 5451 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5452 SDValue Cvt; 5453 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5454 SrcVT.getVectorNumElements() > 1) 5455 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5456 DAG.getVTList(MVT::i32, MVT::i32), 5457 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5458 else 5459 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5460 DAG.getVTList(MVT::i32, MVT::i32), Op); 5461 // Merge the pieces into a single i64 value. 5462 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5463 } 5464 5465 return SDValue(); 5466 } 5467 5468 /// getZeroVector - Returns a vector of specified type with all zero elements. 5469 /// Zero vectors are used to represent vector negation and in those cases 5470 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5471 /// not support i64 elements, so sometimes the zero vectors will need to be 5472 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5473 /// zero vector. 5474 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5475 assert(VT.isVector() && "Expected a vector type"); 5476 // The canonical modified immediate encoding of a zero vector is....0! 5477 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5478 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5479 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5480 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5481 } 5482 5483 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5484 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5485 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5486 SelectionDAG &DAG) const { 5487 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5488 EVT VT = Op.getValueType(); 5489 unsigned VTBits = VT.getSizeInBits(); 5490 SDLoc dl(Op); 5491 SDValue ShOpLo = Op.getOperand(0); 5492 SDValue ShOpHi = Op.getOperand(1); 5493 SDValue ShAmt = Op.getOperand(2); 5494 SDValue ARMcc; 5495 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5496 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5497 5498 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5499 5500 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5501 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5502 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5503 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5504 DAG.getConstant(VTBits, dl, MVT::i32)); 5505 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5506 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5507 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5508 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5509 ISD::SETGE, ARMcc, DAG, dl); 5510 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5511 ARMcc, CCR, CmpLo); 5512 5513 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5514 SDValue HiBigShift = Opc == ISD::SRA 5515 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5516 DAG.getConstant(VTBits - 1, dl, VT)) 5517 : DAG.getConstant(0, dl, VT); 5518 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5519 ISD::SETGE, ARMcc, DAG, dl); 5520 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5521 ARMcc, CCR, CmpHi); 5522 5523 SDValue Ops[2] = { Lo, Hi }; 5524 return DAG.getMergeValues(Ops, dl); 5525 } 5526 5527 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5528 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5529 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5530 SelectionDAG &DAG) const { 5531 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5532 EVT VT = Op.getValueType(); 5533 unsigned VTBits = VT.getSizeInBits(); 5534 SDLoc dl(Op); 5535 SDValue ShOpLo = Op.getOperand(0); 5536 SDValue ShOpHi = Op.getOperand(1); 5537 SDValue ShAmt = Op.getOperand(2); 5538 SDValue ARMcc; 5539 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5540 5541 assert(Op.getOpcode() == ISD::SHL_PARTS); 5542 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5543 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5544 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5545 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5546 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5547 5548 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5549 DAG.getConstant(VTBits, dl, MVT::i32)); 5550 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5551 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5552 ISD::SETGE, ARMcc, DAG, dl); 5553 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5554 ARMcc, CCR, CmpHi); 5555 5556 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5557 ISD::SETGE, ARMcc, DAG, dl); 5558 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5559 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5560 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5561 5562 SDValue Ops[2] = { Lo, Hi }; 5563 return DAG.getMergeValues(Ops, dl); 5564 } 5565 5566 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5567 SelectionDAG &DAG) const { 5568 // The rounding mode is in bits 23:22 of the FPSCR. 5569 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5570 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5571 // so that the shift + and get folded into a bitfield extract. 5572 SDLoc dl(Op); 5573 SDValue Ops[] = { DAG.getEntryNode(), 5574 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5575 5576 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5577 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5578 DAG.getConstant(1U << 22, dl, MVT::i32)); 5579 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5580 DAG.getConstant(22, dl, MVT::i32)); 5581 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5582 DAG.getConstant(3, dl, MVT::i32)); 5583 } 5584 5585 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5586 const ARMSubtarget *ST) { 5587 SDLoc dl(N); 5588 EVT VT = N->getValueType(0); 5589 if (VT.isVector()) { 5590 assert(ST->hasNEON()); 5591 5592 // Compute the least significant set bit: LSB = X & -X 5593 SDValue X = N->getOperand(0); 5594 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5595 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5596 5597 EVT ElemTy = VT.getVectorElementType(); 5598 5599 if (ElemTy == MVT::i8) { 5600 // Compute with: cttz(x) = ctpop(lsb - 1) 5601 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5602 DAG.getTargetConstant(1, dl, ElemTy)); 5603 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5604 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5605 } 5606 5607 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5608 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5609 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5610 unsigned NumBits = ElemTy.getSizeInBits(); 5611 SDValue WidthMinus1 = 5612 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5613 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5614 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5615 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5616 } 5617 5618 // Compute with: cttz(x) = ctpop(lsb - 1) 5619 5620 // Compute LSB - 1. 5621 SDValue Bits; 5622 if (ElemTy == MVT::i64) { 5623 // Load constant 0xffff'ffff'ffff'ffff to register. 5624 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5625 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5626 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5627 } else { 5628 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5629 DAG.getTargetConstant(1, dl, ElemTy)); 5630 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5631 } 5632 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5633 } 5634 5635 if (!ST->hasV6T2Ops()) 5636 return SDValue(); 5637 5638 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5639 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5640 } 5641 5642 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5643 const ARMSubtarget *ST) { 5644 EVT VT = N->getValueType(0); 5645 SDLoc DL(N); 5646 5647 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5648 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5649 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5650 "Unexpected type for custom ctpop lowering"); 5651 5652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5653 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5654 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 5655 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 5656 5657 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5658 unsigned EltSize = 8; 5659 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5660 while (EltSize != VT.getScalarSizeInBits()) { 5661 SmallVector<SDValue, 8> Ops; 5662 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 5663 TLI.getPointerTy(DAG.getDataLayout()))); 5664 Ops.push_back(Res); 5665 5666 EltSize *= 2; 5667 NumElts /= 2; 5668 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5669 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 5670 } 5671 5672 return Res; 5673 } 5674 5675 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 5676 /// operand of a vector shift operation, where all the elements of the 5677 /// build_vector must have the same constant integer value. 5678 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 5679 // Ignore bit_converts. 5680 while (Op.getOpcode() == ISD::BITCAST) 5681 Op = Op.getOperand(0); 5682 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 5683 APInt SplatBits, SplatUndef; 5684 unsigned SplatBitSize; 5685 bool HasAnyUndefs; 5686 if (!BVN || 5687 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 5688 ElementBits) || 5689 SplatBitSize > ElementBits) 5690 return false; 5691 Cnt = SplatBits.getSExtValue(); 5692 return true; 5693 } 5694 5695 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 5696 /// operand of a vector shift left operation. That value must be in the range: 5697 /// 0 <= Value < ElementBits for a left shift; or 5698 /// 0 <= Value <= ElementBits for a long left shift. 5699 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 5700 assert(VT.isVector() && "vector shift count is not a vector type"); 5701 int64_t ElementBits = VT.getScalarSizeInBits(); 5702 if (!getVShiftImm(Op, ElementBits, Cnt)) 5703 return false; 5704 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 5705 } 5706 5707 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 5708 /// operand of a vector shift right operation. For a shift opcode, the value 5709 /// is positive, but for an intrinsic the value count must be negative. The 5710 /// absolute value must be in the range: 5711 /// 1 <= |Value| <= ElementBits for a right shift; or 5712 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 5713 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 5714 int64_t &Cnt) { 5715 assert(VT.isVector() && "vector shift count is not a vector type"); 5716 int64_t ElementBits = VT.getScalarSizeInBits(); 5717 if (!getVShiftImm(Op, ElementBits, Cnt)) 5718 return false; 5719 if (!isIntrinsic) 5720 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 5721 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 5722 Cnt = -Cnt; 5723 return true; 5724 } 5725 return false; 5726 } 5727 5728 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5729 const ARMSubtarget *ST) { 5730 EVT VT = N->getValueType(0); 5731 SDLoc dl(N); 5732 int64_t Cnt; 5733 5734 if (!VT.isVector()) 5735 return SDValue(); 5736 5737 // We essentially have two forms here. Shift by an immediate and shift by a 5738 // vector register (there are also shift by a gpr, but that is just handled 5739 // with a tablegen pattern). We cannot easily match shift by an immediate in 5740 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 5741 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 5742 // signed or unsigned, and a negative shift indicates a shift right). 5743 if (N->getOpcode() == ISD::SHL) { 5744 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 5745 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 5746 DAG.getConstant(Cnt, dl, MVT::i32)); 5747 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 5748 N->getOperand(1)); 5749 } 5750 5751 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 5752 "unexpected vector shift opcode"); 5753 5754 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 5755 unsigned VShiftOpc = 5756 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 5757 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 5758 DAG.getConstant(Cnt, dl, MVT::i32)); 5759 } 5760 5761 // Other right shifts we don't have operations for (we use a shift left by a 5762 // negative number). 5763 EVT ShiftVT = N->getOperand(1).getValueType(); 5764 SDValue NegatedCount = DAG.getNode( 5765 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 5766 unsigned VShiftOpc = 5767 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 5768 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 5769 } 5770 5771 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5772 const ARMSubtarget *ST) { 5773 EVT VT = N->getValueType(0); 5774 SDLoc dl(N); 5775 5776 // We can get here for a node like i32 = ISD::SHL i32, i64 5777 if (VT != MVT::i64) 5778 return SDValue(); 5779 5780 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 5781 N->getOpcode() == ISD::SHL) && 5782 "Unknown shift to lower!"); 5783 5784 unsigned ShOpc = N->getOpcode(); 5785 if (ST->hasMVEIntegerOps()) { 5786 SDValue ShAmt = N->getOperand(1); 5787 unsigned ShPartsOpc = ARMISD::LSLL; 5788 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 5789 5790 // If the shift amount is greater than 32 then do the default optimisation 5791 if (Con && Con->getZExtValue() > 32) 5792 return SDValue(); 5793 5794 // Extract the lower 32 bits of the shift amount if it's an i64 5795 if (ShAmt->getValueType(0) == MVT::i64) 5796 ShAmt = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, ShAmt, 5797 DAG.getConstant(0, dl, MVT::i32)); 5798 5799 if (ShOpc == ISD::SRL) { 5800 if (!Con) 5801 // There is no t2LSRLr instruction so negate and perform an lsll if the 5802 // shift amount is in a register, emulating a right shift. 5803 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5804 DAG.getConstant(0, dl, MVT::i32), ShAmt); 5805 else 5806 // Else generate an lsrl on the immediate shift amount 5807 ShPartsOpc = ARMISD::LSRL; 5808 } else if (ShOpc == ISD::SRA) 5809 ShPartsOpc = ARMISD::ASRL; 5810 5811 // Lower 32 bits of the destination/source 5812 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5813 DAG.getConstant(0, dl, MVT::i32)); 5814 // Upper 32 bits of the destination/source 5815 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5816 DAG.getConstant(1, dl, MVT::i32)); 5817 5818 // Generate the shift operation as computed above 5819 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 5820 ShAmt); 5821 // The upper 32 bits come from the second return value of lsll 5822 Hi = SDValue(Lo.getNode(), 1); 5823 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5824 } 5825 5826 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5827 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 5828 return SDValue(); 5829 5830 // If we are in thumb mode, we don't have RRX. 5831 if (ST->isThumb1Only()) 5832 return SDValue(); 5833 5834 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5835 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5836 DAG.getConstant(0, dl, MVT::i32)); 5837 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5838 DAG.getConstant(1, dl, MVT::i32)); 5839 5840 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5841 // captures the result into a carry flag. 5842 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5843 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5844 5845 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5846 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5847 5848 // Merge the pieces into a single i64 value. 5849 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5850 } 5851 5852 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5853 SDValue TmpOp0, TmpOp1; 5854 bool Invert = false; 5855 bool Swap = false; 5856 unsigned Opc = 0; 5857 5858 SDValue Op0 = Op.getOperand(0); 5859 SDValue Op1 = Op.getOperand(1); 5860 SDValue CC = Op.getOperand(2); 5861 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5862 EVT VT = Op.getValueType(); 5863 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5864 SDLoc dl(Op); 5865 5866 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5867 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5868 // Special-case integer 64-bit equality comparisons. They aren't legal, 5869 // but they can be lowered with a few vector instructions. 5870 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5871 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5872 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5873 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5874 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5875 DAG.getCondCode(ISD::SETEQ)); 5876 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5877 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5878 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5879 if (SetCCOpcode == ISD::SETNE) 5880 Merged = DAG.getNOT(dl, Merged, CmpVT); 5881 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5882 return Merged; 5883 } 5884 5885 if (CmpVT.getVectorElementType() == MVT::i64) 5886 // 64-bit comparisons are not legal in general. 5887 return SDValue(); 5888 5889 if (Op1.getValueType().isFloatingPoint()) { 5890 switch (SetCCOpcode) { 5891 default: llvm_unreachable("Illegal FP comparison"); 5892 case ISD::SETUNE: 5893 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5894 case ISD::SETOEQ: 5895 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5896 case ISD::SETOLT: 5897 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5898 case ISD::SETOGT: 5899 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5900 case ISD::SETOLE: 5901 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5902 case ISD::SETOGE: 5903 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5904 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5905 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5906 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5907 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5908 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5909 case ISD::SETONE: 5910 // Expand this to (OLT | OGT). 5911 TmpOp0 = Op0; 5912 TmpOp1 = Op1; 5913 Opc = ISD::OR; 5914 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5915 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5916 break; 5917 case ISD::SETUO: 5918 Invert = true; 5919 LLVM_FALLTHROUGH; 5920 case ISD::SETO: 5921 // Expand this to (OLT | OGE). 5922 TmpOp0 = Op0; 5923 TmpOp1 = Op1; 5924 Opc = ISD::OR; 5925 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5926 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5927 break; 5928 } 5929 } else { 5930 // Integer comparisons. 5931 switch (SetCCOpcode) { 5932 default: llvm_unreachable("Illegal integer comparison"); 5933 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5934 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5935 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5936 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5937 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5938 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5939 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5940 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5941 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5942 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5943 } 5944 5945 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5946 if (Opc == ARMISD::VCEQ) { 5947 SDValue AndOp; 5948 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5949 AndOp = Op0; 5950 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5951 AndOp = Op1; 5952 5953 // Ignore bitconvert. 5954 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5955 AndOp = AndOp.getOperand(0); 5956 5957 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5958 Opc = ARMISD::VTST; 5959 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5960 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5961 Invert = !Invert; 5962 } 5963 } 5964 } 5965 5966 if (Swap) 5967 std::swap(Op0, Op1); 5968 5969 // If one of the operands is a constant vector zero, attempt to fold the 5970 // comparison to a specialized compare-against-zero form. 5971 SDValue SingleOp; 5972 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5973 SingleOp = Op0; 5974 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5975 if (Opc == ARMISD::VCGE) 5976 Opc = ARMISD::VCLEZ; 5977 else if (Opc == ARMISD::VCGT) 5978 Opc = ARMISD::VCLTZ; 5979 SingleOp = Op1; 5980 } 5981 5982 SDValue Result; 5983 if (SingleOp.getNode()) { 5984 switch (Opc) { 5985 case ARMISD::VCEQ: 5986 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5987 case ARMISD::VCGE: 5988 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5989 case ARMISD::VCLEZ: 5990 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5991 case ARMISD::VCGT: 5992 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5993 case ARMISD::VCLTZ: 5994 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5995 default: 5996 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5997 } 5998 } else { 5999 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 6000 } 6001 6002 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6003 6004 if (Invert) 6005 Result = DAG.getNOT(dl, Result, VT); 6006 6007 return Result; 6008 } 6009 6010 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6011 SDValue LHS = Op.getOperand(0); 6012 SDValue RHS = Op.getOperand(1); 6013 SDValue Carry = Op.getOperand(2); 6014 SDValue Cond = Op.getOperand(3); 6015 SDLoc DL(Op); 6016 6017 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6018 6019 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6020 // have to invert the carry first. 6021 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6022 DAG.getConstant(1, DL, MVT::i32), Carry); 6023 // This converts the boolean value carry into the carry flag. 6024 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6025 6026 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6027 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6028 6029 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6030 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6031 SDValue ARMcc = DAG.getConstant( 6032 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6033 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6034 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6035 Cmp.getValue(1), SDValue()); 6036 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6037 CCR, Chain.getValue(1)); 6038 } 6039 6040 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6041 /// valid vector constant for a NEON or MVE instruction with a "modified 6042 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6043 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6044 unsigned SplatBitSize, SelectionDAG &DAG, 6045 const SDLoc &dl, EVT &VT, bool is128Bits, 6046 VMOVModImmType type) { 6047 unsigned OpCmode, Imm; 6048 6049 // SplatBitSize is set to the smallest size that splats the vector, so a 6050 // zero vector will always have SplatBitSize == 8. However, NEON modified 6051 // immediate instructions others than VMOV do not support the 8-bit encoding 6052 // of a zero vector, and the default encoding of zero is supposed to be the 6053 // 32-bit version. 6054 if (SplatBits == 0) 6055 SplatBitSize = 32; 6056 6057 switch (SplatBitSize) { 6058 case 8: 6059 if (type != VMOVModImm) 6060 return SDValue(); 6061 // Any 1-byte value is OK. Op=0, Cmode=1110. 6062 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6063 OpCmode = 0xe; 6064 Imm = SplatBits; 6065 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6066 break; 6067 6068 case 16: 6069 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6070 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6071 if ((SplatBits & ~0xff) == 0) { 6072 // Value = 0x00nn: Op=x, Cmode=100x. 6073 OpCmode = 0x8; 6074 Imm = SplatBits; 6075 break; 6076 } 6077 if ((SplatBits & ~0xff00) == 0) { 6078 // Value = 0xnn00: Op=x, Cmode=101x. 6079 OpCmode = 0xa; 6080 Imm = SplatBits >> 8; 6081 break; 6082 } 6083 return SDValue(); 6084 6085 case 32: 6086 // NEON's 32-bit VMOV supports splat values where: 6087 // * only one byte is nonzero, or 6088 // * the least significant byte is 0xff and the second byte is nonzero, or 6089 // * the least significant 2 bytes are 0xff and the third is nonzero. 6090 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6091 if ((SplatBits & ~0xff) == 0) { 6092 // Value = 0x000000nn: Op=x, Cmode=000x. 6093 OpCmode = 0; 6094 Imm = SplatBits; 6095 break; 6096 } 6097 if ((SplatBits & ~0xff00) == 0) { 6098 // Value = 0x0000nn00: Op=x, Cmode=001x. 6099 OpCmode = 0x2; 6100 Imm = SplatBits >> 8; 6101 break; 6102 } 6103 if ((SplatBits & ~0xff0000) == 0) { 6104 // Value = 0x00nn0000: Op=x, Cmode=010x. 6105 OpCmode = 0x4; 6106 Imm = SplatBits >> 16; 6107 break; 6108 } 6109 if ((SplatBits & ~0xff000000) == 0) { 6110 // Value = 0xnn000000: Op=x, Cmode=011x. 6111 OpCmode = 0x6; 6112 Imm = SplatBits >> 24; 6113 break; 6114 } 6115 6116 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6117 if (type == OtherModImm) return SDValue(); 6118 6119 if ((SplatBits & ~0xffff) == 0 && 6120 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6121 // Value = 0x0000nnff: Op=x, Cmode=1100. 6122 OpCmode = 0xc; 6123 Imm = SplatBits >> 8; 6124 break; 6125 } 6126 6127 // cmode == 0b1101 is not supported for MVE VMVN 6128 if (type == MVEVMVNModImm) 6129 return SDValue(); 6130 6131 if ((SplatBits & ~0xffffff) == 0 && 6132 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6133 // Value = 0x00nnffff: Op=x, Cmode=1101. 6134 OpCmode = 0xd; 6135 Imm = SplatBits >> 16; 6136 break; 6137 } 6138 6139 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6140 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6141 // VMOV.I32. A (very) minor optimization would be to replicate the value 6142 // and fall through here to test for a valid 64-bit splat. But, then the 6143 // caller would also need to check and handle the change in size. 6144 return SDValue(); 6145 6146 case 64: { 6147 if (type != VMOVModImm) 6148 return SDValue(); 6149 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6150 uint64_t BitMask = 0xff; 6151 uint64_t Val = 0; 6152 unsigned ImmMask = 1; 6153 Imm = 0; 6154 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6155 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6156 Val |= BitMask; 6157 Imm |= ImmMask; 6158 } else if ((SplatBits & BitMask) != 0) { 6159 return SDValue(); 6160 } 6161 BitMask <<= 8; 6162 ImmMask <<= 1; 6163 } 6164 6165 if (DAG.getDataLayout().isBigEndian()) 6166 // swap higher and lower 32 bit word 6167 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 6168 6169 // Op=1, Cmode=1110. 6170 OpCmode = 0x1e; 6171 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6172 break; 6173 } 6174 6175 default: 6176 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6177 } 6178 6179 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6180 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6181 } 6182 6183 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6184 const ARMSubtarget *ST) const { 6185 EVT VT = Op.getValueType(); 6186 bool IsDouble = (VT == MVT::f64); 6187 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6188 const APFloat &FPVal = CFP->getValueAPF(); 6189 6190 // Prevent floating-point constants from using literal loads 6191 // when execute-only is enabled. 6192 if (ST->genExecuteOnly()) { 6193 // If we can represent the constant as an immediate, don't lower it 6194 if (isFPImmLegal(FPVal, VT)) 6195 return Op; 6196 // Otherwise, construct as integer, and move to float register 6197 APInt INTVal = FPVal.bitcastToAPInt(); 6198 SDLoc DL(CFP); 6199 switch (VT.getSimpleVT().SimpleTy) { 6200 default: 6201 llvm_unreachable("Unknown floating point type!"); 6202 break; 6203 case MVT::f64: { 6204 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6205 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6206 if (!ST->isLittle()) 6207 std::swap(Lo, Hi); 6208 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6209 } 6210 case MVT::f32: 6211 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6212 DAG.getConstant(INTVal, DL, MVT::i32)); 6213 } 6214 } 6215 6216 if (!ST->hasVFP3Base()) 6217 return SDValue(); 6218 6219 // Use the default (constant pool) lowering for double constants when we have 6220 // an SP-only FPU 6221 if (IsDouble && !Subtarget->hasFP64()) 6222 return SDValue(); 6223 6224 // Try splatting with a VMOV.f32... 6225 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6226 6227 if (ImmVal != -1) { 6228 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6229 // We have code in place to select a valid ConstantFP already, no need to 6230 // do any mangling. 6231 return Op; 6232 } 6233 6234 // It's a float and we are trying to use NEON operations where 6235 // possible. Lower it to a splat followed by an extract. 6236 SDLoc DL(Op); 6237 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6238 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6239 NewVal); 6240 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6241 DAG.getConstant(0, DL, MVT::i32)); 6242 } 6243 6244 // The rest of our options are NEON only, make sure that's allowed before 6245 // proceeding.. 6246 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6247 return SDValue(); 6248 6249 EVT VMovVT; 6250 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6251 6252 // It wouldn't really be worth bothering for doubles except for one very 6253 // important value, which does happen to match: 0.0. So make sure we don't do 6254 // anything stupid. 6255 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6256 return SDValue(); 6257 6258 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6259 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6260 VMovVT, false, VMOVModImm); 6261 if (NewVal != SDValue()) { 6262 SDLoc DL(Op); 6263 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6264 NewVal); 6265 if (IsDouble) 6266 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6267 6268 // It's a float: cast and extract a vector element. 6269 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6270 VecConstant); 6271 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6272 DAG.getConstant(0, DL, MVT::i32)); 6273 } 6274 6275 // Finally, try a VMVN.i32 6276 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6277 false, VMVNModImm); 6278 if (NewVal != SDValue()) { 6279 SDLoc DL(Op); 6280 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6281 6282 if (IsDouble) 6283 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6284 6285 // It's a float: cast and extract a vector element. 6286 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6287 VecConstant); 6288 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6289 DAG.getConstant(0, DL, MVT::i32)); 6290 } 6291 6292 return SDValue(); 6293 } 6294 6295 // check if an VEXT instruction can handle the shuffle mask when the 6296 // vector sources of the shuffle are the same. 6297 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6298 unsigned NumElts = VT.getVectorNumElements(); 6299 6300 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6301 if (M[0] < 0) 6302 return false; 6303 6304 Imm = M[0]; 6305 6306 // If this is a VEXT shuffle, the immediate value is the index of the first 6307 // element. The other shuffle indices must be the successive elements after 6308 // the first one. 6309 unsigned ExpectedElt = Imm; 6310 for (unsigned i = 1; i < NumElts; ++i) { 6311 // Increment the expected index. If it wraps around, just follow it 6312 // back to index zero and keep going. 6313 ++ExpectedElt; 6314 if (ExpectedElt == NumElts) 6315 ExpectedElt = 0; 6316 6317 if (M[i] < 0) continue; // ignore UNDEF indices 6318 if (ExpectedElt != static_cast<unsigned>(M[i])) 6319 return false; 6320 } 6321 6322 return true; 6323 } 6324 6325 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6326 bool &ReverseVEXT, unsigned &Imm) { 6327 unsigned NumElts = VT.getVectorNumElements(); 6328 ReverseVEXT = false; 6329 6330 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6331 if (M[0] < 0) 6332 return false; 6333 6334 Imm = M[0]; 6335 6336 // If this is a VEXT shuffle, the immediate value is the index of the first 6337 // element. The other shuffle indices must be the successive elements after 6338 // the first one. 6339 unsigned ExpectedElt = Imm; 6340 for (unsigned i = 1; i < NumElts; ++i) { 6341 // Increment the expected index. If it wraps around, it may still be 6342 // a VEXT but the source vectors must be swapped. 6343 ExpectedElt += 1; 6344 if (ExpectedElt == NumElts * 2) { 6345 ExpectedElt = 0; 6346 ReverseVEXT = true; 6347 } 6348 6349 if (M[i] < 0) continue; // ignore UNDEF indices 6350 if (ExpectedElt != static_cast<unsigned>(M[i])) 6351 return false; 6352 } 6353 6354 // Adjust the index value if the source operands will be swapped. 6355 if (ReverseVEXT) 6356 Imm -= NumElts; 6357 6358 return true; 6359 } 6360 6361 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6362 /// instruction with the specified blocksize. (The order of the elements 6363 /// within each block of the vector is reversed.) 6364 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6365 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6366 "Only possible block sizes for VREV are: 16, 32, 64"); 6367 6368 unsigned EltSz = VT.getScalarSizeInBits(); 6369 if (EltSz == 64) 6370 return false; 6371 6372 unsigned NumElts = VT.getVectorNumElements(); 6373 unsigned BlockElts = M[0] + 1; 6374 // If the first shuffle index is UNDEF, be optimistic. 6375 if (M[0] < 0) 6376 BlockElts = BlockSize / EltSz; 6377 6378 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6379 return false; 6380 6381 for (unsigned i = 0; i < NumElts; ++i) { 6382 if (M[i] < 0) continue; // ignore UNDEF indices 6383 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6384 return false; 6385 } 6386 6387 return true; 6388 } 6389 6390 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6391 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6392 // range, then 0 is placed into the resulting vector. So pretty much any mask 6393 // of 8 elements can work here. 6394 return VT == MVT::v8i8 && M.size() == 8; 6395 } 6396 6397 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6398 unsigned Index) { 6399 if (Mask.size() == Elements * 2) 6400 return Index / Elements; 6401 return Mask[Index] == 0 ? 0 : 1; 6402 } 6403 6404 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6405 // checking that pairs of elements in the shuffle mask represent the same index 6406 // in each vector, incrementing the expected index by 2 at each step. 6407 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6408 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6409 // v2={e,f,g,h} 6410 // WhichResult gives the offset for each element in the mask based on which 6411 // of the two results it belongs to. 6412 // 6413 // The transpose can be represented either as: 6414 // result1 = shufflevector v1, v2, result1_shuffle_mask 6415 // result2 = shufflevector v1, v2, result2_shuffle_mask 6416 // where v1/v2 and the shuffle masks have the same number of elements 6417 // (here WhichResult (see below) indicates which result is being checked) 6418 // 6419 // or as: 6420 // results = shufflevector v1, v2, shuffle_mask 6421 // where both results are returned in one vector and the shuffle mask has twice 6422 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6423 // want to check the low half and high half of the shuffle mask as if it were 6424 // the other case 6425 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6426 unsigned EltSz = VT.getScalarSizeInBits(); 6427 if (EltSz == 64) 6428 return false; 6429 6430 unsigned NumElts = VT.getVectorNumElements(); 6431 if (M.size() != NumElts && M.size() != NumElts*2) 6432 return false; 6433 6434 // If the mask is twice as long as the input vector then we need to check the 6435 // upper and lower parts of the mask with a matching value for WhichResult 6436 // FIXME: A mask with only even values will be rejected in case the first 6437 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6438 // M[0] is used to determine WhichResult 6439 for (unsigned i = 0; i < M.size(); i += NumElts) { 6440 WhichResult = SelectPairHalf(NumElts, M, i); 6441 for (unsigned j = 0; j < NumElts; j += 2) { 6442 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6443 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6444 return false; 6445 } 6446 } 6447 6448 if (M.size() == NumElts*2) 6449 WhichResult = 0; 6450 6451 return true; 6452 } 6453 6454 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6455 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6456 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6457 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6458 unsigned EltSz = VT.getScalarSizeInBits(); 6459 if (EltSz == 64) 6460 return false; 6461 6462 unsigned NumElts = VT.getVectorNumElements(); 6463 if (M.size() != NumElts && M.size() != NumElts*2) 6464 return false; 6465 6466 for (unsigned i = 0; i < M.size(); i += NumElts) { 6467 WhichResult = SelectPairHalf(NumElts, M, i); 6468 for (unsigned j = 0; j < NumElts; j += 2) { 6469 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6470 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6471 return false; 6472 } 6473 } 6474 6475 if (M.size() == NumElts*2) 6476 WhichResult = 0; 6477 6478 return true; 6479 } 6480 6481 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6482 // that the mask elements are either all even and in steps of size 2 or all odd 6483 // and in steps of size 2. 6484 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6485 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6486 // v2={e,f,g,h} 6487 // Requires similar checks to that of isVTRNMask with 6488 // respect the how results are returned. 6489 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6490 unsigned EltSz = VT.getScalarSizeInBits(); 6491 if (EltSz == 64) 6492 return false; 6493 6494 unsigned NumElts = VT.getVectorNumElements(); 6495 if (M.size() != NumElts && M.size() != NumElts*2) 6496 return false; 6497 6498 for (unsigned i = 0; i < M.size(); i += NumElts) { 6499 WhichResult = SelectPairHalf(NumElts, M, i); 6500 for (unsigned j = 0; j < NumElts; ++j) { 6501 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6502 return false; 6503 } 6504 } 6505 6506 if (M.size() == NumElts*2) 6507 WhichResult = 0; 6508 6509 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6510 if (VT.is64BitVector() && EltSz == 32) 6511 return false; 6512 6513 return true; 6514 } 6515 6516 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6517 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6518 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6519 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6520 unsigned EltSz = VT.getScalarSizeInBits(); 6521 if (EltSz == 64) 6522 return false; 6523 6524 unsigned NumElts = VT.getVectorNumElements(); 6525 if (M.size() != NumElts && M.size() != NumElts*2) 6526 return false; 6527 6528 unsigned Half = NumElts / 2; 6529 for (unsigned i = 0; i < M.size(); i += NumElts) { 6530 WhichResult = SelectPairHalf(NumElts, M, i); 6531 for (unsigned j = 0; j < NumElts; j += Half) { 6532 unsigned Idx = WhichResult; 6533 for (unsigned k = 0; k < Half; ++k) { 6534 int MIdx = M[i + j + k]; 6535 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6536 return false; 6537 Idx += 2; 6538 } 6539 } 6540 } 6541 6542 if (M.size() == NumElts*2) 6543 WhichResult = 0; 6544 6545 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6546 if (VT.is64BitVector() && EltSz == 32) 6547 return false; 6548 6549 return true; 6550 } 6551 6552 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6553 // that pairs of elements of the shufflemask represent the same index in each 6554 // vector incrementing sequentially through the vectors. 6555 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6556 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6557 // v2={e,f,g,h} 6558 // Requires similar checks to that of isVTRNMask with respect the how results 6559 // are returned. 6560 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6561 unsigned EltSz = VT.getScalarSizeInBits(); 6562 if (EltSz == 64) 6563 return false; 6564 6565 unsigned NumElts = VT.getVectorNumElements(); 6566 if (M.size() != NumElts && M.size() != NumElts*2) 6567 return false; 6568 6569 for (unsigned i = 0; i < M.size(); i += NumElts) { 6570 WhichResult = SelectPairHalf(NumElts, M, i); 6571 unsigned Idx = WhichResult * NumElts / 2; 6572 for (unsigned j = 0; j < NumElts; j += 2) { 6573 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6574 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6575 return false; 6576 Idx += 1; 6577 } 6578 } 6579 6580 if (M.size() == NumElts*2) 6581 WhichResult = 0; 6582 6583 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6584 if (VT.is64BitVector() && EltSz == 32) 6585 return false; 6586 6587 return true; 6588 } 6589 6590 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6591 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6592 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6593 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6594 unsigned EltSz = VT.getScalarSizeInBits(); 6595 if (EltSz == 64) 6596 return false; 6597 6598 unsigned NumElts = VT.getVectorNumElements(); 6599 if (M.size() != NumElts && M.size() != NumElts*2) 6600 return false; 6601 6602 for (unsigned i = 0; i < M.size(); i += NumElts) { 6603 WhichResult = SelectPairHalf(NumElts, M, i); 6604 unsigned Idx = WhichResult * NumElts / 2; 6605 for (unsigned j = 0; j < NumElts; j += 2) { 6606 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6607 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6608 return false; 6609 Idx += 1; 6610 } 6611 } 6612 6613 if (M.size() == NumElts*2) 6614 WhichResult = 0; 6615 6616 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6617 if (VT.is64BitVector() && EltSz == 32) 6618 return false; 6619 6620 return true; 6621 } 6622 6623 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6624 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6625 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6626 unsigned &WhichResult, 6627 bool &isV_UNDEF) { 6628 isV_UNDEF = false; 6629 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6630 return ARMISD::VTRN; 6631 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6632 return ARMISD::VUZP; 6633 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6634 return ARMISD::VZIP; 6635 6636 isV_UNDEF = true; 6637 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6638 return ARMISD::VTRN; 6639 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6640 return ARMISD::VUZP; 6641 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6642 return ARMISD::VZIP; 6643 6644 return 0; 6645 } 6646 6647 /// \return true if this is a reverse operation on an vector. 6648 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6649 unsigned NumElts = VT.getVectorNumElements(); 6650 // Make sure the mask has the right size. 6651 if (NumElts != M.size()) 6652 return false; 6653 6654 // Look for <15, ..., 3, -1, 1, 0>. 6655 for (unsigned i = 0; i != NumElts; ++i) 6656 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6657 return false; 6658 6659 return true; 6660 } 6661 6662 // If N is an integer constant that can be moved into a register in one 6663 // instruction, return an SDValue of such a constant (will become a MOV 6664 // instruction). Otherwise return null. 6665 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6666 const ARMSubtarget *ST, const SDLoc &dl) { 6667 uint64_t Val; 6668 if (!isa<ConstantSDNode>(N)) 6669 return SDValue(); 6670 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6671 6672 if (ST->isThumb1Only()) { 6673 if (Val <= 255 || ~Val <= 255) 6674 return DAG.getConstant(Val, dl, MVT::i32); 6675 } else { 6676 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6677 return DAG.getConstant(Val, dl, MVT::i32); 6678 } 6679 return SDValue(); 6680 } 6681 6682 // If this is a case we can't handle, return null and let the default 6683 // expansion code take care of it. 6684 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6685 const ARMSubtarget *ST) const { 6686 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6687 SDLoc dl(Op); 6688 EVT VT = Op.getValueType(); 6689 6690 APInt SplatBits, SplatUndef; 6691 unsigned SplatBitSize; 6692 bool HasAnyUndefs; 6693 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6694 if (SplatUndef.isAllOnesValue()) 6695 return DAG.getUNDEF(VT); 6696 6697 if ((ST->hasNEON() && SplatBitSize <= 64) || 6698 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) { 6699 // Check if an immediate VMOV works. 6700 EVT VmovVT; 6701 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 6702 SplatUndef.getZExtValue(), SplatBitSize, 6703 DAG, dl, VmovVT, VT.is128BitVector(), 6704 VMOVModImm); 6705 6706 if (Val.getNode()) { 6707 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6708 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6709 } 6710 6711 // Try an immediate VMVN. 6712 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6713 Val = isVMOVModifiedImm( 6714 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, 6715 DAG, dl, VmovVT, VT.is128BitVector(), 6716 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 6717 if (Val.getNode()) { 6718 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6719 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6720 } 6721 6722 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6723 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6724 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6725 if (ImmVal != -1) { 6726 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6727 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6728 } 6729 } 6730 } 6731 } 6732 6733 // Scan through the operands to see if only one value is used. 6734 // 6735 // As an optimisation, even if more than one value is used it may be more 6736 // profitable to splat with one value then change some lanes. 6737 // 6738 // Heuristically we decide to do this if the vector has a "dominant" value, 6739 // defined as splatted to more than half of the lanes. 6740 unsigned NumElts = VT.getVectorNumElements(); 6741 bool isOnlyLowElement = true; 6742 bool usesOnlyOneValue = true; 6743 bool hasDominantValue = false; 6744 bool isConstant = true; 6745 6746 // Map of the number of times a particular SDValue appears in the 6747 // element list. 6748 DenseMap<SDValue, unsigned> ValueCounts; 6749 SDValue Value; 6750 for (unsigned i = 0; i < NumElts; ++i) { 6751 SDValue V = Op.getOperand(i); 6752 if (V.isUndef()) 6753 continue; 6754 if (i > 0) 6755 isOnlyLowElement = false; 6756 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6757 isConstant = false; 6758 6759 ValueCounts.insert(std::make_pair(V, 0)); 6760 unsigned &Count = ValueCounts[V]; 6761 6762 // Is this value dominant? (takes up more than half of the lanes) 6763 if (++Count > (NumElts / 2)) { 6764 hasDominantValue = true; 6765 Value = V; 6766 } 6767 } 6768 if (ValueCounts.size() != 1) 6769 usesOnlyOneValue = false; 6770 if (!Value.getNode() && !ValueCounts.empty()) 6771 Value = ValueCounts.begin()->first; 6772 6773 if (ValueCounts.empty()) 6774 return DAG.getUNDEF(VT); 6775 6776 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6777 // Keep going if we are hitting this case. 6778 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6779 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6780 6781 unsigned EltSize = VT.getScalarSizeInBits(); 6782 6783 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6784 // i32 and try again. 6785 if (hasDominantValue && EltSize <= 32) { 6786 if (!isConstant) { 6787 SDValue N; 6788 6789 // If we are VDUPing a value that comes directly from a vector, that will 6790 // cause an unnecessary move to and from a GPR, where instead we could 6791 // just use VDUPLANE. We can only do this if the lane being extracted 6792 // is at a constant index, as the VDUP from lane instructions only have 6793 // constant-index forms. 6794 ConstantSDNode *constIndex; 6795 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6796 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6797 // We need to create a new undef vector to use for the VDUPLANE if the 6798 // size of the vector from which we get the value is different than the 6799 // size of the vector that we need to create. We will insert the element 6800 // such that the register coalescer will remove unnecessary copies. 6801 if (VT != Value->getOperand(0).getValueType()) { 6802 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6803 VT.getVectorNumElements(); 6804 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6805 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6806 Value, DAG.getConstant(index, dl, MVT::i32)), 6807 DAG.getConstant(index, dl, MVT::i32)); 6808 } else 6809 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6810 Value->getOperand(0), Value->getOperand(1)); 6811 } else 6812 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6813 6814 if (!usesOnlyOneValue) { 6815 // The dominant value was splatted as 'N', but we now have to insert 6816 // all differing elements. 6817 for (unsigned I = 0; I < NumElts; ++I) { 6818 if (Op.getOperand(I) == Value) 6819 continue; 6820 SmallVector<SDValue, 3> Ops; 6821 Ops.push_back(N); 6822 Ops.push_back(Op.getOperand(I)); 6823 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6824 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6825 } 6826 } 6827 return N; 6828 } 6829 if (VT.getVectorElementType().isFloatingPoint()) { 6830 SmallVector<SDValue, 8> Ops; 6831 MVT FVT = VT.getVectorElementType().getSimpleVT(); 6832 assert(FVT == MVT::f32 || FVT == MVT::f16); 6833 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 6834 for (unsigned i = 0; i < NumElts; ++i) 6835 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 6836 Op.getOperand(i))); 6837 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 6838 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6839 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6840 if (Val.getNode()) 6841 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6842 } 6843 if (usesOnlyOneValue) { 6844 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6845 if (isConstant && Val.getNode()) 6846 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6847 } 6848 } 6849 6850 // If all elements are constants and the case above didn't get hit, fall back 6851 // to the default expansion, which will generate a load from the constant 6852 // pool. 6853 if (isConstant) 6854 return SDValue(); 6855 6856 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6857 if (NumElts >= 4) { 6858 SDValue shuffle = ReconstructShuffle(Op, DAG); 6859 if (shuffle != SDValue()) 6860 return shuffle; 6861 } 6862 6863 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6864 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6865 // into two 64-bit vectors; we might discover a better way to lower it. 6866 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6867 EVT ExtVT = VT.getVectorElementType(); 6868 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6869 SDValue Lower = 6870 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6871 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6872 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6873 SDValue Upper = DAG.getBuildVector( 6874 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6875 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6876 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6877 if (Lower && Upper) 6878 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6879 } 6880 6881 // Vectors with 32- or 64-bit elements can be built by directly assigning 6882 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6883 // will be legalized. 6884 if (EltSize >= 32) { 6885 // Do the expansion with floating-point types, since that is what the VFP 6886 // registers are defined to use, and since i64 is not legal. 6887 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6888 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6889 SmallVector<SDValue, 8> Ops; 6890 for (unsigned i = 0; i < NumElts; ++i) 6891 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6892 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6893 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6894 } 6895 6896 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6897 // know the default expansion would otherwise fall back on something even 6898 // worse. For a vector with one or two non-undef values, that's 6899 // scalar_to_vector for the elements followed by a shuffle (provided the 6900 // shuffle is valid for the target) and materialization element by element 6901 // on the stack followed by a load for everything else. 6902 if (!isConstant && !usesOnlyOneValue) { 6903 SDValue Vec = DAG.getUNDEF(VT); 6904 for (unsigned i = 0 ; i < NumElts; ++i) { 6905 SDValue V = Op.getOperand(i); 6906 if (V.isUndef()) 6907 continue; 6908 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6909 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6910 } 6911 return Vec; 6912 } 6913 6914 return SDValue(); 6915 } 6916 6917 // Gather data to see if the operation can be modelled as a 6918 // shuffle in combination with VEXTs. 6919 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6920 SelectionDAG &DAG) const { 6921 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6922 SDLoc dl(Op); 6923 EVT VT = Op.getValueType(); 6924 unsigned NumElts = VT.getVectorNumElements(); 6925 6926 struct ShuffleSourceInfo { 6927 SDValue Vec; 6928 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6929 unsigned MaxElt = 0; 6930 6931 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6932 // be compatible with the shuffle we intend to construct. As a result 6933 // ShuffleVec will be some sliding window into the original Vec. 6934 SDValue ShuffleVec; 6935 6936 // Code should guarantee that element i in Vec starts at element "WindowBase 6937 // + i * WindowScale in ShuffleVec". 6938 int WindowBase = 0; 6939 int WindowScale = 1; 6940 6941 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6942 6943 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6944 }; 6945 6946 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6947 // node. 6948 SmallVector<ShuffleSourceInfo, 2> Sources; 6949 for (unsigned i = 0; i < NumElts; ++i) { 6950 SDValue V = Op.getOperand(i); 6951 if (V.isUndef()) 6952 continue; 6953 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6954 // A shuffle can only come from building a vector from various 6955 // elements of other vectors. 6956 return SDValue(); 6957 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6958 // Furthermore, shuffles require a constant mask, whereas extractelts 6959 // accept variable indices. 6960 return SDValue(); 6961 } 6962 6963 // Add this element source to the list if it's not already there. 6964 SDValue SourceVec = V.getOperand(0); 6965 auto Source = llvm::find(Sources, SourceVec); 6966 if (Source == Sources.end()) 6967 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6968 6969 // Update the minimum and maximum lane number seen. 6970 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6971 Source->MinElt = std::min(Source->MinElt, EltNo); 6972 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6973 } 6974 6975 // Currently only do something sane when at most two source vectors 6976 // are involved. 6977 if (Sources.size() > 2) 6978 return SDValue(); 6979 6980 // Find out the smallest element size among result and two sources, and use 6981 // it as element size to build the shuffle_vector. 6982 EVT SmallestEltTy = VT.getVectorElementType(); 6983 for (auto &Source : Sources) { 6984 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6985 if (SrcEltTy.bitsLT(SmallestEltTy)) 6986 SmallestEltTy = SrcEltTy; 6987 } 6988 unsigned ResMultiplier = 6989 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6990 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6991 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6992 6993 // If the source vector is too wide or too narrow, we may nevertheless be able 6994 // to construct a compatible shuffle either by concatenating it with UNDEF or 6995 // extracting a suitable range of elements. 6996 for (auto &Src : Sources) { 6997 EVT SrcVT = Src.ShuffleVec.getValueType(); 6998 6999 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 7000 continue; 7001 7002 // This stage of the search produces a source with the same element type as 7003 // the original, but with a total width matching the BUILD_VECTOR output. 7004 EVT EltVT = SrcVT.getVectorElementType(); 7005 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 7006 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7007 7008 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 7009 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 7010 return SDValue(); 7011 // We can pad out the smaller vector for free, so if it's part of a 7012 // shuffle... 7013 Src.ShuffleVec = 7014 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7015 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7016 continue; 7017 } 7018 7019 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 7020 return SDValue(); 7021 7022 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7023 // Span too large for a VEXT to cope 7024 return SDValue(); 7025 } 7026 7027 if (Src.MinElt >= NumSrcElts) { 7028 // The extraction can just take the second half 7029 Src.ShuffleVec = 7030 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7031 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7032 Src.WindowBase = -NumSrcElts; 7033 } else if (Src.MaxElt < NumSrcElts) { 7034 // The extraction can just take the first half 7035 Src.ShuffleVec = 7036 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7037 DAG.getConstant(0, dl, MVT::i32)); 7038 } else { 7039 // An actual VEXT is needed 7040 SDValue VEXTSrc1 = 7041 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7042 DAG.getConstant(0, dl, MVT::i32)); 7043 SDValue VEXTSrc2 = 7044 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7045 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7046 7047 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7048 VEXTSrc2, 7049 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7050 Src.WindowBase = -Src.MinElt; 7051 } 7052 } 7053 7054 // Another possible incompatibility occurs from the vector element types. We 7055 // can fix this by bitcasting the source vectors to the same type we intend 7056 // for the shuffle. 7057 for (auto &Src : Sources) { 7058 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7059 if (SrcEltTy == SmallestEltTy) 7060 continue; 7061 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7062 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 7063 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7064 Src.WindowBase *= Src.WindowScale; 7065 } 7066 7067 // Final sanity check before we try to actually produce a shuffle. 7068 LLVM_DEBUG(for (auto Src 7069 : Sources) 7070 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7071 7072 // The stars all align, our next step is to produce the mask for the shuffle. 7073 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7074 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7075 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7076 SDValue Entry = Op.getOperand(i); 7077 if (Entry.isUndef()) 7078 continue; 7079 7080 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7081 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7082 7083 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7084 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7085 // segment. 7086 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7087 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 7088 VT.getScalarSizeInBits()); 7089 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7090 7091 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7092 // starting at the appropriate offset. 7093 int *LaneMask = &Mask[i * ResMultiplier]; 7094 7095 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7096 ExtractBase += NumElts * (Src - Sources.begin()); 7097 for (int j = 0; j < LanesDefined; ++j) 7098 LaneMask[j] = ExtractBase + j; 7099 } 7100 7101 // Final check before we try to produce nonsense... 7102 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 7103 return SDValue(); 7104 7105 // We can't handle more than two sources. This should have already 7106 // been checked before this point. 7107 assert(Sources.size() <= 2 && "Too many sources!"); 7108 7109 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7110 for (unsigned i = 0; i < Sources.size(); ++i) 7111 ShuffleOps[i] = Sources[i].ShuffleVec; 7112 7113 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7114 ShuffleOps[1], Mask); 7115 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 7116 } 7117 7118 enum ShuffleOpCodes { 7119 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7120 OP_VREV, 7121 OP_VDUP0, 7122 OP_VDUP1, 7123 OP_VDUP2, 7124 OP_VDUP3, 7125 OP_VEXT1, 7126 OP_VEXT2, 7127 OP_VEXT3, 7128 OP_VUZPL, // VUZP, left result 7129 OP_VUZPR, // VUZP, right result 7130 OP_VZIPL, // VZIP, left result 7131 OP_VZIPR, // VZIP, right result 7132 OP_VTRNL, // VTRN, left result 7133 OP_VTRNR // VTRN, right result 7134 }; 7135 7136 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7137 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7138 switch (OpNum) { 7139 case OP_COPY: 7140 case OP_VREV: 7141 case OP_VDUP0: 7142 case OP_VDUP1: 7143 case OP_VDUP2: 7144 case OP_VDUP3: 7145 return true; 7146 } 7147 return false; 7148 } 7149 7150 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7151 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7152 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7153 /// are assumed to be legal. 7154 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7155 if (VT.getVectorNumElements() == 4 && 7156 (VT.is128BitVector() || VT.is64BitVector())) { 7157 unsigned PFIndexes[4]; 7158 for (unsigned i = 0; i != 4; ++i) { 7159 if (M[i] < 0) 7160 PFIndexes[i] = 8; 7161 else 7162 PFIndexes[i] = M[i]; 7163 } 7164 7165 // Compute the index in the perfect shuffle table. 7166 unsigned PFTableIndex = 7167 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7168 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7169 unsigned Cost = (PFEntry >> 30); 7170 7171 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7172 return true; 7173 } 7174 7175 bool ReverseVEXT, isV_UNDEF; 7176 unsigned Imm, WhichResult; 7177 7178 unsigned EltSize = VT.getScalarSizeInBits(); 7179 if (EltSize >= 32 || 7180 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7181 isVREVMask(M, VT, 64) || 7182 isVREVMask(M, VT, 32) || 7183 isVREVMask(M, VT, 16)) 7184 return true; 7185 else if (Subtarget->hasNEON() && 7186 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7187 isVTBLMask(M, VT) || 7188 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7189 return true; 7190 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7191 isReverseMask(M, VT)) 7192 return true; 7193 else 7194 return false; 7195 } 7196 7197 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7198 /// the specified operations to build the shuffle. 7199 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7200 SDValue RHS, SelectionDAG &DAG, 7201 const SDLoc &dl) { 7202 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7203 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7204 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7205 7206 if (OpNum == OP_COPY) { 7207 if (LHSID == (1*9+2)*9+3) return LHS; 7208 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7209 return RHS; 7210 } 7211 7212 SDValue OpLHS, OpRHS; 7213 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7214 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7215 EVT VT = OpLHS.getValueType(); 7216 7217 switch (OpNum) { 7218 default: llvm_unreachable("Unknown shuffle opcode!"); 7219 case OP_VREV: 7220 // VREV divides the vector in half and swaps within the half. 7221 if (VT.getVectorElementType() == MVT::i32 || 7222 VT.getVectorElementType() == MVT::f32) 7223 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7224 // vrev <4 x i16> -> VREV32 7225 if (VT.getVectorElementType() == MVT::i16) 7226 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7227 // vrev <4 x i8> -> VREV16 7228 assert(VT.getVectorElementType() == MVT::i8); 7229 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 7230 case OP_VDUP0: 7231 case OP_VDUP1: 7232 case OP_VDUP2: 7233 case OP_VDUP3: 7234 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7235 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 7236 case OP_VEXT1: 7237 case OP_VEXT2: 7238 case OP_VEXT3: 7239 return DAG.getNode(ARMISD::VEXT, dl, VT, 7240 OpLHS, OpRHS, 7241 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 7242 case OP_VUZPL: 7243 case OP_VUZPR: 7244 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7245 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7246 case OP_VZIPL: 7247 case OP_VZIPR: 7248 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7249 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7250 case OP_VTRNL: 7251 case OP_VTRNR: 7252 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7253 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7254 } 7255 } 7256 7257 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7258 ArrayRef<int> ShuffleMask, 7259 SelectionDAG &DAG) { 7260 // Check to see if we can use the VTBL instruction. 7261 SDValue V1 = Op.getOperand(0); 7262 SDValue V2 = Op.getOperand(1); 7263 SDLoc DL(Op); 7264 7265 SmallVector<SDValue, 8> VTBLMask; 7266 for (ArrayRef<int>::iterator 7267 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7268 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7269 7270 if (V2.getNode()->isUndef()) 7271 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7272 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7273 7274 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7275 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7276 } 7277 7278 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7279 SelectionDAG &DAG) { 7280 SDLoc DL(Op); 7281 SDValue OpLHS = Op.getOperand(0); 7282 EVT VT = OpLHS.getValueType(); 7283 7284 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7285 "Expect an v8i16/v16i8 type"); 7286 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7287 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7288 // extract the first 8 bytes into the top double word and the last 8 bytes 7289 // into the bottom double word. The v8i16 case is similar. 7290 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7291 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7292 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7293 } 7294 7295 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 7296 const ARMSubtarget *ST) { 7297 SDValue V1 = Op.getOperand(0); 7298 SDValue V2 = Op.getOperand(1); 7299 SDLoc dl(Op); 7300 EVT VT = Op.getValueType(); 7301 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7302 7303 // Convert shuffles that are directly supported on NEON to target-specific 7304 // DAG nodes, instead of keeping them as shuffles and matching them again 7305 // during code selection. This is more efficient and avoids the possibility 7306 // of inconsistencies between legalization and selection. 7307 // FIXME: floating-point vectors should be canonicalized to integer vectors 7308 // of the same time so that they get CSEd properly. 7309 ArrayRef<int> ShuffleMask = SVN->getMask(); 7310 7311 unsigned EltSize = VT.getScalarSizeInBits(); 7312 if (EltSize <= 32) { 7313 if (SVN->isSplat()) { 7314 int Lane = SVN->getSplatIndex(); 7315 // If this is undef splat, generate it via "just" vdup, if possible. 7316 if (Lane == -1) Lane = 0; 7317 7318 // Test if V1 is a SCALAR_TO_VECTOR. 7319 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7320 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7321 } 7322 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7323 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7324 // reaches it). 7325 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7326 !isa<ConstantSDNode>(V1.getOperand(0))) { 7327 bool IsScalarToVector = true; 7328 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7329 if (!V1.getOperand(i).isUndef()) { 7330 IsScalarToVector = false; 7331 break; 7332 } 7333 if (IsScalarToVector) 7334 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7335 } 7336 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7337 DAG.getConstant(Lane, dl, MVT::i32)); 7338 } 7339 7340 bool ReverseVEXT = false; 7341 unsigned Imm = 0; 7342 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7343 if (ReverseVEXT) 7344 std::swap(V1, V2); 7345 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7346 DAG.getConstant(Imm, dl, MVT::i32)); 7347 } 7348 7349 if (isVREVMask(ShuffleMask, VT, 64)) 7350 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7351 if (isVREVMask(ShuffleMask, VT, 32)) 7352 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7353 if (isVREVMask(ShuffleMask, VT, 16)) 7354 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7355 7356 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7357 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7358 DAG.getConstant(Imm, dl, MVT::i32)); 7359 } 7360 7361 // Check for Neon shuffles that modify both input vectors in place. 7362 // If both results are used, i.e., if there are two shuffles with the same 7363 // source operands and with masks corresponding to both results of one of 7364 // these operations, DAG memoization will ensure that a single node is 7365 // used for both shuffles. 7366 unsigned WhichResult = 0; 7367 bool isV_UNDEF = false; 7368 if (ST->hasNEON()) { 7369 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7370 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7371 if (isV_UNDEF) 7372 V2 = V1; 7373 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7374 .getValue(WhichResult); 7375 } 7376 } 7377 7378 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7379 // shuffles that produce a result larger than their operands with: 7380 // shuffle(concat(v1, undef), concat(v2, undef)) 7381 // -> 7382 // shuffle(concat(v1, v2), undef) 7383 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7384 // 7385 // This is useful in the general case, but there are special cases where 7386 // native shuffles produce larger results: the two-result ops. 7387 // 7388 // Look through the concat when lowering them: 7389 // shuffle(concat(v1, v2), undef) 7390 // -> 7391 // concat(VZIP(v1, v2):0, :1) 7392 // 7393 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7394 SDValue SubV1 = V1->getOperand(0); 7395 SDValue SubV2 = V1->getOperand(1); 7396 EVT SubVT = SubV1.getValueType(); 7397 7398 // We expect these to have been canonicalized to -1. 7399 assert(llvm::all_of(ShuffleMask, [&](int i) { 7400 return i < (int)VT.getVectorNumElements(); 7401 }) && "Unexpected shuffle index into UNDEF operand!"); 7402 7403 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7404 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7405 if (isV_UNDEF) 7406 SubV2 = SubV1; 7407 assert((WhichResult == 0) && 7408 "In-place shuffle of concat can only have one result!"); 7409 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7410 SubV1, SubV2); 7411 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7412 Res.getValue(1)); 7413 } 7414 } 7415 } 7416 7417 // If the shuffle is not directly supported and it has 4 elements, use 7418 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7419 unsigned NumElts = VT.getVectorNumElements(); 7420 if (NumElts == 4) { 7421 unsigned PFIndexes[4]; 7422 for (unsigned i = 0; i != 4; ++i) { 7423 if (ShuffleMask[i] < 0) 7424 PFIndexes[i] = 8; 7425 else 7426 PFIndexes[i] = ShuffleMask[i]; 7427 } 7428 7429 // Compute the index in the perfect shuffle table. 7430 unsigned PFTableIndex = 7431 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7432 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7433 unsigned Cost = (PFEntry >> 30); 7434 7435 if (Cost <= 4) { 7436 if (ST->hasNEON()) 7437 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7438 else if (isLegalMVEShuffleOp(PFEntry)) { 7439 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7440 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7441 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 7442 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 7443 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 7444 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7445 } 7446 } 7447 } 7448 7449 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7450 if (EltSize >= 32) { 7451 // Do the expansion with floating-point types, since that is what the VFP 7452 // registers are defined to use, and since i64 is not legal. 7453 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7454 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7455 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7456 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7457 SmallVector<SDValue, 8> Ops; 7458 for (unsigned i = 0; i < NumElts; ++i) { 7459 if (ShuffleMask[i] < 0) 7460 Ops.push_back(DAG.getUNDEF(EltVT)); 7461 else 7462 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7463 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7464 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7465 dl, MVT::i32))); 7466 } 7467 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7468 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7469 } 7470 7471 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7472 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7473 7474 if (ST->hasNEON() && VT == MVT::v8i8) 7475 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7476 return NewOp; 7477 7478 return SDValue(); 7479 } 7480 7481 SDValue ARMTargetLowering:: 7482 LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 7483 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7484 SDValue Lane = Op.getOperand(2); 7485 if (!isa<ConstantSDNode>(Lane)) 7486 return SDValue(); 7487 7488 SDValue Elt = Op.getOperand(1); 7489 EVT EltVT = Elt.getValueType(); 7490 if (getTypeAction(*DAG.getContext(), EltVT) == 7491 TargetLowering::TypePromoteFloat) { 7492 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 7493 // but the type system will try to do that if we don't intervene. 7494 // Reinterpret any such vector-element insertion as one with the 7495 // corresponding integer types. 7496 7497 SDLoc dl(Op); 7498 7499 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 7500 assert(getTypeAction(*DAG.getContext(), IEltVT) != 7501 TargetLowering::TypePromoteFloat); 7502 7503 SDValue VecIn = Op.getOperand(0); 7504 EVT VecVT = VecIn.getValueType(); 7505 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 7506 VecVT.getVectorNumElements()); 7507 7508 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 7509 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 7510 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 7511 IVecIn, IElt, Lane); 7512 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 7513 } 7514 7515 return Op; 7516 } 7517 7518 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7519 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7520 SDValue Lane = Op.getOperand(1); 7521 if (!isa<ConstantSDNode>(Lane)) 7522 return SDValue(); 7523 7524 SDValue Vec = Op.getOperand(0); 7525 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7526 SDLoc dl(Op); 7527 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7528 } 7529 7530 return Op; 7531 } 7532 7533 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7534 // The only time a CONCAT_VECTORS operation can have legal types is when 7535 // two 64-bit vectors are concatenated to a 128-bit vector. 7536 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7537 "unexpected CONCAT_VECTORS"); 7538 SDLoc dl(Op); 7539 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7540 SDValue Op0 = Op.getOperand(0); 7541 SDValue Op1 = Op.getOperand(1); 7542 if (!Op0.isUndef()) 7543 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7544 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7545 DAG.getIntPtrConstant(0, dl)); 7546 if (!Op1.isUndef()) 7547 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7548 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7549 DAG.getIntPtrConstant(1, dl)); 7550 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7551 } 7552 7553 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7554 /// element has been zero/sign-extended, depending on the isSigned parameter, 7555 /// from an integer type half its size. 7556 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7557 bool isSigned) { 7558 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7559 EVT VT = N->getValueType(0); 7560 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7561 SDNode *BVN = N->getOperand(0).getNode(); 7562 if (BVN->getValueType(0) != MVT::v4i32 || 7563 BVN->getOpcode() != ISD::BUILD_VECTOR) 7564 return false; 7565 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7566 unsigned HiElt = 1 - LoElt; 7567 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7568 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7569 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7570 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7571 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7572 return false; 7573 if (isSigned) { 7574 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7575 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7576 return true; 7577 } else { 7578 if (Hi0->isNullValue() && Hi1->isNullValue()) 7579 return true; 7580 } 7581 return false; 7582 } 7583 7584 if (N->getOpcode() != ISD::BUILD_VECTOR) 7585 return false; 7586 7587 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7588 SDNode *Elt = N->getOperand(i).getNode(); 7589 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7590 unsigned EltSize = VT.getScalarSizeInBits(); 7591 unsigned HalfSize = EltSize / 2; 7592 if (isSigned) { 7593 if (!isIntN(HalfSize, C->getSExtValue())) 7594 return false; 7595 } else { 7596 if (!isUIntN(HalfSize, C->getZExtValue())) 7597 return false; 7598 } 7599 continue; 7600 } 7601 return false; 7602 } 7603 7604 return true; 7605 } 7606 7607 /// isSignExtended - Check if a node is a vector value that is sign-extended 7608 /// or a constant BUILD_VECTOR with sign-extended elements. 7609 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7610 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7611 return true; 7612 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7613 return true; 7614 return false; 7615 } 7616 7617 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7618 /// or a constant BUILD_VECTOR with zero-extended elements. 7619 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7620 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7621 return true; 7622 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7623 return true; 7624 return false; 7625 } 7626 7627 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7628 if (OrigVT.getSizeInBits() >= 64) 7629 return OrigVT; 7630 7631 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7632 7633 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7634 switch (OrigSimpleTy) { 7635 default: llvm_unreachable("Unexpected Vector Type"); 7636 case MVT::v2i8: 7637 case MVT::v2i16: 7638 return MVT::v2i32; 7639 case MVT::v4i8: 7640 return MVT::v4i16; 7641 } 7642 } 7643 7644 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7645 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7646 /// We insert the required extension here to get the vector to fill a D register. 7647 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7648 const EVT &OrigTy, 7649 const EVT &ExtTy, 7650 unsigned ExtOpcode) { 7651 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7652 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7653 // 64-bits we need to insert a new extension so that it will be 64-bits. 7654 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7655 if (OrigTy.getSizeInBits() >= 64) 7656 return N; 7657 7658 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7659 EVT NewVT = getExtensionTo64Bits(OrigTy); 7660 7661 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7662 } 7663 7664 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7665 /// does not do any sign/zero extension. If the original vector is less 7666 /// than 64 bits, an appropriate extension will be added after the load to 7667 /// reach a total size of 64 bits. We have to add the extension separately 7668 /// because ARM does not have a sign/zero extending load for vectors. 7669 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7670 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7671 7672 // The load already has the right type. 7673 if (ExtendedTy == LD->getMemoryVT()) 7674 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7675 LD->getBasePtr(), LD->getPointerInfo(), 7676 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7677 7678 // We need to create a zextload/sextload. We cannot just create a load 7679 // followed by a zext/zext node because LowerMUL is also run during normal 7680 // operation legalization where we can't create illegal types. 7681 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7682 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7683 LD->getMemoryVT(), LD->getAlignment(), 7684 LD->getMemOperand()->getFlags()); 7685 } 7686 7687 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7688 /// extending load, or BUILD_VECTOR with extended elements, return the 7689 /// unextended value. The unextended vector should be 64 bits so that it can 7690 /// be used as an operand to a VMULL instruction. If the original vector size 7691 /// before extension is less than 64 bits we add a an extension to resize 7692 /// the vector to 64 bits. 7693 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7694 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7695 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7696 N->getOperand(0)->getValueType(0), 7697 N->getValueType(0), 7698 N->getOpcode()); 7699 7700 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7701 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7702 "Expected extending load"); 7703 7704 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7705 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7706 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7707 SDValue extLoad = 7708 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7709 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7710 7711 return newLoad; 7712 } 7713 7714 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7715 // have been legalized as a BITCAST from v4i32. 7716 if (N->getOpcode() == ISD::BITCAST) { 7717 SDNode *BVN = N->getOperand(0).getNode(); 7718 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7719 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7720 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7721 return DAG.getBuildVector( 7722 MVT::v2i32, SDLoc(N), 7723 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7724 } 7725 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7726 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7727 EVT VT = N->getValueType(0); 7728 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7729 unsigned NumElts = VT.getVectorNumElements(); 7730 MVT TruncVT = MVT::getIntegerVT(EltSize); 7731 SmallVector<SDValue, 8> Ops; 7732 SDLoc dl(N); 7733 for (unsigned i = 0; i != NumElts; ++i) { 7734 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7735 const APInt &CInt = C->getAPIntValue(); 7736 // Element types smaller than 32 bits are not legal, so use i32 elements. 7737 // The values are implicitly truncated so sext vs. zext doesn't matter. 7738 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7739 } 7740 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7741 } 7742 7743 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7744 unsigned Opcode = N->getOpcode(); 7745 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7746 SDNode *N0 = N->getOperand(0).getNode(); 7747 SDNode *N1 = N->getOperand(1).getNode(); 7748 return N0->hasOneUse() && N1->hasOneUse() && 7749 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7750 } 7751 return false; 7752 } 7753 7754 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7755 unsigned Opcode = N->getOpcode(); 7756 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7757 SDNode *N0 = N->getOperand(0).getNode(); 7758 SDNode *N1 = N->getOperand(1).getNode(); 7759 return N0->hasOneUse() && N1->hasOneUse() && 7760 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7761 } 7762 return false; 7763 } 7764 7765 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7766 // Multiplications are only custom-lowered for 128-bit vectors so that 7767 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7768 EVT VT = Op.getValueType(); 7769 assert(VT.is128BitVector() && VT.isInteger() && 7770 "unexpected type for custom-lowering ISD::MUL"); 7771 SDNode *N0 = Op.getOperand(0).getNode(); 7772 SDNode *N1 = Op.getOperand(1).getNode(); 7773 unsigned NewOpc = 0; 7774 bool isMLA = false; 7775 bool isN0SExt = isSignExtended(N0, DAG); 7776 bool isN1SExt = isSignExtended(N1, DAG); 7777 if (isN0SExt && isN1SExt) 7778 NewOpc = ARMISD::VMULLs; 7779 else { 7780 bool isN0ZExt = isZeroExtended(N0, DAG); 7781 bool isN1ZExt = isZeroExtended(N1, DAG); 7782 if (isN0ZExt && isN1ZExt) 7783 NewOpc = ARMISD::VMULLu; 7784 else if (isN1SExt || isN1ZExt) { 7785 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7786 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7787 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7788 NewOpc = ARMISD::VMULLs; 7789 isMLA = true; 7790 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7791 NewOpc = ARMISD::VMULLu; 7792 isMLA = true; 7793 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7794 std::swap(N0, N1); 7795 NewOpc = ARMISD::VMULLu; 7796 isMLA = true; 7797 } 7798 } 7799 7800 if (!NewOpc) { 7801 if (VT == MVT::v2i64) 7802 // Fall through to expand this. It is not legal. 7803 return SDValue(); 7804 else 7805 // Other vector multiplications are legal. 7806 return Op; 7807 } 7808 } 7809 7810 // Legalize to a VMULL instruction. 7811 SDLoc DL(Op); 7812 SDValue Op0; 7813 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7814 if (!isMLA) { 7815 Op0 = SkipExtensionForVMULL(N0, DAG); 7816 assert(Op0.getValueType().is64BitVector() && 7817 Op1.getValueType().is64BitVector() && 7818 "unexpected types for extended operands to VMULL"); 7819 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7820 } 7821 7822 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7823 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7824 // vmull q0, d4, d6 7825 // vmlal q0, d5, d6 7826 // is faster than 7827 // vaddl q0, d4, d5 7828 // vmovl q1, d6 7829 // vmul q0, q0, q1 7830 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7831 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7832 EVT Op1VT = Op1.getValueType(); 7833 return DAG.getNode(N0->getOpcode(), DL, VT, 7834 DAG.getNode(NewOpc, DL, VT, 7835 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7836 DAG.getNode(NewOpc, DL, VT, 7837 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7838 } 7839 7840 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7841 SelectionDAG &DAG) { 7842 // TODO: Should this propagate fast-math-flags? 7843 7844 // Convert to float 7845 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7846 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7847 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7848 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7849 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7850 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7851 // Get reciprocal estimate. 7852 // float4 recip = vrecpeq_f32(yf); 7853 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7854 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7855 Y); 7856 // Because char has a smaller range than uchar, we can actually get away 7857 // without any newton steps. This requires that we use a weird bias 7858 // of 0xb000, however (again, this has been exhaustively tested). 7859 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7860 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7861 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7862 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7863 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7864 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7865 // Convert back to short. 7866 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7867 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7868 return X; 7869 } 7870 7871 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7872 SelectionDAG &DAG) { 7873 // TODO: Should this propagate fast-math-flags? 7874 7875 SDValue N2; 7876 // Convert to float. 7877 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7878 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7879 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7880 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7881 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7882 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7883 7884 // Use reciprocal estimate and one refinement step. 7885 // float4 recip = vrecpeq_f32(yf); 7886 // recip *= vrecpsq_f32(yf, recip); 7887 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7888 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7889 N1); 7890 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7891 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7892 N1, N2); 7893 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7894 // Because short has a smaller range than ushort, we can actually get away 7895 // with only a single newton step. This requires that we use a weird bias 7896 // of 89, however (again, this has been exhaustively tested). 7897 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7898 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7899 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7900 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7901 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7902 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7903 // Convert back to integer and return. 7904 // return vmovn_s32(vcvt_s32_f32(result)); 7905 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7906 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7907 return N0; 7908 } 7909 7910 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7911 EVT VT = Op.getValueType(); 7912 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7913 "unexpected type for custom-lowering ISD::SDIV"); 7914 7915 SDLoc dl(Op); 7916 SDValue N0 = Op.getOperand(0); 7917 SDValue N1 = Op.getOperand(1); 7918 SDValue N2, N3; 7919 7920 if (VT == MVT::v8i8) { 7921 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7922 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7923 7924 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7925 DAG.getIntPtrConstant(4, dl)); 7926 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7927 DAG.getIntPtrConstant(4, dl)); 7928 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7929 DAG.getIntPtrConstant(0, dl)); 7930 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7931 DAG.getIntPtrConstant(0, dl)); 7932 7933 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7934 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7935 7936 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7937 N0 = LowerCONCAT_VECTORS(N0, DAG); 7938 7939 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7940 return N0; 7941 } 7942 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7943 } 7944 7945 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7946 // TODO: Should this propagate fast-math-flags? 7947 EVT VT = Op.getValueType(); 7948 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7949 "unexpected type for custom-lowering ISD::UDIV"); 7950 7951 SDLoc dl(Op); 7952 SDValue N0 = Op.getOperand(0); 7953 SDValue N1 = Op.getOperand(1); 7954 SDValue N2, N3; 7955 7956 if (VT == MVT::v8i8) { 7957 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7958 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7959 7960 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7961 DAG.getIntPtrConstant(4, dl)); 7962 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7963 DAG.getIntPtrConstant(4, dl)); 7964 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7965 DAG.getIntPtrConstant(0, dl)); 7966 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7967 DAG.getIntPtrConstant(0, dl)); 7968 7969 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7970 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7971 7972 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7973 N0 = LowerCONCAT_VECTORS(N0, DAG); 7974 7975 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7976 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7977 MVT::i32), 7978 N0); 7979 return N0; 7980 } 7981 7982 // v4i16 sdiv ... Convert to float. 7983 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7984 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7985 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7986 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7987 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7988 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7989 7990 // Use reciprocal estimate and two refinement steps. 7991 // float4 recip = vrecpeq_f32(yf); 7992 // recip *= vrecpsq_f32(yf, recip); 7993 // recip *= vrecpsq_f32(yf, recip); 7994 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7995 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7996 BN1); 7997 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7998 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7999 BN1, N2); 8000 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8001 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8002 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8003 BN1, N2); 8004 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8005 // Simply multiplying by the reciprocal estimate can leave us a few ulps 8006 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 8007 // and that it will never cause us to return an answer too large). 8008 // float4 result = as_float4(as_int4(xf*recip) + 2); 8009 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8010 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8011 N1 = DAG.getConstant(2, dl, MVT::v4i32); 8012 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8013 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8014 // Convert back to integer and return. 8015 // return vmovn_u32(vcvt_s32_f32(result)); 8016 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8017 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8018 return N0; 8019 } 8020 8021 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 8022 SDNode *N = Op.getNode(); 8023 EVT VT = N->getValueType(0); 8024 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 8025 8026 SDValue Carry = Op.getOperand(2); 8027 8028 SDLoc DL(Op); 8029 8030 SDValue Result; 8031 if (Op.getOpcode() == ISD::ADDCARRY) { 8032 // This converts the boolean value carry into the carry flag. 8033 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8034 8035 // Do the addition proper using the carry flag we wanted. 8036 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 8037 Op.getOperand(1), Carry); 8038 8039 // Now convert the carry flag into a boolean value. 8040 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8041 } else { 8042 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 8043 // have to invert the carry first. 8044 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8045 DAG.getConstant(1, DL, MVT::i32), Carry); 8046 // This converts the boolean value carry into the carry flag. 8047 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8048 8049 // Do the subtraction proper using the carry flag we wanted. 8050 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 8051 Op.getOperand(1), Carry); 8052 8053 // Now convert the carry flag into a boolean value. 8054 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8055 // But the carry returned by ARMISD::SUBE is not a borrow as expected 8056 // by ISD::SUBCARRY, so compute 1 - C. 8057 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8058 DAG.getConstant(1, DL, MVT::i32), Carry); 8059 } 8060 8061 // Return both values. 8062 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 8063 } 8064 8065 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 8066 assert(Subtarget->isTargetDarwin()); 8067 8068 // For iOS, we want to call an alternative entry point: __sincos_stret, 8069 // return values are passed via sret. 8070 SDLoc dl(Op); 8071 SDValue Arg = Op.getOperand(0); 8072 EVT ArgVT = Arg.getValueType(); 8073 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 8074 auto PtrVT = getPointerTy(DAG.getDataLayout()); 8075 8076 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8077 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8078 8079 // Pair of floats / doubles used to pass the result. 8080 Type *RetTy = StructType::get(ArgTy, ArgTy); 8081 auto &DL = DAG.getDataLayout(); 8082 8083 ArgListTy Args; 8084 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 8085 SDValue SRet; 8086 if (ShouldUseSRet) { 8087 // Create stack object for sret. 8088 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 8089 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 8090 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 8091 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 8092 8093 ArgListEntry Entry; 8094 Entry.Node = SRet; 8095 Entry.Ty = RetTy->getPointerTo(); 8096 Entry.IsSExt = false; 8097 Entry.IsZExt = false; 8098 Entry.IsSRet = true; 8099 Args.push_back(Entry); 8100 RetTy = Type::getVoidTy(*DAG.getContext()); 8101 } 8102 8103 ArgListEntry Entry; 8104 Entry.Node = Arg; 8105 Entry.Ty = ArgTy; 8106 Entry.IsSExt = false; 8107 Entry.IsZExt = false; 8108 Args.push_back(Entry); 8109 8110 RTLIB::Libcall LC = 8111 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 8112 const char *LibcallName = getLibcallName(LC); 8113 CallingConv::ID CC = getLibcallCallingConv(LC); 8114 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 8115 8116 TargetLowering::CallLoweringInfo CLI(DAG); 8117 CLI.setDebugLoc(dl) 8118 .setChain(DAG.getEntryNode()) 8119 .setCallee(CC, RetTy, Callee, std::move(Args)) 8120 .setDiscardResult(ShouldUseSRet); 8121 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8122 8123 if (!ShouldUseSRet) 8124 return CallResult.first; 8125 8126 SDValue LoadSin = 8127 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 8128 8129 // Address of cos field. 8130 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 8131 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 8132 SDValue LoadCos = 8133 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 8134 8135 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 8136 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 8137 LoadSin.getValue(0), LoadCos.getValue(0)); 8138 } 8139 8140 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 8141 bool Signed, 8142 SDValue &Chain) const { 8143 EVT VT = Op.getValueType(); 8144 assert((VT == MVT::i32 || VT == MVT::i64) && 8145 "unexpected type for custom lowering DIV"); 8146 SDLoc dl(Op); 8147 8148 const auto &DL = DAG.getDataLayout(); 8149 const auto &TLI = DAG.getTargetLoweringInfo(); 8150 8151 const char *Name = nullptr; 8152 if (Signed) 8153 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 8154 else 8155 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 8156 8157 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 8158 8159 ARMTargetLowering::ArgListTy Args; 8160 8161 for (auto AI : {1, 0}) { 8162 ArgListEntry Arg; 8163 Arg.Node = Op.getOperand(AI); 8164 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 8165 Args.push_back(Arg); 8166 } 8167 8168 CallLoweringInfo CLI(DAG); 8169 CLI.setDebugLoc(dl) 8170 .setChain(Chain) 8171 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 8172 ES, std::move(Args)); 8173 8174 return LowerCallTo(CLI).first; 8175 } 8176 8177 // This is a code size optimisation: return the original SDIV node to 8178 // DAGCombiner when we don't want to expand SDIV into a sequence of 8179 // instructions, and an empty node otherwise which will cause the 8180 // SDIV to be expanded in DAGCombine. 8181 SDValue 8182 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8183 SelectionDAG &DAG, 8184 SmallVectorImpl<SDNode *> &Created) const { 8185 // TODO: Support SREM 8186 if (N->getOpcode() != ISD::SDIV) 8187 return SDValue(); 8188 8189 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 8190 const bool MinSize = ST.hasMinSize(); 8191 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 8192 : ST.hasDivideInARMMode(); 8193 8194 // Don't touch vector types; rewriting this may lead to scalarizing 8195 // the int divs. 8196 if (N->getOperand(0).getValueType().isVector()) 8197 return SDValue(); 8198 8199 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 8200 // hwdiv support for this to be really profitable. 8201 if (!(MinSize && HasDivide)) 8202 return SDValue(); 8203 8204 // ARM mode is a bit simpler than Thumb: we can handle large power 8205 // of 2 immediates with 1 mov instruction; no further checks required, 8206 // just return the sdiv node. 8207 if (!ST.isThumb()) 8208 return SDValue(N, 0); 8209 8210 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 8211 // and thus lose the code size benefits of a MOVS that requires only 2. 8212 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 8213 // but as it's doing exactly this, it's not worth the trouble to get TTI. 8214 if (Divisor.sgt(128)) 8215 return SDValue(); 8216 8217 return SDValue(N, 0); 8218 } 8219 8220 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 8221 bool Signed) const { 8222 assert(Op.getValueType() == MVT::i32 && 8223 "unexpected type for custom lowering DIV"); 8224 SDLoc dl(Op); 8225 8226 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 8227 DAG.getEntryNode(), Op.getOperand(1)); 8228 8229 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8230 } 8231 8232 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 8233 SDLoc DL(N); 8234 SDValue Op = N->getOperand(1); 8235 if (N->getValueType(0) == MVT::i32) 8236 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 8237 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8238 DAG.getConstant(0, DL, MVT::i32)); 8239 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8240 DAG.getConstant(1, DL, MVT::i32)); 8241 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 8242 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 8243 } 8244 8245 void ARMTargetLowering::ExpandDIV_Windows( 8246 SDValue Op, SelectionDAG &DAG, bool Signed, 8247 SmallVectorImpl<SDValue> &Results) const { 8248 const auto &DL = DAG.getDataLayout(); 8249 const auto &TLI = DAG.getTargetLoweringInfo(); 8250 8251 assert(Op.getValueType() == MVT::i64 && 8252 "unexpected type for custom lowering DIV"); 8253 SDLoc dl(Op); 8254 8255 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 8256 8257 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8258 8259 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 8260 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 8261 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 8262 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 8263 8264 Results.push_back(Lower); 8265 Results.push_back(Upper); 8266 } 8267 8268 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 8269 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 8270 // Acquire/Release load/store is not legal for targets without a dmb or 8271 // equivalent available. 8272 return SDValue(); 8273 8274 // Monotonic load/store is legal for all targets. 8275 return Op; 8276 } 8277 8278 static void ReplaceREADCYCLECOUNTER(SDNode *N, 8279 SmallVectorImpl<SDValue> &Results, 8280 SelectionDAG &DAG, 8281 const ARMSubtarget *Subtarget) { 8282 SDLoc DL(N); 8283 // Under Power Management extensions, the cycle-count is: 8284 // mrc p15, #0, <Rt>, c9, c13, #0 8285 SDValue Ops[] = { N->getOperand(0), // Chain 8286 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 8287 DAG.getConstant(15, DL, MVT::i32), 8288 DAG.getConstant(0, DL, MVT::i32), 8289 DAG.getConstant(9, DL, MVT::i32), 8290 DAG.getConstant(13, DL, MVT::i32), 8291 DAG.getConstant(0, DL, MVT::i32) 8292 }; 8293 8294 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 8295 DAG.getVTList(MVT::i32, MVT::Other), Ops); 8296 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 8297 DAG.getConstant(0, DL, MVT::i32))); 8298 Results.push_back(Cycles32.getValue(1)); 8299 } 8300 8301 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 8302 SDLoc dl(V.getNode()); 8303 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 8304 SDValue VHi = DAG.getAnyExtOrTrunc( 8305 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 8306 dl, MVT::i32); 8307 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8308 if (isBigEndian) 8309 std::swap (VLo, VHi); 8310 SDValue RegClass = 8311 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 8312 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 8313 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 8314 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 8315 return SDValue( 8316 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 8317 } 8318 8319 static void ReplaceCMP_SWAP_64Results(SDNode *N, 8320 SmallVectorImpl<SDValue> & Results, 8321 SelectionDAG &DAG) { 8322 assert(N->getValueType(0) == MVT::i64 && 8323 "AtomicCmpSwap on types less than 64 should be legal"); 8324 SDValue Ops[] = {N->getOperand(1), 8325 createGPRPairNode(DAG, N->getOperand(2)), 8326 createGPRPairNode(DAG, N->getOperand(3)), 8327 N->getOperand(0)}; 8328 SDNode *CmpSwap = DAG.getMachineNode( 8329 ARM::CMP_SWAP_64, SDLoc(N), 8330 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 8331 8332 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 8333 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 8334 8335 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8336 8337 Results.push_back( 8338 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 8339 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8340 Results.push_back( 8341 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 8342 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8343 Results.push_back(SDValue(CmpSwap, 2)); 8344 } 8345 8346 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 8347 SelectionDAG &DAG) { 8348 const auto &TLI = DAG.getTargetLoweringInfo(); 8349 8350 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 8351 "Custom lowering is MSVCRT specific!"); 8352 8353 SDLoc dl(Op); 8354 SDValue Val = Op.getOperand(0); 8355 MVT Ty = Val->getSimpleValueType(0); 8356 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 8357 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 8358 TLI.getPointerTy(DAG.getDataLayout())); 8359 8360 TargetLowering::ArgListTy Args; 8361 TargetLowering::ArgListEntry Entry; 8362 8363 Entry.Node = Val; 8364 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8365 Entry.IsZExt = true; 8366 Args.push_back(Entry); 8367 8368 Entry.Node = Exponent; 8369 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8370 Entry.IsZExt = true; 8371 Args.push_back(Entry); 8372 8373 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8374 8375 // In the in-chain to the call is the entry node If we are emitting a 8376 // tailcall, the chain will be mutated if the node has a non-entry input 8377 // chain. 8378 SDValue InChain = DAG.getEntryNode(); 8379 SDValue TCChain = InChain; 8380 8381 const Function &F = DAG.getMachineFunction().getFunction(); 8382 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8383 F.getReturnType() == LCRTy; 8384 if (IsTC) 8385 InChain = TCChain; 8386 8387 TargetLowering::CallLoweringInfo CLI(DAG); 8388 CLI.setDebugLoc(dl) 8389 .setChain(InChain) 8390 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8391 .setTailCall(IsTC); 8392 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8393 8394 // Return the chain (the DAG root) if it is a tail call 8395 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8396 } 8397 8398 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8399 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8400 switch (Op.getOpcode()) { 8401 default: llvm_unreachable("Don't know how to custom lower this!"); 8402 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8403 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8404 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8405 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8406 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8407 case ISD::SELECT: return LowerSELECT(Op, DAG); 8408 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8409 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8410 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8411 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8412 case ISD::VASTART: return LowerVASTART(Op, DAG); 8413 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8414 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8415 case ISD::SINT_TO_FP: 8416 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8417 case ISD::FP_TO_SINT: 8418 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8419 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8420 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8421 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8422 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8423 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8424 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8425 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8426 Subtarget); 8427 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8428 case ISD::SHL: 8429 case ISD::SRL: 8430 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8431 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8432 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8433 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8434 case ISD::SRL_PARTS: 8435 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8436 case ISD::CTTZ: 8437 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8438 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8439 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8440 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8441 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8442 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8443 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 8444 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8445 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8446 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8447 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8448 case ISD::MUL: return LowerMUL(Op, DAG); 8449 case ISD::SDIV: 8450 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8451 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8452 return LowerSDIV(Op, DAG); 8453 case ISD::UDIV: 8454 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8455 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8456 return LowerUDIV(Op, DAG); 8457 case ISD::ADDCARRY: 8458 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8459 case ISD::SADDO: 8460 case ISD::SSUBO: 8461 return LowerSignedALUO(Op, DAG); 8462 case ISD::UADDO: 8463 case ISD::USUBO: 8464 return LowerUnsignedALUO(Op, DAG); 8465 case ISD::ATOMIC_LOAD: 8466 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8467 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8468 case ISD::SDIVREM: 8469 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8470 case ISD::DYNAMIC_STACKALLOC: 8471 if (Subtarget->isTargetWindows()) 8472 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8473 llvm_unreachable("Don't know how to custom lower this!"); 8474 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8475 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8476 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8477 case ARMISD::WIN__DBZCHK: return SDValue(); 8478 } 8479 } 8480 8481 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8482 SelectionDAG &DAG) { 8483 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8484 unsigned Opc = 0; 8485 if (IntNo == Intrinsic::arm_smlald) 8486 Opc = ARMISD::SMLALD; 8487 else if (IntNo == Intrinsic::arm_smlaldx) 8488 Opc = ARMISD::SMLALDX; 8489 else if (IntNo == Intrinsic::arm_smlsld) 8490 Opc = ARMISD::SMLSLD; 8491 else if (IntNo == Intrinsic::arm_smlsldx) 8492 Opc = ARMISD::SMLSLDX; 8493 else 8494 return; 8495 8496 SDLoc dl(N); 8497 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8498 N->getOperand(3), 8499 DAG.getConstant(0, dl, MVT::i32)); 8500 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8501 N->getOperand(3), 8502 DAG.getConstant(1, dl, MVT::i32)); 8503 8504 SDValue LongMul = DAG.getNode(Opc, dl, 8505 DAG.getVTList(MVT::i32, MVT::i32), 8506 N->getOperand(1), N->getOperand(2), 8507 Lo, Hi); 8508 Results.push_back(LongMul.getValue(0)); 8509 Results.push_back(LongMul.getValue(1)); 8510 } 8511 8512 /// ReplaceNodeResults - Replace the results of node with an illegal result 8513 /// type with new values built out of custom code. 8514 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8515 SmallVectorImpl<SDValue> &Results, 8516 SelectionDAG &DAG) const { 8517 SDValue Res; 8518 switch (N->getOpcode()) { 8519 default: 8520 llvm_unreachable("Don't know how to custom expand this!"); 8521 case ISD::READ_REGISTER: 8522 ExpandREAD_REGISTER(N, Results, DAG); 8523 break; 8524 case ISD::BITCAST: 8525 Res = ExpandBITCAST(N, DAG, Subtarget); 8526 break; 8527 case ISD::SRL: 8528 case ISD::SRA: 8529 case ISD::SHL: 8530 Res = Expand64BitShift(N, DAG, Subtarget); 8531 break; 8532 case ISD::SREM: 8533 case ISD::UREM: 8534 Res = LowerREM(N, DAG); 8535 break; 8536 case ISD::SDIVREM: 8537 case ISD::UDIVREM: 8538 Res = LowerDivRem(SDValue(N, 0), DAG); 8539 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8540 Results.push_back(Res.getValue(0)); 8541 Results.push_back(Res.getValue(1)); 8542 return; 8543 case ISD::READCYCLECOUNTER: 8544 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8545 return; 8546 case ISD::UDIV: 8547 case ISD::SDIV: 8548 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8549 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8550 Results); 8551 case ISD::ATOMIC_CMP_SWAP: 8552 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8553 return; 8554 case ISD::INTRINSIC_WO_CHAIN: 8555 return ReplaceLongIntrinsic(N, Results, DAG); 8556 case ISD::ABS: 8557 lowerABS(N, Results, DAG); 8558 return ; 8559 8560 } 8561 if (Res.getNode()) 8562 Results.push_back(Res); 8563 } 8564 8565 //===----------------------------------------------------------------------===// 8566 // ARM Scheduler Hooks 8567 //===----------------------------------------------------------------------===// 8568 8569 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8570 /// registers the function context. 8571 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8572 MachineBasicBlock *MBB, 8573 MachineBasicBlock *DispatchBB, 8574 int FI) const { 8575 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8576 "ROPI/RWPI not currently supported with SjLj"); 8577 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8578 DebugLoc dl = MI.getDebugLoc(); 8579 MachineFunction *MF = MBB->getParent(); 8580 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8581 MachineConstantPool *MCP = MF->getConstantPool(); 8582 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8583 const Function &F = MF->getFunction(); 8584 8585 bool isThumb = Subtarget->isThumb(); 8586 bool isThumb2 = Subtarget->isThumb2(); 8587 8588 unsigned PCLabelId = AFI->createPICLabelUId(); 8589 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8590 ARMConstantPoolValue *CPV = 8591 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8592 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8593 8594 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8595 : &ARM::GPRRegClass; 8596 8597 // Grab constant pool and fixed stack memory operands. 8598 MachineMemOperand *CPMMO = 8599 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8600 MachineMemOperand::MOLoad, 4, 4); 8601 8602 MachineMemOperand *FIMMOSt = 8603 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8604 MachineMemOperand::MOStore, 4, 4); 8605 8606 // Load the address of the dispatch MBB into the jump buffer. 8607 if (isThumb2) { 8608 // Incoming value: jbuf 8609 // ldr.n r5, LCPI1_1 8610 // orr r5, r5, #1 8611 // add r5, pc 8612 // str r5, [$jbuf, #+4] ; &jbuf[1] 8613 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8614 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8615 .addConstantPoolIndex(CPI) 8616 .addMemOperand(CPMMO) 8617 .add(predOps(ARMCC::AL)); 8618 // Set the low bit because of thumb mode. 8619 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8620 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8621 .addReg(NewVReg1, RegState::Kill) 8622 .addImm(0x01) 8623 .add(predOps(ARMCC::AL)) 8624 .add(condCodeOp()); 8625 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8626 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8627 .addReg(NewVReg2, RegState::Kill) 8628 .addImm(PCLabelId); 8629 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8630 .addReg(NewVReg3, RegState::Kill) 8631 .addFrameIndex(FI) 8632 .addImm(36) // &jbuf[1] :: pc 8633 .addMemOperand(FIMMOSt) 8634 .add(predOps(ARMCC::AL)); 8635 } else if (isThumb) { 8636 // Incoming value: jbuf 8637 // ldr.n r1, LCPI1_4 8638 // add r1, pc 8639 // mov r2, #1 8640 // orrs r1, r2 8641 // add r2, $jbuf, #+4 ; &jbuf[1] 8642 // str r1, [r2] 8643 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8644 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8645 .addConstantPoolIndex(CPI) 8646 .addMemOperand(CPMMO) 8647 .add(predOps(ARMCC::AL)); 8648 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8649 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8650 .addReg(NewVReg1, RegState::Kill) 8651 .addImm(PCLabelId); 8652 // Set the low bit because of thumb mode. 8653 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8654 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8655 .addReg(ARM::CPSR, RegState::Define) 8656 .addImm(1) 8657 .add(predOps(ARMCC::AL)); 8658 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8659 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8660 .addReg(ARM::CPSR, RegState::Define) 8661 .addReg(NewVReg2, RegState::Kill) 8662 .addReg(NewVReg3, RegState::Kill) 8663 .add(predOps(ARMCC::AL)); 8664 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8665 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8666 .addFrameIndex(FI) 8667 .addImm(36); // &jbuf[1] :: pc 8668 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8669 .addReg(NewVReg4, RegState::Kill) 8670 .addReg(NewVReg5, RegState::Kill) 8671 .addImm(0) 8672 .addMemOperand(FIMMOSt) 8673 .add(predOps(ARMCC::AL)); 8674 } else { 8675 // Incoming value: jbuf 8676 // ldr r1, LCPI1_1 8677 // add r1, pc, r1 8678 // str r1, [$jbuf, #+4] ; &jbuf[1] 8679 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8680 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8681 .addConstantPoolIndex(CPI) 8682 .addImm(0) 8683 .addMemOperand(CPMMO) 8684 .add(predOps(ARMCC::AL)); 8685 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8686 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8687 .addReg(NewVReg1, RegState::Kill) 8688 .addImm(PCLabelId) 8689 .add(predOps(ARMCC::AL)); 8690 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8691 .addReg(NewVReg2, RegState::Kill) 8692 .addFrameIndex(FI) 8693 .addImm(36) // &jbuf[1] :: pc 8694 .addMemOperand(FIMMOSt) 8695 .add(predOps(ARMCC::AL)); 8696 } 8697 } 8698 8699 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8700 MachineBasicBlock *MBB) const { 8701 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8702 DebugLoc dl = MI.getDebugLoc(); 8703 MachineFunction *MF = MBB->getParent(); 8704 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8705 MachineFrameInfo &MFI = MF->getFrameInfo(); 8706 int FI = MFI.getFunctionContextIndex(); 8707 8708 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8709 : &ARM::GPRnopcRegClass; 8710 8711 // Get a mapping of the call site numbers to all of the landing pads they're 8712 // associated with. 8713 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8714 unsigned MaxCSNum = 0; 8715 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8716 ++BB) { 8717 if (!BB->isEHPad()) continue; 8718 8719 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8720 // pad. 8721 for (MachineBasicBlock::iterator 8722 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8723 if (!II->isEHLabel()) continue; 8724 8725 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8726 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8727 8728 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8729 for (SmallVectorImpl<unsigned>::iterator 8730 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8731 CSI != CSE; ++CSI) { 8732 CallSiteNumToLPad[*CSI].push_back(&*BB); 8733 MaxCSNum = std::max(MaxCSNum, *CSI); 8734 } 8735 break; 8736 } 8737 } 8738 8739 // Get an ordered list of the machine basic blocks for the jump table. 8740 std::vector<MachineBasicBlock*> LPadList; 8741 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8742 LPadList.reserve(CallSiteNumToLPad.size()); 8743 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8744 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8745 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8746 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8747 LPadList.push_back(*II); 8748 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8749 } 8750 } 8751 8752 assert(!LPadList.empty() && 8753 "No landing pad destinations for the dispatch jump table!"); 8754 8755 // Create the jump table and associated information. 8756 MachineJumpTableInfo *JTI = 8757 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8758 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8759 8760 // Create the MBBs for the dispatch code. 8761 8762 // Shove the dispatch's address into the return slot in the function context. 8763 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8764 DispatchBB->setIsEHPad(); 8765 8766 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8767 unsigned trap_opcode; 8768 if (Subtarget->isThumb()) 8769 trap_opcode = ARM::tTRAP; 8770 else 8771 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8772 8773 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8774 DispatchBB->addSuccessor(TrapBB); 8775 8776 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8777 DispatchBB->addSuccessor(DispContBB); 8778 8779 // Insert and MBBs. 8780 MF->insert(MF->end(), DispatchBB); 8781 MF->insert(MF->end(), DispContBB); 8782 MF->insert(MF->end(), TrapBB); 8783 8784 // Insert code into the entry block that creates and registers the function 8785 // context. 8786 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8787 8788 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8789 MachinePointerInfo::getFixedStack(*MF, FI), 8790 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8791 8792 MachineInstrBuilder MIB; 8793 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8794 8795 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8796 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8797 8798 // Add a register mask with no preserved registers. This results in all 8799 // registers being marked as clobbered. This can't work if the dispatch block 8800 // is in a Thumb1 function and is linked with ARM code which uses the FP 8801 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8802 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8803 8804 bool IsPositionIndependent = isPositionIndependent(); 8805 unsigned NumLPads = LPadList.size(); 8806 if (Subtarget->isThumb2()) { 8807 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8808 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8809 .addFrameIndex(FI) 8810 .addImm(4) 8811 .addMemOperand(FIMMOLd) 8812 .add(predOps(ARMCC::AL)); 8813 8814 if (NumLPads < 256) { 8815 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8816 .addReg(NewVReg1) 8817 .addImm(LPadList.size()) 8818 .add(predOps(ARMCC::AL)); 8819 } else { 8820 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8821 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8822 .addImm(NumLPads & 0xFFFF) 8823 .add(predOps(ARMCC::AL)); 8824 8825 unsigned VReg2 = VReg1; 8826 if ((NumLPads & 0xFFFF0000) != 0) { 8827 VReg2 = MRI->createVirtualRegister(TRC); 8828 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8829 .addReg(VReg1) 8830 .addImm(NumLPads >> 16) 8831 .add(predOps(ARMCC::AL)); 8832 } 8833 8834 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8835 .addReg(NewVReg1) 8836 .addReg(VReg2) 8837 .add(predOps(ARMCC::AL)); 8838 } 8839 8840 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8841 .addMBB(TrapBB) 8842 .addImm(ARMCC::HI) 8843 .addReg(ARM::CPSR); 8844 8845 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8846 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8847 .addJumpTableIndex(MJTI) 8848 .add(predOps(ARMCC::AL)); 8849 8850 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8851 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8852 .addReg(NewVReg3, RegState::Kill) 8853 .addReg(NewVReg1) 8854 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8855 .add(predOps(ARMCC::AL)) 8856 .add(condCodeOp()); 8857 8858 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8859 .addReg(NewVReg4, RegState::Kill) 8860 .addReg(NewVReg1) 8861 .addJumpTableIndex(MJTI); 8862 } else if (Subtarget->isThumb()) { 8863 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8864 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8865 .addFrameIndex(FI) 8866 .addImm(1) 8867 .addMemOperand(FIMMOLd) 8868 .add(predOps(ARMCC::AL)); 8869 8870 if (NumLPads < 256) { 8871 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8872 .addReg(NewVReg1) 8873 .addImm(NumLPads) 8874 .add(predOps(ARMCC::AL)); 8875 } else { 8876 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8877 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8878 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8879 8880 // MachineConstantPool wants an explicit alignment. 8881 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8882 if (Align == 0) 8883 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8884 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8885 8886 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8887 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8888 .addReg(VReg1, RegState::Define) 8889 .addConstantPoolIndex(Idx) 8890 .add(predOps(ARMCC::AL)); 8891 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8892 .addReg(NewVReg1) 8893 .addReg(VReg1) 8894 .add(predOps(ARMCC::AL)); 8895 } 8896 8897 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8898 .addMBB(TrapBB) 8899 .addImm(ARMCC::HI) 8900 .addReg(ARM::CPSR); 8901 8902 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8903 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8904 .addReg(ARM::CPSR, RegState::Define) 8905 .addReg(NewVReg1) 8906 .addImm(2) 8907 .add(predOps(ARMCC::AL)); 8908 8909 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8910 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8911 .addJumpTableIndex(MJTI) 8912 .add(predOps(ARMCC::AL)); 8913 8914 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8915 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8916 .addReg(ARM::CPSR, RegState::Define) 8917 .addReg(NewVReg2, RegState::Kill) 8918 .addReg(NewVReg3) 8919 .add(predOps(ARMCC::AL)); 8920 8921 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8922 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8923 8924 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8925 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8926 .addReg(NewVReg4, RegState::Kill) 8927 .addImm(0) 8928 .addMemOperand(JTMMOLd) 8929 .add(predOps(ARMCC::AL)); 8930 8931 unsigned NewVReg6 = NewVReg5; 8932 if (IsPositionIndependent) { 8933 NewVReg6 = MRI->createVirtualRegister(TRC); 8934 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8935 .addReg(ARM::CPSR, RegState::Define) 8936 .addReg(NewVReg5, RegState::Kill) 8937 .addReg(NewVReg3) 8938 .add(predOps(ARMCC::AL)); 8939 } 8940 8941 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8942 .addReg(NewVReg6, RegState::Kill) 8943 .addJumpTableIndex(MJTI); 8944 } else { 8945 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8946 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8947 .addFrameIndex(FI) 8948 .addImm(4) 8949 .addMemOperand(FIMMOLd) 8950 .add(predOps(ARMCC::AL)); 8951 8952 if (NumLPads < 256) { 8953 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8954 .addReg(NewVReg1) 8955 .addImm(NumLPads) 8956 .add(predOps(ARMCC::AL)); 8957 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8958 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8959 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8960 .addImm(NumLPads & 0xFFFF) 8961 .add(predOps(ARMCC::AL)); 8962 8963 unsigned VReg2 = VReg1; 8964 if ((NumLPads & 0xFFFF0000) != 0) { 8965 VReg2 = MRI->createVirtualRegister(TRC); 8966 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8967 .addReg(VReg1) 8968 .addImm(NumLPads >> 16) 8969 .add(predOps(ARMCC::AL)); 8970 } 8971 8972 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8973 .addReg(NewVReg1) 8974 .addReg(VReg2) 8975 .add(predOps(ARMCC::AL)); 8976 } else { 8977 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8978 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8979 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8980 8981 // MachineConstantPool wants an explicit alignment. 8982 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8983 if (Align == 0) 8984 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8985 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8986 8987 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8988 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8989 .addReg(VReg1, RegState::Define) 8990 .addConstantPoolIndex(Idx) 8991 .addImm(0) 8992 .add(predOps(ARMCC::AL)); 8993 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8994 .addReg(NewVReg1) 8995 .addReg(VReg1, RegState::Kill) 8996 .add(predOps(ARMCC::AL)); 8997 } 8998 8999 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 9000 .addMBB(TrapBB) 9001 .addImm(ARMCC::HI) 9002 .addReg(ARM::CPSR); 9003 9004 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9005 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 9006 .addReg(NewVReg1) 9007 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9008 .add(predOps(ARMCC::AL)) 9009 .add(condCodeOp()); 9010 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 9011 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 9012 .addJumpTableIndex(MJTI) 9013 .add(predOps(ARMCC::AL)); 9014 9015 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9016 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9017 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 9018 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 9019 .addReg(NewVReg3, RegState::Kill) 9020 .addReg(NewVReg4) 9021 .addImm(0) 9022 .addMemOperand(JTMMOLd) 9023 .add(predOps(ARMCC::AL)); 9024 9025 if (IsPositionIndependent) { 9026 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 9027 .addReg(NewVReg5, RegState::Kill) 9028 .addReg(NewVReg4) 9029 .addJumpTableIndex(MJTI); 9030 } else { 9031 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 9032 .addReg(NewVReg5, RegState::Kill) 9033 .addJumpTableIndex(MJTI); 9034 } 9035 } 9036 9037 // Add the jump table entries as successors to the MBB. 9038 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 9039 for (std::vector<MachineBasicBlock*>::iterator 9040 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 9041 MachineBasicBlock *CurMBB = *I; 9042 if (SeenMBBs.insert(CurMBB).second) 9043 DispContBB->addSuccessor(CurMBB); 9044 } 9045 9046 // N.B. the order the invoke BBs are processed in doesn't matter here. 9047 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 9048 SmallVector<MachineBasicBlock*, 64> MBBLPads; 9049 for (MachineBasicBlock *BB : InvokeBBs) { 9050 9051 // Remove the landing pad successor from the invoke block and replace it 9052 // with the new dispatch block. 9053 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 9054 BB->succ_end()); 9055 while (!Successors.empty()) { 9056 MachineBasicBlock *SMBB = Successors.pop_back_val(); 9057 if (SMBB->isEHPad()) { 9058 BB->removeSuccessor(SMBB); 9059 MBBLPads.push_back(SMBB); 9060 } 9061 } 9062 9063 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 9064 BB->normalizeSuccProbs(); 9065 9066 // Find the invoke call and mark all of the callee-saved registers as 9067 // 'implicit defined' so that they're spilled. This prevents code from 9068 // moving instructions to before the EH block, where they will never be 9069 // executed. 9070 for (MachineBasicBlock::reverse_iterator 9071 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 9072 if (!II->isCall()) continue; 9073 9074 DenseMap<unsigned, bool> DefRegs; 9075 for (MachineInstr::mop_iterator 9076 OI = II->operands_begin(), OE = II->operands_end(); 9077 OI != OE; ++OI) { 9078 if (!OI->isReg()) continue; 9079 DefRegs[OI->getReg()] = true; 9080 } 9081 9082 MachineInstrBuilder MIB(*MF, &*II); 9083 9084 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 9085 unsigned Reg = SavedRegs[i]; 9086 if (Subtarget->isThumb2() && 9087 !ARM::tGPRRegClass.contains(Reg) && 9088 !ARM::hGPRRegClass.contains(Reg)) 9089 continue; 9090 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 9091 continue; 9092 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 9093 continue; 9094 if (!DefRegs[Reg]) 9095 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 9096 } 9097 9098 break; 9099 } 9100 } 9101 9102 // Mark all former landing pads as non-landing pads. The dispatch is the only 9103 // landing pad now. 9104 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9105 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 9106 (*I)->setIsEHPad(false); 9107 9108 // The instruction is gone now. 9109 MI.eraseFromParent(); 9110 } 9111 9112 static 9113 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 9114 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 9115 E = MBB->succ_end(); I != E; ++I) 9116 if (*I != Succ) 9117 return *I; 9118 llvm_unreachable("Expecting a BB with two successors!"); 9119 } 9120 9121 /// Return the load opcode for a given load size. If load size >= 8, 9122 /// neon opcode will be returned. 9123 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 9124 if (LdSize >= 8) 9125 return LdSize == 16 ? ARM::VLD1q32wb_fixed 9126 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 9127 if (IsThumb1) 9128 return LdSize == 4 ? ARM::tLDRi 9129 : LdSize == 2 ? ARM::tLDRHi 9130 : LdSize == 1 ? ARM::tLDRBi : 0; 9131 if (IsThumb2) 9132 return LdSize == 4 ? ARM::t2LDR_POST 9133 : LdSize == 2 ? ARM::t2LDRH_POST 9134 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 9135 return LdSize == 4 ? ARM::LDR_POST_IMM 9136 : LdSize == 2 ? ARM::LDRH_POST 9137 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 9138 } 9139 9140 /// Return the store opcode for a given store size. If store size >= 8, 9141 /// neon opcode will be returned. 9142 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 9143 if (StSize >= 8) 9144 return StSize == 16 ? ARM::VST1q32wb_fixed 9145 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 9146 if (IsThumb1) 9147 return StSize == 4 ? ARM::tSTRi 9148 : StSize == 2 ? ARM::tSTRHi 9149 : StSize == 1 ? ARM::tSTRBi : 0; 9150 if (IsThumb2) 9151 return StSize == 4 ? ARM::t2STR_POST 9152 : StSize == 2 ? ARM::t2STRH_POST 9153 : StSize == 1 ? ARM::t2STRB_POST : 0; 9154 return StSize == 4 ? ARM::STR_POST_IMM 9155 : StSize == 2 ? ARM::STRH_POST 9156 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 9157 } 9158 9159 /// Emit a post-increment load operation with given size. The instructions 9160 /// will be added to BB at Pos. 9161 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9162 const TargetInstrInfo *TII, const DebugLoc &dl, 9163 unsigned LdSize, unsigned Data, unsigned AddrIn, 9164 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9165 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 9166 assert(LdOpc != 0 && "Should have a load opcode"); 9167 if (LdSize >= 8) { 9168 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9169 .addReg(AddrOut, RegState::Define) 9170 .addReg(AddrIn) 9171 .addImm(0) 9172 .add(predOps(ARMCC::AL)); 9173 } else if (IsThumb1) { 9174 // load + update AddrIn 9175 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9176 .addReg(AddrIn) 9177 .addImm(0) 9178 .add(predOps(ARMCC::AL)); 9179 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9180 .add(t1CondCodeOp()) 9181 .addReg(AddrIn) 9182 .addImm(LdSize) 9183 .add(predOps(ARMCC::AL)); 9184 } else if (IsThumb2) { 9185 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9186 .addReg(AddrOut, RegState::Define) 9187 .addReg(AddrIn) 9188 .addImm(LdSize) 9189 .add(predOps(ARMCC::AL)); 9190 } else { // arm 9191 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9192 .addReg(AddrOut, RegState::Define) 9193 .addReg(AddrIn) 9194 .addReg(0) 9195 .addImm(LdSize) 9196 .add(predOps(ARMCC::AL)); 9197 } 9198 } 9199 9200 /// Emit a post-increment store operation with given size. The instructions 9201 /// will be added to BB at Pos. 9202 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9203 const TargetInstrInfo *TII, const DebugLoc &dl, 9204 unsigned StSize, unsigned Data, unsigned AddrIn, 9205 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9206 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 9207 assert(StOpc != 0 && "Should have a store opcode"); 9208 if (StSize >= 8) { 9209 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9210 .addReg(AddrIn) 9211 .addImm(0) 9212 .addReg(Data) 9213 .add(predOps(ARMCC::AL)); 9214 } else if (IsThumb1) { 9215 // store + update AddrIn 9216 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 9217 .addReg(Data) 9218 .addReg(AddrIn) 9219 .addImm(0) 9220 .add(predOps(ARMCC::AL)); 9221 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9222 .add(t1CondCodeOp()) 9223 .addReg(AddrIn) 9224 .addImm(StSize) 9225 .add(predOps(ARMCC::AL)); 9226 } else if (IsThumb2) { 9227 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9228 .addReg(Data) 9229 .addReg(AddrIn) 9230 .addImm(StSize) 9231 .add(predOps(ARMCC::AL)); 9232 } else { // arm 9233 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9234 .addReg(Data) 9235 .addReg(AddrIn) 9236 .addReg(0) 9237 .addImm(StSize) 9238 .add(predOps(ARMCC::AL)); 9239 } 9240 } 9241 9242 MachineBasicBlock * 9243 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 9244 MachineBasicBlock *BB) const { 9245 // This pseudo instruction has 3 operands: dst, src, size 9246 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 9247 // Otherwise, we will generate unrolled scalar copies. 9248 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9249 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9250 MachineFunction::iterator It = ++BB->getIterator(); 9251 9252 unsigned dest = MI.getOperand(0).getReg(); 9253 unsigned src = MI.getOperand(1).getReg(); 9254 unsigned SizeVal = MI.getOperand(2).getImm(); 9255 unsigned Align = MI.getOperand(3).getImm(); 9256 DebugLoc dl = MI.getDebugLoc(); 9257 9258 MachineFunction *MF = BB->getParent(); 9259 MachineRegisterInfo &MRI = MF->getRegInfo(); 9260 unsigned UnitSize = 0; 9261 const TargetRegisterClass *TRC = nullptr; 9262 const TargetRegisterClass *VecTRC = nullptr; 9263 9264 bool IsThumb1 = Subtarget->isThumb1Only(); 9265 bool IsThumb2 = Subtarget->isThumb2(); 9266 bool IsThumb = Subtarget->isThumb(); 9267 9268 if (Align & 1) { 9269 UnitSize = 1; 9270 } else if (Align & 2) { 9271 UnitSize = 2; 9272 } else { 9273 // Check whether we can use NEON instructions. 9274 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 9275 Subtarget->hasNEON()) { 9276 if ((Align % 16 == 0) && SizeVal >= 16) 9277 UnitSize = 16; 9278 else if ((Align % 8 == 0) && SizeVal >= 8) 9279 UnitSize = 8; 9280 } 9281 // Can't use NEON instructions. 9282 if (UnitSize == 0) 9283 UnitSize = 4; 9284 } 9285 9286 // Select the correct opcode and register class for unit size load/store 9287 bool IsNeon = UnitSize >= 8; 9288 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 9289 if (IsNeon) 9290 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 9291 : UnitSize == 8 ? &ARM::DPRRegClass 9292 : nullptr; 9293 9294 unsigned BytesLeft = SizeVal % UnitSize; 9295 unsigned LoopSize = SizeVal - BytesLeft; 9296 9297 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 9298 // Use LDR and STR to copy. 9299 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 9300 // [destOut] = STR_POST(scratch, destIn, UnitSize) 9301 unsigned srcIn = src; 9302 unsigned destIn = dest; 9303 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 9304 unsigned srcOut = MRI.createVirtualRegister(TRC); 9305 unsigned destOut = MRI.createVirtualRegister(TRC); 9306 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9307 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 9308 IsThumb1, IsThumb2); 9309 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 9310 IsThumb1, IsThumb2); 9311 srcIn = srcOut; 9312 destIn = destOut; 9313 } 9314 9315 // Handle the leftover bytes with LDRB and STRB. 9316 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 9317 // [destOut] = STRB_POST(scratch, destIn, 1) 9318 for (unsigned i = 0; i < BytesLeft; i++) { 9319 unsigned srcOut = MRI.createVirtualRegister(TRC); 9320 unsigned destOut = MRI.createVirtualRegister(TRC); 9321 unsigned scratch = MRI.createVirtualRegister(TRC); 9322 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 9323 IsThumb1, IsThumb2); 9324 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 9325 IsThumb1, IsThumb2); 9326 srcIn = srcOut; 9327 destIn = destOut; 9328 } 9329 MI.eraseFromParent(); // The instruction is gone now. 9330 return BB; 9331 } 9332 9333 // Expand the pseudo op to a loop. 9334 // thisMBB: 9335 // ... 9336 // movw varEnd, # --> with thumb2 9337 // movt varEnd, # 9338 // ldrcp varEnd, idx --> without thumb2 9339 // fallthrough --> loopMBB 9340 // loopMBB: 9341 // PHI varPhi, varEnd, varLoop 9342 // PHI srcPhi, src, srcLoop 9343 // PHI destPhi, dst, destLoop 9344 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9345 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 9346 // subs varLoop, varPhi, #UnitSize 9347 // bne loopMBB 9348 // fallthrough --> exitMBB 9349 // exitMBB: 9350 // epilogue to handle left-over bytes 9351 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9352 // [destOut] = STRB_POST(scratch, destLoop, 1) 9353 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9354 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9355 MF->insert(It, loopMBB); 9356 MF->insert(It, exitMBB); 9357 9358 // Transfer the remainder of BB and its successor edges to exitMBB. 9359 exitMBB->splice(exitMBB->begin(), BB, 9360 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9361 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9362 9363 // Load an immediate to varEnd. 9364 unsigned varEnd = MRI.createVirtualRegister(TRC); 9365 if (Subtarget->useMovt()) { 9366 unsigned Vtmp = varEnd; 9367 if ((LoopSize & 0xFFFF0000) != 0) 9368 Vtmp = MRI.createVirtualRegister(TRC); 9369 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 9370 .addImm(LoopSize & 0xFFFF) 9371 .add(predOps(ARMCC::AL)); 9372 9373 if ((LoopSize & 0xFFFF0000) != 0) 9374 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9375 .addReg(Vtmp) 9376 .addImm(LoopSize >> 16) 9377 .add(predOps(ARMCC::AL)); 9378 } else { 9379 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9380 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9381 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9382 9383 // MachineConstantPool wants an explicit alignment. 9384 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9385 if (Align == 0) 9386 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9387 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9388 MachineMemOperand *CPMMO = 9389 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9390 MachineMemOperand::MOLoad, 4, 4); 9391 9392 if (IsThumb) 9393 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9394 .addReg(varEnd, RegState::Define) 9395 .addConstantPoolIndex(Idx) 9396 .add(predOps(ARMCC::AL)) 9397 .addMemOperand(CPMMO); 9398 else 9399 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9400 .addReg(varEnd, RegState::Define) 9401 .addConstantPoolIndex(Idx) 9402 .addImm(0) 9403 .add(predOps(ARMCC::AL)) 9404 .addMemOperand(CPMMO); 9405 } 9406 BB->addSuccessor(loopMBB); 9407 9408 // Generate the loop body: 9409 // varPhi = PHI(varLoop, varEnd) 9410 // srcPhi = PHI(srcLoop, src) 9411 // destPhi = PHI(destLoop, dst) 9412 MachineBasicBlock *entryBB = BB; 9413 BB = loopMBB; 9414 unsigned varLoop = MRI.createVirtualRegister(TRC); 9415 unsigned varPhi = MRI.createVirtualRegister(TRC); 9416 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9417 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9418 unsigned destLoop = MRI.createVirtualRegister(TRC); 9419 unsigned destPhi = MRI.createVirtualRegister(TRC); 9420 9421 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9422 .addReg(varLoop).addMBB(loopMBB) 9423 .addReg(varEnd).addMBB(entryBB); 9424 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9425 .addReg(srcLoop).addMBB(loopMBB) 9426 .addReg(src).addMBB(entryBB); 9427 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9428 .addReg(destLoop).addMBB(loopMBB) 9429 .addReg(dest).addMBB(entryBB); 9430 9431 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9432 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9433 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9434 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9435 IsThumb1, IsThumb2); 9436 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9437 IsThumb1, IsThumb2); 9438 9439 // Decrement loop variable by UnitSize. 9440 if (IsThumb1) { 9441 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9442 .add(t1CondCodeOp()) 9443 .addReg(varPhi) 9444 .addImm(UnitSize) 9445 .add(predOps(ARMCC::AL)); 9446 } else { 9447 MachineInstrBuilder MIB = 9448 BuildMI(*BB, BB->end(), dl, 9449 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9450 MIB.addReg(varPhi) 9451 .addImm(UnitSize) 9452 .add(predOps(ARMCC::AL)) 9453 .add(condCodeOp()); 9454 MIB->getOperand(5).setReg(ARM::CPSR); 9455 MIB->getOperand(5).setIsDef(true); 9456 } 9457 BuildMI(*BB, BB->end(), dl, 9458 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9459 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9460 9461 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9462 BB->addSuccessor(loopMBB); 9463 BB->addSuccessor(exitMBB); 9464 9465 // Add epilogue to handle BytesLeft. 9466 BB = exitMBB; 9467 auto StartOfExit = exitMBB->begin(); 9468 9469 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9470 // [destOut] = STRB_POST(scratch, destLoop, 1) 9471 unsigned srcIn = srcLoop; 9472 unsigned destIn = destLoop; 9473 for (unsigned i = 0; i < BytesLeft; i++) { 9474 unsigned srcOut = MRI.createVirtualRegister(TRC); 9475 unsigned destOut = MRI.createVirtualRegister(TRC); 9476 unsigned scratch = MRI.createVirtualRegister(TRC); 9477 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9478 IsThumb1, IsThumb2); 9479 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9480 IsThumb1, IsThumb2); 9481 srcIn = srcOut; 9482 destIn = destOut; 9483 } 9484 9485 MI.eraseFromParent(); // The instruction is gone now. 9486 return BB; 9487 } 9488 9489 MachineBasicBlock * 9490 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9491 MachineBasicBlock *MBB) const { 9492 const TargetMachine &TM = getTargetMachine(); 9493 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9494 DebugLoc DL = MI.getDebugLoc(); 9495 9496 assert(Subtarget->isTargetWindows() && 9497 "__chkstk is only supported on Windows"); 9498 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9499 9500 // __chkstk takes the number of words to allocate on the stack in R4, and 9501 // returns the stack adjustment in number of bytes in R4. This will not 9502 // clober any other registers (other than the obvious lr). 9503 // 9504 // Although, technically, IP should be considered a register which may be 9505 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9506 // thumb-2 environment, so there is no interworking required. As a result, we 9507 // do not expect a veneer to be emitted by the linker, clobbering IP. 9508 // 9509 // Each module receives its own copy of __chkstk, so no import thunk is 9510 // required, again, ensuring that IP is not clobbered. 9511 // 9512 // Finally, although some linkers may theoretically provide a trampoline for 9513 // out of range calls (which is quite common due to a 32M range limitation of 9514 // branches for Thumb), we can generate the long-call version via 9515 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9516 // IP. 9517 9518 switch (TM.getCodeModel()) { 9519 case CodeModel::Tiny: 9520 llvm_unreachable("Tiny code model not available on ARM."); 9521 case CodeModel::Small: 9522 case CodeModel::Medium: 9523 case CodeModel::Kernel: 9524 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9525 .add(predOps(ARMCC::AL)) 9526 .addExternalSymbol("__chkstk") 9527 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9528 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9529 .addReg(ARM::R12, 9530 RegState::Implicit | RegState::Define | RegState::Dead) 9531 .addReg(ARM::CPSR, 9532 RegState::Implicit | RegState::Define | RegState::Dead); 9533 break; 9534 case CodeModel::Large: { 9535 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9536 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9537 9538 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9539 .addExternalSymbol("__chkstk"); 9540 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9541 .add(predOps(ARMCC::AL)) 9542 .addReg(Reg, RegState::Kill) 9543 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9544 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9545 .addReg(ARM::R12, 9546 RegState::Implicit | RegState::Define | RegState::Dead) 9547 .addReg(ARM::CPSR, 9548 RegState::Implicit | RegState::Define | RegState::Dead); 9549 break; 9550 } 9551 } 9552 9553 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9554 .addReg(ARM::SP, RegState::Kill) 9555 .addReg(ARM::R4, RegState::Kill) 9556 .setMIFlags(MachineInstr::FrameSetup) 9557 .add(predOps(ARMCC::AL)) 9558 .add(condCodeOp()); 9559 9560 MI.eraseFromParent(); 9561 return MBB; 9562 } 9563 9564 MachineBasicBlock * 9565 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9566 MachineBasicBlock *MBB) const { 9567 DebugLoc DL = MI.getDebugLoc(); 9568 MachineFunction *MF = MBB->getParent(); 9569 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9570 9571 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9572 MF->insert(++MBB->getIterator(), ContBB); 9573 ContBB->splice(ContBB->begin(), MBB, 9574 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9575 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9576 MBB->addSuccessor(ContBB); 9577 9578 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9579 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9580 MF->push_back(TrapBB); 9581 MBB->addSuccessor(TrapBB); 9582 9583 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9584 .addReg(MI.getOperand(0).getReg()) 9585 .addImm(0) 9586 .add(predOps(ARMCC::AL)); 9587 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9588 .addMBB(TrapBB) 9589 .addImm(ARMCC::EQ) 9590 .addReg(ARM::CPSR); 9591 9592 MI.eraseFromParent(); 9593 return ContBB; 9594 } 9595 9596 // The CPSR operand of SelectItr might be missing a kill marker 9597 // because there were multiple uses of CPSR, and ISel didn't know 9598 // which to mark. Figure out whether SelectItr should have had a 9599 // kill marker, and set it if it should. Returns the correct kill 9600 // marker value. 9601 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 9602 MachineBasicBlock* BB, 9603 const TargetRegisterInfo* TRI) { 9604 // Scan forward through BB for a use/def of CPSR. 9605 MachineBasicBlock::iterator miI(std::next(SelectItr)); 9606 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 9607 const MachineInstr& mi = *miI; 9608 if (mi.readsRegister(ARM::CPSR)) 9609 return false; 9610 if (mi.definesRegister(ARM::CPSR)) 9611 break; // Should have kill-flag - update below. 9612 } 9613 9614 // If we hit the end of the block, check whether CPSR is live into a 9615 // successor. 9616 if (miI == BB->end()) { 9617 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 9618 sEnd = BB->succ_end(); 9619 sItr != sEnd; ++sItr) { 9620 MachineBasicBlock* succ = *sItr; 9621 if (succ->isLiveIn(ARM::CPSR)) 9622 return false; 9623 } 9624 } 9625 9626 // We found a def, or hit the end of the basic block and CPSR wasn't live 9627 // out. SelectMI should have a kill flag on CPSR. 9628 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 9629 return true; 9630 } 9631 9632 MachineBasicBlock * 9633 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9634 MachineBasicBlock *BB) const { 9635 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9636 DebugLoc dl = MI.getDebugLoc(); 9637 bool isThumb2 = Subtarget->isThumb2(); 9638 switch (MI.getOpcode()) { 9639 default: { 9640 MI.print(errs()); 9641 llvm_unreachable("Unexpected instr type to insert"); 9642 } 9643 9644 // Thumb1 post-indexed loads are really just single-register LDMs. 9645 case ARM::tLDR_postidx: { 9646 MachineOperand Def(MI.getOperand(1)); 9647 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9648 .add(Def) // Rn_wb 9649 .add(MI.getOperand(2)) // Rn 9650 .add(MI.getOperand(3)) // PredImm 9651 .add(MI.getOperand(4)) // PredReg 9652 .add(MI.getOperand(0)) // Rt 9653 .cloneMemRefs(MI); 9654 MI.eraseFromParent(); 9655 return BB; 9656 } 9657 9658 // The Thumb2 pre-indexed stores have the same MI operands, they just 9659 // define them differently in the .td files from the isel patterns, so 9660 // they need pseudos. 9661 case ARM::t2STR_preidx: 9662 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9663 return BB; 9664 case ARM::t2STRB_preidx: 9665 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9666 return BB; 9667 case ARM::t2STRH_preidx: 9668 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9669 return BB; 9670 9671 case ARM::STRi_preidx: 9672 case ARM::STRBi_preidx: { 9673 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9674 : ARM::STRB_PRE_IMM; 9675 // Decode the offset. 9676 unsigned Offset = MI.getOperand(4).getImm(); 9677 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9678 Offset = ARM_AM::getAM2Offset(Offset); 9679 if (isSub) 9680 Offset = -Offset; 9681 9682 MachineMemOperand *MMO = *MI.memoperands_begin(); 9683 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9684 .add(MI.getOperand(0)) // Rn_wb 9685 .add(MI.getOperand(1)) // Rt 9686 .add(MI.getOperand(2)) // Rn 9687 .addImm(Offset) // offset (skip GPR==zero_reg) 9688 .add(MI.getOperand(5)) // pred 9689 .add(MI.getOperand(6)) 9690 .addMemOperand(MMO); 9691 MI.eraseFromParent(); 9692 return BB; 9693 } 9694 case ARM::STRr_preidx: 9695 case ARM::STRBr_preidx: 9696 case ARM::STRH_preidx: { 9697 unsigned NewOpc; 9698 switch (MI.getOpcode()) { 9699 default: llvm_unreachable("unexpected opcode!"); 9700 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9701 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9702 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9703 } 9704 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9705 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9706 MIB.add(MI.getOperand(i)); 9707 MI.eraseFromParent(); 9708 return BB; 9709 } 9710 9711 case ARM::tMOVCCr_pseudo: { 9712 // To "insert" a SELECT_CC instruction, we actually have to insert the 9713 // diamond control-flow pattern. The incoming instruction knows the 9714 // destination vreg to set, the condition code register to branch on, the 9715 // true/false values to select between, and a branch opcode to use. 9716 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9717 MachineFunction::iterator It = ++BB->getIterator(); 9718 9719 // thisMBB: 9720 // ... 9721 // TrueVal = ... 9722 // cmpTY ccX, r1, r2 9723 // bCC copy1MBB 9724 // fallthrough --> copy0MBB 9725 MachineBasicBlock *thisMBB = BB; 9726 MachineFunction *F = BB->getParent(); 9727 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9728 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9729 F->insert(It, copy0MBB); 9730 F->insert(It, sinkMBB); 9731 9732 // Check whether CPSR is live past the tMOVCCr_pseudo. 9733 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 9734 if (!MI.killsRegister(ARM::CPSR) && 9735 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 9736 copy0MBB->addLiveIn(ARM::CPSR); 9737 sinkMBB->addLiveIn(ARM::CPSR); 9738 } 9739 9740 // Transfer the remainder of BB and its successor edges to sinkMBB. 9741 sinkMBB->splice(sinkMBB->begin(), BB, 9742 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9743 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9744 9745 BB->addSuccessor(copy0MBB); 9746 BB->addSuccessor(sinkMBB); 9747 9748 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9749 .addMBB(sinkMBB) 9750 .addImm(MI.getOperand(3).getImm()) 9751 .addReg(MI.getOperand(4).getReg()); 9752 9753 // copy0MBB: 9754 // %FalseValue = ... 9755 // # fallthrough to sinkMBB 9756 BB = copy0MBB; 9757 9758 // Update machine-CFG edges 9759 BB->addSuccessor(sinkMBB); 9760 9761 // sinkMBB: 9762 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9763 // ... 9764 BB = sinkMBB; 9765 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9766 .addReg(MI.getOperand(1).getReg()) 9767 .addMBB(copy0MBB) 9768 .addReg(MI.getOperand(2).getReg()) 9769 .addMBB(thisMBB); 9770 9771 MI.eraseFromParent(); // The pseudo instruction is gone now. 9772 return BB; 9773 } 9774 9775 case ARM::BCCi64: 9776 case ARM::BCCZi64: { 9777 // If there is an unconditional branch to the other successor, remove it. 9778 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9779 9780 // Compare both parts that make up the double comparison separately for 9781 // equality. 9782 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9783 9784 unsigned LHS1 = MI.getOperand(1).getReg(); 9785 unsigned LHS2 = MI.getOperand(2).getReg(); 9786 if (RHSisZero) { 9787 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9788 .addReg(LHS1) 9789 .addImm(0) 9790 .add(predOps(ARMCC::AL)); 9791 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9792 .addReg(LHS2).addImm(0) 9793 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9794 } else { 9795 unsigned RHS1 = MI.getOperand(3).getReg(); 9796 unsigned RHS2 = MI.getOperand(4).getReg(); 9797 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9798 .addReg(LHS1) 9799 .addReg(RHS1) 9800 .add(predOps(ARMCC::AL)); 9801 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9802 .addReg(LHS2).addReg(RHS2) 9803 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9804 } 9805 9806 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9807 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9808 if (MI.getOperand(0).getImm() == ARMCC::NE) 9809 std::swap(destMBB, exitMBB); 9810 9811 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9812 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9813 if (isThumb2) 9814 BuildMI(BB, dl, TII->get(ARM::t2B)) 9815 .addMBB(exitMBB) 9816 .add(predOps(ARMCC::AL)); 9817 else 9818 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9819 9820 MI.eraseFromParent(); // The pseudo instruction is gone now. 9821 return BB; 9822 } 9823 9824 case ARM::Int_eh_sjlj_setjmp: 9825 case ARM::Int_eh_sjlj_setjmp_nofp: 9826 case ARM::tInt_eh_sjlj_setjmp: 9827 case ARM::t2Int_eh_sjlj_setjmp: 9828 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9829 return BB; 9830 9831 case ARM::Int_eh_sjlj_setup_dispatch: 9832 EmitSjLjDispatchBlock(MI, BB); 9833 return BB; 9834 9835 case ARM::ABS: 9836 case ARM::t2ABS: { 9837 // To insert an ABS instruction, we have to insert the 9838 // diamond control-flow pattern. The incoming instruction knows the 9839 // source vreg to test against 0, the destination vreg to set, 9840 // the condition code register to branch on, the 9841 // true/false values to select between, and a branch opcode to use. 9842 // It transforms 9843 // V1 = ABS V0 9844 // into 9845 // V2 = MOVS V0 9846 // BCC (branch to SinkBB if V0 >= 0) 9847 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9848 // SinkBB: V1 = PHI(V2, V3) 9849 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9850 MachineFunction::iterator BBI = ++BB->getIterator(); 9851 MachineFunction *Fn = BB->getParent(); 9852 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9853 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9854 Fn->insert(BBI, RSBBB); 9855 Fn->insert(BBI, SinkBB); 9856 9857 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9858 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9859 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9860 bool isThumb2 = Subtarget->isThumb2(); 9861 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9862 // In Thumb mode S must not be specified if source register is the SP or 9863 // PC and if destination register is the SP, so restrict register class 9864 unsigned NewRsbDstReg = 9865 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9866 9867 // Transfer the remainder of BB and its successor edges to sinkMBB. 9868 SinkBB->splice(SinkBB->begin(), BB, 9869 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9870 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9871 9872 BB->addSuccessor(RSBBB); 9873 BB->addSuccessor(SinkBB); 9874 9875 // fall through to SinkMBB 9876 RSBBB->addSuccessor(SinkBB); 9877 9878 // insert a cmp at the end of BB 9879 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9880 .addReg(ABSSrcReg) 9881 .addImm(0) 9882 .add(predOps(ARMCC::AL)); 9883 9884 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9885 BuildMI(BB, dl, 9886 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9887 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9888 9889 // insert rsbri in RSBBB 9890 // Note: BCC and rsbri will be converted into predicated rsbmi 9891 // by if-conversion pass 9892 BuildMI(*RSBBB, RSBBB->begin(), dl, 9893 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9894 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9895 .addImm(0) 9896 .add(predOps(ARMCC::AL)) 9897 .add(condCodeOp()); 9898 9899 // insert PHI in SinkBB, 9900 // reuse ABSDstReg to not change uses of ABS instruction 9901 BuildMI(*SinkBB, SinkBB->begin(), dl, 9902 TII->get(ARM::PHI), ABSDstReg) 9903 .addReg(NewRsbDstReg).addMBB(RSBBB) 9904 .addReg(ABSSrcReg).addMBB(BB); 9905 9906 // remove ABS instruction 9907 MI.eraseFromParent(); 9908 9909 // return last added BB 9910 return SinkBB; 9911 } 9912 case ARM::COPY_STRUCT_BYVAL_I32: 9913 ++NumLoopByVals; 9914 return EmitStructByval(MI, BB); 9915 case ARM::WIN__CHKSTK: 9916 return EmitLowered__chkstk(MI, BB); 9917 case ARM::WIN__DBZCHK: 9918 return EmitLowered__dbzchk(MI, BB); 9919 } 9920 } 9921 9922 /// Attaches vregs to MEMCPY that it will use as scratch registers 9923 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9924 /// instead of as a custom inserter because we need the use list from the SDNode. 9925 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9926 MachineInstr &MI, const SDNode *Node) { 9927 bool isThumb1 = Subtarget->isThumb1Only(); 9928 9929 DebugLoc DL = MI.getDebugLoc(); 9930 MachineFunction *MF = MI.getParent()->getParent(); 9931 MachineRegisterInfo &MRI = MF->getRegInfo(); 9932 MachineInstrBuilder MIB(*MF, MI); 9933 9934 // If the new dst/src is unused mark it as dead. 9935 if (!Node->hasAnyUseOfValue(0)) { 9936 MI.getOperand(0).setIsDead(true); 9937 } 9938 if (!Node->hasAnyUseOfValue(1)) { 9939 MI.getOperand(1).setIsDead(true); 9940 } 9941 9942 // The MEMCPY both defines and kills the scratch registers. 9943 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9944 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9945 : &ARM::GPRRegClass); 9946 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9947 } 9948 } 9949 9950 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9951 SDNode *Node) const { 9952 if (MI.getOpcode() == ARM::MEMCPY) { 9953 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9954 return; 9955 } 9956 9957 const MCInstrDesc *MCID = &MI.getDesc(); 9958 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9959 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9960 // operand is still set to noreg. If needed, set the optional operand's 9961 // register to CPSR, and remove the redundant implicit def. 9962 // 9963 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9964 9965 // Rename pseudo opcodes. 9966 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9967 unsigned ccOutIdx; 9968 if (NewOpc) { 9969 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9970 MCID = &TII->get(NewOpc); 9971 9972 assert(MCID->getNumOperands() == 9973 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9974 && "converted opcode should be the same except for cc_out" 9975 " (and, on Thumb1, pred)"); 9976 9977 MI.setDesc(*MCID); 9978 9979 // Add the optional cc_out operand 9980 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9981 9982 // On Thumb1, move all input operands to the end, then add the predicate 9983 if (Subtarget->isThumb1Only()) { 9984 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9985 MI.addOperand(MI.getOperand(1)); 9986 MI.RemoveOperand(1); 9987 } 9988 9989 // Restore the ties 9990 for (unsigned i = MI.getNumOperands(); i--;) { 9991 const MachineOperand& op = MI.getOperand(i); 9992 if (op.isReg() && op.isUse()) { 9993 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9994 if (DefIdx != -1) 9995 MI.tieOperands(DefIdx, i); 9996 } 9997 } 9998 9999 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 10000 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 10001 ccOutIdx = 1; 10002 } else 10003 ccOutIdx = MCID->getNumOperands() - 1; 10004 } else 10005 ccOutIdx = MCID->getNumOperands() - 1; 10006 10007 // Any ARM instruction that sets the 's' bit should specify an optional 10008 // "cc_out" operand in the last operand position. 10009 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 10010 assert(!NewOpc && "Optional cc_out operand required"); 10011 return; 10012 } 10013 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 10014 // since we already have an optional CPSR def. 10015 bool definesCPSR = false; 10016 bool deadCPSR = false; 10017 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 10018 ++i) { 10019 const MachineOperand &MO = MI.getOperand(i); 10020 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 10021 definesCPSR = true; 10022 if (MO.isDead()) 10023 deadCPSR = true; 10024 MI.RemoveOperand(i); 10025 break; 10026 } 10027 } 10028 if (!definesCPSR) { 10029 assert(!NewOpc && "Optional cc_out operand required"); 10030 return; 10031 } 10032 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 10033 if (deadCPSR) { 10034 assert(!MI.getOperand(ccOutIdx).getReg() && 10035 "expect uninitialized optional cc_out operand"); 10036 // Thumb1 instructions must have the S bit even if the CPSR is dead. 10037 if (!Subtarget->isThumb1Only()) 10038 return; 10039 } 10040 10041 // If this instruction was defined with an optional CPSR def and its dag node 10042 // had a live implicit CPSR def, then activate the optional CPSR def. 10043 MachineOperand &MO = MI.getOperand(ccOutIdx); 10044 MO.setReg(ARM::CPSR); 10045 MO.setIsDef(true); 10046 } 10047 10048 //===----------------------------------------------------------------------===// 10049 // ARM Optimization Hooks 10050 //===----------------------------------------------------------------------===// 10051 10052 // Helper function that checks if N is a null or all ones constant. 10053 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 10054 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 10055 } 10056 10057 // Return true if N is conditionally 0 or all ones. 10058 // Detects these expressions where cc is an i1 value: 10059 // 10060 // (select cc 0, y) [AllOnes=0] 10061 // (select cc y, 0) [AllOnes=0] 10062 // (zext cc) [AllOnes=0] 10063 // (sext cc) [AllOnes=0/1] 10064 // (select cc -1, y) [AllOnes=1] 10065 // (select cc y, -1) [AllOnes=1] 10066 // 10067 // Invert is set when N is the null/all ones constant when CC is false. 10068 // OtherOp is set to the alternative value of N. 10069 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 10070 SDValue &CC, bool &Invert, 10071 SDValue &OtherOp, 10072 SelectionDAG &DAG) { 10073 switch (N->getOpcode()) { 10074 default: return false; 10075 case ISD::SELECT: { 10076 CC = N->getOperand(0); 10077 SDValue N1 = N->getOperand(1); 10078 SDValue N2 = N->getOperand(2); 10079 if (isZeroOrAllOnes(N1, AllOnes)) { 10080 Invert = false; 10081 OtherOp = N2; 10082 return true; 10083 } 10084 if (isZeroOrAllOnes(N2, AllOnes)) { 10085 Invert = true; 10086 OtherOp = N1; 10087 return true; 10088 } 10089 return false; 10090 } 10091 case ISD::ZERO_EXTEND: 10092 // (zext cc) can never be the all ones value. 10093 if (AllOnes) 10094 return false; 10095 LLVM_FALLTHROUGH; 10096 case ISD::SIGN_EXTEND: { 10097 SDLoc dl(N); 10098 EVT VT = N->getValueType(0); 10099 CC = N->getOperand(0); 10100 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 10101 return false; 10102 Invert = !AllOnes; 10103 if (AllOnes) 10104 // When looking for an AllOnes constant, N is an sext, and the 'other' 10105 // value is 0. 10106 OtherOp = DAG.getConstant(0, dl, VT); 10107 else if (N->getOpcode() == ISD::ZERO_EXTEND) 10108 // When looking for a 0 constant, N can be zext or sext. 10109 OtherOp = DAG.getConstant(1, dl, VT); 10110 else 10111 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 10112 VT); 10113 return true; 10114 } 10115 } 10116 } 10117 10118 // Combine a constant select operand into its use: 10119 // 10120 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10121 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10122 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 10123 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10124 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10125 // 10126 // The transform is rejected if the select doesn't have a constant operand that 10127 // is null, or all ones when AllOnes is set. 10128 // 10129 // Also recognize sext/zext from i1: 10130 // 10131 // (add (zext cc), x) -> (select cc (add x, 1), x) 10132 // (add (sext cc), x) -> (select cc (add x, -1), x) 10133 // 10134 // These transformations eventually create predicated instructions. 10135 // 10136 // @param N The node to transform. 10137 // @param Slct The N operand that is a select. 10138 // @param OtherOp The other N operand (x above). 10139 // @param DCI Context. 10140 // @param AllOnes Require the select constant to be all ones instead of null. 10141 // @returns The new node, or SDValue() on failure. 10142 static 10143 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 10144 TargetLowering::DAGCombinerInfo &DCI, 10145 bool AllOnes = false) { 10146 SelectionDAG &DAG = DCI.DAG; 10147 EVT VT = N->getValueType(0); 10148 SDValue NonConstantVal; 10149 SDValue CCOp; 10150 bool SwapSelectOps; 10151 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 10152 NonConstantVal, DAG)) 10153 return SDValue(); 10154 10155 // Slct is now know to be the desired identity constant when CC is true. 10156 SDValue TrueVal = OtherOp; 10157 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 10158 OtherOp, NonConstantVal); 10159 // Unless SwapSelectOps says CC should be false. 10160 if (SwapSelectOps) 10161 std::swap(TrueVal, FalseVal); 10162 10163 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 10164 CCOp, TrueVal, FalseVal); 10165 } 10166 10167 // Attempt combineSelectAndUse on each operand of a commutative operator N. 10168 static 10169 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 10170 TargetLowering::DAGCombinerInfo &DCI) { 10171 SDValue N0 = N->getOperand(0); 10172 SDValue N1 = N->getOperand(1); 10173 if (N0.getNode()->hasOneUse()) 10174 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 10175 return Result; 10176 if (N1.getNode()->hasOneUse()) 10177 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 10178 return Result; 10179 return SDValue(); 10180 } 10181 10182 static bool IsVUZPShuffleNode(SDNode *N) { 10183 // VUZP shuffle node. 10184 if (N->getOpcode() == ARMISD::VUZP) 10185 return true; 10186 10187 // "VUZP" on i32 is an alias for VTRN. 10188 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 10189 return true; 10190 10191 return false; 10192 } 10193 10194 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 10195 TargetLowering::DAGCombinerInfo &DCI, 10196 const ARMSubtarget *Subtarget) { 10197 // Look for ADD(VUZP.0, VUZP.1). 10198 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 10199 N0 == N1) 10200 return SDValue(); 10201 10202 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 10203 if (!N->getValueType(0).is64BitVector()) 10204 return SDValue(); 10205 10206 // Generate vpadd. 10207 SelectionDAG &DAG = DCI.DAG; 10208 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10209 SDLoc dl(N); 10210 SDNode *Unzip = N0.getNode(); 10211 EVT VT = N->getValueType(0); 10212 10213 SmallVector<SDValue, 8> Ops; 10214 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 10215 TLI.getPointerTy(DAG.getDataLayout()))); 10216 Ops.push_back(Unzip->getOperand(0)); 10217 Ops.push_back(Unzip->getOperand(1)); 10218 10219 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10220 } 10221 10222 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10223 TargetLowering::DAGCombinerInfo &DCI, 10224 const ARMSubtarget *Subtarget) { 10225 // Check for two extended operands. 10226 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 10227 N1.getOpcode() == ISD::SIGN_EXTEND) && 10228 !(N0.getOpcode() == ISD::ZERO_EXTEND && 10229 N1.getOpcode() == ISD::ZERO_EXTEND)) 10230 return SDValue(); 10231 10232 SDValue N00 = N0.getOperand(0); 10233 SDValue N10 = N1.getOperand(0); 10234 10235 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 10236 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 10237 N00 == N10) 10238 return SDValue(); 10239 10240 // We only recognize Q register paddl here; this can't be reached until 10241 // after type legalization. 10242 if (!N00.getValueType().is64BitVector() || 10243 !N0.getValueType().is128BitVector()) 10244 return SDValue(); 10245 10246 // Generate vpaddl. 10247 SelectionDAG &DAG = DCI.DAG; 10248 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10249 SDLoc dl(N); 10250 EVT VT = N->getValueType(0); 10251 10252 SmallVector<SDValue, 8> Ops; 10253 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 10254 unsigned Opcode; 10255 if (N0.getOpcode() == ISD::SIGN_EXTEND) 10256 Opcode = Intrinsic::arm_neon_vpaddls; 10257 else 10258 Opcode = Intrinsic::arm_neon_vpaddlu; 10259 Ops.push_back(DAG.getConstant(Opcode, dl, 10260 TLI.getPointerTy(DAG.getDataLayout()))); 10261 EVT ElemTy = N00.getValueType().getVectorElementType(); 10262 unsigned NumElts = VT.getVectorNumElements(); 10263 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 10264 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 10265 N00.getOperand(0), N00.getOperand(1)); 10266 Ops.push_back(Concat); 10267 10268 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10269 } 10270 10271 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 10272 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 10273 // much easier to match. 10274 static SDValue 10275 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10276 TargetLowering::DAGCombinerInfo &DCI, 10277 const ARMSubtarget *Subtarget) { 10278 // Only perform optimization if after legalize, and if NEON is available. We 10279 // also expected both operands to be BUILD_VECTORs. 10280 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 10281 || N0.getOpcode() != ISD::BUILD_VECTOR 10282 || N1.getOpcode() != ISD::BUILD_VECTOR) 10283 return SDValue(); 10284 10285 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 10286 EVT VT = N->getValueType(0); 10287 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 10288 return SDValue(); 10289 10290 // Check that the vector operands are of the right form. 10291 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 10292 // operands, where N is the size of the formed vector. 10293 // Each EXTRACT_VECTOR should have the same input vector and odd or even 10294 // index such that we have a pair wise add pattern. 10295 10296 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 10297 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10298 return SDValue(); 10299 SDValue Vec = N0->getOperand(0)->getOperand(0); 10300 SDNode *V = Vec.getNode(); 10301 unsigned nextIndex = 0; 10302 10303 // For each operands to the ADD which are BUILD_VECTORs, 10304 // check to see if each of their operands are an EXTRACT_VECTOR with 10305 // the same vector and appropriate index. 10306 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 10307 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 10308 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10309 10310 SDValue ExtVec0 = N0->getOperand(i); 10311 SDValue ExtVec1 = N1->getOperand(i); 10312 10313 // First operand is the vector, verify its the same. 10314 if (V != ExtVec0->getOperand(0).getNode() || 10315 V != ExtVec1->getOperand(0).getNode()) 10316 return SDValue(); 10317 10318 // Second is the constant, verify its correct. 10319 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 10320 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 10321 10322 // For the constant, we want to see all the even or all the odd. 10323 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 10324 || C1->getZExtValue() != nextIndex+1) 10325 return SDValue(); 10326 10327 // Increment index. 10328 nextIndex+=2; 10329 } else 10330 return SDValue(); 10331 } 10332 10333 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 10334 // we're using the entire input vector, otherwise there's a size/legality 10335 // mismatch somewhere. 10336 if (nextIndex != Vec.getValueType().getVectorNumElements() || 10337 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 10338 return SDValue(); 10339 10340 // Create VPADDL node. 10341 SelectionDAG &DAG = DCI.DAG; 10342 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10343 10344 SDLoc dl(N); 10345 10346 // Build operand list. 10347 SmallVector<SDValue, 8> Ops; 10348 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 10349 TLI.getPointerTy(DAG.getDataLayout()))); 10350 10351 // Input is the vector. 10352 Ops.push_back(Vec); 10353 10354 // Get widened type and narrowed type. 10355 MVT widenType; 10356 unsigned numElem = VT.getVectorNumElements(); 10357 10358 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 10359 switch (inputLaneType.getSimpleVT().SimpleTy) { 10360 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 10361 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 10362 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 10363 default: 10364 llvm_unreachable("Invalid vector element type for padd optimization."); 10365 } 10366 10367 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 10368 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 10369 return DAG.getNode(ExtOp, dl, VT, tmp); 10370 } 10371 10372 static SDValue findMUL_LOHI(SDValue V) { 10373 if (V->getOpcode() == ISD::UMUL_LOHI || 10374 V->getOpcode() == ISD::SMUL_LOHI) 10375 return V; 10376 return SDValue(); 10377 } 10378 10379 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 10380 TargetLowering::DAGCombinerInfo &DCI, 10381 const ARMSubtarget *Subtarget) { 10382 if (Subtarget->isThumb()) { 10383 if (!Subtarget->hasDSP()) 10384 return SDValue(); 10385 } else if (!Subtarget->hasV5TEOps()) 10386 return SDValue(); 10387 10388 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 10389 // accumulates the product into a 64-bit value. The 16-bit values will 10390 // be sign extended somehow or SRA'd into 32-bit values 10391 // (addc (adde (mul 16bit, 16bit), lo), hi) 10392 SDValue Mul = AddcNode->getOperand(0); 10393 SDValue Lo = AddcNode->getOperand(1); 10394 if (Mul.getOpcode() != ISD::MUL) { 10395 Lo = AddcNode->getOperand(0); 10396 Mul = AddcNode->getOperand(1); 10397 if (Mul.getOpcode() != ISD::MUL) 10398 return SDValue(); 10399 } 10400 10401 SDValue SRA = AddeNode->getOperand(0); 10402 SDValue Hi = AddeNode->getOperand(1); 10403 if (SRA.getOpcode() != ISD::SRA) { 10404 SRA = AddeNode->getOperand(1); 10405 Hi = AddeNode->getOperand(0); 10406 if (SRA.getOpcode() != ISD::SRA) 10407 return SDValue(); 10408 } 10409 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10410 if (Const->getZExtValue() != 31) 10411 return SDValue(); 10412 } else 10413 return SDValue(); 10414 10415 if (SRA.getOperand(0) != Mul) 10416 return SDValue(); 10417 10418 SelectionDAG &DAG = DCI.DAG; 10419 SDLoc dl(AddcNode); 10420 unsigned Opcode = 0; 10421 SDValue Op0; 10422 SDValue Op1; 10423 10424 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10425 Opcode = ARMISD::SMLALBB; 10426 Op0 = Mul.getOperand(0); 10427 Op1 = Mul.getOperand(1); 10428 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10429 Opcode = ARMISD::SMLALBT; 10430 Op0 = Mul.getOperand(0); 10431 Op1 = Mul.getOperand(1).getOperand(0); 10432 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10433 Opcode = ARMISD::SMLALTB; 10434 Op0 = Mul.getOperand(0).getOperand(0); 10435 Op1 = Mul.getOperand(1); 10436 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10437 Opcode = ARMISD::SMLALTT; 10438 Op0 = Mul->getOperand(0).getOperand(0); 10439 Op1 = Mul->getOperand(1).getOperand(0); 10440 } 10441 10442 if (!Op0 || !Op1) 10443 return SDValue(); 10444 10445 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10446 Op0, Op1, Lo, Hi); 10447 // Replace the ADDs' nodes uses by the MLA node's values. 10448 SDValue HiMLALResult(SMLAL.getNode(), 1); 10449 SDValue LoMLALResult(SMLAL.getNode(), 0); 10450 10451 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10452 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10453 10454 // Return original node to notify the driver to stop replacing. 10455 SDValue resNode(AddcNode, 0); 10456 return resNode; 10457 } 10458 10459 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10460 TargetLowering::DAGCombinerInfo &DCI, 10461 const ARMSubtarget *Subtarget) { 10462 // Look for multiply add opportunities. 10463 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10464 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10465 // a glue link from the first add to the second add. 10466 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10467 // a S/UMLAL instruction. 10468 // UMUL_LOHI 10469 // / :lo \ :hi 10470 // V \ [no multiline comment] 10471 // loAdd -> ADDC | 10472 // \ :carry / 10473 // V V 10474 // ADDE <- hiAdd 10475 // 10476 // In the special case where only the higher part of a signed result is used 10477 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10478 // a constant with the exact value of 0x80000000, we recognize we are dealing 10479 // with a "rounded multiply and add" (or subtract) and transform it into 10480 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10481 10482 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10483 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10484 "Expect an ADDE or SUBE"); 10485 10486 assert(AddeSubeNode->getNumOperands() == 3 && 10487 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10488 "ADDE node has the wrong inputs"); 10489 10490 // Check that we are chained to the right ADDC or SUBC node. 10491 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10492 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10493 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10494 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10495 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10496 return SDValue(); 10497 10498 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10499 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10500 10501 // Check if the two operands are from the same mul_lohi node. 10502 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10503 return SDValue(); 10504 10505 assert(AddcSubcNode->getNumValues() == 2 && 10506 AddcSubcNode->getValueType(0) == MVT::i32 && 10507 "Expect ADDC with two result values. First: i32"); 10508 10509 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10510 // maybe a SMLAL which multiplies two 16-bit values. 10511 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10512 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10513 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10514 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10515 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10516 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10517 10518 // Check for the triangle shape. 10519 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10520 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10521 10522 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10523 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10524 return SDValue(); 10525 10526 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10527 bool IsLeftOperandMUL = false; 10528 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10529 if (MULOp == SDValue()) 10530 MULOp = findMUL_LOHI(AddeSubeOp1); 10531 else 10532 IsLeftOperandMUL = true; 10533 if (MULOp == SDValue()) 10534 return SDValue(); 10535 10536 // Figure out the right opcode. 10537 unsigned Opc = MULOp->getOpcode(); 10538 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10539 10540 // Figure out the high and low input values to the MLAL node. 10541 SDValue *HiAddSub = nullptr; 10542 SDValue *LoMul = nullptr; 10543 SDValue *LowAddSub = nullptr; 10544 10545 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10546 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10547 return SDValue(); 10548 10549 if (IsLeftOperandMUL) 10550 HiAddSub = &AddeSubeOp1; 10551 else 10552 HiAddSub = &AddeSubeOp0; 10553 10554 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10555 // whose low result is fed to the ADDC/SUBC we are checking. 10556 10557 if (AddcSubcOp0 == MULOp.getValue(0)) { 10558 LoMul = &AddcSubcOp0; 10559 LowAddSub = &AddcSubcOp1; 10560 } 10561 if (AddcSubcOp1 == MULOp.getValue(0)) { 10562 LoMul = &AddcSubcOp1; 10563 LowAddSub = &AddcSubcOp0; 10564 } 10565 10566 if (!LoMul) 10567 return SDValue(); 10568 10569 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10570 // the replacement below will create a cycle. 10571 if (AddcSubcNode == HiAddSub->getNode() || 10572 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10573 return SDValue(); 10574 10575 // Create the merged node. 10576 SelectionDAG &DAG = DCI.DAG; 10577 10578 // Start building operand list. 10579 SmallVector<SDValue, 8> Ops; 10580 Ops.push_back(LoMul->getOperand(0)); 10581 Ops.push_back(LoMul->getOperand(1)); 10582 10583 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10584 // the case, we must be doing signed multiplication and only use the higher 10585 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10586 // addition or subtraction with the value of 0x800000. 10587 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10588 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10589 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10590 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10591 0x80000000) { 10592 Ops.push_back(*HiAddSub); 10593 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10594 FinalOpc = ARMISD::SMMLSR; 10595 } else { 10596 FinalOpc = ARMISD::SMMLAR; 10597 } 10598 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10599 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10600 10601 return SDValue(AddeSubeNode, 0); 10602 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10603 // SMMLS is generated during instruction selection and the rest of this 10604 // function can not handle the case where AddcSubcNode is a SUBC. 10605 return SDValue(); 10606 10607 // Finish building the operand list for {U/S}MLAL 10608 Ops.push_back(*LowAddSub); 10609 Ops.push_back(*HiAddSub); 10610 10611 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10612 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10613 10614 // Replace the ADDs' nodes uses by the MLA node's values. 10615 SDValue HiMLALResult(MLALNode.getNode(), 1); 10616 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10617 10618 SDValue LoMLALResult(MLALNode.getNode(), 0); 10619 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10620 10621 // Return original node to notify the driver to stop replacing. 10622 return SDValue(AddeSubeNode, 0); 10623 } 10624 10625 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10626 TargetLowering::DAGCombinerInfo &DCI, 10627 const ARMSubtarget *Subtarget) { 10628 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10629 // While trying to combine for the other MLAL nodes, first search for the 10630 // chance to use UMAAL. Check if Addc uses a node which has already 10631 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10632 // as the addend, and it's handled in PerformUMLALCombine. 10633 10634 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10635 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10636 10637 // Check that we have a glued ADDC node. 10638 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10639 if (AddcNode->getOpcode() != ARMISD::ADDC) 10640 return SDValue(); 10641 10642 // Find the converted UMAAL or quit if it doesn't exist. 10643 SDNode *UmlalNode = nullptr; 10644 SDValue AddHi; 10645 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10646 UmlalNode = AddcNode->getOperand(0).getNode(); 10647 AddHi = AddcNode->getOperand(1); 10648 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10649 UmlalNode = AddcNode->getOperand(1).getNode(); 10650 AddHi = AddcNode->getOperand(0); 10651 } else { 10652 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10653 } 10654 10655 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10656 // the ADDC as well as Zero. 10657 if (!isNullConstant(UmlalNode->getOperand(3))) 10658 return SDValue(); 10659 10660 if ((isNullConstant(AddeNode->getOperand(0)) && 10661 AddeNode->getOperand(1).getNode() == UmlalNode) || 10662 (AddeNode->getOperand(0).getNode() == UmlalNode && 10663 isNullConstant(AddeNode->getOperand(1)))) { 10664 SelectionDAG &DAG = DCI.DAG; 10665 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10666 UmlalNode->getOperand(2), AddHi }; 10667 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10668 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10669 10670 // Replace the ADDs' nodes uses by the UMAAL node's values. 10671 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10672 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10673 10674 // Return original node to notify the driver to stop replacing. 10675 return SDValue(AddeNode, 0); 10676 } 10677 return SDValue(); 10678 } 10679 10680 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10681 const ARMSubtarget *Subtarget) { 10682 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10683 return SDValue(); 10684 10685 // Check that we have a pair of ADDC and ADDE as operands. 10686 // Both addends of the ADDE must be zero. 10687 SDNode* AddcNode = N->getOperand(2).getNode(); 10688 SDNode* AddeNode = N->getOperand(3).getNode(); 10689 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10690 (AddeNode->getOpcode() == ARMISD::ADDE) && 10691 isNullConstant(AddeNode->getOperand(0)) && 10692 isNullConstant(AddeNode->getOperand(1)) && 10693 (AddeNode->getOperand(2).getNode() == AddcNode)) 10694 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10695 DAG.getVTList(MVT::i32, MVT::i32), 10696 {N->getOperand(0), N->getOperand(1), 10697 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10698 else 10699 return SDValue(); 10700 } 10701 10702 static SDValue PerformAddcSubcCombine(SDNode *N, 10703 TargetLowering::DAGCombinerInfo &DCI, 10704 const ARMSubtarget *Subtarget) { 10705 SelectionDAG &DAG(DCI.DAG); 10706 10707 if (N->getOpcode() == ARMISD::SUBC) { 10708 // (SUBC (ADDE 0, 0, C), 1) -> C 10709 SDValue LHS = N->getOperand(0); 10710 SDValue RHS = N->getOperand(1); 10711 if (LHS->getOpcode() == ARMISD::ADDE && 10712 isNullConstant(LHS->getOperand(0)) && 10713 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 10714 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10715 } 10716 } 10717 10718 if (Subtarget->isThumb1Only()) { 10719 SDValue RHS = N->getOperand(1); 10720 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10721 int32_t imm = C->getSExtValue(); 10722 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10723 SDLoc DL(N); 10724 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10725 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10726 : ARMISD::ADDC; 10727 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10728 } 10729 } 10730 } 10731 10732 return SDValue(); 10733 } 10734 10735 static SDValue PerformAddeSubeCombine(SDNode *N, 10736 TargetLowering::DAGCombinerInfo &DCI, 10737 const ARMSubtarget *Subtarget) { 10738 if (Subtarget->isThumb1Only()) { 10739 SelectionDAG &DAG = DCI.DAG; 10740 SDValue RHS = N->getOperand(1); 10741 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10742 int64_t imm = C->getSExtValue(); 10743 if (imm < 0) { 10744 SDLoc DL(N); 10745 10746 // The with-carry-in form matches bitwise not instead of the negation. 10747 // Effectively, the inverse interpretation of the carry flag already 10748 // accounts for part of the negation. 10749 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10750 10751 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10752 : ARMISD::ADDE; 10753 return DAG.getNode(Opcode, DL, N->getVTList(), 10754 N->getOperand(0), RHS, N->getOperand(2)); 10755 } 10756 } 10757 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10758 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10759 } 10760 return SDValue(); 10761 } 10762 10763 static SDValue PerformABSCombine(SDNode *N, 10764 TargetLowering::DAGCombinerInfo &DCI, 10765 const ARMSubtarget *Subtarget) { 10766 SDValue res; 10767 SelectionDAG &DAG = DCI.DAG; 10768 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10769 10770 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 10771 return SDValue(); 10772 10773 if (!TLI.expandABS(N, res, DAG)) 10774 return SDValue(); 10775 10776 return res; 10777 } 10778 10779 /// PerformADDECombine - Target-specific dag combine transform from 10780 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10781 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10782 static SDValue PerformADDECombine(SDNode *N, 10783 TargetLowering::DAGCombinerInfo &DCI, 10784 const ARMSubtarget *Subtarget) { 10785 // Only ARM and Thumb2 support UMLAL/SMLAL. 10786 if (Subtarget->isThumb1Only()) 10787 return PerformAddeSubeCombine(N, DCI, Subtarget); 10788 10789 // Only perform the checks after legalize when the pattern is available. 10790 if (DCI.isBeforeLegalize()) return SDValue(); 10791 10792 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10793 } 10794 10795 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10796 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10797 /// called with the default operands, and if that fails, with commuted 10798 /// operands. 10799 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10800 TargetLowering::DAGCombinerInfo &DCI, 10801 const ARMSubtarget *Subtarget){ 10802 // Attempt to create vpadd for this add. 10803 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10804 return Result; 10805 10806 // Attempt to create vpaddl for this add. 10807 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10808 return Result; 10809 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10810 Subtarget)) 10811 return Result; 10812 10813 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10814 if (N0.getNode()->hasOneUse()) 10815 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10816 return Result; 10817 return SDValue(); 10818 } 10819 10820 bool 10821 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 10822 CombineLevel Level) const { 10823 if (Level == BeforeLegalizeTypes) 10824 return true; 10825 10826 if (N->getOpcode() != ISD::SHL) 10827 return true; 10828 10829 if (Subtarget->isThumb1Only()) { 10830 // Avoid making expensive immediates by commuting shifts. (This logic 10831 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 10832 // for free.) 10833 if (N->getOpcode() != ISD::SHL) 10834 return true; 10835 SDValue N1 = N->getOperand(0); 10836 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 10837 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 10838 return true; 10839 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 10840 if (Const->getAPIntValue().ult(256)) 10841 return false; 10842 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 10843 Const->getAPIntValue().sgt(-256)) 10844 return false; 10845 } 10846 return true; 10847 } 10848 10849 // Turn off commute-with-shift transform after legalization, so it doesn't 10850 // conflict with PerformSHLSimplify. (We could try to detect when 10851 // PerformSHLSimplify would trigger more precisely, but it isn't 10852 // really necessary.) 10853 return false; 10854 } 10855 10856 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 10857 const SDNode *N, CombineLevel Level) const { 10858 if (!Subtarget->isThumb1Only()) 10859 return true; 10860 10861 if (Level == BeforeLegalizeTypes) 10862 return true; 10863 10864 return false; 10865 } 10866 10867 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 10868 if (!Subtarget->hasNEON()) { 10869 if (Subtarget->isThumb1Only()) 10870 return VT.getScalarSizeInBits() <= 32; 10871 return true; 10872 } 10873 return VT.isScalarInteger(); 10874 } 10875 10876 static SDValue PerformSHLSimplify(SDNode *N, 10877 TargetLowering::DAGCombinerInfo &DCI, 10878 const ARMSubtarget *ST) { 10879 // Allow the generic combiner to identify potential bswaps. 10880 if (DCI.isBeforeLegalize()) 10881 return SDValue(); 10882 10883 // DAG combiner will fold: 10884 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10885 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10886 // Other code patterns that can be also be modified have the following form: 10887 // b + ((a << 1) | 510) 10888 // b + ((a << 1) & 510) 10889 // b + ((a << 1) ^ 510) 10890 // b + ((a << 1) + 510) 10891 10892 // Many instructions can perform the shift for free, but it requires both 10893 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10894 // instruction will needed. So, unfold back to the original pattern if: 10895 // - if c1 and c2 are small enough that they don't require mov imms. 10896 // - the user(s) of the node can perform an shl 10897 10898 // No shifted operands for 16-bit instructions. 10899 if (ST->isThumb() && ST->isThumb1Only()) 10900 return SDValue(); 10901 10902 // Check that all the users could perform the shl themselves. 10903 for (auto U : N->uses()) { 10904 switch(U->getOpcode()) { 10905 default: 10906 return SDValue(); 10907 case ISD::SUB: 10908 case ISD::ADD: 10909 case ISD::AND: 10910 case ISD::OR: 10911 case ISD::XOR: 10912 case ISD::SETCC: 10913 case ARMISD::CMP: 10914 // Check that the user isn't already using a constant because there 10915 // aren't any instructions that support an immediate operand and a 10916 // shifted operand. 10917 if (isa<ConstantSDNode>(U->getOperand(0)) || 10918 isa<ConstantSDNode>(U->getOperand(1))) 10919 return SDValue(); 10920 10921 // Check that it's not already using a shift. 10922 if (U->getOperand(0).getOpcode() == ISD::SHL || 10923 U->getOperand(1).getOpcode() == ISD::SHL) 10924 return SDValue(); 10925 break; 10926 } 10927 } 10928 10929 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10930 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10931 return SDValue(); 10932 10933 if (N->getOperand(0).getOpcode() != ISD::SHL) 10934 return SDValue(); 10935 10936 SDValue SHL = N->getOperand(0); 10937 10938 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10939 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10940 if (!C1ShlC2 || !C2) 10941 return SDValue(); 10942 10943 APInt C2Int = C2->getAPIntValue(); 10944 APInt C1Int = C1ShlC2->getAPIntValue(); 10945 10946 // Check that performing a lshr will not lose any information. 10947 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10948 C2Int.getBitWidth() - C2->getZExtValue()); 10949 if ((C1Int & Mask) != C1Int) 10950 return SDValue(); 10951 10952 // Shift the first constant. 10953 C1Int.lshrInPlace(C2Int); 10954 10955 // The immediates are encoded as an 8-bit value that can be rotated. 10956 auto LargeImm = [](const APInt &Imm) { 10957 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 10958 return Imm.getBitWidth() - Zeros > 8; 10959 }; 10960 10961 if (LargeImm(C1Int) || LargeImm(C2Int)) 10962 return SDValue(); 10963 10964 SelectionDAG &DAG = DCI.DAG; 10965 SDLoc dl(N); 10966 SDValue X = SHL.getOperand(0); 10967 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10968 DAG.getConstant(C1Int, dl, MVT::i32)); 10969 // Shift left to compensate for the lshr of C1Int. 10970 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10971 10972 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 10973 SHL.dump(); N->dump()); 10974 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 10975 return Res; 10976 } 10977 10978 10979 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10980 /// 10981 static SDValue PerformADDCombine(SDNode *N, 10982 TargetLowering::DAGCombinerInfo &DCI, 10983 const ARMSubtarget *Subtarget) { 10984 SDValue N0 = N->getOperand(0); 10985 SDValue N1 = N->getOperand(1); 10986 10987 // Only works one way, because it needs an immediate operand. 10988 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10989 return Result; 10990 10991 // First try with the default operand order. 10992 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10993 return Result; 10994 10995 // If that didn't work, try again with the operands commuted. 10996 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10997 } 10998 10999 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 11000 /// 11001 static SDValue PerformSUBCombine(SDNode *N, 11002 TargetLowering::DAGCombinerInfo &DCI) { 11003 SDValue N0 = N->getOperand(0); 11004 SDValue N1 = N->getOperand(1); 11005 11006 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11007 if (N1.getNode()->hasOneUse()) 11008 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 11009 return Result; 11010 11011 return SDValue(); 11012 } 11013 11014 /// PerformVMULCombine 11015 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 11016 /// special multiplier accumulator forwarding. 11017 /// vmul d3, d0, d2 11018 /// vmla d3, d1, d2 11019 /// is faster than 11020 /// vadd d3, d0, d1 11021 /// vmul d3, d3, d2 11022 // However, for (A + B) * (A + B), 11023 // vadd d2, d0, d1 11024 // vmul d3, d0, d2 11025 // vmla d3, d1, d2 11026 // is slower than 11027 // vadd d2, d0, d1 11028 // vmul d3, d2, d2 11029 static SDValue PerformVMULCombine(SDNode *N, 11030 TargetLowering::DAGCombinerInfo &DCI, 11031 const ARMSubtarget *Subtarget) { 11032 if (!Subtarget->hasVMLxForwarding()) 11033 return SDValue(); 11034 11035 SelectionDAG &DAG = DCI.DAG; 11036 SDValue N0 = N->getOperand(0); 11037 SDValue N1 = N->getOperand(1); 11038 unsigned Opcode = N0.getOpcode(); 11039 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11040 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 11041 Opcode = N1.getOpcode(); 11042 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11043 Opcode != ISD::FADD && Opcode != ISD::FSUB) 11044 return SDValue(); 11045 std::swap(N0, N1); 11046 } 11047 11048 if (N0 == N1) 11049 return SDValue(); 11050 11051 EVT VT = N->getValueType(0); 11052 SDLoc DL(N); 11053 SDValue N00 = N0->getOperand(0); 11054 SDValue N01 = N0->getOperand(1); 11055 return DAG.getNode(Opcode, DL, VT, 11056 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 11057 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 11058 } 11059 11060 static SDValue PerformMULCombine(SDNode *N, 11061 TargetLowering::DAGCombinerInfo &DCI, 11062 const ARMSubtarget *Subtarget) { 11063 SelectionDAG &DAG = DCI.DAG; 11064 11065 if (Subtarget->isThumb1Only()) 11066 return SDValue(); 11067 11068 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11069 return SDValue(); 11070 11071 EVT VT = N->getValueType(0); 11072 if (VT.is64BitVector() || VT.is128BitVector()) 11073 return PerformVMULCombine(N, DCI, Subtarget); 11074 if (VT != MVT::i32) 11075 return SDValue(); 11076 11077 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11078 if (!C) 11079 return SDValue(); 11080 11081 int64_t MulAmt = C->getSExtValue(); 11082 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 11083 11084 ShiftAmt = ShiftAmt & (32 - 1); 11085 SDValue V = N->getOperand(0); 11086 SDLoc DL(N); 11087 11088 SDValue Res; 11089 MulAmt >>= ShiftAmt; 11090 11091 if (MulAmt >= 0) { 11092 if (isPowerOf2_32(MulAmt - 1)) { 11093 // (mul x, 2^N + 1) => (add (shl x, N), x) 11094 Res = DAG.getNode(ISD::ADD, DL, VT, 11095 V, 11096 DAG.getNode(ISD::SHL, DL, VT, 11097 V, 11098 DAG.getConstant(Log2_32(MulAmt - 1), DL, 11099 MVT::i32))); 11100 } else if (isPowerOf2_32(MulAmt + 1)) { 11101 // (mul x, 2^N - 1) => (sub (shl x, N), x) 11102 Res = DAG.getNode(ISD::SUB, DL, VT, 11103 DAG.getNode(ISD::SHL, DL, VT, 11104 V, 11105 DAG.getConstant(Log2_32(MulAmt + 1), DL, 11106 MVT::i32)), 11107 V); 11108 } else 11109 return SDValue(); 11110 } else { 11111 uint64_t MulAmtAbs = -MulAmt; 11112 if (isPowerOf2_32(MulAmtAbs + 1)) { 11113 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 11114 Res = DAG.getNode(ISD::SUB, DL, VT, 11115 V, 11116 DAG.getNode(ISD::SHL, DL, VT, 11117 V, 11118 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 11119 MVT::i32))); 11120 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 11121 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 11122 Res = DAG.getNode(ISD::ADD, DL, VT, 11123 V, 11124 DAG.getNode(ISD::SHL, DL, VT, 11125 V, 11126 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 11127 MVT::i32))); 11128 Res = DAG.getNode(ISD::SUB, DL, VT, 11129 DAG.getConstant(0, DL, MVT::i32), Res); 11130 } else 11131 return SDValue(); 11132 } 11133 11134 if (ShiftAmt != 0) 11135 Res = DAG.getNode(ISD::SHL, DL, VT, 11136 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 11137 11138 // Do not add new nodes to DAG combiner worklist. 11139 DCI.CombineTo(N, Res, false); 11140 return SDValue(); 11141 } 11142 11143 static SDValue CombineANDShift(SDNode *N, 11144 TargetLowering::DAGCombinerInfo &DCI, 11145 const ARMSubtarget *Subtarget) { 11146 // Allow DAGCombine to pattern-match before we touch the canonical form. 11147 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11148 return SDValue(); 11149 11150 if (N->getValueType(0) != MVT::i32) 11151 return SDValue(); 11152 11153 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11154 if (!N1C) 11155 return SDValue(); 11156 11157 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 11158 // Don't transform uxtb/uxth. 11159 if (C1 == 255 || C1 == 65535) 11160 return SDValue(); 11161 11162 SDNode *N0 = N->getOperand(0).getNode(); 11163 if (!N0->hasOneUse()) 11164 return SDValue(); 11165 11166 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 11167 return SDValue(); 11168 11169 bool LeftShift = N0->getOpcode() == ISD::SHL; 11170 11171 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 11172 if (!N01C) 11173 return SDValue(); 11174 11175 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 11176 if (!C2 || C2 >= 32) 11177 return SDValue(); 11178 11179 // Clear irrelevant bits in the mask. 11180 if (LeftShift) 11181 C1 &= (-1U << C2); 11182 else 11183 C1 &= (-1U >> C2); 11184 11185 SelectionDAG &DAG = DCI.DAG; 11186 SDLoc DL(N); 11187 11188 // We have a pattern of the form "(and (shl x, c2) c1)" or 11189 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 11190 // transform to a pair of shifts, to save materializing c1. 11191 11192 // First pattern: right shift, then mask off leading bits. 11193 // FIXME: Use demanded bits? 11194 if (!LeftShift && isMask_32(C1)) { 11195 uint32_t C3 = countLeadingZeros(C1); 11196 if (C2 < C3) { 11197 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11198 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11199 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11200 DAG.getConstant(C3, DL, MVT::i32)); 11201 } 11202 } 11203 11204 // First pattern, reversed: left shift, then mask off trailing bits. 11205 if (LeftShift && isMask_32(~C1)) { 11206 uint32_t C3 = countTrailingZeros(C1); 11207 if (C2 < C3) { 11208 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11209 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11210 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11211 DAG.getConstant(C3, DL, MVT::i32)); 11212 } 11213 } 11214 11215 // Second pattern: left shift, then mask off leading bits. 11216 // FIXME: Use demanded bits? 11217 if (LeftShift && isShiftedMask_32(C1)) { 11218 uint32_t Trailing = countTrailingZeros(C1); 11219 uint32_t C3 = countLeadingZeros(C1); 11220 if (Trailing == C2 && C2 + C3 < 32) { 11221 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11222 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11223 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11224 DAG.getConstant(C3, DL, MVT::i32)); 11225 } 11226 } 11227 11228 // Second pattern, reversed: right shift, then mask off trailing bits. 11229 // FIXME: Handle other patterns of known/demanded bits. 11230 if (!LeftShift && isShiftedMask_32(C1)) { 11231 uint32_t Leading = countLeadingZeros(C1); 11232 uint32_t C3 = countTrailingZeros(C1); 11233 if (Leading == C2 && C2 + C3 < 32) { 11234 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11235 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11236 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11237 DAG.getConstant(C3, DL, MVT::i32)); 11238 } 11239 } 11240 11241 // FIXME: Transform "(and (shl x, c2) c1)" -> 11242 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 11243 // c1. 11244 return SDValue(); 11245 } 11246 11247 static SDValue PerformANDCombine(SDNode *N, 11248 TargetLowering::DAGCombinerInfo &DCI, 11249 const ARMSubtarget *Subtarget) { 11250 // Attempt to use immediate-form VBIC 11251 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11252 SDLoc dl(N); 11253 EVT VT = N->getValueType(0); 11254 SelectionDAG &DAG = DCI.DAG; 11255 11256 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11257 return SDValue(); 11258 11259 APInt SplatBits, SplatUndef; 11260 unsigned SplatBitSize; 11261 bool HasAnyUndefs; 11262 if (BVN && Subtarget->hasNEON() && 11263 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11264 if (SplatBitSize <= 64) { 11265 EVT VbicVT; 11266 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 11267 SplatUndef.getZExtValue(), SplatBitSize, 11268 DAG, dl, VbicVT, VT.is128BitVector(), 11269 OtherModImm); 11270 if (Val.getNode()) { 11271 SDValue Input = 11272 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 11273 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 11274 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 11275 } 11276 } 11277 } 11278 11279 if (!Subtarget->isThumb1Only()) { 11280 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 11281 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 11282 return Result; 11283 11284 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11285 return Result; 11286 } 11287 11288 if (Subtarget->isThumb1Only()) 11289 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 11290 return Result; 11291 11292 return SDValue(); 11293 } 11294 11295 // Try combining OR nodes to SMULWB, SMULWT. 11296 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 11297 TargetLowering::DAGCombinerInfo &DCI, 11298 const ARMSubtarget *Subtarget) { 11299 if (!Subtarget->hasV6Ops() || 11300 (Subtarget->isThumb() && 11301 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 11302 return SDValue(); 11303 11304 SDValue SRL = OR->getOperand(0); 11305 SDValue SHL = OR->getOperand(1); 11306 11307 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 11308 SRL = OR->getOperand(1); 11309 SHL = OR->getOperand(0); 11310 } 11311 if (!isSRL16(SRL) || !isSHL16(SHL)) 11312 return SDValue(); 11313 11314 // The first operands to the shifts need to be the two results from the 11315 // same smul_lohi node. 11316 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 11317 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 11318 return SDValue(); 11319 11320 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 11321 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 11322 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 11323 return SDValue(); 11324 11325 // Now we have: 11326 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 11327 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 11328 // For SMUWB the 16-bit value will signed extended somehow. 11329 // For SMULWT only the SRA is required. 11330 // Check both sides of SMUL_LOHI 11331 SDValue OpS16 = SMULLOHI->getOperand(0); 11332 SDValue OpS32 = SMULLOHI->getOperand(1); 11333 11334 SelectionDAG &DAG = DCI.DAG; 11335 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 11336 OpS16 = OpS32; 11337 OpS32 = SMULLOHI->getOperand(0); 11338 } 11339 11340 SDLoc dl(OR); 11341 unsigned Opcode = 0; 11342 if (isS16(OpS16, DAG)) 11343 Opcode = ARMISD::SMULWB; 11344 else if (isSRA16(OpS16)) { 11345 Opcode = ARMISD::SMULWT; 11346 OpS16 = OpS16->getOperand(0); 11347 } 11348 else 11349 return SDValue(); 11350 11351 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 11352 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 11353 return SDValue(OR, 0); 11354 } 11355 11356 static SDValue PerformORCombineToBFI(SDNode *N, 11357 TargetLowering::DAGCombinerInfo &DCI, 11358 const ARMSubtarget *Subtarget) { 11359 // BFI is only available on V6T2+ 11360 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 11361 return SDValue(); 11362 11363 EVT VT = N->getValueType(0); 11364 SDValue N0 = N->getOperand(0); 11365 SDValue N1 = N->getOperand(1); 11366 SelectionDAG &DAG = DCI.DAG; 11367 SDLoc DL(N); 11368 // 1) or (and A, mask), val => ARMbfi A, val, mask 11369 // iff (val & mask) == val 11370 // 11371 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11372 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 11373 // && mask == ~mask2 11374 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 11375 // && ~mask == mask2 11376 // (i.e., copy a bitfield value into another bitfield of the same width) 11377 11378 if (VT != MVT::i32) 11379 return SDValue(); 11380 11381 SDValue N00 = N0.getOperand(0); 11382 11383 // The value and the mask need to be constants so we can verify this is 11384 // actually a bitfield set. If the mask is 0xffff, we can do better 11385 // via a movt instruction, so don't use BFI in that case. 11386 SDValue MaskOp = N0.getOperand(1); 11387 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 11388 if (!MaskC) 11389 return SDValue(); 11390 unsigned Mask = MaskC->getZExtValue(); 11391 if (Mask == 0xffff) 11392 return SDValue(); 11393 SDValue Res; 11394 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 11395 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11396 if (N1C) { 11397 unsigned Val = N1C->getZExtValue(); 11398 if ((Val & ~Mask) != Val) 11399 return SDValue(); 11400 11401 if (ARM::isBitFieldInvertedMask(Mask)) { 11402 Val >>= countTrailingZeros(~Mask); 11403 11404 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 11405 DAG.getConstant(Val, DL, MVT::i32), 11406 DAG.getConstant(Mask, DL, MVT::i32)); 11407 11408 DCI.CombineTo(N, Res, false); 11409 // Return value from the original node to inform the combiner than N is 11410 // now dead. 11411 return SDValue(N, 0); 11412 } 11413 } else if (N1.getOpcode() == ISD::AND) { 11414 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11415 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11416 if (!N11C) 11417 return SDValue(); 11418 unsigned Mask2 = N11C->getZExtValue(); 11419 11420 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 11421 // as is to match. 11422 if (ARM::isBitFieldInvertedMask(Mask) && 11423 (Mask == ~Mask2)) { 11424 // The pack halfword instruction works better for masks that fit it, 11425 // so use that when it's available. 11426 if (Subtarget->hasDSP() && 11427 (Mask == 0xffff || Mask == 0xffff0000)) 11428 return SDValue(); 11429 // 2a 11430 unsigned amt = countTrailingZeros(Mask2); 11431 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 11432 DAG.getConstant(amt, DL, MVT::i32)); 11433 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 11434 DAG.getConstant(Mask, DL, MVT::i32)); 11435 DCI.CombineTo(N, Res, false); 11436 // Return value from the original node to inform the combiner than N is 11437 // now dead. 11438 return SDValue(N, 0); 11439 } else if (ARM::isBitFieldInvertedMask(~Mask) && 11440 (~Mask == Mask2)) { 11441 // The pack halfword instruction works better for masks that fit it, 11442 // so use that when it's available. 11443 if (Subtarget->hasDSP() && 11444 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 11445 return SDValue(); 11446 // 2b 11447 unsigned lsb = countTrailingZeros(Mask); 11448 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 11449 DAG.getConstant(lsb, DL, MVT::i32)); 11450 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 11451 DAG.getConstant(Mask2, DL, MVT::i32)); 11452 DCI.CombineTo(N, Res, false); 11453 // Return value from the original node to inform the combiner than N is 11454 // now dead. 11455 return SDValue(N, 0); 11456 } 11457 } 11458 11459 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 11460 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 11461 ARM::isBitFieldInvertedMask(~Mask)) { 11462 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 11463 // where lsb(mask) == #shamt and masked bits of B are known zero. 11464 SDValue ShAmt = N00.getOperand(1); 11465 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 11466 unsigned LSB = countTrailingZeros(Mask); 11467 if (ShAmtC != LSB) 11468 return SDValue(); 11469 11470 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 11471 DAG.getConstant(~Mask, DL, MVT::i32)); 11472 11473 DCI.CombineTo(N, Res, false); 11474 // Return value from the original node to inform the combiner than N is 11475 // now dead. 11476 return SDValue(N, 0); 11477 } 11478 11479 return SDValue(); 11480 } 11481 11482 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 11483 static SDValue PerformORCombine(SDNode *N, 11484 TargetLowering::DAGCombinerInfo &DCI, 11485 const ARMSubtarget *Subtarget) { 11486 // Attempt to use immediate-form VORR 11487 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11488 SDLoc dl(N); 11489 EVT VT = N->getValueType(0); 11490 SelectionDAG &DAG = DCI.DAG; 11491 11492 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11493 return SDValue(); 11494 11495 APInt SplatBits, SplatUndef; 11496 unsigned SplatBitSize; 11497 bool HasAnyUndefs; 11498 if (BVN && Subtarget->hasNEON() && 11499 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11500 if (SplatBitSize <= 64) { 11501 EVT VorrVT; 11502 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 11503 SplatUndef.getZExtValue(), SplatBitSize, 11504 DAG, dl, VorrVT, VT.is128BitVector(), 11505 OtherModImm); 11506 if (Val.getNode()) { 11507 SDValue Input = 11508 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 11509 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 11510 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 11511 } 11512 } 11513 } 11514 11515 if (!Subtarget->isThumb1Only()) { 11516 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11517 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11518 return Result; 11519 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 11520 return Result; 11521 } 11522 11523 SDValue N0 = N->getOperand(0); 11524 SDValue N1 = N->getOperand(1); 11525 11526 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 11527 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 11528 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 11529 11530 // The code below optimizes (or (and X, Y), Z). 11531 // The AND operand needs to have a single user to make these optimizations 11532 // profitable. 11533 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 11534 return SDValue(); 11535 11536 APInt SplatUndef; 11537 unsigned SplatBitSize; 11538 bool HasAnyUndefs; 11539 11540 APInt SplatBits0, SplatBits1; 11541 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 11542 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 11543 // Ensure that the second operand of both ands are constants 11544 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 11545 HasAnyUndefs) && !HasAnyUndefs) { 11546 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 11547 HasAnyUndefs) && !HasAnyUndefs) { 11548 // Ensure that the bit width of the constants are the same and that 11549 // the splat arguments are logical inverses as per the pattern we 11550 // are trying to simplify. 11551 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 11552 SplatBits0 == ~SplatBits1) { 11553 // Canonicalize the vector type to make instruction selection 11554 // simpler. 11555 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 11556 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 11557 N0->getOperand(1), 11558 N0->getOperand(0), 11559 N1->getOperand(0)); 11560 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 11561 } 11562 } 11563 } 11564 } 11565 11566 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 11567 // reasonable. 11568 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 11569 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 11570 return Res; 11571 } 11572 11573 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11574 return Result; 11575 11576 return SDValue(); 11577 } 11578 11579 static SDValue PerformXORCombine(SDNode *N, 11580 TargetLowering::DAGCombinerInfo &DCI, 11581 const ARMSubtarget *Subtarget) { 11582 EVT VT = N->getValueType(0); 11583 SelectionDAG &DAG = DCI.DAG; 11584 11585 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11586 return SDValue(); 11587 11588 if (!Subtarget->isThumb1Only()) { 11589 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11590 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11591 return Result; 11592 11593 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11594 return Result; 11595 } 11596 11597 return SDValue(); 11598 } 11599 11600 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 11601 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 11602 // their position in "to" (Rd). 11603 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 11604 assert(N->getOpcode() == ARMISD::BFI); 11605 11606 SDValue From = N->getOperand(1); 11607 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 11608 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 11609 11610 // If the Base came from a SHR #C, we can deduce that it is really testing bit 11611 // #C in the base of the SHR. 11612 if (From->getOpcode() == ISD::SRL && 11613 isa<ConstantSDNode>(From->getOperand(1))) { 11614 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 11615 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 11616 FromMask <<= Shift.getLimitedValue(31); 11617 From = From->getOperand(0); 11618 } 11619 11620 return From; 11621 } 11622 11623 // If A and B contain one contiguous set of bits, does A | B == A . B? 11624 // 11625 // Neither A nor B must be zero. 11626 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11627 unsigned LastActiveBitInA = A.countTrailingZeros(); 11628 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11629 return LastActiveBitInA - 1 == FirstActiveBitInB; 11630 } 11631 11632 static SDValue FindBFIToCombineWith(SDNode *N) { 11633 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11634 // if one exists. 11635 APInt ToMask, FromMask; 11636 SDValue From = ParseBFI(N, ToMask, FromMask); 11637 SDValue To = N->getOperand(0); 11638 11639 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11640 // aren't compatible, but not if they set the same bit in their destination as 11641 // we do (or that of any BFI we're going to combine with). 11642 SDValue V = To; 11643 APInt CombinedToMask = ToMask; 11644 while (V.getOpcode() == ARMISD::BFI) { 11645 APInt NewToMask, NewFromMask; 11646 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11647 if (NewFrom != From) { 11648 // This BFI has a different base. Keep going. 11649 CombinedToMask |= NewToMask; 11650 V = V.getOperand(0); 11651 continue; 11652 } 11653 11654 // Do the written bits conflict with any we've seen so far? 11655 if ((NewToMask & CombinedToMask).getBoolValue()) 11656 // Conflicting bits - bail out because going further is unsafe. 11657 return SDValue(); 11658 11659 // Are the new bits contiguous when combined with the old bits? 11660 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11661 BitsProperlyConcatenate(FromMask, NewFromMask)) 11662 return V; 11663 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11664 BitsProperlyConcatenate(NewFromMask, FromMask)) 11665 return V; 11666 11667 // We've seen a write to some bits, so track it. 11668 CombinedToMask |= NewToMask; 11669 // Keep going... 11670 V = V.getOperand(0); 11671 } 11672 11673 return SDValue(); 11674 } 11675 11676 static SDValue PerformBFICombine(SDNode *N, 11677 TargetLowering::DAGCombinerInfo &DCI) { 11678 SDValue N1 = N->getOperand(1); 11679 if (N1.getOpcode() == ISD::AND) { 11680 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11681 // the bits being cleared by the AND are not demanded by the BFI. 11682 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11683 if (!N11C) 11684 return SDValue(); 11685 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11686 unsigned LSB = countTrailingZeros(~InvMask); 11687 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11688 assert(Width < 11689 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11690 "undefined behavior"); 11691 unsigned Mask = (1u << Width) - 1; 11692 unsigned Mask2 = N11C->getZExtValue(); 11693 if ((Mask & (~Mask2)) == 0) 11694 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11695 N->getOperand(0), N1.getOperand(0), 11696 N->getOperand(2)); 11697 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11698 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11699 // Keep track of any consecutive bits set that all come from the same base 11700 // value. We can combine these together into a single BFI. 11701 SDValue CombineBFI = FindBFIToCombineWith(N); 11702 if (CombineBFI == SDValue()) 11703 return SDValue(); 11704 11705 // We've found a BFI. 11706 APInt ToMask1, FromMask1; 11707 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11708 11709 APInt ToMask2, FromMask2; 11710 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11711 assert(From1 == From2); 11712 (void)From2; 11713 11714 // First, unlink CombineBFI. 11715 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11716 // Then create a new BFI, combining the two together. 11717 APInt NewFromMask = FromMask1 | FromMask2; 11718 APInt NewToMask = ToMask1 | ToMask2; 11719 11720 EVT VT = N->getValueType(0); 11721 SDLoc dl(N); 11722 11723 if (NewFromMask[0] == 0) 11724 From1 = DCI.DAG.getNode( 11725 ISD::SRL, dl, VT, From1, 11726 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11727 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11728 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11729 } 11730 return SDValue(); 11731 } 11732 11733 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11734 /// ARMISD::VMOVRRD. 11735 static SDValue PerformVMOVRRDCombine(SDNode *N, 11736 TargetLowering::DAGCombinerInfo &DCI, 11737 const ARMSubtarget *Subtarget) { 11738 // vmovrrd(vmovdrr x, y) -> x,y 11739 SDValue InDouble = N->getOperand(0); 11740 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 11741 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11742 11743 // vmovrrd(load f64) -> (load i32), (load i32) 11744 SDNode *InNode = InDouble.getNode(); 11745 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11746 InNode->getValueType(0) == MVT::f64 && 11747 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11748 !cast<LoadSDNode>(InNode)->isVolatile()) { 11749 // TODO: Should this be done for non-FrameIndex operands? 11750 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11751 11752 SelectionDAG &DAG = DCI.DAG; 11753 SDLoc DL(LD); 11754 SDValue BasePtr = LD->getBasePtr(); 11755 SDValue NewLD1 = 11756 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11757 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11758 11759 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11760 DAG.getConstant(4, DL, MVT::i32)); 11761 11762 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 11763 LD->getPointerInfo().getWithOffset(4), 11764 std::min(4U, LD->getAlignment()), 11765 LD->getMemOperand()->getFlags()); 11766 11767 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11768 if (DCI.DAG.getDataLayout().isBigEndian()) 11769 std::swap (NewLD1, NewLD2); 11770 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11771 return Result; 11772 } 11773 11774 return SDValue(); 11775 } 11776 11777 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11778 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11779 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11780 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11781 SDValue Op0 = N->getOperand(0); 11782 SDValue Op1 = N->getOperand(1); 11783 if (Op0.getOpcode() == ISD::BITCAST) 11784 Op0 = Op0.getOperand(0); 11785 if (Op1.getOpcode() == ISD::BITCAST) 11786 Op1 = Op1.getOperand(0); 11787 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11788 Op0.getNode() == Op1.getNode() && 11789 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11790 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11791 N->getValueType(0), Op0.getOperand(0)); 11792 return SDValue(); 11793 } 11794 11795 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11796 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11797 /// i64 vector to have f64 elements, since the value can then be loaded 11798 /// directly into a VFP register. 11799 static bool hasNormalLoadOperand(SDNode *N) { 11800 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11801 for (unsigned i = 0; i < NumElts; ++i) { 11802 SDNode *Elt = N->getOperand(i).getNode(); 11803 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11804 return true; 11805 } 11806 return false; 11807 } 11808 11809 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11810 /// ISD::BUILD_VECTOR. 11811 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11812 TargetLowering::DAGCombinerInfo &DCI, 11813 const ARMSubtarget *Subtarget) { 11814 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11815 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11816 // into a pair of GPRs, which is fine when the value is used as a scalar, 11817 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11818 SelectionDAG &DAG = DCI.DAG; 11819 if (N->getNumOperands() == 2) 11820 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11821 return RV; 11822 11823 // Load i64 elements as f64 values so that type legalization does not split 11824 // them up into i32 values. 11825 EVT VT = N->getValueType(0); 11826 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11827 return SDValue(); 11828 SDLoc dl(N); 11829 SmallVector<SDValue, 8> Ops; 11830 unsigned NumElts = VT.getVectorNumElements(); 11831 for (unsigned i = 0; i < NumElts; ++i) { 11832 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11833 Ops.push_back(V); 11834 // Make the DAGCombiner fold the bitcast. 11835 DCI.AddToWorklist(V.getNode()); 11836 } 11837 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11838 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11839 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11840 } 11841 11842 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11843 static SDValue 11844 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11845 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11846 // At that time, we may have inserted bitcasts from integer to float. 11847 // If these bitcasts have survived DAGCombine, change the lowering of this 11848 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11849 // force to use floating point types. 11850 11851 // Make sure we can change the type of the vector. 11852 // This is possible iff: 11853 // 1. The vector is only used in a bitcast to a integer type. I.e., 11854 // 1.1. Vector is used only once. 11855 // 1.2. Use is a bit convert to an integer type. 11856 // 2. The size of its operands are 32-bits (64-bits are not legal). 11857 EVT VT = N->getValueType(0); 11858 EVT EltVT = VT.getVectorElementType(); 11859 11860 // Check 1.1. and 2. 11861 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11862 return SDValue(); 11863 11864 // By construction, the input type must be float. 11865 assert(EltVT == MVT::f32 && "Unexpected type!"); 11866 11867 // Check 1.2. 11868 SDNode *Use = *N->use_begin(); 11869 if (Use->getOpcode() != ISD::BITCAST || 11870 Use->getValueType(0).isFloatingPoint()) 11871 return SDValue(); 11872 11873 // Check profitability. 11874 // Model is, if more than half of the relevant operands are bitcast from 11875 // i32, turn the build_vector into a sequence of insert_vector_elt. 11876 // Relevant operands are everything that is not statically 11877 // (i.e., at compile time) bitcasted. 11878 unsigned NumOfBitCastedElts = 0; 11879 unsigned NumElts = VT.getVectorNumElements(); 11880 unsigned NumOfRelevantElts = NumElts; 11881 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11882 SDValue Elt = N->getOperand(Idx); 11883 if (Elt->getOpcode() == ISD::BITCAST) { 11884 // Assume only bit cast to i32 will go away. 11885 if (Elt->getOperand(0).getValueType() == MVT::i32) 11886 ++NumOfBitCastedElts; 11887 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11888 // Constants are statically casted, thus do not count them as 11889 // relevant operands. 11890 --NumOfRelevantElts; 11891 } 11892 11893 // Check if more than half of the elements require a non-free bitcast. 11894 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11895 return SDValue(); 11896 11897 SelectionDAG &DAG = DCI.DAG; 11898 // Create the new vector type. 11899 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11900 // Check if the type is legal. 11901 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11902 if (!TLI.isTypeLegal(VecVT)) 11903 return SDValue(); 11904 11905 // Combine: 11906 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11907 // => BITCAST INSERT_VECTOR_ELT 11908 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11909 // (BITCAST EN), N. 11910 SDValue Vec = DAG.getUNDEF(VecVT); 11911 SDLoc dl(N); 11912 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11913 SDValue V = N->getOperand(Idx); 11914 if (V.isUndef()) 11915 continue; 11916 if (V.getOpcode() == ISD::BITCAST && 11917 V->getOperand(0).getValueType() == MVT::i32) 11918 // Fold obvious case. 11919 V = V.getOperand(0); 11920 else { 11921 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11922 // Make the DAGCombiner fold the bitcasts. 11923 DCI.AddToWorklist(V.getNode()); 11924 } 11925 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11926 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11927 } 11928 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11929 // Make the DAGCombiner fold the bitcasts. 11930 DCI.AddToWorklist(Vec.getNode()); 11931 return Vec; 11932 } 11933 11934 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11935 /// ISD::INSERT_VECTOR_ELT. 11936 static SDValue PerformInsertEltCombine(SDNode *N, 11937 TargetLowering::DAGCombinerInfo &DCI) { 11938 // Bitcast an i64 load inserted into a vector to f64. 11939 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11940 EVT VT = N->getValueType(0); 11941 SDNode *Elt = N->getOperand(1).getNode(); 11942 if (VT.getVectorElementType() != MVT::i64 || 11943 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11944 return SDValue(); 11945 11946 SelectionDAG &DAG = DCI.DAG; 11947 SDLoc dl(N); 11948 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11949 VT.getVectorNumElements()); 11950 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11951 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11952 // Make the DAGCombiner fold the bitcasts. 11953 DCI.AddToWorklist(Vec.getNode()); 11954 DCI.AddToWorklist(V.getNode()); 11955 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11956 Vec, V, N->getOperand(2)); 11957 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11958 } 11959 11960 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11961 /// ISD::VECTOR_SHUFFLE. 11962 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11963 // The LLVM shufflevector instruction does not require the shuffle mask 11964 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11965 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11966 // operands do not match the mask length, they are extended by concatenating 11967 // them with undef vectors. That is probably the right thing for other 11968 // targets, but for NEON it is better to concatenate two double-register 11969 // size vector operands into a single quad-register size vector. Do that 11970 // transformation here: 11971 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11972 // shuffle(concat(v1, v2), undef) 11973 SDValue Op0 = N->getOperand(0); 11974 SDValue Op1 = N->getOperand(1); 11975 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11976 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11977 Op0.getNumOperands() != 2 || 11978 Op1.getNumOperands() != 2) 11979 return SDValue(); 11980 SDValue Concat0Op1 = Op0.getOperand(1); 11981 SDValue Concat1Op1 = Op1.getOperand(1); 11982 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11983 return SDValue(); 11984 // Skip the transformation if any of the types are illegal. 11985 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11986 EVT VT = N->getValueType(0); 11987 if (!TLI.isTypeLegal(VT) || 11988 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11989 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11990 return SDValue(); 11991 11992 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11993 Op0.getOperand(0), Op1.getOperand(0)); 11994 // Translate the shuffle mask. 11995 SmallVector<int, 16> NewMask; 11996 unsigned NumElts = VT.getVectorNumElements(); 11997 unsigned HalfElts = NumElts/2; 11998 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11999 for (unsigned n = 0; n < NumElts; ++n) { 12000 int MaskElt = SVN->getMaskElt(n); 12001 int NewElt = -1; 12002 if (MaskElt < (int)HalfElts) 12003 NewElt = MaskElt; 12004 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 12005 NewElt = HalfElts + MaskElt - NumElts; 12006 NewMask.push_back(NewElt); 12007 } 12008 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 12009 DAG.getUNDEF(VT), NewMask); 12010 } 12011 12012 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 12013 /// NEON load/store intrinsics, and generic vector load/stores, to merge 12014 /// base address updates. 12015 /// For generic load/stores, the memory type is assumed to be a vector. 12016 /// The caller is assumed to have checked legality. 12017 static SDValue CombineBaseUpdate(SDNode *N, 12018 TargetLowering::DAGCombinerInfo &DCI) { 12019 SelectionDAG &DAG = DCI.DAG; 12020 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 12021 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 12022 const bool isStore = N->getOpcode() == ISD::STORE; 12023 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 12024 SDValue Addr = N->getOperand(AddrOpIdx); 12025 MemSDNode *MemN = cast<MemSDNode>(N); 12026 SDLoc dl(N); 12027 12028 // Search for a use of the address operand that is an increment. 12029 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 12030 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 12031 SDNode *User = *UI; 12032 if (User->getOpcode() != ISD::ADD || 12033 UI.getUse().getResNo() != Addr.getResNo()) 12034 continue; 12035 12036 // Check that the add is independent of the load/store. Otherwise, folding 12037 // it would create a cycle. We can avoid searching through Addr as it's a 12038 // predecessor to both. 12039 SmallPtrSet<const SDNode *, 32> Visited; 12040 SmallVector<const SDNode *, 16> Worklist; 12041 Visited.insert(Addr.getNode()); 12042 Worklist.push_back(N); 12043 Worklist.push_back(User); 12044 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 12045 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 12046 continue; 12047 12048 // Find the new opcode for the updating load/store. 12049 bool isLoadOp = true; 12050 bool isLaneOp = false; 12051 unsigned NewOpc = 0; 12052 unsigned NumVecs = 0; 12053 if (isIntrinsic) { 12054 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 12055 switch (IntNo) { 12056 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 12057 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 12058 NumVecs = 1; break; 12059 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 12060 NumVecs = 2; break; 12061 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 12062 NumVecs = 3; break; 12063 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 12064 NumVecs = 4; break; 12065 case Intrinsic::arm_neon_vld2dup: 12066 case Intrinsic::arm_neon_vld3dup: 12067 case Intrinsic::arm_neon_vld4dup: 12068 // TODO: Support updating VLDxDUP nodes. For now, we just skip 12069 // combining base updates for such intrinsics. 12070 continue; 12071 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 12072 NumVecs = 2; isLaneOp = true; break; 12073 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 12074 NumVecs = 3; isLaneOp = true; break; 12075 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 12076 NumVecs = 4; isLaneOp = true; break; 12077 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 12078 NumVecs = 1; isLoadOp = false; break; 12079 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 12080 NumVecs = 2; isLoadOp = false; break; 12081 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 12082 NumVecs = 3; isLoadOp = false; break; 12083 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 12084 NumVecs = 4; isLoadOp = false; break; 12085 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 12086 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 12087 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 12088 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 12089 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 12090 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 12091 } 12092 } else { 12093 isLaneOp = true; 12094 switch (N->getOpcode()) { 12095 default: llvm_unreachable("unexpected opcode for Neon base update"); 12096 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 12097 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 12098 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 12099 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 12100 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 12101 NumVecs = 1; isLaneOp = false; break; 12102 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 12103 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 12104 } 12105 } 12106 12107 // Find the size of memory referenced by the load/store. 12108 EVT VecTy; 12109 if (isLoadOp) { 12110 VecTy = N->getValueType(0); 12111 } else if (isIntrinsic) { 12112 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 12113 } else { 12114 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 12115 VecTy = N->getOperand(1).getValueType(); 12116 } 12117 12118 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 12119 if (isLaneOp) 12120 NumBytes /= VecTy.getVectorNumElements(); 12121 12122 // If the increment is a constant, it must match the memory ref size. 12123 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 12124 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 12125 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 12126 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 12127 // separate instructions that make it harder to use a non-constant update. 12128 continue; 12129 } 12130 12131 // OK, we found an ADD we can fold into the base update. 12132 // Now, create a _UPD node, taking care of not breaking alignment. 12133 12134 EVT AlignedVecTy = VecTy; 12135 unsigned Alignment = MemN->getAlignment(); 12136 12137 // If this is a less-than-standard-aligned load/store, change the type to 12138 // match the standard alignment. 12139 // The alignment is overlooked when selecting _UPD variants; and it's 12140 // easier to introduce bitcasts here than fix that. 12141 // There are 3 ways to get to this base-update combine: 12142 // - intrinsics: they are assumed to be properly aligned (to the standard 12143 // alignment of the memory type), so we don't need to do anything. 12144 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 12145 // intrinsics, so, likewise, there's nothing to do. 12146 // - generic load/store instructions: the alignment is specified as an 12147 // explicit operand, rather than implicitly as the standard alignment 12148 // of the memory type (like the intrisics). We need to change the 12149 // memory type to match the explicit alignment. That way, we don't 12150 // generate non-standard-aligned ARMISD::VLDx nodes. 12151 if (isa<LSBaseSDNode>(N)) { 12152 if (Alignment == 0) 12153 Alignment = 1; 12154 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 12155 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 12156 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 12157 assert(!isLaneOp && "Unexpected generic load/store lane."); 12158 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 12159 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 12160 } 12161 // Don't set an explicit alignment on regular load/stores that we want 12162 // to transform to VLD/VST 1_UPD nodes. 12163 // This matches the behavior of regular load/stores, which only get an 12164 // explicit alignment if the MMO alignment is larger than the standard 12165 // alignment of the memory type. 12166 // Intrinsics, however, always get an explicit alignment, set to the 12167 // alignment of the MMO. 12168 Alignment = 1; 12169 } 12170 12171 // Create the new updating load/store node. 12172 // First, create an SDVTList for the new updating node's results. 12173 EVT Tys[6]; 12174 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 12175 unsigned n; 12176 for (n = 0; n < NumResultVecs; ++n) 12177 Tys[n] = AlignedVecTy; 12178 Tys[n++] = MVT::i32; 12179 Tys[n] = MVT::Other; 12180 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 12181 12182 // Then, gather the new node's operands. 12183 SmallVector<SDValue, 8> Ops; 12184 Ops.push_back(N->getOperand(0)); // incoming chain 12185 Ops.push_back(N->getOperand(AddrOpIdx)); 12186 Ops.push_back(Inc); 12187 12188 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 12189 // Try to match the intrinsic's signature 12190 Ops.push_back(StN->getValue()); 12191 } else { 12192 // Loads (and of course intrinsics) match the intrinsics' signature, 12193 // so just add all but the alignment operand. 12194 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 12195 Ops.push_back(N->getOperand(i)); 12196 } 12197 12198 // For all node types, the alignment operand is always the last one. 12199 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 12200 12201 // If this is a non-standard-aligned STORE, the penultimate operand is the 12202 // stored value. Bitcast it to the aligned type. 12203 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 12204 SDValue &StVal = Ops[Ops.size()-2]; 12205 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 12206 } 12207 12208 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 12209 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 12210 MemN->getMemOperand()); 12211 12212 // Update the uses. 12213 SmallVector<SDValue, 5> NewResults; 12214 for (unsigned i = 0; i < NumResultVecs; ++i) 12215 NewResults.push_back(SDValue(UpdN.getNode(), i)); 12216 12217 // If this is an non-standard-aligned LOAD, the first result is the loaded 12218 // value. Bitcast it to the expected result type. 12219 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 12220 SDValue &LdVal = NewResults[0]; 12221 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 12222 } 12223 12224 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 12225 DCI.CombineTo(N, NewResults); 12226 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 12227 12228 break; 12229 } 12230 return SDValue(); 12231 } 12232 12233 static SDValue PerformVLDCombine(SDNode *N, 12234 TargetLowering::DAGCombinerInfo &DCI) { 12235 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12236 return SDValue(); 12237 12238 return CombineBaseUpdate(N, DCI); 12239 } 12240 12241 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 12242 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 12243 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 12244 /// return true. 12245 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12246 SelectionDAG &DAG = DCI.DAG; 12247 EVT VT = N->getValueType(0); 12248 // vldN-dup instructions only support 64-bit vectors for N > 1. 12249 if (!VT.is64BitVector()) 12250 return false; 12251 12252 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 12253 SDNode *VLD = N->getOperand(0).getNode(); 12254 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 12255 return false; 12256 unsigned NumVecs = 0; 12257 unsigned NewOpc = 0; 12258 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 12259 if (IntNo == Intrinsic::arm_neon_vld2lane) { 12260 NumVecs = 2; 12261 NewOpc = ARMISD::VLD2DUP; 12262 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 12263 NumVecs = 3; 12264 NewOpc = ARMISD::VLD3DUP; 12265 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 12266 NumVecs = 4; 12267 NewOpc = ARMISD::VLD4DUP; 12268 } else { 12269 return false; 12270 } 12271 12272 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 12273 // numbers match the load. 12274 unsigned VLDLaneNo = 12275 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 12276 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12277 UI != UE; ++UI) { 12278 // Ignore uses of the chain result. 12279 if (UI.getUse().getResNo() == NumVecs) 12280 continue; 12281 SDNode *User = *UI; 12282 if (User->getOpcode() != ARMISD::VDUPLANE || 12283 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 12284 return false; 12285 } 12286 12287 // Create the vldN-dup node. 12288 EVT Tys[5]; 12289 unsigned n; 12290 for (n = 0; n < NumVecs; ++n) 12291 Tys[n] = VT; 12292 Tys[n] = MVT::Other; 12293 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 12294 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 12295 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 12296 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 12297 Ops, VLDMemInt->getMemoryVT(), 12298 VLDMemInt->getMemOperand()); 12299 12300 // Update the uses. 12301 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12302 UI != UE; ++UI) { 12303 unsigned ResNo = UI.getUse().getResNo(); 12304 // Ignore uses of the chain result. 12305 if (ResNo == NumVecs) 12306 continue; 12307 SDNode *User = *UI; 12308 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 12309 } 12310 12311 // Now the vldN-lane intrinsic is dead except for its chain result. 12312 // Update uses of the chain. 12313 std::vector<SDValue> VLDDupResults; 12314 for (unsigned n = 0; n < NumVecs; ++n) 12315 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 12316 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 12317 DCI.CombineTo(VLD, VLDDupResults); 12318 12319 return true; 12320 } 12321 12322 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 12323 /// ARMISD::VDUPLANE. 12324 static SDValue PerformVDUPLANECombine(SDNode *N, 12325 TargetLowering::DAGCombinerInfo &DCI) { 12326 SDValue Op = N->getOperand(0); 12327 12328 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 12329 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 12330 if (CombineVLDDUP(N, DCI)) 12331 return SDValue(N, 0); 12332 12333 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 12334 // redundant. Ignore bit_converts for now; element sizes are checked below. 12335 while (Op.getOpcode() == ISD::BITCAST) 12336 Op = Op.getOperand(0); 12337 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 12338 return SDValue(); 12339 12340 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 12341 unsigned EltSize = Op.getScalarValueSizeInBits(); 12342 // The canonical VMOV for a zero vector uses a 32-bit element size. 12343 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12344 unsigned EltBits; 12345 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 12346 EltSize = 8; 12347 EVT VT = N->getValueType(0); 12348 if (EltSize > VT.getScalarSizeInBits()) 12349 return SDValue(); 12350 12351 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 12352 } 12353 12354 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 12355 static SDValue PerformVDUPCombine(SDNode *N, 12356 TargetLowering::DAGCombinerInfo &DCI, 12357 const ARMSubtarget *Subtarget) { 12358 SelectionDAG &DAG = DCI.DAG; 12359 SDValue Op = N->getOperand(0); 12360 12361 if (!Subtarget->hasNEON()) 12362 return SDValue(); 12363 12364 // Match VDUP(LOAD) -> VLD1DUP. 12365 // We match this pattern here rather than waiting for isel because the 12366 // transform is only legal for unindexed loads. 12367 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 12368 if (LD && Op.hasOneUse() && LD->isUnindexed() && 12369 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 12370 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 12371 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 12372 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 12373 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 12374 Ops, LD->getMemoryVT(), 12375 LD->getMemOperand()); 12376 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 12377 return VLDDup; 12378 } 12379 12380 return SDValue(); 12381 } 12382 12383 static SDValue PerformLOADCombine(SDNode *N, 12384 TargetLowering::DAGCombinerInfo &DCI) { 12385 EVT VT = N->getValueType(0); 12386 12387 // If this is a legal vector load, try to combine it into a VLD1_UPD. 12388 if (ISD::isNormalLoad(N) && VT.isVector() && 12389 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12390 return CombineBaseUpdate(N, DCI); 12391 12392 return SDValue(); 12393 } 12394 12395 /// PerformSTORECombine - Target-specific dag combine xforms for 12396 /// ISD::STORE. 12397 static SDValue PerformSTORECombine(SDNode *N, 12398 TargetLowering::DAGCombinerInfo &DCI) { 12399 StoreSDNode *St = cast<StoreSDNode>(N); 12400 if (St->isVolatile()) 12401 return SDValue(); 12402 12403 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 12404 // pack all of the elements in one place. Next, store to memory in fewer 12405 // chunks. 12406 SDValue StVal = St->getValue(); 12407 EVT VT = StVal.getValueType(); 12408 if (St->isTruncatingStore() && VT.isVector()) { 12409 SelectionDAG &DAG = DCI.DAG; 12410 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12411 EVT StVT = St->getMemoryVT(); 12412 unsigned NumElems = VT.getVectorNumElements(); 12413 assert(StVT != VT && "Cannot truncate to the same type"); 12414 unsigned FromEltSz = VT.getScalarSizeInBits(); 12415 unsigned ToEltSz = StVT.getScalarSizeInBits(); 12416 12417 // From, To sizes and ElemCount must be pow of two 12418 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 12419 12420 // We are going to use the original vector elt for storing. 12421 // Accumulated smaller vector elements must be a multiple of the store size. 12422 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 12423 12424 unsigned SizeRatio = FromEltSz / ToEltSz; 12425 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 12426 12427 // Create a type on which we perform the shuffle. 12428 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 12429 NumElems*SizeRatio); 12430 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 12431 12432 SDLoc DL(St); 12433 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 12434 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 12435 for (unsigned i = 0; i < NumElems; ++i) 12436 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 12437 ? (i + 1) * SizeRatio - 1 12438 : i * SizeRatio; 12439 12440 // Can't shuffle using an illegal type. 12441 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 12442 12443 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 12444 DAG.getUNDEF(WideVec.getValueType()), 12445 ShuffleVec); 12446 // At this point all of the data is stored at the bottom of the 12447 // register. We now need to save it to mem. 12448 12449 // Find the largest store unit 12450 MVT StoreType = MVT::i8; 12451 for (MVT Tp : MVT::integer_valuetypes()) { 12452 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 12453 StoreType = Tp; 12454 } 12455 // Didn't find a legal store type. 12456 if (!TLI.isTypeLegal(StoreType)) 12457 return SDValue(); 12458 12459 // Bitcast the original vector into a vector of store-size units 12460 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 12461 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 12462 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 12463 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 12464 SmallVector<SDValue, 8> Chains; 12465 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 12466 TLI.getPointerTy(DAG.getDataLayout())); 12467 SDValue BasePtr = St->getBasePtr(); 12468 12469 // Perform one or more big stores into memory. 12470 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 12471 for (unsigned I = 0; I < E; I++) { 12472 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 12473 StoreType, ShuffWide, 12474 DAG.getIntPtrConstant(I, DL)); 12475 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 12476 St->getPointerInfo(), St->getAlignment(), 12477 St->getMemOperand()->getFlags()); 12478 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 12479 Increment); 12480 Chains.push_back(Ch); 12481 } 12482 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 12483 } 12484 12485 if (!ISD::isNormalStore(St)) 12486 return SDValue(); 12487 12488 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 12489 // ARM stores of arguments in the same cache line. 12490 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 12491 StVal.getNode()->hasOneUse()) { 12492 SelectionDAG &DAG = DCI.DAG; 12493 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 12494 SDLoc DL(St); 12495 SDValue BasePtr = St->getBasePtr(); 12496 SDValue NewST1 = DAG.getStore( 12497 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 12498 BasePtr, St->getPointerInfo(), St->getAlignment(), 12499 St->getMemOperand()->getFlags()); 12500 12501 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12502 DAG.getConstant(4, DL, MVT::i32)); 12503 return DAG.getStore(NewST1.getValue(0), DL, 12504 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 12505 OffsetPtr, St->getPointerInfo(), 12506 std::min(4U, St->getAlignment() / 2), 12507 St->getMemOperand()->getFlags()); 12508 } 12509 12510 if (StVal.getValueType() == MVT::i64 && 12511 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12512 12513 // Bitcast an i64 store extracted from a vector to f64. 12514 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12515 SelectionDAG &DAG = DCI.DAG; 12516 SDLoc dl(StVal); 12517 SDValue IntVec = StVal.getOperand(0); 12518 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12519 IntVec.getValueType().getVectorNumElements()); 12520 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 12521 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 12522 Vec, StVal.getOperand(1)); 12523 dl = SDLoc(N); 12524 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 12525 // Make the DAGCombiner fold the bitcasts. 12526 DCI.AddToWorklist(Vec.getNode()); 12527 DCI.AddToWorklist(ExtElt.getNode()); 12528 DCI.AddToWorklist(V.getNode()); 12529 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 12530 St->getPointerInfo(), St->getAlignment(), 12531 St->getMemOperand()->getFlags(), St->getAAInfo()); 12532 } 12533 12534 // If this is a legal vector store, try to combine it into a VST1_UPD. 12535 if (ISD::isNormalStore(N) && VT.isVector() && 12536 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12537 return CombineBaseUpdate(N, DCI); 12538 12539 return SDValue(); 12540 } 12541 12542 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 12543 /// can replace combinations of VMUL and VCVT (floating-point to integer) 12544 /// when the VMUL has a constant operand that is a power of 2. 12545 /// 12546 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12547 /// vmul.f32 d16, d17, d16 12548 /// vcvt.s32.f32 d16, d16 12549 /// becomes: 12550 /// vcvt.s32.f32 d16, d16, #3 12551 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 12552 const ARMSubtarget *Subtarget) { 12553 if (!Subtarget->hasNEON()) 12554 return SDValue(); 12555 12556 SDValue Op = N->getOperand(0); 12557 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12558 Op.getOpcode() != ISD::FMUL) 12559 return SDValue(); 12560 12561 SDValue ConstVec = Op->getOperand(1); 12562 if (!isa<BuildVectorSDNode>(ConstVec)) 12563 return SDValue(); 12564 12565 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12566 uint32_t FloatBits = FloatTy.getSizeInBits(); 12567 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12568 uint32_t IntBits = IntTy.getSizeInBits(); 12569 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12570 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 12571 // These instructions only exist converting from f32 to i32. We can handle 12572 // smaller integers by generating an extra truncate, but larger ones would 12573 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 12574 // these intructions only support v2i32/v4i32 types. 12575 return SDValue(); 12576 } 12577 12578 BitVector UndefElements; 12579 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12580 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12581 if (C == -1 || C == 0 || C > 32) 12582 return SDValue(); 12583 12584 SDLoc dl(N); 12585 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 12586 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 12587 Intrinsic::arm_neon_vcvtfp2fxu; 12588 SDValue FixConv = DAG.getNode( 12589 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12590 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 12591 DAG.getConstant(C, dl, MVT::i32)); 12592 12593 if (IntBits < FloatBits) 12594 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 12595 12596 return FixConv; 12597 } 12598 12599 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 12600 /// can replace combinations of VCVT (integer to floating-point) and VDIV 12601 /// when the VDIV has a constant operand that is a power of 2. 12602 /// 12603 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12604 /// vcvt.f32.s32 d16, d16 12605 /// vdiv.f32 d16, d17, d16 12606 /// becomes: 12607 /// vcvt.f32.s32 d16, d16, #3 12608 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 12609 const ARMSubtarget *Subtarget) { 12610 if (!Subtarget->hasNEON()) 12611 return SDValue(); 12612 12613 SDValue Op = N->getOperand(0); 12614 unsigned OpOpcode = Op.getNode()->getOpcode(); 12615 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 12616 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 12617 return SDValue(); 12618 12619 SDValue ConstVec = N->getOperand(1); 12620 if (!isa<BuildVectorSDNode>(ConstVec)) 12621 return SDValue(); 12622 12623 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12624 uint32_t FloatBits = FloatTy.getSizeInBits(); 12625 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12626 uint32_t IntBits = IntTy.getSizeInBits(); 12627 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12628 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 12629 // These instructions only exist converting from i32 to f32. We can handle 12630 // smaller integers by generating an extra extend, but larger ones would 12631 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 12632 // these intructions only support v2i32/v4i32 types. 12633 return SDValue(); 12634 } 12635 12636 BitVector UndefElements; 12637 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12638 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12639 if (C == -1 || C == 0 || C > 32) 12640 return SDValue(); 12641 12642 SDLoc dl(N); 12643 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12644 SDValue ConvInput = Op.getOperand(0); 12645 if (IntBits < FloatBits) 12646 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12647 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12648 ConvInput); 12649 12650 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12651 Intrinsic::arm_neon_vcvtfxu2fp; 12652 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12653 Op.getValueType(), 12654 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12655 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12656 } 12657 12658 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12659 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12660 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12661 switch (IntNo) { 12662 default: 12663 // Don't do anything for most intrinsics. 12664 break; 12665 12666 // Vector shifts: check for immediate versions and lower them. 12667 // Note: This is done during DAG combining instead of DAG legalizing because 12668 // the build_vectors for 64-bit vector element shift counts are generally 12669 // not legal, and it is hard to see their values after they get legalized to 12670 // loads from a constant pool. 12671 case Intrinsic::arm_neon_vshifts: 12672 case Intrinsic::arm_neon_vshiftu: 12673 case Intrinsic::arm_neon_vrshifts: 12674 case Intrinsic::arm_neon_vrshiftu: 12675 case Intrinsic::arm_neon_vrshiftn: 12676 case Intrinsic::arm_neon_vqshifts: 12677 case Intrinsic::arm_neon_vqshiftu: 12678 case Intrinsic::arm_neon_vqshiftsu: 12679 case Intrinsic::arm_neon_vqshiftns: 12680 case Intrinsic::arm_neon_vqshiftnu: 12681 case Intrinsic::arm_neon_vqshiftnsu: 12682 case Intrinsic::arm_neon_vqrshiftns: 12683 case Intrinsic::arm_neon_vqrshiftnu: 12684 case Intrinsic::arm_neon_vqrshiftnsu: { 12685 EVT VT = N->getOperand(1).getValueType(); 12686 int64_t Cnt; 12687 unsigned VShiftOpc = 0; 12688 12689 switch (IntNo) { 12690 case Intrinsic::arm_neon_vshifts: 12691 case Intrinsic::arm_neon_vshiftu: 12692 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12693 VShiftOpc = ARMISD::VSHLIMM; 12694 break; 12695 } 12696 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12697 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 12698 : ARMISD::VSHRuIMM); 12699 break; 12700 } 12701 return SDValue(); 12702 12703 case Intrinsic::arm_neon_vrshifts: 12704 case Intrinsic::arm_neon_vrshiftu: 12705 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12706 break; 12707 return SDValue(); 12708 12709 case Intrinsic::arm_neon_vqshifts: 12710 case Intrinsic::arm_neon_vqshiftu: 12711 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12712 break; 12713 return SDValue(); 12714 12715 case Intrinsic::arm_neon_vqshiftsu: 12716 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12717 break; 12718 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12719 12720 case Intrinsic::arm_neon_vrshiftn: 12721 case Intrinsic::arm_neon_vqshiftns: 12722 case Intrinsic::arm_neon_vqshiftnu: 12723 case Intrinsic::arm_neon_vqshiftnsu: 12724 case Intrinsic::arm_neon_vqrshiftns: 12725 case Intrinsic::arm_neon_vqrshiftnu: 12726 case Intrinsic::arm_neon_vqrshiftnsu: 12727 // Narrowing shifts require an immediate right shift. 12728 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12729 break; 12730 llvm_unreachable("invalid shift count for narrowing vector shift " 12731 "intrinsic"); 12732 12733 default: 12734 llvm_unreachable("unhandled vector shift"); 12735 } 12736 12737 switch (IntNo) { 12738 case Intrinsic::arm_neon_vshifts: 12739 case Intrinsic::arm_neon_vshiftu: 12740 // Opcode already set above. 12741 break; 12742 case Intrinsic::arm_neon_vrshifts: 12743 VShiftOpc = ARMISD::VRSHRsIMM; 12744 break; 12745 case Intrinsic::arm_neon_vrshiftu: 12746 VShiftOpc = ARMISD::VRSHRuIMM; 12747 break; 12748 case Intrinsic::arm_neon_vrshiftn: 12749 VShiftOpc = ARMISD::VRSHRNIMM; 12750 break; 12751 case Intrinsic::arm_neon_vqshifts: 12752 VShiftOpc = ARMISD::VQSHLsIMM; 12753 break; 12754 case Intrinsic::arm_neon_vqshiftu: 12755 VShiftOpc = ARMISD::VQSHLuIMM; 12756 break; 12757 case Intrinsic::arm_neon_vqshiftsu: 12758 VShiftOpc = ARMISD::VQSHLsuIMM; 12759 break; 12760 case Intrinsic::arm_neon_vqshiftns: 12761 VShiftOpc = ARMISD::VQSHRNsIMM; 12762 break; 12763 case Intrinsic::arm_neon_vqshiftnu: 12764 VShiftOpc = ARMISD::VQSHRNuIMM; 12765 break; 12766 case Intrinsic::arm_neon_vqshiftnsu: 12767 VShiftOpc = ARMISD::VQSHRNsuIMM; 12768 break; 12769 case Intrinsic::arm_neon_vqrshiftns: 12770 VShiftOpc = ARMISD::VQRSHRNsIMM; 12771 break; 12772 case Intrinsic::arm_neon_vqrshiftnu: 12773 VShiftOpc = ARMISD::VQRSHRNuIMM; 12774 break; 12775 case Intrinsic::arm_neon_vqrshiftnsu: 12776 VShiftOpc = ARMISD::VQRSHRNsuIMM; 12777 break; 12778 } 12779 12780 SDLoc dl(N); 12781 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12782 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12783 } 12784 12785 case Intrinsic::arm_neon_vshiftins: { 12786 EVT VT = N->getOperand(1).getValueType(); 12787 int64_t Cnt; 12788 unsigned VShiftOpc = 0; 12789 12790 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12791 VShiftOpc = ARMISD::VSLIIMM; 12792 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12793 VShiftOpc = ARMISD::VSRIIMM; 12794 else { 12795 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12796 } 12797 12798 SDLoc dl(N); 12799 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12800 N->getOperand(1), N->getOperand(2), 12801 DAG.getConstant(Cnt, dl, MVT::i32)); 12802 } 12803 12804 case Intrinsic::arm_neon_vqrshifts: 12805 case Intrinsic::arm_neon_vqrshiftu: 12806 // No immediate versions of these to check for. 12807 break; 12808 } 12809 12810 return SDValue(); 12811 } 12812 12813 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12814 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12815 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12816 /// vector element shift counts are generally not legal, and it is hard to see 12817 /// their values after they get legalized to loads from a constant pool. 12818 static SDValue PerformShiftCombine(SDNode *N, 12819 TargetLowering::DAGCombinerInfo &DCI, 12820 const ARMSubtarget *ST) { 12821 SelectionDAG &DAG = DCI.DAG; 12822 EVT VT = N->getValueType(0); 12823 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12824 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12825 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12826 SDValue N1 = N->getOperand(1); 12827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12828 SDValue N0 = N->getOperand(0); 12829 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12830 DAG.MaskedValueIsZero(N0.getOperand(0), 12831 APInt::getHighBitsSet(32, 16))) 12832 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12833 } 12834 } 12835 12836 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 12837 N->getOperand(0)->getOpcode() == ISD::AND && 12838 N->getOperand(0)->hasOneUse()) { 12839 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12840 return SDValue(); 12841 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 12842 // usually show up because instcombine prefers to canonicalize it to 12843 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 12844 // out of GEP lowering in some cases. 12845 SDValue N0 = N->getOperand(0); 12846 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12847 if (!ShiftAmtNode) 12848 return SDValue(); 12849 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 12850 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12851 if (!AndMaskNode) 12852 return SDValue(); 12853 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 12854 // Don't transform uxtb/uxth. 12855 if (AndMask == 255 || AndMask == 65535) 12856 return SDValue(); 12857 if (isMask_32(AndMask)) { 12858 uint32_t MaskedBits = countLeadingZeros(AndMask); 12859 if (MaskedBits > ShiftAmt) { 12860 SDLoc DL(N); 12861 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12862 DAG.getConstant(MaskedBits, DL, MVT::i32)); 12863 return DAG.getNode( 12864 ISD::SRL, DL, MVT::i32, SHL, 12865 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 12866 } 12867 } 12868 } 12869 12870 // Nothing to be done for scalar shifts. 12871 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12872 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12873 return SDValue(); 12874 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 12875 return SDValue(); 12876 12877 int64_t Cnt; 12878 12879 switch (N->getOpcode()) { 12880 default: llvm_unreachable("unexpected shift opcode"); 12881 12882 case ISD::SHL: 12883 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12884 SDLoc dl(N); 12885 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 12886 DAG.getConstant(Cnt, dl, MVT::i32)); 12887 } 12888 break; 12889 12890 case ISD::SRA: 12891 case ISD::SRL: 12892 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12893 unsigned VShiftOpc = 12894 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 12895 SDLoc dl(N); 12896 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12897 DAG.getConstant(Cnt, dl, MVT::i32)); 12898 } 12899 } 12900 return SDValue(); 12901 } 12902 12903 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12904 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12905 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12906 const ARMSubtarget *ST) { 12907 SDValue N0 = N->getOperand(0); 12908 12909 // Check for sign- and zero-extensions of vector extract operations of 8- 12910 // and 16-bit vector elements. NEON supports these directly. They are 12911 // handled during DAG combining because type legalization will promote them 12912 // to 32-bit types and it is messy to recognize the operations after that. 12913 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12914 SDValue Vec = N0.getOperand(0); 12915 SDValue Lane = N0.getOperand(1); 12916 EVT VT = N->getValueType(0); 12917 EVT EltVT = N0.getValueType(); 12918 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12919 12920 if (VT == MVT::i32 && 12921 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12922 TLI.isTypeLegal(Vec.getValueType()) && 12923 isa<ConstantSDNode>(Lane)) { 12924 12925 unsigned Opc = 0; 12926 switch (N->getOpcode()) { 12927 default: llvm_unreachable("unexpected opcode"); 12928 case ISD::SIGN_EXTEND: 12929 Opc = ARMISD::VGETLANEs; 12930 break; 12931 case ISD::ZERO_EXTEND: 12932 case ISD::ANY_EXTEND: 12933 Opc = ARMISD::VGETLANEu; 12934 break; 12935 } 12936 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12937 } 12938 } 12939 12940 return SDValue(); 12941 } 12942 12943 static const APInt *isPowerOf2Constant(SDValue V) { 12944 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12945 if (!C) 12946 return nullptr; 12947 const APInt *CV = &C->getAPIntValue(); 12948 return CV->isPowerOf2() ? CV : nullptr; 12949 } 12950 12951 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12952 // If we have a CMOV, OR and AND combination such as: 12953 // if (x & CN) 12954 // y |= CM; 12955 // 12956 // And: 12957 // * CN is a single bit; 12958 // * All bits covered by CM are known zero in y 12959 // 12960 // Then we can convert this into a sequence of BFI instructions. This will 12961 // always be a win if CM is a single bit, will always be no worse than the 12962 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12963 // three bits (due to the extra IT instruction). 12964 12965 SDValue Op0 = CMOV->getOperand(0); 12966 SDValue Op1 = CMOV->getOperand(1); 12967 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12968 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12969 SDValue CmpZ = CMOV->getOperand(4); 12970 12971 // The compare must be against zero. 12972 if (!isNullConstant(CmpZ->getOperand(1))) 12973 return SDValue(); 12974 12975 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12976 SDValue And = CmpZ->getOperand(0); 12977 if (And->getOpcode() != ISD::AND) 12978 return SDValue(); 12979 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12980 if (!AndC) 12981 return SDValue(); 12982 SDValue X = And->getOperand(0); 12983 12984 if (CC == ARMCC::EQ) { 12985 // We're performing an "equal to zero" compare. Swap the operands so we 12986 // canonicalize on a "not equal to zero" compare. 12987 std::swap(Op0, Op1); 12988 } else { 12989 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12990 } 12991 12992 if (Op1->getOpcode() != ISD::OR) 12993 return SDValue(); 12994 12995 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12996 if (!OrC) 12997 return SDValue(); 12998 SDValue Y = Op1->getOperand(0); 12999 13000 if (Op0 != Y) 13001 return SDValue(); 13002 13003 // Now, is it profitable to continue? 13004 APInt OrCI = OrC->getAPIntValue(); 13005 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 13006 if (OrCI.countPopulation() > Heuristic) 13007 return SDValue(); 13008 13009 // Lastly, can we determine that the bits defined by OrCI 13010 // are zero in Y? 13011 KnownBits Known = DAG.computeKnownBits(Y); 13012 if ((OrCI & Known.Zero) != OrCI) 13013 return SDValue(); 13014 13015 // OK, we can do the combine. 13016 SDValue V = Y; 13017 SDLoc dl(X); 13018 EVT VT = X.getValueType(); 13019 unsigned BitInX = AndC->logBase2(); 13020 13021 if (BitInX != 0) { 13022 // We must shift X first. 13023 X = DAG.getNode(ISD::SRL, dl, VT, X, 13024 DAG.getConstant(BitInX, dl, VT)); 13025 } 13026 13027 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 13028 BitInY < NumActiveBits; ++BitInY) { 13029 if (OrCI[BitInY] == 0) 13030 continue; 13031 APInt Mask(VT.getSizeInBits(), 0); 13032 Mask.setBit(BitInY); 13033 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 13034 // Confusingly, the operand is an *inverted* mask. 13035 DAG.getConstant(~Mask, dl, VT)); 13036 } 13037 13038 return V; 13039 } 13040 13041 // Given N, the value controlling the conditional branch, search for the loop 13042 // intrinsic, returning it, along with how the value is used. We need to handle 13043 // patterns such as the following: 13044 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 13045 // (brcond (setcc (loop.decrement), 0, eq), exit) 13046 // (brcond (setcc (loop.decrement), 0, ne), header) 13047 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 13048 bool &Negate) { 13049 switch (N->getOpcode()) { 13050 default: 13051 break; 13052 case ISD::XOR: { 13053 if (!isa<ConstantSDNode>(N.getOperand(1))) 13054 return SDValue(); 13055 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 13056 return SDValue(); 13057 Negate = !Negate; 13058 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 13059 } 13060 case ISD::SETCC: { 13061 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 13062 if (!Const) 13063 return SDValue(); 13064 if (Const->isNullValue()) 13065 Imm = 0; 13066 else if (Const->isOne()) 13067 Imm = 1; 13068 else 13069 return SDValue(); 13070 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 13071 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 13072 } 13073 case ISD::INTRINSIC_W_CHAIN: { 13074 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 13075 if (IntOp != Intrinsic::test_set_loop_iterations && 13076 IntOp != Intrinsic::loop_decrement_reg) 13077 return SDValue(); 13078 return N; 13079 } 13080 } 13081 return SDValue(); 13082 } 13083 13084 static SDValue PerformHWLoopCombine(SDNode *N, 13085 TargetLowering::DAGCombinerInfo &DCI, 13086 const ARMSubtarget *ST) { 13087 13088 // The hwloop intrinsics that we're interested are used for control-flow, 13089 // either for entering or exiting the loop: 13090 // - test.set.loop.iterations will test whether its operand is zero. If it 13091 // is zero, the proceeding branch should not enter the loop. 13092 // - loop.decrement.reg also tests whether its operand is zero. If it is 13093 // zero, the proceeding branch should not branch back to the beginning of 13094 // the loop. 13095 // So here, we need to check that how the brcond is using the result of each 13096 // of the intrinsics to ensure that we're branching to the right place at the 13097 // right time. 13098 13099 ISD::CondCode CC; 13100 SDValue Cond; 13101 int Imm = 1; 13102 bool Negate = false; 13103 SDValue Chain = N->getOperand(0); 13104 SDValue Dest; 13105 13106 if (N->getOpcode() == ISD::BRCOND) { 13107 CC = ISD::SETEQ; 13108 Cond = N->getOperand(1); 13109 Dest = N->getOperand(2); 13110 } else { 13111 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 13112 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13113 Cond = N->getOperand(2); 13114 Dest = N->getOperand(4); 13115 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 13116 if (!Const->isOne() && !Const->isNullValue()) 13117 return SDValue(); 13118 Imm = Const->getZExtValue(); 13119 } else 13120 return SDValue(); 13121 } 13122 13123 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 13124 if (!Int) 13125 return SDValue(); 13126 13127 if (Negate) 13128 CC = ISD::getSetCCInverse(CC, true); 13129 13130 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 13131 return (CC == ISD::SETEQ && Imm == 0) || 13132 (CC == ISD::SETNE && Imm == 1) || 13133 (CC == ISD::SETLT && Imm == 1) || 13134 (CC == ISD::SETULT && Imm == 1); 13135 }; 13136 13137 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 13138 return (CC == ISD::SETEQ && Imm == 1) || 13139 (CC == ISD::SETNE && Imm == 0) || 13140 (CC == ISD::SETGT && Imm == 0) || 13141 (CC == ISD::SETUGT && Imm == 0) || 13142 (CC == ISD::SETGE && Imm == 1) || 13143 (CC == ISD::SETUGE && Imm == 1); 13144 }; 13145 13146 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 13147 "unsupported condition"); 13148 13149 SDLoc dl(Int); 13150 SelectionDAG &DAG = DCI.DAG; 13151 SDValue Elements = Int.getOperand(2); 13152 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 13153 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 13154 && "expected single br user"); 13155 SDNode *Br = *N->use_begin(); 13156 SDValue OtherTarget = Br->getOperand(1); 13157 13158 // Update the unconditional branch to branch to the given Dest. 13159 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 13160 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 13161 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 13162 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 13163 }; 13164 13165 if (IntOp == Intrinsic::test_set_loop_iterations) { 13166 SDValue Res; 13167 // We expect this 'instruction' to branch when the counter is zero. 13168 if (IsTrueIfZero(CC, Imm)) { 13169 SDValue Ops[] = { Chain, Elements, Dest }; 13170 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 13171 } else { 13172 // The logic is the reverse of what we need for WLS, so find the other 13173 // basic block target: the target of the proceeding br. 13174 UpdateUncondBr(Br, Dest, DAG); 13175 13176 SDValue Ops[] = { Chain, Elements, OtherTarget }; 13177 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 13178 } 13179 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 13180 return Res; 13181 } else { 13182 SDValue Size = DAG.getTargetConstant( 13183 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 13184 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 13185 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 13186 DAG.getVTList(MVT::i32, MVT::Other), Args); 13187 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 13188 13189 // We expect this instruction to branch when the count is not zero. 13190 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 13191 13192 // Update the unconditional branch to target the loop preheader if we've 13193 // found the condition has been reversed. 13194 if (Target == OtherTarget) 13195 UpdateUncondBr(Br, Dest, DAG); 13196 13197 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13198 SDValue(LoopDec.getNode(), 1), Chain); 13199 13200 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 13201 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 13202 } 13203 return SDValue(); 13204 } 13205 13206 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 13207 SDValue 13208 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 13209 SDValue Cmp = N->getOperand(4); 13210 if (Cmp.getOpcode() != ARMISD::CMPZ) 13211 // Only looking at NE cases. 13212 return SDValue(); 13213 13214 EVT VT = N->getValueType(0); 13215 SDLoc dl(N); 13216 SDValue LHS = Cmp.getOperand(0); 13217 SDValue RHS = Cmp.getOperand(1); 13218 SDValue Chain = N->getOperand(0); 13219 SDValue BB = N->getOperand(1); 13220 SDValue ARMcc = N->getOperand(2); 13221 ARMCC::CondCodes CC = 13222 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13223 13224 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 13225 // -> (brcond Chain BB CC CPSR Cmp) 13226 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 13227 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 13228 LHS->getOperand(0)->hasOneUse()) { 13229 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 13230 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 13231 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13232 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13233 if ((LHS00C && LHS00C->getZExtValue() == 0) && 13234 (LHS01C && LHS01C->getZExtValue() == 1) && 13235 (LHS1C && LHS1C->getZExtValue() == 1) && 13236 (RHSC && RHSC->getZExtValue() == 0)) { 13237 return DAG.getNode( 13238 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 13239 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 13240 } 13241 } 13242 13243 return SDValue(); 13244 } 13245 13246 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 13247 SDValue 13248 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 13249 SDValue Cmp = N->getOperand(4); 13250 if (Cmp.getOpcode() != ARMISD::CMPZ) 13251 // Only looking at EQ and NE cases. 13252 return SDValue(); 13253 13254 EVT VT = N->getValueType(0); 13255 SDLoc dl(N); 13256 SDValue LHS = Cmp.getOperand(0); 13257 SDValue RHS = Cmp.getOperand(1); 13258 SDValue FalseVal = N->getOperand(0); 13259 SDValue TrueVal = N->getOperand(1); 13260 SDValue ARMcc = N->getOperand(2); 13261 ARMCC::CondCodes CC = 13262 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13263 13264 // BFI is only available on V6T2+. 13265 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 13266 SDValue R = PerformCMOVToBFICombine(N, DAG); 13267 if (R) 13268 return R; 13269 } 13270 13271 // Simplify 13272 // mov r1, r0 13273 // cmp r1, x 13274 // mov r0, y 13275 // moveq r0, x 13276 // to 13277 // cmp r0, x 13278 // movne r0, y 13279 // 13280 // mov r1, r0 13281 // cmp r1, x 13282 // mov r0, x 13283 // movne r0, y 13284 // to 13285 // cmp r0, x 13286 // movne r0, y 13287 /// FIXME: Turn this into a target neutral optimization? 13288 SDValue Res; 13289 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 13290 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 13291 N->getOperand(3), Cmp); 13292 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 13293 SDValue ARMcc; 13294 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 13295 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 13296 N->getOperand(3), NewCmp); 13297 } 13298 13299 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 13300 // -> (cmov F T CC CPSR Cmp) 13301 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 13302 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 13303 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13304 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13305 if ((LHS0C && LHS0C->getZExtValue() == 0) && 13306 (LHS1C && LHS1C->getZExtValue() == 1) && 13307 (RHSC && RHSC->getZExtValue() == 0)) { 13308 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 13309 LHS->getOperand(2), LHS->getOperand(3), 13310 LHS->getOperand(4)); 13311 } 13312 } 13313 13314 if (!VT.isInteger()) 13315 return SDValue(); 13316 13317 // Materialize a boolean comparison for integers so we can avoid branching. 13318 if (isNullConstant(FalseVal)) { 13319 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 13320 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 13321 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 13322 // right 5 bits will make that 32 be 1, otherwise it will be 0. 13323 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 13324 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13325 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 13326 DAG.getConstant(5, dl, MVT::i32)); 13327 } else { 13328 // CMOV 0, 1, ==, (CMPZ x, y) -> 13329 // (ADDCARRY (SUB x, y), t:0, t:1) 13330 // where t = (SUBCARRY 0, (SUB x, y), 0) 13331 // 13332 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 13333 // x != y. In other words, a carry C == 1 when x == y, C == 0 13334 // otherwise. 13335 // The final ADDCARRY computes 13336 // x - y + (0 - (x - y)) + C == C 13337 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13338 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13339 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 13340 // ISD::SUBCARRY returns a borrow but we want the carry here 13341 // actually. 13342 SDValue Carry = 13343 DAG.getNode(ISD::SUB, dl, MVT::i32, 13344 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 13345 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 13346 } 13347 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 13348 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 13349 // This seems pointless but will allow us to combine it further below. 13350 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13351 SDValue Sub = 13352 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13353 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13354 Sub.getValue(1), SDValue()); 13355 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 13356 N->getOperand(3), CPSRGlue.getValue(1)); 13357 FalseVal = Sub; 13358 } 13359 } else if (isNullConstant(TrueVal)) { 13360 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 13361 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 13362 // This seems pointless but will allow us to combine it further below 13363 // Note that we change == for != as this is the dual for the case above. 13364 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13365 SDValue Sub = 13366 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13367 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13368 Sub.getValue(1), SDValue()); 13369 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 13370 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 13371 N->getOperand(3), CPSRGlue.getValue(1)); 13372 FalseVal = Sub; 13373 } 13374 } 13375 13376 // On Thumb1, the DAG above may be further combined if z is a power of 2 13377 // (z == 2 ^ K). 13378 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 13379 // t1 = (USUBO (SUB x, y), 1) 13380 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 13381 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13382 // 13383 // This also handles the special case of comparing against zero; it's 13384 // essentially, the same pattern, except there's no SUBS: 13385 // CMOV x, z, !=, (CMPZ x, 0) -> 13386 // t1 = (USUBO x, 1) 13387 // t2 = (SUBCARRY x, t1:0, t1:1) 13388 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13389 const APInt *TrueConst; 13390 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 13391 ((FalseVal.getOpcode() == ARMISD::SUBS && 13392 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 13393 (FalseVal == LHS && isNullConstant(RHS))) && 13394 (TrueConst = isPowerOf2Constant(TrueVal))) { 13395 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13396 unsigned ShiftAmount = TrueConst->logBase2(); 13397 if (ShiftAmount) 13398 TrueVal = DAG.getConstant(1, dl, VT); 13399 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 13400 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 13401 13402 if (ShiftAmount) 13403 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 13404 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 13405 } 13406 13407 if (Res.getNode()) { 13408 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 13409 // Capture demanded bits information that would be otherwise lost. 13410 if (Known.Zero == 0xfffffffe) 13411 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13412 DAG.getValueType(MVT::i1)); 13413 else if (Known.Zero == 0xffffff00) 13414 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13415 DAG.getValueType(MVT::i8)); 13416 else if (Known.Zero == 0xffff0000) 13417 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13418 DAG.getValueType(MVT::i16)); 13419 } 13420 13421 return Res; 13422 } 13423 13424 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 13425 DAGCombinerInfo &DCI) const { 13426 switch (N->getOpcode()) { 13427 default: break; 13428 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 13429 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 13430 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 13431 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 13432 case ISD::SUB: return PerformSUBCombine(N, DCI); 13433 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 13434 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 13435 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 13436 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 13437 case ISD::BRCOND: 13438 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 13439 case ARMISD::ADDC: 13440 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 13441 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 13442 case ARMISD::BFI: return PerformBFICombine(N, DCI); 13443 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 13444 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 13445 case ISD::STORE: return PerformSTORECombine(N, DCI); 13446 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 13447 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 13448 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 13449 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 13450 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 13451 case ISD::FP_TO_SINT: 13452 case ISD::FP_TO_UINT: 13453 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 13454 case ISD::FDIV: 13455 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 13456 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 13457 case ISD::SHL: 13458 case ISD::SRA: 13459 case ISD::SRL: 13460 return PerformShiftCombine(N, DCI, Subtarget); 13461 case ISD::SIGN_EXTEND: 13462 case ISD::ZERO_EXTEND: 13463 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 13464 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 13465 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 13466 case ISD::LOAD: return PerformLOADCombine(N, DCI); 13467 case ARMISD::VLD1DUP: 13468 case ARMISD::VLD2DUP: 13469 case ARMISD::VLD3DUP: 13470 case ARMISD::VLD4DUP: 13471 return PerformVLDCombine(N, DCI); 13472 case ARMISD::BUILD_VECTOR: 13473 return PerformARMBUILD_VECTORCombine(N, DCI); 13474 case ARMISD::SMULWB: { 13475 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13476 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 13477 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 13478 return SDValue(); 13479 break; 13480 } 13481 case ARMISD::SMULWT: { 13482 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13483 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 13484 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 13485 return SDValue(); 13486 break; 13487 } 13488 case ARMISD::SMLALBB: { 13489 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13490 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 13491 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 13492 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 13493 return SDValue(); 13494 break; 13495 } 13496 case ARMISD::SMLALBT: { 13497 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 13498 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 13499 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 13500 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 13501 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 13502 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 13503 return SDValue(); 13504 break; 13505 } 13506 case ARMISD::SMLALTB: { 13507 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 13508 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 13509 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 13510 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 13511 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 13512 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 13513 return SDValue(); 13514 break; 13515 } 13516 case ARMISD::SMLALTT: { 13517 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13518 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 13519 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 13520 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 13521 return SDValue(); 13522 break; 13523 } 13524 case ISD::INTRINSIC_VOID: 13525 case ISD::INTRINSIC_W_CHAIN: 13526 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13527 case Intrinsic::arm_neon_vld1: 13528 case Intrinsic::arm_neon_vld1x2: 13529 case Intrinsic::arm_neon_vld1x3: 13530 case Intrinsic::arm_neon_vld1x4: 13531 case Intrinsic::arm_neon_vld2: 13532 case Intrinsic::arm_neon_vld3: 13533 case Intrinsic::arm_neon_vld4: 13534 case Intrinsic::arm_neon_vld2lane: 13535 case Intrinsic::arm_neon_vld3lane: 13536 case Intrinsic::arm_neon_vld4lane: 13537 case Intrinsic::arm_neon_vld2dup: 13538 case Intrinsic::arm_neon_vld3dup: 13539 case Intrinsic::arm_neon_vld4dup: 13540 case Intrinsic::arm_neon_vst1: 13541 case Intrinsic::arm_neon_vst1x2: 13542 case Intrinsic::arm_neon_vst1x3: 13543 case Intrinsic::arm_neon_vst1x4: 13544 case Intrinsic::arm_neon_vst2: 13545 case Intrinsic::arm_neon_vst3: 13546 case Intrinsic::arm_neon_vst4: 13547 case Intrinsic::arm_neon_vst2lane: 13548 case Intrinsic::arm_neon_vst3lane: 13549 case Intrinsic::arm_neon_vst4lane: 13550 return PerformVLDCombine(N, DCI); 13551 default: break; 13552 } 13553 break; 13554 } 13555 return SDValue(); 13556 } 13557 13558 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 13559 EVT VT) const { 13560 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 13561 } 13562 13563 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 13564 unsigned Alignment, 13565 MachineMemOperand::Flags, 13566 bool *Fast) const { 13567 // Depends what it gets converted into if the type is weird. 13568 if (!VT.isSimple()) 13569 return false; 13570 13571 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 13572 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 13573 auto Ty = VT.getSimpleVT().SimpleTy; 13574 13575 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 13576 // Unaligned access can use (for example) LRDB, LRDH, LDR 13577 if (AllowsUnaligned) { 13578 if (Fast) 13579 *Fast = Subtarget->hasV7Ops(); 13580 return true; 13581 } 13582 } 13583 13584 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 13585 // For any little-endian targets with neon, we can support unaligned ld/st 13586 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 13587 // A big-endian target may also explicitly support unaligned accesses 13588 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 13589 if (Fast) 13590 *Fast = true; 13591 return true; 13592 } 13593 } 13594 13595 if (!Subtarget->hasMVEIntegerOps()) 13596 return false; 13597 if (Ty != MVT::v16i8 && Ty != MVT::v8i16 && Ty != MVT::v8f16 && 13598 Ty != MVT::v4i32 && Ty != MVT::v4f32 && Ty != MVT::v2i64 && 13599 Ty != MVT::v2f64 && 13600 // These are for truncated stores 13601 Ty != MVT::v4i8 && Ty != MVT::v8i8 && Ty != MVT::v4i16) 13602 return false; 13603 13604 if (Subtarget->isLittle()) { 13605 // In little-endian MVE, the store instructions VSTRB.U8, 13606 // VSTRH.U16 and VSTRW.U32 all store the vector register in 13607 // exactly the same format, and differ only in the range of 13608 // their immediate offset field and the required alignment. 13609 // 13610 // In particular, VSTRB.U8 can store a vector at byte alignment. 13611 // So at this stage we can simply say that loads/stores of all 13612 // 128-bit wide vector types are permitted at any alignment, 13613 // because we know at least _one_ instruction can manage that. 13614 // 13615 // Later on we might find that some of those loads are better 13616 // generated as VLDRW.U32 if alignment permits, to take 13617 // advantage of the larger immediate range. But for the moment, 13618 // all that matters is that if we don't lower the load then 13619 // _some_ instruction can handle it. 13620 if (Fast) 13621 *Fast = true; 13622 return true; 13623 } else { 13624 // In big-endian MVE, those instructions aren't so similar 13625 // after all, because they reorder the bytes of the vector 13626 // differently. So this time we can only store a particular 13627 // kind of vector if its alignment is at least the element 13628 // type. And we can't store vectors of i64 or f64 at all 13629 // without having to do some postprocessing, because there's 13630 // no VSTRD.U64. 13631 if (Ty == MVT::v16i8 || 13632 ((Ty == MVT::v8i16 || Ty == MVT::v8f16) && Alignment >= 2) || 13633 ((Ty == MVT::v4i32 || Ty == MVT::v4f32) && Alignment >= 4)) { 13634 if (Fast) 13635 *Fast = true; 13636 return true; 13637 } 13638 } 13639 13640 return false; 13641 } 13642 13643 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 13644 unsigned AlignCheck) { 13645 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 13646 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 13647 } 13648 13649 EVT ARMTargetLowering::getOptimalMemOpType( 13650 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 13651 bool ZeroMemset, bool MemcpyStrSrc, 13652 const AttributeList &FuncAttributes) const { 13653 // See if we can use NEON instructions for this... 13654 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 13655 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 13656 bool Fast; 13657 if (Size >= 16 && 13658 (memOpAlign(SrcAlign, DstAlign, 16) || 13659 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 13660 MachineMemOperand::MONone, &Fast) && 13661 Fast))) { 13662 return MVT::v2f64; 13663 } else if (Size >= 8 && 13664 (memOpAlign(SrcAlign, DstAlign, 8) || 13665 (allowsMisalignedMemoryAccesses( 13666 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 13667 Fast))) { 13668 return MVT::f64; 13669 } 13670 } 13671 13672 // Let the target-independent logic figure it out. 13673 return MVT::Other; 13674 } 13675 13676 // 64-bit integers are split into their high and low parts and held in two 13677 // different registers, so the trunc is free since the low register can just 13678 // be used. 13679 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 13680 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 13681 return false; 13682 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 13683 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 13684 return (SrcBits == 64 && DestBits == 32); 13685 } 13686 13687 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 13688 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 13689 !DstVT.isInteger()) 13690 return false; 13691 unsigned SrcBits = SrcVT.getSizeInBits(); 13692 unsigned DestBits = DstVT.getSizeInBits(); 13693 return (SrcBits == 64 && DestBits == 32); 13694 } 13695 13696 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13697 if (Val.getOpcode() != ISD::LOAD) 13698 return false; 13699 13700 EVT VT1 = Val.getValueType(); 13701 if (!VT1.isSimple() || !VT1.isInteger() || 13702 !VT2.isSimple() || !VT2.isInteger()) 13703 return false; 13704 13705 switch (VT1.getSimpleVT().SimpleTy) { 13706 default: break; 13707 case MVT::i1: 13708 case MVT::i8: 13709 case MVT::i16: 13710 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 13711 return true; 13712 } 13713 13714 return false; 13715 } 13716 13717 bool ARMTargetLowering::isFNegFree(EVT VT) const { 13718 if (!VT.isSimple()) 13719 return false; 13720 13721 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 13722 // negate values directly (fneg is free). So, we don't want to let the DAG 13723 // combiner rewrite fneg into xors and some other instructions. For f16 and 13724 // FullFP16 argument passing, some bitcast nodes may be introduced, 13725 // triggering this DAG combine rewrite, so we are avoiding that with this. 13726 switch (VT.getSimpleVT().SimpleTy) { 13727 default: break; 13728 case MVT::f16: 13729 return Subtarget->hasFullFP16(); 13730 } 13731 13732 return false; 13733 } 13734 13735 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 13736 /// of the vector elements. 13737 static bool areExtractExts(Value *Ext1, Value *Ext2) { 13738 auto areExtDoubled = [](Instruction *Ext) { 13739 return Ext->getType()->getScalarSizeInBits() == 13740 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 13741 }; 13742 13743 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 13744 !match(Ext2, m_ZExtOrSExt(m_Value())) || 13745 !areExtDoubled(cast<Instruction>(Ext1)) || 13746 !areExtDoubled(cast<Instruction>(Ext2))) 13747 return false; 13748 13749 return true; 13750 } 13751 13752 /// Check if sinking \p I's operands to I's basic block is profitable, because 13753 /// the operands can be folded into a target instruction, e.g. 13754 /// sext/zext can be folded into vsubl. 13755 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 13756 SmallVectorImpl<Use *> &Ops) const { 13757 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy()) 13758 return false; 13759 13760 switch (I->getOpcode()) { 13761 case Instruction::Sub: 13762 case Instruction::Add: { 13763 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 13764 return false; 13765 Ops.push_back(&I->getOperandUse(0)); 13766 Ops.push_back(&I->getOperandUse(1)); 13767 return true; 13768 } 13769 default: 13770 return false; 13771 } 13772 return false; 13773 } 13774 13775 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 13776 EVT VT = ExtVal.getValueType(); 13777 13778 if (!isTypeLegal(VT)) 13779 return false; 13780 13781 // Don't create a loadext if we can fold the extension into a wide/long 13782 // instruction. 13783 // If there's more than one user instruction, the loadext is desirable no 13784 // matter what. There can be two uses by the same instruction. 13785 if (ExtVal->use_empty() || 13786 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 13787 return true; 13788 13789 SDNode *U = *ExtVal->use_begin(); 13790 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 13791 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 13792 return false; 13793 13794 return true; 13795 } 13796 13797 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 13798 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13799 return false; 13800 13801 if (!isTypeLegal(EVT::getEVT(Ty1))) 13802 return false; 13803 13804 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 13805 13806 // Assuming the caller doesn't have a zeroext or signext return parameter, 13807 // truncation all the way down to i1 is valid. 13808 return true; 13809 } 13810 13811 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 13812 const AddrMode &AM, Type *Ty, 13813 unsigned AS) const { 13814 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 13815 if (Subtarget->hasFPAO()) 13816 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 13817 return 0; 13818 } 13819 return -1; 13820 } 13821 13822 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 13823 if (V < 0) 13824 return false; 13825 13826 unsigned Scale = 1; 13827 switch (VT.getSimpleVT().SimpleTy) { 13828 case MVT::i1: 13829 case MVT::i8: 13830 // Scale == 1; 13831 break; 13832 case MVT::i16: 13833 // Scale == 2; 13834 Scale = 2; 13835 break; 13836 default: 13837 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 13838 // Scale == 4; 13839 Scale = 4; 13840 break; 13841 } 13842 13843 if ((V & (Scale - 1)) != 0) 13844 return false; 13845 return isUInt<5>(V / Scale); 13846 } 13847 13848 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 13849 const ARMSubtarget *Subtarget) { 13850 if (!VT.isInteger() && !VT.isFloatingPoint()) 13851 return false; 13852 if (VT.isVector() && Subtarget->hasNEON()) 13853 return false; 13854 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 13855 !Subtarget->hasMVEFloatOps()) 13856 return false; 13857 13858 bool IsNeg = false; 13859 if (V < 0) { 13860 IsNeg = true; 13861 V = -V; 13862 } 13863 13864 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U); 13865 13866 // MVE: size * imm7 13867 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 13868 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 13869 case MVT::i32: 13870 case MVT::f32: 13871 return isShiftedUInt<7,2>(V); 13872 case MVT::i16: 13873 case MVT::f16: 13874 return isShiftedUInt<7,1>(V); 13875 case MVT::i8: 13876 return isUInt<7>(V); 13877 default: 13878 return false; 13879 } 13880 } 13881 13882 // half VLDR: 2 * imm8 13883 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 13884 return isShiftedUInt<8, 1>(V); 13885 // VLDR and LDRD: 4 * imm8 13886 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 13887 return isShiftedUInt<8, 2>(V); 13888 13889 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 13890 // + imm12 or - imm8 13891 if (IsNeg) 13892 return isUInt<8>(V); 13893 return isUInt<12>(V); 13894 } 13895 13896 return false; 13897 } 13898 13899 /// isLegalAddressImmediate - Return true if the integer value can be used 13900 /// as the offset of the target addressing mode for load / store of the 13901 /// given type. 13902 static bool isLegalAddressImmediate(int64_t V, EVT VT, 13903 const ARMSubtarget *Subtarget) { 13904 if (V == 0) 13905 return true; 13906 13907 if (!VT.isSimple()) 13908 return false; 13909 13910 if (Subtarget->isThumb1Only()) 13911 return isLegalT1AddressImmediate(V, VT); 13912 else if (Subtarget->isThumb2()) 13913 return isLegalT2AddressImmediate(V, VT, Subtarget); 13914 13915 // ARM mode. 13916 if (V < 0) 13917 V = - V; 13918 switch (VT.getSimpleVT().SimpleTy) { 13919 default: return false; 13920 case MVT::i1: 13921 case MVT::i8: 13922 case MVT::i32: 13923 // +- imm12 13924 return isUInt<12>(V); 13925 case MVT::i16: 13926 // +- imm8 13927 return isUInt<8>(V); 13928 case MVT::f32: 13929 case MVT::f64: 13930 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 13931 return false; 13932 return isShiftedUInt<8, 2>(V); 13933 } 13934 } 13935 13936 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 13937 EVT VT) const { 13938 int Scale = AM.Scale; 13939 if (Scale < 0) 13940 return false; 13941 13942 switch (VT.getSimpleVT().SimpleTy) { 13943 default: return false; 13944 case MVT::i1: 13945 case MVT::i8: 13946 case MVT::i16: 13947 case MVT::i32: 13948 if (Scale == 1) 13949 return true; 13950 // r + r << imm 13951 Scale = Scale & ~1; 13952 return Scale == 2 || Scale == 4 || Scale == 8; 13953 case MVT::i64: 13954 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 13955 // version in Thumb mode. 13956 // r + r 13957 if (Scale == 1) 13958 return true; 13959 // r * 2 (this can be lowered to r + r). 13960 if (!AM.HasBaseReg && Scale == 2) 13961 return true; 13962 return false; 13963 case MVT::isVoid: 13964 // Note, we allow "void" uses (basically, uses that aren't loads or 13965 // stores), because arm allows folding a scale into many arithmetic 13966 // operations. This should be made more precise and revisited later. 13967 13968 // Allow r << imm, but the imm has to be a multiple of two. 13969 if (Scale & 1) return false; 13970 return isPowerOf2_32(Scale); 13971 } 13972 } 13973 13974 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 13975 EVT VT) const { 13976 const int Scale = AM.Scale; 13977 13978 // Negative scales are not supported in Thumb1. 13979 if (Scale < 0) 13980 return false; 13981 13982 // Thumb1 addressing modes do not support register scaling excepting the 13983 // following cases: 13984 // 1. Scale == 1 means no scaling. 13985 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 13986 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 13987 } 13988 13989 /// isLegalAddressingMode - Return true if the addressing mode represented 13990 /// by AM is legal for this target, for a load/store of the specified type. 13991 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13992 const AddrMode &AM, Type *Ty, 13993 unsigned AS, Instruction *I) const { 13994 EVT VT = getValueType(DL, Ty, true); 13995 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 13996 return false; 13997 13998 // Can never fold addr of global into load/store. 13999 if (AM.BaseGV) 14000 return false; 14001 14002 switch (AM.Scale) { 14003 case 0: // no scale reg, must be "r+i" or "r", or "i". 14004 break; 14005 default: 14006 // ARM doesn't support any R+R*scale+imm addr modes. 14007 if (AM.BaseOffs) 14008 return false; 14009 14010 if (!VT.isSimple()) 14011 return false; 14012 14013 if (Subtarget->isThumb1Only()) 14014 return isLegalT1ScaledAddressingMode(AM, VT); 14015 14016 if (Subtarget->isThumb2()) 14017 return isLegalT2ScaledAddressingMode(AM, VT); 14018 14019 int Scale = AM.Scale; 14020 switch (VT.getSimpleVT().SimpleTy) { 14021 default: return false; 14022 case MVT::i1: 14023 case MVT::i8: 14024 case MVT::i32: 14025 if (Scale < 0) Scale = -Scale; 14026 if (Scale == 1) 14027 return true; 14028 // r + r << imm 14029 return isPowerOf2_32(Scale & ~1); 14030 case MVT::i16: 14031 case MVT::i64: 14032 // r +/- r 14033 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 14034 return true; 14035 // r * 2 (this can be lowered to r + r). 14036 if (!AM.HasBaseReg && Scale == 2) 14037 return true; 14038 return false; 14039 14040 case MVT::isVoid: 14041 // Note, we allow "void" uses (basically, uses that aren't loads or 14042 // stores), because arm allows folding a scale into many arithmetic 14043 // operations. This should be made more precise and revisited later. 14044 14045 // Allow r << imm, but the imm has to be a multiple of two. 14046 if (Scale & 1) return false; 14047 return isPowerOf2_32(Scale); 14048 } 14049 } 14050 return true; 14051 } 14052 14053 /// isLegalICmpImmediate - Return true if the specified immediate is legal 14054 /// icmp immediate, that is the target has icmp instructions which can compare 14055 /// a register against the immediate without having to materialize the 14056 /// immediate into a register. 14057 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14058 // Thumb2 and ARM modes can use cmn for negative immediates. 14059 if (!Subtarget->isThumb()) 14060 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 14061 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 14062 if (Subtarget->isThumb2()) 14063 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 14064 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 14065 // Thumb1 doesn't have cmn, and only 8-bit immediates. 14066 return Imm >= 0 && Imm <= 255; 14067 } 14068 14069 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 14070 /// *or sub* immediate, that is the target has add or sub instructions which can 14071 /// add a register with the immediate without having to materialize the 14072 /// immediate into a register. 14073 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14074 // Same encoding for add/sub, just flip the sign. 14075 int64_t AbsImm = std::abs(Imm); 14076 if (!Subtarget->isThumb()) 14077 return ARM_AM::getSOImmVal(AbsImm) != -1; 14078 if (Subtarget->isThumb2()) 14079 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 14080 // Thumb1 only has 8-bit unsigned immediate. 14081 return AbsImm >= 0 && AbsImm <= 255; 14082 } 14083 14084 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 14085 bool isSEXTLoad, SDValue &Base, 14086 SDValue &Offset, bool &isInc, 14087 SelectionDAG &DAG) { 14088 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14089 return false; 14090 14091 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 14092 // AddressingMode 3 14093 Base = Ptr->getOperand(0); 14094 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14095 int RHSC = (int)RHS->getZExtValue(); 14096 if (RHSC < 0 && RHSC > -256) { 14097 assert(Ptr->getOpcode() == ISD::ADD); 14098 isInc = false; 14099 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14100 return true; 14101 } 14102 } 14103 isInc = (Ptr->getOpcode() == ISD::ADD); 14104 Offset = Ptr->getOperand(1); 14105 return true; 14106 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 14107 // AddressingMode 2 14108 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14109 int RHSC = (int)RHS->getZExtValue(); 14110 if (RHSC < 0 && RHSC > -0x1000) { 14111 assert(Ptr->getOpcode() == ISD::ADD); 14112 isInc = false; 14113 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14114 Base = Ptr->getOperand(0); 14115 return true; 14116 } 14117 } 14118 14119 if (Ptr->getOpcode() == ISD::ADD) { 14120 isInc = true; 14121 ARM_AM::ShiftOpc ShOpcVal= 14122 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 14123 if (ShOpcVal != ARM_AM::no_shift) { 14124 Base = Ptr->getOperand(1); 14125 Offset = Ptr->getOperand(0); 14126 } else { 14127 Base = Ptr->getOperand(0); 14128 Offset = Ptr->getOperand(1); 14129 } 14130 return true; 14131 } 14132 14133 isInc = (Ptr->getOpcode() == ISD::ADD); 14134 Base = Ptr->getOperand(0); 14135 Offset = Ptr->getOperand(1); 14136 return true; 14137 } 14138 14139 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 14140 return false; 14141 } 14142 14143 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 14144 bool isSEXTLoad, SDValue &Base, 14145 SDValue &Offset, bool &isInc, 14146 SelectionDAG &DAG) { 14147 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14148 return false; 14149 14150 Base = Ptr->getOperand(0); 14151 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14152 int RHSC = (int)RHS->getZExtValue(); 14153 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 14154 assert(Ptr->getOpcode() == ISD::ADD); 14155 isInc = false; 14156 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14157 return true; 14158 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 14159 isInc = Ptr->getOpcode() == ISD::ADD; 14160 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14161 return true; 14162 } 14163 } 14164 14165 return false; 14166 } 14167 14168 /// getPreIndexedAddressParts - returns true by value, base pointer and 14169 /// offset pointer and addressing mode by reference if the node's address 14170 /// can be legally represented as pre-indexed load / store address. 14171 bool 14172 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 14173 SDValue &Offset, 14174 ISD::MemIndexedMode &AM, 14175 SelectionDAG &DAG) const { 14176 if (Subtarget->isThumb1Only()) 14177 return false; 14178 14179 EVT VT; 14180 SDValue Ptr; 14181 bool isSEXTLoad = false; 14182 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 14183 Ptr = LD->getBasePtr(); 14184 VT = LD->getMemoryVT(); 14185 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 14186 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 14187 Ptr = ST->getBasePtr(); 14188 VT = ST->getMemoryVT(); 14189 } else 14190 return false; 14191 14192 bool isInc; 14193 bool isLegal = false; 14194 if (Subtarget->isThumb2()) 14195 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 14196 Offset, isInc, DAG); 14197 else 14198 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 14199 Offset, isInc, DAG); 14200 if (!isLegal) 14201 return false; 14202 14203 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 14204 return true; 14205 } 14206 14207 /// getPostIndexedAddressParts - returns true by value, base pointer and 14208 /// offset pointer and addressing mode by reference if this node can be 14209 /// combined with a load / store to form a post-indexed load / store. 14210 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 14211 SDValue &Base, 14212 SDValue &Offset, 14213 ISD::MemIndexedMode &AM, 14214 SelectionDAG &DAG) const { 14215 EVT VT; 14216 SDValue Ptr; 14217 bool isSEXTLoad = false, isNonExt; 14218 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 14219 VT = LD->getMemoryVT(); 14220 Ptr = LD->getBasePtr(); 14221 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 14222 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 14223 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 14224 VT = ST->getMemoryVT(); 14225 Ptr = ST->getBasePtr(); 14226 isNonExt = !ST->isTruncatingStore(); 14227 } else 14228 return false; 14229 14230 if (Subtarget->isThumb1Only()) { 14231 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 14232 // must be non-extending/truncating, i32, with an offset of 4. 14233 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 14234 if (Op->getOpcode() != ISD::ADD || !isNonExt) 14235 return false; 14236 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 14237 if (!RHS || RHS->getZExtValue() != 4) 14238 return false; 14239 14240 Offset = Op->getOperand(1); 14241 Base = Op->getOperand(0); 14242 AM = ISD::POST_INC; 14243 return true; 14244 } 14245 14246 bool isInc; 14247 bool isLegal = false; 14248 if (Subtarget->isThumb2()) 14249 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14250 isInc, DAG); 14251 else 14252 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14253 isInc, DAG); 14254 if (!isLegal) 14255 return false; 14256 14257 if (Ptr != Base) { 14258 // Swap base ptr and offset to catch more post-index load / store when 14259 // it's legal. In Thumb2 mode, offset must be an immediate. 14260 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 14261 !Subtarget->isThumb2()) 14262 std::swap(Base, Offset); 14263 14264 // Post-indexed load / store update the base pointer. 14265 if (Ptr != Base) 14266 return false; 14267 } 14268 14269 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 14270 return true; 14271 } 14272 14273 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14274 KnownBits &Known, 14275 const APInt &DemandedElts, 14276 const SelectionDAG &DAG, 14277 unsigned Depth) const { 14278 unsigned BitWidth = Known.getBitWidth(); 14279 Known.resetAll(); 14280 switch (Op.getOpcode()) { 14281 default: break; 14282 case ARMISD::ADDC: 14283 case ARMISD::ADDE: 14284 case ARMISD::SUBC: 14285 case ARMISD::SUBE: 14286 // Special cases when we convert a carry to a boolean. 14287 if (Op.getResNo() == 0) { 14288 SDValue LHS = Op.getOperand(0); 14289 SDValue RHS = Op.getOperand(1); 14290 // (ADDE 0, 0, C) will give us a single bit. 14291 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 14292 isNullConstant(RHS)) { 14293 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 14294 return; 14295 } 14296 } 14297 break; 14298 case ARMISD::CMOV: { 14299 // Bits are known zero/one if known on the LHS and RHS. 14300 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 14301 if (Known.isUnknown()) 14302 return; 14303 14304 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 14305 Known.Zero &= KnownRHS.Zero; 14306 Known.One &= KnownRHS.One; 14307 return; 14308 } 14309 case ISD::INTRINSIC_W_CHAIN: { 14310 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 14311 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 14312 switch (IntID) { 14313 default: return; 14314 case Intrinsic::arm_ldaex: 14315 case Intrinsic::arm_ldrex: { 14316 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 14317 unsigned MemBits = VT.getScalarSizeInBits(); 14318 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 14319 return; 14320 } 14321 } 14322 } 14323 case ARMISD::BFI: { 14324 // Conservatively, we can recurse down the first operand 14325 // and just mask out all affected bits. 14326 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 14327 14328 // The operand to BFI is already a mask suitable for removing the bits it 14329 // sets. 14330 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 14331 const APInt &Mask = CI->getAPIntValue(); 14332 Known.Zero &= Mask; 14333 Known.One &= Mask; 14334 return; 14335 } 14336 case ARMISD::VGETLANEs: 14337 case ARMISD::VGETLANEu: { 14338 const SDValue &SrcSV = Op.getOperand(0); 14339 EVT VecVT = SrcSV.getValueType(); 14340 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 14341 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 14342 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 14343 assert(Pos->getAPIntValue().ult(NumSrcElts) && 14344 "VGETLANE index out of bounds"); 14345 unsigned Idx = Pos->getZExtValue(); 14346 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 14347 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 14348 14349 EVT VT = Op.getValueType(); 14350 const unsigned DstSz = VT.getScalarSizeInBits(); 14351 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 14352 (void)SrcSz; 14353 assert(SrcSz == Known.getBitWidth()); 14354 assert(DstSz > SrcSz); 14355 if (Op.getOpcode() == ARMISD::VGETLANEs) 14356 Known = Known.sext(DstSz); 14357 else { 14358 Known = Known.zext(DstSz, true /* extended bits are known zero */); 14359 } 14360 assert(DstSz == Known.getBitWidth()); 14361 break; 14362 } 14363 } 14364 } 14365 14366 bool 14367 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 14368 const APInt &DemandedAPInt, 14369 TargetLoweringOpt &TLO) const { 14370 // Delay optimization, so we don't have to deal with illegal types, or block 14371 // optimizations. 14372 if (!TLO.LegalOps) 14373 return false; 14374 14375 // Only optimize AND for now. 14376 if (Op.getOpcode() != ISD::AND) 14377 return false; 14378 14379 EVT VT = Op.getValueType(); 14380 14381 // Ignore vectors. 14382 if (VT.isVector()) 14383 return false; 14384 14385 assert(VT == MVT::i32 && "Unexpected integer type"); 14386 14387 // Make sure the RHS really is a constant. 14388 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14389 if (!C) 14390 return false; 14391 14392 unsigned Mask = C->getZExtValue(); 14393 14394 unsigned Demanded = DemandedAPInt.getZExtValue(); 14395 unsigned ShrunkMask = Mask & Demanded; 14396 unsigned ExpandedMask = Mask | ~Demanded; 14397 14398 // If the mask is all zeros, let the target-independent code replace the 14399 // result with zero. 14400 if (ShrunkMask == 0) 14401 return false; 14402 14403 // If the mask is all ones, erase the AND. (Currently, the target-independent 14404 // code won't do this, so we have to do it explicitly to avoid an infinite 14405 // loop in obscure cases.) 14406 if (ExpandedMask == ~0U) 14407 return TLO.CombineTo(Op, Op.getOperand(0)); 14408 14409 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 14410 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 14411 }; 14412 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 14413 if (NewMask == Mask) 14414 return true; 14415 SDLoc DL(Op); 14416 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 14417 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 14418 return TLO.CombineTo(Op, NewOp); 14419 }; 14420 14421 // Prefer uxtb mask. 14422 if (IsLegalMask(0xFF)) 14423 return UseMask(0xFF); 14424 14425 // Prefer uxth mask. 14426 if (IsLegalMask(0xFFFF)) 14427 return UseMask(0xFFFF); 14428 14429 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 14430 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 14431 if (ShrunkMask < 256) 14432 return UseMask(ShrunkMask); 14433 14434 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 14435 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 14436 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 14437 return UseMask(ExpandedMask); 14438 14439 // Potential improvements: 14440 // 14441 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 14442 // We could try to prefer Thumb1 immediates which can be lowered to a 14443 // two-instruction sequence. 14444 // We could try to recognize more legal ARM/Thumb2 immediates here. 14445 14446 return false; 14447 } 14448 14449 14450 //===----------------------------------------------------------------------===// 14451 // ARM Inline Assembly Support 14452 //===----------------------------------------------------------------------===// 14453 14454 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 14455 // Looking for "rev" which is V6+. 14456 if (!Subtarget->hasV6Ops()) 14457 return false; 14458 14459 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 14460 std::string AsmStr = IA->getAsmString(); 14461 SmallVector<StringRef, 4> AsmPieces; 14462 SplitString(AsmStr, AsmPieces, ";\n"); 14463 14464 switch (AsmPieces.size()) { 14465 default: return false; 14466 case 1: 14467 AsmStr = AsmPieces[0]; 14468 AsmPieces.clear(); 14469 SplitString(AsmStr, AsmPieces, " \t,"); 14470 14471 // rev $0, $1 14472 if (AsmPieces.size() == 3 && 14473 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 14474 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 14475 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14476 if (Ty && Ty->getBitWidth() == 32) 14477 return IntrinsicLowering::LowerToByteSwap(CI); 14478 } 14479 break; 14480 } 14481 14482 return false; 14483 } 14484 14485 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 14486 // At this point, we have to lower this constraint to something else, so we 14487 // lower it to an "r" or "w". However, by doing this we will force the result 14488 // to be in register, while the X constraint is much more permissive. 14489 // 14490 // Although we are correct (we are free to emit anything, without 14491 // constraints), we might break use cases that would expect us to be more 14492 // efficient and emit something else. 14493 if (!Subtarget->hasVFP2Base()) 14494 return "r"; 14495 if (ConstraintVT.isFloatingPoint()) 14496 return "w"; 14497 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 14498 (ConstraintVT.getSizeInBits() == 64 || 14499 ConstraintVT.getSizeInBits() == 128)) 14500 return "w"; 14501 14502 return "r"; 14503 } 14504 14505 /// getConstraintType - Given a constraint letter, return the type of 14506 /// constraint it is for this target. 14507 ARMTargetLowering::ConstraintType 14508 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 14509 if (Constraint.size() == 1) { 14510 switch (Constraint[0]) { 14511 default: break; 14512 case 'l': return C_RegisterClass; 14513 case 'w': return C_RegisterClass; 14514 case 'h': return C_RegisterClass; 14515 case 'x': return C_RegisterClass; 14516 case 't': return C_RegisterClass; 14517 case 'j': return C_Other; // Constant for movw. 14518 // An address with a single base register. Due to the way we 14519 // currently handle addresses it is the same as an 'r' memory constraint. 14520 case 'Q': return C_Memory; 14521 } 14522 } else if (Constraint.size() == 2) { 14523 switch (Constraint[0]) { 14524 default: break; 14525 case 'T': return C_RegisterClass; 14526 // All 'U+' constraints are addresses. 14527 case 'U': return C_Memory; 14528 } 14529 } 14530 return TargetLowering::getConstraintType(Constraint); 14531 } 14532 14533 /// Examine constraint type and operand type and determine a weight value. 14534 /// This object must already have been set up with the operand type 14535 /// and the current alternative constraint selected. 14536 TargetLowering::ConstraintWeight 14537 ARMTargetLowering::getSingleConstraintMatchWeight( 14538 AsmOperandInfo &info, const char *constraint) const { 14539 ConstraintWeight weight = CW_Invalid; 14540 Value *CallOperandVal = info.CallOperandVal; 14541 // If we don't have a value, we can't do a match, 14542 // but allow it at the lowest weight. 14543 if (!CallOperandVal) 14544 return CW_Default; 14545 Type *type = CallOperandVal->getType(); 14546 // Look at the constraint type. 14547 switch (*constraint) { 14548 default: 14549 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14550 break; 14551 case 'l': 14552 if (type->isIntegerTy()) { 14553 if (Subtarget->isThumb()) 14554 weight = CW_SpecificReg; 14555 else 14556 weight = CW_Register; 14557 } 14558 break; 14559 case 'w': 14560 if (type->isFloatingPointTy()) 14561 weight = CW_Register; 14562 break; 14563 } 14564 return weight; 14565 } 14566 14567 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 14568 14569 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 14570 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 14571 switch (Constraint.size()) { 14572 case 1: 14573 // GCC ARM Constraint Letters 14574 switch (Constraint[0]) { 14575 case 'l': // Low regs or general regs. 14576 if (Subtarget->isThumb()) 14577 return RCPair(0U, &ARM::tGPRRegClass); 14578 return RCPair(0U, &ARM::GPRRegClass); 14579 case 'h': // High regs or no regs. 14580 if (Subtarget->isThumb()) 14581 return RCPair(0U, &ARM::hGPRRegClass); 14582 break; 14583 case 'r': 14584 if (Subtarget->isThumb1Only()) 14585 return RCPair(0U, &ARM::tGPRRegClass); 14586 return RCPair(0U, &ARM::GPRRegClass); 14587 case 'w': 14588 if (VT == MVT::Other) 14589 break; 14590 if (VT == MVT::f32) 14591 return RCPair(0U, &ARM::SPRRegClass); 14592 if (VT.getSizeInBits() == 64) 14593 return RCPair(0U, &ARM::DPRRegClass); 14594 if (VT.getSizeInBits() == 128) 14595 return RCPair(0U, &ARM::QPRRegClass); 14596 break; 14597 case 'x': 14598 if (VT == MVT::Other) 14599 break; 14600 if (VT == MVT::f32) 14601 return RCPair(0U, &ARM::SPR_8RegClass); 14602 if (VT.getSizeInBits() == 64) 14603 return RCPair(0U, &ARM::DPR_8RegClass); 14604 if (VT.getSizeInBits() == 128) 14605 return RCPair(0U, &ARM::QPR_8RegClass); 14606 break; 14607 case 't': 14608 if (VT == MVT::Other) 14609 break; 14610 if (VT == MVT::f32 || VT == MVT::i32) 14611 return RCPair(0U, &ARM::SPRRegClass); 14612 if (VT.getSizeInBits() == 64) 14613 return RCPair(0U, &ARM::DPR_VFP2RegClass); 14614 if (VT.getSizeInBits() == 128) 14615 return RCPair(0U, &ARM::QPR_VFP2RegClass); 14616 break; 14617 } 14618 break; 14619 14620 case 2: 14621 if (Constraint[0] == 'T') { 14622 switch (Constraint[1]) { 14623 default: 14624 break; 14625 case 'e': 14626 return RCPair(0U, &ARM::tGPREvenRegClass); 14627 case 'o': 14628 return RCPair(0U, &ARM::tGPROddRegClass); 14629 } 14630 } 14631 break; 14632 14633 default: 14634 break; 14635 } 14636 14637 if (StringRef("{cc}").equals_lower(Constraint)) 14638 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 14639 14640 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14641 } 14642 14643 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14644 /// vector. If it is invalid, don't add anything to Ops. 14645 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14646 std::string &Constraint, 14647 std::vector<SDValue>&Ops, 14648 SelectionDAG &DAG) const { 14649 SDValue Result; 14650 14651 // Currently only support length 1 constraints. 14652 if (Constraint.length() != 1) return; 14653 14654 char ConstraintLetter = Constraint[0]; 14655 switch (ConstraintLetter) { 14656 default: break; 14657 case 'j': 14658 case 'I': case 'J': case 'K': case 'L': 14659 case 'M': case 'N': case 'O': 14660 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 14661 if (!C) 14662 return; 14663 14664 int64_t CVal64 = C->getSExtValue(); 14665 int CVal = (int) CVal64; 14666 // None of these constraints allow values larger than 32 bits. Check 14667 // that the value fits in an int. 14668 if (CVal != CVal64) 14669 return; 14670 14671 switch (ConstraintLetter) { 14672 case 'j': 14673 // Constant suitable for movw, must be between 0 and 14674 // 65535. 14675 if (Subtarget->hasV6T2Ops()) 14676 if (CVal >= 0 && CVal <= 65535) 14677 break; 14678 return; 14679 case 'I': 14680 if (Subtarget->isThumb1Only()) { 14681 // This must be a constant between 0 and 255, for ADD 14682 // immediates. 14683 if (CVal >= 0 && CVal <= 255) 14684 break; 14685 } else if (Subtarget->isThumb2()) { 14686 // A constant that can be used as an immediate value in a 14687 // data-processing instruction. 14688 if (ARM_AM::getT2SOImmVal(CVal) != -1) 14689 break; 14690 } else { 14691 // A constant that can be used as an immediate value in a 14692 // data-processing instruction. 14693 if (ARM_AM::getSOImmVal(CVal) != -1) 14694 break; 14695 } 14696 return; 14697 14698 case 'J': 14699 if (Subtarget->isThumb1Only()) { 14700 // This must be a constant between -255 and -1, for negated ADD 14701 // immediates. This can be used in GCC with an "n" modifier that 14702 // prints the negated value, for use with SUB instructions. It is 14703 // not useful otherwise but is implemented for compatibility. 14704 if (CVal >= -255 && CVal <= -1) 14705 break; 14706 } else { 14707 // This must be a constant between -4095 and 4095. It is not clear 14708 // what this constraint is intended for. Implemented for 14709 // compatibility with GCC. 14710 if (CVal >= -4095 && CVal <= 4095) 14711 break; 14712 } 14713 return; 14714 14715 case 'K': 14716 if (Subtarget->isThumb1Only()) { 14717 // A 32-bit value where only one byte has a nonzero value. Exclude 14718 // zero to match GCC. This constraint is used by GCC internally for 14719 // constants that can be loaded with a move/shift combination. 14720 // It is not useful otherwise but is implemented for compatibility. 14721 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 14722 break; 14723 } else if (Subtarget->isThumb2()) { 14724 // A constant whose bitwise inverse can be used as an immediate 14725 // value in a data-processing instruction. This can be used in GCC 14726 // with a "B" modifier that prints the inverted value, for use with 14727 // BIC and MVN instructions. It is not useful otherwise but is 14728 // implemented for compatibility. 14729 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 14730 break; 14731 } else { 14732 // A constant whose bitwise inverse can be used as an immediate 14733 // value in a data-processing instruction. This can be used in GCC 14734 // with a "B" modifier that prints the inverted value, for use with 14735 // BIC and MVN instructions. It is not useful otherwise but is 14736 // implemented for compatibility. 14737 if (ARM_AM::getSOImmVal(~CVal) != -1) 14738 break; 14739 } 14740 return; 14741 14742 case 'L': 14743 if (Subtarget->isThumb1Only()) { 14744 // This must be a constant between -7 and 7, 14745 // for 3-operand ADD/SUB immediate instructions. 14746 if (CVal >= -7 && CVal < 7) 14747 break; 14748 } else if (Subtarget->isThumb2()) { 14749 // A constant whose negation can be used as an immediate value in a 14750 // data-processing instruction. This can be used in GCC with an "n" 14751 // modifier that prints the negated value, for use with SUB 14752 // instructions. It is not useful otherwise but is implemented for 14753 // compatibility. 14754 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 14755 break; 14756 } else { 14757 // A constant whose negation can be used as an immediate value in a 14758 // data-processing instruction. This can be used in GCC with an "n" 14759 // modifier that prints the negated value, for use with SUB 14760 // instructions. It is not useful otherwise but is implemented for 14761 // compatibility. 14762 if (ARM_AM::getSOImmVal(-CVal) != -1) 14763 break; 14764 } 14765 return; 14766 14767 case 'M': 14768 if (Subtarget->isThumb1Only()) { 14769 // This must be a multiple of 4 between 0 and 1020, for 14770 // ADD sp + immediate. 14771 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 14772 break; 14773 } else { 14774 // A power of two or a constant between 0 and 32. This is used in 14775 // GCC for the shift amount on shifted register operands, but it is 14776 // useful in general for any shift amounts. 14777 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 14778 break; 14779 } 14780 return; 14781 14782 case 'N': 14783 if (Subtarget->isThumb()) { // FIXME thumb2 14784 // This must be a constant between 0 and 31, for shift amounts. 14785 if (CVal >= 0 && CVal <= 31) 14786 break; 14787 } 14788 return; 14789 14790 case 'O': 14791 if (Subtarget->isThumb()) { // FIXME thumb2 14792 // This must be a multiple of 4 between -508 and 508, for 14793 // ADD/SUB sp = sp + immediate. 14794 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 14795 break; 14796 } 14797 return; 14798 } 14799 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 14800 break; 14801 } 14802 14803 if (Result.getNode()) { 14804 Ops.push_back(Result); 14805 return; 14806 } 14807 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14808 } 14809 14810 static RTLIB::Libcall getDivRemLibcall( 14811 const SDNode *N, MVT::SimpleValueType SVT) { 14812 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14813 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14814 "Unhandled Opcode in getDivRemLibcall"); 14815 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14816 N->getOpcode() == ISD::SREM; 14817 RTLIB::Libcall LC; 14818 switch (SVT) { 14819 default: llvm_unreachable("Unexpected request for libcall!"); 14820 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 14821 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 14822 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 14823 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 14824 } 14825 return LC; 14826 } 14827 14828 static TargetLowering::ArgListTy getDivRemArgList( 14829 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 14830 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14831 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14832 "Unhandled Opcode in getDivRemArgList"); 14833 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14834 N->getOpcode() == ISD::SREM; 14835 TargetLowering::ArgListTy Args; 14836 TargetLowering::ArgListEntry Entry; 14837 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14838 EVT ArgVT = N->getOperand(i).getValueType(); 14839 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 14840 Entry.Node = N->getOperand(i); 14841 Entry.Ty = ArgTy; 14842 Entry.IsSExt = isSigned; 14843 Entry.IsZExt = !isSigned; 14844 Args.push_back(Entry); 14845 } 14846 if (Subtarget->isTargetWindows() && Args.size() >= 2) 14847 std::swap(Args[0], Args[1]); 14848 return Args; 14849 } 14850 14851 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 14852 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 14853 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 14854 Subtarget->isTargetWindows()) && 14855 "Register-based DivRem lowering only"); 14856 unsigned Opcode = Op->getOpcode(); 14857 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 14858 "Invalid opcode for Div/Rem lowering"); 14859 bool isSigned = (Opcode == ISD::SDIVREM); 14860 EVT VT = Op->getValueType(0); 14861 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 14862 SDLoc dl(Op); 14863 14864 // If the target has hardware divide, use divide + multiply + subtract: 14865 // div = a / b 14866 // rem = a - b * div 14867 // return {div, rem} 14868 // This should be lowered into UDIV/SDIV + MLS later on. 14869 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 14870 : Subtarget->hasDivideInARMMode(); 14871 if (hasDivide && Op->getValueType(0).isSimple() && 14872 Op->getSimpleValueType(0) == MVT::i32) { 14873 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 14874 const SDValue Dividend = Op->getOperand(0); 14875 const SDValue Divisor = Op->getOperand(1); 14876 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 14877 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 14878 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 14879 14880 SDValue Values[2] = {Div, Rem}; 14881 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 14882 } 14883 14884 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 14885 VT.getSimpleVT().SimpleTy); 14886 SDValue InChain = DAG.getEntryNode(); 14887 14888 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 14889 DAG.getContext(), 14890 Subtarget); 14891 14892 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14893 getPointerTy(DAG.getDataLayout())); 14894 14895 Type *RetTy = StructType::get(Ty, Ty); 14896 14897 if (Subtarget->isTargetWindows()) 14898 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 14899 14900 TargetLowering::CallLoweringInfo CLI(DAG); 14901 CLI.setDebugLoc(dl).setChain(InChain) 14902 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 14903 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 14904 14905 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 14906 return CallInfo.first; 14907 } 14908 14909 // Lowers REM using divmod helpers 14910 // see RTABI section 4.2/4.3 14911 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 14912 // Build return types (div and rem) 14913 std::vector<Type*> RetTyParams; 14914 Type *RetTyElement; 14915 14916 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 14917 default: llvm_unreachable("Unexpected request for libcall!"); 14918 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 14919 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 14920 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 14921 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 14922 } 14923 14924 RetTyParams.push_back(RetTyElement); 14925 RetTyParams.push_back(RetTyElement); 14926 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 14927 Type *RetTy = StructType::get(*DAG.getContext(), ret); 14928 14929 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 14930 SimpleTy); 14931 SDValue InChain = DAG.getEntryNode(); 14932 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 14933 Subtarget); 14934 bool isSigned = N->getOpcode() == ISD::SREM; 14935 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14936 getPointerTy(DAG.getDataLayout())); 14937 14938 if (Subtarget->isTargetWindows()) 14939 InChain = WinDBZCheckDenominator(DAG, N, InChain); 14940 14941 // Lower call 14942 CallLoweringInfo CLI(DAG); 14943 CLI.setChain(InChain) 14944 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 14945 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 14946 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 14947 14948 // Return second (rem) result operand (first contains div) 14949 SDNode *ResNode = CallResult.first.getNode(); 14950 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 14951 return ResNode->getOperand(1); 14952 } 14953 14954 SDValue 14955 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 14956 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 14957 SDLoc DL(Op); 14958 14959 // Get the inputs. 14960 SDValue Chain = Op.getOperand(0); 14961 SDValue Size = Op.getOperand(1); 14962 14963 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 14964 "no-stack-arg-probe")) { 14965 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 14966 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14967 Chain = SP.getValue(1); 14968 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 14969 if (Align) 14970 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 14971 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 14972 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 14973 SDValue Ops[2] = { SP, Chain }; 14974 return DAG.getMergeValues(Ops, DL); 14975 } 14976 14977 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 14978 DAG.getConstant(2, DL, MVT::i32)); 14979 14980 SDValue Flag; 14981 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 14982 Flag = Chain.getValue(1); 14983 14984 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 14985 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 14986 14987 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14988 Chain = NewSP.getValue(1); 14989 14990 SDValue Ops[2] = { NewSP, Chain }; 14991 return DAG.getMergeValues(Ops, DL); 14992 } 14993 14994 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 14995 SDValue SrcVal = Op.getOperand(0); 14996 const unsigned DstSz = Op.getValueType().getSizeInBits(); 14997 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 14998 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 14999 "Unexpected type for custom-lowering FP_EXTEND"); 15000 15001 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 15002 "With both FP DP and 16, any FP conversion is legal!"); 15003 15004 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 15005 "With FP16, 16 to 32 conversion is legal!"); 15006 15007 // Either we are converting from 16 -> 64, without FP16 and/or 15008 // FP.double-precision or without Armv8-fp. So we must do it in two 15009 // steps. 15010 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 15011 // without FP16. So we must do a function call. 15012 SDLoc Loc(Op); 15013 RTLIB::Libcall LC; 15014 if (SrcSz == 16) { 15015 // Instruction from 16 -> 32 15016 if (Subtarget->hasFP16()) 15017 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal); 15018 // Lib call from 16 -> 32 15019 else { 15020 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32); 15021 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15022 "Unexpected type for custom-lowering FP_EXTEND"); 15023 SrcVal = 15024 makeLibCall(DAG, LC, MVT::f32, SrcVal, /*isSigned*/ false, Loc).first; 15025 } 15026 } 15027 15028 if (DstSz != 64) 15029 return SrcVal; 15030 // For sure now SrcVal is 32 bits 15031 if (Subtarget->hasFP64()) // Instruction from 32 -> 64 15032 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal); 15033 15034 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64); 15035 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15036 "Unexpected type for custom-lowering FP_EXTEND"); 15037 return makeLibCall(DAG, LC, MVT::f64, SrcVal, /*isSigned*/ false, Loc).first; 15038 } 15039 15040 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 15041 SDValue SrcVal = Op.getOperand(0); 15042 EVT SrcVT = SrcVal.getValueType(); 15043 EVT DstVT = Op.getValueType(); 15044 const unsigned DstSz = Op.getValueType().getSizeInBits(); 15045 const unsigned SrcSz = SrcVT.getSizeInBits(); 15046 (void)DstSz; 15047 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 15048 "Unexpected type for custom-lowering FP_ROUND"); 15049 15050 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 15051 "With both FP DP and 16, any FP conversion is legal!"); 15052 15053 SDLoc Loc(Op); 15054 15055 // Instruction from 32 -> 16 if hasFP16 is valid 15056 if (SrcSz == 32 && Subtarget->hasFP16()) 15057 return Op; 15058 15059 // Lib call from 32 -> 16 / 64 -> [32, 16] 15060 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 15061 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15062 "Unexpected type for custom-lowering FP_ROUND"); 15063 return makeLibCall(DAG, LC, DstVT, SrcVal, /*isSigned*/ false, Loc).first; 15064 } 15065 15066 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 15067 SelectionDAG &DAG) const { 15068 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 15069 MVT HalfT = MVT::i32; 15070 SDLoc dl(N); 15071 SDValue Hi, Lo, Tmp; 15072 15073 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 15074 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 15075 return ; 15076 15077 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 15078 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 15079 15080 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 15081 DAG.getConstant(0, dl, HalfT)); 15082 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 15083 DAG.getConstant(1, dl, HalfT)); 15084 15085 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 15086 DAG.getConstant(OpTypeBits - 1, dl, 15087 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 15088 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 15089 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 15090 SDValue(Lo.getNode(), 1)); 15091 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 15092 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 15093 15094 Results.push_back(Lo); 15095 Results.push_back(Hi); 15096 } 15097 15098 bool 15099 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15100 // The ARM target isn't yet aware of offsets. 15101 return false; 15102 } 15103 15104 bool ARM::isBitFieldInvertedMask(unsigned v) { 15105 if (v == 0xffffffff) 15106 return false; 15107 15108 // there can be 1's on either or both "outsides", all the "inside" 15109 // bits must be 0's 15110 return isShiftedMask_32(~v); 15111 } 15112 15113 /// isFPImmLegal - Returns true if the target can instruction select the 15114 /// specified FP immediate natively. If false, the legalizer will 15115 /// materialize the FP immediate as a load from a constant pool. 15116 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15117 bool ForCodeSize) const { 15118 if (!Subtarget->hasVFP3Base()) 15119 return false; 15120 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 15121 return ARM_AM::getFP16Imm(Imm) != -1; 15122 if (VT == MVT::f32) 15123 return ARM_AM::getFP32Imm(Imm) != -1; 15124 if (VT == MVT::f64 && Subtarget->hasFP64()) 15125 return ARM_AM::getFP64Imm(Imm) != -1; 15126 return false; 15127 } 15128 15129 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 15130 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 15131 /// specified in the intrinsic calls. 15132 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15133 const CallInst &I, 15134 MachineFunction &MF, 15135 unsigned Intrinsic) const { 15136 switch (Intrinsic) { 15137 case Intrinsic::arm_neon_vld1: 15138 case Intrinsic::arm_neon_vld2: 15139 case Intrinsic::arm_neon_vld3: 15140 case Intrinsic::arm_neon_vld4: 15141 case Intrinsic::arm_neon_vld2lane: 15142 case Intrinsic::arm_neon_vld3lane: 15143 case Intrinsic::arm_neon_vld4lane: 15144 case Intrinsic::arm_neon_vld2dup: 15145 case Intrinsic::arm_neon_vld3dup: 15146 case Intrinsic::arm_neon_vld4dup: { 15147 Info.opc = ISD::INTRINSIC_W_CHAIN; 15148 // Conservatively set memVT to the entire set of vectors loaded. 15149 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15150 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 15151 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15152 Info.ptrVal = I.getArgOperand(0); 15153 Info.offset = 0; 15154 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 15155 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 15156 // volatile loads with NEON intrinsics not supported 15157 Info.flags = MachineMemOperand::MOLoad; 15158 return true; 15159 } 15160 case Intrinsic::arm_neon_vld1x2: 15161 case Intrinsic::arm_neon_vld1x3: 15162 case Intrinsic::arm_neon_vld1x4: { 15163 Info.opc = ISD::INTRINSIC_W_CHAIN; 15164 // Conservatively set memVT to the entire set of vectors loaded. 15165 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15166 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 15167 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15168 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 15169 Info.offset = 0; 15170 Info.align = 0; 15171 // volatile loads with NEON intrinsics not supported 15172 Info.flags = MachineMemOperand::MOLoad; 15173 return true; 15174 } 15175 case Intrinsic::arm_neon_vst1: 15176 case Intrinsic::arm_neon_vst2: 15177 case Intrinsic::arm_neon_vst3: 15178 case Intrinsic::arm_neon_vst4: 15179 case Intrinsic::arm_neon_vst2lane: 15180 case Intrinsic::arm_neon_vst3lane: 15181 case Intrinsic::arm_neon_vst4lane: { 15182 Info.opc = ISD::INTRINSIC_VOID; 15183 // Conservatively set memVT to the entire set of vectors stored. 15184 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15185 unsigned NumElts = 0; 15186 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 15187 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 15188 if (!ArgTy->isVectorTy()) 15189 break; 15190 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 15191 } 15192 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15193 Info.ptrVal = I.getArgOperand(0); 15194 Info.offset = 0; 15195 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 15196 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 15197 // volatile stores with NEON intrinsics not supported 15198 Info.flags = MachineMemOperand::MOStore; 15199 return true; 15200 } 15201 case Intrinsic::arm_neon_vst1x2: 15202 case Intrinsic::arm_neon_vst1x3: 15203 case Intrinsic::arm_neon_vst1x4: { 15204 Info.opc = ISD::INTRINSIC_VOID; 15205 // Conservatively set memVT to the entire set of vectors stored. 15206 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15207 unsigned NumElts = 0; 15208 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 15209 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 15210 if (!ArgTy->isVectorTy()) 15211 break; 15212 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 15213 } 15214 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15215 Info.ptrVal = I.getArgOperand(0); 15216 Info.offset = 0; 15217 Info.align = 0; 15218 // volatile stores with NEON intrinsics not supported 15219 Info.flags = MachineMemOperand::MOStore; 15220 return true; 15221 } 15222 case Intrinsic::arm_ldaex: 15223 case Intrinsic::arm_ldrex: { 15224 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15225 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 15226 Info.opc = ISD::INTRINSIC_W_CHAIN; 15227 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15228 Info.ptrVal = I.getArgOperand(0); 15229 Info.offset = 0; 15230 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 15231 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15232 return true; 15233 } 15234 case Intrinsic::arm_stlex: 15235 case Intrinsic::arm_strex: { 15236 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15237 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 15238 Info.opc = ISD::INTRINSIC_W_CHAIN; 15239 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15240 Info.ptrVal = I.getArgOperand(1); 15241 Info.offset = 0; 15242 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 15243 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15244 return true; 15245 } 15246 case Intrinsic::arm_stlexd: 15247 case Intrinsic::arm_strexd: 15248 Info.opc = ISD::INTRINSIC_W_CHAIN; 15249 Info.memVT = MVT::i64; 15250 Info.ptrVal = I.getArgOperand(2); 15251 Info.offset = 0; 15252 Info.align = 8; 15253 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15254 return true; 15255 15256 case Intrinsic::arm_ldaexd: 15257 case Intrinsic::arm_ldrexd: 15258 Info.opc = ISD::INTRINSIC_W_CHAIN; 15259 Info.memVT = MVT::i64; 15260 Info.ptrVal = I.getArgOperand(0); 15261 Info.offset = 0; 15262 Info.align = 8; 15263 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15264 return true; 15265 15266 default: 15267 break; 15268 } 15269 15270 return false; 15271 } 15272 15273 /// Returns true if it is beneficial to convert a load of a constant 15274 /// to just the constant itself. 15275 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15276 Type *Ty) const { 15277 assert(Ty->isIntegerTy()); 15278 15279 unsigned Bits = Ty->getPrimitiveSizeInBits(); 15280 if (Bits == 0 || Bits > 32) 15281 return false; 15282 return true; 15283 } 15284 15285 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 15286 unsigned Index) const { 15287 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 15288 return false; 15289 15290 return (Index == 0 || Index == ResVT.getVectorNumElements()); 15291 } 15292 15293 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 15294 ARM_MB::MemBOpt Domain) const { 15295 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15296 15297 // First, if the target has no DMB, see what fallback we can use. 15298 if (!Subtarget->hasDataBarrier()) { 15299 // Some ARMv6 cpus can support data barriers with an mcr instruction. 15300 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 15301 // here. 15302 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 15303 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 15304 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 15305 Builder.getInt32(0), Builder.getInt32(7), 15306 Builder.getInt32(10), Builder.getInt32(5)}; 15307 return Builder.CreateCall(MCR, args); 15308 } else { 15309 // Instead of using barriers, atomic accesses on these subtargets use 15310 // libcalls. 15311 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 15312 } 15313 } else { 15314 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 15315 // Only a full system barrier exists in the M-class architectures. 15316 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 15317 Constant *CDomain = Builder.getInt32(Domain); 15318 return Builder.CreateCall(DMB, CDomain); 15319 } 15320 } 15321 15322 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 15323 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 15324 Instruction *Inst, 15325 AtomicOrdering Ord) const { 15326 switch (Ord) { 15327 case AtomicOrdering::NotAtomic: 15328 case AtomicOrdering::Unordered: 15329 llvm_unreachable("Invalid fence: unordered/non-atomic"); 15330 case AtomicOrdering::Monotonic: 15331 case AtomicOrdering::Acquire: 15332 return nullptr; // Nothing to do 15333 case AtomicOrdering::SequentiallyConsistent: 15334 if (!Inst->hasAtomicStore()) 15335 return nullptr; // Nothing to do 15336 LLVM_FALLTHROUGH; 15337 case AtomicOrdering::Release: 15338 case AtomicOrdering::AcquireRelease: 15339 if (Subtarget->preferISHSTBarriers()) 15340 return makeDMB(Builder, ARM_MB::ISHST); 15341 // FIXME: add a comment with a link to documentation justifying this. 15342 else 15343 return makeDMB(Builder, ARM_MB::ISH); 15344 } 15345 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 15346 } 15347 15348 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 15349 Instruction *Inst, 15350 AtomicOrdering Ord) const { 15351 switch (Ord) { 15352 case AtomicOrdering::NotAtomic: 15353 case AtomicOrdering::Unordered: 15354 llvm_unreachable("Invalid fence: unordered/not-atomic"); 15355 case AtomicOrdering::Monotonic: 15356 case AtomicOrdering::Release: 15357 return nullptr; // Nothing to do 15358 case AtomicOrdering::Acquire: 15359 case AtomicOrdering::AcquireRelease: 15360 case AtomicOrdering::SequentiallyConsistent: 15361 return makeDMB(Builder, ARM_MB::ISH); 15362 } 15363 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 15364 } 15365 15366 // Loads and stores less than 64-bits are already atomic; ones above that 15367 // are doomed anyway, so defer to the default libcall and blame the OS when 15368 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15369 // anything for those. 15370 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 15371 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 15372 return (Size == 64) && !Subtarget->isMClass(); 15373 } 15374 15375 // Loads and stores less than 64-bits are already atomic; ones above that 15376 // are doomed anyway, so defer to the default libcall and blame the OS when 15377 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15378 // anything for those. 15379 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 15380 // guarantee, see DDI0406C ARM architecture reference manual, 15381 // sections A8.8.72-74 LDRD) 15382 TargetLowering::AtomicExpansionKind 15383 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 15384 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 15385 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 15386 : AtomicExpansionKind::None; 15387 } 15388 15389 // For the real atomic operations, we have ldrex/strex up to 32 bits, 15390 // and up to 64 bits on the non-M profiles 15391 TargetLowering::AtomicExpansionKind 15392 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 15393 if (AI->isFloatingPointOperation()) 15394 return AtomicExpansionKind::CmpXChg; 15395 15396 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 15397 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 15398 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 15399 ? AtomicExpansionKind::LLSC 15400 : AtomicExpansionKind::None; 15401 } 15402 15403 TargetLowering::AtomicExpansionKind 15404 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 15405 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 15406 // implement cmpxchg without spilling. If the address being exchanged is also 15407 // on the stack and close enough to the spill slot, this can lead to a 15408 // situation where the monitor always gets cleared and the atomic operation 15409 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 15410 bool HasAtomicCmpXchg = 15411 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 15412 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 15413 return AtomicExpansionKind::LLSC; 15414 return AtomicExpansionKind::None; 15415 } 15416 15417 bool ARMTargetLowering::shouldInsertFencesForAtomic( 15418 const Instruction *I) const { 15419 return InsertFencesForAtomic; 15420 } 15421 15422 // This has so far only been implemented for MachO. 15423 bool ARMTargetLowering::useLoadStackGuardNode() const { 15424 return Subtarget->isTargetMachO(); 15425 } 15426 15427 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 15428 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 15429 return TargetLowering::insertSSPDeclarations(M); 15430 15431 // MSVC CRT has a global variable holding security cookie. 15432 M.getOrInsertGlobal("__security_cookie", 15433 Type::getInt8PtrTy(M.getContext())); 15434 15435 // MSVC CRT has a function to validate security cookie. 15436 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 15437 "__security_check_cookie", Type::getVoidTy(M.getContext()), 15438 Type::getInt8PtrTy(M.getContext())); 15439 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 15440 F->addAttribute(1, Attribute::AttrKind::InReg); 15441 } 15442 15443 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 15444 // MSVC CRT has a global variable holding security cookie. 15445 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 15446 return M.getGlobalVariable("__security_cookie"); 15447 return TargetLowering::getSDagStackGuard(M); 15448 } 15449 15450 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 15451 // MSVC CRT has a function to validate security cookie. 15452 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 15453 return M.getFunction("__security_check_cookie"); 15454 return TargetLowering::getSSPStackGuardCheck(M); 15455 } 15456 15457 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 15458 unsigned &Cost) const { 15459 // If we do not have NEON, vector types are not natively supported. 15460 if (!Subtarget->hasNEON()) 15461 return false; 15462 15463 // Floating point values and vector values map to the same register file. 15464 // Therefore, although we could do a store extract of a vector type, this is 15465 // better to leave at float as we have more freedom in the addressing mode for 15466 // those. 15467 if (VectorTy->isFPOrFPVectorTy()) 15468 return false; 15469 15470 // If the index is unknown at compile time, this is very expensive to lower 15471 // and it is not possible to combine the store with the extract. 15472 if (!isa<ConstantInt>(Idx)) 15473 return false; 15474 15475 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 15476 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 15477 // We can do a store + vector extract on any vector that fits perfectly in a D 15478 // or Q register. 15479 if (BitWidth == 64 || BitWidth == 128) { 15480 Cost = 0; 15481 return true; 15482 } 15483 return false; 15484 } 15485 15486 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 15487 return Subtarget->hasV6T2Ops(); 15488 } 15489 15490 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 15491 return Subtarget->hasV6T2Ops(); 15492 } 15493 15494 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 15495 return !Subtarget->hasMinSize(); 15496 } 15497 15498 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 15499 AtomicOrdering Ord) const { 15500 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15501 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 15502 bool IsAcquire = isAcquireOrStronger(Ord); 15503 15504 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 15505 // intrinsic must return {i32, i32} and we have to recombine them into a 15506 // single i64 here. 15507 if (ValTy->getPrimitiveSizeInBits() == 64) { 15508 Intrinsic::ID Int = 15509 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 15510 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 15511 15512 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 15513 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 15514 15515 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 15516 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 15517 if (!Subtarget->isLittle()) 15518 std::swap (Lo, Hi); 15519 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 15520 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 15521 return Builder.CreateOr( 15522 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 15523 } 15524 15525 Type *Tys[] = { Addr->getType() }; 15526 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 15527 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 15528 15529 return Builder.CreateTruncOrBitCast( 15530 Builder.CreateCall(Ldrex, Addr), 15531 cast<PointerType>(Addr->getType())->getElementType()); 15532 } 15533 15534 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 15535 IRBuilder<> &Builder) const { 15536 if (!Subtarget->hasV7Ops()) 15537 return; 15538 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15539 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 15540 } 15541 15542 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 15543 Value *Addr, 15544 AtomicOrdering Ord) const { 15545 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15546 bool IsRelease = isReleaseOrStronger(Ord); 15547 15548 // Since the intrinsics must have legal type, the i64 intrinsics take two 15549 // parameters: "i32, i32". We must marshal Val into the appropriate form 15550 // before the call. 15551 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 15552 Intrinsic::ID Int = 15553 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 15554 Function *Strex = Intrinsic::getDeclaration(M, Int); 15555 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 15556 15557 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 15558 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 15559 if (!Subtarget->isLittle()) 15560 std::swap(Lo, Hi); 15561 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 15562 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 15563 } 15564 15565 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 15566 Type *Tys[] = { Addr->getType() }; 15567 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 15568 15569 return Builder.CreateCall( 15570 Strex, {Builder.CreateZExtOrBitCast( 15571 Val, Strex->getFunctionType()->getParamType(0)), 15572 Addr}); 15573 } 15574 15575 15576 bool ARMTargetLowering::alignLoopsWithOptSize() const { 15577 return Subtarget->isMClass(); 15578 } 15579 15580 /// A helper function for determining the number of interleaved accesses we 15581 /// will generate when lowering accesses of the given type. 15582 unsigned 15583 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 15584 const DataLayout &DL) const { 15585 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 15586 } 15587 15588 bool ARMTargetLowering::isLegalInterleavedAccessType( 15589 VectorType *VecTy, const DataLayout &DL) const { 15590 15591 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 15592 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 15593 15594 // Ensure the vector doesn't have f16 elements. Even though we could do an 15595 // i16 vldN, we can't hold the f16 vectors and will end up converting via 15596 // f32. 15597 if (VecTy->getElementType()->isHalfTy()) 15598 return false; 15599 15600 // Ensure the number of vector elements is greater than 1. 15601 if (VecTy->getNumElements() < 2) 15602 return false; 15603 15604 // Ensure the element type is legal. 15605 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 15606 return false; 15607 15608 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 15609 // 128 will be split into multiple interleaved accesses. 15610 return VecSize == 64 || VecSize % 128 == 0; 15611 } 15612 15613 /// Lower an interleaved load into a vldN intrinsic. 15614 /// 15615 /// E.g. Lower an interleaved load (Factor = 2): 15616 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 15617 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 15618 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 15619 /// 15620 /// Into: 15621 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 15622 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 15623 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 15624 bool ARMTargetLowering::lowerInterleavedLoad( 15625 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 15626 ArrayRef<unsigned> Indices, unsigned Factor) const { 15627 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 15628 "Invalid interleave factor"); 15629 assert(!Shuffles.empty() && "Empty shufflevector input"); 15630 assert(Shuffles.size() == Indices.size() && 15631 "Unmatched number of shufflevectors and indices"); 15632 15633 VectorType *VecTy = Shuffles[0]->getType(); 15634 Type *EltTy = VecTy->getVectorElementType(); 15635 15636 const DataLayout &DL = LI->getModule()->getDataLayout(); 15637 15638 // Skip if we do not have NEON and skip illegal vector types. We can 15639 // "legalize" wide vector types into multiple interleaved accesses as long as 15640 // the vector types are divisible by 128. 15641 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 15642 return false; 15643 15644 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 15645 15646 // A pointer vector can not be the return type of the ldN intrinsics. Need to 15647 // load integer vectors first and then convert to pointer vectors. 15648 if (EltTy->isPointerTy()) 15649 VecTy = 15650 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 15651 15652 IRBuilder<> Builder(LI); 15653 15654 // The base address of the load. 15655 Value *BaseAddr = LI->getPointerOperand(); 15656 15657 if (NumLoads > 1) { 15658 // If we're going to generate more than one load, reset the sub-vector type 15659 // to something legal. 15660 VecTy = VectorType::get(VecTy->getVectorElementType(), 15661 VecTy->getVectorNumElements() / NumLoads); 15662 15663 // We will compute the pointer operand of each load from the original base 15664 // address using GEPs. Cast the base address to a pointer to the scalar 15665 // element type. 15666 BaseAddr = Builder.CreateBitCast( 15667 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 15668 LI->getPointerAddressSpace())); 15669 } 15670 15671 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 15672 15673 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 15674 Type *Tys[] = {VecTy, Int8Ptr}; 15675 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 15676 Intrinsic::arm_neon_vld3, 15677 Intrinsic::arm_neon_vld4}; 15678 Function *VldnFunc = 15679 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 15680 15681 // Holds sub-vectors extracted from the load intrinsic return values. The 15682 // sub-vectors are associated with the shufflevector instructions they will 15683 // replace. 15684 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 15685 15686 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 15687 // If we're generating more than one load, compute the base address of 15688 // subsequent loads as an offset from the previous. 15689 if (LoadCount > 0) 15690 BaseAddr = 15691 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 15692 VecTy->getVectorNumElements() * Factor); 15693 15694 SmallVector<Value *, 2> Ops; 15695 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 15696 Ops.push_back(Builder.getInt32(LI->getAlignment())); 15697 15698 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 15699 15700 // Replace uses of each shufflevector with the corresponding vector loaded 15701 // by ldN. 15702 for (unsigned i = 0; i < Shuffles.size(); i++) { 15703 ShuffleVectorInst *SV = Shuffles[i]; 15704 unsigned Index = Indices[i]; 15705 15706 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 15707 15708 // Convert the integer vector to pointer vector if the element is pointer. 15709 if (EltTy->isPointerTy()) 15710 SubVec = Builder.CreateIntToPtr( 15711 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 15712 VecTy->getVectorNumElements())); 15713 15714 SubVecs[SV].push_back(SubVec); 15715 } 15716 } 15717 15718 // Replace uses of the shufflevector instructions with the sub-vectors 15719 // returned by the load intrinsic. If a shufflevector instruction is 15720 // associated with more than one sub-vector, those sub-vectors will be 15721 // concatenated into a single wide vector. 15722 for (ShuffleVectorInst *SVI : Shuffles) { 15723 auto &SubVec = SubVecs[SVI]; 15724 auto *WideVec = 15725 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 15726 SVI->replaceAllUsesWith(WideVec); 15727 } 15728 15729 return true; 15730 } 15731 15732 /// Lower an interleaved store into a vstN intrinsic. 15733 /// 15734 /// E.g. Lower an interleaved store (Factor = 3): 15735 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 15736 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 15737 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 15738 /// 15739 /// Into: 15740 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 15741 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 15742 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 15743 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 15744 /// 15745 /// Note that the new shufflevectors will be removed and we'll only generate one 15746 /// vst3 instruction in CodeGen. 15747 /// 15748 /// Example for a more general valid mask (Factor 3). Lower: 15749 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 15750 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 15751 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 15752 /// 15753 /// Into: 15754 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 15755 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 15756 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 15757 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 15758 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 15759 ShuffleVectorInst *SVI, 15760 unsigned Factor) const { 15761 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 15762 "Invalid interleave factor"); 15763 15764 VectorType *VecTy = SVI->getType(); 15765 assert(VecTy->getVectorNumElements() % Factor == 0 && 15766 "Invalid interleaved store"); 15767 15768 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 15769 Type *EltTy = VecTy->getVectorElementType(); 15770 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 15771 15772 const DataLayout &DL = SI->getModule()->getDataLayout(); 15773 15774 // Skip if we do not have NEON and skip illegal vector types. We can 15775 // "legalize" wide vector types into multiple interleaved accesses as long as 15776 // the vector types are divisible by 128. 15777 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 15778 return false; 15779 15780 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 15781 15782 Value *Op0 = SVI->getOperand(0); 15783 Value *Op1 = SVI->getOperand(1); 15784 IRBuilder<> Builder(SI); 15785 15786 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 15787 // vectors to integer vectors. 15788 if (EltTy->isPointerTy()) { 15789 Type *IntTy = DL.getIntPtrType(EltTy); 15790 15791 // Convert to the corresponding integer vector. 15792 Type *IntVecTy = 15793 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 15794 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 15795 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 15796 15797 SubVecTy = VectorType::get(IntTy, LaneLen); 15798 } 15799 15800 // The base address of the store. 15801 Value *BaseAddr = SI->getPointerOperand(); 15802 15803 if (NumStores > 1) { 15804 // If we're going to generate more than one store, reset the lane length 15805 // and sub-vector type to something legal. 15806 LaneLen /= NumStores; 15807 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 15808 15809 // We will compute the pointer operand of each store from the original base 15810 // address using GEPs. Cast the base address to a pointer to the scalar 15811 // element type. 15812 BaseAddr = Builder.CreateBitCast( 15813 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 15814 SI->getPointerAddressSpace())); 15815 } 15816 15817 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 15818 15819 auto Mask = SVI->getShuffleMask(); 15820 15821 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 15822 Type *Tys[] = {Int8Ptr, SubVecTy}; 15823 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 15824 Intrinsic::arm_neon_vst3, 15825 Intrinsic::arm_neon_vst4}; 15826 15827 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 15828 // If we generating more than one store, we compute the base address of 15829 // subsequent stores as an offset from the previous. 15830 if (StoreCount > 0) 15831 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 15832 BaseAddr, LaneLen * Factor); 15833 15834 SmallVector<Value *, 6> Ops; 15835 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 15836 15837 Function *VstNFunc = 15838 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 15839 15840 // Split the shufflevector operands into sub vectors for the new vstN call. 15841 for (unsigned i = 0; i < Factor; i++) { 15842 unsigned IdxI = StoreCount * LaneLen * Factor + i; 15843 if (Mask[IdxI] >= 0) { 15844 Ops.push_back(Builder.CreateShuffleVector( 15845 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 15846 } else { 15847 unsigned StartMask = 0; 15848 for (unsigned j = 1; j < LaneLen; j++) { 15849 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 15850 if (Mask[IdxJ * Factor + IdxI] >= 0) { 15851 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 15852 break; 15853 } 15854 } 15855 // Note: If all elements in a chunk are undefs, StartMask=0! 15856 // Note: Filling undef gaps with random elements is ok, since 15857 // those elements were being written anyway (with undefs). 15858 // In the case of all undefs we're defaulting to using elems from 0 15859 // Note: StartMask cannot be negative, it's checked in 15860 // isReInterleaveMask 15861 Ops.push_back(Builder.CreateShuffleVector( 15862 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 15863 } 15864 } 15865 15866 Ops.push_back(Builder.getInt32(SI->getAlignment())); 15867 Builder.CreateCall(VstNFunc, Ops); 15868 } 15869 return true; 15870 } 15871 15872 enum HABaseType { 15873 HA_UNKNOWN = 0, 15874 HA_FLOAT, 15875 HA_DOUBLE, 15876 HA_VECT64, 15877 HA_VECT128 15878 }; 15879 15880 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 15881 uint64_t &Members) { 15882 if (auto *ST = dyn_cast<StructType>(Ty)) { 15883 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 15884 uint64_t SubMembers = 0; 15885 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 15886 return false; 15887 Members += SubMembers; 15888 } 15889 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 15890 uint64_t SubMembers = 0; 15891 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 15892 return false; 15893 Members += SubMembers * AT->getNumElements(); 15894 } else if (Ty->isFloatTy()) { 15895 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 15896 return false; 15897 Members = 1; 15898 Base = HA_FLOAT; 15899 } else if (Ty->isDoubleTy()) { 15900 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 15901 return false; 15902 Members = 1; 15903 Base = HA_DOUBLE; 15904 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 15905 Members = 1; 15906 switch (Base) { 15907 case HA_FLOAT: 15908 case HA_DOUBLE: 15909 return false; 15910 case HA_VECT64: 15911 return VT->getBitWidth() == 64; 15912 case HA_VECT128: 15913 return VT->getBitWidth() == 128; 15914 case HA_UNKNOWN: 15915 switch (VT->getBitWidth()) { 15916 case 64: 15917 Base = HA_VECT64; 15918 return true; 15919 case 128: 15920 Base = HA_VECT128; 15921 return true; 15922 default: 15923 return false; 15924 } 15925 } 15926 } 15927 15928 return (Members > 0 && Members <= 4); 15929 } 15930 15931 /// Return the correct alignment for the current calling convention. 15932 unsigned 15933 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 15934 DataLayout DL) const { 15935 if (!ArgTy->isVectorTy()) 15936 return DL.getABITypeAlignment(ArgTy); 15937 15938 // Avoid over-aligning vector parameters. It would require realigning the 15939 // stack and waste space for no real benefit. 15940 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 15941 } 15942 15943 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 15944 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 15945 /// passing according to AAPCS rules. 15946 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 15947 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 15948 if (getEffectiveCallingConv(CallConv, isVarArg) != 15949 CallingConv::ARM_AAPCS_VFP) 15950 return false; 15951 15952 HABaseType Base = HA_UNKNOWN; 15953 uint64_t Members = 0; 15954 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 15955 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 15956 15957 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 15958 return IsHA || IsIntArray; 15959 } 15960 15961 unsigned ARMTargetLowering::getExceptionPointerRegister( 15962 const Constant *PersonalityFn) const { 15963 // Platforms which do not use SjLj EH may return values in these registers 15964 // via the personality function. 15965 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 15966 } 15967 15968 unsigned ARMTargetLowering::getExceptionSelectorRegister( 15969 const Constant *PersonalityFn) const { 15970 // Platforms which do not use SjLj EH may return values in these registers 15971 // via the personality function. 15972 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 15973 } 15974 15975 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15976 // Update IsSplitCSR in ARMFunctionInfo. 15977 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 15978 AFI->setIsSplitCSR(true); 15979 } 15980 15981 void ARMTargetLowering::insertCopiesSplitCSR( 15982 MachineBasicBlock *Entry, 15983 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15984 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 15985 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15986 if (!IStart) 15987 return; 15988 15989 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 15990 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15991 MachineBasicBlock::iterator MBBI = Entry->begin(); 15992 for (const MCPhysReg *I = IStart; *I; ++I) { 15993 const TargetRegisterClass *RC = nullptr; 15994 if (ARM::GPRRegClass.contains(*I)) 15995 RC = &ARM::GPRRegClass; 15996 else if (ARM::DPRRegClass.contains(*I)) 15997 RC = &ARM::DPRRegClass; 15998 else 15999 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 16000 16001 unsigned NewVR = MRI->createVirtualRegister(RC); 16002 // Create copy from CSR to a virtual register. 16003 // FIXME: this currently does not emit CFI pseudo-instructions, it works 16004 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 16005 // nounwind. If we want to generalize this later, we may need to emit 16006 // CFI pseudo-instructions. 16007 assert(Entry->getParent()->getFunction().hasFnAttribute( 16008 Attribute::NoUnwind) && 16009 "Function should be nounwind in insertCopiesSplitCSR!"); 16010 Entry->addLiveIn(*I); 16011 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 16012 .addReg(*I); 16013 16014 // Insert the copy-back instructions right before the terminator. 16015 for (auto *Exit : Exits) 16016 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 16017 TII->get(TargetOpcode::COPY), *I) 16018 .addReg(NewVR); 16019 } 16020 } 16021 16022 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 16023 MF.getFrameInfo().computeMaxCallFrameSize(MF); 16024 TargetLoweringBase::finalizeLowering(MF); 16025 } 16026