1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that ARM uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "ARMISelLowering.h" 15 #include "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMCallingConv.h" 18 #include "ARMConstantPoolValue.h" 19 #include "ARMMachineFunctionInfo.h" 20 #include "ARMPerfectShuffle.h" 21 #include "ARMRegisterInfo.h" 22 #include "ARMSelectionDAGInfo.h" 23 #include "ARMSubtarget.h" 24 #include "MCTargetDesc/ARMAddressingModes.h" 25 #include "MCTargetDesc/ARMBaseInfo.h" 26 #include "Utils/ARMBaseInfo.h" 27 #include "llvm/ADT/APFloat.h" 28 #include "llvm/ADT/APInt.h" 29 #include "llvm/ADT/ArrayRef.h" 30 #include "llvm/ADT/BitVector.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringRef.h" 38 #include "llvm/ADT/StringSwitch.h" 39 #include "llvm/ADT/Triple.h" 40 #include "llvm/ADT/Twine.h" 41 #include "llvm/Analysis/VectorUtils.h" 42 #include "llvm/CodeGen/CallingConvLower.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/IntrinsicLowering.h" 45 #include "llvm/CodeGen/MachineBasicBlock.h" 46 #include "llvm/CodeGen/MachineConstantPool.h" 47 #include "llvm/CodeGen/MachineFrameInfo.h" 48 #include "llvm/CodeGen/MachineFunction.h" 49 #include "llvm/CodeGen/MachineInstr.h" 50 #include "llvm/CodeGen/MachineInstrBuilder.h" 51 #include "llvm/CodeGen/MachineJumpTableInfo.h" 52 #include "llvm/CodeGen/MachineMemOperand.h" 53 #include "llvm/CodeGen/MachineOperand.h" 54 #include "llvm/CodeGen/MachineRegisterInfo.h" 55 #include "llvm/CodeGen/RuntimeLibcalls.h" 56 #include "llvm/CodeGen/SelectionDAG.h" 57 #include "llvm/CodeGen/SelectionDAGNodes.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/IR/Attributes.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugLoc.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GlobalAlias.h" 73 #include "llvm/IR/GlobalValue.h" 74 #include "llvm/IR/GlobalVariable.h" 75 #include "llvm/IR/IRBuilder.h" 76 #include "llvm/IR/InlineAsm.h" 77 #include "llvm/IR/Instruction.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/IntrinsicInst.h" 80 #include "llvm/IR/Intrinsics.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/PatternMatch.h" 83 #include "llvm/IR/Type.h" 84 #include "llvm/IR/User.h" 85 #include "llvm/IR/Value.h" 86 #include "llvm/MC/MCInstrDesc.h" 87 #include "llvm/MC/MCInstrItineraries.h" 88 #include "llvm/MC/MCRegisterInfo.h" 89 #include "llvm/MC/MCSchedule.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/BranchProbability.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CodeGen.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/ErrorHandling.h" 98 #include "llvm/Support/KnownBits.h" 99 #include "llvm/Support/MachineValueType.h" 100 #include "llvm/Support/MathExtras.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include <algorithm> 105 #include <cassert> 106 #include <cstdint> 107 #include <cstdlib> 108 #include <iterator> 109 #include <limits> 110 #include <string> 111 #include <tuple> 112 #include <utility> 113 #include <vector> 114 115 using namespace llvm; 116 using namespace llvm::PatternMatch; 117 118 #define DEBUG_TYPE "arm-isel" 119 120 STATISTIC(NumTailCalls, "Number of tail calls"); 121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 123 STATISTIC(NumConstpoolPromoted, 124 "Number of constants with their storage promoted into constant pools"); 125 126 static cl::opt<bool> 127 ARMInterworking("arm-interworking", cl::Hidden, 128 cl::desc("Enable / disable ARM interworking (for debugging only)"), 129 cl::init(true)); 130 131 static cl::opt<bool> EnableConstpoolPromotion( 132 "arm-promote-constant", cl::Hidden, 133 cl::desc("Enable / disable promotion of unnamed_addr constants into " 134 "constant pools"), 135 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 136 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 137 "arm-promote-constant-max-size", cl::Hidden, 138 cl::desc("Maximum size of constant to promote into a constant pool"), 139 cl::init(64)); 140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 141 "arm-promote-constant-max-total", cl::Hidden, 142 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 143 cl::init(128)); 144 145 // The APCS parameter registers. 146 static const MCPhysReg GPRArgRegs[] = { 147 ARM::R0, ARM::R1, ARM::R2, ARM::R3 148 }; 149 150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 151 MVT PromotedBitwiseVT) { 152 if (VT != PromotedLdStVT) { 153 setOperationAction(ISD::LOAD, VT, Promote); 154 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 155 156 setOperationAction(ISD::STORE, VT, Promote); 157 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 158 } 159 160 MVT ElemTy = VT.getVectorElementType(); 161 if (ElemTy != MVT::f64) 162 setOperationAction(ISD::SETCC, VT, Custom); 163 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 164 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 165 if (ElemTy == MVT::i32) { 166 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 167 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 168 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 169 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 170 } else { 171 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 172 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 173 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 174 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 175 } 176 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 177 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 178 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 179 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 180 setOperationAction(ISD::SELECT, VT, Expand); 181 setOperationAction(ISD::SELECT_CC, VT, Expand); 182 setOperationAction(ISD::VSELECT, VT, Expand); 183 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 184 if (VT.isInteger()) { 185 setOperationAction(ISD::SHL, VT, Custom); 186 setOperationAction(ISD::SRA, VT, Custom); 187 setOperationAction(ISD::SRL, VT, Custom); 188 } 189 190 // Promote all bit-wise operations. 191 if (VT.isInteger() && VT != PromotedBitwiseVT) { 192 setOperationAction(ISD::AND, VT, Promote); 193 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 194 setOperationAction(ISD::OR, VT, Promote); 195 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 196 setOperationAction(ISD::XOR, VT, Promote); 197 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 198 } 199 200 // Neon does not support vector divide/remainder operations. 201 setOperationAction(ISD::SDIV, VT, Expand); 202 setOperationAction(ISD::UDIV, VT, Expand); 203 setOperationAction(ISD::FDIV, VT, Expand); 204 setOperationAction(ISD::SREM, VT, Expand); 205 setOperationAction(ISD::UREM, VT, Expand); 206 setOperationAction(ISD::FREM, VT, Expand); 207 208 if (!VT.isFloatingPoint() && 209 VT != MVT::v2i64 && VT != MVT::v1i64) 210 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 211 setOperationAction(Opcode, VT, Legal); 212 } 213 214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 215 addRegisterClass(VT, &ARM::DPRRegClass); 216 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 217 } 218 219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 220 addRegisterClass(VT, &ARM::DPairRegClass); 221 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 222 } 223 224 void ARMTargetLowering::setAllExpand(MVT VT) { 225 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc) 226 setOperationAction(Opc, VT, Expand); 227 228 // We support these really simple operations even on types where all 229 // the actual arithmetic has to be broken down into simpler 230 // operations or turned into library calls. 231 setOperationAction(ISD::BITCAST, VT, Legal); 232 setOperationAction(ISD::LOAD, VT, Legal); 233 setOperationAction(ISD::STORE, VT, Legal); 234 setOperationAction(ISD::UNDEF, VT, Legal); 235 } 236 237 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To, 238 LegalizeAction Action) { 239 setLoadExtAction(ISD::EXTLOAD, From, To, Action); 240 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action); 241 setLoadExtAction(ISD::SEXTLOAD, From, To, Action); 242 } 243 244 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) { 245 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 }; 246 247 for (auto VT : IntTypes) { 248 addRegisterClass(VT, &ARM::QPRRegClass); 249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 250 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 251 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 252 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 253 setOperationAction(ISD::SHL, VT, Custom); 254 setOperationAction(ISD::SRA, VT, Custom); 255 setOperationAction(ISD::SRL, VT, Custom); 256 setOperationAction(ISD::SMIN, VT, Legal); 257 setOperationAction(ISD::SMAX, VT, Legal); 258 setOperationAction(ISD::UMIN, VT, Legal); 259 setOperationAction(ISD::UMAX, VT, Legal); 260 setOperationAction(ISD::ABS, VT, Legal); 261 setOperationAction(ISD::SETCC, VT, Custom); 262 263 // No native support for these. 264 setOperationAction(ISD::UDIV, VT, Expand); 265 setOperationAction(ISD::SDIV, VT, Expand); 266 setOperationAction(ISD::UREM, VT, Expand); 267 setOperationAction(ISD::SREM, VT, Expand); 268 269 if (!HasMVEFP) { 270 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 271 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 272 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 273 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 274 } 275 } 276 277 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 278 for (auto VT : FloatTypes) { 279 addRegisterClass(VT, &ARM::QPRRegClass); 280 if (!HasMVEFP) 281 setAllExpand(VT); 282 283 // These are legal or custom whether we have MVE.fp or not 284 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 285 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 286 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 287 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 288 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 289 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 290 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 291 setOperationAction(ISD::SETCC, VT, Custom); 292 293 if (HasMVEFP) { 294 setOperationAction(ISD::FMINNUM, VT, Legal); 295 setOperationAction(ISD::FMAXNUM, VT, Legal); 296 setOperationAction(ISD::FROUND, VT, Legal); 297 298 // No native support for these. 299 setOperationAction(ISD::FDIV, VT, Expand); 300 setOperationAction(ISD::FREM, VT, Expand); 301 setOperationAction(ISD::FSQRT, VT, Expand); 302 setOperationAction(ISD::FSIN, VT, Expand); 303 setOperationAction(ISD::FCOS, VT, Expand); 304 setOperationAction(ISD::FPOW, VT, Expand); 305 setOperationAction(ISD::FLOG, VT, Expand); 306 setOperationAction(ISD::FLOG2, VT, Expand); 307 setOperationAction(ISD::FLOG10, VT, Expand); 308 setOperationAction(ISD::FEXP, VT, Expand); 309 setOperationAction(ISD::FEXP2, VT, Expand); 310 setOperationAction(ISD::FNEARBYINT, VT, Expand); 311 } 312 } 313 314 // We 'support' these types up to bitcast/load/store level, regardless of 315 // MVE integer-only / float support. Only doing FP data processing on the FP 316 // vector types is inhibited at integer-only level. 317 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 318 for (auto VT : LongTypes) { 319 addRegisterClass(VT, &ARM::QPRRegClass); 320 setAllExpand(VT); 321 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 323 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 324 } 325 // We can do bitwise operations on v2i64 vectors 326 setOperationAction(ISD::AND, MVT::v2i64, Legal); 327 setOperationAction(ISD::OR, MVT::v2i64, Legal); 328 setOperationAction(ISD::XOR, MVT::v2i64, Legal); 329 330 // It is legal to extload from v4i8 to v4i16 or v4i32. 331 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 332 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 333 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 334 335 // Some truncating stores are legal too. 336 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 337 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 338 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 339 340 // Predicate types 341 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1}; 342 for (auto VT : pTypes) { 343 addRegisterClass(VT, &ARM::VCCRRegClass); 344 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 345 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 346 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 347 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 348 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 349 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 350 setOperationAction(ISD::SETCC, VT, Custom); 351 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 352 } 353 } 354 355 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 356 const ARMSubtarget &STI) 357 : TargetLowering(TM), Subtarget(&STI) { 358 RegInfo = Subtarget->getRegisterInfo(); 359 Itins = Subtarget->getInstrItineraryData(); 360 361 setBooleanContents(ZeroOrOneBooleanContent); 362 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 363 364 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 365 !Subtarget->isTargetWatchOS()) { 366 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 367 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 368 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 369 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 370 : CallingConv::ARM_AAPCS); 371 } 372 373 if (Subtarget->isTargetMachO()) { 374 // Uses VFP for Thumb libfuncs if available. 375 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 376 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 377 static const struct { 378 const RTLIB::Libcall Op; 379 const char * const Name; 380 const ISD::CondCode Cond; 381 } LibraryCalls[] = { 382 // Single-precision floating-point arithmetic. 383 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 384 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 385 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 386 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 387 388 // Double-precision floating-point arithmetic. 389 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 390 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 391 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 392 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 393 394 // Single-precision comparisons. 395 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 396 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 397 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 398 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 399 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 400 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 401 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 402 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 403 404 // Double-precision comparisons. 405 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 406 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 407 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 408 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 409 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 410 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 411 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 412 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 413 414 // Floating-point to integer conversions. 415 // i64 conversions are done via library routines even when generating VFP 416 // instructions, so use the same ones. 417 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 418 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 419 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 420 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 421 422 // Conversions between floating types. 423 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 424 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 425 426 // Integer to floating-point conversions. 427 // i64 conversions are done via library routines even when generating VFP 428 // instructions, so use the same ones. 429 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 430 // e.g., __floatunsidf vs. __floatunssidfvfp. 431 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 432 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 433 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 434 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 435 }; 436 437 for (const auto &LC : LibraryCalls) { 438 setLibcallName(LC.Op, LC.Name); 439 if (LC.Cond != ISD::SETCC_INVALID) 440 setCmpLibcallCC(LC.Op, LC.Cond); 441 } 442 } 443 } 444 445 // These libcalls are not available in 32-bit. 446 setLibcallName(RTLIB::SHL_I128, nullptr); 447 setLibcallName(RTLIB::SRL_I128, nullptr); 448 setLibcallName(RTLIB::SRA_I128, nullptr); 449 450 // RTLIB 451 if (Subtarget->isAAPCS_ABI() && 452 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 453 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 454 static const struct { 455 const RTLIB::Libcall Op; 456 const char * const Name; 457 const CallingConv::ID CC; 458 const ISD::CondCode Cond; 459 } LibraryCalls[] = { 460 // Double-precision floating-point arithmetic helper functions 461 // RTABI chapter 4.1.2, Table 2 462 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 463 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 464 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 465 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 466 467 // Double-precision floating-point comparison helper functions 468 // RTABI chapter 4.1.2, Table 3 469 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 470 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 471 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 472 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 473 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 474 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 475 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 476 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 477 478 // Single-precision floating-point arithmetic helper functions 479 // RTABI chapter 4.1.2, Table 4 480 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 481 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 482 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 483 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 484 485 // Single-precision floating-point comparison helper functions 486 // RTABI chapter 4.1.2, Table 5 487 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 488 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 489 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 490 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 491 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 492 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 493 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 494 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 495 496 // Floating-point to integer conversions. 497 // RTABI chapter 4.1.2, Table 6 498 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 499 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 500 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 501 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 502 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 503 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 504 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 505 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 506 507 // Conversions between floating types. 508 // RTABI chapter 4.1.2, Table 7 509 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 510 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 511 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 512 513 // Integer to floating-point conversions. 514 // RTABI chapter 4.1.2, Table 8 515 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 516 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 517 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 518 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 519 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 520 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 521 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 522 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 523 524 // Long long helper functions 525 // RTABI chapter 4.2, Table 9 526 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 527 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 528 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 529 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 530 531 // Integer division functions 532 // RTABI chapter 4.3.1 533 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 534 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 535 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 536 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 537 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 538 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 539 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 540 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 541 }; 542 543 for (const auto &LC : LibraryCalls) { 544 setLibcallName(LC.Op, LC.Name); 545 setLibcallCallingConv(LC.Op, LC.CC); 546 if (LC.Cond != ISD::SETCC_INVALID) 547 setCmpLibcallCC(LC.Op, LC.Cond); 548 } 549 550 // EABI dependent RTLIB 551 if (TM.Options.EABIVersion == EABI::EABI4 || 552 TM.Options.EABIVersion == EABI::EABI5) { 553 static const struct { 554 const RTLIB::Libcall Op; 555 const char *const Name; 556 const CallingConv::ID CC; 557 const ISD::CondCode Cond; 558 } MemOpsLibraryCalls[] = { 559 // Memory operations 560 // RTABI chapter 4.3.4 561 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 562 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 563 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 564 }; 565 566 for (const auto &LC : MemOpsLibraryCalls) { 567 setLibcallName(LC.Op, LC.Name); 568 setLibcallCallingConv(LC.Op, LC.CC); 569 if (LC.Cond != ISD::SETCC_INVALID) 570 setCmpLibcallCC(LC.Op, LC.Cond); 571 } 572 } 573 } 574 575 if (Subtarget->isTargetWindows()) { 576 static const struct { 577 const RTLIB::Libcall Op; 578 const char * const Name; 579 const CallingConv::ID CC; 580 } LibraryCalls[] = { 581 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 582 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 583 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 584 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 585 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 586 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 587 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 588 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 589 }; 590 591 for (const auto &LC : LibraryCalls) { 592 setLibcallName(LC.Op, LC.Name); 593 setLibcallCallingConv(LC.Op, LC.CC); 594 } 595 } 596 597 // Use divmod compiler-rt calls for iOS 5.0 and later. 598 if (Subtarget->isTargetMachO() && 599 !(Subtarget->isTargetIOS() && 600 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 601 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 602 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 603 } 604 605 // The half <-> float conversion functions are always soft-float on 606 // non-watchos platforms, but are needed for some targets which use a 607 // hard-float calling convention by default. 608 if (!Subtarget->isTargetWatchABI()) { 609 if (Subtarget->isAAPCS_ABI()) { 610 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 611 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 612 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 613 } else { 614 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 615 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 616 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 617 } 618 } 619 620 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 621 // a __gnu_ prefix (which is the default). 622 if (Subtarget->isTargetAEABI()) { 623 static const struct { 624 const RTLIB::Libcall Op; 625 const char * const Name; 626 const CallingConv::ID CC; 627 } LibraryCalls[] = { 628 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 629 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 630 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 631 }; 632 633 for (const auto &LC : LibraryCalls) { 634 setLibcallName(LC.Op, LC.Name); 635 setLibcallCallingConv(LC.Op, LC.CC); 636 } 637 } 638 639 if (Subtarget->isThumb1Only()) 640 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 641 else 642 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 643 644 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 645 Subtarget->hasFPRegs()) { 646 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 647 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 648 if (!Subtarget->hasVFP2Base()) 649 setAllExpand(MVT::f32); 650 if (!Subtarget->hasFP64()) 651 setAllExpand(MVT::f64); 652 } 653 654 if (Subtarget->hasFullFP16()) { 655 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 656 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 657 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 658 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 659 660 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 661 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 662 } 663 664 for (MVT VT : MVT::vector_valuetypes()) { 665 for (MVT InnerVT : MVT::vector_valuetypes()) { 666 setTruncStoreAction(VT, InnerVT, Expand); 667 addAllExtLoads(VT, InnerVT, Expand); 668 } 669 670 setOperationAction(ISD::MULHS, VT, Expand); 671 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 672 setOperationAction(ISD::MULHU, VT, Expand); 673 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 674 675 setOperationAction(ISD::BSWAP, VT, Expand); 676 } 677 678 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 679 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 680 681 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 682 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 683 684 if (Subtarget->hasMVEIntegerOps()) 685 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 686 687 // Combine low-overhead loop intrinsics so that we can lower i1 types. 688 if (Subtarget->hasLOB()) { 689 setTargetDAGCombine(ISD::BRCOND); 690 setTargetDAGCombine(ISD::BR_CC); 691 } 692 693 if (Subtarget->hasNEON()) { 694 addDRTypeForNEON(MVT::v2f32); 695 addDRTypeForNEON(MVT::v8i8); 696 addDRTypeForNEON(MVT::v4i16); 697 addDRTypeForNEON(MVT::v2i32); 698 addDRTypeForNEON(MVT::v1i64); 699 700 addQRTypeForNEON(MVT::v4f32); 701 addQRTypeForNEON(MVT::v2f64); 702 addQRTypeForNEON(MVT::v16i8); 703 addQRTypeForNEON(MVT::v8i16); 704 addQRTypeForNEON(MVT::v4i32); 705 addQRTypeForNEON(MVT::v2i64); 706 707 if (Subtarget->hasFullFP16()) { 708 addQRTypeForNEON(MVT::v8f16); 709 addDRTypeForNEON(MVT::v4f16); 710 } 711 } 712 713 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 714 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 715 // none of Neon, MVE or VFP supports any arithmetic operations on it. 716 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 717 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 718 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 719 // FIXME: Code duplication: FDIV and FREM are expanded always, see 720 // ARMTargetLowering::addTypeForNEON method for details. 721 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 722 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 723 // FIXME: Create unittest. 724 // In another words, find a way when "copysign" appears in DAG with vector 725 // operands. 726 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 727 // FIXME: Code duplication: SETCC has custom operation action, see 728 // ARMTargetLowering::addTypeForNEON method for details. 729 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 730 // FIXME: Create unittest for FNEG and for FABS. 731 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 732 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 733 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 734 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 735 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 736 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 737 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 738 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 739 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 740 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 741 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 742 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 743 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 744 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 745 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 746 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 747 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 748 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 749 } 750 751 if (Subtarget->hasNEON()) { 752 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 753 // supported for v4f32. 754 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 755 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 756 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 757 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 758 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 759 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 760 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 761 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 762 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 763 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 764 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 765 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 766 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 767 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 768 769 // Mark v2f32 intrinsics. 770 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 771 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 772 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 773 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 774 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 775 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 776 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 777 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 778 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 779 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 780 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 781 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 782 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 783 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 784 785 // Neon does not support some operations on v1i64 and v2i64 types. 786 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 787 // Custom handling for some quad-vector types to detect VMULL. 788 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 789 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 790 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 791 // Custom handling for some vector types to avoid expensive expansions 792 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 793 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 794 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 795 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 796 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 797 // a destination type that is wider than the source, and nor does 798 // it have a FP_TO_[SU]INT instruction with a narrower destination than 799 // source. 800 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 801 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 802 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 803 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 804 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 805 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 806 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 807 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 808 809 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 810 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 811 812 // NEON does not have single instruction CTPOP for vectors with element 813 // types wider than 8-bits. However, custom lowering can leverage the 814 // v8i8/v16i8 vcnt instruction. 815 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 816 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 817 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 818 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 819 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 820 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 821 822 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 823 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 824 825 // NEON does not have single instruction CTTZ for vectors. 826 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 827 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 828 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 829 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 830 831 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 832 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 833 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 834 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 835 836 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 838 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 839 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 840 841 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 842 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 843 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 844 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 845 846 // NEON only has FMA instructions as of VFP4. 847 if (!Subtarget->hasVFP4Base()) { 848 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 849 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 850 } 851 852 setTargetDAGCombine(ISD::INTRINSIC_VOID); 853 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 854 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 855 setTargetDAGCombine(ISD::SHL); 856 setTargetDAGCombine(ISD::SRL); 857 setTargetDAGCombine(ISD::SRA); 858 setTargetDAGCombine(ISD::SIGN_EXTEND); 859 setTargetDAGCombine(ISD::ZERO_EXTEND); 860 setTargetDAGCombine(ISD::ANY_EXTEND); 861 setTargetDAGCombine(ISD::STORE); 862 setTargetDAGCombine(ISD::FP_TO_SINT); 863 setTargetDAGCombine(ISD::FP_TO_UINT); 864 setTargetDAGCombine(ISD::FDIV); 865 setTargetDAGCombine(ISD::LOAD); 866 867 // It is legal to extload from v4i8 to v4i16 or v4i32. 868 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 869 MVT::v2i32}) { 870 for (MVT VT : MVT::integer_vector_valuetypes()) { 871 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 872 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 873 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 874 } 875 } 876 } 877 878 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 879 setTargetDAGCombine(ISD::BUILD_VECTOR); 880 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 881 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 882 } 883 884 if (!Subtarget->hasFP64()) { 885 // When targeting a floating-point unit with only single-precision 886 // operations, f64 is legal for the few double-precision instructions which 887 // are present However, no double-precision operations other than moves, 888 // loads and stores are provided by the hardware. 889 setOperationAction(ISD::FADD, MVT::f64, Expand); 890 setOperationAction(ISD::FSUB, MVT::f64, Expand); 891 setOperationAction(ISD::FMUL, MVT::f64, Expand); 892 setOperationAction(ISD::FMA, MVT::f64, Expand); 893 setOperationAction(ISD::FDIV, MVT::f64, Expand); 894 setOperationAction(ISD::FREM, MVT::f64, Expand); 895 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 896 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 897 setOperationAction(ISD::FNEG, MVT::f64, Expand); 898 setOperationAction(ISD::FABS, MVT::f64, Expand); 899 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 900 setOperationAction(ISD::FSIN, MVT::f64, Expand); 901 setOperationAction(ISD::FCOS, MVT::f64, Expand); 902 setOperationAction(ISD::FPOW, MVT::f64, Expand); 903 setOperationAction(ISD::FLOG, MVT::f64, Expand); 904 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 905 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 906 setOperationAction(ISD::FEXP, MVT::f64, Expand); 907 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 908 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 909 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 910 setOperationAction(ISD::FRINT, MVT::f64, Expand); 911 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 912 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 913 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 914 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 915 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 916 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 917 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 918 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 919 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 920 } 921 922 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) { 923 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 924 if (Subtarget->hasFullFP16()) 925 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 926 } 927 928 if (!Subtarget->hasFP16()) 929 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 930 931 if (!Subtarget->hasFP64()) 932 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 933 934 computeRegisterProperties(Subtarget->getRegisterInfo()); 935 936 // ARM does not have floating-point extending loads. 937 for (MVT VT : MVT::fp_valuetypes()) { 938 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 939 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 940 } 941 942 // ... or truncating stores 943 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 944 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 945 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 946 947 // ARM does not have i1 sign extending load. 948 for (MVT VT : MVT::integer_valuetypes()) 949 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 950 951 // ARM supports all 4 flavors of integer indexed load / store. 952 if (!Subtarget->isThumb1Only()) { 953 for (unsigned im = (unsigned)ISD::PRE_INC; 954 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 955 setIndexedLoadAction(im, MVT::i1, Legal); 956 setIndexedLoadAction(im, MVT::i8, Legal); 957 setIndexedLoadAction(im, MVT::i16, Legal); 958 setIndexedLoadAction(im, MVT::i32, Legal); 959 setIndexedStoreAction(im, MVT::i1, Legal); 960 setIndexedStoreAction(im, MVT::i8, Legal); 961 setIndexedStoreAction(im, MVT::i16, Legal); 962 setIndexedStoreAction(im, MVT::i32, Legal); 963 } 964 } else { 965 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 966 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 967 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 968 } 969 970 setOperationAction(ISD::SADDO, MVT::i32, Custom); 971 setOperationAction(ISD::UADDO, MVT::i32, Custom); 972 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 973 setOperationAction(ISD::USUBO, MVT::i32, Custom); 974 975 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 976 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 977 978 // i64 operation support. 979 setOperationAction(ISD::MUL, MVT::i64, Expand); 980 setOperationAction(ISD::MULHU, MVT::i32, Expand); 981 if (Subtarget->isThumb1Only()) { 982 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 983 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 984 } 985 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 986 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 987 setOperationAction(ISD::MULHS, MVT::i32, Expand); 988 989 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 990 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 991 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 992 setOperationAction(ISD::SRL, MVT::i64, Custom); 993 setOperationAction(ISD::SRA, MVT::i64, Custom); 994 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 995 996 // MVE lowers 64 bit shifts to lsll and lsrl 997 // assuming that ISD::SRL and SRA of i64 are already marked custom 998 if (Subtarget->hasMVEIntegerOps()) 999 setOperationAction(ISD::SHL, MVT::i64, Custom); 1000 1001 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 1002 if (Subtarget->isThumb1Only()) { 1003 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 1004 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 1005 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 1006 } 1007 1008 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 1009 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 1010 1011 // ARM does not have ROTL. 1012 setOperationAction(ISD::ROTL, MVT::i32, Expand); 1013 for (MVT VT : MVT::vector_valuetypes()) { 1014 setOperationAction(ISD::ROTL, VT, Expand); 1015 setOperationAction(ISD::ROTR, VT, Expand); 1016 } 1017 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 1018 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1019 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 1020 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 1021 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 1022 } 1023 1024 // @llvm.readcyclecounter requires the Performance Monitors extension. 1025 // Default to the 0 expansion on unsupported platforms. 1026 // FIXME: Technically there are older ARM CPUs that have 1027 // implementation-specific ways of obtaining this information. 1028 if (Subtarget->hasPerfMon()) 1029 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 1030 1031 // Only ARMv6 has BSWAP. 1032 if (!Subtarget->hasV6Ops()) 1033 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 1034 1035 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 1036 : Subtarget->hasDivideInARMMode(); 1037 if (!hasDivide) { 1038 // These are expanded into libcalls if the cpu doesn't have HW divider. 1039 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 1040 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 1041 } 1042 1043 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 1044 setOperationAction(ISD::SDIV, MVT::i32, Custom); 1045 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1046 1047 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1048 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1049 } 1050 1051 setOperationAction(ISD::SREM, MVT::i32, Expand); 1052 setOperationAction(ISD::UREM, MVT::i32, Expand); 1053 1054 // Register based DivRem for AEABI (RTABI 4.2) 1055 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1056 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1057 Subtarget->isTargetWindows()) { 1058 setOperationAction(ISD::SREM, MVT::i64, Custom); 1059 setOperationAction(ISD::UREM, MVT::i64, Custom); 1060 HasStandaloneRem = false; 1061 1062 if (Subtarget->isTargetWindows()) { 1063 const struct { 1064 const RTLIB::Libcall Op; 1065 const char * const Name; 1066 const CallingConv::ID CC; 1067 } LibraryCalls[] = { 1068 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1069 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1070 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1071 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1072 1073 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1074 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1075 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1076 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1077 }; 1078 1079 for (const auto &LC : LibraryCalls) { 1080 setLibcallName(LC.Op, LC.Name); 1081 setLibcallCallingConv(LC.Op, LC.CC); 1082 } 1083 } else { 1084 const struct { 1085 const RTLIB::Libcall Op; 1086 const char * const Name; 1087 const CallingConv::ID CC; 1088 } LibraryCalls[] = { 1089 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1090 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1091 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1092 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1093 1094 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1095 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1096 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1097 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1098 }; 1099 1100 for (const auto &LC : LibraryCalls) { 1101 setLibcallName(LC.Op, LC.Name); 1102 setLibcallCallingConv(LC.Op, LC.CC); 1103 } 1104 } 1105 1106 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1107 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1108 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1109 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1110 } else { 1111 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1112 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1113 } 1114 1115 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 1116 for (auto &VT : {MVT::f32, MVT::f64}) 1117 setOperationAction(ISD::FPOWI, VT, Custom); 1118 1119 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1120 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1121 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1122 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1123 1124 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1125 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1126 1127 // Use the default implementation. 1128 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1129 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1130 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1131 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1132 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1133 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1134 1135 if (Subtarget->isTargetWindows()) 1136 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1137 else 1138 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1139 1140 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1141 // the default expansion. 1142 InsertFencesForAtomic = false; 1143 if (Subtarget->hasAnyDataBarrier() && 1144 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1145 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1146 // to ldrex/strex loops already. 1147 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1148 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1149 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1150 1151 // On v8, we have particularly efficient implementations of atomic fences 1152 // if they can be combined with nearby atomic loads and stores. 1153 if (!Subtarget->hasAcquireRelease() || 1154 getTargetMachine().getOptLevel() == 0) { 1155 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1156 InsertFencesForAtomic = true; 1157 } 1158 } else { 1159 // If there's anything we can use as a barrier, go through custom lowering 1160 // for ATOMIC_FENCE. 1161 // If target has DMB in thumb, Fences can be inserted. 1162 if (Subtarget->hasDataBarrier()) 1163 InsertFencesForAtomic = true; 1164 1165 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1166 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1167 1168 // Set them all for expansion, which will force libcalls. 1169 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1170 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1171 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1172 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1173 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1174 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1175 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1176 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1177 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1178 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1179 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1180 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1181 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1182 // Unordered/Monotonic case. 1183 if (!InsertFencesForAtomic) { 1184 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1185 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1186 } 1187 } 1188 1189 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1190 1191 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1192 if (!Subtarget->hasV6Ops()) { 1193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1195 } 1196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1197 1198 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1199 !Subtarget->isThumb1Only()) { 1200 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1201 // iff target supports vfp2. 1202 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1203 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1204 } 1205 1206 // We want to custom lower some of our intrinsics. 1207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1208 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1209 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1210 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1211 if (Subtarget->useSjLjEH()) 1212 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1213 1214 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1215 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1216 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1217 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1218 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1219 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1220 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1221 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1222 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1223 if (Subtarget->hasFullFP16()) { 1224 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1225 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1226 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1227 } 1228 1229 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1230 1231 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1232 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1233 if (Subtarget->hasFullFP16()) 1234 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1235 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1236 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1237 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1238 1239 // We don't support sin/cos/fmod/copysign/pow 1240 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1241 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1242 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1243 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1244 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1245 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1246 setOperationAction(ISD::FREM, MVT::f64, Expand); 1247 setOperationAction(ISD::FREM, MVT::f32, Expand); 1248 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1249 !Subtarget->isThumb1Only()) { 1250 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1251 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1252 } 1253 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1254 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1255 1256 if (!Subtarget->hasVFP4Base()) { 1257 setOperationAction(ISD::FMA, MVT::f64, Expand); 1258 setOperationAction(ISD::FMA, MVT::f32, Expand); 1259 } 1260 1261 // Various VFP goodness 1262 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1263 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1264 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1265 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1266 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1267 } 1268 1269 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1270 if (!Subtarget->hasFP16()) { 1271 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1272 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1273 } 1274 } 1275 1276 // Use __sincos_stret if available. 1277 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1278 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1279 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1280 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1281 } 1282 1283 // FP-ARMv8 implements a lot of rounding-like FP operations. 1284 if (Subtarget->hasFPARMv8Base()) { 1285 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1286 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1287 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1288 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1289 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1290 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1291 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1292 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1293 if (Subtarget->hasNEON()) { 1294 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1295 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1296 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1297 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1298 } 1299 1300 if (Subtarget->hasFP64()) { 1301 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1302 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1303 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1304 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1305 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1306 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1307 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1308 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1309 } 1310 } 1311 1312 // FP16 often need to be promoted to call lib functions 1313 if (Subtarget->hasFullFP16()) { 1314 setOperationAction(ISD::FREM, MVT::f16, Promote); 1315 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1316 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1317 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1318 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1319 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1320 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1321 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1322 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1323 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1324 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1325 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1326 1327 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1328 } 1329 1330 if (Subtarget->hasNEON()) { 1331 // vmin and vmax aren't available in a scalar form, so we use 1332 // a NEON instruction with an undef lane instead. 1333 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1334 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1335 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1336 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1337 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1338 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1339 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1340 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1341 1342 if (Subtarget->hasFullFP16()) { 1343 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1344 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1345 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1346 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1347 1348 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1349 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1350 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1351 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1352 } 1353 } 1354 1355 // We have target-specific dag combine patterns for the following nodes: 1356 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1357 setTargetDAGCombine(ISD::ADD); 1358 setTargetDAGCombine(ISD::SUB); 1359 setTargetDAGCombine(ISD::MUL); 1360 setTargetDAGCombine(ISD::AND); 1361 setTargetDAGCombine(ISD::OR); 1362 setTargetDAGCombine(ISD::XOR); 1363 1364 if (Subtarget->hasV6Ops()) 1365 setTargetDAGCombine(ISD::SRL); 1366 if (Subtarget->isThumb1Only()) 1367 setTargetDAGCombine(ISD::SHL); 1368 1369 setStackPointerRegisterToSaveRestore(ARM::SP); 1370 1371 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1372 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1373 setSchedulingPreference(Sched::RegPressure); 1374 else 1375 setSchedulingPreference(Sched::Hybrid); 1376 1377 //// temporary - rewrite interface to use type 1378 MaxStoresPerMemset = 8; 1379 MaxStoresPerMemsetOptSize = 4; 1380 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1381 MaxStoresPerMemcpyOptSize = 2; 1382 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1383 MaxStoresPerMemmoveOptSize = 2; 1384 1385 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1386 // are at least 4 bytes aligned. 1387 setMinStackArgumentAlignment(4); 1388 1389 // Prefer likely predicted branches to selects on out-of-order cores. 1390 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1391 1392 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment()); 1393 1394 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1395 1396 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1397 setTargetDAGCombine(ISD::ABS); 1398 } 1399 1400 bool ARMTargetLowering::useSoftFloat() const { 1401 return Subtarget->useSoftFloat(); 1402 } 1403 1404 // FIXME: It might make sense to define the representative register class as the 1405 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1406 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1407 // SPR's representative would be DPR_VFP2. This should work well if register 1408 // pressure tracking were modified such that a register use would increment the 1409 // pressure of the register class's representative and all of it's super 1410 // classes' representatives transitively. We have not implemented this because 1411 // of the difficulty prior to coalescing of modeling operand register classes 1412 // due to the common occurrence of cross class copies and subregister insertions 1413 // and extractions. 1414 std::pair<const TargetRegisterClass *, uint8_t> 1415 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1416 MVT VT) const { 1417 const TargetRegisterClass *RRC = nullptr; 1418 uint8_t Cost = 1; 1419 switch (VT.SimpleTy) { 1420 default: 1421 return TargetLowering::findRepresentativeClass(TRI, VT); 1422 // Use DPR as representative register class for all floating point 1423 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1424 // the cost is 1 for both f32 and f64. 1425 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1426 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1427 RRC = &ARM::DPRRegClass; 1428 // When NEON is used for SP, only half of the register file is available 1429 // because operations that define both SP and DP results will be constrained 1430 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1431 // coalescing by double-counting the SP regs. See the FIXME above. 1432 if (Subtarget->useNEONForSinglePrecisionFP()) 1433 Cost = 2; 1434 break; 1435 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1436 case MVT::v4f32: case MVT::v2f64: 1437 RRC = &ARM::DPRRegClass; 1438 Cost = 2; 1439 break; 1440 case MVT::v4i64: 1441 RRC = &ARM::DPRRegClass; 1442 Cost = 4; 1443 break; 1444 case MVT::v8i64: 1445 RRC = &ARM::DPRRegClass; 1446 Cost = 8; 1447 break; 1448 } 1449 return std::make_pair(RRC, Cost); 1450 } 1451 1452 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1453 switch ((ARMISD::NodeType)Opcode) { 1454 case ARMISD::FIRST_NUMBER: break; 1455 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1456 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1457 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1458 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1459 case ARMISD::CALL: return "ARMISD::CALL"; 1460 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1461 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1462 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1463 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1464 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1465 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1466 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1467 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1468 case ARMISD::CMP: return "ARMISD::CMP"; 1469 case ARMISD::CMN: return "ARMISD::CMN"; 1470 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1471 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1472 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1473 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1474 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1475 1476 case ARMISD::CMOV: return "ARMISD::CMOV"; 1477 case ARMISD::SUBS: return "ARMISD::SUBS"; 1478 1479 case ARMISD::SSAT: return "ARMISD::SSAT"; 1480 case ARMISD::USAT: return "ARMISD::USAT"; 1481 1482 case ARMISD::ASRL: return "ARMISD::ASRL"; 1483 case ARMISD::LSRL: return "ARMISD::LSRL"; 1484 case ARMISD::LSLL: return "ARMISD::LSLL"; 1485 1486 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1487 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1488 case ARMISD::RRX: return "ARMISD::RRX"; 1489 1490 case ARMISD::ADDC: return "ARMISD::ADDC"; 1491 case ARMISD::ADDE: return "ARMISD::ADDE"; 1492 case ARMISD::SUBC: return "ARMISD::SUBC"; 1493 case ARMISD::SUBE: return "ARMISD::SUBE"; 1494 case ARMISD::LSLS: return "ARMISD::LSLS"; 1495 1496 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1497 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1498 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1499 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1500 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1501 1502 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1503 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1504 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1505 1506 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1507 1508 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1509 1510 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1511 1512 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1513 1514 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1515 1516 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1517 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1518 1519 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST"; 1520 case ARMISD::VCMP: return "ARMISD::VCMP"; 1521 case ARMISD::VCMPZ: return "ARMISD::VCMPZ"; 1522 case ARMISD::VTST: return "ARMISD::VTST"; 1523 1524 case ARMISD::VSHLs: return "ARMISD::VSHLs"; 1525 case ARMISD::VSHLu: return "ARMISD::VSHLu"; 1526 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM"; 1527 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM"; 1528 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM"; 1529 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM"; 1530 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM"; 1531 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM"; 1532 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM"; 1533 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM"; 1534 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM"; 1535 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM"; 1536 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM"; 1537 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM"; 1538 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM"; 1539 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM"; 1540 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM"; 1541 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM"; 1542 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM"; 1543 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1544 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1545 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1546 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1547 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1548 case ARMISD::VDUP: return "ARMISD::VDUP"; 1549 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1550 case ARMISD::VEXT: return "ARMISD::VEXT"; 1551 case ARMISD::VREV64: return "ARMISD::VREV64"; 1552 case ARMISD::VREV32: return "ARMISD::VREV32"; 1553 case ARMISD::VREV16: return "ARMISD::VREV16"; 1554 case ARMISD::VZIP: return "ARMISD::VZIP"; 1555 case ARMISD::VUZP: return "ARMISD::VUZP"; 1556 case ARMISD::VTRN: return "ARMISD::VTRN"; 1557 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1558 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1559 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1560 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1561 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1562 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1563 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1564 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1565 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1566 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1567 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1568 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1569 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1570 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1571 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1572 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1573 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1574 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1575 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1576 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1577 case ARMISD::BFI: return "ARMISD::BFI"; 1578 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1579 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1580 case ARMISD::VBSL: return "ARMISD::VBSL"; 1581 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1582 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1583 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1584 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1585 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1586 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1587 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1588 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1589 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1590 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1591 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1592 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1593 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1594 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1595 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1596 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1597 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1598 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1599 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1600 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1601 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1602 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1603 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1604 case ARMISD::WLS: return "ARMISD::WLS"; 1605 case ARMISD::LE: return "ARMISD::LE"; 1606 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC"; 1607 } 1608 return nullptr; 1609 } 1610 1611 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1612 EVT VT) const { 1613 if (!VT.isVector()) 1614 return getPointerTy(DL); 1615 1616 // MVE has a predicate register. 1617 if (Subtarget->hasMVEIntegerOps() && 1618 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) 1619 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1620 return VT.changeVectorElementTypeToInteger(); 1621 } 1622 1623 /// getRegClassFor - Return the register class that should be used for the 1624 /// specified value type. 1625 const TargetRegisterClass * 1626 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1627 (void)isDivergent; 1628 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1629 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1630 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1631 // MVE Q registers. 1632 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1633 if (VT == MVT::v4i64) 1634 return &ARM::QQPRRegClass; 1635 if (VT == MVT::v8i64) 1636 return &ARM::QQQQPRRegClass; 1637 } 1638 return TargetLowering::getRegClassFor(VT); 1639 } 1640 1641 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1642 // source/dest is aligned and the copy size is large enough. We therefore want 1643 // to align such objects passed to memory intrinsics. 1644 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1645 unsigned &PrefAlign) const { 1646 if (!isa<MemIntrinsic>(CI)) 1647 return false; 1648 MinSize = 8; 1649 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1650 // cycle faster than 4-byte aligned LDM. 1651 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1652 return true; 1653 } 1654 1655 // Create a fast isel object. 1656 FastISel * 1657 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1658 const TargetLibraryInfo *libInfo) const { 1659 return ARM::createFastISel(funcInfo, libInfo); 1660 } 1661 1662 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1663 unsigned NumVals = N->getNumValues(); 1664 if (!NumVals) 1665 return Sched::RegPressure; 1666 1667 for (unsigned i = 0; i != NumVals; ++i) { 1668 EVT VT = N->getValueType(i); 1669 if (VT == MVT::Glue || VT == MVT::Other) 1670 continue; 1671 if (VT.isFloatingPoint() || VT.isVector()) 1672 return Sched::ILP; 1673 } 1674 1675 if (!N->isMachineOpcode()) 1676 return Sched::RegPressure; 1677 1678 // Load are scheduled for latency even if there instruction itinerary 1679 // is not available. 1680 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1681 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1682 1683 if (MCID.getNumDefs() == 0) 1684 return Sched::RegPressure; 1685 if (!Itins->isEmpty() && 1686 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1687 return Sched::ILP; 1688 1689 return Sched::RegPressure; 1690 } 1691 1692 //===----------------------------------------------------------------------===// 1693 // Lowering Code 1694 //===----------------------------------------------------------------------===// 1695 1696 static bool isSRL16(const SDValue &Op) { 1697 if (Op.getOpcode() != ISD::SRL) 1698 return false; 1699 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1700 return Const->getZExtValue() == 16; 1701 return false; 1702 } 1703 1704 static bool isSRA16(const SDValue &Op) { 1705 if (Op.getOpcode() != ISD::SRA) 1706 return false; 1707 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1708 return Const->getZExtValue() == 16; 1709 return false; 1710 } 1711 1712 static bool isSHL16(const SDValue &Op) { 1713 if (Op.getOpcode() != ISD::SHL) 1714 return false; 1715 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1716 return Const->getZExtValue() == 16; 1717 return false; 1718 } 1719 1720 // Check for a signed 16-bit value. We special case SRA because it makes it 1721 // more simple when also looking for SRAs that aren't sign extending a 1722 // smaller value. Without the check, we'd need to take extra care with 1723 // checking order for some operations. 1724 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1725 if (isSRA16(Op)) 1726 return isSHL16(Op.getOperand(0)); 1727 return DAG.ComputeNumSignBits(Op) == 17; 1728 } 1729 1730 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1731 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1732 switch (CC) { 1733 default: llvm_unreachable("Unknown condition code!"); 1734 case ISD::SETNE: return ARMCC::NE; 1735 case ISD::SETEQ: return ARMCC::EQ; 1736 case ISD::SETGT: return ARMCC::GT; 1737 case ISD::SETGE: return ARMCC::GE; 1738 case ISD::SETLT: return ARMCC::LT; 1739 case ISD::SETLE: return ARMCC::LE; 1740 case ISD::SETUGT: return ARMCC::HI; 1741 case ISD::SETUGE: return ARMCC::HS; 1742 case ISD::SETULT: return ARMCC::LO; 1743 case ISD::SETULE: return ARMCC::LS; 1744 } 1745 } 1746 1747 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1748 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1749 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1750 CondCode2 = ARMCC::AL; 1751 InvalidOnQNaN = true; 1752 switch (CC) { 1753 default: llvm_unreachable("Unknown FP condition!"); 1754 case ISD::SETEQ: 1755 case ISD::SETOEQ: 1756 CondCode = ARMCC::EQ; 1757 InvalidOnQNaN = false; 1758 break; 1759 case ISD::SETGT: 1760 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1761 case ISD::SETGE: 1762 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1763 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1764 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1765 case ISD::SETONE: 1766 CondCode = ARMCC::MI; 1767 CondCode2 = ARMCC::GT; 1768 InvalidOnQNaN = false; 1769 break; 1770 case ISD::SETO: CondCode = ARMCC::VC; break; 1771 case ISD::SETUO: CondCode = ARMCC::VS; break; 1772 case ISD::SETUEQ: 1773 CondCode = ARMCC::EQ; 1774 CondCode2 = ARMCC::VS; 1775 InvalidOnQNaN = false; 1776 break; 1777 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1778 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1779 case ISD::SETLT: 1780 case ISD::SETULT: CondCode = ARMCC::LT; break; 1781 case ISD::SETLE: 1782 case ISD::SETULE: CondCode = ARMCC::LE; break; 1783 case ISD::SETNE: 1784 case ISD::SETUNE: 1785 CondCode = ARMCC::NE; 1786 InvalidOnQNaN = false; 1787 break; 1788 } 1789 } 1790 1791 //===----------------------------------------------------------------------===// 1792 // Calling Convention Implementation 1793 //===----------------------------------------------------------------------===// 1794 1795 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1796 /// account presence of floating point hardware and calling convention 1797 /// limitations, such as support for variadic functions. 1798 CallingConv::ID 1799 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1800 bool isVarArg) const { 1801 switch (CC) { 1802 default: 1803 report_fatal_error("Unsupported calling convention"); 1804 case CallingConv::ARM_AAPCS: 1805 case CallingConv::ARM_APCS: 1806 case CallingConv::GHC: 1807 return CC; 1808 case CallingConv::PreserveMost: 1809 return CallingConv::PreserveMost; 1810 case CallingConv::ARM_AAPCS_VFP: 1811 case CallingConv::Swift: 1812 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1813 case CallingConv::C: 1814 if (!Subtarget->isAAPCS_ABI()) 1815 return CallingConv::ARM_APCS; 1816 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1817 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1818 !isVarArg) 1819 return CallingConv::ARM_AAPCS_VFP; 1820 else 1821 return CallingConv::ARM_AAPCS; 1822 case CallingConv::Fast: 1823 case CallingConv::CXX_FAST_TLS: 1824 if (!Subtarget->isAAPCS_ABI()) { 1825 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 1826 return CallingConv::Fast; 1827 return CallingConv::ARM_APCS; 1828 } else if (Subtarget->hasVFP2Base() && 1829 !Subtarget->isThumb1Only() && !isVarArg) 1830 return CallingConv::ARM_AAPCS_VFP; 1831 else 1832 return CallingConv::ARM_AAPCS; 1833 } 1834 } 1835 1836 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1837 bool isVarArg) const { 1838 return CCAssignFnForNode(CC, false, isVarArg); 1839 } 1840 1841 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1842 bool isVarArg) const { 1843 return CCAssignFnForNode(CC, true, isVarArg); 1844 } 1845 1846 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1847 /// CallingConvention. 1848 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1849 bool Return, 1850 bool isVarArg) const { 1851 switch (getEffectiveCallingConv(CC, isVarArg)) { 1852 default: 1853 report_fatal_error("Unsupported calling convention"); 1854 case CallingConv::ARM_APCS: 1855 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1856 case CallingConv::ARM_AAPCS: 1857 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1858 case CallingConv::ARM_AAPCS_VFP: 1859 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1860 case CallingConv::Fast: 1861 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1862 case CallingConv::GHC: 1863 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1864 case CallingConv::PreserveMost: 1865 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1866 } 1867 } 1868 1869 /// LowerCallResult - Lower the result values of a call into the 1870 /// appropriate copies out of appropriate physical registers. 1871 SDValue ARMTargetLowering::LowerCallResult( 1872 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1873 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1874 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1875 SDValue ThisVal) const { 1876 // Assign locations to each value returned by this call. 1877 SmallVector<CCValAssign, 16> RVLocs; 1878 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1879 *DAG.getContext()); 1880 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1881 1882 // Copy all of the result registers out of their specified physreg. 1883 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1884 CCValAssign VA = RVLocs[i]; 1885 1886 // Pass 'this' value directly from the argument to return value, to avoid 1887 // reg unit interference 1888 if (i == 0 && isThisReturn) { 1889 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1890 "unexpected return calling convention register assignment"); 1891 InVals.push_back(ThisVal); 1892 continue; 1893 } 1894 1895 SDValue Val; 1896 if (VA.needsCustom()) { 1897 // Handle f64 or half of a v2f64. 1898 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1899 InFlag); 1900 Chain = Lo.getValue(1); 1901 InFlag = Lo.getValue(2); 1902 VA = RVLocs[++i]; // skip ahead to next loc 1903 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1904 InFlag); 1905 Chain = Hi.getValue(1); 1906 InFlag = Hi.getValue(2); 1907 if (!Subtarget->isLittle()) 1908 std::swap (Lo, Hi); 1909 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1910 1911 if (VA.getLocVT() == MVT::v2f64) { 1912 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1913 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1914 DAG.getConstant(0, dl, MVT::i32)); 1915 1916 VA = RVLocs[++i]; // skip ahead to next loc 1917 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1918 Chain = Lo.getValue(1); 1919 InFlag = Lo.getValue(2); 1920 VA = RVLocs[++i]; // skip ahead to next loc 1921 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1922 Chain = Hi.getValue(1); 1923 InFlag = Hi.getValue(2); 1924 if (!Subtarget->isLittle()) 1925 std::swap (Lo, Hi); 1926 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1927 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1928 DAG.getConstant(1, dl, MVT::i32)); 1929 } 1930 } else { 1931 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1932 InFlag); 1933 Chain = Val.getValue(1); 1934 InFlag = Val.getValue(2); 1935 } 1936 1937 switch (VA.getLocInfo()) { 1938 default: llvm_unreachable("Unknown loc info!"); 1939 case CCValAssign::Full: break; 1940 case CCValAssign::BCvt: 1941 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1942 break; 1943 } 1944 1945 InVals.push_back(Val); 1946 } 1947 1948 return Chain; 1949 } 1950 1951 /// LowerMemOpCallTo - Store the argument to the stack. 1952 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1953 SDValue Arg, const SDLoc &dl, 1954 SelectionDAG &DAG, 1955 const CCValAssign &VA, 1956 ISD::ArgFlagsTy Flags) const { 1957 unsigned LocMemOffset = VA.getLocMemOffset(); 1958 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1959 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1960 StackPtr, PtrOff); 1961 return DAG.getStore( 1962 Chain, dl, Arg, PtrOff, 1963 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1964 } 1965 1966 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1967 SDValue Chain, SDValue &Arg, 1968 RegsToPassVector &RegsToPass, 1969 CCValAssign &VA, CCValAssign &NextVA, 1970 SDValue &StackPtr, 1971 SmallVectorImpl<SDValue> &MemOpChains, 1972 ISD::ArgFlagsTy Flags) const { 1973 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1974 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1975 unsigned id = Subtarget->isLittle() ? 0 : 1; 1976 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1977 1978 if (NextVA.isRegLoc()) 1979 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1980 else { 1981 assert(NextVA.isMemLoc()); 1982 if (!StackPtr.getNode()) 1983 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1984 getPointerTy(DAG.getDataLayout())); 1985 1986 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1987 dl, DAG, NextVA, 1988 Flags)); 1989 } 1990 } 1991 1992 /// LowerCall - Lowering a call into a callseq_start <- 1993 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1994 /// nodes. 1995 SDValue 1996 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1997 SmallVectorImpl<SDValue> &InVals) const { 1998 SelectionDAG &DAG = CLI.DAG; 1999 SDLoc &dl = CLI.DL; 2000 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2001 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2002 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2003 SDValue Chain = CLI.Chain; 2004 SDValue Callee = CLI.Callee; 2005 bool &isTailCall = CLI.IsTailCall; 2006 CallingConv::ID CallConv = CLI.CallConv; 2007 bool doesNotRet = CLI.DoesNotReturn; 2008 bool isVarArg = CLI.IsVarArg; 2009 2010 MachineFunction &MF = DAG.getMachineFunction(); 2011 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2012 bool isThisReturn = false; 2013 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 2014 bool PreferIndirect = false; 2015 2016 // Disable tail calls if they're not supported. 2017 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 2018 isTailCall = false; 2019 2020 if (isa<GlobalAddressSDNode>(Callee)) { 2021 // If we're optimizing for minimum size and the function is called three or 2022 // more times in this block, we can improve codesize by calling indirectly 2023 // as BLXr has a 16-bit encoding. 2024 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2025 if (CLI.CS) { 2026 auto *BB = CLI.CS.getParent(); 2027 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() && 2028 count_if(GV->users(), [&BB](const User *U) { 2029 return isa<Instruction>(U) && 2030 cast<Instruction>(U)->getParent() == BB; 2031 }) > 2; 2032 } 2033 } 2034 if (isTailCall) { 2035 // Check if it's really possible to do a tail call. 2036 isTailCall = IsEligibleForTailCallOptimization( 2037 Callee, CallConv, isVarArg, isStructRet, 2038 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 2039 PreferIndirect); 2040 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 2041 report_fatal_error("failed to perform tail call elimination on a call " 2042 "site marked musttail"); 2043 // We don't support GuaranteedTailCallOpt for ARM, only automatically 2044 // detected sibcalls. 2045 if (isTailCall) 2046 ++NumTailCalls; 2047 } 2048 2049 // Analyze operands of the call, assigning locations to each operand. 2050 SmallVector<CCValAssign, 16> ArgLocs; 2051 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2052 *DAG.getContext()); 2053 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2054 2055 // Get a count of how many bytes are to be pushed on the stack. 2056 unsigned NumBytes = CCInfo.getNextStackOffset(); 2057 2058 if (isTailCall) { 2059 // For tail calls, memory operands are available in our caller's stack. 2060 NumBytes = 0; 2061 } else { 2062 // Adjust the stack pointer for the new arguments... 2063 // These operations are automatically eliminated by the prolog/epilog pass 2064 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2065 } 2066 2067 SDValue StackPtr = 2068 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2069 2070 RegsToPassVector RegsToPass; 2071 SmallVector<SDValue, 8> MemOpChains; 2072 2073 // Walk the register/memloc assignments, inserting copies/loads. In the case 2074 // of tail call optimization, arguments are handled later. 2075 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2076 i != e; 2077 ++i, ++realArgIdx) { 2078 CCValAssign &VA = ArgLocs[i]; 2079 SDValue Arg = OutVals[realArgIdx]; 2080 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2081 bool isByVal = Flags.isByVal(); 2082 2083 // Promote the value if needed. 2084 switch (VA.getLocInfo()) { 2085 default: llvm_unreachable("Unknown loc info!"); 2086 case CCValAssign::Full: break; 2087 case CCValAssign::SExt: 2088 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2089 break; 2090 case CCValAssign::ZExt: 2091 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2092 break; 2093 case CCValAssign::AExt: 2094 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2095 break; 2096 case CCValAssign::BCvt: 2097 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2098 break; 2099 } 2100 2101 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2102 if (VA.needsCustom()) { 2103 if (VA.getLocVT() == MVT::v2f64) { 2104 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2105 DAG.getConstant(0, dl, MVT::i32)); 2106 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2107 DAG.getConstant(1, dl, MVT::i32)); 2108 2109 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 2110 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2111 2112 VA = ArgLocs[++i]; // skip ahead to next loc 2113 if (VA.isRegLoc()) { 2114 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 2115 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2116 } else { 2117 assert(VA.isMemLoc()); 2118 2119 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 2120 dl, DAG, VA, Flags)); 2121 } 2122 } else { 2123 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2124 StackPtr, MemOpChains, Flags); 2125 } 2126 } else if (VA.isRegLoc()) { 2127 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2128 Outs[0].VT == MVT::i32) { 2129 assert(VA.getLocVT() == MVT::i32 && 2130 "unexpected calling convention register assignment"); 2131 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2132 "unexpected use of 'returned'"); 2133 isThisReturn = true; 2134 } 2135 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2136 } else if (isByVal) { 2137 assert(VA.isMemLoc()); 2138 unsigned offset = 0; 2139 2140 // True if this byval aggregate will be split between registers 2141 // and memory. 2142 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2143 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2144 2145 if (CurByValIdx < ByValArgsCount) { 2146 2147 unsigned RegBegin, RegEnd; 2148 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2149 2150 EVT PtrVT = 2151 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2152 unsigned int i, j; 2153 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2154 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2155 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2156 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 2157 MachinePointerInfo(), 2158 DAG.InferPtrAlignment(AddArg)); 2159 MemOpChains.push_back(Load.getValue(1)); 2160 RegsToPass.push_back(std::make_pair(j, Load)); 2161 } 2162 2163 // If parameter size outsides register area, "offset" value 2164 // helps us to calculate stack slot for remained part properly. 2165 offset = RegEnd - RegBegin; 2166 2167 CCInfo.nextInRegsParam(); 2168 } 2169 2170 if (Flags.getByValSize() > 4*offset) { 2171 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2172 unsigned LocMemOffset = VA.getLocMemOffset(); 2173 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2174 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2175 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2176 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2177 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2178 MVT::i32); 2179 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 2180 MVT::i32); 2181 2182 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2183 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2184 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2185 Ops)); 2186 } 2187 } else if (!isTailCall) { 2188 assert(VA.isMemLoc()); 2189 2190 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2191 dl, DAG, VA, Flags)); 2192 } 2193 } 2194 2195 if (!MemOpChains.empty()) 2196 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2197 2198 // Build a sequence of copy-to-reg nodes chained together with token chain 2199 // and flag operands which copy the outgoing args into the appropriate regs. 2200 SDValue InFlag; 2201 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2202 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2203 RegsToPass[i].second, InFlag); 2204 InFlag = Chain.getValue(1); 2205 } 2206 2207 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2208 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2209 // node so that legalize doesn't hack it. 2210 bool isDirect = false; 2211 2212 const TargetMachine &TM = getTargetMachine(); 2213 const Module *Mod = MF.getFunction().getParent(); 2214 const GlobalValue *GV = nullptr; 2215 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2216 GV = G->getGlobal(); 2217 bool isStub = 2218 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2219 2220 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2221 bool isLocalARMFunc = false; 2222 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2223 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2224 2225 if (Subtarget->genLongCalls()) { 2226 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2227 "long-calls codegen is not position independent!"); 2228 // Handle a global address or an external symbol. If it's not one of 2229 // those, the target's already in a register, so we don't need to do 2230 // anything extra. 2231 if (isa<GlobalAddressSDNode>(Callee)) { 2232 // Create a constant pool entry for the callee address 2233 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2234 ARMConstantPoolValue *CPV = 2235 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2236 2237 // Get the address of the callee into a register 2238 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2239 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2240 Callee = DAG.getLoad( 2241 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2242 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2243 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2244 const char *Sym = S->getSymbol(); 2245 2246 // Create a constant pool entry for the callee address 2247 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2248 ARMConstantPoolValue *CPV = 2249 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2250 ARMPCLabelIndex, 0); 2251 // Get the address of the callee into a register 2252 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2253 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2254 Callee = DAG.getLoad( 2255 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2256 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2257 } 2258 } else if (isa<GlobalAddressSDNode>(Callee)) { 2259 if (!PreferIndirect) { 2260 isDirect = true; 2261 bool isDef = GV->isStrongDefinitionForLinker(); 2262 2263 // ARM call to a local ARM function is predicable. 2264 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2265 // tBX takes a register source operand. 2266 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2267 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2268 Callee = DAG.getNode( 2269 ARMISD::WrapperPIC, dl, PtrVt, 2270 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2271 Callee = DAG.getLoad( 2272 PtrVt, dl, DAG.getEntryNode(), Callee, 2273 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2274 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2275 MachineMemOperand::MOInvariant); 2276 } else if (Subtarget->isTargetCOFF()) { 2277 assert(Subtarget->isTargetWindows() && 2278 "Windows is the only supported COFF target"); 2279 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2280 ? ARMII::MO_DLLIMPORT 2281 : ARMII::MO_NO_FLAG; 2282 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0, 2283 TargetFlags); 2284 if (GV->hasDLLImportStorageClass()) 2285 Callee = 2286 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2287 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2288 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2289 } else { 2290 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2291 } 2292 } 2293 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2294 isDirect = true; 2295 // tBX takes a register source operand. 2296 const char *Sym = S->getSymbol(); 2297 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2298 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2299 ARMConstantPoolValue *CPV = 2300 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2301 ARMPCLabelIndex, 4); 2302 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2303 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2304 Callee = DAG.getLoad( 2305 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2306 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2307 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2308 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2309 } else { 2310 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2311 } 2312 } 2313 2314 // FIXME: handle tail calls differently. 2315 unsigned CallOpc; 2316 if (Subtarget->isThumb()) { 2317 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2318 CallOpc = ARMISD::CALL_NOLINK; 2319 else 2320 CallOpc = ARMISD::CALL; 2321 } else { 2322 if (!isDirect && !Subtarget->hasV5TOps()) 2323 CallOpc = ARMISD::CALL_NOLINK; 2324 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2325 // Emit regular call when code size is the priority 2326 !Subtarget->hasMinSize()) 2327 // "mov lr, pc; b _foo" to avoid confusing the RSP 2328 CallOpc = ARMISD::CALL_NOLINK; 2329 else 2330 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2331 } 2332 2333 std::vector<SDValue> Ops; 2334 Ops.push_back(Chain); 2335 Ops.push_back(Callee); 2336 2337 // Add argument registers to the end of the list so that they are known live 2338 // into the call. 2339 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2340 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2341 RegsToPass[i].second.getValueType())); 2342 2343 // Add a register mask operand representing the call-preserved registers. 2344 if (!isTailCall) { 2345 const uint32_t *Mask; 2346 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2347 if (isThisReturn) { 2348 // For 'this' returns, use the R0-preserving mask if applicable 2349 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2350 if (!Mask) { 2351 // Set isThisReturn to false if the calling convention is not one that 2352 // allows 'returned' to be modeled in this way, so LowerCallResult does 2353 // not try to pass 'this' straight through 2354 isThisReturn = false; 2355 Mask = ARI->getCallPreservedMask(MF, CallConv); 2356 } 2357 } else 2358 Mask = ARI->getCallPreservedMask(MF, CallConv); 2359 2360 assert(Mask && "Missing call preserved mask for calling convention"); 2361 Ops.push_back(DAG.getRegisterMask(Mask)); 2362 } 2363 2364 if (InFlag.getNode()) 2365 Ops.push_back(InFlag); 2366 2367 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2368 if (isTailCall) { 2369 MF.getFrameInfo().setHasTailCall(); 2370 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2371 } 2372 2373 // Returns a chain and a flag for retval copy to use. 2374 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2375 InFlag = Chain.getValue(1); 2376 2377 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2378 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2379 if (!Ins.empty()) 2380 InFlag = Chain.getValue(1); 2381 2382 // Handle result values, copying them out of physregs into vregs that we 2383 // return. 2384 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2385 InVals, isThisReturn, 2386 isThisReturn ? OutVals[0] : SDValue()); 2387 } 2388 2389 /// HandleByVal - Every parameter *after* a byval parameter is passed 2390 /// on the stack. Remember the next parameter register to allocate, 2391 /// and then confiscate the rest of the parameter registers to insure 2392 /// this. 2393 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2394 unsigned Align) const { 2395 // Byval (as with any stack) slots are always at least 4 byte aligned. 2396 Align = std::max(Align, 4U); 2397 2398 unsigned Reg = State->AllocateReg(GPRArgRegs); 2399 if (!Reg) 2400 return; 2401 2402 unsigned AlignInRegs = Align / 4; 2403 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2404 for (unsigned i = 0; i < Waste; ++i) 2405 Reg = State->AllocateReg(GPRArgRegs); 2406 2407 if (!Reg) 2408 return; 2409 2410 unsigned Excess = 4 * (ARM::R4 - Reg); 2411 2412 // Special case when NSAA != SP and parameter size greater than size of 2413 // all remained GPR regs. In that case we can't split parameter, we must 2414 // send it to stack. We also must set NCRN to R4, so waste all 2415 // remained registers. 2416 const unsigned NSAAOffset = State->getNextStackOffset(); 2417 if (NSAAOffset != 0 && Size > Excess) { 2418 while (State->AllocateReg(GPRArgRegs)) 2419 ; 2420 return; 2421 } 2422 2423 // First register for byval parameter is the first register that wasn't 2424 // allocated before this method call, so it would be "reg". 2425 // If parameter is small enough to be saved in range [reg, r4), then 2426 // the end (first after last) register would be reg + param-size-in-regs, 2427 // else parameter would be splitted between registers and stack, 2428 // end register would be r4 in this case. 2429 unsigned ByValRegBegin = Reg; 2430 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2431 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2432 // Note, first register is allocated in the beginning of function already, 2433 // allocate remained amount of registers we need. 2434 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2435 State->AllocateReg(GPRArgRegs); 2436 // A byval parameter that is split between registers and memory needs its 2437 // size truncated here. 2438 // In the case where the entire structure fits in registers, we set the 2439 // size in memory to zero. 2440 Size = std::max<int>(Size - Excess, 0); 2441 } 2442 2443 /// MatchingStackOffset - Return true if the given stack call argument is 2444 /// already available in the same position (relatively) of the caller's 2445 /// incoming argument stack. 2446 static 2447 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2448 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2449 const TargetInstrInfo *TII) { 2450 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2451 int FI = std::numeric_limits<int>::max(); 2452 if (Arg.getOpcode() == ISD::CopyFromReg) { 2453 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2454 if (!Register::isVirtualRegister(VR)) 2455 return false; 2456 MachineInstr *Def = MRI->getVRegDef(VR); 2457 if (!Def) 2458 return false; 2459 if (!Flags.isByVal()) { 2460 if (!TII->isLoadFromStackSlot(*Def, FI)) 2461 return false; 2462 } else { 2463 return false; 2464 } 2465 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2466 if (Flags.isByVal()) 2467 // ByVal argument is passed in as a pointer but it's now being 2468 // dereferenced. e.g. 2469 // define @foo(%struct.X* %A) { 2470 // tail call @bar(%struct.X* byval %A) 2471 // } 2472 return false; 2473 SDValue Ptr = Ld->getBasePtr(); 2474 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2475 if (!FINode) 2476 return false; 2477 FI = FINode->getIndex(); 2478 } else 2479 return false; 2480 2481 assert(FI != std::numeric_limits<int>::max()); 2482 if (!MFI.isFixedObjectIndex(FI)) 2483 return false; 2484 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2485 } 2486 2487 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2488 /// for tail call optimization. Targets which want to do tail call 2489 /// optimization should implement this function. 2490 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2491 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2492 bool isCalleeStructRet, bool isCallerStructRet, 2493 const SmallVectorImpl<ISD::OutputArg> &Outs, 2494 const SmallVectorImpl<SDValue> &OutVals, 2495 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2496 const bool isIndirect) const { 2497 MachineFunction &MF = DAG.getMachineFunction(); 2498 const Function &CallerF = MF.getFunction(); 2499 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2500 2501 assert(Subtarget->supportsTailCall()); 2502 2503 // Indirect tail calls cannot be optimized for Thumb1 if the args 2504 // to the call take up r0-r3. The reason is that there are no legal registers 2505 // left to hold the pointer to the function to be called. 2506 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2507 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2508 return false; 2509 2510 // Look for obvious safe cases to perform tail call optimization that do not 2511 // require ABI changes. This is what gcc calls sibcall. 2512 2513 // Exception-handling functions need a special set of instructions to indicate 2514 // a return to the hardware. Tail-calling another function would probably 2515 // break this. 2516 if (CallerF.hasFnAttribute("interrupt")) 2517 return false; 2518 2519 // Also avoid sibcall optimization if either caller or callee uses struct 2520 // return semantics. 2521 if (isCalleeStructRet || isCallerStructRet) 2522 return false; 2523 2524 // Externally-defined functions with weak linkage should not be 2525 // tail-called on ARM when the OS does not support dynamic 2526 // pre-emption of symbols, as the AAELF spec requires normal calls 2527 // to undefined weak functions to be replaced with a NOP or jump to the 2528 // next instruction. The behaviour of branch instructions in this 2529 // situation (as used for tail calls) is implementation-defined, so we 2530 // cannot rely on the linker replacing the tail call with a return. 2531 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2532 const GlobalValue *GV = G->getGlobal(); 2533 const Triple &TT = getTargetMachine().getTargetTriple(); 2534 if (GV->hasExternalWeakLinkage() && 2535 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2536 return false; 2537 } 2538 2539 // Check that the call results are passed in the same way. 2540 LLVMContext &C = *DAG.getContext(); 2541 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2542 CCAssignFnForReturn(CalleeCC, isVarArg), 2543 CCAssignFnForReturn(CallerCC, isVarArg))) 2544 return false; 2545 // The callee has to preserve all registers the caller needs to preserve. 2546 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2547 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2548 if (CalleeCC != CallerCC) { 2549 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2550 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2551 return false; 2552 } 2553 2554 // If Caller's vararg or byval argument has been split between registers and 2555 // stack, do not perform tail call, since part of the argument is in caller's 2556 // local frame. 2557 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2558 if (AFI_Caller->getArgRegsSaveSize()) 2559 return false; 2560 2561 // If the callee takes no arguments then go on to check the results of the 2562 // call. 2563 if (!Outs.empty()) { 2564 // Check if stack adjustment is needed. For now, do not do this if any 2565 // argument is passed on the stack. 2566 SmallVector<CCValAssign, 16> ArgLocs; 2567 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2568 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2569 if (CCInfo.getNextStackOffset()) { 2570 // Check if the arguments are already laid out in the right way as 2571 // the caller's fixed stack objects. 2572 MachineFrameInfo &MFI = MF.getFrameInfo(); 2573 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2574 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2575 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2576 i != e; 2577 ++i, ++realArgIdx) { 2578 CCValAssign &VA = ArgLocs[i]; 2579 EVT RegVT = VA.getLocVT(); 2580 SDValue Arg = OutVals[realArgIdx]; 2581 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2582 if (VA.getLocInfo() == CCValAssign::Indirect) 2583 return false; 2584 if (VA.needsCustom()) { 2585 // f64 and vector types are split into multiple registers or 2586 // register/stack-slot combinations. The types will not match 2587 // the registers; give up on memory f64 refs until we figure 2588 // out what to do about this. 2589 if (!VA.isRegLoc()) 2590 return false; 2591 if (!ArgLocs[++i].isRegLoc()) 2592 return false; 2593 if (RegVT == MVT::v2f64) { 2594 if (!ArgLocs[++i].isRegLoc()) 2595 return false; 2596 if (!ArgLocs[++i].isRegLoc()) 2597 return false; 2598 } 2599 } else if (!VA.isRegLoc()) { 2600 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2601 MFI, MRI, TII)) 2602 return false; 2603 } 2604 } 2605 } 2606 2607 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2608 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2609 return false; 2610 } 2611 2612 return true; 2613 } 2614 2615 bool 2616 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2617 MachineFunction &MF, bool isVarArg, 2618 const SmallVectorImpl<ISD::OutputArg> &Outs, 2619 LLVMContext &Context) const { 2620 SmallVector<CCValAssign, 16> RVLocs; 2621 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2622 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2623 } 2624 2625 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2626 const SDLoc &DL, SelectionDAG &DAG) { 2627 const MachineFunction &MF = DAG.getMachineFunction(); 2628 const Function &F = MF.getFunction(); 2629 2630 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2631 2632 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2633 // version of the "preferred return address". These offsets affect the return 2634 // instruction if this is a return from PL1 without hypervisor extensions. 2635 // IRQ/FIQ: +4 "subs pc, lr, #4" 2636 // SWI: 0 "subs pc, lr, #0" 2637 // ABORT: +4 "subs pc, lr, #4" 2638 // UNDEF: +4/+2 "subs pc, lr, #0" 2639 // UNDEF varies depending on where the exception came from ARM or Thumb 2640 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2641 2642 int64_t LROffset; 2643 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2644 IntKind == "ABORT") 2645 LROffset = 4; 2646 else if (IntKind == "SWI" || IntKind == "UNDEF") 2647 LROffset = 0; 2648 else 2649 report_fatal_error("Unsupported interrupt attribute. If present, value " 2650 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2651 2652 RetOps.insert(RetOps.begin() + 1, 2653 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2654 2655 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2656 } 2657 2658 SDValue 2659 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2660 bool isVarArg, 2661 const SmallVectorImpl<ISD::OutputArg> &Outs, 2662 const SmallVectorImpl<SDValue> &OutVals, 2663 const SDLoc &dl, SelectionDAG &DAG) const { 2664 // CCValAssign - represent the assignment of the return value to a location. 2665 SmallVector<CCValAssign, 16> RVLocs; 2666 2667 // CCState - Info about the registers and stack slots. 2668 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2669 *DAG.getContext()); 2670 2671 // Analyze outgoing return values. 2672 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2673 2674 SDValue Flag; 2675 SmallVector<SDValue, 4> RetOps; 2676 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2677 bool isLittleEndian = Subtarget->isLittle(); 2678 2679 MachineFunction &MF = DAG.getMachineFunction(); 2680 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2681 AFI->setReturnRegsCount(RVLocs.size()); 2682 2683 // Copy the result values into the output registers. 2684 for (unsigned i = 0, realRVLocIdx = 0; 2685 i != RVLocs.size(); 2686 ++i, ++realRVLocIdx) { 2687 CCValAssign &VA = RVLocs[i]; 2688 assert(VA.isRegLoc() && "Can only return in registers!"); 2689 2690 SDValue Arg = OutVals[realRVLocIdx]; 2691 bool ReturnF16 = false; 2692 2693 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2694 // Half-precision return values can be returned like this: 2695 // 2696 // t11 f16 = fadd ... 2697 // t12: i16 = bitcast t11 2698 // t13: i32 = zero_extend t12 2699 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2700 // 2701 // to avoid code generation for bitcasts, we simply set Arg to the node 2702 // that produces the f16 value, t11 in this case. 2703 // 2704 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2705 SDValue ZE = Arg.getOperand(0); 2706 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2707 SDValue BC = ZE.getOperand(0); 2708 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2709 Arg = BC.getOperand(0); 2710 ReturnF16 = true; 2711 } 2712 } 2713 } 2714 } 2715 2716 switch (VA.getLocInfo()) { 2717 default: llvm_unreachable("Unknown loc info!"); 2718 case CCValAssign::Full: break; 2719 case CCValAssign::BCvt: 2720 if (!ReturnF16) 2721 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2722 break; 2723 } 2724 2725 if (VA.needsCustom()) { 2726 if (VA.getLocVT() == MVT::v2f64) { 2727 // Extract the first half and return it in two registers. 2728 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2729 DAG.getConstant(0, dl, MVT::i32)); 2730 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2731 DAG.getVTList(MVT::i32, MVT::i32), Half); 2732 2733 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2734 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2735 Flag); 2736 Flag = Chain.getValue(1); 2737 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2738 VA = RVLocs[++i]; // skip ahead to next loc 2739 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2740 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2741 Flag); 2742 Flag = Chain.getValue(1); 2743 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2744 VA = RVLocs[++i]; // skip ahead to next loc 2745 2746 // Extract the 2nd half and fall through to handle it as an f64 value. 2747 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2748 DAG.getConstant(1, dl, MVT::i32)); 2749 } 2750 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2751 // available. 2752 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2753 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2754 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2755 fmrrd.getValue(isLittleEndian ? 0 : 1), 2756 Flag); 2757 Flag = Chain.getValue(1); 2758 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2759 VA = RVLocs[++i]; // skip ahead to next loc 2760 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2761 fmrrd.getValue(isLittleEndian ? 1 : 0), 2762 Flag); 2763 } else 2764 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2765 2766 // Guarantee that all emitted copies are 2767 // stuck together, avoiding something bad. 2768 Flag = Chain.getValue(1); 2769 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2770 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2771 } 2772 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2773 const MCPhysReg *I = 2774 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2775 if (I) { 2776 for (; *I; ++I) { 2777 if (ARM::GPRRegClass.contains(*I)) 2778 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2779 else if (ARM::DPRRegClass.contains(*I)) 2780 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2781 else 2782 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2783 } 2784 } 2785 2786 // Update chain and glue. 2787 RetOps[0] = Chain; 2788 if (Flag.getNode()) 2789 RetOps.push_back(Flag); 2790 2791 // CPUs which aren't M-class use a special sequence to return from 2792 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2793 // though we use "subs pc, lr, #N"). 2794 // 2795 // M-class CPUs actually use a normal return sequence with a special 2796 // (hardware-provided) value in LR, so the normal code path works. 2797 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2798 !Subtarget->isMClass()) { 2799 if (Subtarget->isThumb1Only()) 2800 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2801 return LowerInterruptReturn(RetOps, dl, DAG); 2802 } 2803 2804 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2805 } 2806 2807 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2808 if (N->getNumValues() != 1) 2809 return false; 2810 if (!N->hasNUsesOfValue(1, 0)) 2811 return false; 2812 2813 SDValue TCChain = Chain; 2814 SDNode *Copy = *N->use_begin(); 2815 if (Copy->getOpcode() == ISD::CopyToReg) { 2816 // If the copy has a glue operand, we conservatively assume it isn't safe to 2817 // perform a tail call. 2818 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2819 return false; 2820 TCChain = Copy->getOperand(0); 2821 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2822 SDNode *VMov = Copy; 2823 // f64 returned in a pair of GPRs. 2824 SmallPtrSet<SDNode*, 2> Copies; 2825 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2826 UI != UE; ++UI) { 2827 if (UI->getOpcode() != ISD::CopyToReg) 2828 return false; 2829 Copies.insert(*UI); 2830 } 2831 if (Copies.size() > 2) 2832 return false; 2833 2834 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2835 UI != UE; ++UI) { 2836 SDValue UseChain = UI->getOperand(0); 2837 if (Copies.count(UseChain.getNode())) 2838 // Second CopyToReg 2839 Copy = *UI; 2840 else { 2841 // We are at the top of this chain. 2842 // If the copy has a glue operand, we conservatively assume it 2843 // isn't safe to perform a tail call. 2844 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2845 return false; 2846 // First CopyToReg 2847 TCChain = UseChain; 2848 } 2849 } 2850 } else if (Copy->getOpcode() == ISD::BITCAST) { 2851 // f32 returned in a single GPR. 2852 if (!Copy->hasOneUse()) 2853 return false; 2854 Copy = *Copy->use_begin(); 2855 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2856 return false; 2857 // If the copy has a glue operand, we conservatively assume it isn't safe to 2858 // perform a tail call. 2859 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2860 return false; 2861 TCChain = Copy->getOperand(0); 2862 } else { 2863 return false; 2864 } 2865 2866 bool HasRet = false; 2867 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2868 UI != UE; ++UI) { 2869 if (UI->getOpcode() != ARMISD::RET_FLAG && 2870 UI->getOpcode() != ARMISD::INTRET_FLAG) 2871 return false; 2872 HasRet = true; 2873 } 2874 2875 if (!HasRet) 2876 return false; 2877 2878 Chain = TCChain; 2879 return true; 2880 } 2881 2882 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2883 if (!Subtarget->supportsTailCall()) 2884 return false; 2885 2886 auto Attr = 2887 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2888 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2889 return false; 2890 2891 return true; 2892 } 2893 2894 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2895 // and pass the lower and high parts through. 2896 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2897 SDLoc DL(Op); 2898 SDValue WriteValue = Op->getOperand(2); 2899 2900 // This function is only supposed to be called for i64 type argument. 2901 assert(WriteValue.getValueType() == MVT::i64 2902 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2903 2904 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2905 DAG.getConstant(0, DL, MVT::i32)); 2906 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2907 DAG.getConstant(1, DL, MVT::i32)); 2908 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2909 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2910 } 2911 2912 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2913 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2914 // one of the above mentioned nodes. It has to be wrapped because otherwise 2915 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2916 // be used to form addressing mode. These wrapped nodes will be selected 2917 // into MOVi. 2918 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2919 SelectionDAG &DAG) const { 2920 EVT PtrVT = Op.getValueType(); 2921 // FIXME there is no actual debug info here 2922 SDLoc dl(Op); 2923 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2924 SDValue Res; 2925 2926 // When generating execute-only code Constant Pools must be promoted to the 2927 // global data section. It's a bit ugly that we can't share them across basic 2928 // blocks, but this way we guarantee that execute-only behaves correct with 2929 // position-independent addressing modes. 2930 if (Subtarget->genExecuteOnly()) { 2931 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2932 auto T = const_cast<Type*>(CP->getType()); 2933 auto C = const_cast<Constant*>(CP->getConstVal()); 2934 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2935 getFunction().getParent()); 2936 auto GV = new GlobalVariable( 2937 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C, 2938 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2939 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2940 Twine(AFI->createPICLabelUId()) 2941 ); 2942 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2943 dl, PtrVT); 2944 return LowerGlobalAddress(GA, DAG); 2945 } 2946 2947 if (CP->isMachineConstantPoolEntry()) 2948 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2949 CP->getAlignment()); 2950 else 2951 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2952 CP->getAlignment()); 2953 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2954 } 2955 2956 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2957 return MachineJumpTableInfo::EK_Inline; 2958 } 2959 2960 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2961 SelectionDAG &DAG) const { 2962 MachineFunction &MF = DAG.getMachineFunction(); 2963 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2964 unsigned ARMPCLabelIndex = 0; 2965 SDLoc DL(Op); 2966 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2967 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2968 SDValue CPAddr; 2969 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2970 if (!IsPositionIndependent) { 2971 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2972 } else { 2973 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2974 ARMPCLabelIndex = AFI->createPICLabelUId(); 2975 ARMConstantPoolValue *CPV = 2976 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2977 ARMCP::CPBlockAddress, PCAdj); 2978 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2979 } 2980 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2981 SDValue Result = DAG.getLoad( 2982 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2983 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2984 if (!IsPositionIndependent) 2985 return Result; 2986 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2987 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2988 } 2989 2990 /// Convert a TLS address reference into the correct sequence of loads 2991 /// and calls to compute the variable's address for Darwin, and return an 2992 /// SDValue containing the final node. 2993 2994 /// Darwin only has one TLS scheme which must be capable of dealing with the 2995 /// fully general situation, in the worst case. This means: 2996 /// + "extern __thread" declaration. 2997 /// + Defined in a possibly unknown dynamic library. 2998 /// 2999 /// The general system is that each __thread variable has a [3 x i32] descriptor 3000 /// which contains information used by the runtime to calculate the address. The 3001 /// only part of this the compiler needs to know about is the first word, which 3002 /// contains a function pointer that must be called with the address of the 3003 /// entire descriptor in "r0". 3004 /// 3005 /// Since this descriptor may be in a different unit, in general access must 3006 /// proceed along the usual ARM rules. A common sequence to produce is: 3007 /// 3008 /// movw rT1, :lower16:_var$non_lazy_ptr 3009 /// movt rT1, :upper16:_var$non_lazy_ptr 3010 /// ldr r0, [rT1] 3011 /// ldr rT2, [r0] 3012 /// blx rT2 3013 /// [...address now in r0...] 3014 SDValue 3015 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 3016 SelectionDAG &DAG) const { 3017 assert(Subtarget->isTargetDarwin() && 3018 "This function expects a Darwin target"); 3019 SDLoc DL(Op); 3020 3021 // First step is to get the address of the actua global symbol. This is where 3022 // the TLS descriptor lives. 3023 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 3024 3025 // The first entry in the descriptor is a function pointer that we must call 3026 // to obtain the address of the variable. 3027 SDValue Chain = DAG.getEntryNode(); 3028 SDValue FuncTLVGet = DAG.getLoad( 3029 MVT::i32, DL, Chain, DescAddr, 3030 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3031 /* Alignment = */ 4, 3032 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 3033 MachineMemOperand::MOInvariant); 3034 Chain = FuncTLVGet.getValue(1); 3035 3036 MachineFunction &F = DAG.getMachineFunction(); 3037 MachineFrameInfo &MFI = F.getFrameInfo(); 3038 MFI.setAdjustsStack(true); 3039 3040 // TLS calls preserve all registers except those that absolutely must be 3041 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 3042 // silly). 3043 auto TRI = 3044 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 3045 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 3046 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 3047 3048 // Finally, we can make the call. This is just a degenerate version of a 3049 // normal AArch64 call node: r0 takes the address of the descriptor, and 3050 // returns the address of the variable in this thread. 3051 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 3052 Chain = 3053 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3054 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3055 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3056 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3057 } 3058 3059 SDValue 3060 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3061 SelectionDAG &DAG) const { 3062 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3063 3064 SDValue Chain = DAG.getEntryNode(); 3065 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3066 SDLoc DL(Op); 3067 3068 // Load the current TEB (thread environment block) 3069 SDValue Ops[] = {Chain, 3070 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3071 DAG.getConstant(15, DL, MVT::i32), 3072 DAG.getConstant(0, DL, MVT::i32), 3073 DAG.getConstant(13, DL, MVT::i32), 3074 DAG.getConstant(0, DL, MVT::i32), 3075 DAG.getConstant(2, DL, MVT::i32)}; 3076 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3077 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3078 3079 SDValue TEB = CurrentTEB.getValue(0); 3080 Chain = CurrentTEB.getValue(1); 3081 3082 // Load the ThreadLocalStoragePointer from the TEB 3083 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3084 SDValue TLSArray = 3085 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3086 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3087 3088 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3089 // offset into the TLSArray. 3090 3091 // Load the TLS index from the C runtime 3092 SDValue TLSIndex = 3093 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3094 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3095 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3096 3097 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3098 DAG.getConstant(2, DL, MVT::i32)); 3099 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3100 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3101 MachinePointerInfo()); 3102 3103 // Get the offset of the start of the .tls section (section base) 3104 const auto *GA = cast<GlobalAddressSDNode>(Op); 3105 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3106 SDValue Offset = DAG.getLoad( 3107 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3108 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 3109 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3110 3111 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3112 } 3113 3114 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3115 SDValue 3116 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3117 SelectionDAG &DAG) const { 3118 SDLoc dl(GA); 3119 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3120 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3121 MachineFunction &MF = DAG.getMachineFunction(); 3122 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3123 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3124 ARMConstantPoolValue *CPV = 3125 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3126 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3127 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3128 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3129 Argument = DAG.getLoad( 3130 PtrVT, dl, DAG.getEntryNode(), Argument, 3131 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3132 SDValue Chain = Argument.getValue(1); 3133 3134 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3135 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3136 3137 // call __tls_get_addr. 3138 ArgListTy Args; 3139 ArgListEntry Entry; 3140 Entry.Node = Argument; 3141 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3142 Args.push_back(Entry); 3143 3144 // FIXME: is there useful debug info available here? 3145 TargetLowering::CallLoweringInfo CLI(DAG); 3146 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3147 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3148 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3149 3150 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3151 return CallResult.first; 3152 } 3153 3154 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3155 // "local exec" model. 3156 SDValue 3157 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3158 SelectionDAG &DAG, 3159 TLSModel::Model model) const { 3160 const GlobalValue *GV = GA->getGlobal(); 3161 SDLoc dl(GA); 3162 SDValue Offset; 3163 SDValue Chain = DAG.getEntryNode(); 3164 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3165 // Get the Thread Pointer 3166 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3167 3168 if (model == TLSModel::InitialExec) { 3169 MachineFunction &MF = DAG.getMachineFunction(); 3170 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3171 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3172 // Initial exec model. 3173 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3174 ARMConstantPoolValue *CPV = 3175 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3176 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3177 true); 3178 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3179 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3180 Offset = DAG.getLoad( 3181 PtrVT, dl, Chain, Offset, 3182 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3183 Chain = Offset.getValue(1); 3184 3185 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3186 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3187 3188 Offset = DAG.getLoad( 3189 PtrVT, dl, Chain, Offset, 3190 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3191 } else { 3192 // local exec model 3193 assert(model == TLSModel::LocalExec); 3194 ARMConstantPoolValue *CPV = 3195 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3196 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3197 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3198 Offset = DAG.getLoad( 3199 PtrVT, dl, Chain, Offset, 3200 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3201 } 3202 3203 // The address of the thread local variable is the add of the thread 3204 // pointer with the offset of the variable. 3205 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3206 } 3207 3208 SDValue 3209 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3210 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3211 if (DAG.getTarget().useEmulatedTLS()) 3212 return LowerToTLSEmulatedModel(GA, DAG); 3213 3214 if (Subtarget->isTargetDarwin()) 3215 return LowerGlobalTLSAddressDarwin(Op, DAG); 3216 3217 if (Subtarget->isTargetWindows()) 3218 return LowerGlobalTLSAddressWindows(Op, DAG); 3219 3220 // TODO: implement the "local dynamic" model 3221 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3222 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3223 3224 switch (model) { 3225 case TLSModel::GeneralDynamic: 3226 case TLSModel::LocalDynamic: 3227 return LowerToTLSGeneralDynamicModel(GA, DAG); 3228 case TLSModel::InitialExec: 3229 case TLSModel::LocalExec: 3230 return LowerToTLSExecModels(GA, DAG, model); 3231 } 3232 llvm_unreachable("bogus TLS model"); 3233 } 3234 3235 /// Return true if all users of V are within function F, looking through 3236 /// ConstantExprs. 3237 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3238 SmallVector<const User*,4> Worklist; 3239 for (auto *U : V->users()) 3240 Worklist.push_back(U); 3241 while (!Worklist.empty()) { 3242 auto *U = Worklist.pop_back_val(); 3243 if (isa<ConstantExpr>(U)) { 3244 for (auto *UU : U->users()) 3245 Worklist.push_back(UU); 3246 continue; 3247 } 3248 3249 auto *I = dyn_cast<Instruction>(U); 3250 if (!I || I->getParent()->getParent() != F) 3251 return false; 3252 } 3253 return true; 3254 } 3255 3256 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3257 const GlobalValue *GV, SelectionDAG &DAG, 3258 EVT PtrVT, const SDLoc &dl) { 3259 // If we're creating a pool entry for a constant global with unnamed address, 3260 // and the global is small enough, we can emit it inline into the constant pool 3261 // to save ourselves an indirection. 3262 // 3263 // This is a win if the constant is only used in one function (so it doesn't 3264 // need to be duplicated) or duplicating the constant wouldn't increase code 3265 // size (implying the constant is no larger than 4 bytes). 3266 const Function &F = DAG.getMachineFunction().getFunction(); 3267 3268 // We rely on this decision to inline being idemopotent and unrelated to the 3269 // use-site. We know that if we inline a variable at one use site, we'll 3270 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3271 // doesn't know about this optimization, so bail out if it's enabled else 3272 // we could decide to inline here (and thus never emit the GV) but require 3273 // the GV from fast-isel generated code. 3274 if (!EnableConstpoolPromotion || 3275 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3276 return SDValue(); 3277 3278 auto *GVar = dyn_cast<GlobalVariable>(GV); 3279 if (!GVar || !GVar->hasInitializer() || 3280 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3281 !GVar->hasLocalLinkage()) 3282 return SDValue(); 3283 3284 // If we inline a value that contains relocations, we move the relocations 3285 // from .data to .text. This is not allowed in position-independent code. 3286 auto *Init = GVar->getInitializer(); 3287 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3288 Init->needsRelocation()) 3289 return SDValue(); 3290 3291 // The constant islands pass can only really deal with alignment requests 3292 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3293 // any type wanting greater alignment requirements than 4 bytes. We also 3294 // can only promote constants that are multiples of 4 bytes in size or 3295 // are paddable to a multiple of 4. Currently we only try and pad constants 3296 // that are strings for simplicity. 3297 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3298 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3299 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3300 unsigned RequiredPadding = 4 - (Size % 4); 3301 bool PaddingPossible = 3302 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3303 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3304 Size == 0) 3305 return SDValue(); 3306 3307 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3308 MachineFunction &MF = DAG.getMachineFunction(); 3309 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3310 3311 // We can't bloat the constant pool too much, else the ConstantIslands pass 3312 // may fail to converge. If we haven't promoted this global yet (it may have 3313 // multiple uses), and promoting it would increase the constant pool size (Sz 3314 // > 4), ensure we have space to do so up to MaxTotal. 3315 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3316 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3317 ConstpoolPromotionMaxTotal) 3318 return SDValue(); 3319 3320 // This is only valid if all users are in a single function; we can't clone 3321 // the constant in general. The LLVM IR unnamed_addr allows merging 3322 // constants, but not cloning them. 3323 // 3324 // We could potentially allow cloning if we could prove all uses of the 3325 // constant in the current function don't care about the address, like 3326 // printf format strings. But that isn't implemented for now. 3327 if (!allUsersAreInFunction(GVar, &F)) 3328 return SDValue(); 3329 3330 // We're going to inline this global. Pad it out if needed. 3331 if (RequiredPadding != 4) { 3332 StringRef S = CDAInit->getAsString(); 3333 3334 SmallVector<uint8_t,16> V(S.size()); 3335 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3336 while (RequiredPadding--) 3337 V.push_back(0); 3338 Init = ConstantDataArray::get(*DAG.getContext(), V); 3339 } 3340 3341 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3342 SDValue CPAddr = 3343 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3344 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3345 AFI->markGlobalAsPromotedToConstantPool(GVar); 3346 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3347 PaddedSize - 4); 3348 } 3349 ++NumConstpoolPromoted; 3350 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3351 } 3352 3353 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3354 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3355 if (!(GV = GA->getBaseObject())) 3356 return false; 3357 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3358 return V->isConstant(); 3359 return isa<Function>(GV); 3360 } 3361 3362 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3363 SelectionDAG &DAG) const { 3364 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3365 default: llvm_unreachable("unknown object format"); 3366 case Triple::COFF: 3367 return LowerGlobalAddressWindows(Op, DAG); 3368 case Triple::ELF: 3369 return LowerGlobalAddressELF(Op, DAG); 3370 case Triple::MachO: 3371 return LowerGlobalAddressDarwin(Op, DAG); 3372 } 3373 } 3374 3375 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3376 SelectionDAG &DAG) const { 3377 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3378 SDLoc dl(Op); 3379 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3380 const TargetMachine &TM = getTargetMachine(); 3381 bool IsRO = isReadOnly(GV); 3382 3383 // promoteToConstantPool only if not generating XO text section 3384 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3385 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3386 return V; 3387 3388 if (isPositionIndependent()) { 3389 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3390 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3391 UseGOT_PREL ? ARMII::MO_GOT : 0); 3392 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3393 if (UseGOT_PREL) 3394 Result = 3395 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3396 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3397 return Result; 3398 } else if (Subtarget->isROPI() && IsRO) { 3399 // PC-relative. 3400 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3401 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3402 return Result; 3403 } else if (Subtarget->isRWPI() && !IsRO) { 3404 // SB-relative. 3405 SDValue RelAddr; 3406 if (Subtarget->useMovt()) { 3407 ++NumMovwMovt; 3408 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3409 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3410 } else { // use literal pool for address constant 3411 ARMConstantPoolValue *CPV = 3412 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3413 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3414 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3415 RelAddr = DAG.getLoad( 3416 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3417 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3418 } 3419 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3420 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3421 return Result; 3422 } 3423 3424 // If we have T2 ops, we can materialize the address directly via movt/movw 3425 // pair. This is always cheaper. 3426 if (Subtarget->useMovt()) { 3427 ++NumMovwMovt; 3428 // FIXME: Once remat is capable of dealing with instructions with register 3429 // operands, expand this into two nodes. 3430 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3431 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3432 } else { 3433 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3434 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3435 return DAG.getLoad( 3436 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3437 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3438 } 3439 } 3440 3441 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3442 SelectionDAG &DAG) const { 3443 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3444 "ROPI/RWPI not currently supported for Darwin"); 3445 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3446 SDLoc dl(Op); 3447 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3448 3449 if (Subtarget->useMovt()) 3450 ++NumMovwMovt; 3451 3452 // FIXME: Once remat is capable of dealing with instructions with register 3453 // operands, expand this into multiple nodes 3454 unsigned Wrapper = 3455 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3456 3457 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3458 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3459 3460 if (Subtarget->isGVIndirectSymbol(GV)) 3461 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3462 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3463 return Result; 3464 } 3465 3466 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3467 SelectionDAG &DAG) const { 3468 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3469 assert(Subtarget->useMovt() && 3470 "Windows on ARM expects to use movw/movt"); 3471 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3472 "ROPI/RWPI not currently supported for Windows"); 3473 3474 const TargetMachine &TM = getTargetMachine(); 3475 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3476 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3477 if (GV->hasDLLImportStorageClass()) 3478 TargetFlags = ARMII::MO_DLLIMPORT; 3479 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3480 TargetFlags = ARMII::MO_COFFSTUB; 3481 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3482 SDValue Result; 3483 SDLoc DL(Op); 3484 3485 ++NumMovwMovt; 3486 3487 // FIXME: Once remat is capable of dealing with instructions with register 3488 // operands, expand this into two nodes. 3489 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3490 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0, 3491 TargetFlags)); 3492 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3493 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3494 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3495 return Result; 3496 } 3497 3498 SDValue 3499 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3500 SDLoc dl(Op); 3501 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3502 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3503 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3504 Op.getOperand(1), Val); 3505 } 3506 3507 SDValue 3508 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3509 SDLoc dl(Op); 3510 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3511 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3512 } 3513 3514 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3515 SelectionDAG &DAG) const { 3516 SDLoc dl(Op); 3517 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3518 Op.getOperand(0)); 3519 } 3520 3521 SDValue 3522 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3523 const ARMSubtarget *Subtarget) const { 3524 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3525 SDLoc dl(Op); 3526 switch (IntNo) { 3527 default: return SDValue(); // Don't custom lower most intrinsics. 3528 case Intrinsic::thread_pointer: { 3529 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3530 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3531 } 3532 case Intrinsic::eh_sjlj_lsda: { 3533 MachineFunction &MF = DAG.getMachineFunction(); 3534 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3535 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3536 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3537 SDValue CPAddr; 3538 bool IsPositionIndependent = isPositionIndependent(); 3539 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3540 ARMConstantPoolValue *CPV = 3541 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3542 ARMCP::CPLSDA, PCAdj); 3543 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3544 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3545 SDValue Result = DAG.getLoad( 3546 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3547 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3548 3549 if (IsPositionIndependent) { 3550 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3551 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3552 } 3553 return Result; 3554 } 3555 case Intrinsic::arm_neon_vabs: 3556 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3557 Op.getOperand(1)); 3558 case Intrinsic::arm_neon_vmulls: 3559 case Intrinsic::arm_neon_vmullu: { 3560 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3561 ? ARMISD::VMULLs : ARMISD::VMULLu; 3562 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3563 Op.getOperand(1), Op.getOperand(2)); 3564 } 3565 case Intrinsic::arm_neon_vminnm: 3566 case Intrinsic::arm_neon_vmaxnm: { 3567 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3568 ? ISD::FMINNUM : ISD::FMAXNUM; 3569 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3570 Op.getOperand(1), Op.getOperand(2)); 3571 } 3572 case Intrinsic::arm_neon_vminu: 3573 case Intrinsic::arm_neon_vmaxu: { 3574 if (Op.getValueType().isFloatingPoint()) 3575 return SDValue(); 3576 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3577 ? ISD::UMIN : ISD::UMAX; 3578 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3579 Op.getOperand(1), Op.getOperand(2)); 3580 } 3581 case Intrinsic::arm_neon_vmins: 3582 case Intrinsic::arm_neon_vmaxs: { 3583 // v{min,max}s is overloaded between signed integers and floats. 3584 if (!Op.getValueType().isFloatingPoint()) { 3585 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3586 ? ISD::SMIN : ISD::SMAX; 3587 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3588 Op.getOperand(1), Op.getOperand(2)); 3589 } 3590 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3591 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3592 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3593 Op.getOperand(1), Op.getOperand(2)); 3594 } 3595 case Intrinsic::arm_neon_vtbl1: 3596 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3597 Op.getOperand(1), Op.getOperand(2)); 3598 case Intrinsic::arm_neon_vtbl2: 3599 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3600 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3601 } 3602 } 3603 3604 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3605 const ARMSubtarget *Subtarget) { 3606 SDLoc dl(Op); 3607 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3608 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3609 if (SSID == SyncScope::SingleThread) 3610 return Op; 3611 3612 if (!Subtarget->hasDataBarrier()) { 3613 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3614 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3615 // here. 3616 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3617 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3618 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3619 DAG.getConstant(0, dl, MVT::i32)); 3620 } 3621 3622 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3623 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3624 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3625 if (Subtarget->isMClass()) { 3626 // Only a full system barrier exists in the M-class architectures. 3627 Domain = ARM_MB::SY; 3628 } else if (Subtarget->preferISHSTBarriers() && 3629 Ord == AtomicOrdering::Release) { 3630 // Swift happens to implement ISHST barriers in a way that's compatible with 3631 // Release semantics but weaker than ISH so we'd be fools not to use 3632 // it. Beware: other processors probably don't! 3633 Domain = ARM_MB::ISHST; 3634 } 3635 3636 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3637 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3638 DAG.getConstant(Domain, dl, MVT::i32)); 3639 } 3640 3641 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3642 const ARMSubtarget *Subtarget) { 3643 // ARM pre v5TE and Thumb1 does not have preload instructions. 3644 if (!(Subtarget->isThumb2() || 3645 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3646 // Just preserve the chain. 3647 return Op.getOperand(0); 3648 3649 SDLoc dl(Op); 3650 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3651 if (!isRead && 3652 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3653 // ARMv7 with MP extension has PLDW. 3654 return Op.getOperand(0); 3655 3656 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3657 if (Subtarget->isThumb()) { 3658 // Invert the bits. 3659 isRead = ~isRead & 1; 3660 isData = ~isData & 1; 3661 } 3662 3663 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3664 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3665 DAG.getConstant(isData, dl, MVT::i32)); 3666 } 3667 3668 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3669 MachineFunction &MF = DAG.getMachineFunction(); 3670 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3671 3672 // vastart just stores the address of the VarArgsFrameIndex slot into the 3673 // memory location argument. 3674 SDLoc dl(Op); 3675 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3676 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3677 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3678 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3679 MachinePointerInfo(SV)); 3680 } 3681 3682 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3683 CCValAssign &NextVA, 3684 SDValue &Root, 3685 SelectionDAG &DAG, 3686 const SDLoc &dl) const { 3687 MachineFunction &MF = DAG.getMachineFunction(); 3688 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3689 3690 const TargetRegisterClass *RC; 3691 if (AFI->isThumb1OnlyFunction()) 3692 RC = &ARM::tGPRRegClass; 3693 else 3694 RC = &ARM::GPRRegClass; 3695 3696 // Transform the arguments stored in physical registers into virtual ones. 3697 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3698 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3699 3700 SDValue ArgValue2; 3701 if (NextVA.isMemLoc()) { 3702 MachineFrameInfo &MFI = MF.getFrameInfo(); 3703 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3704 3705 // Create load node to retrieve arguments from the stack. 3706 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3707 ArgValue2 = DAG.getLoad( 3708 MVT::i32, dl, Root, FIN, 3709 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3710 } else { 3711 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3712 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3713 } 3714 if (!Subtarget->isLittle()) 3715 std::swap (ArgValue, ArgValue2); 3716 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3717 } 3718 3719 // The remaining GPRs hold either the beginning of variable-argument 3720 // data, or the beginning of an aggregate passed by value (usually 3721 // byval). Either way, we allocate stack slots adjacent to the data 3722 // provided by our caller, and store the unallocated registers there. 3723 // If this is a variadic function, the va_list pointer will begin with 3724 // these values; otherwise, this reassembles a (byval) structure that 3725 // was split between registers and memory. 3726 // Return: The frame index registers were stored into. 3727 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3728 const SDLoc &dl, SDValue &Chain, 3729 const Value *OrigArg, 3730 unsigned InRegsParamRecordIdx, 3731 int ArgOffset, unsigned ArgSize) const { 3732 // Currently, two use-cases possible: 3733 // Case #1. Non-var-args function, and we meet first byval parameter. 3734 // Setup first unallocated register as first byval register; 3735 // eat all remained registers 3736 // (these two actions are performed by HandleByVal method). 3737 // Then, here, we initialize stack frame with 3738 // "store-reg" instructions. 3739 // Case #2. Var-args function, that doesn't contain byval parameters. 3740 // The same: eat all remained unallocated registers, 3741 // initialize stack frame. 3742 3743 MachineFunction &MF = DAG.getMachineFunction(); 3744 MachineFrameInfo &MFI = MF.getFrameInfo(); 3745 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3746 unsigned RBegin, REnd; 3747 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3748 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3749 } else { 3750 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3751 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3752 REnd = ARM::R4; 3753 } 3754 3755 if (REnd != RBegin) 3756 ArgOffset = -4 * (ARM::R4 - RBegin); 3757 3758 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3759 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3760 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3761 3762 SmallVector<SDValue, 4> MemOps; 3763 const TargetRegisterClass *RC = 3764 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3765 3766 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3767 unsigned VReg = MF.addLiveIn(Reg, RC); 3768 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3769 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3770 MachinePointerInfo(OrigArg, 4 * i)); 3771 MemOps.push_back(Store); 3772 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3773 } 3774 3775 if (!MemOps.empty()) 3776 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3777 return FrameIndex; 3778 } 3779 3780 // Setup stack frame, the va_list pointer will start from. 3781 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3782 const SDLoc &dl, SDValue &Chain, 3783 unsigned ArgOffset, 3784 unsigned TotalArgRegsSaveSize, 3785 bool ForceMutable) const { 3786 MachineFunction &MF = DAG.getMachineFunction(); 3787 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3788 3789 // Try to store any remaining integer argument regs 3790 // to their spots on the stack so that they may be loaded by dereferencing 3791 // the result of va_next. 3792 // If there is no regs to be stored, just point address after last 3793 // argument passed via stack. 3794 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3795 CCInfo.getInRegsParamsCount(), 3796 CCInfo.getNextStackOffset(), 3797 std::max(4U, TotalArgRegsSaveSize)); 3798 AFI->setVarArgsFrameIndex(FrameIndex); 3799 } 3800 3801 SDValue ARMTargetLowering::LowerFormalArguments( 3802 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3803 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3804 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3805 MachineFunction &MF = DAG.getMachineFunction(); 3806 MachineFrameInfo &MFI = MF.getFrameInfo(); 3807 3808 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3809 3810 // Assign locations to all of the incoming arguments. 3811 SmallVector<CCValAssign, 16> ArgLocs; 3812 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3813 *DAG.getContext()); 3814 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3815 3816 SmallVector<SDValue, 16> ArgValues; 3817 SDValue ArgValue; 3818 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3819 unsigned CurArgIdx = 0; 3820 3821 // Initially ArgRegsSaveSize is zero. 3822 // Then we increase this value each time we meet byval parameter. 3823 // We also increase this value in case of varargs function. 3824 AFI->setArgRegsSaveSize(0); 3825 3826 // Calculate the amount of stack space that we need to allocate to store 3827 // byval and variadic arguments that are passed in registers. 3828 // We need to know this before we allocate the first byval or variadic 3829 // argument, as they will be allocated a stack slot below the CFA (Canonical 3830 // Frame Address, the stack pointer at entry to the function). 3831 unsigned ArgRegBegin = ARM::R4; 3832 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3833 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3834 break; 3835 3836 CCValAssign &VA = ArgLocs[i]; 3837 unsigned Index = VA.getValNo(); 3838 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3839 if (!Flags.isByVal()) 3840 continue; 3841 3842 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3843 unsigned RBegin, REnd; 3844 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3845 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3846 3847 CCInfo.nextInRegsParam(); 3848 } 3849 CCInfo.rewindByValRegsInfo(); 3850 3851 int lastInsIndex = -1; 3852 if (isVarArg && MFI.hasVAStart()) { 3853 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3854 if (RegIdx != array_lengthof(GPRArgRegs)) 3855 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3856 } 3857 3858 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3859 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3860 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3861 3862 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3863 CCValAssign &VA = ArgLocs[i]; 3864 if (Ins[VA.getValNo()].isOrigArg()) { 3865 std::advance(CurOrigArg, 3866 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3867 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3868 } 3869 // Arguments stored in registers. 3870 if (VA.isRegLoc()) { 3871 EVT RegVT = VA.getLocVT(); 3872 3873 if (VA.needsCustom()) { 3874 // f64 and vector types are split up into multiple registers or 3875 // combinations of registers and stack slots. 3876 if (VA.getLocVT() == MVT::v2f64) { 3877 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3878 Chain, DAG, dl); 3879 VA = ArgLocs[++i]; // skip ahead to next loc 3880 SDValue ArgValue2; 3881 if (VA.isMemLoc()) { 3882 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3883 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3884 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3885 MachinePointerInfo::getFixedStack( 3886 DAG.getMachineFunction(), FI)); 3887 } else { 3888 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3889 Chain, DAG, dl); 3890 } 3891 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3892 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3893 ArgValue, ArgValue1, 3894 DAG.getIntPtrConstant(0, dl)); 3895 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3896 ArgValue, ArgValue2, 3897 DAG.getIntPtrConstant(1, dl)); 3898 } else 3899 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3900 } else { 3901 const TargetRegisterClass *RC; 3902 3903 3904 if (RegVT == MVT::f16) 3905 RC = &ARM::HPRRegClass; 3906 else if (RegVT == MVT::f32) 3907 RC = &ARM::SPRRegClass; 3908 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3909 RC = &ARM::DPRRegClass; 3910 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3911 RC = &ARM::QPRRegClass; 3912 else if (RegVT == MVT::i32) 3913 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3914 : &ARM::GPRRegClass; 3915 else 3916 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3917 3918 // Transform the arguments in physical registers into virtual ones. 3919 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3920 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3921 3922 // If this value is passed in r0 and has the returned attribute (e.g. 3923 // C++ 'structors), record this fact for later use. 3924 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) { 3925 AFI->setPreservesR0(); 3926 } 3927 } 3928 3929 // If this is an 8 or 16-bit value, it is really passed promoted 3930 // to 32 bits. Insert an assert[sz]ext to capture this, then 3931 // truncate to the right size. 3932 switch (VA.getLocInfo()) { 3933 default: llvm_unreachable("Unknown loc info!"); 3934 case CCValAssign::Full: break; 3935 case CCValAssign::BCvt: 3936 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3937 break; 3938 case CCValAssign::SExt: 3939 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3940 DAG.getValueType(VA.getValVT())); 3941 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3942 break; 3943 case CCValAssign::ZExt: 3944 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3945 DAG.getValueType(VA.getValVT())); 3946 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3947 break; 3948 } 3949 3950 InVals.push_back(ArgValue); 3951 } else { // VA.isRegLoc() 3952 // sanity check 3953 assert(VA.isMemLoc()); 3954 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3955 3956 int index = VA.getValNo(); 3957 3958 // Some Ins[] entries become multiple ArgLoc[] entries. 3959 // Process them only once. 3960 if (index != lastInsIndex) 3961 { 3962 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3963 // FIXME: For now, all byval parameter objects are marked mutable. 3964 // This can be changed with more analysis. 3965 // In case of tail call optimization mark all arguments mutable. 3966 // Since they could be overwritten by lowering of arguments in case of 3967 // a tail call. 3968 if (Flags.isByVal()) { 3969 assert(Ins[index].isOrigArg() && 3970 "Byval arguments cannot be implicit"); 3971 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3972 3973 int FrameIndex = StoreByValRegs( 3974 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3975 VA.getLocMemOffset(), Flags.getByValSize()); 3976 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3977 CCInfo.nextInRegsParam(); 3978 } else { 3979 unsigned FIOffset = VA.getLocMemOffset(); 3980 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3981 FIOffset, true); 3982 3983 // Create load nodes to retrieve arguments from the stack. 3984 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3985 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3986 MachinePointerInfo::getFixedStack( 3987 DAG.getMachineFunction(), FI))); 3988 } 3989 lastInsIndex = index; 3990 } 3991 } 3992 } 3993 3994 // varargs 3995 if (isVarArg && MFI.hasVAStart()) 3996 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3997 CCInfo.getNextStackOffset(), 3998 TotalArgRegsSaveSize); 3999 4000 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 4001 4002 return Chain; 4003 } 4004 4005 /// isFloatingPointZero - Return true if this is +0.0. 4006 static bool isFloatingPointZero(SDValue Op) { 4007 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 4008 return CFP->getValueAPF().isPosZero(); 4009 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 4010 // Maybe this has already been legalized into the constant pool? 4011 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 4012 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 4013 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 4014 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 4015 return CFP->getValueAPF().isPosZero(); 4016 } 4017 } else if (Op->getOpcode() == ISD::BITCAST && 4018 Op->getValueType(0) == MVT::f64) { 4019 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 4020 // created by LowerConstantFP(). 4021 SDValue BitcastOp = Op->getOperand(0); 4022 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 4023 isNullConstant(BitcastOp->getOperand(0))) 4024 return true; 4025 } 4026 return false; 4027 } 4028 4029 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 4030 /// the given operands. 4031 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 4032 SDValue &ARMcc, SelectionDAG &DAG, 4033 const SDLoc &dl) const { 4034 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 4035 unsigned C = RHSC->getZExtValue(); 4036 if (!isLegalICmpImmediate((int32_t)C)) { 4037 // Constant does not fit, try adjusting it by one. 4038 switch (CC) { 4039 default: break; 4040 case ISD::SETLT: 4041 case ISD::SETGE: 4042 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 4043 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 4044 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4045 } 4046 break; 4047 case ISD::SETULT: 4048 case ISD::SETUGE: 4049 if (C != 0 && isLegalICmpImmediate(C-1)) { 4050 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 4051 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 4052 } 4053 break; 4054 case ISD::SETLE: 4055 case ISD::SETGT: 4056 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 4057 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 4058 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4059 } 4060 break; 4061 case ISD::SETULE: 4062 case ISD::SETUGT: 4063 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4064 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4065 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4066 } 4067 break; 4068 } 4069 } 4070 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4071 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4072 // In ARM and Thumb-2, the compare instructions can shift their second 4073 // operand. 4074 CC = ISD::getSetCCSwappedOperands(CC); 4075 std::swap(LHS, RHS); 4076 } 4077 4078 // Thumb1 has very limited immediate modes, so turning an "and" into a 4079 // shift can save multiple instructions. 4080 // 4081 // If we have (x & C1), and C1 is an appropriate mask, we can transform it 4082 // into "((x << n) >> n)". But that isn't necessarily profitable on its 4083 // own. If it's the operand to an unsigned comparison with an immediate, 4084 // we can eliminate one of the shifts: we transform 4085 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)". 4086 // 4087 // We avoid transforming cases which aren't profitable due to encoding 4088 // details: 4089 // 4090 // 1. C2 fits into the immediate field of a cmp, and the transformed version 4091 // would not; in that case, we're essentially trading one immediate load for 4092 // another. 4093 // 2. C1 is 255 or 65535, so we can use uxtb or uxth. 4094 // 3. C2 is zero; we have other code for this special case. 4095 // 4096 // FIXME: Figure out profitability for Thumb2; we usually can't save an 4097 // instruction, since the AND is always one instruction anyway, but we could 4098 // use narrow instructions in some cases. 4099 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND && 4100 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) && 4101 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) && 4102 !isSignedIntSetCC(CC)) { 4103 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue(); 4104 auto *RHSC = cast<ConstantSDNode>(RHS.getNode()); 4105 uint64_t RHSV = RHSC->getZExtValue(); 4106 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) { 4107 unsigned ShiftBits = countLeadingZeros(Mask); 4108 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) { 4109 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32); 4110 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt); 4111 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32); 4112 } 4113 } 4114 } 4115 4116 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a 4117 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same 4118 // way a cmp would. 4119 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and 4120 // some tweaks to the heuristics for the previous and->shift transform. 4121 // FIXME: Optimize cases where the LHS isn't a shift. 4122 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL && 4123 isa<ConstantSDNode>(RHS) && 4124 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U && 4125 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) && 4126 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) { 4127 unsigned ShiftAmt = 4128 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1; 4129 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl, 4130 DAG.getVTList(MVT::i32, MVT::i32), 4131 LHS.getOperand(0), 4132 DAG.getConstant(ShiftAmt, dl, MVT::i32)); 4133 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 4134 Shift.getValue(1), SDValue()); 4135 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32); 4136 return Chain.getValue(1); 4137 } 4138 4139 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4140 4141 // If the RHS is a constant zero then the V (overflow) flag will never be 4142 // set. This can allow us to simplify GE to PL or LT to MI, which can be 4143 // simpler for other passes (like the peephole optimiser) to deal with. 4144 if (isNullConstant(RHS)) { 4145 switch (CondCode) { 4146 default: break; 4147 case ARMCC::GE: 4148 CondCode = ARMCC::PL; 4149 break; 4150 case ARMCC::LT: 4151 CondCode = ARMCC::MI; 4152 break; 4153 } 4154 } 4155 4156 ARMISD::NodeType CompareType; 4157 switch (CondCode) { 4158 default: 4159 CompareType = ARMISD::CMP; 4160 break; 4161 case ARMCC::EQ: 4162 case ARMCC::NE: 4163 // Uses only Z Flag 4164 CompareType = ARMISD::CMPZ; 4165 break; 4166 } 4167 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4168 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4169 } 4170 4171 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4172 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4173 SelectionDAG &DAG, const SDLoc &dl, 4174 bool InvalidOnQNaN) const { 4175 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4176 SDValue Cmp; 4177 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 4178 if (!isFloatingPointZero(RHS)) 4179 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 4180 else 4181 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 4182 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4183 } 4184 4185 /// duplicateCmp - Glue values can have only one use, so this function 4186 /// duplicates a comparison node. 4187 SDValue 4188 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4189 unsigned Opc = Cmp.getOpcode(); 4190 SDLoc DL(Cmp); 4191 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4192 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4193 4194 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4195 Cmp = Cmp.getOperand(0); 4196 Opc = Cmp.getOpcode(); 4197 if (Opc == ARMISD::CMPFP) 4198 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4199 Cmp.getOperand(1), Cmp.getOperand(2)); 4200 else { 4201 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4202 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4203 Cmp.getOperand(1)); 4204 } 4205 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4206 } 4207 4208 // This function returns three things: the arithmetic computation itself 4209 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4210 // comparison and the condition code define the case in which the arithmetic 4211 // computation *does not* overflow. 4212 std::pair<SDValue, SDValue> 4213 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4214 SDValue &ARMcc) const { 4215 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4216 4217 SDValue Value, OverflowCmp; 4218 SDValue LHS = Op.getOperand(0); 4219 SDValue RHS = Op.getOperand(1); 4220 SDLoc dl(Op); 4221 4222 // FIXME: We are currently always generating CMPs because we don't support 4223 // generating CMN through the backend. This is not as good as the natural 4224 // CMP case because it causes a register dependency and cannot be folded 4225 // later. 4226 4227 switch (Op.getOpcode()) { 4228 default: 4229 llvm_unreachable("Unknown overflow instruction!"); 4230 case ISD::SADDO: 4231 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4232 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4233 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4234 break; 4235 case ISD::UADDO: 4236 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4237 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4238 // We do not use it in the USUBO case as Value may not be used. 4239 Value = DAG.getNode(ARMISD::ADDC, dl, 4240 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4241 .getValue(0); 4242 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4243 break; 4244 case ISD::SSUBO: 4245 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4246 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4247 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4248 break; 4249 case ISD::USUBO: 4250 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4251 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4252 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4253 break; 4254 case ISD::UMULO: 4255 // We generate a UMUL_LOHI and then check if the high word is 0. 4256 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4257 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4258 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4259 LHS, RHS); 4260 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4261 DAG.getConstant(0, dl, MVT::i32)); 4262 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4263 break; 4264 case ISD::SMULO: 4265 // We generate a SMUL_LOHI and then check if all the bits of the high word 4266 // are the same as the sign bit of the low word. 4267 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4268 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4269 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4270 LHS, RHS); 4271 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4272 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4273 Value.getValue(0), 4274 DAG.getConstant(31, dl, MVT::i32))); 4275 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4276 break; 4277 } // switch (...) 4278 4279 return std::make_pair(Value, OverflowCmp); 4280 } 4281 4282 SDValue 4283 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4284 // Let legalize expand this if it isn't a legal type yet. 4285 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4286 return SDValue(); 4287 4288 SDValue Value, OverflowCmp; 4289 SDValue ARMcc; 4290 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4291 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4292 SDLoc dl(Op); 4293 // We use 0 and 1 as false and true values. 4294 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4295 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4296 EVT VT = Op.getValueType(); 4297 4298 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4299 ARMcc, CCR, OverflowCmp); 4300 4301 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4302 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4303 } 4304 4305 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4306 SelectionDAG &DAG) { 4307 SDLoc DL(BoolCarry); 4308 EVT CarryVT = BoolCarry.getValueType(); 4309 4310 // This converts the boolean value carry into the carry flag by doing 4311 // ARMISD::SUBC Carry, 1 4312 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4313 DAG.getVTList(CarryVT, MVT::i32), 4314 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4315 return Carry.getValue(1); 4316 } 4317 4318 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4319 SelectionDAG &DAG) { 4320 SDLoc DL(Flags); 4321 4322 // Now convert the carry flag into a boolean carry. We do this 4323 // using ARMISD:ADDE 0, 0, Carry 4324 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4325 DAG.getConstant(0, DL, MVT::i32), 4326 DAG.getConstant(0, DL, MVT::i32), Flags); 4327 } 4328 4329 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4330 SelectionDAG &DAG) const { 4331 // Let legalize expand this if it isn't a legal type yet. 4332 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4333 return SDValue(); 4334 4335 SDValue LHS = Op.getOperand(0); 4336 SDValue RHS = Op.getOperand(1); 4337 SDLoc dl(Op); 4338 4339 EVT VT = Op.getValueType(); 4340 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4341 SDValue Value; 4342 SDValue Overflow; 4343 switch (Op.getOpcode()) { 4344 default: 4345 llvm_unreachable("Unknown overflow instruction!"); 4346 case ISD::UADDO: 4347 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4348 // Convert the carry flag into a boolean value. 4349 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4350 break; 4351 case ISD::USUBO: { 4352 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4353 // Convert the carry flag into a boolean value. 4354 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4355 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4356 // value. So compute 1 - C. 4357 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4358 DAG.getConstant(1, dl, MVT::i32), Overflow); 4359 break; 4360 } 4361 } 4362 4363 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4364 } 4365 4366 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4367 SDValue Cond = Op.getOperand(0); 4368 SDValue SelectTrue = Op.getOperand(1); 4369 SDValue SelectFalse = Op.getOperand(2); 4370 SDLoc dl(Op); 4371 unsigned Opc = Cond.getOpcode(); 4372 4373 if (Cond.getResNo() == 1 && 4374 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4375 Opc == ISD::USUBO)) { 4376 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4377 return SDValue(); 4378 4379 SDValue Value, OverflowCmp; 4380 SDValue ARMcc; 4381 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4382 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4383 EVT VT = Op.getValueType(); 4384 4385 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4386 OverflowCmp, DAG); 4387 } 4388 4389 // Convert: 4390 // 4391 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4392 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4393 // 4394 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4395 const ConstantSDNode *CMOVTrue = 4396 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4397 const ConstantSDNode *CMOVFalse = 4398 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4399 4400 if (CMOVTrue && CMOVFalse) { 4401 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4402 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4403 4404 SDValue True; 4405 SDValue False; 4406 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4407 True = SelectTrue; 4408 False = SelectFalse; 4409 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4410 True = SelectFalse; 4411 False = SelectTrue; 4412 } 4413 4414 if (True.getNode() && False.getNode()) { 4415 EVT VT = Op.getValueType(); 4416 SDValue ARMcc = Cond.getOperand(2); 4417 SDValue CCR = Cond.getOperand(3); 4418 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4419 assert(True.getValueType() == VT); 4420 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4421 } 4422 } 4423 } 4424 4425 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4426 // undefined bits before doing a full-word comparison with zero. 4427 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4428 DAG.getConstant(1, dl, Cond.getValueType())); 4429 4430 return DAG.getSelectCC(dl, Cond, 4431 DAG.getConstant(0, dl, Cond.getValueType()), 4432 SelectTrue, SelectFalse, ISD::SETNE); 4433 } 4434 4435 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4436 bool &swpCmpOps, bool &swpVselOps) { 4437 // Start by selecting the GE condition code for opcodes that return true for 4438 // 'equality' 4439 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4440 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4441 CondCode = ARMCC::GE; 4442 4443 // and GT for opcodes that return false for 'equality'. 4444 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4445 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4446 CondCode = ARMCC::GT; 4447 4448 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4449 // to swap the compare operands. 4450 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4451 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4452 swpCmpOps = true; 4453 4454 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4455 // If we have an unordered opcode, we need to swap the operands to the VSEL 4456 // instruction (effectively negating the condition). 4457 // 4458 // This also has the effect of swapping which one of 'less' or 'greater' 4459 // returns true, so we also swap the compare operands. It also switches 4460 // whether we return true for 'equality', so we compensate by picking the 4461 // opposite condition code to our original choice. 4462 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4463 CC == ISD::SETUGT) { 4464 swpCmpOps = !swpCmpOps; 4465 swpVselOps = !swpVselOps; 4466 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4467 } 4468 4469 // 'ordered' is 'anything but unordered', so use the VS condition code and 4470 // swap the VSEL operands. 4471 if (CC == ISD::SETO) { 4472 CondCode = ARMCC::VS; 4473 swpVselOps = true; 4474 } 4475 4476 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4477 // code and swap the VSEL operands. Also do this if we don't care about the 4478 // unordered case. 4479 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4480 CondCode = ARMCC::EQ; 4481 swpVselOps = true; 4482 } 4483 } 4484 4485 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4486 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4487 SDValue Cmp, SelectionDAG &DAG) const { 4488 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4489 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4490 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4491 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4492 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4493 4494 SDValue TrueLow = TrueVal.getValue(0); 4495 SDValue TrueHigh = TrueVal.getValue(1); 4496 SDValue FalseLow = FalseVal.getValue(0); 4497 SDValue FalseHigh = FalseVal.getValue(1); 4498 4499 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4500 ARMcc, CCR, Cmp); 4501 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4502 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4503 4504 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4505 } else { 4506 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4507 Cmp); 4508 } 4509 } 4510 4511 static bool isGTorGE(ISD::CondCode CC) { 4512 return CC == ISD::SETGT || CC == ISD::SETGE; 4513 } 4514 4515 static bool isLTorLE(ISD::CondCode CC) { 4516 return CC == ISD::SETLT || CC == ISD::SETLE; 4517 } 4518 4519 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4520 // All of these conditions (and their <= and >= counterparts) will do: 4521 // x < k ? k : x 4522 // x > k ? x : k 4523 // k < x ? x : k 4524 // k > x ? k : x 4525 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4526 const SDValue TrueVal, const SDValue FalseVal, 4527 const ISD::CondCode CC, const SDValue K) { 4528 return (isGTorGE(CC) && 4529 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4530 (isLTorLE(CC) && 4531 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4532 } 4533 4534 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4535 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4536 const SDValue TrueVal, const SDValue FalseVal, 4537 const ISD::CondCode CC, const SDValue K) { 4538 return (isGTorGE(CC) && 4539 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4540 (isLTorLE(CC) && 4541 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4542 } 4543 4544 // Check if two chained conditionals could be converted into SSAT or USAT. 4545 // 4546 // SSAT can replace a set of two conditional selectors that bound a number to an 4547 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4548 // 4549 // x < -k ? -k : (x > k ? k : x) 4550 // x < -k ? -k : (x < k ? x : k) 4551 // x > -k ? (x > k ? k : x) : -k 4552 // x < k ? (x < -k ? -k : x) : k 4553 // etc. 4554 // 4555 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4556 // a power of 2. 4557 // 4558 // It returns true if the conversion can be done, false otherwise. 4559 // Additionally, the variable is returned in parameter V, the constant in K and 4560 // usat is set to true if the conditional represents an unsigned saturation 4561 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4562 uint64_t &K, bool &usat) { 4563 SDValue LHS1 = Op.getOperand(0); 4564 SDValue RHS1 = Op.getOperand(1); 4565 SDValue TrueVal1 = Op.getOperand(2); 4566 SDValue FalseVal1 = Op.getOperand(3); 4567 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4568 4569 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4570 if (Op2.getOpcode() != ISD::SELECT_CC) 4571 return false; 4572 4573 SDValue LHS2 = Op2.getOperand(0); 4574 SDValue RHS2 = Op2.getOperand(1); 4575 SDValue TrueVal2 = Op2.getOperand(2); 4576 SDValue FalseVal2 = Op2.getOperand(3); 4577 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4578 4579 // Find out which are the constants and which are the variables 4580 // in each conditional 4581 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4582 ? &RHS1 4583 : nullptr; 4584 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4585 ? &RHS2 4586 : nullptr; 4587 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4588 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4589 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4590 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4591 4592 // We must detect cases where the original operations worked with 16- or 4593 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4594 // must work with sign-extended values but the select operations return 4595 // the original non-extended value. 4596 SDValue V2TmpReg = V2Tmp; 4597 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4598 V2TmpReg = V2Tmp->getOperand(0); 4599 4600 // Check that the registers and the constants have the correct values 4601 // in both conditionals 4602 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4603 V2TmpReg != V2) 4604 return false; 4605 4606 // Figure out which conditional is saturating the lower/upper bound. 4607 const SDValue *LowerCheckOp = 4608 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4609 ? &Op 4610 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4611 ? &Op2 4612 : nullptr; 4613 const SDValue *UpperCheckOp = 4614 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4615 ? &Op 4616 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4617 ? &Op2 4618 : nullptr; 4619 4620 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4621 return false; 4622 4623 // Check that the constant in the lower-bound check is 4624 // the opposite of the constant in the upper-bound check 4625 // in 1's complement. 4626 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4627 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4628 int64_t PosVal = std::max(Val1, Val2); 4629 int64_t NegVal = std::min(Val1, Val2); 4630 4631 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4632 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4633 isPowerOf2_64(PosVal + 1)) { 4634 4635 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4636 if (Val1 == ~Val2) 4637 usat = false; 4638 else if (NegVal == 0) 4639 usat = true; 4640 else 4641 return false; 4642 4643 V = V2; 4644 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4645 4646 return true; 4647 } 4648 4649 return false; 4650 } 4651 4652 // Check if a condition of the type x < k ? k : x can be converted into a 4653 // bit operation instead of conditional moves. 4654 // Currently this is allowed given: 4655 // - The conditions and values match up 4656 // - k is 0 or -1 (all ones) 4657 // This function will not check the last condition, thats up to the caller 4658 // It returns true if the transformation can be made, and in such case 4659 // returns x in V, and k in SatK. 4660 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4661 SDValue &SatK) 4662 { 4663 SDValue LHS = Op.getOperand(0); 4664 SDValue RHS = Op.getOperand(1); 4665 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4666 SDValue TrueVal = Op.getOperand(2); 4667 SDValue FalseVal = Op.getOperand(3); 4668 4669 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4670 ? &RHS 4671 : nullptr; 4672 4673 // No constant operation in comparison, early out 4674 if (!K) 4675 return false; 4676 4677 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4678 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4679 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4680 4681 // If the constant on left and right side, or variable on left and right, 4682 // does not match, early out 4683 if (*K != KTmp || V != VTmp) 4684 return false; 4685 4686 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4687 SatK = *K; 4688 return true; 4689 } 4690 4691 return false; 4692 } 4693 4694 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 4695 if (VT == MVT::f32) 4696 return !Subtarget->hasVFP2Base(); 4697 if (VT == MVT::f64) 4698 return !Subtarget->hasFP64(); 4699 if (VT == MVT::f16) 4700 return !Subtarget->hasFullFP16(); 4701 return false; 4702 } 4703 4704 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4705 EVT VT = Op.getValueType(); 4706 SDLoc dl(Op); 4707 4708 // Try to convert two saturating conditional selects into a single SSAT 4709 SDValue SatValue; 4710 uint64_t SatConstant; 4711 bool SatUSat; 4712 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4713 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4714 if (SatUSat) 4715 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4716 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4717 else 4718 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4719 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4720 } 4721 4722 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4723 // into more efficient bit operations, which is possible when k is 0 or -1 4724 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4725 // single instructions. On Thumb the shift and the bit operation will be two 4726 // instructions. 4727 // Only allow this transformation on full-width (32-bit) operations 4728 SDValue LowerSatConstant; 4729 if (VT == MVT::i32 && 4730 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4731 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4732 DAG.getConstant(31, dl, VT)); 4733 if (isNullConstant(LowerSatConstant)) { 4734 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4735 DAG.getAllOnesConstant(dl, VT)); 4736 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4737 } else if (isAllOnesConstant(LowerSatConstant)) 4738 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4739 } 4740 4741 SDValue LHS = Op.getOperand(0); 4742 SDValue RHS = Op.getOperand(1); 4743 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4744 SDValue TrueVal = Op.getOperand(2); 4745 SDValue FalseVal = Op.getOperand(3); 4746 4747 if (isUnsupportedFloatingType(LHS.getValueType())) { 4748 DAG.getTargetLoweringInfo().softenSetCCOperands( 4749 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 4750 4751 // If softenSetCCOperands only returned one value, we should compare it to 4752 // zero. 4753 if (!RHS.getNode()) { 4754 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4755 CC = ISD::SETNE; 4756 } 4757 } 4758 4759 if (LHS.getValueType() == MVT::i32) { 4760 // Try to generate VSEL on ARMv8. 4761 // The VSEL instruction can't use all the usual ARM condition 4762 // codes: it only has two bits to select the condition code, so it's 4763 // constrained to use only GE, GT, VS and EQ. 4764 // 4765 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4766 // swap the operands of the previous compare instruction (effectively 4767 // inverting the compare condition, swapping 'less' and 'greater') and 4768 // sometimes need to swap the operands to the VSEL (which inverts the 4769 // condition in the sense of firing whenever the previous condition didn't) 4770 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 4771 TrueVal.getValueType() == MVT::f32 || 4772 TrueVal.getValueType() == MVT::f64)) { 4773 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4774 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4775 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4776 CC = ISD::getSetCCInverse(CC, true); 4777 std::swap(TrueVal, FalseVal); 4778 } 4779 } 4780 4781 SDValue ARMcc; 4782 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4783 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4784 // Choose GE over PL, which vsel does now support 4785 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL) 4786 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32); 4787 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4788 } 4789 4790 ARMCC::CondCodes CondCode, CondCode2; 4791 bool InvalidOnQNaN; 4792 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4793 4794 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 4795 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 4796 // must use VSEL (limited condition codes), due to not having conditional f16 4797 // moves. 4798 if (Subtarget->hasFPARMv8Base() && 4799 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 4800 (TrueVal.getValueType() == MVT::f16 || 4801 TrueVal.getValueType() == MVT::f32 || 4802 TrueVal.getValueType() == MVT::f64)) { 4803 bool swpCmpOps = false; 4804 bool swpVselOps = false; 4805 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4806 4807 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4808 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4809 if (swpCmpOps) 4810 std::swap(LHS, RHS); 4811 if (swpVselOps) 4812 std::swap(TrueVal, FalseVal); 4813 } 4814 } 4815 4816 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4817 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4818 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4819 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4820 if (CondCode2 != ARMCC::AL) { 4821 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4822 // FIXME: Needs another CMP because flag can have but one use. 4823 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4824 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4825 } 4826 return Result; 4827 } 4828 4829 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4830 /// to morph to an integer compare sequence. 4831 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4832 const ARMSubtarget *Subtarget) { 4833 SDNode *N = Op.getNode(); 4834 if (!N->hasOneUse()) 4835 // Otherwise it requires moving the value from fp to integer registers. 4836 return false; 4837 if (!N->getNumValues()) 4838 return false; 4839 EVT VT = Op.getValueType(); 4840 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4841 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4842 // vmrs are very slow, e.g. cortex-a8. 4843 return false; 4844 4845 if (isFloatingPointZero(Op)) { 4846 SeenZero = true; 4847 return true; 4848 } 4849 return ISD::isNormalLoad(N); 4850 } 4851 4852 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4853 if (isFloatingPointZero(Op)) 4854 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4855 4856 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4857 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4858 Ld->getPointerInfo(), Ld->getAlignment(), 4859 Ld->getMemOperand()->getFlags()); 4860 4861 llvm_unreachable("Unknown VFP cmp argument!"); 4862 } 4863 4864 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4865 SDValue &RetVal1, SDValue &RetVal2) { 4866 SDLoc dl(Op); 4867 4868 if (isFloatingPointZero(Op)) { 4869 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4870 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4871 return; 4872 } 4873 4874 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4875 SDValue Ptr = Ld->getBasePtr(); 4876 RetVal1 = 4877 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4878 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4879 4880 EVT PtrType = Ptr.getValueType(); 4881 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4882 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4883 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4884 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4885 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4886 Ld->getMemOperand()->getFlags()); 4887 return; 4888 } 4889 4890 llvm_unreachable("Unknown VFP cmp argument!"); 4891 } 4892 4893 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4894 /// f32 and even f64 comparisons to integer ones. 4895 SDValue 4896 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4897 SDValue Chain = Op.getOperand(0); 4898 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4899 SDValue LHS = Op.getOperand(2); 4900 SDValue RHS = Op.getOperand(3); 4901 SDValue Dest = Op.getOperand(4); 4902 SDLoc dl(Op); 4903 4904 bool LHSSeenZero = false; 4905 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4906 bool RHSSeenZero = false; 4907 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4908 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4909 // If unsafe fp math optimization is enabled and there are no other uses of 4910 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4911 // to an integer comparison. 4912 if (CC == ISD::SETOEQ) 4913 CC = ISD::SETEQ; 4914 else if (CC == ISD::SETUNE) 4915 CC = ISD::SETNE; 4916 4917 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4918 SDValue ARMcc; 4919 if (LHS.getValueType() == MVT::f32) { 4920 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4921 bitcastf32Toi32(LHS, DAG), Mask); 4922 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4923 bitcastf32Toi32(RHS, DAG), Mask); 4924 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4925 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4926 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4927 Chain, Dest, ARMcc, CCR, Cmp); 4928 } 4929 4930 SDValue LHS1, LHS2; 4931 SDValue RHS1, RHS2; 4932 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4933 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4934 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4935 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4936 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4937 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4938 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4939 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4940 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4941 } 4942 4943 return SDValue(); 4944 } 4945 4946 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4947 SDValue Chain = Op.getOperand(0); 4948 SDValue Cond = Op.getOperand(1); 4949 SDValue Dest = Op.getOperand(2); 4950 SDLoc dl(Op); 4951 4952 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4953 // instruction. 4954 unsigned Opc = Cond.getOpcode(); 4955 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4956 !Subtarget->isThumb1Only(); 4957 if (Cond.getResNo() == 1 && 4958 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4959 Opc == ISD::USUBO || OptimizeMul)) { 4960 // Only lower legal XALUO ops. 4961 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4962 return SDValue(); 4963 4964 // The actual operation with overflow check. 4965 SDValue Value, OverflowCmp; 4966 SDValue ARMcc; 4967 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4968 4969 // Reverse the condition code. 4970 ARMCC::CondCodes CondCode = 4971 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4972 CondCode = ARMCC::getOppositeCondition(CondCode); 4973 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4974 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4975 4976 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4977 OverflowCmp); 4978 } 4979 4980 return SDValue(); 4981 } 4982 4983 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4984 SDValue Chain = Op.getOperand(0); 4985 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4986 SDValue LHS = Op.getOperand(2); 4987 SDValue RHS = Op.getOperand(3); 4988 SDValue Dest = Op.getOperand(4); 4989 SDLoc dl(Op); 4990 4991 if (isUnsupportedFloatingType(LHS.getValueType())) { 4992 DAG.getTargetLoweringInfo().softenSetCCOperands( 4993 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 4994 4995 // If softenSetCCOperands only returned one value, we should compare it to 4996 // zero. 4997 if (!RHS.getNode()) { 4998 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4999 CC = ISD::SETNE; 5000 } 5001 } 5002 5003 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5004 // instruction. 5005 unsigned Opc = LHS.getOpcode(); 5006 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 5007 !Subtarget->isThumb1Only(); 5008 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 5009 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 5010 Opc == ISD::USUBO || OptimizeMul) && 5011 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5012 // Only lower legal XALUO ops. 5013 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5014 return SDValue(); 5015 5016 // The actual operation with overflow check. 5017 SDValue Value, OverflowCmp; 5018 SDValue ARMcc; 5019 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 5020 5021 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 5022 // Reverse the condition code. 5023 ARMCC::CondCodes CondCode = 5024 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 5025 CondCode = ARMCC::getOppositeCondition(CondCode); 5026 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 5027 } 5028 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5029 5030 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 5031 OverflowCmp); 5032 } 5033 5034 if (LHS.getValueType() == MVT::i32) { 5035 SDValue ARMcc; 5036 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 5037 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5038 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 5039 Chain, Dest, ARMcc, CCR, Cmp); 5040 } 5041 5042 if (getTargetMachine().Options.UnsafeFPMath && 5043 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 5044 CC == ISD::SETNE || CC == ISD::SETUNE)) { 5045 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 5046 return Result; 5047 } 5048 5049 ARMCC::CondCodes CondCode, CondCode2; 5050 bool InvalidOnQNaN; 5051 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 5052 5053 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 5054 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 5055 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5056 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 5057 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 5058 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5059 if (CondCode2 != ARMCC::AL) { 5060 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 5061 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 5062 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 5063 } 5064 return Res; 5065 } 5066 5067 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 5068 SDValue Chain = Op.getOperand(0); 5069 SDValue Table = Op.getOperand(1); 5070 SDValue Index = Op.getOperand(2); 5071 SDLoc dl(Op); 5072 5073 EVT PTy = getPointerTy(DAG.getDataLayout()); 5074 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 5075 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 5076 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 5077 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 5078 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 5079 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 5080 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 5081 // which does another jump to the destination. This also makes it easier 5082 // to translate it to TBB / TBH later (Thumb2 only). 5083 // FIXME: This might not work if the function is extremely large. 5084 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 5085 Addr, Op.getOperand(2), JTI); 5086 } 5087 if (isPositionIndependent() || Subtarget->isROPI()) { 5088 Addr = 5089 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 5090 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5091 Chain = Addr.getValue(1); 5092 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 5093 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5094 } else { 5095 Addr = 5096 DAG.getLoad(PTy, dl, Chain, Addr, 5097 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 5098 Chain = Addr.getValue(1); 5099 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 5100 } 5101 } 5102 5103 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 5104 EVT VT = Op.getValueType(); 5105 SDLoc dl(Op); 5106 5107 if (Op.getValueType().getVectorElementType() == MVT::i32) { 5108 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 5109 return Op; 5110 return DAG.UnrollVectorOp(Op.getNode()); 5111 } 5112 5113 const bool HasFullFP16 = 5114 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5115 5116 EVT NewTy; 5117 const EVT OpTy = Op.getOperand(0).getValueType(); 5118 if (OpTy == MVT::v4f32) 5119 NewTy = MVT::v4i32; 5120 else if (OpTy == MVT::v4f16 && HasFullFP16) 5121 NewTy = MVT::v4i16; 5122 else if (OpTy == MVT::v8f16 && HasFullFP16) 5123 NewTy = MVT::v8i16; 5124 else 5125 llvm_unreachable("Invalid type for custom lowering!"); 5126 5127 if (VT != MVT::v4i16 && VT != MVT::v8i16) 5128 return DAG.UnrollVectorOp(Op.getNode()); 5129 5130 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 5131 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 5132 } 5133 5134 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 5135 EVT VT = Op.getValueType(); 5136 if (VT.isVector()) 5137 return LowerVectorFP_TO_INT(Op, DAG); 5138 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) { 5139 RTLIB::Libcall LC; 5140 if (Op.getOpcode() == ISD::FP_TO_SINT) 5141 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 5142 Op.getValueType()); 5143 else 5144 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 5145 Op.getValueType()); 5146 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5147 /*isSigned*/ false, SDLoc(Op)).first; 5148 } 5149 5150 return Op; 5151 } 5152 5153 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5154 EVT VT = Op.getValueType(); 5155 SDLoc dl(Op); 5156 5157 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5158 if (VT.getVectorElementType() == MVT::f32) 5159 return Op; 5160 return DAG.UnrollVectorOp(Op.getNode()); 5161 } 5162 5163 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5164 Op.getOperand(0).getValueType() == MVT::v8i16) && 5165 "Invalid type for custom lowering!"); 5166 5167 const bool HasFullFP16 = 5168 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5169 5170 EVT DestVecType; 5171 if (VT == MVT::v4f32) 5172 DestVecType = MVT::v4i32; 5173 else if (VT == MVT::v4f16 && HasFullFP16) 5174 DestVecType = MVT::v4i16; 5175 else if (VT == MVT::v8f16 && HasFullFP16) 5176 DestVecType = MVT::v8i16; 5177 else 5178 return DAG.UnrollVectorOp(Op.getNode()); 5179 5180 unsigned CastOpc; 5181 unsigned Opc; 5182 switch (Op.getOpcode()) { 5183 default: llvm_unreachable("Invalid opcode!"); 5184 case ISD::SINT_TO_FP: 5185 CastOpc = ISD::SIGN_EXTEND; 5186 Opc = ISD::SINT_TO_FP; 5187 break; 5188 case ISD::UINT_TO_FP: 5189 CastOpc = ISD::ZERO_EXTEND; 5190 Opc = ISD::UINT_TO_FP; 5191 break; 5192 } 5193 5194 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5195 return DAG.getNode(Opc, dl, VT, Op); 5196 } 5197 5198 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5199 EVT VT = Op.getValueType(); 5200 if (VT.isVector()) 5201 return LowerVectorINT_TO_FP(Op, DAG); 5202 if (isUnsupportedFloatingType(VT)) { 5203 RTLIB::Libcall LC; 5204 if (Op.getOpcode() == ISD::SINT_TO_FP) 5205 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5206 Op.getValueType()); 5207 else 5208 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5209 Op.getValueType()); 5210 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5211 /*isSigned*/ false, SDLoc(Op)).first; 5212 } 5213 5214 return Op; 5215 } 5216 5217 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5218 // Implement fcopysign with a fabs and a conditional fneg. 5219 SDValue Tmp0 = Op.getOperand(0); 5220 SDValue Tmp1 = Op.getOperand(1); 5221 SDLoc dl(Op); 5222 EVT VT = Op.getValueType(); 5223 EVT SrcVT = Tmp1.getValueType(); 5224 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5225 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5226 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5227 5228 if (UseNEON) { 5229 // Use VBSL to copy the sign bit. 5230 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80); 5231 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5232 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5233 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5234 if (VT == MVT::f64) 5235 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5236 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5237 DAG.getConstant(32, dl, MVT::i32)); 5238 else /*if (VT == MVT::f32)*/ 5239 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5240 if (SrcVT == MVT::f32) { 5241 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5242 if (VT == MVT::f64) 5243 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT, 5244 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5245 DAG.getConstant(32, dl, MVT::i32)); 5246 } else if (VT == MVT::f32) 5247 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64, 5248 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5249 DAG.getConstant(32, dl, MVT::i32)); 5250 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5251 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5252 5253 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), 5254 dl, MVT::i32); 5255 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5256 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5257 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5258 5259 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5260 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5261 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5262 if (VT == MVT::f32) { 5263 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5264 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5265 DAG.getConstant(0, dl, MVT::i32)); 5266 } else { 5267 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5268 } 5269 5270 return Res; 5271 } 5272 5273 // Bitcast operand 1 to i32. 5274 if (SrcVT == MVT::f64) 5275 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5276 Tmp1).getValue(1); 5277 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5278 5279 // Or in the signbit with integer operations. 5280 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5281 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5282 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5283 if (VT == MVT::f32) { 5284 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5285 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5286 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5287 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5288 } 5289 5290 // f64: Or the high part with signbit and then combine two parts. 5291 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5292 Tmp0); 5293 SDValue Lo = Tmp0.getValue(0); 5294 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5295 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5296 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5297 } 5298 5299 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5300 MachineFunction &MF = DAG.getMachineFunction(); 5301 MachineFrameInfo &MFI = MF.getFrameInfo(); 5302 MFI.setReturnAddressIsTaken(true); 5303 5304 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5305 return SDValue(); 5306 5307 EVT VT = Op.getValueType(); 5308 SDLoc dl(Op); 5309 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5310 if (Depth) { 5311 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5312 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5313 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5314 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5315 MachinePointerInfo()); 5316 } 5317 5318 // Return LR, which contains the return address. Mark it an implicit live-in. 5319 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5320 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5321 } 5322 5323 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5324 const ARMBaseRegisterInfo &ARI = 5325 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5326 MachineFunction &MF = DAG.getMachineFunction(); 5327 MachineFrameInfo &MFI = MF.getFrameInfo(); 5328 MFI.setFrameAddressIsTaken(true); 5329 5330 EVT VT = Op.getValueType(); 5331 SDLoc dl(Op); // FIXME probably not meaningful 5332 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5333 unsigned FrameReg = ARI.getFrameRegister(MF); 5334 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5335 while (Depth--) 5336 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5337 MachinePointerInfo()); 5338 return FrameAddr; 5339 } 5340 5341 // FIXME? Maybe this could be a TableGen attribute on some registers and 5342 // this table could be generated automatically from RegInfo. 5343 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5344 SelectionDAG &DAG) const { 5345 unsigned Reg = StringSwitch<unsigned>(RegName) 5346 .Case("sp", ARM::SP) 5347 .Default(0); 5348 if (Reg) 5349 return Reg; 5350 report_fatal_error(Twine("Invalid register name \"" 5351 + StringRef(RegName) + "\".")); 5352 } 5353 5354 // Result is 64 bit value so split into two 32 bit values and return as a 5355 // pair of values. 5356 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5357 SelectionDAG &DAG) { 5358 SDLoc DL(N); 5359 5360 // This function is only supposed to be called for i64 type destination. 5361 assert(N->getValueType(0) == MVT::i64 5362 && "ExpandREAD_REGISTER called for non-i64 type result."); 5363 5364 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5365 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5366 N->getOperand(0), 5367 N->getOperand(1)); 5368 5369 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5370 Read.getValue(1))); 5371 Results.push_back(Read.getOperand(0)); 5372 } 5373 5374 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5375 /// When \p DstVT, the destination type of \p BC, is on the vector 5376 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5377 /// it might be possible to combine them, such that everything stays on the 5378 /// vector register bank. 5379 /// \p return The node that would replace \p BT, if the combine 5380 /// is possible. 5381 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5382 SelectionDAG &DAG) { 5383 SDValue Op = BC->getOperand(0); 5384 EVT DstVT = BC->getValueType(0); 5385 5386 // The only vector instruction that can produce a scalar (remember, 5387 // since the bitcast was about to be turned into VMOVDRR, the source 5388 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5389 // Moreover, we can do this combine only if there is one use. 5390 // Finally, if the destination type is not a vector, there is not 5391 // much point on forcing everything on the vector bank. 5392 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5393 !Op.hasOneUse()) 5394 return SDValue(); 5395 5396 // If the index is not constant, we will introduce an additional 5397 // multiply that will stick. 5398 // Give up in that case. 5399 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5400 if (!Index) 5401 return SDValue(); 5402 unsigned DstNumElt = DstVT.getVectorNumElements(); 5403 5404 // Compute the new index. 5405 const APInt &APIntIndex = Index->getAPIntValue(); 5406 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5407 NewIndex *= APIntIndex; 5408 // Check if the new constant index fits into i32. 5409 if (NewIndex.getBitWidth() > 32) 5410 return SDValue(); 5411 5412 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5413 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5414 SDLoc dl(Op); 5415 SDValue ExtractSrc = Op.getOperand(0); 5416 EVT VecVT = EVT::getVectorVT( 5417 *DAG.getContext(), DstVT.getScalarType(), 5418 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5419 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5420 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5421 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5422 } 5423 5424 /// ExpandBITCAST - If the target supports VFP, this function is called to 5425 /// expand a bit convert where either the source or destination type is i64 to 5426 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5427 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5428 /// vectors), since the legalizer won't know what to do with that. 5429 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5430 const ARMSubtarget *Subtarget) { 5431 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5432 SDLoc dl(N); 5433 SDValue Op = N->getOperand(0); 5434 5435 // This function is only supposed to be called for i64 types, either as the 5436 // source or destination of the bit convert. 5437 EVT SrcVT = Op.getValueType(); 5438 EVT DstVT = N->getValueType(0); 5439 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5440 5441 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5442 // FullFP16: half values are passed in S-registers, and we don't 5443 // need any of the bitcast and moves: 5444 // 5445 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5446 // t5: i32 = bitcast t2 5447 // t18: f16 = ARMISD::VMOVhr t5 5448 if (Op.getOpcode() != ISD::CopyFromReg || 5449 Op.getValueType() != MVT::f32) 5450 return SDValue(); 5451 5452 auto Move = N->use_begin(); 5453 if (Move->getOpcode() != ARMISD::VMOVhr) 5454 return SDValue(); 5455 5456 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5457 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5458 DAG.ReplaceAllUsesWith(*Move, &Copy); 5459 return Copy; 5460 } 5461 5462 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5463 if (!HasFullFP16) 5464 return SDValue(); 5465 // SoftFP: read half-precision arguments: 5466 // 5467 // t2: i32,ch = ... 5468 // t7: i16 = truncate t2 <~~~~ Op 5469 // t8: f16 = bitcast t7 <~~~~ N 5470 // 5471 if (Op.getOperand(0).getValueType() == MVT::i32) 5472 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5473 MVT::f16, Op.getOperand(0)); 5474 5475 return SDValue(); 5476 } 5477 5478 // Half-precision return values 5479 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5480 if (!HasFullFP16) 5481 return SDValue(); 5482 // 5483 // t11: f16 = fadd t8, t10 5484 // t12: i16 = bitcast t11 <~~~ SDNode N 5485 // t13: i32 = zero_extend t12 5486 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5487 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5488 // 5489 // transform this into: 5490 // 5491 // t20: i32 = ARMISD::VMOVrh t11 5492 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5493 // 5494 auto ZeroExtend = N->use_begin(); 5495 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5496 ZeroExtend->getValueType(0) != MVT::i32) 5497 return SDValue(); 5498 5499 auto Copy = ZeroExtend->use_begin(); 5500 if (Copy->getOpcode() == ISD::CopyToReg && 5501 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5502 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5503 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5504 return Cvt; 5505 } 5506 return SDValue(); 5507 } 5508 5509 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5510 return SDValue(); 5511 5512 // Turn i64->f64 into VMOVDRR. 5513 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5514 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5515 // if we can combine the bitcast with its source. 5516 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5517 return Val; 5518 5519 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5520 DAG.getConstant(0, dl, MVT::i32)); 5521 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5522 DAG.getConstant(1, dl, MVT::i32)); 5523 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5524 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5525 } 5526 5527 // Turn f64->i64 into VMOVRRD. 5528 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5529 SDValue Cvt; 5530 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5531 SrcVT.getVectorNumElements() > 1) 5532 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5533 DAG.getVTList(MVT::i32, MVT::i32), 5534 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5535 else 5536 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5537 DAG.getVTList(MVT::i32, MVT::i32), Op); 5538 // Merge the pieces into a single i64 value. 5539 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5540 } 5541 5542 return SDValue(); 5543 } 5544 5545 /// getZeroVector - Returns a vector of specified type with all zero elements. 5546 /// Zero vectors are used to represent vector negation and in those cases 5547 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5548 /// not support i64 elements, so sometimes the zero vectors will need to be 5549 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5550 /// zero vector. 5551 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5552 assert(VT.isVector() && "Expected a vector type"); 5553 // The canonical modified immediate encoding of a zero vector is....0! 5554 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5555 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5556 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5557 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5558 } 5559 5560 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5561 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5562 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5563 SelectionDAG &DAG) const { 5564 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5565 EVT VT = Op.getValueType(); 5566 unsigned VTBits = VT.getSizeInBits(); 5567 SDLoc dl(Op); 5568 SDValue ShOpLo = Op.getOperand(0); 5569 SDValue ShOpHi = Op.getOperand(1); 5570 SDValue ShAmt = Op.getOperand(2); 5571 SDValue ARMcc; 5572 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5573 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5574 5575 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5576 5577 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5578 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5579 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5580 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5581 DAG.getConstant(VTBits, dl, MVT::i32)); 5582 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5583 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5584 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5585 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5586 ISD::SETGE, ARMcc, DAG, dl); 5587 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5588 ARMcc, CCR, CmpLo); 5589 5590 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5591 SDValue HiBigShift = Opc == ISD::SRA 5592 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5593 DAG.getConstant(VTBits - 1, dl, VT)) 5594 : DAG.getConstant(0, dl, VT); 5595 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5596 ISD::SETGE, ARMcc, DAG, dl); 5597 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5598 ARMcc, CCR, CmpHi); 5599 5600 SDValue Ops[2] = { Lo, Hi }; 5601 return DAG.getMergeValues(Ops, dl); 5602 } 5603 5604 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5605 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5606 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5607 SelectionDAG &DAG) const { 5608 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5609 EVT VT = Op.getValueType(); 5610 unsigned VTBits = VT.getSizeInBits(); 5611 SDLoc dl(Op); 5612 SDValue ShOpLo = Op.getOperand(0); 5613 SDValue ShOpHi = Op.getOperand(1); 5614 SDValue ShAmt = Op.getOperand(2); 5615 SDValue ARMcc; 5616 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5617 5618 assert(Op.getOpcode() == ISD::SHL_PARTS); 5619 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5620 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5621 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5622 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5623 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5624 5625 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5626 DAG.getConstant(VTBits, dl, MVT::i32)); 5627 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5628 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5629 ISD::SETGE, ARMcc, DAG, dl); 5630 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5631 ARMcc, CCR, CmpHi); 5632 5633 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5634 ISD::SETGE, ARMcc, DAG, dl); 5635 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5636 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5637 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5638 5639 SDValue Ops[2] = { Lo, Hi }; 5640 return DAG.getMergeValues(Ops, dl); 5641 } 5642 5643 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5644 SelectionDAG &DAG) const { 5645 // The rounding mode is in bits 23:22 of the FPSCR. 5646 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5647 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5648 // so that the shift + and get folded into a bitfield extract. 5649 SDLoc dl(Op); 5650 SDValue Ops[] = { DAG.getEntryNode(), 5651 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5652 5653 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5654 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5655 DAG.getConstant(1U << 22, dl, MVT::i32)); 5656 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5657 DAG.getConstant(22, dl, MVT::i32)); 5658 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5659 DAG.getConstant(3, dl, MVT::i32)); 5660 } 5661 5662 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5663 const ARMSubtarget *ST) { 5664 SDLoc dl(N); 5665 EVT VT = N->getValueType(0); 5666 if (VT.isVector()) { 5667 assert(ST->hasNEON()); 5668 5669 // Compute the least significant set bit: LSB = X & -X 5670 SDValue X = N->getOperand(0); 5671 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5672 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5673 5674 EVT ElemTy = VT.getVectorElementType(); 5675 5676 if (ElemTy == MVT::i8) { 5677 // Compute with: cttz(x) = ctpop(lsb - 1) 5678 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5679 DAG.getTargetConstant(1, dl, ElemTy)); 5680 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5681 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5682 } 5683 5684 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5685 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5686 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5687 unsigned NumBits = ElemTy.getSizeInBits(); 5688 SDValue WidthMinus1 = 5689 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5690 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5691 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5692 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5693 } 5694 5695 // Compute with: cttz(x) = ctpop(lsb - 1) 5696 5697 // Compute LSB - 1. 5698 SDValue Bits; 5699 if (ElemTy == MVT::i64) { 5700 // Load constant 0xffff'ffff'ffff'ffff to register. 5701 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5702 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5703 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5704 } else { 5705 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5706 DAG.getTargetConstant(1, dl, ElemTy)); 5707 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5708 } 5709 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5710 } 5711 5712 if (!ST->hasV6T2Ops()) 5713 return SDValue(); 5714 5715 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5716 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5717 } 5718 5719 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5720 const ARMSubtarget *ST) { 5721 EVT VT = N->getValueType(0); 5722 SDLoc DL(N); 5723 5724 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5725 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5726 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5727 "Unexpected type for custom ctpop lowering"); 5728 5729 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5730 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5731 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 5732 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 5733 5734 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5735 unsigned EltSize = 8; 5736 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5737 while (EltSize != VT.getScalarSizeInBits()) { 5738 SmallVector<SDValue, 8> Ops; 5739 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 5740 TLI.getPointerTy(DAG.getDataLayout()))); 5741 Ops.push_back(Res); 5742 5743 EltSize *= 2; 5744 NumElts /= 2; 5745 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5746 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 5747 } 5748 5749 return Res; 5750 } 5751 5752 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 5753 /// operand of a vector shift operation, where all the elements of the 5754 /// build_vector must have the same constant integer value. 5755 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 5756 // Ignore bit_converts. 5757 while (Op.getOpcode() == ISD::BITCAST) 5758 Op = Op.getOperand(0); 5759 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 5760 APInt SplatBits, SplatUndef; 5761 unsigned SplatBitSize; 5762 bool HasAnyUndefs; 5763 if (!BVN || 5764 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 5765 ElementBits) || 5766 SplatBitSize > ElementBits) 5767 return false; 5768 Cnt = SplatBits.getSExtValue(); 5769 return true; 5770 } 5771 5772 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 5773 /// operand of a vector shift left operation. That value must be in the range: 5774 /// 0 <= Value < ElementBits for a left shift; or 5775 /// 0 <= Value <= ElementBits for a long left shift. 5776 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 5777 assert(VT.isVector() && "vector shift count is not a vector type"); 5778 int64_t ElementBits = VT.getScalarSizeInBits(); 5779 if (!getVShiftImm(Op, ElementBits, Cnt)) 5780 return false; 5781 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 5782 } 5783 5784 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 5785 /// operand of a vector shift right operation. For a shift opcode, the value 5786 /// is positive, but for an intrinsic the value count must be negative. The 5787 /// absolute value must be in the range: 5788 /// 1 <= |Value| <= ElementBits for a right shift; or 5789 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 5790 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 5791 int64_t &Cnt) { 5792 assert(VT.isVector() && "vector shift count is not a vector type"); 5793 int64_t ElementBits = VT.getScalarSizeInBits(); 5794 if (!getVShiftImm(Op, ElementBits, Cnt)) 5795 return false; 5796 if (!isIntrinsic) 5797 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 5798 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) { 5799 Cnt = -Cnt; 5800 return true; 5801 } 5802 return false; 5803 } 5804 5805 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5806 const ARMSubtarget *ST) { 5807 EVT VT = N->getValueType(0); 5808 SDLoc dl(N); 5809 int64_t Cnt; 5810 5811 if (!VT.isVector()) 5812 return SDValue(); 5813 5814 // We essentially have two forms here. Shift by an immediate and shift by a 5815 // vector register (there are also shift by a gpr, but that is just handled 5816 // with a tablegen pattern). We cannot easily match shift by an immediate in 5817 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM. 5818 // For shifting by a vector, we don't have VSHR, only VSHL (which can be 5819 // signed or unsigned, and a negative shift indicates a shift right). 5820 if (N->getOpcode() == ISD::SHL) { 5821 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 5822 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 5823 DAG.getConstant(Cnt, dl, MVT::i32)); 5824 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0), 5825 N->getOperand(1)); 5826 } 5827 5828 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && 5829 "unexpected vector shift opcode"); 5830 5831 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 5832 unsigned VShiftOpc = 5833 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 5834 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 5835 DAG.getConstant(Cnt, dl, MVT::i32)); 5836 } 5837 5838 // Other right shifts we don't have operations for (we use a shift left by a 5839 // negative number). 5840 EVT ShiftVT = N->getOperand(1).getValueType(); 5841 SDValue NegatedCount = DAG.getNode( 5842 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1)); 5843 unsigned VShiftOpc = 5844 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu); 5845 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount); 5846 } 5847 5848 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5849 const ARMSubtarget *ST) { 5850 EVT VT = N->getValueType(0); 5851 SDLoc dl(N); 5852 5853 // We can get here for a node like i32 = ISD::SHL i32, i64 5854 if (VT != MVT::i64) 5855 return SDValue(); 5856 5857 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 5858 N->getOpcode() == ISD::SHL) && 5859 "Unknown shift to lower!"); 5860 5861 unsigned ShOpc = N->getOpcode(); 5862 if (ST->hasMVEIntegerOps()) { 5863 SDValue ShAmt = N->getOperand(1); 5864 unsigned ShPartsOpc = ARMISD::LSLL; 5865 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 5866 5867 // If the shift amount is greater than 32 then do the default optimisation 5868 if (Con && Con->getZExtValue() > 32) 5869 return SDValue(); 5870 5871 // Extract the lower 32 bits of the shift amount if it's an i64 5872 if (ShAmt->getValueType(0) == MVT::i64) 5873 ShAmt = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, ShAmt, 5874 DAG.getConstant(0, dl, MVT::i32)); 5875 5876 if (ShOpc == ISD::SRL) { 5877 if (!Con) 5878 // There is no t2LSRLr instruction so negate and perform an lsll if the 5879 // shift amount is in a register, emulating a right shift. 5880 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5881 DAG.getConstant(0, dl, MVT::i32), ShAmt); 5882 else 5883 // Else generate an lsrl on the immediate shift amount 5884 ShPartsOpc = ARMISD::LSRL; 5885 } else if (ShOpc == ISD::SRA) 5886 ShPartsOpc = ARMISD::ASRL; 5887 5888 // Lower 32 bits of the destination/source 5889 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5890 DAG.getConstant(0, dl, MVT::i32)); 5891 // Upper 32 bits of the destination/source 5892 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5893 DAG.getConstant(1, dl, MVT::i32)); 5894 5895 // Generate the shift operation as computed above 5896 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 5897 ShAmt); 5898 // The upper 32 bits come from the second return value of lsll 5899 Hi = SDValue(Lo.getNode(), 1); 5900 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5901 } 5902 5903 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5904 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 5905 return SDValue(); 5906 5907 // If we are in thumb mode, we don't have RRX. 5908 if (ST->isThumb1Only()) 5909 return SDValue(); 5910 5911 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5912 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5913 DAG.getConstant(0, dl, MVT::i32)); 5914 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5915 DAG.getConstant(1, dl, MVT::i32)); 5916 5917 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5918 // captures the result into a carry flag. 5919 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5920 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5921 5922 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5923 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5924 5925 // Merge the pieces into a single i64 value. 5926 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5927 } 5928 5929 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, 5930 const ARMSubtarget *ST) { 5931 bool Invert = false; 5932 bool Swap = false; 5933 unsigned Opc = ARMCC::AL; 5934 5935 SDValue Op0 = Op.getOperand(0); 5936 SDValue Op1 = Op.getOperand(1); 5937 SDValue CC = Op.getOperand(2); 5938 EVT VT = Op.getValueType(); 5939 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5940 SDLoc dl(Op); 5941 5942 EVT CmpVT; 5943 if (ST->hasNEON()) 5944 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5945 else { 5946 assert(ST->hasMVEIntegerOps() && 5947 "No hardware support for integer vector comparison!"); 5948 5949 if (Op.getValueType().getVectorElementType() != MVT::i1) 5950 return SDValue(); 5951 5952 // Make sure we expand floating point setcc to scalar if we do not have 5953 // mve.fp, so that we can handle them from there. 5954 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps()) 5955 return SDValue(); 5956 5957 CmpVT = VT; 5958 } 5959 5960 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5961 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5962 // Special-case integer 64-bit equality comparisons. They aren't legal, 5963 // but they can be lowered with a few vector instructions. 5964 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5965 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5966 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5967 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5968 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5969 DAG.getCondCode(ISD::SETEQ)); 5970 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5971 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5972 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5973 if (SetCCOpcode == ISD::SETNE) 5974 Merged = DAG.getNOT(dl, Merged, CmpVT); 5975 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5976 return Merged; 5977 } 5978 5979 if (CmpVT.getVectorElementType() == MVT::i64) 5980 // 64-bit comparisons are not legal in general. 5981 return SDValue(); 5982 5983 if (Op1.getValueType().isFloatingPoint()) { 5984 switch (SetCCOpcode) { 5985 default: llvm_unreachable("Illegal FP comparison"); 5986 case ISD::SETUNE: 5987 case ISD::SETNE: 5988 if (ST->hasMVEFloatOps()) { 5989 Opc = ARMCC::NE; break; 5990 } else { 5991 Invert = true; LLVM_FALLTHROUGH; 5992 } 5993 case ISD::SETOEQ: 5994 case ISD::SETEQ: Opc = ARMCC::EQ; break; 5995 case ISD::SETOLT: 5996 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5997 case ISD::SETOGT: 5998 case ISD::SETGT: Opc = ARMCC::GT; break; 5999 case ISD::SETOLE: 6000 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6001 case ISD::SETOGE: 6002 case ISD::SETGE: Opc = ARMCC::GE; break; 6003 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 6004 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break; 6005 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 6006 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break; 6007 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 6008 case ISD::SETONE: { 6009 // Expand this to (OLT | OGT). 6010 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6011 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6012 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6013 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6014 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6015 if (Invert) 6016 Result = DAG.getNOT(dl, Result, VT); 6017 return Result; 6018 } 6019 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; 6020 case ISD::SETO: { 6021 // Expand this to (OLT | OGE). 6022 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0, 6023 DAG.getConstant(ARMCC::GT, dl, MVT::i32)); 6024 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6025 DAG.getConstant(ARMCC::GE, dl, MVT::i32)); 6026 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1); 6027 if (Invert) 6028 Result = DAG.getNOT(dl, Result, VT); 6029 return Result; 6030 } 6031 } 6032 } else { 6033 // Integer comparisons. 6034 switch (SetCCOpcode) { 6035 default: llvm_unreachable("Illegal integer comparison"); 6036 case ISD::SETNE: 6037 if (ST->hasMVEIntegerOps()) { 6038 Opc = ARMCC::NE; break; 6039 } else { 6040 Invert = true; LLVM_FALLTHROUGH; 6041 } 6042 case ISD::SETEQ: Opc = ARMCC::EQ; break; 6043 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 6044 case ISD::SETGT: Opc = ARMCC::GT; break; 6045 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 6046 case ISD::SETGE: Opc = ARMCC::GE; break; 6047 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 6048 case ISD::SETUGT: Opc = ARMCC::HI; break; 6049 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 6050 case ISD::SETUGE: Opc = ARMCC::HS; break; 6051 } 6052 6053 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 6054 if (ST->hasNEON() && Opc == ARMCC::EQ) { 6055 SDValue AndOp; 6056 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6057 AndOp = Op0; 6058 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 6059 AndOp = Op1; 6060 6061 // Ignore bitconvert. 6062 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 6063 AndOp = AndOp.getOperand(0); 6064 6065 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 6066 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 6067 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 6068 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1); 6069 if (!Invert) 6070 Result = DAG.getNOT(dl, Result, VT); 6071 return Result; 6072 } 6073 } 6074 } 6075 6076 if (Swap) 6077 std::swap(Op0, Op1); 6078 6079 // If one of the operands is a constant vector zero, attempt to fold the 6080 // comparison to a specialized compare-against-zero form. 6081 SDValue SingleOp; 6082 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 6083 SingleOp = Op0; 6084 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 6085 if (Opc == ARMCC::GE) 6086 Opc = ARMCC::LE; 6087 else if (Opc == ARMCC::GT) 6088 Opc = ARMCC::LT; 6089 SingleOp = Op1; 6090 } 6091 6092 SDValue Result; 6093 if (SingleOp.getNode()) { 6094 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp, 6095 DAG.getConstant(Opc, dl, MVT::i32)); 6096 } else { 6097 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1, 6098 DAG.getConstant(Opc, dl, MVT::i32)); 6099 } 6100 6101 Result = DAG.getSExtOrTrunc(Result, dl, VT); 6102 6103 if (Invert) 6104 Result = DAG.getNOT(dl, Result, VT); 6105 6106 return Result; 6107 } 6108 6109 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 6110 SDValue LHS = Op.getOperand(0); 6111 SDValue RHS = Op.getOperand(1); 6112 SDValue Carry = Op.getOperand(2); 6113 SDValue Cond = Op.getOperand(3); 6114 SDLoc DL(Op); 6115 6116 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 6117 6118 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 6119 // have to invert the carry first. 6120 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 6121 DAG.getConstant(1, DL, MVT::i32), Carry); 6122 // This converts the boolean value carry into the carry flag. 6123 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 6124 6125 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 6126 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 6127 6128 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 6129 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 6130 SDValue ARMcc = DAG.getConstant( 6131 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 6132 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 6133 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 6134 Cmp.getValue(1), SDValue()); 6135 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 6136 CCR, Chain.getValue(1)); 6137 } 6138 6139 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a 6140 /// valid vector constant for a NEON or MVE instruction with a "modified 6141 /// immediate" operand (e.g., VMOV). If so, return the encoded value. 6142 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 6143 unsigned SplatBitSize, SelectionDAG &DAG, 6144 const SDLoc &dl, EVT &VT, bool is128Bits, 6145 VMOVModImmType type) { 6146 unsigned OpCmode, Imm; 6147 6148 // SplatBitSize is set to the smallest size that splats the vector, so a 6149 // zero vector will always have SplatBitSize == 8. However, NEON modified 6150 // immediate instructions others than VMOV do not support the 8-bit encoding 6151 // of a zero vector, and the default encoding of zero is supposed to be the 6152 // 32-bit version. 6153 if (SplatBits == 0) 6154 SplatBitSize = 32; 6155 6156 switch (SplatBitSize) { 6157 case 8: 6158 if (type != VMOVModImm) 6159 return SDValue(); 6160 // Any 1-byte value is OK. Op=0, Cmode=1110. 6161 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 6162 OpCmode = 0xe; 6163 Imm = SplatBits; 6164 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 6165 break; 6166 6167 case 16: 6168 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 6169 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 6170 if ((SplatBits & ~0xff) == 0) { 6171 // Value = 0x00nn: Op=x, Cmode=100x. 6172 OpCmode = 0x8; 6173 Imm = SplatBits; 6174 break; 6175 } 6176 if ((SplatBits & ~0xff00) == 0) { 6177 // Value = 0xnn00: Op=x, Cmode=101x. 6178 OpCmode = 0xa; 6179 Imm = SplatBits >> 8; 6180 break; 6181 } 6182 return SDValue(); 6183 6184 case 32: 6185 // NEON's 32-bit VMOV supports splat values where: 6186 // * only one byte is nonzero, or 6187 // * the least significant byte is 0xff and the second byte is nonzero, or 6188 // * the least significant 2 bytes are 0xff and the third is nonzero. 6189 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 6190 if ((SplatBits & ~0xff) == 0) { 6191 // Value = 0x000000nn: Op=x, Cmode=000x. 6192 OpCmode = 0; 6193 Imm = SplatBits; 6194 break; 6195 } 6196 if ((SplatBits & ~0xff00) == 0) { 6197 // Value = 0x0000nn00: Op=x, Cmode=001x. 6198 OpCmode = 0x2; 6199 Imm = SplatBits >> 8; 6200 break; 6201 } 6202 if ((SplatBits & ~0xff0000) == 0) { 6203 // Value = 0x00nn0000: Op=x, Cmode=010x. 6204 OpCmode = 0x4; 6205 Imm = SplatBits >> 16; 6206 break; 6207 } 6208 if ((SplatBits & ~0xff000000) == 0) { 6209 // Value = 0xnn000000: Op=x, Cmode=011x. 6210 OpCmode = 0x6; 6211 Imm = SplatBits >> 24; 6212 break; 6213 } 6214 6215 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 6216 if (type == OtherModImm) return SDValue(); 6217 6218 if ((SplatBits & ~0xffff) == 0 && 6219 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 6220 // Value = 0x0000nnff: Op=x, Cmode=1100. 6221 OpCmode = 0xc; 6222 Imm = SplatBits >> 8; 6223 break; 6224 } 6225 6226 // cmode == 0b1101 is not supported for MVE VMVN 6227 if (type == MVEVMVNModImm) 6228 return SDValue(); 6229 6230 if ((SplatBits & ~0xffffff) == 0 && 6231 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6232 // Value = 0x00nnffff: Op=x, Cmode=1101. 6233 OpCmode = 0xd; 6234 Imm = SplatBits >> 16; 6235 break; 6236 } 6237 6238 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6239 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6240 // VMOV.I32. A (very) minor optimization would be to replicate the value 6241 // and fall through here to test for a valid 64-bit splat. But, then the 6242 // caller would also need to check and handle the change in size. 6243 return SDValue(); 6244 6245 case 64: { 6246 if (type != VMOVModImm) 6247 return SDValue(); 6248 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6249 uint64_t BitMask = 0xff; 6250 uint64_t Val = 0; 6251 unsigned ImmMask = 1; 6252 Imm = 0; 6253 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6254 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6255 Val |= BitMask; 6256 Imm |= ImmMask; 6257 } else if ((SplatBits & BitMask) != 0) { 6258 return SDValue(); 6259 } 6260 BitMask <<= 8; 6261 ImmMask <<= 1; 6262 } 6263 6264 if (DAG.getDataLayout().isBigEndian()) 6265 // swap higher and lower 32 bit word 6266 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 6267 6268 // Op=1, Cmode=1110. 6269 OpCmode = 0x1e; 6270 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6271 break; 6272 } 6273 6274 default: 6275 llvm_unreachable("unexpected size for isVMOVModifiedImm"); 6276 } 6277 6278 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm); 6279 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6280 } 6281 6282 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6283 const ARMSubtarget *ST) const { 6284 EVT VT = Op.getValueType(); 6285 bool IsDouble = (VT == MVT::f64); 6286 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6287 const APFloat &FPVal = CFP->getValueAPF(); 6288 6289 // Prevent floating-point constants from using literal loads 6290 // when execute-only is enabled. 6291 if (ST->genExecuteOnly()) { 6292 // If we can represent the constant as an immediate, don't lower it 6293 if (isFPImmLegal(FPVal, VT)) 6294 return Op; 6295 // Otherwise, construct as integer, and move to float register 6296 APInt INTVal = FPVal.bitcastToAPInt(); 6297 SDLoc DL(CFP); 6298 switch (VT.getSimpleVT().SimpleTy) { 6299 default: 6300 llvm_unreachable("Unknown floating point type!"); 6301 break; 6302 case MVT::f64: { 6303 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6304 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6305 if (!ST->isLittle()) 6306 std::swap(Lo, Hi); 6307 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6308 } 6309 case MVT::f32: 6310 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6311 DAG.getConstant(INTVal, DL, MVT::i32)); 6312 } 6313 } 6314 6315 if (!ST->hasVFP3Base()) 6316 return SDValue(); 6317 6318 // Use the default (constant pool) lowering for double constants when we have 6319 // an SP-only FPU 6320 if (IsDouble && !Subtarget->hasFP64()) 6321 return SDValue(); 6322 6323 // Try splatting with a VMOV.f32... 6324 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6325 6326 if (ImmVal != -1) { 6327 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6328 // We have code in place to select a valid ConstantFP already, no need to 6329 // do any mangling. 6330 return Op; 6331 } 6332 6333 // It's a float and we are trying to use NEON operations where 6334 // possible. Lower it to a splat followed by an extract. 6335 SDLoc DL(Op); 6336 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6337 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6338 NewVal); 6339 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6340 DAG.getConstant(0, DL, MVT::i32)); 6341 } 6342 6343 // The rest of our options are NEON only, make sure that's allowed before 6344 // proceeding.. 6345 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6346 return SDValue(); 6347 6348 EVT VMovVT; 6349 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6350 6351 // It wouldn't really be worth bothering for doubles except for one very 6352 // important value, which does happen to match: 0.0. So make sure we don't do 6353 // anything stupid. 6354 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6355 return SDValue(); 6356 6357 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6358 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6359 VMovVT, false, VMOVModImm); 6360 if (NewVal != SDValue()) { 6361 SDLoc DL(Op); 6362 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6363 NewVal); 6364 if (IsDouble) 6365 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6366 6367 // It's a float: cast and extract a vector element. 6368 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6369 VecConstant); 6370 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6371 DAG.getConstant(0, DL, MVT::i32)); 6372 } 6373 6374 // Finally, try a VMVN.i32 6375 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6376 false, VMVNModImm); 6377 if (NewVal != SDValue()) { 6378 SDLoc DL(Op); 6379 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6380 6381 if (IsDouble) 6382 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6383 6384 // It's a float: cast and extract a vector element. 6385 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6386 VecConstant); 6387 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6388 DAG.getConstant(0, DL, MVT::i32)); 6389 } 6390 6391 return SDValue(); 6392 } 6393 6394 // check if an VEXT instruction can handle the shuffle mask when the 6395 // vector sources of the shuffle are the same. 6396 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6397 unsigned NumElts = VT.getVectorNumElements(); 6398 6399 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6400 if (M[0] < 0) 6401 return false; 6402 6403 Imm = M[0]; 6404 6405 // If this is a VEXT shuffle, the immediate value is the index of the first 6406 // element. The other shuffle indices must be the successive elements after 6407 // the first one. 6408 unsigned ExpectedElt = Imm; 6409 for (unsigned i = 1; i < NumElts; ++i) { 6410 // Increment the expected index. If it wraps around, just follow it 6411 // back to index zero and keep going. 6412 ++ExpectedElt; 6413 if (ExpectedElt == NumElts) 6414 ExpectedElt = 0; 6415 6416 if (M[i] < 0) continue; // ignore UNDEF indices 6417 if (ExpectedElt != static_cast<unsigned>(M[i])) 6418 return false; 6419 } 6420 6421 return true; 6422 } 6423 6424 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6425 bool &ReverseVEXT, unsigned &Imm) { 6426 unsigned NumElts = VT.getVectorNumElements(); 6427 ReverseVEXT = false; 6428 6429 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6430 if (M[0] < 0) 6431 return false; 6432 6433 Imm = M[0]; 6434 6435 // If this is a VEXT shuffle, the immediate value is the index of the first 6436 // element. The other shuffle indices must be the successive elements after 6437 // the first one. 6438 unsigned ExpectedElt = Imm; 6439 for (unsigned i = 1; i < NumElts; ++i) { 6440 // Increment the expected index. If it wraps around, it may still be 6441 // a VEXT but the source vectors must be swapped. 6442 ExpectedElt += 1; 6443 if (ExpectedElt == NumElts * 2) { 6444 ExpectedElt = 0; 6445 ReverseVEXT = true; 6446 } 6447 6448 if (M[i] < 0) continue; // ignore UNDEF indices 6449 if (ExpectedElt != static_cast<unsigned>(M[i])) 6450 return false; 6451 } 6452 6453 // Adjust the index value if the source operands will be swapped. 6454 if (ReverseVEXT) 6455 Imm -= NumElts; 6456 6457 return true; 6458 } 6459 6460 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6461 /// instruction with the specified blocksize. (The order of the elements 6462 /// within each block of the vector is reversed.) 6463 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6464 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6465 "Only possible block sizes for VREV are: 16, 32, 64"); 6466 6467 unsigned EltSz = VT.getScalarSizeInBits(); 6468 if (EltSz == 64) 6469 return false; 6470 6471 unsigned NumElts = VT.getVectorNumElements(); 6472 unsigned BlockElts = M[0] + 1; 6473 // If the first shuffle index is UNDEF, be optimistic. 6474 if (M[0] < 0) 6475 BlockElts = BlockSize / EltSz; 6476 6477 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6478 return false; 6479 6480 for (unsigned i = 0; i < NumElts; ++i) { 6481 if (M[i] < 0) continue; // ignore UNDEF indices 6482 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6483 return false; 6484 } 6485 6486 return true; 6487 } 6488 6489 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6490 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6491 // range, then 0 is placed into the resulting vector. So pretty much any mask 6492 // of 8 elements can work here. 6493 return VT == MVT::v8i8 && M.size() == 8; 6494 } 6495 6496 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6497 unsigned Index) { 6498 if (Mask.size() == Elements * 2) 6499 return Index / Elements; 6500 return Mask[Index] == 0 ? 0 : 1; 6501 } 6502 6503 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6504 // checking that pairs of elements in the shuffle mask represent the same index 6505 // in each vector, incrementing the expected index by 2 at each step. 6506 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6507 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6508 // v2={e,f,g,h} 6509 // WhichResult gives the offset for each element in the mask based on which 6510 // of the two results it belongs to. 6511 // 6512 // The transpose can be represented either as: 6513 // result1 = shufflevector v1, v2, result1_shuffle_mask 6514 // result2 = shufflevector v1, v2, result2_shuffle_mask 6515 // where v1/v2 and the shuffle masks have the same number of elements 6516 // (here WhichResult (see below) indicates which result is being checked) 6517 // 6518 // or as: 6519 // results = shufflevector v1, v2, shuffle_mask 6520 // where both results are returned in one vector and the shuffle mask has twice 6521 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6522 // want to check the low half and high half of the shuffle mask as if it were 6523 // the other case 6524 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6525 unsigned EltSz = VT.getScalarSizeInBits(); 6526 if (EltSz == 64) 6527 return false; 6528 6529 unsigned NumElts = VT.getVectorNumElements(); 6530 if (M.size() != NumElts && M.size() != NumElts*2) 6531 return false; 6532 6533 // If the mask is twice as long as the input vector then we need to check the 6534 // upper and lower parts of the mask with a matching value for WhichResult 6535 // FIXME: A mask with only even values will be rejected in case the first 6536 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6537 // M[0] is used to determine WhichResult 6538 for (unsigned i = 0; i < M.size(); i += NumElts) { 6539 WhichResult = SelectPairHalf(NumElts, M, i); 6540 for (unsigned j = 0; j < NumElts; j += 2) { 6541 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6542 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6543 return false; 6544 } 6545 } 6546 6547 if (M.size() == NumElts*2) 6548 WhichResult = 0; 6549 6550 return true; 6551 } 6552 6553 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6554 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6555 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6556 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6557 unsigned EltSz = VT.getScalarSizeInBits(); 6558 if (EltSz == 64) 6559 return false; 6560 6561 unsigned NumElts = VT.getVectorNumElements(); 6562 if (M.size() != NumElts && M.size() != NumElts*2) 6563 return false; 6564 6565 for (unsigned i = 0; i < M.size(); i += NumElts) { 6566 WhichResult = SelectPairHalf(NumElts, M, i); 6567 for (unsigned j = 0; j < NumElts; j += 2) { 6568 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6569 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6570 return false; 6571 } 6572 } 6573 6574 if (M.size() == NumElts*2) 6575 WhichResult = 0; 6576 6577 return true; 6578 } 6579 6580 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6581 // that the mask elements are either all even and in steps of size 2 or all odd 6582 // and in steps of size 2. 6583 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6584 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6585 // v2={e,f,g,h} 6586 // Requires similar checks to that of isVTRNMask with 6587 // respect the how results are returned. 6588 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6589 unsigned EltSz = VT.getScalarSizeInBits(); 6590 if (EltSz == 64) 6591 return false; 6592 6593 unsigned NumElts = VT.getVectorNumElements(); 6594 if (M.size() != NumElts && M.size() != NumElts*2) 6595 return false; 6596 6597 for (unsigned i = 0; i < M.size(); i += NumElts) { 6598 WhichResult = SelectPairHalf(NumElts, M, i); 6599 for (unsigned j = 0; j < NumElts; ++j) { 6600 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6601 return false; 6602 } 6603 } 6604 6605 if (M.size() == NumElts*2) 6606 WhichResult = 0; 6607 6608 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6609 if (VT.is64BitVector() && EltSz == 32) 6610 return false; 6611 6612 return true; 6613 } 6614 6615 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6616 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6617 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6618 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6619 unsigned EltSz = VT.getScalarSizeInBits(); 6620 if (EltSz == 64) 6621 return false; 6622 6623 unsigned NumElts = VT.getVectorNumElements(); 6624 if (M.size() != NumElts && M.size() != NumElts*2) 6625 return false; 6626 6627 unsigned Half = NumElts / 2; 6628 for (unsigned i = 0; i < M.size(); i += NumElts) { 6629 WhichResult = SelectPairHalf(NumElts, M, i); 6630 for (unsigned j = 0; j < NumElts; j += Half) { 6631 unsigned Idx = WhichResult; 6632 for (unsigned k = 0; k < Half; ++k) { 6633 int MIdx = M[i + j + k]; 6634 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6635 return false; 6636 Idx += 2; 6637 } 6638 } 6639 } 6640 6641 if (M.size() == NumElts*2) 6642 WhichResult = 0; 6643 6644 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6645 if (VT.is64BitVector() && EltSz == 32) 6646 return false; 6647 6648 return true; 6649 } 6650 6651 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6652 // that pairs of elements of the shufflemask represent the same index in each 6653 // vector incrementing sequentially through the vectors. 6654 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6655 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6656 // v2={e,f,g,h} 6657 // Requires similar checks to that of isVTRNMask with respect the how results 6658 // are returned. 6659 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6660 unsigned EltSz = VT.getScalarSizeInBits(); 6661 if (EltSz == 64) 6662 return false; 6663 6664 unsigned NumElts = VT.getVectorNumElements(); 6665 if (M.size() != NumElts && M.size() != NumElts*2) 6666 return false; 6667 6668 for (unsigned i = 0; i < M.size(); i += NumElts) { 6669 WhichResult = SelectPairHalf(NumElts, M, i); 6670 unsigned Idx = WhichResult * NumElts / 2; 6671 for (unsigned j = 0; j < NumElts; j += 2) { 6672 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6673 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6674 return false; 6675 Idx += 1; 6676 } 6677 } 6678 6679 if (M.size() == NumElts*2) 6680 WhichResult = 0; 6681 6682 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6683 if (VT.is64BitVector() && EltSz == 32) 6684 return false; 6685 6686 return true; 6687 } 6688 6689 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6690 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6691 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6692 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6693 unsigned EltSz = VT.getScalarSizeInBits(); 6694 if (EltSz == 64) 6695 return false; 6696 6697 unsigned NumElts = VT.getVectorNumElements(); 6698 if (M.size() != NumElts && M.size() != NumElts*2) 6699 return false; 6700 6701 for (unsigned i = 0; i < M.size(); i += NumElts) { 6702 WhichResult = SelectPairHalf(NumElts, M, i); 6703 unsigned Idx = WhichResult * NumElts / 2; 6704 for (unsigned j = 0; j < NumElts; j += 2) { 6705 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6706 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6707 return false; 6708 Idx += 1; 6709 } 6710 } 6711 6712 if (M.size() == NumElts*2) 6713 WhichResult = 0; 6714 6715 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6716 if (VT.is64BitVector() && EltSz == 32) 6717 return false; 6718 6719 return true; 6720 } 6721 6722 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6723 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6724 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6725 unsigned &WhichResult, 6726 bool &isV_UNDEF) { 6727 isV_UNDEF = false; 6728 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6729 return ARMISD::VTRN; 6730 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6731 return ARMISD::VUZP; 6732 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6733 return ARMISD::VZIP; 6734 6735 isV_UNDEF = true; 6736 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6737 return ARMISD::VTRN; 6738 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6739 return ARMISD::VUZP; 6740 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6741 return ARMISD::VZIP; 6742 6743 return 0; 6744 } 6745 6746 /// \return true if this is a reverse operation on an vector. 6747 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6748 unsigned NumElts = VT.getVectorNumElements(); 6749 // Make sure the mask has the right size. 6750 if (NumElts != M.size()) 6751 return false; 6752 6753 // Look for <15, ..., 3, -1, 1, 0>. 6754 for (unsigned i = 0; i != NumElts; ++i) 6755 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6756 return false; 6757 6758 return true; 6759 } 6760 6761 // If N is an integer constant that can be moved into a register in one 6762 // instruction, return an SDValue of such a constant (will become a MOV 6763 // instruction). Otherwise return null. 6764 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6765 const ARMSubtarget *ST, const SDLoc &dl) { 6766 uint64_t Val; 6767 if (!isa<ConstantSDNode>(N)) 6768 return SDValue(); 6769 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6770 6771 if (ST->isThumb1Only()) { 6772 if (Val <= 255 || ~Val <= 255) 6773 return DAG.getConstant(Val, dl, MVT::i32); 6774 } else { 6775 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6776 return DAG.getConstant(Val, dl, MVT::i32); 6777 } 6778 return SDValue(); 6779 } 6780 6781 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, 6782 const ARMSubtarget *ST) { 6783 SDLoc dl(Op); 6784 EVT VT = Op.getValueType(); 6785 6786 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!"); 6787 6788 unsigned NumElts = VT.getVectorNumElements(); 6789 unsigned BoolMask; 6790 unsigned BitsPerBool; 6791 if (NumElts == 4) { 6792 BitsPerBool = 4; 6793 BoolMask = 0xf; 6794 } else if (NumElts == 8) { 6795 BitsPerBool = 2; 6796 BoolMask = 0x3; 6797 } else if (NumElts == 16) { 6798 BitsPerBool = 1; 6799 BoolMask = 0x1; 6800 } else 6801 return SDValue(); 6802 6803 // First create base with bits set where known 6804 unsigned Bits32 = 0; 6805 for (unsigned i = 0; i < NumElts; ++i) { 6806 SDValue V = Op.getOperand(i); 6807 if (!isa<ConstantSDNode>(V) && !V.isUndef()) 6808 continue; 6809 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue(); 6810 if (BitSet) 6811 Bits32 |= BoolMask << (i * BitsPerBool); 6812 } 6813 6814 // Add in unknown nodes 6815 // FIXME: Handle splats of the same value better. 6816 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, 6817 DAG.getConstant(Bits32, dl, MVT::i32)); 6818 for (unsigned i = 0; i < NumElts; ++i) { 6819 SDValue V = Op.getOperand(i); 6820 if (isa<ConstantSDNode>(V) || V.isUndef()) 6821 continue; 6822 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V, 6823 DAG.getConstant(i, dl, MVT::i32)); 6824 } 6825 6826 return Base; 6827 } 6828 6829 // If this is a case we can't handle, return null and let the default 6830 // expansion code take care of it. 6831 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6832 const ARMSubtarget *ST) const { 6833 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6834 SDLoc dl(Op); 6835 EVT VT = Op.getValueType(); 6836 6837 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 6838 return LowerBUILD_VECTOR_i1(Op, DAG, ST); 6839 6840 APInt SplatBits, SplatUndef; 6841 unsigned SplatBitSize; 6842 bool HasAnyUndefs; 6843 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6844 if (SplatUndef.isAllOnesValue()) 6845 return DAG.getUNDEF(VT); 6846 6847 if ((ST->hasNEON() && SplatBitSize <= 64) || 6848 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) { 6849 // Check if an immediate VMOV works. 6850 EVT VmovVT; 6851 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 6852 SplatUndef.getZExtValue(), SplatBitSize, 6853 DAG, dl, VmovVT, VT.is128BitVector(), 6854 VMOVModImm); 6855 6856 if (Val.getNode()) { 6857 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6858 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6859 } 6860 6861 // Try an immediate VMVN. 6862 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6863 Val = isVMOVModifiedImm( 6864 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, 6865 DAG, dl, VmovVT, VT.is128BitVector(), 6866 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm); 6867 if (Val.getNode()) { 6868 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6869 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6870 } 6871 6872 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6873 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6874 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6875 if (ImmVal != -1) { 6876 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6877 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6878 } 6879 } 6880 } 6881 } 6882 6883 // Scan through the operands to see if only one value is used. 6884 // 6885 // As an optimisation, even if more than one value is used it may be more 6886 // profitable to splat with one value then change some lanes. 6887 // 6888 // Heuristically we decide to do this if the vector has a "dominant" value, 6889 // defined as splatted to more than half of the lanes. 6890 unsigned NumElts = VT.getVectorNumElements(); 6891 bool isOnlyLowElement = true; 6892 bool usesOnlyOneValue = true; 6893 bool hasDominantValue = false; 6894 bool isConstant = true; 6895 6896 // Map of the number of times a particular SDValue appears in the 6897 // element list. 6898 DenseMap<SDValue, unsigned> ValueCounts; 6899 SDValue Value; 6900 for (unsigned i = 0; i < NumElts; ++i) { 6901 SDValue V = Op.getOperand(i); 6902 if (V.isUndef()) 6903 continue; 6904 if (i > 0) 6905 isOnlyLowElement = false; 6906 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6907 isConstant = false; 6908 6909 ValueCounts.insert(std::make_pair(V, 0)); 6910 unsigned &Count = ValueCounts[V]; 6911 6912 // Is this value dominant? (takes up more than half of the lanes) 6913 if (++Count > (NumElts / 2)) { 6914 hasDominantValue = true; 6915 Value = V; 6916 } 6917 } 6918 if (ValueCounts.size() != 1) 6919 usesOnlyOneValue = false; 6920 if (!Value.getNode() && !ValueCounts.empty()) 6921 Value = ValueCounts.begin()->first; 6922 6923 if (ValueCounts.empty()) 6924 return DAG.getUNDEF(VT); 6925 6926 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6927 // Keep going if we are hitting this case. 6928 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6929 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6930 6931 unsigned EltSize = VT.getScalarSizeInBits(); 6932 6933 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6934 // i32 and try again. 6935 if (hasDominantValue && EltSize <= 32) { 6936 if (!isConstant) { 6937 SDValue N; 6938 6939 // If we are VDUPing a value that comes directly from a vector, that will 6940 // cause an unnecessary move to and from a GPR, where instead we could 6941 // just use VDUPLANE. We can only do this if the lane being extracted 6942 // is at a constant index, as the VDUP from lane instructions only have 6943 // constant-index forms. 6944 ConstantSDNode *constIndex; 6945 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6946 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6947 // We need to create a new undef vector to use for the VDUPLANE if the 6948 // size of the vector from which we get the value is different than the 6949 // size of the vector that we need to create. We will insert the element 6950 // such that the register coalescer will remove unnecessary copies. 6951 if (VT != Value->getOperand(0).getValueType()) { 6952 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6953 VT.getVectorNumElements(); 6954 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6955 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6956 Value, DAG.getConstant(index, dl, MVT::i32)), 6957 DAG.getConstant(index, dl, MVT::i32)); 6958 } else 6959 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6960 Value->getOperand(0), Value->getOperand(1)); 6961 } else 6962 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6963 6964 if (!usesOnlyOneValue) { 6965 // The dominant value was splatted as 'N', but we now have to insert 6966 // all differing elements. 6967 for (unsigned I = 0; I < NumElts; ++I) { 6968 if (Op.getOperand(I) == Value) 6969 continue; 6970 SmallVector<SDValue, 3> Ops; 6971 Ops.push_back(N); 6972 Ops.push_back(Op.getOperand(I)); 6973 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6974 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6975 } 6976 } 6977 return N; 6978 } 6979 if (VT.getVectorElementType().isFloatingPoint()) { 6980 SmallVector<SDValue, 8> Ops; 6981 MVT FVT = VT.getVectorElementType().getSimpleVT(); 6982 assert(FVT == MVT::f32 || FVT == MVT::f16); 6983 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 6984 for (unsigned i = 0; i < NumElts; ++i) 6985 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 6986 Op.getOperand(i))); 6987 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 6988 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6989 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6990 if (Val.getNode()) 6991 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6992 } 6993 if (usesOnlyOneValue) { 6994 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6995 if (isConstant && Val.getNode()) 6996 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6997 } 6998 } 6999 7000 // If all elements are constants and the case above didn't get hit, fall back 7001 // to the default expansion, which will generate a load from the constant 7002 // pool. 7003 if (isConstant) 7004 return SDValue(); 7005 7006 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 7007 if (NumElts >= 4) { 7008 SDValue shuffle = ReconstructShuffle(Op, DAG); 7009 if (shuffle != SDValue()) 7010 return shuffle; 7011 } 7012 7013 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 7014 // If we haven't found an efficient lowering, try splitting a 128-bit vector 7015 // into two 64-bit vectors; we might discover a better way to lower it. 7016 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 7017 EVT ExtVT = VT.getVectorElementType(); 7018 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 7019 SDValue Lower = 7020 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 7021 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 7022 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 7023 SDValue Upper = DAG.getBuildVector( 7024 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 7025 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 7026 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 7027 if (Lower && Upper) 7028 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 7029 } 7030 7031 // Vectors with 32- or 64-bit elements can be built by directly assigning 7032 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 7033 // will be legalized. 7034 if (EltSize >= 32) { 7035 // Do the expansion with floating-point types, since that is what the VFP 7036 // registers are defined to use, and since i64 is not legal. 7037 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7038 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7039 SmallVector<SDValue, 8> Ops; 7040 for (unsigned i = 0; i < NumElts; ++i) 7041 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 7042 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7043 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7044 } 7045 7046 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7047 // know the default expansion would otherwise fall back on something even 7048 // worse. For a vector with one or two non-undef values, that's 7049 // scalar_to_vector for the elements followed by a shuffle (provided the 7050 // shuffle is valid for the target) and materialization element by element 7051 // on the stack followed by a load for everything else. 7052 if (!isConstant && !usesOnlyOneValue) { 7053 SDValue Vec = DAG.getUNDEF(VT); 7054 for (unsigned i = 0 ; i < NumElts; ++i) { 7055 SDValue V = Op.getOperand(i); 7056 if (V.isUndef()) 7057 continue; 7058 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 7059 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7060 } 7061 return Vec; 7062 } 7063 7064 return SDValue(); 7065 } 7066 7067 // Gather data to see if the operation can be modelled as a 7068 // shuffle in combination with VEXTs. 7069 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 7070 SelectionDAG &DAG) const { 7071 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7072 SDLoc dl(Op); 7073 EVT VT = Op.getValueType(); 7074 unsigned NumElts = VT.getVectorNumElements(); 7075 7076 struct ShuffleSourceInfo { 7077 SDValue Vec; 7078 unsigned MinElt = std::numeric_limits<unsigned>::max(); 7079 unsigned MaxElt = 0; 7080 7081 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7082 // be compatible with the shuffle we intend to construct. As a result 7083 // ShuffleVec will be some sliding window into the original Vec. 7084 SDValue ShuffleVec; 7085 7086 // Code should guarantee that element i in Vec starts at element "WindowBase 7087 // + i * WindowScale in ShuffleVec". 7088 int WindowBase = 0; 7089 int WindowScale = 1; 7090 7091 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 7092 7093 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 7094 }; 7095 7096 // First gather all vectors used as an immediate source for this BUILD_VECTOR 7097 // node. 7098 SmallVector<ShuffleSourceInfo, 2> Sources; 7099 for (unsigned i = 0; i < NumElts; ++i) { 7100 SDValue V = Op.getOperand(i); 7101 if (V.isUndef()) 7102 continue; 7103 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 7104 // A shuffle can only come from building a vector from various 7105 // elements of other vectors. 7106 return SDValue(); 7107 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 7108 // Furthermore, shuffles require a constant mask, whereas extractelts 7109 // accept variable indices. 7110 return SDValue(); 7111 } 7112 7113 // Add this element source to the list if it's not already there. 7114 SDValue SourceVec = V.getOperand(0); 7115 auto Source = llvm::find(Sources, SourceVec); 7116 if (Source == Sources.end()) 7117 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 7118 7119 // Update the minimum and maximum lane number seen. 7120 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 7121 Source->MinElt = std::min(Source->MinElt, EltNo); 7122 Source->MaxElt = std::max(Source->MaxElt, EltNo); 7123 } 7124 7125 // Currently only do something sane when at most two source vectors 7126 // are involved. 7127 if (Sources.size() > 2) 7128 return SDValue(); 7129 7130 // Find out the smallest element size among result and two sources, and use 7131 // it as element size to build the shuffle_vector. 7132 EVT SmallestEltTy = VT.getVectorElementType(); 7133 for (auto &Source : Sources) { 7134 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 7135 if (SrcEltTy.bitsLT(SmallestEltTy)) 7136 SmallestEltTy = SrcEltTy; 7137 } 7138 unsigned ResMultiplier = 7139 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 7140 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7141 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 7142 7143 // If the source vector is too wide or too narrow, we may nevertheless be able 7144 // to construct a compatible shuffle either by concatenating it with UNDEF or 7145 // extracting a suitable range of elements. 7146 for (auto &Src : Sources) { 7147 EVT SrcVT = Src.ShuffleVec.getValueType(); 7148 7149 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 7150 continue; 7151 7152 // This stage of the search produces a source with the same element type as 7153 // the original, but with a total width matching the BUILD_VECTOR output. 7154 EVT EltVT = SrcVT.getVectorElementType(); 7155 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 7156 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 7157 7158 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 7159 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 7160 return SDValue(); 7161 // We can pad out the smaller vector for free, so if it's part of a 7162 // shuffle... 7163 Src.ShuffleVec = 7164 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 7165 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 7166 continue; 7167 } 7168 7169 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 7170 return SDValue(); 7171 7172 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 7173 // Span too large for a VEXT to cope 7174 return SDValue(); 7175 } 7176 7177 if (Src.MinElt >= NumSrcElts) { 7178 // The extraction can just take the second half 7179 Src.ShuffleVec = 7180 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7181 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7182 Src.WindowBase = -NumSrcElts; 7183 } else if (Src.MaxElt < NumSrcElts) { 7184 // The extraction can just take the first half 7185 Src.ShuffleVec = 7186 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7187 DAG.getConstant(0, dl, MVT::i32)); 7188 } else { 7189 // An actual VEXT is needed 7190 SDValue VEXTSrc1 = 7191 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7192 DAG.getConstant(0, dl, MVT::i32)); 7193 SDValue VEXTSrc2 = 7194 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 7195 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 7196 7197 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 7198 VEXTSrc2, 7199 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 7200 Src.WindowBase = -Src.MinElt; 7201 } 7202 } 7203 7204 // Another possible incompatibility occurs from the vector element types. We 7205 // can fix this by bitcasting the source vectors to the same type we intend 7206 // for the shuffle. 7207 for (auto &Src : Sources) { 7208 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 7209 if (SrcEltTy == SmallestEltTy) 7210 continue; 7211 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 7212 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 7213 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 7214 Src.WindowBase *= Src.WindowScale; 7215 } 7216 7217 // Final sanity check before we try to actually produce a shuffle. 7218 LLVM_DEBUG(for (auto Src 7219 : Sources) 7220 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 7221 7222 // The stars all align, our next step is to produce the mask for the shuffle. 7223 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 7224 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 7225 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 7226 SDValue Entry = Op.getOperand(i); 7227 if (Entry.isUndef()) 7228 continue; 7229 7230 auto Src = llvm::find(Sources, Entry.getOperand(0)); 7231 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 7232 7233 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 7234 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 7235 // segment. 7236 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 7237 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 7238 VT.getScalarSizeInBits()); 7239 int LanesDefined = BitsDefined / BitsPerShuffleLane; 7240 7241 // This source is expected to fill ResMultiplier lanes of the final shuffle, 7242 // starting at the appropriate offset. 7243 int *LaneMask = &Mask[i * ResMultiplier]; 7244 7245 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 7246 ExtractBase += NumElts * (Src - Sources.begin()); 7247 for (int j = 0; j < LanesDefined; ++j) 7248 LaneMask[j] = ExtractBase + j; 7249 } 7250 7251 // Final check before we try to produce nonsense... 7252 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 7253 return SDValue(); 7254 7255 // We can't handle more than two sources. This should have already 7256 // been checked before this point. 7257 assert(Sources.size() <= 2 && "Too many sources!"); 7258 7259 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 7260 for (unsigned i = 0; i < Sources.size(); ++i) 7261 ShuffleOps[i] = Sources[i].ShuffleVec; 7262 7263 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 7264 ShuffleOps[1], Mask); 7265 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 7266 } 7267 7268 enum ShuffleOpCodes { 7269 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7270 OP_VREV, 7271 OP_VDUP0, 7272 OP_VDUP1, 7273 OP_VDUP2, 7274 OP_VDUP3, 7275 OP_VEXT1, 7276 OP_VEXT2, 7277 OP_VEXT3, 7278 OP_VUZPL, // VUZP, left result 7279 OP_VUZPR, // VUZP, right result 7280 OP_VZIPL, // VZIP, left result 7281 OP_VZIPR, // VZIP, right result 7282 OP_VTRNL, // VTRN, left result 7283 OP_VTRNR // VTRN, right result 7284 }; 7285 7286 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7287 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7288 switch (OpNum) { 7289 case OP_COPY: 7290 case OP_VREV: 7291 case OP_VDUP0: 7292 case OP_VDUP1: 7293 case OP_VDUP2: 7294 case OP_VDUP3: 7295 return true; 7296 } 7297 return false; 7298 } 7299 7300 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7301 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7302 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7303 /// are assumed to be legal. 7304 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7305 if (VT.getVectorNumElements() == 4 && 7306 (VT.is128BitVector() || VT.is64BitVector())) { 7307 unsigned PFIndexes[4]; 7308 for (unsigned i = 0; i != 4; ++i) { 7309 if (M[i] < 0) 7310 PFIndexes[i] = 8; 7311 else 7312 PFIndexes[i] = M[i]; 7313 } 7314 7315 // Compute the index in the perfect shuffle table. 7316 unsigned PFTableIndex = 7317 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7318 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7319 unsigned Cost = (PFEntry >> 30); 7320 7321 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7322 return true; 7323 } 7324 7325 bool ReverseVEXT, isV_UNDEF; 7326 unsigned Imm, WhichResult; 7327 7328 unsigned EltSize = VT.getScalarSizeInBits(); 7329 if (EltSize >= 32 || 7330 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7331 isVREVMask(M, VT, 64) || 7332 isVREVMask(M, VT, 32) || 7333 isVREVMask(M, VT, 16)) 7334 return true; 7335 else if (Subtarget->hasNEON() && 7336 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7337 isVTBLMask(M, VT) || 7338 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7339 return true; 7340 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7341 isReverseMask(M, VT)) 7342 return true; 7343 else 7344 return false; 7345 } 7346 7347 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7348 /// the specified operations to build the shuffle. 7349 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7350 SDValue RHS, SelectionDAG &DAG, 7351 const SDLoc &dl) { 7352 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7353 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7354 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7355 7356 if (OpNum == OP_COPY) { 7357 if (LHSID == (1*9+2)*9+3) return LHS; 7358 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7359 return RHS; 7360 } 7361 7362 SDValue OpLHS, OpRHS; 7363 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7364 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7365 EVT VT = OpLHS.getValueType(); 7366 7367 switch (OpNum) { 7368 default: llvm_unreachable("Unknown shuffle opcode!"); 7369 case OP_VREV: 7370 // VREV divides the vector in half and swaps within the half. 7371 if (VT.getVectorElementType() == MVT::i32 || 7372 VT.getVectorElementType() == MVT::f32) 7373 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7374 // vrev <4 x i16> -> VREV32 7375 if (VT.getVectorElementType() == MVT::i16) 7376 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7377 // vrev <4 x i8> -> VREV16 7378 assert(VT.getVectorElementType() == MVT::i8); 7379 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 7380 case OP_VDUP0: 7381 case OP_VDUP1: 7382 case OP_VDUP2: 7383 case OP_VDUP3: 7384 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7385 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 7386 case OP_VEXT1: 7387 case OP_VEXT2: 7388 case OP_VEXT3: 7389 return DAG.getNode(ARMISD::VEXT, dl, VT, 7390 OpLHS, OpRHS, 7391 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 7392 case OP_VUZPL: 7393 case OP_VUZPR: 7394 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7395 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7396 case OP_VZIPL: 7397 case OP_VZIPR: 7398 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7399 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7400 case OP_VTRNL: 7401 case OP_VTRNR: 7402 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7403 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7404 } 7405 } 7406 7407 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7408 ArrayRef<int> ShuffleMask, 7409 SelectionDAG &DAG) { 7410 // Check to see if we can use the VTBL instruction. 7411 SDValue V1 = Op.getOperand(0); 7412 SDValue V2 = Op.getOperand(1); 7413 SDLoc DL(Op); 7414 7415 SmallVector<SDValue, 8> VTBLMask; 7416 for (ArrayRef<int>::iterator 7417 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7418 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7419 7420 if (V2.getNode()->isUndef()) 7421 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7422 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7423 7424 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7425 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7426 } 7427 7428 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7429 SelectionDAG &DAG) { 7430 SDLoc DL(Op); 7431 SDValue OpLHS = Op.getOperand(0); 7432 EVT VT = OpLHS.getValueType(); 7433 7434 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7435 "Expect an v8i16/v16i8 type"); 7436 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7437 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7438 // extract the first 8 bytes into the top double word and the last 8 bytes 7439 // into the bottom double word. The v8i16 case is similar. 7440 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7441 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7442 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7443 } 7444 7445 static EVT getVectorTyFromPredicateVector(EVT VT) { 7446 switch (VT.getSimpleVT().SimpleTy) { 7447 case MVT::v4i1: 7448 return MVT::v4i32; 7449 case MVT::v8i1: 7450 return MVT::v8i16; 7451 case MVT::v16i1: 7452 return MVT::v16i8; 7453 default: 7454 llvm_unreachable("Unexpected vector predicate type"); 7455 } 7456 } 7457 7458 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, 7459 SelectionDAG &DAG) { 7460 // Converting from boolean predicates to integers involves creating a vector 7461 // of all ones or all zeroes and selecting the lanes based upon the real 7462 // predicate. 7463 SDValue AllOnes = 7464 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32); 7465 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes); 7466 7467 SDValue AllZeroes = 7468 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32); 7469 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes); 7470 7471 // Get full vector type from predicate type 7472 EVT NewVT = getVectorTyFromPredicateVector(VT); 7473 7474 SDValue RecastV1; 7475 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast 7476 // this to a v16i1. This cannot be done with an ordinary bitcast because the 7477 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node, 7478 // since we know in hardware the sizes are really the same. 7479 if (VT != MVT::v16i1) 7480 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred); 7481 else 7482 RecastV1 = Pred; 7483 7484 // Select either all ones or zeroes depending upon the real predicate bits. 7485 SDValue PredAsVector = 7486 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes); 7487 7488 // Recast our new predicate-as-integer v16i8 vector into something 7489 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate. 7490 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector); 7491 } 7492 7493 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, 7494 const ARMSubtarget *ST) { 7495 EVT VT = Op.getValueType(); 7496 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7497 ArrayRef<int> ShuffleMask = SVN->getMask(); 7498 7499 assert(ST->hasMVEIntegerOps() && 7500 "No support for vector shuffle of boolean predicates"); 7501 7502 SDValue V1 = Op.getOperand(0); 7503 SDLoc dl(Op); 7504 if (isReverseMask(ShuffleMask, VT)) { 7505 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1); 7506 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast); 7507 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit, 7508 DAG.getConstant(16, dl, MVT::i32)); 7509 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl); 7510 } 7511 7512 // Until we can come up with optimised cases for every single vector 7513 // shuffle in existence we have chosen the least painful strategy. This is 7514 // to essentially promote the boolean predicate to a 8-bit integer, where 7515 // each predicate represents a byte. Then we fall back on a normal integer 7516 // vector shuffle and convert the result back into a predicate vector. In 7517 // many cases the generated code might be even better than scalar code 7518 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit 7519 // fields in a register into 8 other arbitrary 2-bit fields! 7520 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG); 7521 EVT NewVT = PredAsVector.getValueType(); 7522 7523 // Do the shuffle! 7524 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector, 7525 DAG.getUNDEF(NewVT), ShuffleMask); 7526 7527 // Now return the result of comparing the shuffled vector with zero, 7528 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7529 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled, 7530 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7531 } 7532 7533 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 7534 const ARMSubtarget *ST) { 7535 SDValue V1 = Op.getOperand(0); 7536 SDValue V2 = Op.getOperand(1); 7537 SDLoc dl(Op); 7538 EVT VT = Op.getValueType(); 7539 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7540 unsigned EltSize = VT.getScalarSizeInBits(); 7541 7542 if (ST->hasMVEIntegerOps() && EltSize == 1) 7543 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST); 7544 7545 // Convert shuffles that are directly supported on NEON to target-specific 7546 // DAG nodes, instead of keeping them as shuffles and matching them again 7547 // during code selection. This is more efficient and avoids the possibility 7548 // of inconsistencies between legalization and selection. 7549 // FIXME: floating-point vectors should be canonicalized to integer vectors 7550 // of the same time so that they get CSEd properly. 7551 ArrayRef<int> ShuffleMask = SVN->getMask(); 7552 7553 if (EltSize <= 32) { 7554 if (SVN->isSplat()) { 7555 int Lane = SVN->getSplatIndex(); 7556 // If this is undef splat, generate it via "just" vdup, if possible. 7557 if (Lane == -1) Lane = 0; 7558 7559 // Test if V1 is a SCALAR_TO_VECTOR. 7560 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7561 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7562 } 7563 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7564 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7565 // reaches it). 7566 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7567 !isa<ConstantSDNode>(V1.getOperand(0))) { 7568 bool IsScalarToVector = true; 7569 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7570 if (!V1.getOperand(i).isUndef()) { 7571 IsScalarToVector = false; 7572 break; 7573 } 7574 if (IsScalarToVector) 7575 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7576 } 7577 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7578 DAG.getConstant(Lane, dl, MVT::i32)); 7579 } 7580 7581 bool ReverseVEXT = false; 7582 unsigned Imm = 0; 7583 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7584 if (ReverseVEXT) 7585 std::swap(V1, V2); 7586 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7587 DAG.getConstant(Imm, dl, MVT::i32)); 7588 } 7589 7590 if (isVREVMask(ShuffleMask, VT, 64)) 7591 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7592 if (isVREVMask(ShuffleMask, VT, 32)) 7593 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7594 if (isVREVMask(ShuffleMask, VT, 16)) 7595 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7596 7597 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7598 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7599 DAG.getConstant(Imm, dl, MVT::i32)); 7600 } 7601 7602 // Check for Neon shuffles that modify both input vectors in place. 7603 // If both results are used, i.e., if there are two shuffles with the same 7604 // source operands and with masks corresponding to both results of one of 7605 // these operations, DAG memoization will ensure that a single node is 7606 // used for both shuffles. 7607 unsigned WhichResult = 0; 7608 bool isV_UNDEF = false; 7609 if (ST->hasNEON()) { 7610 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7611 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7612 if (isV_UNDEF) 7613 V2 = V1; 7614 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7615 .getValue(WhichResult); 7616 } 7617 } 7618 7619 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7620 // shuffles that produce a result larger than their operands with: 7621 // shuffle(concat(v1, undef), concat(v2, undef)) 7622 // -> 7623 // shuffle(concat(v1, v2), undef) 7624 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7625 // 7626 // This is useful in the general case, but there are special cases where 7627 // native shuffles produce larger results: the two-result ops. 7628 // 7629 // Look through the concat when lowering them: 7630 // shuffle(concat(v1, v2), undef) 7631 // -> 7632 // concat(VZIP(v1, v2):0, :1) 7633 // 7634 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7635 SDValue SubV1 = V1->getOperand(0); 7636 SDValue SubV2 = V1->getOperand(1); 7637 EVT SubVT = SubV1.getValueType(); 7638 7639 // We expect these to have been canonicalized to -1. 7640 assert(llvm::all_of(ShuffleMask, [&](int i) { 7641 return i < (int)VT.getVectorNumElements(); 7642 }) && "Unexpected shuffle index into UNDEF operand!"); 7643 7644 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7645 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7646 if (isV_UNDEF) 7647 SubV2 = SubV1; 7648 assert((WhichResult == 0) && 7649 "In-place shuffle of concat can only have one result!"); 7650 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7651 SubV1, SubV2); 7652 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7653 Res.getValue(1)); 7654 } 7655 } 7656 } 7657 7658 // If the shuffle is not directly supported and it has 4 elements, use 7659 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7660 unsigned NumElts = VT.getVectorNumElements(); 7661 if (NumElts == 4) { 7662 unsigned PFIndexes[4]; 7663 for (unsigned i = 0; i != 4; ++i) { 7664 if (ShuffleMask[i] < 0) 7665 PFIndexes[i] = 8; 7666 else 7667 PFIndexes[i] = ShuffleMask[i]; 7668 } 7669 7670 // Compute the index in the perfect shuffle table. 7671 unsigned PFTableIndex = 7672 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7673 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7674 unsigned Cost = (PFEntry >> 30); 7675 7676 if (Cost <= 4) { 7677 if (ST->hasNEON()) 7678 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7679 else if (isLegalMVEShuffleOp(PFEntry)) { 7680 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7681 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7682 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 7683 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 7684 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 7685 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7686 } 7687 } 7688 } 7689 7690 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7691 if (EltSize >= 32) { 7692 // Do the expansion with floating-point types, since that is what the VFP 7693 // registers are defined to use, and since i64 is not legal. 7694 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7695 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7696 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7697 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7698 SmallVector<SDValue, 8> Ops; 7699 for (unsigned i = 0; i < NumElts; ++i) { 7700 if (ShuffleMask[i] < 0) 7701 Ops.push_back(DAG.getUNDEF(EltVT)); 7702 else 7703 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7704 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7705 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7706 dl, MVT::i32))); 7707 } 7708 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7709 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7710 } 7711 7712 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7713 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7714 7715 if (ST->hasNEON() && VT == MVT::v8i8) 7716 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7717 return NewOp; 7718 7719 return SDValue(); 7720 } 7721 7722 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 7723 const ARMSubtarget *ST) { 7724 EVT VecVT = Op.getOperand(0).getValueType(); 7725 SDLoc dl(Op); 7726 7727 assert(ST->hasMVEIntegerOps() && 7728 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 7729 7730 SDValue Conv = 7731 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 7732 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 7733 unsigned LaneWidth = 7734 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 7735 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth; 7736 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, 7737 Op.getOperand(1), DAG.getValueType(MVT::i1)); 7738 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext, 7739 DAG.getConstant(~Mask, dl, MVT::i32)); 7740 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI); 7741 } 7742 7743 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 7744 SelectionDAG &DAG) const { 7745 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7746 SDValue Lane = Op.getOperand(2); 7747 if (!isa<ConstantSDNode>(Lane)) 7748 return SDValue(); 7749 7750 SDValue Elt = Op.getOperand(1); 7751 EVT EltVT = Elt.getValueType(); 7752 7753 if (Subtarget->hasMVEIntegerOps() && 7754 Op.getValueType().getScalarSizeInBits() == 1) 7755 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget); 7756 7757 if (getTypeAction(*DAG.getContext(), EltVT) == 7758 TargetLowering::TypePromoteFloat) { 7759 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 7760 // but the type system will try to do that if we don't intervene. 7761 // Reinterpret any such vector-element insertion as one with the 7762 // corresponding integer types. 7763 7764 SDLoc dl(Op); 7765 7766 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 7767 assert(getTypeAction(*DAG.getContext(), IEltVT) != 7768 TargetLowering::TypePromoteFloat); 7769 7770 SDValue VecIn = Op.getOperand(0); 7771 EVT VecVT = VecIn.getValueType(); 7772 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 7773 VecVT.getVectorNumElements()); 7774 7775 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 7776 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 7777 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 7778 IVecIn, IElt, Lane); 7779 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 7780 } 7781 7782 return Op; 7783 } 7784 7785 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, 7786 const ARMSubtarget *ST) { 7787 EVT VecVT = Op.getOperand(0).getValueType(); 7788 SDLoc dl(Op); 7789 7790 assert(ST->hasMVEIntegerOps() && 7791 "LowerINSERT_VECTOR_ELT_i1 called without MVE!"); 7792 7793 SDValue Conv = 7794 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0)); 7795 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7796 unsigned LaneWidth = 7797 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8; 7798 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv, 7799 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32)); 7800 return Shift; 7801 } 7802 7803 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, 7804 const ARMSubtarget *ST) { 7805 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7806 SDValue Lane = Op.getOperand(1); 7807 if (!isa<ConstantSDNode>(Lane)) 7808 return SDValue(); 7809 7810 SDValue Vec = Op.getOperand(0); 7811 EVT VT = Vec.getValueType(); 7812 7813 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7814 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST); 7815 7816 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7817 SDLoc dl(Op); 7818 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7819 } 7820 7821 return Op; 7822 } 7823 7824 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, 7825 const ARMSubtarget *ST) { 7826 SDValue V1 = Op.getOperand(0); 7827 SDValue V2 = Op.getOperand(1); 7828 SDLoc dl(Op); 7829 EVT VT = Op.getValueType(); 7830 EVT Op1VT = V1.getValueType(); 7831 EVT Op2VT = V2.getValueType(); 7832 unsigned NumElts = VT.getVectorNumElements(); 7833 7834 assert(Op1VT == Op2VT && "Operand types don't match!"); 7835 assert(VT.getScalarSizeInBits() == 1 && 7836 "Unexpected custom CONCAT_VECTORS lowering"); 7837 assert(ST->hasMVEIntegerOps() && 7838 "CONCAT_VECTORS lowering only supported for MVE"); 7839 7840 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 7841 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG); 7842 7843 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets 7844 // promoted to v8i16, etc. 7845 7846 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 7847 7848 // Extract the vector elements from Op1 and Op2 one by one and truncate them 7849 // to be the right size for the destination. For example, if Op1 is v4i1 then 7850 // the promoted vector is v4i32. The result of concatentation gives a v8i1, 7851 // which when promoted is v8i16. That means each i32 element from Op1 needs 7852 // truncating to i16 and inserting in the result. 7853 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts); 7854 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT); 7855 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) { 7856 EVT NewVT = NewV.getValueType(); 7857 EVT ConcatVT = ConVec.getValueType(); 7858 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) { 7859 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV, 7860 DAG.getIntPtrConstant(i, dl)); 7861 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt, 7862 DAG.getConstant(j, dl, MVT::i32)); 7863 } 7864 return ConVec; 7865 }; 7866 unsigned j = 0; 7867 ConVec = ExractInto(NewV1, ConVec, j); 7868 ConVec = ExractInto(NewV2, ConVec, j); 7869 7870 // Now return the result of comparing the subvector with zero, 7871 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7872 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec, 7873 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7874 } 7875 7876 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, 7877 const ARMSubtarget *ST) { 7878 EVT VT = Op->getValueType(0); 7879 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1) 7880 return LowerCONCAT_VECTORS_i1(Op, DAG, ST); 7881 7882 // The only time a CONCAT_VECTORS operation can have legal types is when 7883 // two 64-bit vectors are concatenated to a 128-bit vector. 7884 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7885 "unexpected CONCAT_VECTORS"); 7886 SDLoc dl(Op); 7887 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7888 SDValue Op0 = Op.getOperand(0); 7889 SDValue Op1 = Op.getOperand(1); 7890 if (!Op0.isUndef()) 7891 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7892 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7893 DAG.getIntPtrConstant(0, dl)); 7894 if (!Op1.isUndef()) 7895 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7896 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7897 DAG.getIntPtrConstant(1, dl)); 7898 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7899 } 7900 7901 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, 7902 const ARMSubtarget *ST) { 7903 SDValue V1 = Op.getOperand(0); 7904 SDValue V2 = Op.getOperand(1); 7905 SDLoc dl(Op); 7906 EVT VT = Op.getValueType(); 7907 EVT Op1VT = V1.getValueType(); 7908 unsigned NumElts = VT.getVectorNumElements(); 7909 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue(); 7910 7911 assert(VT.getScalarSizeInBits() == 1 && 7912 "Unexpected custom EXTRACT_SUBVECTOR lowering"); 7913 assert(ST->hasMVEIntegerOps() && 7914 "EXTRACT_SUBVECTOR lowering only supported for MVE"); 7915 7916 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG); 7917 7918 // We now have Op1 promoted to a vector of integers, where v8i1 gets 7919 // promoted to v8i16, etc. 7920 7921 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT(); 7922 7923 EVT SubVT = MVT::getVectorVT(ElType, NumElts); 7924 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT); 7925 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) { 7926 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1, 7927 DAG.getIntPtrConstant(i, dl)); 7928 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt, 7929 DAG.getConstant(j, dl, MVT::i32)); 7930 } 7931 7932 // Now return the result of comparing the subvector with zero, 7933 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. 7934 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec, 7935 DAG.getConstant(ARMCC::NE, dl, MVT::i32)); 7936 } 7937 7938 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7939 /// element has been zero/sign-extended, depending on the isSigned parameter, 7940 /// from an integer type half its size. 7941 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7942 bool isSigned) { 7943 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7944 EVT VT = N->getValueType(0); 7945 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7946 SDNode *BVN = N->getOperand(0).getNode(); 7947 if (BVN->getValueType(0) != MVT::v4i32 || 7948 BVN->getOpcode() != ISD::BUILD_VECTOR) 7949 return false; 7950 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7951 unsigned HiElt = 1 - LoElt; 7952 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7953 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7954 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7955 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7956 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7957 return false; 7958 if (isSigned) { 7959 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7960 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7961 return true; 7962 } else { 7963 if (Hi0->isNullValue() && Hi1->isNullValue()) 7964 return true; 7965 } 7966 return false; 7967 } 7968 7969 if (N->getOpcode() != ISD::BUILD_VECTOR) 7970 return false; 7971 7972 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7973 SDNode *Elt = N->getOperand(i).getNode(); 7974 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7975 unsigned EltSize = VT.getScalarSizeInBits(); 7976 unsigned HalfSize = EltSize / 2; 7977 if (isSigned) { 7978 if (!isIntN(HalfSize, C->getSExtValue())) 7979 return false; 7980 } else { 7981 if (!isUIntN(HalfSize, C->getZExtValue())) 7982 return false; 7983 } 7984 continue; 7985 } 7986 return false; 7987 } 7988 7989 return true; 7990 } 7991 7992 /// isSignExtended - Check if a node is a vector value that is sign-extended 7993 /// or a constant BUILD_VECTOR with sign-extended elements. 7994 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7995 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7996 return true; 7997 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7998 return true; 7999 return false; 8000 } 8001 8002 /// isZeroExtended - Check if a node is a vector value that is zero-extended 8003 /// or a constant BUILD_VECTOR with zero-extended elements. 8004 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 8005 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 8006 return true; 8007 if (isExtendedBUILD_VECTOR(N, DAG, false)) 8008 return true; 8009 return false; 8010 } 8011 8012 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 8013 if (OrigVT.getSizeInBits() >= 64) 8014 return OrigVT; 8015 8016 assert(OrigVT.isSimple() && "Expecting a simple value type"); 8017 8018 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 8019 switch (OrigSimpleTy) { 8020 default: llvm_unreachable("Unexpected Vector Type"); 8021 case MVT::v2i8: 8022 case MVT::v2i16: 8023 return MVT::v2i32; 8024 case MVT::v4i8: 8025 return MVT::v4i16; 8026 } 8027 } 8028 8029 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 8030 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 8031 /// We insert the required extension here to get the vector to fill a D register. 8032 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 8033 const EVT &OrigTy, 8034 const EVT &ExtTy, 8035 unsigned ExtOpcode) { 8036 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 8037 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 8038 // 64-bits we need to insert a new extension so that it will be 64-bits. 8039 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 8040 if (OrigTy.getSizeInBits() >= 64) 8041 return N; 8042 8043 // Must extend size to at least 64 bits to be used as an operand for VMULL. 8044 EVT NewVT = getExtensionTo64Bits(OrigTy); 8045 8046 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 8047 } 8048 8049 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 8050 /// does not do any sign/zero extension. If the original vector is less 8051 /// than 64 bits, an appropriate extension will be added after the load to 8052 /// reach a total size of 64 bits. We have to add the extension separately 8053 /// because ARM does not have a sign/zero extending load for vectors. 8054 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 8055 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 8056 8057 // The load already has the right type. 8058 if (ExtendedTy == LD->getMemoryVT()) 8059 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 8060 LD->getBasePtr(), LD->getPointerInfo(), 8061 LD->getAlignment(), LD->getMemOperand()->getFlags()); 8062 8063 // We need to create a zextload/sextload. We cannot just create a load 8064 // followed by a zext/zext node because LowerMUL is also run during normal 8065 // operation legalization where we can't create illegal types. 8066 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 8067 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 8068 LD->getMemoryVT(), LD->getAlignment(), 8069 LD->getMemOperand()->getFlags()); 8070 } 8071 8072 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 8073 /// extending load, or BUILD_VECTOR with extended elements, return the 8074 /// unextended value. The unextended vector should be 64 bits so that it can 8075 /// be used as an operand to a VMULL instruction. If the original vector size 8076 /// before extension is less than 64 bits we add a an extension to resize 8077 /// the vector to 64 bits. 8078 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 8079 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 8080 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 8081 N->getOperand(0)->getValueType(0), 8082 N->getValueType(0), 8083 N->getOpcode()); 8084 8085 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8086 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 8087 "Expected extending load"); 8088 8089 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 8090 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 8091 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8092 SDValue extLoad = 8093 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 8094 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 8095 8096 return newLoad; 8097 } 8098 8099 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 8100 // have been legalized as a BITCAST from v4i32. 8101 if (N->getOpcode() == ISD::BITCAST) { 8102 SDNode *BVN = N->getOperand(0).getNode(); 8103 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 8104 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 8105 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8106 return DAG.getBuildVector( 8107 MVT::v2i32, SDLoc(N), 8108 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 8109 } 8110 // Construct a new BUILD_VECTOR with elements truncated to half the size. 8111 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 8112 EVT VT = N->getValueType(0); 8113 unsigned EltSize = VT.getScalarSizeInBits() / 2; 8114 unsigned NumElts = VT.getVectorNumElements(); 8115 MVT TruncVT = MVT::getIntegerVT(EltSize); 8116 SmallVector<SDValue, 8> Ops; 8117 SDLoc dl(N); 8118 for (unsigned i = 0; i != NumElts; ++i) { 8119 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 8120 const APInt &CInt = C->getAPIntValue(); 8121 // Element types smaller than 32 bits are not legal, so use i32 elements. 8122 // The values are implicitly truncated so sext vs. zext doesn't matter. 8123 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 8124 } 8125 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 8126 } 8127 8128 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 8129 unsigned Opcode = N->getOpcode(); 8130 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8131 SDNode *N0 = N->getOperand(0).getNode(); 8132 SDNode *N1 = N->getOperand(1).getNode(); 8133 return N0->hasOneUse() && N1->hasOneUse() && 8134 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 8135 } 8136 return false; 8137 } 8138 8139 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 8140 unsigned Opcode = N->getOpcode(); 8141 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 8142 SDNode *N0 = N->getOperand(0).getNode(); 8143 SDNode *N1 = N->getOperand(1).getNode(); 8144 return N0->hasOneUse() && N1->hasOneUse() && 8145 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 8146 } 8147 return false; 8148 } 8149 8150 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 8151 // Multiplications are only custom-lowered for 128-bit vectors so that 8152 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 8153 EVT VT = Op.getValueType(); 8154 assert(VT.is128BitVector() && VT.isInteger() && 8155 "unexpected type for custom-lowering ISD::MUL"); 8156 SDNode *N0 = Op.getOperand(0).getNode(); 8157 SDNode *N1 = Op.getOperand(1).getNode(); 8158 unsigned NewOpc = 0; 8159 bool isMLA = false; 8160 bool isN0SExt = isSignExtended(N0, DAG); 8161 bool isN1SExt = isSignExtended(N1, DAG); 8162 if (isN0SExt && isN1SExt) 8163 NewOpc = ARMISD::VMULLs; 8164 else { 8165 bool isN0ZExt = isZeroExtended(N0, DAG); 8166 bool isN1ZExt = isZeroExtended(N1, DAG); 8167 if (isN0ZExt && isN1ZExt) 8168 NewOpc = ARMISD::VMULLu; 8169 else if (isN1SExt || isN1ZExt) { 8170 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 8171 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 8172 if (isN1SExt && isAddSubSExt(N0, DAG)) { 8173 NewOpc = ARMISD::VMULLs; 8174 isMLA = true; 8175 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 8176 NewOpc = ARMISD::VMULLu; 8177 isMLA = true; 8178 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 8179 std::swap(N0, N1); 8180 NewOpc = ARMISD::VMULLu; 8181 isMLA = true; 8182 } 8183 } 8184 8185 if (!NewOpc) { 8186 if (VT == MVT::v2i64) 8187 // Fall through to expand this. It is not legal. 8188 return SDValue(); 8189 else 8190 // Other vector multiplications are legal. 8191 return Op; 8192 } 8193 } 8194 8195 // Legalize to a VMULL instruction. 8196 SDLoc DL(Op); 8197 SDValue Op0; 8198 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 8199 if (!isMLA) { 8200 Op0 = SkipExtensionForVMULL(N0, DAG); 8201 assert(Op0.getValueType().is64BitVector() && 8202 Op1.getValueType().is64BitVector() && 8203 "unexpected types for extended operands to VMULL"); 8204 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 8205 } 8206 8207 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 8208 // isel lowering to take advantage of no-stall back to back vmul + vmla. 8209 // vmull q0, d4, d6 8210 // vmlal q0, d5, d6 8211 // is faster than 8212 // vaddl q0, d4, d5 8213 // vmovl q1, d6 8214 // vmul q0, q0, q1 8215 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 8216 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 8217 EVT Op1VT = Op1.getValueType(); 8218 return DAG.getNode(N0->getOpcode(), DL, VT, 8219 DAG.getNode(NewOpc, DL, VT, 8220 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 8221 DAG.getNode(NewOpc, DL, VT, 8222 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 8223 } 8224 8225 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 8226 SelectionDAG &DAG) { 8227 // TODO: Should this propagate fast-math-flags? 8228 8229 // Convert to float 8230 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 8231 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 8232 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 8233 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 8234 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 8235 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 8236 // Get reciprocal estimate. 8237 // float4 recip = vrecpeq_f32(yf); 8238 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8239 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8240 Y); 8241 // Because char has a smaller range than uchar, we can actually get away 8242 // without any newton steps. This requires that we use a weird bias 8243 // of 0xb000, however (again, this has been exhaustively tested). 8244 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 8245 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 8246 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 8247 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 8248 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 8249 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 8250 // Convert back to short. 8251 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 8252 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 8253 return X; 8254 } 8255 8256 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 8257 SelectionDAG &DAG) { 8258 // TODO: Should this propagate fast-math-flags? 8259 8260 SDValue N2; 8261 // Convert to float. 8262 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 8263 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 8264 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 8265 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 8266 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8267 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8268 8269 // Use reciprocal estimate and one refinement step. 8270 // float4 recip = vrecpeq_f32(yf); 8271 // recip *= vrecpsq_f32(yf, recip); 8272 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8273 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8274 N1); 8275 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8276 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8277 N1, N2); 8278 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8279 // Because short has a smaller range than ushort, we can actually get away 8280 // with only a single newton step. This requires that we use a weird bias 8281 // of 89, however (again, this has been exhaustively tested). 8282 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 8283 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8284 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8285 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 8286 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8287 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8288 // Convert back to integer and return. 8289 // return vmovn_s32(vcvt_s32_f32(result)); 8290 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8291 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8292 return N0; 8293 } 8294 8295 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, 8296 const ARMSubtarget *ST) { 8297 EVT VT = Op.getValueType(); 8298 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8299 "unexpected type for custom-lowering ISD::SDIV"); 8300 8301 SDLoc dl(Op); 8302 SDValue N0 = Op.getOperand(0); 8303 SDValue N1 = Op.getOperand(1); 8304 SDValue N2, N3; 8305 8306 if (VT == MVT::v8i8) { 8307 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 8308 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 8309 8310 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8311 DAG.getIntPtrConstant(4, dl)); 8312 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8313 DAG.getIntPtrConstant(4, dl)); 8314 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8315 DAG.getIntPtrConstant(0, dl)); 8316 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8317 DAG.getIntPtrConstant(0, dl)); 8318 8319 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 8320 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 8321 8322 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8323 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8324 8325 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 8326 return N0; 8327 } 8328 return LowerSDIV_v4i16(N0, N1, dl, DAG); 8329 } 8330 8331 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, 8332 const ARMSubtarget *ST) { 8333 // TODO: Should this propagate fast-math-flags? 8334 EVT VT = Op.getValueType(); 8335 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 8336 "unexpected type for custom-lowering ISD::UDIV"); 8337 8338 SDLoc dl(Op); 8339 SDValue N0 = Op.getOperand(0); 8340 SDValue N1 = Op.getOperand(1); 8341 SDValue N2, N3; 8342 8343 if (VT == MVT::v8i8) { 8344 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 8345 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 8346 8347 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8348 DAG.getIntPtrConstant(4, dl)); 8349 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8350 DAG.getIntPtrConstant(4, dl)); 8351 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 8352 DAG.getIntPtrConstant(0, dl)); 8353 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 8354 DAG.getIntPtrConstant(0, dl)); 8355 8356 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 8357 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 8358 8359 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 8360 N0 = LowerCONCAT_VECTORS(N0, DAG, ST); 8361 8362 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 8363 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 8364 MVT::i32), 8365 N0); 8366 return N0; 8367 } 8368 8369 // v4i16 sdiv ... Convert to float. 8370 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 8371 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 8372 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 8373 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 8374 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 8375 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 8376 8377 // Use reciprocal estimate and two refinement steps. 8378 // float4 recip = vrecpeq_f32(yf); 8379 // recip *= vrecpsq_f32(yf, recip); 8380 // recip *= vrecpsq_f32(yf, recip); 8381 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8382 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 8383 BN1); 8384 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8385 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8386 BN1, N2); 8387 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8388 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 8389 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 8390 BN1, N2); 8391 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 8392 // Simply multiplying by the reciprocal estimate can leave us a few ulps 8393 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 8394 // and that it will never cause us to return an answer too large). 8395 // float4 result = as_float4(as_int4(xf*recip) + 2); 8396 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 8397 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 8398 N1 = DAG.getConstant(2, dl, MVT::v4i32); 8399 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 8400 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 8401 // Convert back to integer and return. 8402 // return vmovn_u32(vcvt_s32_f32(result)); 8403 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 8404 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 8405 return N0; 8406 } 8407 8408 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 8409 SDNode *N = Op.getNode(); 8410 EVT VT = N->getValueType(0); 8411 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 8412 8413 SDValue Carry = Op.getOperand(2); 8414 8415 SDLoc DL(Op); 8416 8417 SDValue Result; 8418 if (Op.getOpcode() == ISD::ADDCARRY) { 8419 // This converts the boolean value carry into the carry flag. 8420 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8421 8422 // Do the addition proper using the carry flag we wanted. 8423 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 8424 Op.getOperand(1), Carry); 8425 8426 // Now convert the carry flag into a boolean value. 8427 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8428 } else { 8429 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 8430 // have to invert the carry first. 8431 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8432 DAG.getConstant(1, DL, MVT::i32), Carry); 8433 // This converts the boolean value carry into the carry flag. 8434 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 8435 8436 // Do the subtraction proper using the carry flag we wanted. 8437 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 8438 Op.getOperand(1), Carry); 8439 8440 // Now convert the carry flag into a boolean value. 8441 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 8442 // But the carry returned by ARMISD::SUBE is not a borrow as expected 8443 // by ISD::SUBCARRY, so compute 1 - C. 8444 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 8445 DAG.getConstant(1, DL, MVT::i32), Carry); 8446 } 8447 8448 // Return both values. 8449 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 8450 } 8451 8452 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 8453 assert(Subtarget->isTargetDarwin()); 8454 8455 // For iOS, we want to call an alternative entry point: __sincos_stret, 8456 // return values are passed via sret. 8457 SDLoc dl(Op); 8458 SDValue Arg = Op.getOperand(0); 8459 EVT ArgVT = Arg.getValueType(); 8460 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 8461 auto PtrVT = getPointerTy(DAG.getDataLayout()); 8462 8463 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8464 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8465 8466 // Pair of floats / doubles used to pass the result. 8467 Type *RetTy = StructType::get(ArgTy, ArgTy); 8468 auto &DL = DAG.getDataLayout(); 8469 8470 ArgListTy Args; 8471 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 8472 SDValue SRet; 8473 if (ShouldUseSRet) { 8474 // Create stack object for sret. 8475 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 8476 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 8477 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 8478 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 8479 8480 ArgListEntry Entry; 8481 Entry.Node = SRet; 8482 Entry.Ty = RetTy->getPointerTo(); 8483 Entry.IsSExt = false; 8484 Entry.IsZExt = false; 8485 Entry.IsSRet = true; 8486 Args.push_back(Entry); 8487 RetTy = Type::getVoidTy(*DAG.getContext()); 8488 } 8489 8490 ArgListEntry Entry; 8491 Entry.Node = Arg; 8492 Entry.Ty = ArgTy; 8493 Entry.IsSExt = false; 8494 Entry.IsZExt = false; 8495 Args.push_back(Entry); 8496 8497 RTLIB::Libcall LC = 8498 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 8499 const char *LibcallName = getLibcallName(LC); 8500 CallingConv::ID CC = getLibcallCallingConv(LC); 8501 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 8502 8503 TargetLowering::CallLoweringInfo CLI(DAG); 8504 CLI.setDebugLoc(dl) 8505 .setChain(DAG.getEntryNode()) 8506 .setCallee(CC, RetTy, Callee, std::move(Args)) 8507 .setDiscardResult(ShouldUseSRet); 8508 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8509 8510 if (!ShouldUseSRet) 8511 return CallResult.first; 8512 8513 SDValue LoadSin = 8514 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 8515 8516 // Address of cos field. 8517 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 8518 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 8519 SDValue LoadCos = 8520 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 8521 8522 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 8523 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 8524 LoadSin.getValue(0), LoadCos.getValue(0)); 8525 } 8526 8527 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 8528 bool Signed, 8529 SDValue &Chain) const { 8530 EVT VT = Op.getValueType(); 8531 assert((VT == MVT::i32 || VT == MVT::i64) && 8532 "unexpected type for custom lowering DIV"); 8533 SDLoc dl(Op); 8534 8535 const auto &DL = DAG.getDataLayout(); 8536 const auto &TLI = DAG.getTargetLoweringInfo(); 8537 8538 const char *Name = nullptr; 8539 if (Signed) 8540 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 8541 else 8542 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 8543 8544 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 8545 8546 ARMTargetLowering::ArgListTy Args; 8547 8548 for (auto AI : {1, 0}) { 8549 ArgListEntry Arg; 8550 Arg.Node = Op.getOperand(AI); 8551 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 8552 Args.push_back(Arg); 8553 } 8554 8555 CallLoweringInfo CLI(DAG); 8556 CLI.setDebugLoc(dl) 8557 .setChain(Chain) 8558 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 8559 ES, std::move(Args)); 8560 8561 return LowerCallTo(CLI).first; 8562 } 8563 8564 // This is a code size optimisation: return the original SDIV node to 8565 // DAGCombiner when we don't want to expand SDIV into a sequence of 8566 // instructions, and an empty node otherwise which will cause the 8567 // SDIV to be expanded in DAGCombine. 8568 SDValue 8569 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8570 SelectionDAG &DAG, 8571 SmallVectorImpl<SDNode *> &Created) const { 8572 // TODO: Support SREM 8573 if (N->getOpcode() != ISD::SDIV) 8574 return SDValue(); 8575 8576 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 8577 const bool MinSize = ST.hasMinSize(); 8578 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 8579 : ST.hasDivideInARMMode(); 8580 8581 // Don't touch vector types; rewriting this may lead to scalarizing 8582 // the int divs. 8583 if (N->getOperand(0).getValueType().isVector()) 8584 return SDValue(); 8585 8586 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 8587 // hwdiv support for this to be really profitable. 8588 if (!(MinSize && HasDivide)) 8589 return SDValue(); 8590 8591 // ARM mode is a bit simpler than Thumb: we can handle large power 8592 // of 2 immediates with 1 mov instruction; no further checks required, 8593 // just return the sdiv node. 8594 if (!ST.isThumb()) 8595 return SDValue(N, 0); 8596 8597 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 8598 // and thus lose the code size benefits of a MOVS that requires only 2. 8599 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 8600 // but as it's doing exactly this, it's not worth the trouble to get TTI. 8601 if (Divisor.sgt(128)) 8602 return SDValue(); 8603 8604 return SDValue(N, 0); 8605 } 8606 8607 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 8608 bool Signed) const { 8609 assert(Op.getValueType() == MVT::i32 && 8610 "unexpected type for custom lowering DIV"); 8611 SDLoc dl(Op); 8612 8613 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 8614 DAG.getEntryNode(), Op.getOperand(1)); 8615 8616 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8617 } 8618 8619 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 8620 SDLoc DL(N); 8621 SDValue Op = N->getOperand(1); 8622 if (N->getValueType(0) == MVT::i32) 8623 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 8624 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8625 DAG.getConstant(0, DL, MVT::i32)); 8626 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8627 DAG.getConstant(1, DL, MVT::i32)); 8628 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 8629 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 8630 } 8631 8632 void ARMTargetLowering::ExpandDIV_Windows( 8633 SDValue Op, SelectionDAG &DAG, bool Signed, 8634 SmallVectorImpl<SDValue> &Results) const { 8635 const auto &DL = DAG.getDataLayout(); 8636 const auto &TLI = DAG.getTargetLoweringInfo(); 8637 8638 assert(Op.getValueType() == MVT::i64 && 8639 "unexpected type for custom lowering DIV"); 8640 SDLoc dl(Op); 8641 8642 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 8643 8644 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8645 8646 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 8647 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 8648 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 8649 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 8650 8651 Results.push_back(Lower); 8652 Results.push_back(Upper); 8653 } 8654 8655 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 8656 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 8657 // Acquire/Release load/store is not legal for targets without a dmb or 8658 // equivalent available. 8659 return SDValue(); 8660 8661 // Monotonic load/store is legal for all targets. 8662 return Op; 8663 } 8664 8665 static void ReplaceREADCYCLECOUNTER(SDNode *N, 8666 SmallVectorImpl<SDValue> &Results, 8667 SelectionDAG &DAG, 8668 const ARMSubtarget *Subtarget) { 8669 SDLoc DL(N); 8670 // Under Power Management extensions, the cycle-count is: 8671 // mrc p15, #0, <Rt>, c9, c13, #0 8672 SDValue Ops[] = { N->getOperand(0), // Chain 8673 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 8674 DAG.getConstant(15, DL, MVT::i32), 8675 DAG.getConstant(0, DL, MVT::i32), 8676 DAG.getConstant(9, DL, MVT::i32), 8677 DAG.getConstant(13, DL, MVT::i32), 8678 DAG.getConstant(0, DL, MVT::i32) 8679 }; 8680 8681 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 8682 DAG.getVTList(MVT::i32, MVT::Other), Ops); 8683 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 8684 DAG.getConstant(0, DL, MVT::i32))); 8685 Results.push_back(Cycles32.getValue(1)); 8686 } 8687 8688 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 8689 SDLoc dl(V.getNode()); 8690 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 8691 SDValue VHi = DAG.getAnyExtOrTrunc( 8692 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 8693 dl, MVT::i32); 8694 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8695 if (isBigEndian) 8696 std::swap (VLo, VHi); 8697 SDValue RegClass = 8698 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 8699 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 8700 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 8701 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 8702 return SDValue( 8703 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 8704 } 8705 8706 static void ReplaceCMP_SWAP_64Results(SDNode *N, 8707 SmallVectorImpl<SDValue> & Results, 8708 SelectionDAG &DAG) { 8709 assert(N->getValueType(0) == MVT::i64 && 8710 "AtomicCmpSwap on types less than 64 should be legal"); 8711 SDValue Ops[] = {N->getOperand(1), 8712 createGPRPairNode(DAG, N->getOperand(2)), 8713 createGPRPairNode(DAG, N->getOperand(3)), 8714 N->getOperand(0)}; 8715 SDNode *CmpSwap = DAG.getMachineNode( 8716 ARM::CMP_SWAP_64, SDLoc(N), 8717 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 8718 8719 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 8720 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 8721 8722 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8723 8724 Results.push_back( 8725 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 8726 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8727 Results.push_back( 8728 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 8729 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8730 Results.push_back(SDValue(CmpSwap, 2)); 8731 } 8732 8733 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 8734 SelectionDAG &DAG) { 8735 const auto &TLI = DAG.getTargetLoweringInfo(); 8736 8737 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 8738 "Custom lowering is MSVCRT specific!"); 8739 8740 SDLoc dl(Op); 8741 SDValue Val = Op.getOperand(0); 8742 MVT Ty = Val->getSimpleValueType(0); 8743 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 8744 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 8745 TLI.getPointerTy(DAG.getDataLayout())); 8746 8747 TargetLowering::ArgListTy Args; 8748 TargetLowering::ArgListEntry Entry; 8749 8750 Entry.Node = Val; 8751 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8752 Entry.IsZExt = true; 8753 Args.push_back(Entry); 8754 8755 Entry.Node = Exponent; 8756 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8757 Entry.IsZExt = true; 8758 Args.push_back(Entry); 8759 8760 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8761 8762 // In the in-chain to the call is the entry node If we are emitting a 8763 // tailcall, the chain will be mutated if the node has a non-entry input 8764 // chain. 8765 SDValue InChain = DAG.getEntryNode(); 8766 SDValue TCChain = InChain; 8767 8768 const Function &F = DAG.getMachineFunction().getFunction(); 8769 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8770 F.getReturnType() == LCRTy; 8771 if (IsTC) 8772 InChain = TCChain; 8773 8774 TargetLowering::CallLoweringInfo CLI(DAG); 8775 CLI.setDebugLoc(dl) 8776 .setChain(InChain) 8777 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8778 .setTailCall(IsTC); 8779 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8780 8781 // Return the chain (the DAG root) if it is a tail call 8782 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8783 } 8784 8785 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8786 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8787 switch (Op.getOpcode()) { 8788 default: llvm_unreachable("Don't know how to custom lower this!"); 8789 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8790 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8791 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8792 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8793 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8794 case ISD::SELECT: return LowerSELECT(Op, DAG); 8795 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8796 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8797 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8798 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8799 case ISD::VASTART: return LowerVASTART(Op, DAG); 8800 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8801 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8802 case ISD::SINT_TO_FP: 8803 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8804 case ISD::FP_TO_SINT: 8805 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8806 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8807 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8808 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8809 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8810 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8811 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8812 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8813 Subtarget); 8814 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8815 case ISD::SHL: 8816 case ISD::SRL: 8817 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8818 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8819 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8820 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8821 case ISD::SRL_PARTS: 8822 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8823 case ISD::CTTZ: 8824 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8825 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8826 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget); 8827 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8828 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8829 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8830 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 8831 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget); 8832 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8833 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget); 8834 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget); 8835 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8836 case ISD::MUL: return LowerMUL(Op, DAG); 8837 case ISD::SDIV: 8838 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8839 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8840 return LowerSDIV(Op, DAG, Subtarget); 8841 case ISD::UDIV: 8842 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8843 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8844 return LowerUDIV(Op, DAG, Subtarget); 8845 case ISD::ADDCARRY: 8846 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8847 case ISD::SADDO: 8848 case ISD::SSUBO: 8849 return LowerSignedALUO(Op, DAG); 8850 case ISD::UADDO: 8851 case ISD::USUBO: 8852 return LowerUnsignedALUO(Op, DAG); 8853 case ISD::ATOMIC_LOAD: 8854 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8855 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8856 case ISD::SDIVREM: 8857 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8858 case ISD::DYNAMIC_STACKALLOC: 8859 if (Subtarget->isTargetWindows()) 8860 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8861 llvm_unreachable("Don't know how to custom lower this!"); 8862 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8863 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8864 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8865 case ARMISD::WIN__DBZCHK: return SDValue(); 8866 } 8867 } 8868 8869 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8870 SelectionDAG &DAG) { 8871 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8872 unsigned Opc = 0; 8873 if (IntNo == Intrinsic::arm_smlald) 8874 Opc = ARMISD::SMLALD; 8875 else if (IntNo == Intrinsic::arm_smlaldx) 8876 Opc = ARMISD::SMLALDX; 8877 else if (IntNo == Intrinsic::arm_smlsld) 8878 Opc = ARMISD::SMLSLD; 8879 else if (IntNo == Intrinsic::arm_smlsldx) 8880 Opc = ARMISD::SMLSLDX; 8881 else 8882 return; 8883 8884 SDLoc dl(N); 8885 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8886 N->getOperand(3), 8887 DAG.getConstant(0, dl, MVT::i32)); 8888 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8889 N->getOperand(3), 8890 DAG.getConstant(1, dl, MVT::i32)); 8891 8892 SDValue LongMul = DAG.getNode(Opc, dl, 8893 DAG.getVTList(MVT::i32, MVT::i32), 8894 N->getOperand(1), N->getOperand(2), 8895 Lo, Hi); 8896 Results.push_back(LongMul.getValue(0)); 8897 Results.push_back(LongMul.getValue(1)); 8898 } 8899 8900 /// ReplaceNodeResults - Replace the results of node with an illegal result 8901 /// type with new values built out of custom code. 8902 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8903 SmallVectorImpl<SDValue> &Results, 8904 SelectionDAG &DAG) const { 8905 SDValue Res; 8906 switch (N->getOpcode()) { 8907 default: 8908 llvm_unreachable("Don't know how to custom expand this!"); 8909 case ISD::READ_REGISTER: 8910 ExpandREAD_REGISTER(N, Results, DAG); 8911 break; 8912 case ISD::BITCAST: 8913 Res = ExpandBITCAST(N, DAG, Subtarget); 8914 break; 8915 case ISD::SRL: 8916 case ISD::SRA: 8917 case ISD::SHL: 8918 Res = Expand64BitShift(N, DAG, Subtarget); 8919 break; 8920 case ISD::SREM: 8921 case ISD::UREM: 8922 Res = LowerREM(N, DAG); 8923 break; 8924 case ISD::SDIVREM: 8925 case ISD::UDIVREM: 8926 Res = LowerDivRem(SDValue(N, 0), DAG); 8927 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8928 Results.push_back(Res.getValue(0)); 8929 Results.push_back(Res.getValue(1)); 8930 return; 8931 case ISD::READCYCLECOUNTER: 8932 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8933 return; 8934 case ISD::UDIV: 8935 case ISD::SDIV: 8936 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8937 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8938 Results); 8939 case ISD::ATOMIC_CMP_SWAP: 8940 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8941 return; 8942 case ISD::INTRINSIC_WO_CHAIN: 8943 return ReplaceLongIntrinsic(N, Results, DAG); 8944 case ISD::ABS: 8945 lowerABS(N, Results, DAG); 8946 return ; 8947 8948 } 8949 if (Res.getNode()) 8950 Results.push_back(Res); 8951 } 8952 8953 //===----------------------------------------------------------------------===// 8954 // ARM Scheduler Hooks 8955 //===----------------------------------------------------------------------===// 8956 8957 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8958 /// registers the function context. 8959 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8960 MachineBasicBlock *MBB, 8961 MachineBasicBlock *DispatchBB, 8962 int FI) const { 8963 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8964 "ROPI/RWPI not currently supported with SjLj"); 8965 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8966 DebugLoc dl = MI.getDebugLoc(); 8967 MachineFunction *MF = MBB->getParent(); 8968 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8969 MachineConstantPool *MCP = MF->getConstantPool(); 8970 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8971 const Function &F = MF->getFunction(); 8972 8973 bool isThumb = Subtarget->isThumb(); 8974 bool isThumb2 = Subtarget->isThumb2(); 8975 8976 unsigned PCLabelId = AFI->createPICLabelUId(); 8977 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8978 ARMConstantPoolValue *CPV = 8979 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8980 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8981 8982 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8983 : &ARM::GPRRegClass; 8984 8985 // Grab constant pool and fixed stack memory operands. 8986 MachineMemOperand *CPMMO = 8987 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8988 MachineMemOperand::MOLoad, 4, 4); 8989 8990 MachineMemOperand *FIMMOSt = 8991 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8992 MachineMemOperand::MOStore, 4, 4); 8993 8994 // Load the address of the dispatch MBB into the jump buffer. 8995 if (isThumb2) { 8996 // Incoming value: jbuf 8997 // ldr.n r5, LCPI1_1 8998 // orr r5, r5, #1 8999 // add r5, pc 9000 // str r5, [$jbuf, #+4] ; &jbuf[1] 9001 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9002 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 9003 .addConstantPoolIndex(CPI) 9004 .addMemOperand(CPMMO) 9005 .add(predOps(ARMCC::AL)); 9006 // Set the low bit because of thumb mode. 9007 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 9008 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 9009 .addReg(NewVReg1, RegState::Kill) 9010 .addImm(0x01) 9011 .add(predOps(ARMCC::AL)) 9012 .add(condCodeOp()); 9013 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9014 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 9015 .addReg(NewVReg2, RegState::Kill) 9016 .addImm(PCLabelId); 9017 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 9018 .addReg(NewVReg3, RegState::Kill) 9019 .addFrameIndex(FI) 9020 .addImm(36) // &jbuf[1] :: pc 9021 .addMemOperand(FIMMOSt) 9022 .add(predOps(ARMCC::AL)); 9023 } else if (isThumb) { 9024 // Incoming value: jbuf 9025 // ldr.n r1, LCPI1_4 9026 // add r1, pc 9027 // mov r2, #1 9028 // orrs r1, r2 9029 // add r2, $jbuf, #+4 ; &jbuf[1] 9030 // str r1, [r2] 9031 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9032 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 9033 .addConstantPoolIndex(CPI) 9034 .addMemOperand(CPMMO) 9035 .add(predOps(ARMCC::AL)); 9036 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 9037 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 9038 .addReg(NewVReg1, RegState::Kill) 9039 .addImm(PCLabelId); 9040 // Set the low bit because of thumb mode. 9041 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9042 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 9043 .addReg(ARM::CPSR, RegState::Define) 9044 .addImm(1) 9045 .add(predOps(ARMCC::AL)); 9046 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 9047 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 9048 .addReg(ARM::CPSR, RegState::Define) 9049 .addReg(NewVReg2, RegState::Kill) 9050 .addReg(NewVReg3, RegState::Kill) 9051 .add(predOps(ARMCC::AL)); 9052 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 9053 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 9054 .addFrameIndex(FI) 9055 .addImm(36); // &jbuf[1] :: pc 9056 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 9057 .addReg(NewVReg4, RegState::Kill) 9058 .addReg(NewVReg5, RegState::Kill) 9059 .addImm(0) 9060 .addMemOperand(FIMMOSt) 9061 .add(predOps(ARMCC::AL)); 9062 } else { 9063 // Incoming value: jbuf 9064 // ldr r1, LCPI1_1 9065 // add r1, pc, r1 9066 // str r1, [$jbuf, #+4] ; &jbuf[1] 9067 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9068 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 9069 .addConstantPoolIndex(CPI) 9070 .addImm(0) 9071 .addMemOperand(CPMMO) 9072 .add(predOps(ARMCC::AL)); 9073 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 9074 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 9075 .addReg(NewVReg1, RegState::Kill) 9076 .addImm(PCLabelId) 9077 .add(predOps(ARMCC::AL)); 9078 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 9079 .addReg(NewVReg2, RegState::Kill) 9080 .addFrameIndex(FI) 9081 .addImm(36) // &jbuf[1] :: pc 9082 .addMemOperand(FIMMOSt) 9083 .add(predOps(ARMCC::AL)); 9084 } 9085 } 9086 9087 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 9088 MachineBasicBlock *MBB) const { 9089 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9090 DebugLoc dl = MI.getDebugLoc(); 9091 MachineFunction *MF = MBB->getParent(); 9092 MachineRegisterInfo *MRI = &MF->getRegInfo(); 9093 MachineFrameInfo &MFI = MF->getFrameInfo(); 9094 int FI = MFI.getFunctionContextIndex(); 9095 9096 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 9097 : &ARM::GPRnopcRegClass; 9098 9099 // Get a mapping of the call site numbers to all of the landing pads they're 9100 // associated with. 9101 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 9102 unsigned MaxCSNum = 0; 9103 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 9104 ++BB) { 9105 if (!BB->isEHPad()) continue; 9106 9107 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 9108 // pad. 9109 for (MachineBasicBlock::iterator 9110 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 9111 if (!II->isEHLabel()) continue; 9112 9113 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 9114 if (!MF->hasCallSiteLandingPad(Sym)) continue; 9115 9116 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 9117 for (SmallVectorImpl<unsigned>::iterator 9118 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 9119 CSI != CSE; ++CSI) { 9120 CallSiteNumToLPad[*CSI].push_back(&*BB); 9121 MaxCSNum = std::max(MaxCSNum, *CSI); 9122 } 9123 break; 9124 } 9125 } 9126 9127 // Get an ordered list of the machine basic blocks for the jump table. 9128 std::vector<MachineBasicBlock*> LPadList; 9129 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 9130 LPadList.reserve(CallSiteNumToLPad.size()); 9131 for (unsigned I = 1; I <= MaxCSNum; ++I) { 9132 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 9133 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9134 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 9135 LPadList.push_back(*II); 9136 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 9137 } 9138 } 9139 9140 assert(!LPadList.empty() && 9141 "No landing pad destinations for the dispatch jump table!"); 9142 9143 // Create the jump table and associated information. 9144 MachineJumpTableInfo *JTI = 9145 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 9146 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 9147 9148 // Create the MBBs for the dispatch code. 9149 9150 // Shove the dispatch's address into the return slot in the function context. 9151 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 9152 DispatchBB->setIsEHPad(); 9153 9154 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9155 unsigned trap_opcode; 9156 if (Subtarget->isThumb()) 9157 trap_opcode = ARM::tTRAP; 9158 else 9159 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 9160 9161 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 9162 DispatchBB->addSuccessor(TrapBB); 9163 9164 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 9165 DispatchBB->addSuccessor(DispContBB); 9166 9167 // Insert and MBBs. 9168 MF->insert(MF->end(), DispatchBB); 9169 MF->insert(MF->end(), DispContBB); 9170 MF->insert(MF->end(), TrapBB); 9171 9172 // Insert code into the entry block that creates and registers the function 9173 // context. 9174 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 9175 9176 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 9177 MachinePointerInfo::getFixedStack(*MF, FI), 9178 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 9179 9180 MachineInstrBuilder MIB; 9181 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 9182 9183 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 9184 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 9185 9186 // Add a register mask with no preserved registers. This results in all 9187 // registers being marked as clobbered. This can't work if the dispatch block 9188 // is in a Thumb1 function and is linked with ARM code which uses the FP 9189 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 9190 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 9191 9192 bool IsPositionIndependent = isPositionIndependent(); 9193 unsigned NumLPads = LPadList.size(); 9194 if (Subtarget->isThumb2()) { 9195 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9196 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 9197 .addFrameIndex(FI) 9198 .addImm(4) 9199 .addMemOperand(FIMMOLd) 9200 .add(predOps(ARMCC::AL)); 9201 9202 if (NumLPads < 256) { 9203 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 9204 .addReg(NewVReg1) 9205 .addImm(LPadList.size()) 9206 .add(predOps(ARMCC::AL)); 9207 } else { 9208 unsigned VReg1 = MRI->createVirtualRegister(TRC); 9209 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 9210 .addImm(NumLPads & 0xFFFF) 9211 .add(predOps(ARMCC::AL)); 9212 9213 unsigned VReg2 = VReg1; 9214 if ((NumLPads & 0xFFFF0000) != 0) { 9215 VReg2 = MRI->createVirtualRegister(TRC); 9216 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 9217 .addReg(VReg1) 9218 .addImm(NumLPads >> 16) 9219 .add(predOps(ARMCC::AL)); 9220 } 9221 9222 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 9223 .addReg(NewVReg1) 9224 .addReg(VReg2) 9225 .add(predOps(ARMCC::AL)); 9226 } 9227 9228 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 9229 .addMBB(TrapBB) 9230 .addImm(ARMCC::HI) 9231 .addReg(ARM::CPSR); 9232 9233 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9234 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 9235 .addJumpTableIndex(MJTI) 9236 .add(predOps(ARMCC::AL)); 9237 9238 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 9239 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 9240 .addReg(NewVReg3, RegState::Kill) 9241 .addReg(NewVReg1) 9242 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9243 .add(predOps(ARMCC::AL)) 9244 .add(condCodeOp()); 9245 9246 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 9247 .addReg(NewVReg4, RegState::Kill) 9248 .addReg(NewVReg1) 9249 .addJumpTableIndex(MJTI); 9250 } else if (Subtarget->isThumb()) { 9251 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9252 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 9253 .addFrameIndex(FI) 9254 .addImm(1) 9255 .addMemOperand(FIMMOLd) 9256 .add(predOps(ARMCC::AL)); 9257 9258 if (NumLPads < 256) { 9259 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 9260 .addReg(NewVReg1) 9261 .addImm(NumLPads) 9262 .add(predOps(ARMCC::AL)); 9263 } else { 9264 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9265 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9266 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9267 9268 // MachineConstantPool wants an explicit alignment. 9269 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9270 if (Align == 0) 9271 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9272 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9273 9274 unsigned VReg1 = MRI->createVirtualRegister(TRC); 9275 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 9276 .addReg(VReg1, RegState::Define) 9277 .addConstantPoolIndex(Idx) 9278 .add(predOps(ARMCC::AL)); 9279 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 9280 .addReg(NewVReg1) 9281 .addReg(VReg1) 9282 .add(predOps(ARMCC::AL)); 9283 } 9284 9285 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 9286 .addMBB(TrapBB) 9287 .addImm(ARMCC::HI) 9288 .addReg(ARM::CPSR); 9289 9290 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 9291 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 9292 .addReg(ARM::CPSR, RegState::Define) 9293 .addReg(NewVReg1) 9294 .addImm(2) 9295 .add(predOps(ARMCC::AL)); 9296 9297 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9298 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 9299 .addJumpTableIndex(MJTI) 9300 .add(predOps(ARMCC::AL)); 9301 9302 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 9303 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 9304 .addReg(ARM::CPSR, RegState::Define) 9305 .addReg(NewVReg2, RegState::Kill) 9306 .addReg(NewVReg3) 9307 .add(predOps(ARMCC::AL)); 9308 9309 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9310 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9311 9312 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 9313 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 9314 .addReg(NewVReg4, RegState::Kill) 9315 .addImm(0) 9316 .addMemOperand(JTMMOLd) 9317 .add(predOps(ARMCC::AL)); 9318 9319 unsigned NewVReg6 = NewVReg5; 9320 if (IsPositionIndependent) { 9321 NewVReg6 = MRI->createVirtualRegister(TRC); 9322 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 9323 .addReg(ARM::CPSR, RegState::Define) 9324 .addReg(NewVReg5, RegState::Kill) 9325 .addReg(NewVReg3) 9326 .add(predOps(ARMCC::AL)); 9327 } 9328 9329 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 9330 .addReg(NewVReg6, RegState::Kill) 9331 .addJumpTableIndex(MJTI); 9332 } else { 9333 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 9334 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 9335 .addFrameIndex(FI) 9336 .addImm(4) 9337 .addMemOperand(FIMMOLd) 9338 .add(predOps(ARMCC::AL)); 9339 9340 if (NumLPads < 256) { 9341 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 9342 .addReg(NewVReg1) 9343 .addImm(NumLPads) 9344 .add(predOps(ARMCC::AL)); 9345 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 9346 unsigned VReg1 = MRI->createVirtualRegister(TRC); 9347 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 9348 .addImm(NumLPads & 0xFFFF) 9349 .add(predOps(ARMCC::AL)); 9350 9351 unsigned VReg2 = VReg1; 9352 if ((NumLPads & 0xFFFF0000) != 0) { 9353 VReg2 = MRI->createVirtualRegister(TRC); 9354 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 9355 .addReg(VReg1) 9356 .addImm(NumLPads >> 16) 9357 .add(predOps(ARMCC::AL)); 9358 } 9359 9360 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9361 .addReg(NewVReg1) 9362 .addReg(VReg2) 9363 .add(predOps(ARMCC::AL)); 9364 } else { 9365 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9366 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9367 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 9368 9369 // MachineConstantPool wants an explicit alignment. 9370 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9371 if (Align == 0) 9372 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9373 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9374 9375 unsigned VReg1 = MRI->createVirtualRegister(TRC); 9376 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 9377 .addReg(VReg1, RegState::Define) 9378 .addConstantPoolIndex(Idx) 9379 .addImm(0) 9380 .add(predOps(ARMCC::AL)); 9381 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 9382 .addReg(NewVReg1) 9383 .addReg(VReg1, RegState::Kill) 9384 .add(predOps(ARMCC::AL)); 9385 } 9386 9387 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 9388 .addMBB(TrapBB) 9389 .addImm(ARMCC::HI) 9390 .addReg(ARM::CPSR); 9391 9392 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 9393 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 9394 .addReg(NewVReg1) 9395 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 9396 .add(predOps(ARMCC::AL)) 9397 .add(condCodeOp()); 9398 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 9399 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 9400 .addJumpTableIndex(MJTI) 9401 .add(predOps(ARMCC::AL)); 9402 9403 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 9404 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 9405 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 9406 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 9407 .addReg(NewVReg3, RegState::Kill) 9408 .addReg(NewVReg4) 9409 .addImm(0) 9410 .addMemOperand(JTMMOLd) 9411 .add(predOps(ARMCC::AL)); 9412 9413 if (IsPositionIndependent) { 9414 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 9415 .addReg(NewVReg5, RegState::Kill) 9416 .addReg(NewVReg4) 9417 .addJumpTableIndex(MJTI); 9418 } else { 9419 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 9420 .addReg(NewVReg5, RegState::Kill) 9421 .addJumpTableIndex(MJTI); 9422 } 9423 } 9424 9425 // Add the jump table entries as successors to the MBB. 9426 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 9427 for (std::vector<MachineBasicBlock*>::iterator 9428 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 9429 MachineBasicBlock *CurMBB = *I; 9430 if (SeenMBBs.insert(CurMBB).second) 9431 DispContBB->addSuccessor(CurMBB); 9432 } 9433 9434 // N.B. the order the invoke BBs are processed in doesn't matter here. 9435 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 9436 SmallVector<MachineBasicBlock*, 64> MBBLPads; 9437 for (MachineBasicBlock *BB : InvokeBBs) { 9438 9439 // Remove the landing pad successor from the invoke block and replace it 9440 // with the new dispatch block. 9441 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 9442 BB->succ_end()); 9443 while (!Successors.empty()) { 9444 MachineBasicBlock *SMBB = Successors.pop_back_val(); 9445 if (SMBB->isEHPad()) { 9446 BB->removeSuccessor(SMBB); 9447 MBBLPads.push_back(SMBB); 9448 } 9449 } 9450 9451 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 9452 BB->normalizeSuccProbs(); 9453 9454 // Find the invoke call and mark all of the callee-saved registers as 9455 // 'implicit defined' so that they're spilled. This prevents code from 9456 // moving instructions to before the EH block, where they will never be 9457 // executed. 9458 for (MachineBasicBlock::reverse_iterator 9459 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 9460 if (!II->isCall()) continue; 9461 9462 DenseMap<unsigned, bool> DefRegs; 9463 for (MachineInstr::mop_iterator 9464 OI = II->operands_begin(), OE = II->operands_end(); 9465 OI != OE; ++OI) { 9466 if (!OI->isReg()) continue; 9467 DefRegs[OI->getReg()] = true; 9468 } 9469 9470 MachineInstrBuilder MIB(*MF, &*II); 9471 9472 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 9473 unsigned Reg = SavedRegs[i]; 9474 if (Subtarget->isThumb2() && 9475 !ARM::tGPRRegClass.contains(Reg) && 9476 !ARM::hGPRRegClass.contains(Reg)) 9477 continue; 9478 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 9479 continue; 9480 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 9481 continue; 9482 if (!DefRegs[Reg]) 9483 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 9484 } 9485 9486 break; 9487 } 9488 } 9489 9490 // Mark all former landing pads as non-landing pads. The dispatch is the only 9491 // landing pad now. 9492 for (SmallVectorImpl<MachineBasicBlock*>::iterator 9493 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 9494 (*I)->setIsEHPad(false); 9495 9496 // The instruction is gone now. 9497 MI.eraseFromParent(); 9498 } 9499 9500 static 9501 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 9502 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 9503 E = MBB->succ_end(); I != E; ++I) 9504 if (*I != Succ) 9505 return *I; 9506 llvm_unreachable("Expecting a BB with two successors!"); 9507 } 9508 9509 /// Return the load opcode for a given load size. If load size >= 8, 9510 /// neon opcode will be returned. 9511 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 9512 if (LdSize >= 8) 9513 return LdSize == 16 ? ARM::VLD1q32wb_fixed 9514 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 9515 if (IsThumb1) 9516 return LdSize == 4 ? ARM::tLDRi 9517 : LdSize == 2 ? ARM::tLDRHi 9518 : LdSize == 1 ? ARM::tLDRBi : 0; 9519 if (IsThumb2) 9520 return LdSize == 4 ? ARM::t2LDR_POST 9521 : LdSize == 2 ? ARM::t2LDRH_POST 9522 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 9523 return LdSize == 4 ? ARM::LDR_POST_IMM 9524 : LdSize == 2 ? ARM::LDRH_POST 9525 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 9526 } 9527 9528 /// Return the store opcode for a given store size. If store size >= 8, 9529 /// neon opcode will be returned. 9530 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 9531 if (StSize >= 8) 9532 return StSize == 16 ? ARM::VST1q32wb_fixed 9533 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 9534 if (IsThumb1) 9535 return StSize == 4 ? ARM::tSTRi 9536 : StSize == 2 ? ARM::tSTRHi 9537 : StSize == 1 ? ARM::tSTRBi : 0; 9538 if (IsThumb2) 9539 return StSize == 4 ? ARM::t2STR_POST 9540 : StSize == 2 ? ARM::t2STRH_POST 9541 : StSize == 1 ? ARM::t2STRB_POST : 0; 9542 return StSize == 4 ? ARM::STR_POST_IMM 9543 : StSize == 2 ? ARM::STRH_POST 9544 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 9545 } 9546 9547 /// Emit a post-increment load operation with given size. The instructions 9548 /// will be added to BB at Pos. 9549 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9550 const TargetInstrInfo *TII, const DebugLoc &dl, 9551 unsigned LdSize, unsigned Data, unsigned AddrIn, 9552 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9553 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 9554 assert(LdOpc != 0 && "Should have a load opcode"); 9555 if (LdSize >= 8) { 9556 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9557 .addReg(AddrOut, RegState::Define) 9558 .addReg(AddrIn) 9559 .addImm(0) 9560 .add(predOps(ARMCC::AL)); 9561 } else if (IsThumb1) { 9562 // load + update AddrIn 9563 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9564 .addReg(AddrIn) 9565 .addImm(0) 9566 .add(predOps(ARMCC::AL)); 9567 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9568 .add(t1CondCodeOp()) 9569 .addReg(AddrIn) 9570 .addImm(LdSize) 9571 .add(predOps(ARMCC::AL)); 9572 } else if (IsThumb2) { 9573 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9574 .addReg(AddrOut, RegState::Define) 9575 .addReg(AddrIn) 9576 .addImm(LdSize) 9577 .add(predOps(ARMCC::AL)); 9578 } else { // arm 9579 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9580 .addReg(AddrOut, RegState::Define) 9581 .addReg(AddrIn) 9582 .addReg(0) 9583 .addImm(LdSize) 9584 .add(predOps(ARMCC::AL)); 9585 } 9586 } 9587 9588 /// Emit a post-increment store operation with given size. The instructions 9589 /// will be added to BB at Pos. 9590 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9591 const TargetInstrInfo *TII, const DebugLoc &dl, 9592 unsigned StSize, unsigned Data, unsigned AddrIn, 9593 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9594 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 9595 assert(StOpc != 0 && "Should have a store opcode"); 9596 if (StSize >= 8) { 9597 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9598 .addReg(AddrIn) 9599 .addImm(0) 9600 .addReg(Data) 9601 .add(predOps(ARMCC::AL)); 9602 } else if (IsThumb1) { 9603 // store + update AddrIn 9604 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 9605 .addReg(Data) 9606 .addReg(AddrIn) 9607 .addImm(0) 9608 .add(predOps(ARMCC::AL)); 9609 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9610 .add(t1CondCodeOp()) 9611 .addReg(AddrIn) 9612 .addImm(StSize) 9613 .add(predOps(ARMCC::AL)); 9614 } else if (IsThumb2) { 9615 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9616 .addReg(Data) 9617 .addReg(AddrIn) 9618 .addImm(StSize) 9619 .add(predOps(ARMCC::AL)); 9620 } else { // arm 9621 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9622 .addReg(Data) 9623 .addReg(AddrIn) 9624 .addReg(0) 9625 .addImm(StSize) 9626 .add(predOps(ARMCC::AL)); 9627 } 9628 } 9629 9630 MachineBasicBlock * 9631 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 9632 MachineBasicBlock *BB) const { 9633 // This pseudo instruction has 3 operands: dst, src, size 9634 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 9635 // Otherwise, we will generate unrolled scalar copies. 9636 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9637 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9638 MachineFunction::iterator It = ++BB->getIterator(); 9639 9640 unsigned dest = MI.getOperand(0).getReg(); 9641 unsigned src = MI.getOperand(1).getReg(); 9642 unsigned SizeVal = MI.getOperand(2).getImm(); 9643 unsigned Align = MI.getOperand(3).getImm(); 9644 DebugLoc dl = MI.getDebugLoc(); 9645 9646 MachineFunction *MF = BB->getParent(); 9647 MachineRegisterInfo &MRI = MF->getRegInfo(); 9648 unsigned UnitSize = 0; 9649 const TargetRegisterClass *TRC = nullptr; 9650 const TargetRegisterClass *VecTRC = nullptr; 9651 9652 bool IsThumb1 = Subtarget->isThumb1Only(); 9653 bool IsThumb2 = Subtarget->isThumb2(); 9654 bool IsThumb = Subtarget->isThumb(); 9655 9656 if (Align & 1) { 9657 UnitSize = 1; 9658 } else if (Align & 2) { 9659 UnitSize = 2; 9660 } else { 9661 // Check whether we can use NEON instructions. 9662 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 9663 Subtarget->hasNEON()) { 9664 if ((Align % 16 == 0) && SizeVal >= 16) 9665 UnitSize = 16; 9666 else if ((Align % 8 == 0) && SizeVal >= 8) 9667 UnitSize = 8; 9668 } 9669 // Can't use NEON instructions. 9670 if (UnitSize == 0) 9671 UnitSize = 4; 9672 } 9673 9674 // Select the correct opcode and register class for unit size load/store 9675 bool IsNeon = UnitSize >= 8; 9676 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 9677 if (IsNeon) 9678 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 9679 : UnitSize == 8 ? &ARM::DPRRegClass 9680 : nullptr; 9681 9682 unsigned BytesLeft = SizeVal % UnitSize; 9683 unsigned LoopSize = SizeVal - BytesLeft; 9684 9685 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 9686 // Use LDR and STR to copy. 9687 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 9688 // [destOut] = STR_POST(scratch, destIn, UnitSize) 9689 unsigned srcIn = src; 9690 unsigned destIn = dest; 9691 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 9692 unsigned srcOut = MRI.createVirtualRegister(TRC); 9693 unsigned destOut = MRI.createVirtualRegister(TRC); 9694 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9695 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 9696 IsThumb1, IsThumb2); 9697 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 9698 IsThumb1, IsThumb2); 9699 srcIn = srcOut; 9700 destIn = destOut; 9701 } 9702 9703 // Handle the leftover bytes with LDRB and STRB. 9704 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 9705 // [destOut] = STRB_POST(scratch, destIn, 1) 9706 for (unsigned i = 0; i < BytesLeft; i++) { 9707 unsigned srcOut = MRI.createVirtualRegister(TRC); 9708 unsigned destOut = MRI.createVirtualRegister(TRC); 9709 unsigned scratch = MRI.createVirtualRegister(TRC); 9710 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 9711 IsThumb1, IsThumb2); 9712 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 9713 IsThumb1, IsThumb2); 9714 srcIn = srcOut; 9715 destIn = destOut; 9716 } 9717 MI.eraseFromParent(); // The instruction is gone now. 9718 return BB; 9719 } 9720 9721 // Expand the pseudo op to a loop. 9722 // thisMBB: 9723 // ... 9724 // movw varEnd, # --> with thumb2 9725 // movt varEnd, # 9726 // ldrcp varEnd, idx --> without thumb2 9727 // fallthrough --> loopMBB 9728 // loopMBB: 9729 // PHI varPhi, varEnd, varLoop 9730 // PHI srcPhi, src, srcLoop 9731 // PHI destPhi, dst, destLoop 9732 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9733 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 9734 // subs varLoop, varPhi, #UnitSize 9735 // bne loopMBB 9736 // fallthrough --> exitMBB 9737 // exitMBB: 9738 // epilogue to handle left-over bytes 9739 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9740 // [destOut] = STRB_POST(scratch, destLoop, 1) 9741 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9742 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9743 MF->insert(It, loopMBB); 9744 MF->insert(It, exitMBB); 9745 9746 // Transfer the remainder of BB and its successor edges to exitMBB. 9747 exitMBB->splice(exitMBB->begin(), BB, 9748 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9749 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9750 9751 // Load an immediate to varEnd. 9752 unsigned varEnd = MRI.createVirtualRegister(TRC); 9753 if (Subtarget->useMovt()) { 9754 unsigned Vtmp = varEnd; 9755 if ((LoopSize & 0xFFFF0000) != 0) 9756 Vtmp = MRI.createVirtualRegister(TRC); 9757 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 9758 .addImm(LoopSize & 0xFFFF) 9759 .add(predOps(ARMCC::AL)); 9760 9761 if ((LoopSize & 0xFFFF0000) != 0) 9762 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9763 .addReg(Vtmp) 9764 .addImm(LoopSize >> 16) 9765 .add(predOps(ARMCC::AL)); 9766 } else { 9767 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9768 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9769 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9770 9771 // MachineConstantPool wants an explicit alignment. 9772 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9773 if (Align == 0) 9774 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9775 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9776 MachineMemOperand *CPMMO = 9777 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9778 MachineMemOperand::MOLoad, 4, 4); 9779 9780 if (IsThumb) 9781 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9782 .addReg(varEnd, RegState::Define) 9783 .addConstantPoolIndex(Idx) 9784 .add(predOps(ARMCC::AL)) 9785 .addMemOperand(CPMMO); 9786 else 9787 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9788 .addReg(varEnd, RegState::Define) 9789 .addConstantPoolIndex(Idx) 9790 .addImm(0) 9791 .add(predOps(ARMCC::AL)) 9792 .addMemOperand(CPMMO); 9793 } 9794 BB->addSuccessor(loopMBB); 9795 9796 // Generate the loop body: 9797 // varPhi = PHI(varLoop, varEnd) 9798 // srcPhi = PHI(srcLoop, src) 9799 // destPhi = PHI(destLoop, dst) 9800 MachineBasicBlock *entryBB = BB; 9801 BB = loopMBB; 9802 unsigned varLoop = MRI.createVirtualRegister(TRC); 9803 unsigned varPhi = MRI.createVirtualRegister(TRC); 9804 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9805 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9806 unsigned destLoop = MRI.createVirtualRegister(TRC); 9807 unsigned destPhi = MRI.createVirtualRegister(TRC); 9808 9809 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9810 .addReg(varLoop).addMBB(loopMBB) 9811 .addReg(varEnd).addMBB(entryBB); 9812 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9813 .addReg(srcLoop).addMBB(loopMBB) 9814 .addReg(src).addMBB(entryBB); 9815 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9816 .addReg(destLoop).addMBB(loopMBB) 9817 .addReg(dest).addMBB(entryBB); 9818 9819 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9820 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9821 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9822 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9823 IsThumb1, IsThumb2); 9824 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9825 IsThumb1, IsThumb2); 9826 9827 // Decrement loop variable by UnitSize. 9828 if (IsThumb1) { 9829 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9830 .add(t1CondCodeOp()) 9831 .addReg(varPhi) 9832 .addImm(UnitSize) 9833 .add(predOps(ARMCC::AL)); 9834 } else { 9835 MachineInstrBuilder MIB = 9836 BuildMI(*BB, BB->end(), dl, 9837 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9838 MIB.addReg(varPhi) 9839 .addImm(UnitSize) 9840 .add(predOps(ARMCC::AL)) 9841 .add(condCodeOp()); 9842 MIB->getOperand(5).setReg(ARM::CPSR); 9843 MIB->getOperand(5).setIsDef(true); 9844 } 9845 BuildMI(*BB, BB->end(), dl, 9846 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9847 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9848 9849 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9850 BB->addSuccessor(loopMBB); 9851 BB->addSuccessor(exitMBB); 9852 9853 // Add epilogue to handle BytesLeft. 9854 BB = exitMBB; 9855 auto StartOfExit = exitMBB->begin(); 9856 9857 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9858 // [destOut] = STRB_POST(scratch, destLoop, 1) 9859 unsigned srcIn = srcLoop; 9860 unsigned destIn = destLoop; 9861 for (unsigned i = 0; i < BytesLeft; i++) { 9862 unsigned srcOut = MRI.createVirtualRegister(TRC); 9863 unsigned destOut = MRI.createVirtualRegister(TRC); 9864 unsigned scratch = MRI.createVirtualRegister(TRC); 9865 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9866 IsThumb1, IsThumb2); 9867 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9868 IsThumb1, IsThumb2); 9869 srcIn = srcOut; 9870 destIn = destOut; 9871 } 9872 9873 MI.eraseFromParent(); // The instruction is gone now. 9874 return BB; 9875 } 9876 9877 MachineBasicBlock * 9878 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9879 MachineBasicBlock *MBB) const { 9880 const TargetMachine &TM = getTargetMachine(); 9881 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9882 DebugLoc DL = MI.getDebugLoc(); 9883 9884 assert(Subtarget->isTargetWindows() && 9885 "__chkstk is only supported on Windows"); 9886 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9887 9888 // __chkstk takes the number of words to allocate on the stack in R4, and 9889 // returns the stack adjustment in number of bytes in R4. This will not 9890 // clober any other registers (other than the obvious lr). 9891 // 9892 // Although, technically, IP should be considered a register which may be 9893 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9894 // thumb-2 environment, so there is no interworking required. As a result, we 9895 // do not expect a veneer to be emitted by the linker, clobbering IP. 9896 // 9897 // Each module receives its own copy of __chkstk, so no import thunk is 9898 // required, again, ensuring that IP is not clobbered. 9899 // 9900 // Finally, although some linkers may theoretically provide a trampoline for 9901 // out of range calls (which is quite common due to a 32M range limitation of 9902 // branches for Thumb), we can generate the long-call version via 9903 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9904 // IP. 9905 9906 switch (TM.getCodeModel()) { 9907 case CodeModel::Tiny: 9908 llvm_unreachable("Tiny code model not available on ARM."); 9909 case CodeModel::Small: 9910 case CodeModel::Medium: 9911 case CodeModel::Kernel: 9912 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9913 .add(predOps(ARMCC::AL)) 9914 .addExternalSymbol("__chkstk") 9915 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9916 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9917 .addReg(ARM::R12, 9918 RegState::Implicit | RegState::Define | RegState::Dead) 9919 .addReg(ARM::CPSR, 9920 RegState::Implicit | RegState::Define | RegState::Dead); 9921 break; 9922 case CodeModel::Large: { 9923 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9924 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9925 9926 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9927 .addExternalSymbol("__chkstk"); 9928 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9929 .add(predOps(ARMCC::AL)) 9930 .addReg(Reg, RegState::Kill) 9931 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9932 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9933 .addReg(ARM::R12, 9934 RegState::Implicit | RegState::Define | RegState::Dead) 9935 .addReg(ARM::CPSR, 9936 RegState::Implicit | RegState::Define | RegState::Dead); 9937 break; 9938 } 9939 } 9940 9941 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9942 .addReg(ARM::SP, RegState::Kill) 9943 .addReg(ARM::R4, RegState::Kill) 9944 .setMIFlags(MachineInstr::FrameSetup) 9945 .add(predOps(ARMCC::AL)) 9946 .add(condCodeOp()); 9947 9948 MI.eraseFromParent(); 9949 return MBB; 9950 } 9951 9952 MachineBasicBlock * 9953 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9954 MachineBasicBlock *MBB) const { 9955 DebugLoc DL = MI.getDebugLoc(); 9956 MachineFunction *MF = MBB->getParent(); 9957 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9958 9959 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9960 MF->insert(++MBB->getIterator(), ContBB); 9961 ContBB->splice(ContBB->begin(), MBB, 9962 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9963 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9964 MBB->addSuccessor(ContBB); 9965 9966 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9967 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9968 MF->push_back(TrapBB); 9969 MBB->addSuccessor(TrapBB); 9970 9971 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9972 .addReg(MI.getOperand(0).getReg()) 9973 .addImm(0) 9974 .add(predOps(ARMCC::AL)); 9975 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9976 .addMBB(TrapBB) 9977 .addImm(ARMCC::EQ) 9978 .addReg(ARM::CPSR); 9979 9980 MI.eraseFromParent(); 9981 return ContBB; 9982 } 9983 9984 // The CPSR operand of SelectItr might be missing a kill marker 9985 // because there were multiple uses of CPSR, and ISel didn't know 9986 // which to mark. Figure out whether SelectItr should have had a 9987 // kill marker, and set it if it should. Returns the correct kill 9988 // marker value. 9989 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 9990 MachineBasicBlock* BB, 9991 const TargetRegisterInfo* TRI) { 9992 // Scan forward through BB for a use/def of CPSR. 9993 MachineBasicBlock::iterator miI(std::next(SelectItr)); 9994 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 9995 const MachineInstr& mi = *miI; 9996 if (mi.readsRegister(ARM::CPSR)) 9997 return false; 9998 if (mi.definesRegister(ARM::CPSR)) 9999 break; // Should have kill-flag - update below. 10000 } 10001 10002 // If we hit the end of the block, check whether CPSR is live into a 10003 // successor. 10004 if (miI == BB->end()) { 10005 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 10006 sEnd = BB->succ_end(); 10007 sItr != sEnd; ++sItr) { 10008 MachineBasicBlock* succ = *sItr; 10009 if (succ->isLiveIn(ARM::CPSR)) 10010 return false; 10011 } 10012 } 10013 10014 // We found a def, or hit the end of the basic block and CPSR wasn't live 10015 // out. SelectMI should have a kill flag on CPSR. 10016 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 10017 return true; 10018 } 10019 10020 MachineBasicBlock * 10021 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10022 MachineBasicBlock *BB) const { 10023 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10024 DebugLoc dl = MI.getDebugLoc(); 10025 bool isThumb2 = Subtarget->isThumb2(); 10026 switch (MI.getOpcode()) { 10027 default: { 10028 MI.print(errs()); 10029 llvm_unreachable("Unexpected instr type to insert"); 10030 } 10031 10032 // Thumb1 post-indexed loads are really just single-register LDMs. 10033 case ARM::tLDR_postidx: { 10034 MachineOperand Def(MI.getOperand(1)); 10035 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 10036 .add(Def) // Rn_wb 10037 .add(MI.getOperand(2)) // Rn 10038 .add(MI.getOperand(3)) // PredImm 10039 .add(MI.getOperand(4)) // PredReg 10040 .add(MI.getOperand(0)) // Rt 10041 .cloneMemRefs(MI); 10042 MI.eraseFromParent(); 10043 return BB; 10044 } 10045 10046 // The Thumb2 pre-indexed stores have the same MI operands, they just 10047 // define them differently in the .td files from the isel patterns, so 10048 // they need pseudos. 10049 case ARM::t2STR_preidx: 10050 MI.setDesc(TII->get(ARM::t2STR_PRE)); 10051 return BB; 10052 case ARM::t2STRB_preidx: 10053 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 10054 return BB; 10055 case ARM::t2STRH_preidx: 10056 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 10057 return BB; 10058 10059 case ARM::STRi_preidx: 10060 case ARM::STRBi_preidx: { 10061 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 10062 : ARM::STRB_PRE_IMM; 10063 // Decode the offset. 10064 unsigned Offset = MI.getOperand(4).getImm(); 10065 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 10066 Offset = ARM_AM::getAM2Offset(Offset); 10067 if (isSub) 10068 Offset = -Offset; 10069 10070 MachineMemOperand *MMO = *MI.memoperands_begin(); 10071 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 10072 .add(MI.getOperand(0)) // Rn_wb 10073 .add(MI.getOperand(1)) // Rt 10074 .add(MI.getOperand(2)) // Rn 10075 .addImm(Offset) // offset (skip GPR==zero_reg) 10076 .add(MI.getOperand(5)) // pred 10077 .add(MI.getOperand(6)) 10078 .addMemOperand(MMO); 10079 MI.eraseFromParent(); 10080 return BB; 10081 } 10082 case ARM::STRr_preidx: 10083 case ARM::STRBr_preidx: 10084 case ARM::STRH_preidx: { 10085 unsigned NewOpc; 10086 switch (MI.getOpcode()) { 10087 default: llvm_unreachable("unexpected opcode!"); 10088 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 10089 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 10090 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 10091 } 10092 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 10093 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 10094 MIB.add(MI.getOperand(i)); 10095 MI.eraseFromParent(); 10096 return BB; 10097 } 10098 10099 case ARM::tMOVCCr_pseudo: { 10100 // To "insert" a SELECT_CC instruction, we actually have to insert the 10101 // diamond control-flow pattern. The incoming instruction knows the 10102 // destination vreg to set, the condition code register to branch on, the 10103 // true/false values to select between, and a branch opcode to use. 10104 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10105 MachineFunction::iterator It = ++BB->getIterator(); 10106 10107 // thisMBB: 10108 // ... 10109 // TrueVal = ... 10110 // cmpTY ccX, r1, r2 10111 // bCC copy1MBB 10112 // fallthrough --> copy0MBB 10113 MachineBasicBlock *thisMBB = BB; 10114 MachineFunction *F = BB->getParent(); 10115 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10116 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10117 F->insert(It, copy0MBB); 10118 F->insert(It, sinkMBB); 10119 10120 // Check whether CPSR is live past the tMOVCCr_pseudo. 10121 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10122 if (!MI.killsRegister(ARM::CPSR) && 10123 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 10124 copy0MBB->addLiveIn(ARM::CPSR); 10125 sinkMBB->addLiveIn(ARM::CPSR); 10126 } 10127 10128 // Transfer the remainder of BB and its successor edges to sinkMBB. 10129 sinkMBB->splice(sinkMBB->begin(), BB, 10130 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10131 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10132 10133 BB->addSuccessor(copy0MBB); 10134 BB->addSuccessor(sinkMBB); 10135 10136 BuildMI(BB, dl, TII->get(ARM::tBcc)) 10137 .addMBB(sinkMBB) 10138 .addImm(MI.getOperand(3).getImm()) 10139 .addReg(MI.getOperand(4).getReg()); 10140 10141 // copy0MBB: 10142 // %FalseValue = ... 10143 // # fallthrough to sinkMBB 10144 BB = copy0MBB; 10145 10146 // Update machine-CFG edges 10147 BB->addSuccessor(sinkMBB); 10148 10149 // sinkMBB: 10150 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10151 // ... 10152 BB = sinkMBB; 10153 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 10154 .addReg(MI.getOperand(1).getReg()) 10155 .addMBB(copy0MBB) 10156 .addReg(MI.getOperand(2).getReg()) 10157 .addMBB(thisMBB); 10158 10159 MI.eraseFromParent(); // The pseudo instruction is gone now. 10160 return BB; 10161 } 10162 10163 case ARM::BCCi64: 10164 case ARM::BCCZi64: { 10165 // If there is an unconditional branch to the other successor, remove it. 10166 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10167 10168 // Compare both parts that make up the double comparison separately for 10169 // equality. 10170 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 10171 10172 unsigned LHS1 = MI.getOperand(1).getReg(); 10173 unsigned LHS2 = MI.getOperand(2).getReg(); 10174 if (RHSisZero) { 10175 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10176 .addReg(LHS1) 10177 .addImm(0) 10178 .add(predOps(ARMCC::AL)); 10179 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10180 .addReg(LHS2).addImm(0) 10181 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10182 } else { 10183 unsigned RHS1 = MI.getOperand(3).getReg(); 10184 unsigned RHS2 = MI.getOperand(4).getReg(); 10185 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10186 .addReg(LHS1) 10187 .addReg(RHS1) 10188 .add(predOps(ARMCC::AL)); 10189 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 10190 .addReg(LHS2).addReg(RHS2) 10191 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 10192 } 10193 10194 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 10195 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 10196 if (MI.getOperand(0).getImm() == ARMCC::NE) 10197 std::swap(destMBB, exitMBB); 10198 10199 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 10200 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 10201 if (isThumb2) 10202 BuildMI(BB, dl, TII->get(ARM::t2B)) 10203 .addMBB(exitMBB) 10204 .add(predOps(ARMCC::AL)); 10205 else 10206 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 10207 10208 MI.eraseFromParent(); // The pseudo instruction is gone now. 10209 return BB; 10210 } 10211 10212 case ARM::Int_eh_sjlj_setjmp: 10213 case ARM::Int_eh_sjlj_setjmp_nofp: 10214 case ARM::tInt_eh_sjlj_setjmp: 10215 case ARM::t2Int_eh_sjlj_setjmp: 10216 case ARM::t2Int_eh_sjlj_setjmp_nofp: 10217 return BB; 10218 10219 case ARM::Int_eh_sjlj_setup_dispatch: 10220 EmitSjLjDispatchBlock(MI, BB); 10221 return BB; 10222 10223 case ARM::ABS: 10224 case ARM::t2ABS: { 10225 // To insert an ABS instruction, we have to insert the 10226 // diamond control-flow pattern. The incoming instruction knows the 10227 // source vreg to test against 0, the destination vreg to set, 10228 // the condition code register to branch on, the 10229 // true/false values to select between, and a branch opcode to use. 10230 // It transforms 10231 // V1 = ABS V0 10232 // into 10233 // V2 = MOVS V0 10234 // BCC (branch to SinkBB if V0 >= 0) 10235 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 10236 // SinkBB: V1 = PHI(V2, V3) 10237 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10238 MachineFunction::iterator BBI = ++BB->getIterator(); 10239 MachineFunction *Fn = BB->getParent(); 10240 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10241 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 10242 Fn->insert(BBI, RSBBB); 10243 Fn->insert(BBI, SinkBB); 10244 10245 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 10246 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 10247 bool ABSSrcKIll = MI.getOperand(1).isKill(); 10248 bool isThumb2 = Subtarget->isThumb2(); 10249 MachineRegisterInfo &MRI = Fn->getRegInfo(); 10250 // In Thumb mode S must not be specified if source register is the SP or 10251 // PC and if destination register is the SP, so restrict register class 10252 unsigned NewRsbDstReg = 10253 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 10254 10255 // Transfer the remainder of BB and its successor edges to sinkMBB. 10256 SinkBB->splice(SinkBB->begin(), BB, 10257 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10258 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 10259 10260 BB->addSuccessor(RSBBB); 10261 BB->addSuccessor(SinkBB); 10262 10263 // fall through to SinkMBB 10264 RSBBB->addSuccessor(SinkBB); 10265 10266 // insert a cmp at the end of BB 10267 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 10268 .addReg(ABSSrcReg) 10269 .addImm(0) 10270 .add(predOps(ARMCC::AL)); 10271 10272 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 10273 BuildMI(BB, dl, 10274 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 10275 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 10276 10277 // insert rsbri in RSBBB 10278 // Note: BCC and rsbri will be converted into predicated rsbmi 10279 // by if-conversion pass 10280 BuildMI(*RSBBB, RSBBB->begin(), dl, 10281 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 10282 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 10283 .addImm(0) 10284 .add(predOps(ARMCC::AL)) 10285 .add(condCodeOp()); 10286 10287 // insert PHI in SinkBB, 10288 // reuse ABSDstReg to not change uses of ABS instruction 10289 BuildMI(*SinkBB, SinkBB->begin(), dl, 10290 TII->get(ARM::PHI), ABSDstReg) 10291 .addReg(NewRsbDstReg).addMBB(RSBBB) 10292 .addReg(ABSSrcReg).addMBB(BB); 10293 10294 // remove ABS instruction 10295 MI.eraseFromParent(); 10296 10297 // return last added BB 10298 return SinkBB; 10299 } 10300 case ARM::COPY_STRUCT_BYVAL_I32: 10301 ++NumLoopByVals; 10302 return EmitStructByval(MI, BB); 10303 case ARM::WIN__CHKSTK: 10304 return EmitLowered__chkstk(MI, BB); 10305 case ARM::WIN__DBZCHK: 10306 return EmitLowered__dbzchk(MI, BB); 10307 } 10308 } 10309 10310 /// Attaches vregs to MEMCPY that it will use as scratch registers 10311 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 10312 /// instead of as a custom inserter because we need the use list from the SDNode. 10313 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 10314 MachineInstr &MI, const SDNode *Node) { 10315 bool isThumb1 = Subtarget->isThumb1Only(); 10316 10317 DebugLoc DL = MI.getDebugLoc(); 10318 MachineFunction *MF = MI.getParent()->getParent(); 10319 MachineRegisterInfo &MRI = MF->getRegInfo(); 10320 MachineInstrBuilder MIB(*MF, MI); 10321 10322 // If the new dst/src is unused mark it as dead. 10323 if (!Node->hasAnyUseOfValue(0)) { 10324 MI.getOperand(0).setIsDead(true); 10325 } 10326 if (!Node->hasAnyUseOfValue(1)) { 10327 MI.getOperand(1).setIsDead(true); 10328 } 10329 10330 // The MEMCPY both defines and kills the scratch registers. 10331 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 10332 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 10333 : &ARM::GPRRegClass); 10334 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 10335 } 10336 } 10337 10338 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10339 SDNode *Node) const { 10340 if (MI.getOpcode() == ARM::MEMCPY) { 10341 attachMEMCPYScratchRegs(Subtarget, MI, Node); 10342 return; 10343 } 10344 10345 const MCInstrDesc *MCID = &MI.getDesc(); 10346 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 10347 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 10348 // operand is still set to noreg. If needed, set the optional operand's 10349 // register to CPSR, and remove the redundant implicit def. 10350 // 10351 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 10352 10353 // Rename pseudo opcodes. 10354 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 10355 unsigned ccOutIdx; 10356 if (NewOpc) { 10357 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 10358 MCID = &TII->get(NewOpc); 10359 10360 assert(MCID->getNumOperands() == 10361 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 10362 && "converted opcode should be the same except for cc_out" 10363 " (and, on Thumb1, pred)"); 10364 10365 MI.setDesc(*MCID); 10366 10367 // Add the optional cc_out operand 10368 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 10369 10370 // On Thumb1, move all input operands to the end, then add the predicate 10371 if (Subtarget->isThumb1Only()) { 10372 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 10373 MI.addOperand(MI.getOperand(1)); 10374 MI.RemoveOperand(1); 10375 } 10376 10377 // Restore the ties 10378 for (unsigned i = MI.getNumOperands(); i--;) { 10379 const MachineOperand& op = MI.getOperand(i); 10380 if (op.isReg() && op.isUse()) { 10381 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 10382 if (DefIdx != -1) 10383 MI.tieOperands(DefIdx, i); 10384 } 10385 } 10386 10387 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 10388 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 10389 ccOutIdx = 1; 10390 } else 10391 ccOutIdx = MCID->getNumOperands() - 1; 10392 } else 10393 ccOutIdx = MCID->getNumOperands() - 1; 10394 10395 // Any ARM instruction that sets the 's' bit should specify an optional 10396 // "cc_out" operand in the last operand position. 10397 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 10398 assert(!NewOpc && "Optional cc_out operand required"); 10399 return; 10400 } 10401 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 10402 // since we already have an optional CPSR def. 10403 bool definesCPSR = false; 10404 bool deadCPSR = false; 10405 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 10406 ++i) { 10407 const MachineOperand &MO = MI.getOperand(i); 10408 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 10409 definesCPSR = true; 10410 if (MO.isDead()) 10411 deadCPSR = true; 10412 MI.RemoveOperand(i); 10413 break; 10414 } 10415 } 10416 if (!definesCPSR) { 10417 assert(!NewOpc && "Optional cc_out operand required"); 10418 return; 10419 } 10420 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 10421 if (deadCPSR) { 10422 assert(!MI.getOperand(ccOutIdx).getReg() && 10423 "expect uninitialized optional cc_out operand"); 10424 // Thumb1 instructions must have the S bit even if the CPSR is dead. 10425 if (!Subtarget->isThumb1Only()) 10426 return; 10427 } 10428 10429 // If this instruction was defined with an optional CPSR def and its dag node 10430 // had a live implicit CPSR def, then activate the optional CPSR def. 10431 MachineOperand &MO = MI.getOperand(ccOutIdx); 10432 MO.setReg(ARM::CPSR); 10433 MO.setIsDef(true); 10434 } 10435 10436 //===----------------------------------------------------------------------===// 10437 // ARM Optimization Hooks 10438 //===----------------------------------------------------------------------===// 10439 10440 // Helper function that checks if N is a null or all ones constant. 10441 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 10442 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 10443 } 10444 10445 // Return true if N is conditionally 0 or all ones. 10446 // Detects these expressions where cc is an i1 value: 10447 // 10448 // (select cc 0, y) [AllOnes=0] 10449 // (select cc y, 0) [AllOnes=0] 10450 // (zext cc) [AllOnes=0] 10451 // (sext cc) [AllOnes=0/1] 10452 // (select cc -1, y) [AllOnes=1] 10453 // (select cc y, -1) [AllOnes=1] 10454 // 10455 // Invert is set when N is the null/all ones constant when CC is false. 10456 // OtherOp is set to the alternative value of N. 10457 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 10458 SDValue &CC, bool &Invert, 10459 SDValue &OtherOp, 10460 SelectionDAG &DAG) { 10461 switch (N->getOpcode()) { 10462 default: return false; 10463 case ISD::SELECT: { 10464 CC = N->getOperand(0); 10465 SDValue N1 = N->getOperand(1); 10466 SDValue N2 = N->getOperand(2); 10467 if (isZeroOrAllOnes(N1, AllOnes)) { 10468 Invert = false; 10469 OtherOp = N2; 10470 return true; 10471 } 10472 if (isZeroOrAllOnes(N2, AllOnes)) { 10473 Invert = true; 10474 OtherOp = N1; 10475 return true; 10476 } 10477 return false; 10478 } 10479 case ISD::ZERO_EXTEND: 10480 // (zext cc) can never be the all ones value. 10481 if (AllOnes) 10482 return false; 10483 LLVM_FALLTHROUGH; 10484 case ISD::SIGN_EXTEND: { 10485 SDLoc dl(N); 10486 EVT VT = N->getValueType(0); 10487 CC = N->getOperand(0); 10488 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 10489 return false; 10490 Invert = !AllOnes; 10491 if (AllOnes) 10492 // When looking for an AllOnes constant, N is an sext, and the 'other' 10493 // value is 0. 10494 OtherOp = DAG.getConstant(0, dl, VT); 10495 else if (N->getOpcode() == ISD::ZERO_EXTEND) 10496 // When looking for a 0 constant, N can be zext or sext. 10497 OtherOp = DAG.getConstant(1, dl, VT); 10498 else 10499 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 10500 VT); 10501 return true; 10502 } 10503 } 10504 } 10505 10506 // Combine a constant select operand into its use: 10507 // 10508 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10509 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10510 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 10511 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10512 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10513 // 10514 // The transform is rejected if the select doesn't have a constant operand that 10515 // is null, or all ones when AllOnes is set. 10516 // 10517 // Also recognize sext/zext from i1: 10518 // 10519 // (add (zext cc), x) -> (select cc (add x, 1), x) 10520 // (add (sext cc), x) -> (select cc (add x, -1), x) 10521 // 10522 // These transformations eventually create predicated instructions. 10523 // 10524 // @param N The node to transform. 10525 // @param Slct The N operand that is a select. 10526 // @param OtherOp The other N operand (x above). 10527 // @param DCI Context. 10528 // @param AllOnes Require the select constant to be all ones instead of null. 10529 // @returns The new node, or SDValue() on failure. 10530 static 10531 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 10532 TargetLowering::DAGCombinerInfo &DCI, 10533 bool AllOnes = false) { 10534 SelectionDAG &DAG = DCI.DAG; 10535 EVT VT = N->getValueType(0); 10536 SDValue NonConstantVal; 10537 SDValue CCOp; 10538 bool SwapSelectOps; 10539 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 10540 NonConstantVal, DAG)) 10541 return SDValue(); 10542 10543 // Slct is now know to be the desired identity constant when CC is true. 10544 SDValue TrueVal = OtherOp; 10545 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 10546 OtherOp, NonConstantVal); 10547 // Unless SwapSelectOps says CC should be false. 10548 if (SwapSelectOps) 10549 std::swap(TrueVal, FalseVal); 10550 10551 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 10552 CCOp, TrueVal, FalseVal); 10553 } 10554 10555 // Attempt combineSelectAndUse on each operand of a commutative operator N. 10556 static 10557 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 10558 TargetLowering::DAGCombinerInfo &DCI) { 10559 SDValue N0 = N->getOperand(0); 10560 SDValue N1 = N->getOperand(1); 10561 if (N0.getNode()->hasOneUse()) 10562 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 10563 return Result; 10564 if (N1.getNode()->hasOneUse()) 10565 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 10566 return Result; 10567 return SDValue(); 10568 } 10569 10570 static bool IsVUZPShuffleNode(SDNode *N) { 10571 // VUZP shuffle node. 10572 if (N->getOpcode() == ARMISD::VUZP) 10573 return true; 10574 10575 // "VUZP" on i32 is an alias for VTRN. 10576 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 10577 return true; 10578 10579 return false; 10580 } 10581 10582 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 10583 TargetLowering::DAGCombinerInfo &DCI, 10584 const ARMSubtarget *Subtarget) { 10585 // Look for ADD(VUZP.0, VUZP.1). 10586 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 10587 N0 == N1) 10588 return SDValue(); 10589 10590 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 10591 if (!N->getValueType(0).is64BitVector()) 10592 return SDValue(); 10593 10594 // Generate vpadd. 10595 SelectionDAG &DAG = DCI.DAG; 10596 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10597 SDLoc dl(N); 10598 SDNode *Unzip = N0.getNode(); 10599 EVT VT = N->getValueType(0); 10600 10601 SmallVector<SDValue, 8> Ops; 10602 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 10603 TLI.getPointerTy(DAG.getDataLayout()))); 10604 Ops.push_back(Unzip->getOperand(0)); 10605 Ops.push_back(Unzip->getOperand(1)); 10606 10607 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10608 } 10609 10610 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10611 TargetLowering::DAGCombinerInfo &DCI, 10612 const ARMSubtarget *Subtarget) { 10613 // Check for two extended operands. 10614 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 10615 N1.getOpcode() == ISD::SIGN_EXTEND) && 10616 !(N0.getOpcode() == ISD::ZERO_EXTEND && 10617 N1.getOpcode() == ISD::ZERO_EXTEND)) 10618 return SDValue(); 10619 10620 SDValue N00 = N0.getOperand(0); 10621 SDValue N10 = N1.getOperand(0); 10622 10623 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 10624 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 10625 N00 == N10) 10626 return SDValue(); 10627 10628 // We only recognize Q register paddl here; this can't be reached until 10629 // after type legalization. 10630 if (!N00.getValueType().is64BitVector() || 10631 !N0.getValueType().is128BitVector()) 10632 return SDValue(); 10633 10634 // Generate vpaddl. 10635 SelectionDAG &DAG = DCI.DAG; 10636 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10637 SDLoc dl(N); 10638 EVT VT = N->getValueType(0); 10639 10640 SmallVector<SDValue, 8> Ops; 10641 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 10642 unsigned Opcode; 10643 if (N0.getOpcode() == ISD::SIGN_EXTEND) 10644 Opcode = Intrinsic::arm_neon_vpaddls; 10645 else 10646 Opcode = Intrinsic::arm_neon_vpaddlu; 10647 Ops.push_back(DAG.getConstant(Opcode, dl, 10648 TLI.getPointerTy(DAG.getDataLayout()))); 10649 EVT ElemTy = N00.getValueType().getVectorElementType(); 10650 unsigned NumElts = VT.getVectorNumElements(); 10651 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 10652 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 10653 N00.getOperand(0), N00.getOperand(1)); 10654 Ops.push_back(Concat); 10655 10656 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10657 } 10658 10659 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 10660 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 10661 // much easier to match. 10662 static SDValue 10663 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10664 TargetLowering::DAGCombinerInfo &DCI, 10665 const ARMSubtarget *Subtarget) { 10666 // Only perform optimization if after legalize, and if NEON is available. We 10667 // also expected both operands to be BUILD_VECTORs. 10668 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 10669 || N0.getOpcode() != ISD::BUILD_VECTOR 10670 || N1.getOpcode() != ISD::BUILD_VECTOR) 10671 return SDValue(); 10672 10673 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 10674 EVT VT = N->getValueType(0); 10675 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 10676 return SDValue(); 10677 10678 // Check that the vector operands are of the right form. 10679 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 10680 // operands, where N is the size of the formed vector. 10681 // Each EXTRACT_VECTOR should have the same input vector and odd or even 10682 // index such that we have a pair wise add pattern. 10683 10684 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 10685 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10686 return SDValue(); 10687 SDValue Vec = N0->getOperand(0)->getOperand(0); 10688 SDNode *V = Vec.getNode(); 10689 unsigned nextIndex = 0; 10690 10691 // For each operands to the ADD which are BUILD_VECTORs, 10692 // check to see if each of their operands are an EXTRACT_VECTOR with 10693 // the same vector and appropriate index. 10694 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 10695 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 10696 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10697 10698 SDValue ExtVec0 = N0->getOperand(i); 10699 SDValue ExtVec1 = N1->getOperand(i); 10700 10701 // First operand is the vector, verify its the same. 10702 if (V != ExtVec0->getOperand(0).getNode() || 10703 V != ExtVec1->getOperand(0).getNode()) 10704 return SDValue(); 10705 10706 // Second is the constant, verify its correct. 10707 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 10708 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 10709 10710 // For the constant, we want to see all the even or all the odd. 10711 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 10712 || C1->getZExtValue() != nextIndex+1) 10713 return SDValue(); 10714 10715 // Increment index. 10716 nextIndex+=2; 10717 } else 10718 return SDValue(); 10719 } 10720 10721 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 10722 // we're using the entire input vector, otherwise there's a size/legality 10723 // mismatch somewhere. 10724 if (nextIndex != Vec.getValueType().getVectorNumElements() || 10725 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 10726 return SDValue(); 10727 10728 // Create VPADDL node. 10729 SelectionDAG &DAG = DCI.DAG; 10730 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10731 10732 SDLoc dl(N); 10733 10734 // Build operand list. 10735 SmallVector<SDValue, 8> Ops; 10736 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 10737 TLI.getPointerTy(DAG.getDataLayout()))); 10738 10739 // Input is the vector. 10740 Ops.push_back(Vec); 10741 10742 // Get widened type and narrowed type. 10743 MVT widenType; 10744 unsigned numElem = VT.getVectorNumElements(); 10745 10746 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 10747 switch (inputLaneType.getSimpleVT().SimpleTy) { 10748 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 10749 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 10750 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 10751 default: 10752 llvm_unreachable("Invalid vector element type for padd optimization."); 10753 } 10754 10755 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 10756 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 10757 return DAG.getNode(ExtOp, dl, VT, tmp); 10758 } 10759 10760 static SDValue findMUL_LOHI(SDValue V) { 10761 if (V->getOpcode() == ISD::UMUL_LOHI || 10762 V->getOpcode() == ISD::SMUL_LOHI) 10763 return V; 10764 return SDValue(); 10765 } 10766 10767 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 10768 TargetLowering::DAGCombinerInfo &DCI, 10769 const ARMSubtarget *Subtarget) { 10770 if (Subtarget->isThumb()) { 10771 if (!Subtarget->hasDSP()) 10772 return SDValue(); 10773 } else if (!Subtarget->hasV5TEOps()) 10774 return SDValue(); 10775 10776 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 10777 // accumulates the product into a 64-bit value. The 16-bit values will 10778 // be sign extended somehow or SRA'd into 32-bit values 10779 // (addc (adde (mul 16bit, 16bit), lo), hi) 10780 SDValue Mul = AddcNode->getOperand(0); 10781 SDValue Lo = AddcNode->getOperand(1); 10782 if (Mul.getOpcode() != ISD::MUL) { 10783 Lo = AddcNode->getOperand(0); 10784 Mul = AddcNode->getOperand(1); 10785 if (Mul.getOpcode() != ISD::MUL) 10786 return SDValue(); 10787 } 10788 10789 SDValue SRA = AddeNode->getOperand(0); 10790 SDValue Hi = AddeNode->getOperand(1); 10791 if (SRA.getOpcode() != ISD::SRA) { 10792 SRA = AddeNode->getOperand(1); 10793 Hi = AddeNode->getOperand(0); 10794 if (SRA.getOpcode() != ISD::SRA) 10795 return SDValue(); 10796 } 10797 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10798 if (Const->getZExtValue() != 31) 10799 return SDValue(); 10800 } else 10801 return SDValue(); 10802 10803 if (SRA.getOperand(0) != Mul) 10804 return SDValue(); 10805 10806 SelectionDAG &DAG = DCI.DAG; 10807 SDLoc dl(AddcNode); 10808 unsigned Opcode = 0; 10809 SDValue Op0; 10810 SDValue Op1; 10811 10812 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10813 Opcode = ARMISD::SMLALBB; 10814 Op0 = Mul.getOperand(0); 10815 Op1 = Mul.getOperand(1); 10816 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10817 Opcode = ARMISD::SMLALBT; 10818 Op0 = Mul.getOperand(0); 10819 Op1 = Mul.getOperand(1).getOperand(0); 10820 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10821 Opcode = ARMISD::SMLALTB; 10822 Op0 = Mul.getOperand(0).getOperand(0); 10823 Op1 = Mul.getOperand(1); 10824 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10825 Opcode = ARMISD::SMLALTT; 10826 Op0 = Mul->getOperand(0).getOperand(0); 10827 Op1 = Mul->getOperand(1).getOperand(0); 10828 } 10829 10830 if (!Op0 || !Op1) 10831 return SDValue(); 10832 10833 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10834 Op0, Op1, Lo, Hi); 10835 // Replace the ADDs' nodes uses by the MLA node's values. 10836 SDValue HiMLALResult(SMLAL.getNode(), 1); 10837 SDValue LoMLALResult(SMLAL.getNode(), 0); 10838 10839 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10840 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10841 10842 // Return original node to notify the driver to stop replacing. 10843 SDValue resNode(AddcNode, 0); 10844 return resNode; 10845 } 10846 10847 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10848 TargetLowering::DAGCombinerInfo &DCI, 10849 const ARMSubtarget *Subtarget) { 10850 // Look for multiply add opportunities. 10851 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10852 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10853 // a glue link from the first add to the second add. 10854 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10855 // a S/UMLAL instruction. 10856 // UMUL_LOHI 10857 // / :lo \ :hi 10858 // V \ [no multiline comment] 10859 // loAdd -> ADDC | 10860 // \ :carry / 10861 // V V 10862 // ADDE <- hiAdd 10863 // 10864 // In the special case where only the higher part of a signed result is used 10865 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10866 // a constant with the exact value of 0x80000000, we recognize we are dealing 10867 // with a "rounded multiply and add" (or subtract) and transform it into 10868 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10869 10870 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10871 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10872 "Expect an ADDE or SUBE"); 10873 10874 assert(AddeSubeNode->getNumOperands() == 3 && 10875 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10876 "ADDE node has the wrong inputs"); 10877 10878 // Check that we are chained to the right ADDC or SUBC node. 10879 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10880 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10881 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10882 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10883 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10884 return SDValue(); 10885 10886 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10887 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10888 10889 // Check if the two operands are from the same mul_lohi node. 10890 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10891 return SDValue(); 10892 10893 assert(AddcSubcNode->getNumValues() == 2 && 10894 AddcSubcNode->getValueType(0) == MVT::i32 && 10895 "Expect ADDC with two result values. First: i32"); 10896 10897 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10898 // maybe a SMLAL which multiplies two 16-bit values. 10899 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10900 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10901 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10902 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10903 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10904 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10905 10906 // Check for the triangle shape. 10907 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10908 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10909 10910 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10911 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10912 return SDValue(); 10913 10914 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10915 bool IsLeftOperandMUL = false; 10916 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10917 if (MULOp == SDValue()) 10918 MULOp = findMUL_LOHI(AddeSubeOp1); 10919 else 10920 IsLeftOperandMUL = true; 10921 if (MULOp == SDValue()) 10922 return SDValue(); 10923 10924 // Figure out the right opcode. 10925 unsigned Opc = MULOp->getOpcode(); 10926 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10927 10928 // Figure out the high and low input values to the MLAL node. 10929 SDValue *HiAddSub = nullptr; 10930 SDValue *LoMul = nullptr; 10931 SDValue *LowAddSub = nullptr; 10932 10933 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10934 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10935 return SDValue(); 10936 10937 if (IsLeftOperandMUL) 10938 HiAddSub = &AddeSubeOp1; 10939 else 10940 HiAddSub = &AddeSubeOp0; 10941 10942 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10943 // whose low result is fed to the ADDC/SUBC we are checking. 10944 10945 if (AddcSubcOp0 == MULOp.getValue(0)) { 10946 LoMul = &AddcSubcOp0; 10947 LowAddSub = &AddcSubcOp1; 10948 } 10949 if (AddcSubcOp1 == MULOp.getValue(0)) { 10950 LoMul = &AddcSubcOp1; 10951 LowAddSub = &AddcSubcOp0; 10952 } 10953 10954 if (!LoMul) 10955 return SDValue(); 10956 10957 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10958 // the replacement below will create a cycle. 10959 if (AddcSubcNode == HiAddSub->getNode() || 10960 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10961 return SDValue(); 10962 10963 // Create the merged node. 10964 SelectionDAG &DAG = DCI.DAG; 10965 10966 // Start building operand list. 10967 SmallVector<SDValue, 8> Ops; 10968 Ops.push_back(LoMul->getOperand(0)); 10969 Ops.push_back(LoMul->getOperand(1)); 10970 10971 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10972 // the case, we must be doing signed multiplication and only use the higher 10973 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10974 // addition or subtraction with the value of 0x800000. 10975 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10976 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10977 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10978 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10979 0x80000000) { 10980 Ops.push_back(*HiAddSub); 10981 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10982 FinalOpc = ARMISD::SMMLSR; 10983 } else { 10984 FinalOpc = ARMISD::SMMLAR; 10985 } 10986 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10987 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10988 10989 return SDValue(AddeSubeNode, 0); 10990 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10991 // SMMLS is generated during instruction selection and the rest of this 10992 // function can not handle the case where AddcSubcNode is a SUBC. 10993 return SDValue(); 10994 10995 // Finish building the operand list for {U/S}MLAL 10996 Ops.push_back(*LowAddSub); 10997 Ops.push_back(*HiAddSub); 10998 10999 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 11000 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11001 11002 // Replace the ADDs' nodes uses by the MLA node's values. 11003 SDValue HiMLALResult(MLALNode.getNode(), 1); 11004 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 11005 11006 SDValue LoMLALResult(MLALNode.getNode(), 0); 11007 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 11008 11009 // Return original node to notify the driver to stop replacing. 11010 return SDValue(AddeSubeNode, 0); 11011 } 11012 11013 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 11014 TargetLowering::DAGCombinerInfo &DCI, 11015 const ARMSubtarget *Subtarget) { 11016 // UMAAL is similar to UMLAL except that it adds two unsigned values. 11017 // While trying to combine for the other MLAL nodes, first search for the 11018 // chance to use UMAAL. Check if Addc uses a node which has already 11019 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 11020 // as the addend, and it's handled in PerformUMLALCombine. 11021 11022 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11023 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11024 11025 // Check that we have a glued ADDC node. 11026 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 11027 if (AddcNode->getOpcode() != ARMISD::ADDC) 11028 return SDValue(); 11029 11030 // Find the converted UMAAL or quit if it doesn't exist. 11031 SDNode *UmlalNode = nullptr; 11032 SDValue AddHi; 11033 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 11034 UmlalNode = AddcNode->getOperand(0).getNode(); 11035 AddHi = AddcNode->getOperand(1); 11036 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 11037 UmlalNode = AddcNode->getOperand(1).getNode(); 11038 AddHi = AddcNode->getOperand(0); 11039 } else { 11040 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 11041 } 11042 11043 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 11044 // the ADDC as well as Zero. 11045 if (!isNullConstant(UmlalNode->getOperand(3))) 11046 return SDValue(); 11047 11048 if ((isNullConstant(AddeNode->getOperand(0)) && 11049 AddeNode->getOperand(1).getNode() == UmlalNode) || 11050 (AddeNode->getOperand(0).getNode() == UmlalNode && 11051 isNullConstant(AddeNode->getOperand(1)))) { 11052 SelectionDAG &DAG = DCI.DAG; 11053 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 11054 UmlalNode->getOperand(2), AddHi }; 11055 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 11056 DAG.getVTList(MVT::i32, MVT::i32), Ops); 11057 11058 // Replace the ADDs' nodes uses by the UMAAL node's values. 11059 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 11060 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 11061 11062 // Return original node to notify the driver to stop replacing. 11063 return SDValue(AddeNode, 0); 11064 } 11065 return SDValue(); 11066 } 11067 11068 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 11069 const ARMSubtarget *Subtarget) { 11070 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 11071 return SDValue(); 11072 11073 // Check that we have a pair of ADDC and ADDE as operands. 11074 // Both addends of the ADDE must be zero. 11075 SDNode* AddcNode = N->getOperand(2).getNode(); 11076 SDNode* AddeNode = N->getOperand(3).getNode(); 11077 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 11078 (AddeNode->getOpcode() == ARMISD::ADDE) && 11079 isNullConstant(AddeNode->getOperand(0)) && 11080 isNullConstant(AddeNode->getOperand(1)) && 11081 (AddeNode->getOperand(2).getNode() == AddcNode)) 11082 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 11083 DAG.getVTList(MVT::i32, MVT::i32), 11084 {N->getOperand(0), N->getOperand(1), 11085 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 11086 else 11087 return SDValue(); 11088 } 11089 11090 static SDValue PerformAddcSubcCombine(SDNode *N, 11091 TargetLowering::DAGCombinerInfo &DCI, 11092 const ARMSubtarget *Subtarget) { 11093 SelectionDAG &DAG(DCI.DAG); 11094 11095 if (N->getOpcode() == ARMISD::SUBC) { 11096 // (SUBC (ADDE 0, 0, C), 1) -> C 11097 SDValue LHS = N->getOperand(0); 11098 SDValue RHS = N->getOperand(1); 11099 if (LHS->getOpcode() == ARMISD::ADDE && 11100 isNullConstant(LHS->getOperand(0)) && 11101 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 11102 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 11103 } 11104 } 11105 11106 if (Subtarget->isThumb1Only()) { 11107 SDValue RHS = N->getOperand(1); 11108 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11109 int32_t imm = C->getSExtValue(); 11110 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 11111 SDLoc DL(N); 11112 RHS = DAG.getConstant(-imm, DL, MVT::i32); 11113 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 11114 : ARMISD::ADDC; 11115 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 11116 } 11117 } 11118 } 11119 11120 return SDValue(); 11121 } 11122 11123 static SDValue PerformAddeSubeCombine(SDNode *N, 11124 TargetLowering::DAGCombinerInfo &DCI, 11125 const ARMSubtarget *Subtarget) { 11126 if (Subtarget->isThumb1Only()) { 11127 SelectionDAG &DAG = DCI.DAG; 11128 SDValue RHS = N->getOperand(1); 11129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 11130 int64_t imm = C->getSExtValue(); 11131 if (imm < 0) { 11132 SDLoc DL(N); 11133 11134 // The with-carry-in form matches bitwise not instead of the negation. 11135 // Effectively, the inverse interpretation of the carry flag already 11136 // accounts for part of the negation. 11137 RHS = DAG.getConstant(~imm, DL, MVT::i32); 11138 11139 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 11140 : ARMISD::ADDE; 11141 return DAG.getNode(Opcode, DL, N->getVTList(), 11142 N->getOperand(0), RHS, N->getOperand(2)); 11143 } 11144 } 11145 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 11146 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 11147 } 11148 return SDValue(); 11149 } 11150 11151 static SDValue PerformABSCombine(SDNode *N, 11152 TargetLowering::DAGCombinerInfo &DCI, 11153 const ARMSubtarget *Subtarget) { 11154 SDValue res; 11155 SelectionDAG &DAG = DCI.DAG; 11156 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11157 11158 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 11159 return SDValue(); 11160 11161 if (!TLI.expandABS(N, res, DAG)) 11162 return SDValue(); 11163 11164 return res; 11165 } 11166 11167 /// PerformADDECombine - Target-specific dag combine transform from 11168 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 11169 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 11170 static SDValue PerformADDECombine(SDNode *N, 11171 TargetLowering::DAGCombinerInfo &DCI, 11172 const ARMSubtarget *Subtarget) { 11173 // Only ARM and Thumb2 support UMLAL/SMLAL. 11174 if (Subtarget->isThumb1Only()) 11175 return PerformAddeSubeCombine(N, DCI, Subtarget); 11176 11177 // Only perform the checks after legalize when the pattern is available. 11178 if (DCI.isBeforeLegalize()) return SDValue(); 11179 11180 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 11181 } 11182 11183 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 11184 /// operands N0 and N1. This is a helper for PerformADDCombine that is 11185 /// called with the default operands, and if that fails, with commuted 11186 /// operands. 11187 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 11188 TargetLowering::DAGCombinerInfo &DCI, 11189 const ARMSubtarget *Subtarget){ 11190 // Attempt to create vpadd for this add. 11191 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 11192 return Result; 11193 11194 // Attempt to create vpaddl for this add. 11195 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 11196 return Result; 11197 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 11198 Subtarget)) 11199 return Result; 11200 11201 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 11202 if (N0.getNode()->hasOneUse()) 11203 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 11204 return Result; 11205 return SDValue(); 11206 } 11207 11208 bool 11209 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 11210 CombineLevel Level) const { 11211 if (Level == BeforeLegalizeTypes) 11212 return true; 11213 11214 if (N->getOpcode() != ISD::SHL) 11215 return true; 11216 11217 if (Subtarget->isThumb1Only()) { 11218 // Avoid making expensive immediates by commuting shifts. (This logic 11219 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 11220 // for free.) 11221 if (N->getOpcode() != ISD::SHL) 11222 return true; 11223 SDValue N1 = N->getOperand(0); 11224 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 11225 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 11226 return true; 11227 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 11228 if (Const->getAPIntValue().ult(256)) 11229 return false; 11230 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 11231 Const->getAPIntValue().sgt(-256)) 11232 return false; 11233 } 11234 return true; 11235 } 11236 11237 // Turn off commute-with-shift transform after legalization, so it doesn't 11238 // conflict with PerformSHLSimplify. (We could try to detect when 11239 // PerformSHLSimplify would trigger more precisely, but it isn't 11240 // really necessary.) 11241 return false; 11242 } 11243 11244 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 11245 const SDNode *N, CombineLevel Level) const { 11246 if (!Subtarget->isThumb1Only()) 11247 return true; 11248 11249 if (Level == BeforeLegalizeTypes) 11250 return true; 11251 11252 return false; 11253 } 11254 11255 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 11256 if (!Subtarget->hasNEON()) { 11257 if (Subtarget->isThumb1Only()) 11258 return VT.getScalarSizeInBits() <= 32; 11259 return true; 11260 } 11261 return VT.isScalarInteger(); 11262 } 11263 11264 static SDValue PerformSHLSimplify(SDNode *N, 11265 TargetLowering::DAGCombinerInfo &DCI, 11266 const ARMSubtarget *ST) { 11267 // Allow the generic combiner to identify potential bswaps. 11268 if (DCI.isBeforeLegalize()) 11269 return SDValue(); 11270 11271 // DAG combiner will fold: 11272 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 11273 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 11274 // Other code patterns that can be also be modified have the following form: 11275 // b + ((a << 1) | 510) 11276 // b + ((a << 1) & 510) 11277 // b + ((a << 1) ^ 510) 11278 // b + ((a << 1) + 510) 11279 11280 // Many instructions can perform the shift for free, but it requires both 11281 // the operands to be registers. If c1 << c2 is too large, a mov immediate 11282 // instruction will needed. So, unfold back to the original pattern if: 11283 // - if c1 and c2 are small enough that they don't require mov imms. 11284 // - the user(s) of the node can perform an shl 11285 11286 // No shifted operands for 16-bit instructions. 11287 if (ST->isThumb() && ST->isThumb1Only()) 11288 return SDValue(); 11289 11290 // Check that all the users could perform the shl themselves. 11291 for (auto U : N->uses()) { 11292 switch(U->getOpcode()) { 11293 default: 11294 return SDValue(); 11295 case ISD::SUB: 11296 case ISD::ADD: 11297 case ISD::AND: 11298 case ISD::OR: 11299 case ISD::XOR: 11300 case ISD::SETCC: 11301 case ARMISD::CMP: 11302 // Check that the user isn't already using a constant because there 11303 // aren't any instructions that support an immediate operand and a 11304 // shifted operand. 11305 if (isa<ConstantSDNode>(U->getOperand(0)) || 11306 isa<ConstantSDNode>(U->getOperand(1))) 11307 return SDValue(); 11308 11309 // Check that it's not already using a shift. 11310 if (U->getOperand(0).getOpcode() == ISD::SHL || 11311 U->getOperand(1).getOpcode() == ISD::SHL) 11312 return SDValue(); 11313 break; 11314 } 11315 } 11316 11317 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 11318 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 11319 return SDValue(); 11320 11321 if (N->getOperand(0).getOpcode() != ISD::SHL) 11322 return SDValue(); 11323 11324 SDValue SHL = N->getOperand(0); 11325 11326 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11327 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 11328 if (!C1ShlC2 || !C2) 11329 return SDValue(); 11330 11331 APInt C2Int = C2->getAPIntValue(); 11332 APInt C1Int = C1ShlC2->getAPIntValue(); 11333 11334 // Check that performing a lshr will not lose any information. 11335 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 11336 C2Int.getBitWidth() - C2->getZExtValue()); 11337 if ((C1Int & Mask) != C1Int) 11338 return SDValue(); 11339 11340 // Shift the first constant. 11341 C1Int.lshrInPlace(C2Int); 11342 11343 // The immediates are encoded as an 8-bit value that can be rotated. 11344 auto LargeImm = [](const APInt &Imm) { 11345 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 11346 return Imm.getBitWidth() - Zeros > 8; 11347 }; 11348 11349 if (LargeImm(C1Int) || LargeImm(C2Int)) 11350 return SDValue(); 11351 11352 SelectionDAG &DAG = DCI.DAG; 11353 SDLoc dl(N); 11354 SDValue X = SHL.getOperand(0); 11355 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 11356 DAG.getConstant(C1Int, dl, MVT::i32)); 11357 // Shift left to compensate for the lshr of C1Int. 11358 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 11359 11360 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 11361 SHL.dump(); N->dump()); 11362 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 11363 return Res; 11364 } 11365 11366 11367 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 11368 /// 11369 static SDValue PerformADDCombine(SDNode *N, 11370 TargetLowering::DAGCombinerInfo &DCI, 11371 const ARMSubtarget *Subtarget) { 11372 SDValue N0 = N->getOperand(0); 11373 SDValue N1 = N->getOperand(1); 11374 11375 // Only works one way, because it needs an immediate operand. 11376 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11377 return Result; 11378 11379 // First try with the default operand order. 11380 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 11381 return Result; 11382 11383 // If that didn't work, try again with the operands commuted. 11384 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 11385 } 11386 11387 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 11388 /// 11389 static SDValue PerformSUBCombine(SDNode *N, 11390 TargetLowering::DAGCombinerInfo &DCI) { 11391 SDValue N0 = N->getOperand(0); 11392 SDValue N1 = N->getOperand(1); 11393 11394 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 11395 if (N1.getNode()->hasOneUse()) 11396 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 11397 return Result; 11398 11399 return SDValue(); 11400 } 11401 11402 /// PerformVMULCombine 11403 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 11404 /// special multiplier accumulator forwarding. 11405 /// vmul d3, d0, d2 11406 /// vmla d3, d1, d2 11407 /// is faster than 11408 /// vadd d3, d0, d1 11409 /// vmul d3, d3, d2 11410 // However, for (A + B) * (A + B), 11411 // vadd d2, d0, d1 11412 // vmul d3, d0, d2 11413 // vmla d3, d1, d2 11414 // is slower than 11415 // vadd d2, d0, d1 11416 // vmul d3, d2, d2 11417 static SDValue PerformVMULCombine(SDNode *N, 11418 TargetLowering::DAGCombinerInfo &DCI, 11419 const ARMSubtarget *Subtarget) { 11420 if (!Subtarget->hasVMLxForwarding()) 11421 return SDValue(); 11422 11423 SelectionDAG &DAG = DCI.DAG; 11424 SDValue N0 = N->getOperand(0); 11425 SDValue N1 = N->getOperand(1); 11426 unsigned Opcode = N0.getOpcode(); 11427 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11428 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 11429 Opcode = N1.getOpcode(); 11430 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 11431 Opcode != ISD::FADD && Opcode != ISD::FSUB) 11432 return SDValue(); 11433 std::swap(N0, N1); 11434 } 11435 11436 if (N0 == N1) 11437 return SDValue(); 11438 11439 EVT VT = N->getValueType(0); 11440 SDLoc DL(N); 11441 SDValue N00 = N0->getOperand(0); 11442 SDValue N01 = N0->getOperand(1); 11443 return DAG.getNode(Opcode, DL, VT, 11444 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 11445 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 11446 } 11447 11448 static SDValue PerformMULCombine(SDNode *N, 11449 TargetLowering::DAGCombinerInfo &DCI, 11450 const ARMSubtarget *Subtarget) { 11451 SelectionDAG &DAG = DCI.DAG; 11452 11453 if (Subtarget->isThumb1Only()) 11454 return SDValue(); 11455 11456 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11457 return SDValue(); 11458 11459 EVT VT = N->getValueType(0); 11460 if (VT.is64BitVector() || VT.is128BitVector()) 11461 return PerformVMULCombine(N, DCI, Subtarget); 11462 if (VT != MVT::i32) 11463 return SDValue(); 11464 11465 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11466 if (!C) 11467 return SDValue(); 11468 11469 int64_t MulAmt = C->getSExtValue(); 11470 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 11471 11472 ShiftAmt = ShiftAmt & (32 - 1); 11473 SDValue V = N->getOperand(0); 11474 SDLoc DL(N); 11475 11476 SDValue Res; 11477 MulAmt >>= ShiftAmt; 11478 11479 if (MulAmt >= 0) { 11480 if (isPowerOf2_32(MulAmt - 1)) { 11481 // (mul x, 2^N + 1) => (add (shl x, N), x) 11482 Res = DAG.getNode(ISD::ADD, DL, VT, 11483 V, 11484 DAG.getNode(ISD::SHL, DL, VT, 11485 V, 11486 DAG.getConstant(Log2_32(MulAmt - 1), DL, 11487 MVT::i32))); 11488 } else if (isPowerOf2_32(MulAmt + 1)) { 11489 // (mul x, 2^N - 1) => (sub (shl x, N), x) 11490 Res = DAG.getNode(ISD::SUB, DL, VT, 11491 DAG.getNode(ISD::SHL, DL, VT, 11492 V, 11493 DAG.getConstant(Log2_32(MulAmt + 1), DL, 11494 MVT::i32)), 11495 V); 11496 } else 11497 return SDValue(); 11498 } else { 11499 uint64_t MulAmtAbs = -MulAmt; 11500 if (isPowerOf2_32(MulAmtAbs + 1)) { 11501 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 11502 Res = DAG.getNode(ISD::SUB, DL, VT, 11503 V, 11504 DAG.getNode(ISD::SHL, DL, VT, 11505 V, 11506 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 11507 MVT::i32))); 11508 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 11509 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 11510 Res = DAG.getNode(ISD::ADD, DL, VT, 11511 V, 11512 DAG.getNode(ISD::SHL, DL, VT, 11513 V, 11514 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 11515 MVT::i32))); 11516 Res = DAG.getNode(ISD::SUB, DL, VT, 11517 DAG.getConstant(0, DL, MVT::i32), Res); 11518 } else 11519 return SDValue(); 11520 } 11521 11522 if (ShiftAmt != 0) 11523 Res = DAG.getNode(ISD::SHL, DL, VT, 11524 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 11525 11526 // Do not add new nodes to DAG combiner worklist. 11527 DCI.CombineTo(N, Res, false); 11528 return SDValue(); 11529 } 11530 11531 static SDValue CombineANDShift(SDNode *N, 11532 TargetLowering::DAGCombinerInfo &DCI, 11533 const ARMSubtarget *Subtarget) { 11534 // Allow DAGCombine to pattern-match before we touch the canonical form. 11535 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11536 return SDValue(); 11537 11538 if (N->getValueType(0) != MVT::i32) 11539 return SDValue(); 11540 11541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11542 if (!N1C) 11543 return SDValue(); 11544 11545 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 11546 // Don't transform uxtb/uxth. 11547 if (C1 == 255 || C1 == 65535) 11548 return SDValue(); 11549 11550 SDNode *N0 = N->getOperand(0).getNode(); 11551 if (!N0->hasOneUse()) 11552 return SDValue(); 11553 11554 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 11555 return SDValue(); 11556 11557 bool LeftShift = N0->getOpcode() == ISD::SHL; 11558 11559 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 11560 if (!N01C) 11561 return SDValue(); 11562 11563 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 11564 if (!C2 || C2 >= 32) 11565 return SDValue(); 11566 11567 // Clear irrelevant bits in the mask. 11568 if (LeftShift) 11569 C1 &= (-1U << C2); 11570 else 11571 C1 &= (-1U >> C2); 11572 11573 SelectionDAG &DAG = DCI.DAG; 11574 SDLoc DL(N); 11575 11576 // We have a pattern of the form "(and (shl x, c2) c1)" or 11577 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 11578 // transform to a pair of shifts, to save materializing c1. 11579 11580 // First pattern: right shift, then mask off leading bits. 11581 // FIXME: Use demanded bits? 11582 if (!LeftShift && isMask_32(C1)) { 11583 uint32_t C3 = countLeadingZeros(C1); 11584 if (C2 < C3) { 11585 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11586 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11587 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11588 DAG.getConstant(C3, DL, MVT::i32)); 11589 } 11590 } 11591 11592 // First pattern, reversed: left shift, then mask off trailing bits. 11593 if (LeftShift && isMask_32(~C1)) { 11594 uint32_t C3 = countTrailingZeros(C1); 11595 if (C2 < C3) { 11596 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11597 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11598 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11599 DAG.getConstant(C3, DL, MVT::i32)); 11600 } 11601 } 11602 11603 // Second pattern: left shift, then mask off leading bits. 11604 // FIXME: Use demanded bits? 11605 if (LeftShift && isShiftedMask_32(C1)) { 11606 uint32_t Trailing = countTrailingZeros(C1); 11607 uint32_t C3 = countLeadingZeros(C1); 11608 if (Trailing == C2 && C2 + C3 < 32) { 11609 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11610 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11611 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11612 DAG.getConstant(C3, DL, MVT::i32)); 11613 } 11614 } 11615 11616 // Second pattern, reversed: right shift, then mask off trailing bits. 11617 // FIXME: Handle other patterns of known/demanded bits. 11618 if (!LeftShift && isShiftedMask_32(C1)) { 11619 uint32_t Leading = countLeadingZeros(C1); 11620 uint32_t C3 = countTrailingZeros(C1); 11621 if (Leading == C2 && C2 + C3 < 32) { 11622 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11623 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11624 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11625 DAG.getConstant(C3, DL, MVT::i32)); 11626 } 11627 } 11628 11629 // FIXME: Transform "(and (shl x, c2) c1)" -> 11630 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 11631 // c1. 11632 return SDValue(); 11633 } 11634 11635 static SDValue PerformANDCombine(SDNode *N, 11636 TargetLowering::DAGCombinerInfo &DCI, 11637 const ARMSubtarget *Subtarget) { 11638 // Attempt to use immediate-form VBIC 11639 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11640 SDLoc dl(N); 11641 EVT VT = N->getValueType(0); 11642 SelectionDAG &DAG = DCI.DAG; 11643 11644 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11645 return SDValue(); 11646 11647 APInt SplatBits, SplatUndef; 11648 unsigned SplatBitSize; 11649 bool HasAnyUndefs; 11650 if (BVN && Subtarget->hasNEON() && 11651 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11652 if (SplatBitSize <= 64) { 11653 EVT VbicVT; 11654 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(), 11655 SplatUndef.getZExtValue(), SplatBitSize, 11656 DAG, dl, VbicVT, VT.is128BitVector(), 11657 OtherModImm); 11658 if (Val.getNode()) { 11659 SDValue Input = 11660 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 11661 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 11662 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 11663 } 11664 } 11665 } 11666 11667 if (!Subtarget->isThumb1Only()) { 11668 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 11669 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 11670 return Result; 11671 11672 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11673 return Result; 11674 } 11675 11676 if (Subtarget->isThumb1Only()) 11677 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 11678 return Result; 11679 11680 return SDValue(); 11681 } 11682 11683 // Try combining OR nodes to SMULWB, SMULWT. 11684 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 11685 TargetLowering::DAGCombinerInfo &DCI, 11686 const ARMSubtarget *Subtarget) { 11687 if (!Subtarget->hasV6Ops() || 11688 (Subtarget->isThumb() && 11689 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 11690 return SDValue(); 11691 11692 SDValue SRL = OR->getOperand(0); 11693 SDValue SHL = OR->getOperand(1); 11694 11695 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 11696 SRL = OR->getOperand(1); 11697 SHL = OR->getOperand(0); 11698 } 11699 if (!isSRL16(SRL) || !isSHL16(SHL)) 11700 return SDValue(); 11701 11702 // The first operands to the shifts need to be the two results from the 11703 // same smul_lohi node. 11704 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 11705 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 11706 return SDValue(); 11707 11708 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 11709 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 11710 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 11711 return SDValue(); 11712 11713 // Now we have: 11714 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 11715 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 11716 // For SMUWB the 16-bit value will signed extended somehow. 11717 // For SMULWT only the SRA is required. 11718 // Check both sides of SMUL_LOHI 11719 SDValue OpS16 = SMULLOHI->getOperand(0); 11720 SDValue OpS32 = SMULLOHI->getOperand(1); 11721 11722 SelectionDAG &DAG = DCI.DAG; 11723 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 11724 OpS16 = OpS32; 11725 OpS32 = SMULLOHI->getOperand(0); 11726 } 11727 11728 SDLoc dl(OR); 11729 unsigned Opcode = 0; 11730 if (isS16(OpS16, DAG)) 11731 Opcode = ARMISD::SMULWB; 11732 else if (isSRA16(OpS16)) { 11733 Opcode = ARMISD::SMULWT; 11734 OpS16 = OpS16->getOperand(0); 11735 } 11736 else 11737 return SDValue(); 11738 11739 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 11740 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 11741 return SDValue(OR, 0); 11742 } 11743 11744 static SDValue PerformORCombineToBFI(SDNode *N, 11745 TargetLowering::DAGCombinerInfo &DCI, 11746 const ARMSubtarget *Subtarget) { 11747 // BFI is only available on V6T2+ 11748 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 11749 return SDValue(); 11750 11751 EVT VT = N->getValueType(0); 11752 SDValue N0 = N->getOperand(0); 11753 SDValue N1 = N->getOperand(1); 11754 SelectionDAG &DAG = DCI.DAG; 11755 SDLoc DL(N); 11756 // 1) or (and A, mask), val => ARMbfi A, val, mask 11757 // iff (val & mask) == val 11758 // 11759 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11760 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 11761 // && mask == ~mask2 11762 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 11763 // && ~mask == mask2 11764 // (i.e., copy a bitfield value into another bitfield of the same width) 11765 11766 if (VT != MVT::i32) 11767 return SDValue(); 11768 11769 SDValue N00 = N0.getOperand(0); 11770 11771 // The value and the mask need to be constants so we can verify this is 11772 // actually a bitfield set. If the mask is 0xffff, we can do better 11773 // via a movt instruction, so don't use BFI in that case. 11774 SDValue MaskOp = N0.getOperand(1); 11775 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 11776 if (!MaskC) 11777 return SDValue(); 11778 unsigned Mask = MaskC->getZExtValue(); 11779 if (Mask == 0xffff) 11780 return SDValue(); 11781 SDValue Res; 11782 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 11783 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11784 if (N1C) { 11785 unsigned Val = N1C->getZExtValue(); 11786 if ((Val & ~Mask) != Val) 11787 return SDValue(); 11788 11789 if (ARM::isBitFieldInvertedMask(Mask)) { 11790 Val >>= countTrailingZeros(~Mask); 11791 11792 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 11793 DAG.getConstant(Val, DL, MVT::i32), 11794 DAG.getConstant(Mask, DL, MVT::i32)); 11795 11796 DCI.CombineTo(N, Res, false); 11797 // Return value from the original node to inform the combiner than N is 11798 // now dead. 11799 return SDValue(N, 0); 11800 } 11801 } else if (N1.getOpcode() == ISD::AND) { 11802 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11803 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11804 if (!N11C) 11805 return SDValue(); 11806 unsigned Mask2 = N11C->getZExtValue(); 11807 11808 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 11809 // as is to match. 11810 if (ARM::isBitFieldInvertedMask(Mask) && 11811 (Mask == ~Mask2)) { 11812 // The pack halfword instruction works better for masks that fit it, 11813 // so use that when it's available. 11814 if (Subtarget->hasDSP() && 11815 (Mask == 0xffff || Mask == 0xffff0000)) 11816 return SDValue(); 11817 // 2a 11818 unsigned amt = countTrailingZeros(Mask2); 11819 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 11820 DAG.getConstant(amt, DL, MVT::i32)); 11821 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 11822 DAG.getConstant(Mask, DL, MVT::i32)); 11823 DCI.CombineTo(N, Res, false); 11824 // Return value from the original node to inform the combiner than N is 11825 // now dead. 11826 return SDValue(N, 0); 11827 } else if (ARM::isBitFieldInvertedMask(~Mask) && 11828 (~Mask == Mask2)) { 11829 // The pack halfword instruction works better for masks that fit it, 11830 // so use that when it's available. 11831 if (Subtarget->hasDSP() && 11832 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 11833 return SDValue(); 11834 // 2b 11835 unsigned lsb = countTrailingZeros(Mask); 11836 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 11837 DAG.getConstant(lsb, DL, MVT::i32)); 11838 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 11839 DAG.getConstant(Mask2, DL, MVT::i32)); 11840 DCI.CombineTo(N, Res, false); 11841 // Return value from the original node to inform the combiner than N is 11842 // now dead. 11843 return SDValue(N, 0); 11844 } 11845 } 11846 11847 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 11848 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 11849 ARM::isBitFieldInvertedMask(~Mask)) { 11850 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 11851 // where lsb(mask) == #shamt and masked bits of B are known zero. 11852 SDValue ShAmt = N00.getOperand(1); 11853 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 11854 unsigned LSB = countTrailingZeros(Mask); 11855 if (ShAmtC != LSB) 11856 return SDValue(); 11857 11858 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 11859 DAG.getConstant(~Mask, DL, MVT::i32)); 11860 11861 DCI.CombineTo(N, Res, false); 11862 // Return value from the original node to inform the combiner than N is 11863 // now dead. 11864 return SDValue(N, 0); 11865 } 11866 11867 return SDValue(); 11868 } 11869 11870 static bool isValidMVECond(unsigned CC, bool IsFloat) { 11871 switch (CC) { 11872 case ARMCC::EQ: 11873 case ARMCC::NE: 11874 case ARMCC::LE: 11875 case ARMCC::GT: 11876 case ARMCC::GE: 11877 case ARMCC::LT: 11878 return true; 11879 case ARMCC::HS: 11880 case ARMCC::HI: 11881 return !IsFloat; 11882 default: 11883 return false; 11884 }; 11885 } 11886 11887 static SDValue PerformORCombine_i1(SDNode *N, 11888 TargetLowering::DAGCombinerInfo &DCI, 11889 const ARMSubtarget *Subtarget) { 11890 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain 11891 // together with predicates 11892 EVT VT = N->getValueType(0); 11893 SDValue N0 = N->getOperand(0); 11894 SDValue N1 = N->getOperand(1); 11895 11896 ARMCC::CondCodes CondCode0 = ARMCC::AL; 11897 ARMCC::CondCodes CondCode1 = ARMCC::AL; 11898 if (N0->getOpcode() == ARMISD::VCMP) 11899 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2)) 11900 ->getZExtValue(); 11901 else if (N0->getOpcode() == ARMISD::VCMPZ) 11902 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1)) 11903 ->getZExtValue(); 11904 if (N1->getOpcode() == ARMISD::VCMP) 11905 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2)) 11906 ->getZExtValue(); 11907 else if (N1->getOpcode() == ARMISD::VCMPZ) 11908 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1)) 11909 ->getZExtValue(); 11910 11911 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL) 11912 return SDValue(); 11913 11914 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0); 11915 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1); 11916 11917 if (!isValidMVECond(Opposite0, 11918 N0->getOperand(0)->getValueType(0).isFloatingPoint()) || 11919 !isValidMVECond(Opposite1, 11920 N1->getOperand(0)->getValueType(0).isFloatingPoint())) 11921 return SDValue(); 11922 11923 SmallVector<SDValue, 4> Ops0; 11924 Ops0.push_back(N0->getOperand(0)); 11925 if (N0->getOpcode() == ARMISD::VCMP) 11926 Ops0.push_back(N0->getOperand(1)); 11927 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32)); 11928 SmallVector<SDValue, 4> Ops1; 11929 Ops1.push_back(N1->getOperand(0)); 11930 if (N1->getOpcode() == ARMISD::VCMP) 11931 Ops1.push_back(N1->getOperand(1)); 11932 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32)); 11933 11934 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0); 11935 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1); 11936 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1); 11937 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And, 11938 DCI.DAG.getAllOnesConstant(SDLoc(N), VT)); 11939 } 11940 11941 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 11942 static SDValue PerformORCombine(SDNode *N, 11943 TargetLowering::DAGCombinerInfo &DCI, 11944 const ARMSubtarget *Subtarget) { 11945 // Attempt to use immediate-form VORR 11946 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11947 SDLoc dl(N); 11948 EVT VT = N->getValueType(0); 11949 SelectionDAG &DAG = DCI.DAG; 11950 11951 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11952 return SDValue(); 11953 11954 APInt SplatBits, SplatUndef; 11955 unsigned SplatBitSize; 11956 bool HasAnyUndefs; 11957 if (BVN && Subtarget->hasNEON() && 11958 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11959 if (SplatBitSize <= 64) { 11960 EVT VorrVT; 11961 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(), 11962 SplatUndef.getZExtValue(), SplatBitSize, 11963 DAG, dl, VorrVT, VT.is128BitVector(), 11964 OtherModImm); 11965 if (Val.getNode()) { 11966 SDValue Input = 11967 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 11968 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 11969 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 11970 } 11971 } 11972 } 11973 11974 if (!Subtarget->isThumb1Only()) { 11975 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11976 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11977 return Result; 11978 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 11979 return Result; 11980 } 11981 11982 SDValue N0 = N->getOperand(0); 11983 SDValue N1 = N->getOperand(1); 11984 11985 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 11986 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 11987 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 11988 11989 // The code below optimizes (or (and X, Y), Z). 11990 // The AND operand needs to have a single user to make these optimizations 11991 // profitable. 11992 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 11993 return SDValue(); 11994 11995 APInt SplatUndef; 11996 unsigned SplatBitSize; 11997 bool HasAnyUndefs; 11998 11999 APInt SplatBits0, SplatBits1; 12000 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 12001 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 12002 // Ensure that the second operand of both ands are constants 12003 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 12004 HasAnyUndefs) && !HasAnyUndefs) { 12005 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 12006 HasAnyUndefs) && !HasAnyUndefs) { 12007 // Ensure that the bit width of the constants are the same and that 12008 // the splat arguments are logical inverses as per the pattern we 12009 // are trying to simplify. 12010 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 12011 SplatBits0 == ~SplatBits1) { 12012 // Canonicalize the vector type to make instruction selection 12013 // simpler. 12014 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 12015 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 12016 N0->getOperand(1), 12017 N0->getOperand(0), 12018 N1->getOperand(0)); 12019 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 12020 } 12021 } 12022 } 12023 } 12024 12025 if (Subtarget->hasMVEIntegerOps() && 12026 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)) 12027 return PerformORCombine_i1(N, DCI, Subtarget); 12028 12029 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 12030 // reasonable. 12031 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 12032 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 12033 return Res; 12034 } 12035 12036 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12037 return Result; 12038 12039 return SDValue(); 12040 } 12041 12042 static SDValue PerformXORCombine(SDNode *N, 12043 TargetLowering::DAGCombinerInfo &DCI, 12044 const ARMSubtarget *Subtarget) { 12045 EVT VT = N->getValueType(0); 12046 SelectionDAG &DAG = DCI.DAG; 12047 12048 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12049 return SDValue(); 12050 12051 if (!Subtarget->isThumb1Only()) { 12052 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 12053 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 12054 return Result; 12055 12056 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 12057 return Result; 12058 } 12059 12060 return SDValue(); 12061 } 12062 12063 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 12064 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 12065 // their position in "to" (Rd). 12066 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 12067 assert(N->getOpcode() == ARMISD::BFI); 12068 12069 SDValue From = N->getOperand(1); 12070 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 12071 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 12072 12073 // If the Base came from a SHR #C, we can deduce that it is really testing bit 12074 // #C in the base of the SHR. 12075 if (From->getOpcode() == ISD::SRL && 12076 isa<ConstantSDNode>(From->getOperand(1))) { 12077 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 12078 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 12079 FromMask <<= Shift.getLimitedValue(31); 12080 From = From->getOperand(0); 12081 } 12082 12083 return From; 12084 } 12085 12086 // If A and B contain one contiguous set of bits, does A | B == A . B? 12087 // 12088 // Neither A nor B must be zero. 12089 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 12090 unsigned LastActiveBitInA = A.countTrailingZeros(); 12091 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 12092 return LastActiveBitInA - 1 == FirstActiveBitInB; 12093 } 12094 12095 static SDValue FindBFIToCombineWith(SDNode *N) { 12096 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 12097 // if one exists. 12098 APInt ToMask, FromMask; 12099 SDValue From = ParseBFI(N, ToMask, FromMask); 12100 SDValue To = N->getOperand(0); 12101 12102 // Now check for a compatible BFI to merge with. We can pass through BFIs that 12103 // aren't compatible, but not if they set the same bit in their destination as 12104 // we do (or that of any BFI we're going to combine with). 12105 SDValue V = To; 12106 APInt CombinedToMask = ToMask; 12107 while (V.getOpcode() == ARMISD::BFI) { 12108 APInt NewToMask, NewFromMask; 12109 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 12110 if (NewFrom != From) { 12111 // This BFI has a different base. Keep going. 12112 CombinedToMask |= NewToMask; 12113 V = V.getOperand(0); 12114 continue; 12115 } 12116 12117 // Do the written bits conflict with any we've seen so far? 12118 if ((NewToMask & CombinedToMask).getBoolValue()) 12119 // Conflicting bits - bail out because going further is unsafe. 12120 return SDValue(); 12121 12122 // Are the new bits contiguous when combined with the old bits? 12123 if (BitsProperlyConcatenate(ToMask, NewToMask) && 12124 BitsProperlyConcatenate(FromMask, NewFromMask)) 12125 return V; 12126 if (BitsProperlyConcatenate(NewToMask, ToMask) && 12127 BitsProperlyConcatenate(NewFromMask, FromMask)) 12128 return V; 12129 12130 // We've seen a write to some bits, so track it. 12131 CombinedToMask |= NewToMask; 12132 // Keep going... 12133 V = V.getOperand(0); 12134 } 12135 12136 return SDValue(); 12137 } 12138 12139 static SDValue PerformBFICombine(SDNode *N, 12140 TargetLowering::DAGCombinerInfo &DCI) { 12141 SDValue N1 = N->getOperand(1); 12142 if (N1.getOpcode() == ISD::AND) { 12143 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 12144 // the bits being cleared by the AND are not demanded by the BFI. 12145 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 12146 if (!N11C) 12147 return SDValue(); 12148 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12149 unsigned LSB = countTrailingZeros(~InvMask); 12150 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 12151 assert(Width < 12152 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 12153 "undefined behavior"); 12154 unsigned Mask = (1u << Width) - 1; 12155 unsigned Mask2 = N11C->getZExtValue(); 12156 if ((Mask & (~Mask2)) == 0) 12157 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 12158 N->getOperand(0), N1.getOperand(0), 12159 N->getOperand(2)); 12160 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 12161 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 12162 // Keep track of any consecutive bits set that all come from the same base 12163 // value. We can combine these together into a single BFI. 12164 SDValue CombineBFI = FindBFIToCombineWith(N); 12165 if (CombineBFI == SDValue()) 12166 return SDValue(); 12167 12168 // We've found a BFI. 12169 APInt ToMask1, FromMask1; 12170 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 12171 12172 APInt ToMask2, FromMask2; 12173 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 12174 assert(From1 == From2); 12175 (void)From2; 12176 12177 // First, unlink CombineBFI. 12178 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 12179 // Then create a new BFI, combining the two together. 12180 APInt NewFromMask = FromMask1 | FromMask2; 12181 APInt NewToMask = ToMask1 | ToMask2; 12182 12183 EVT VT = N->getValueType(0); 12184 SDLoc dl(N); 12185 12186 if (NewFromMask[0] == 0) 12187 From1 = DCI.DAG.getNode( 12188 ISD::SRL, dl, VT, From1, 12189 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 12190 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 12191 DCI.DAG.getConstant(~NewToMask, dl, VT)); 12192 } 12193 return SDValue(); 12194 } 12195 12196 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 12197 /// ARMISD::VMOVRRD. 12198 static SDValue PerformVMOVRRDCombine(SDNode *N, 12199 TargetLowering::DAGCombinerInfo &DCI, 12200 const ARMSubtarget *Subtarget) { 12201 // vmovrrd(vmovdrr x, y) -> x,y 12202 SDValue InDouble = N->getOperand(0); 12203 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 12204 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 12205 12206 // vmovrrd(load f64) -> (load i32), (load i32) 12207 SDNode *InNode = InDouble.getNode(); 12208 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 12209 InNode->getValueType(0) == MVT::f64 && 12210 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 12211 !cast<LoadSDNode>(InNode)->isVolatile()) { 12212 // TODO: Should this be done for non-FrameIndex operands? 12213 LoadSDNode *LD = cast<LoadSDNode>(InNode); 12214 12215 SelectionDAG &DAG = DCI.DAG; 12216 SDLoc DL(LD); 12217 SDValue BasePtr = LD->getBasePtr(); 12218 SDValue NewLD1 = 12219 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 12220 LD->getAlignment(), LD->getMemOperand()->getFlags()); 12221 12222 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12223 DAG.getConstant(4, DL, MVT::i32)); 12224 12225 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr, 12226 LD->getPointerInfo().getWithOffset(4), 12227 std::min(4U, LD->getAlignment()), 12228 LD->getMemOperand()->getFlags()); 12229 12230 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 12231 if (DCI.DAG.getDataLayout().isBigEndian()) 12232 std::swap (NewLD1, NewLD2); 12233 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 12234 return Result; 12235 } 12236 12237 return SDValue(); 12238 } 12239 12240 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 12241 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 12242 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 12243 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 12244 SDValue Op0 = N->getOperand(0); 12245 SDValue Op1 = N->getOperand(1); 12246 if (Op0.getOpcode() == ISD::BITCAST) 12247 Op0 = Op0.getOperand(0); 12248 if (Op1.getOpcode() == ISD::BITCAST) 12249 Op1 = Op1.getOperand(0); 12250 if (Op0.getOpcode() == ARMISD::VMOVRRD && 12251 Op0.getNode() == Op1.getNode() && 12252 Op0.getResNo() == 0 && Op1.getResNo() == 1) 12253 return DAG.getNode(ISD::BITCAST, SDLoc(N), 12254 N->getValueType(0), Op0.getOperand(0)); 12255 return SDValue(); 12256 } 12257 12258 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 12259 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 12260 /// i64 vector to have f64 elements, since the value can then be loaded 12261 /// directly into a VFP register. 12262 static bool hasNormalLoadOperand(SDNode *N) { 12263 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 12264 for (unsigned i = 0; i < NumElts; ++i) { 12265 SDNode *Elt = N->getOperand(i).getNode(); 12266 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 12267 return true; 12268 } 12269 return false; 12270 } 12271 12272 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 12273 /// ISD::BUILD_VECTOR. 12274 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 12275 TargetLowering::DAGCombinerInfo &DCI, 12276 const ARMSubtarget *Subtarget) { 12277 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 12278 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 12279 // into a pair of GPRs, which is fine when the value is used as a scalar, 12280 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 12281 SelectionDAG &DAG = DCI.DAG; 12282 if (N->getNumOperands() == 2) 12283 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 12284 return RV; 12285 12286 // Load i64 elements as f64 values so that type legalization does not split 12287 // them up into i32 values. 12288 EVT VT = N->getValueType(0); 12289 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 12290 return SDValue(); 12291 SDLoc dl(N); 12292 SmallVector<SDValue, 8> Ops; 12293 unsigned NumElts = VT.getVectorNumElements(); 12294 for (unsigned i = 0; i < NumElts; ++i) { 12295 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 12296 Ops.push_back(V); 12297 // Make the DAGCombiner fold the bitcast. 12298 DCI.AddToWorklist(V.getNode()); 12299 } 12300 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 12301 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 12302 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12303 } 12304 12305 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 12306 static SDValue 12307 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12308 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 12309 // At that time, we may have inserted bitcasts from integer to float. 12310 // If these bitcasts have survived DAGCombine, change the lowering of this 12311 // BUILD_VECTOR in something more vector friendly, i.e., that does not 12312 // force to use floating point types. 12313 12314 // Make sure we can change the type of the vector. 12315 // This is possible iff: 12316 // 1. The vector is only used in a bitcast to a integer type. I.e., 12317 // 1.1. Vector is used only once. 12318 // 1.2. Use is a bit convert to an integer type. 12319 // 2. The size of its operands are 32-bits (64-bits are not legal). 12320 EVT VT = N->getValueType(0); 12321 EVT EltVT = VT.getVectorElementType(); 12322 12323 // Check 1.1. and 2. 12324 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 12325 return SDValue(); 12326 12327 // By construction, the input type must be float. 12328 assert(EltVT == MVT::f32 && "Unexpected type!"); 12329 12330 // Check 1.2. 12331 SDNode *Use = *N->use_begin(); 12332 if (Use->getOpcode() != ISD::BITCAST || 12333 Use->getValueType(0).isFloatingPoint()) 12334 return SDValue(); 12335 12336 // Check profitability. 12337 // Model is, if more than half of the relevant operands are bitcast from 12338 // i32, turn the build_vector into a sequence of insert_vector_elt. 12339 // Relevant operands are everything that is not statically 12340 // (i.e., at compile time) bitcasted. 12341 unsigned NumOfBitCastedElts = 0; 12342 unsigned NumElts = VT.getVectorNumElements(); 12343 unsigned NumOfRelevantElts = NumElts; 12344 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 12345 SDValue Elt = N->getOperand(Idx); 12346 if (Elt->getOpcode() == ISD::BITCAST) { 12347 // Assume only bit cast to i32 will go away. 12348 if (Elt->getOperand(0).getValueType() == MVT::i32) 12349 ++NumOfBitCastedElts; 12350 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 12351 // Constants are statically casted, thus do not count them as 12352 // relevant operands. 12353 --NumOfRelevantElts; 12354 } 12355 12356 // Check if more than half of the elements require a non-free bitcast. 12357 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 12358 return SDValue(); 12359 12360 SelectionDAG &DAG = DCI.DAG; 12361 // Create the new vector type. 12362 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 12363 // Check if the type is legal. 12364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12365 if (!TLI.isTypeLegal(VecVT)) 12366 return SDValue(); 12367 12368 // Combine: 12369 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 12370 // => BITCAST INSERT_VECTOR_ELT 12371 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 12372 // (BITCAST EN), N. 12373 SDValue Vec = DAG.getUNDEF(VecVT); 12374 SDLoc dl(N); 12375 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 12376 SDValue V = N->getOperand(Idx); 12377 if (V.isUndef()) 12378 continue; 12379 if (V.getOpcode() == ISD::BITCAST && 12380 V->getOperand(0).getValueType() == MVT::i32) 12381 // Fold obvious case. 12382 V = V.getOperand(0); 12383 else { 12384 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 12385 // Make the DAGCombiner fold the bitcasts. 12386 DCI.AddToWorklist(V.getNode()); 12387 } 12388 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 12389 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 12390 } 12391 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 12392 // Make the DAGCombiner fold the bitcasts. 12393 DCI.AddToWorklist(Vec.getNode()); 12394 return Vec; 12395 } 12396 12397 /// PerformInsertEltCombine - Target-specific dag combine xforms for 12398 /// ISD::INSERT_VECTOR_ELT. 12399 static SDValue PerformInsertEltCombine(SDNode *N, 12400 TargetLowering::DAGCombinerInfo &DCI) { 12401 // Bitcast an i64 load inserted into a vector to f64. 12402 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12403 EVT VT = N->getValueType(0); 12404 SDNode *Elt = N->getOperand(1).getNode(); 12405 if (VT.getVectorElementType() != MVT::i64 || 12406 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 12407 return SDValue(); 12408 12409 SelectionDAG &DAG = DCI.DAG; 12410 SDLoc dl(N); 12411 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12412 VT.getVectorNumElements()); 12413 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 12414 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 12415 // Make the DAGCombiner fold the bitcasts. 12416 DCI.AddToWorklist(Vec.getNode()); 12417 DCI.AddToWorklist(V.getNode()); 12418 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 12419 Vec, V, N->getOperand(2)); 12420 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 12421 } 12422 12423 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 12424 /// ISD::VECTOR_SHUFFLE. 12425 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 12426 // The LLVM shufflevector instruction does not require the shuffle mask 12427 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 12428 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 12429 // operands do not match the mask length, they are extended by concatenating 12430 // them with undef vectors. That is probably the right thing for other 12431 // targets, but for NEON it is better to concatenate two double-register 12432 // size vector operands into a single quad-register size vector. Do that 12433 // transformation here: 12434 // shuffle(concat(v1, undef), concat(v2, undef)) -> 12435 // shuffle(concat(v1, v2), undef) 12436 SDValue Op0 = N->getOperand(0); 12437 SDValue Op1 = N->getOperand(1); 12438 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 12439 Op1.getOpcode() != ISD::CONCAT_VECTORS || 12440 Op0.getNumOperands() != 2 || 12441 Op1.getNumOperands() != 2) 12442 return SDValue(); 12443 SDValue Concat0Op1 = Op0.getOperand(1); 12444 SDValue Concat1Op1 = Op1.getOperand(1); 12445 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 12446 return SDValue(); 12447 // Skip the transformation if any of the types are illegal. 12448 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12449 EVT VT = N->getValueType(0); 12450 if (!TLI.isTypeLegal(VT) || 12451 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 12452 !TLI.isTypeLegal(Concat1Op1.getValueType())) 12453 return SDValue(); 12454 12455 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12456 Op0.getOperand(0), Op1.getOperand(0)); 12457 // Translate the shuffle mask. 12458 SmallVector<int, 16> NewMask; 12459 unsigned NumElts = VT.getVectorNumElements(); 12460 unsigned HalfElts = NumElts/2; 12461 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12462 for (unsigned n = 0; n < NumElts; ++n) { 12463 int MaskElt = SVN->getMaskElt(n); 12464 int NewElt = -1; 12465 if (MaskElt < (int)HalfElts) 12466 NewElt = MaskElt; 12467 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 12468 NewElt = HalfElts + MaskElt - NumElts; 12469 NewMask.push_back(NewElt); 12470 } 12471 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 12472 DAG.getUNDEF(VT), NewMask); 12473 } 12474 12475 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 12476 /// NEON load/store intrinsics, and generic vector load/stores, to merge 12477 /// base address updates. 12478 /// For generic load/stores, the memory type is assumed to be a vector. 12479 /// The caller is assumed to have checked legality. 12480 static SDValue CombineBaseUpdate(SDNode *N, 12481 TargetLowering::DAGCombinerInfo &DCI) { 12482 SelectionDAG &DAG = DCI.DAG; 12483 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 12484 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 12485 const bool isStore = N->getOpcode() == ISD::STORE; 12486 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 12487 SDValue Addr = N->getOperand(AddrOpIdx); 12488 MemSDNode *MemN = cast<MemSDNode>(N); 12489 SDLoc dl(N); 12490 12491 // Search for a use of the address operand that is an increment. 12492 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 12493 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 12494 SDNode *User = *UI; 12495 if (User->getOpcode() != ISD::ADD || 12496 UI.getUse().getResNo() != Addr.getResNo()) 12497 continue; 12498 12499 // Check that the add is independent of the load/store. Otherwise, folding 12500 // it would create a cycle. We can avoid searching through Addr as it's a 12501 // predecessor to both. 12502 SmallPtrSet<const SDNode *, 32> Visited; 12503 SmallVector<const SDNode *, 16> Worklist; 12504 Visited.insert(Addr.getNode()); 12505 Worklist.push_back(N); 12506 Worklist.push_back(User); 12507 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 12508 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 12509 continue; 12510 12511 // Find the new opcode for the updating load/store. 12512 bool isLoadOp = true; 12513 bool isLaneOp = false; 12514 unsigned NewOpc = 0; 12515 unsigned NumVecs = 0; 12516 if (isIntrinsic) { 12517 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 12518 switch (IntNo) { 12519 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 12520 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 12521 NumVecs = 1; break; 12522 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 12523 NumVecs = 2; break; 12524 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 12525 NumVecs = 3; break; 12526 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 12527 NumVecs = 4; break; 12528 case Intrinsic::arm_neon_vld2dup: 12529 case Intrinsic::arm_neon_vld3dup: 12530 case Intrinsic::arm_neon_vld4dup: 12531 // TODO: Support updating VLDxDUP nodes. For now, we just skip 12532 // combining base updates for such intrinsics. 12533 continue; 12534 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 12535 NumVecs = 2; isLaneOp = true; break; 12536 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 12537 NumVecs = 3; isLaneOp = true; break; 12538 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 12539 NumVecs = 4; isLaneOp = true; break; 12540 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 12541 NumVecs = 1; isLoadOp = false; break; 12542 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 12543 NumVecs = 2; isLoadOp = false; break; 12544 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 12545 NumVecs = 3; isLoadOp = false; break; 12546 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 12547 NumVecs = 4; isLoadOp = false; break; 12548 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 12549 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 12550 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 12551 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 12552 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 12553 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 12554 } 12555 } else { 12556 isLaneOp = true; 12557 switch (N->getOpcode()) { 12558 default: llvm_unreachable("unexpected opcode for Neon base update"); 12559 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 12560 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 12561 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 12562 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 12563 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 12564 NumVecs = 1; isLaneOp = false; break; 12565 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 12566 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 12567 } 12568 } 12569 12570 // Find the size of memory referenced by the load/store. 12571 EVT VecTy; 12572 if (isLoadOp) { 12573 VecTy = N->getValueType(0); 12574 } else if (isIntrinsic) { 12575 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 12576 } else { 12577 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 12578 VecTy = N->getOperand(1).getValueType(); 12579 } 12580 12581 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 12582 if (isLaneOp) 12583 NumBytes /= VecTy.getVectorNumElements(); 12584 12585 // If the increment is a constant, it must match the memory ref size. 12586 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 12587 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 12588 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 12589 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 12590 // separate instructions that make it harder to use a non-constant update. 12591 continue; 12592 } 12593 12594 // OK, we found an ADD we can fold into the base update. 12595 // Now, create a _UPD node, taking care of not breaking alignment. 12596 12597 EVT AlignedVecTy = VecTy; 12598 unsigned Alignment = MemN->getAlignment(); 12599 12600 // If this is a less-than-standard-aligned load/store, change the type to 12601 // match the standard alignment. 12602 // The alignment is overlooked when selecting _UPD variants; and it's 12603 // easier to introduce bitcasts here than fix that. 12604 // There are 3 ways to get to this base-update combine: 12605 // - intrinsics: they are assumed to be properly aligned (to the standard 12606 // alignment of the memory type), so we don't need to do anything. 12607 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 12608 // intrinsics, so, likewise, there's nothing to do. 12609 // - generic load/store instructions: the alignment is specified as an 12610 // explicit operand, rather than implicitly as the standard alignment 12611 // of the memory type (like the intrisics). We need to change the 12612 // memory type to match the explicit alignment. That way, we don't 12613 // generate non-standard-aligned ARMISD::VLDx nodes. 12614 if (isa<LSBaseSDNode>(N)) { 12615 if (Alignment == 0) 12616 Alignment = 1; 12617 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 12618 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 12619 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 12620 assert(!isLaneOp && "Unexpected generic load/store lane."); 12621 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 12622 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 12623 } 12624 // Don't set an explicit alignment on regular load/stores that we want 12625 // to transform to VLD/VST 1_UPD nodes. 12626 // This matches the behavior of regular load/stores, which only get an 12627 // explicit alignment if the MMO alignment is larger than the standard 12628 // alignment of the memory type. 12629 // Intrinsics, however, always get an explicit alignment, set to the 12630 // alignment of the MMO. 12631 Alignment = 1; 12632 } 12633 12634 // Create the new updating load/store node. 12635 // First, create an SDVTList for the new updating node's results. 12636 EVT Tys[6]; 12637 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 12638 unsigned n; 12639 for (n = 0; n < NumResultVecs; ++n) 12640 Tys[n] = AlignedVecTy; 12641 Tys[n++] = MVT::i32; 12642 Tys[n] = MVT::Other; 12643 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 12644 12645 // Then, gather the new node's operands. 12646 SmallVector<SDValue, 8> Ops; 12647 Ops.push_back(N->getOperand(0)); // incoming chain 12648 Ops.push_back(N->getOperand(AddrOpIdx)); 12649 Ops.push_back(Inc); 12650 12651 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 12652 // Try to match the intrinsic's signature 12653 Ops.push_back(StN->getValue()); 12654 } else { 12655 // Loads (and of course intrinsics) match the intrinsics' signature, 12656 // so just add all but the alignment operand. 12657 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 12658 Ops.push_back(N->getOperand(i)); 12659 } 12660 12661 // For all node types, the alignment operand is always the last one. 12662 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 12663 12664 // If this is a non-standard-aligned STORE, the penultimate operand is the 12665 // stored value. Bitcast it to the aligned type. 12666 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 12667 SDValue &StVal = Ops[Ops.size()-2]; 12668 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 12669 } 12670 12671 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 12672 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 12673 MemN->getMemOperand()); 12674 12675 // Update the uses. 12676 SmallVector<SDValue, 5> NewResults; 12677 for (unsigned i = 0; i < NumResultVecs; ++i) 12678 NewResults.push_back(SDValue(UpdN.getNode(), i)); 12679 12680 // If this is an non-standard-aligned LOAD, the first result is the loaded 12681 // value. Bitcast it to the expected result type. 12682 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 12683 SDValue &LdVal = NewResults[0]; 12684 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 12685 } 12686 12687 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 12688 DCI.CombineTo(N, NewResults); 12689 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 12690 12691 break; 12692 } 12693 return SDValue(); 12694 } 12695 12696 static SDValue PerformVLDCombine(SDNode *N, 12697 TargetLowering::DAGCombinerInfo &DCI) { 12698 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12699 return SDValue(); 12700 12701 return CombineBaseUpdate(N, DCI); 12702 } 12703 12704 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 12705 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 12706 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 12707 /// return true. 12708 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12709 SelectionDAG &DAG = DCI.DAG; 12710 EVT VT = N->getValueType(0); 12711 // vldN-dup instructions only support 64-bit vectors for N > 1. 12712 if (!VT.is64BitVector()) 12713 return false; 12714 12715 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 12716 SDNode *VLD = N->getOperand(0).getNode(); 12717 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 12718 return false; 12719 unsigned NumVecs = 0; 12720 unsigned NewOpc = 0; 12721 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 12722 if (IntNo == Intrinsic::arm_neon_vld2lane) { 12723 NumVecs = 2; 12724 NewOpc = ARMISD::VLD2DUP; 12725 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 12726 NumVecs = 3; 12727 NewOpc = ARMISD::VLD3DUP; 12728 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 12729 NumVecs = 4; 12730 NewOpc = ARMISD::VLD4DUP; 12731 } else { 12732 return false; 12733 } 12734 12735 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 12736 // numbers match the load. 12737 unsigned VLDLaneNo = 12738 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 12739 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12740 UI != UE; ++UI) { 12741 // Ignore uses of the chain result. 12742 if (UI.getUse().getResNo() == NumVecs) 12743 continue; 12744 SDNode *User = *UI; 12745 if (User->getOpcode() != ARMISD::VDUPLANE || 12746 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 12747 return false; 12748 } 12749 12750 // Create the vldN-dup node. 12751 EVT Tys[5]; 12752 unsigned n; 12753 for (n = 0; n < NumVecs; ++n) 12754 Tys[n] = VT; 12755 Tys[n] = MVT::Other; 12756 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 12757 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 12758 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 12759 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 12760 Ops, VLDMemInt->getMemoryVT(), 12761 VLDMemInt->getMemOperand()); 12762 12763 // Update the uses. 12764 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12765 UI != UE; ++UI) { 12766 unsigned ResNo = UI.getUse().getResNo(); 12767 // Ignore uses of the chain result. 12768 if (ResNo == NumVecs) 12769 continue; 12770 SDNode *User = *UI; 12771 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 12772 } 12773 12774 // Now the vldN-lane intrinsic is dead except for its chain result. 12775 // Update uses of the chain. 12776 std::vector<SDValue> VLDDupResults; 12777 for (unsigned n = 0; n < NumVecs; ++n) 12778 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 12779 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 12780 DCI.CombineTo(VLD, VLDDupResults); 12781 12782 return true; 12783 } 12784 12785 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 12786 /// ARMISD::VDUPLANE. 12787 static SDValue PerformVDUPLANECombine(SDNode *N, 12788 TargetLowering::DAGCombinerInfo &DCI) { 12789 SDValue Op = N->getOperand(0); 12790 12791 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 12792 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 12793 if (CombineVLDDUP(N, DCI)) 12794 return SDValue(N, 0); 12795 12796 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 12797 // redundant. Ignore bit_converts for now; element sizes are checked below. 12798 while (Op.getOpcode() == ISD::BITCAST) 12799 Op = Op.getOperand(0); 12800 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 12801 return SDValue(); 12802 12803 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 12804 unsigned EltSize = Op.getScalarValueSizeInBits(); 12805 // The canonical VMOV for a zero vector uses a 32-bit element size. 12806 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12807 unsigned EltBits; 12808 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0) 12809 EltSize = 8; 12810 EVT VT = N->getValueType(0); 12811 if (EltSize > VT.getScalarSizeInBits()) 12812 return SDValue(); 12813 12814 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 12815 } 12816 12817 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 12818 static SDValue PerformVDUPCombine(SDNode *N, 12819 TargetLowering::DAGCombinerInfo &DCI, 12820 const ARMSubtarget *Subtarget) { 12821 SelectionDAG &DAG = DCI.DAG; 12822 SDValue Op = N->getOperand(0); 12823 12824 if (!Subtarget->hasNEON()) 12825 return SDValue(); 12826 12827 // Match VDUP(LOAD) -> VLD1DUP. 12828 // We match this pattern here rather than waiting for isel because the 12829 // transform is only legal for unindexed loads. 12830 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 12831 if (LD && Op.hasOneUse() && LD->isUnindexed() && 12832 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 12833 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 12834 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 12835 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 12836 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 12837 Ops, LD->getMemoryVT(), 12838 LD->getMemOperand()); 12839 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 12840 return VLDDup; 12841 } 12842 12843 return SDValue(); 12844 } 12845 12846 static SDValue PerformLOADCombine(SDNode *N, 12847 TargetLowering::DAGCombinerInfo &DCI) { 12848 EVT VT = N->getValueType(0); 12849 12850 // If this is a legal vector load, try to combine it into a VLD1_UPD. 12851 if (ISD::isNormalLoad(N) && VT.isVector() && 12852 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12853 return CombineBaseUpdate(N, DCI); 12854 12855 return SDValue(); 12856 } 12857 12858 /// PerformSTORECombine - Target-specific dag combine xforms for 12859 /// ISD::STORE. 12860 static SDValue PerformSTORECombine(SDNode *N, 12861 TargetLowering::DAGCombinerInfo &DCI) { 12862 StoreSDNode *St = cast<StoreSDNode>(N); 12863 if (St->isVolatile()) 12864 return SDValue(); 12865 12866 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 12867 // pack all of the elements in one place. Next, store to memory in fewer 12868 // chunks. 12869 SDValue StVal = St->getValue(); 12870 EVT VT = StVal.getValueType(); 12871 if (St->isTruncatingStore() && VT.isVector()) { 12872 SelectionDAG &DAG = DCI.DAG; 12873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12874 EVT StVT = St->getMemoryVT(); 12875 unsigned NumElems = VT.getVectorNumElements(); 12876 assert(StVT != VT && "Cannot truncate to the same type"); 12877 unsigned FromEltSz = VT.getScalarSizeInBits(); 12878 unsigned ToEltSz = StVT.getScalarSizeInBits(); 12879 12880 // From, To sizes and ElemCount must be pow of two 12881 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 12882 12883 // We are going to use the original vector elt for storing. 12884 // Accumulated smaller vector elements must be a multiple of the store size. 12885 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 12886 12887 unsigned SizeRatio = FromEltSz / ToEltSz; 12888 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 12889 12890 // Create a type on which we perform the shuffle. 12891 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 12892 NumElems*SizeRatio); 12893 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 12894 12895 SDLoc DL(St); 12896 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 12897 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 12898 for (unsigned i = 0; i < NumElems; ++i) 12899 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 12900 ? (i + 1) * SizeRatio - 1 12901 : i * SizeRatio; 12902 12903 // Can't shuffle using an illegal type. 12904 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 12905 12906 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 12907 DAG.getUNDEF(WideVec.getValueType()), 12908 ShuffleVec); 12909 // At this point all of the data is stored at the bottom of the 12910 // register. We now need to save it to mem. 12911 12912 // Find the largest store unit 12913 MVT StoreType = MVT::i8; 12914 for (MVT Tp : MVT::integer_valuetypes()) { 12915 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 12916 StoreType = Tp; 12917 } 12918 // Didn't find a legal store type. 12919 if (!TLI.isTypeLegal(StoreType)) 12920 return SDValue(); 12921 12922 // Bitcast the original vector into a vector of store-size units 12923 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 12924 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 12925 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 12926 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 12927 SmallVector<SDValue, 8> Chains; 12928 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 12929 TLI.getPointerTy(DAG.getDataLayout())); 12930 SDValue BasePtr = St->getBasePtr(); 12931 12932 // Perform one or more big stores into memory. 12933 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 12934 for (unsigned I = 0; I < E; I++) { 12935 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 12936 StoreType, ShuffWide, 12937 DAG.getIntPtrConstant(I, DL)); 12938 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 12939 St->getPointerInfo(), St->getAlignment(), 12940 St->getMemOperand()->getFlags()); 12941 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 12942 Increment); 12943 Chains.push_back(Ch); 12944 } 12945 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 12946 } 12947 12948 if (!ISD::isNormalStore(St)) 12949 return SDValue(); 12950 12951 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 12952 // ARM stores of arguments in the same cache line. 12953 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 12954 StVal.getNode()->hasOneUse()) { 12955 SelectionDAG &DAG = DCI.DAG; 12956 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 12957 SDLoc DL(St); 12958 SDValue BasePtr = St->getBasePtr(); 12959 SDValue NewST1 = DAG.getStore( 12960 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 12961 BasePtr, St->getPointerInfo(), St->getAlignment(), 12962 St->getMemOperand()->getFlags()); 12963 12964 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12965 DAG.getConstant(4, DL, MVT::i32)); 12966 return DAG.getStore(NewST1.getValue(0), DL, 12967 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 12968 OffsetPtr, St->getPointerInfo(), 12969 std::min(4U, St->getAlignment() / 2), 12970 St->getMemOperand()->getFlags()); 12971 } 12972 12973 if (StVal.getValueType() == MVT::i64 && 12974 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12975 12976 // Bitcast an i64 store extracted from a vector to f64. 12977 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12978 SelectionDAG &DAG = DCI.DAG; 12979 SDLoc dl(StVal); 12980 SDValue IntVec = StVal.getOperand(0); 12981 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12982 IntVec.getValueType().getVectorNumElements()); 12983 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 12984 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 12985 Vec, StVal.getOperand(1)); 12986 dl = SDLoc(N); 12987 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 12988 // Make the DAGCombiner fold the bitcasts. 12989 DCI.AddToWorklist(Vec.getNode()); 12990 DCI.AddToWorklist(ExtElt.getNode()); 12991 DCI.AddToWorklist(V.getNode()); 12992 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 12993 St->getPointerInfo(), St->getAlignment(), 12994 St->getMemOperand()->getFlags(), St->getAAInfo()); 12995 } 12996 12997 // If this is a legal vector store, try to combine it into a VST1_UPD. 12998 if (ISD::isNormalStore(N) && VT.isVector() && 12999 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 13000 return CombineBaseUpdate(N, DCI); 13001 13002 return SDValue(); 13003 } 13004 13005 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 13006 /// can replace combinations of VMUL and VCVT (floating-point to integer) 13007 /// when the VMUL has a constant operand that is a power of 2. 13008 /// 13009 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13010 /// vmul.f32 d16, d17, d16 13011 /// vcvt.s32.f32 d16, d16 13012 /// becomes: 13013 /// vcvt.s32.f32 d16, d16, #3 13014 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 13015 const ARMSubtarget *Subtarget) { 13016 if (!Subtarget->hasNEON()) 13017 return SDValue(); 13018 13019 SDValue Op = N->getOperand(0); 13020 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 13021 Op.getOpcode() != ISD::FMUL) 13022 return SDValue(); 13023 13024 SDValue ConstVec = Op->getOperand(1); 13025 if (!isa<BuildVectorSDNode>(ConstVec)) 13026 return SDValue(); 13027 13028 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 13029 uint32_t FloatBits = FloatTy.getSizeInBits(); 13030 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 13031 uint32_t IntBits = IntTy.getSizeInBits(); 13032 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13033 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13034 // These instructions only exist converting from f32 to i32. We can handle 13035 // smaller integers by generating an extra truncate, but larger ones would 13036 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13037 // these intructions only support v2i32/v4i32 types. 13038 return SDValue(); 13039 } 13040 13041 BitVector UndefElements; 13042 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13043 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13044 if (C == -1 || C == 0 || C > 32) 13045 return SDValue(); 13046 13047 SDLoc dl(N); 13048 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 13049 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 13050 Intrinsic::arm_neon_vcvtfp2fxu; 13051 SDValue FixConv = DAG.getNode( 13052 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13053 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 13054 DAG.getConstant(C, dl, MVT::i32)); 13055 13056 if (IntBits < FloatBits) 13057 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 13058 13059 return FixConv; 13060 } 13061 13062 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 13063 /// can replace combinations of VCVT (integer to floating-point) and VDIV 13064 /// when the VDIV has a constant operand that is a power of 2. 13065 /// 13066 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 13067 /// vcvt.f32.s32 d16, d16 13068 /// vdiv.f32 d16, d17, d16 13069 /// becomes: 13070 /// vcvt.f32.s32 d16, d16, #3 13071 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 13072 const ARMSubtarget *Subtarget) { 13073 if (!Subtarget->hasNEON()) 13074 return SDValue(); 13075 13076 SDValue Op = N->getOperand(0); 13077 unsigned OpOpcode = Op.getNode()->getOpcode(); 13078 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 13079 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 13080 return SDValue(); 13081 13082 SDValue ConstVec = N->getOperand(1); 13083 if (!isa<BuildVectorSDNode>(ConstVec)) 13084 return SDValue(); 13085 13086 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 13087 uint32_t FloatBits = FloatTy.getSizeInBits(); 13088 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 13089 uint32_t IntBits = IntTy.getSizeInBits(); 13090 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 13091 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 13092 // These instructions only exist converting from i32 to f32. We can handle 13093 // smaller integers by generating an extra extend, but larger ones would 13094 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 13095 // these intructions only support v2i32/v4i32 types. 13096 return SDValue(); 13097 } 13098 13099 BitVector UndefElements; 13100 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 13101 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 13102 if (C == -1 || C == 0 || C > 32) 13103 return SDValue(); 13104 13105 SDLoc dl(N); 13106 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 13107 SDValue ConvInput = Op.getOperand(0); 13108 if (IntBits < FloatBits) 13109 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 13110 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 13111 ConvInput); 13112 13113 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 13114 Intrinsic::arm_neon_vcvtfxu2fp; 13115 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 13116 Op.getValueType(), 13117 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 13118 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 13119 } 13120 13121 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 13122 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 13123 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13124 switch (IntNo) { 13125 default: 13126 // Don't do anything for most intrinsics. 13127 break; 13128 13129 // Vector shifts: check for immediate versions and lower them. 13130 // Note: This is done during DAG combining instead of DAG legalizing because 13131 // the build_vectors for 64-bit vector element shift counts are generally 13132 // not legal, and it is hard to see their values after they get legalized to 13133 // loads from a constant pool. 13134 case Intrinsic::arm_neon_vshifts: 13135 case Intrinsic::arm_neon_vshiftu: 13136 case Intrinsic::arm_neon_vrshifts: 13137 case Intrinsic::arm_neon_vrshiftu: 13138 case Intrinsic::arm_neon_vrshiftn: 13139 case Intrinsic::arm_neon_vqshifts: 13140 case Intrinsic::arm_neon_vqshiftu: 13141 case Intrinsic::arm_neon_vqshiftsu: 13142 case Intrinsic::arm_neon_vqshiftns: 13143 case Intrinsic::arm_neon_vqshiftnu: 13144 case Intrinsic::arm_neon_vqshiftnsu: 13145 case Intrinsic::arm_neon_vqrshiftns: 13146 case Intrinsic::arm_neon_vqrshiftnu: 13147 case Intrinsic::arm_neon_vqrshiftnsu: { 13148 EVT VT = N->getOperand(1).getValueType(); 13149 int64_t Cnt; 13150 unsigned VShiftOpc = 0; 13151 13152 switch (IntNo) { 13153 case Intrinsic::arm_neon_vshifts: 13154 case Intrinsic::arm_neon_vshiftu: 13155 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 13156 VShiftOpc = ARMISD::VSHLIMM; 13157 break; 13158 } 13159 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 13160 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM 13161 : ARMISD::VSHRuIMM); 13162 break; 13163 } 13164 return SDValue(); 13165 13166 case Intrinsic::arm_neon_vrshifts: 13167 case Intrinsic::arm_neon_vrshiftu: 13168 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 13169 break; 13170 return SDValue(); 13171 13172 case Intrinsic::arm_neon_vqshifts: 13173 case Intrinsic::arm_neon_vqshiftu: 13174 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13175 break; 13176 return SDValue(); 13177 13178 case Intrinsic::arm_neon_vqshiftsu: 13179 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 13180 break; 13181 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 13182 13183 case Intrinsic::arm_neon_vrshiftn: 13184 case Intrinsic::arm_neon_vqshiftns: 13185 case Intrinsic::arm_neon_vqshiftnu: 13186 case Intrinsic::arm_neon_vqshiftnsu: 13187 case Intrinsic::arm_neon_vqrshiftns: 13188 case Intrinsic::arm_neon_vqrshiftnu: 13189 case Intrinsic::arm_neon_vqrshiftnsu: 13190 // Narrowing shifts require an immediate right shift. 13191 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 13192 break; 13193 llvm_unreachable("invalid shift count for narrowing vector shift " 13194 "intrinsic"); 13195 13196 default: 13197 llvm_unreachable("unhandled vector shift"); 13198 } 13199 13200 switch (IntNo) { 13201 case Intrinsic::arm_neon_vshifts: 13202 case Intrinsic::arm_neon_vshiftu: 13203 // Opcode already set above. 13204 break; 13205 case Intrinsic::arm_neon_vrshifts: 13206 VShiftOpc = ARMISD::VRSHRsIMM; 13207 break; 13208 case Intrinsic::arm_neon_vrshiftu: 13209 VShiftOpc = ARMISD::VRSHRuIMM; 13210 break; 13211 case Intrinsic::arm_neon_vrshiftn: 13212 VShiftOpc = ARMISD::VRSHRNIMM; 13213 break; 13214 case Intrinsic::arm_neon_vqshifts: 13215 VShiftOpc = ARMISD::VQSHLsIMM; 13216 break; 13217 case Intrinsic::arm_neon_vqshiftu: 13218 VShiftOpc = ARMISD::VQSHLuIMM; 13219 break; 13220 case Intrinsic::arm_neon_vqshiftsu: 13221 VShiftOpc = ARMISD::VQSHLsuIMM; 13222 break; 13223 case Intrinsic::arm_neon_vqshiftns: 13224 VShiftOpc = ARMISD::VQSHRNsIMM; 13225 break; 13226 case Intrinsic::arm_neon_vqshiftnu: 13227 VShiftOpc = ARMISD::VQSHRNuIMM; 13228 break; 13229 case Intrinsic::arm_neon_vqshiftnsu: 13230 VShiftOpc = ARMISD::VQSHRNsuIMM; 13231 break; 13232 case Intrinsic::arm_neon_vqrshiftns: 13233 VShiftOpc = ARMISD::VQRSHRNsIMM; 13234 break; 13235 case Intrinsic::arm_neon_vqrshiftnu: 13236 VShiftOpc = ARMISD::VQRSHRNuIMM; 13237 break; 13238 case Intrinsic::arm_neon_vqrshiftnsu: 13239 VShiftOpc = ARMISD::VQRSHRNsuIMM; 13240 break; 13241 } 13242 13243 SDLoc dl(N); 13244 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 13245 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 13246 } 13247 13248 case Intrinsic::arm_neon_vshiftins: { 13249 EVT VT = N->getOperand(1).getValueType(); 13250 int64_t Cnt; 13251 unsigned VShiftOpc = 0; 13252 13253 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 13254 VShiftOpc = ARMISD::VSLIIMM; 13255 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 13256 VShiftOpc = ARMISD::VSRIIMM; 13257 else { 13258 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 13259 } 13260 13261 SDLoc dl(N); 13262 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 13263 N->getOperand(1), N->getOperand(2), 13264 DAG.getConstant(Cnt, dl, MVT::i32)); 13265 } 13266 13267 case Intrinsic::arm_neon_vqrshifts: 13268 case Intrinsic::arm_neon_vqrshiftu: 13269 // No immediate versions of these to check for. 13270 break; 13271 } 13272 13273 return SDValue(); 13274 } 13275 13276 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 13277 /// lowers them. As with the vector shift intrinsics, this is done during DAG 13278 /// combining instead of DAG legalizing because the build_vectors for 64-bit 13279 /// vector element shift counts are generally not legal, and it is hard to see 13280 /// their values after they get legalized to loads from a constant pool. 13281 static SDValue PerformShiftCombine(SDNode *N, 13282 TargetLowering::DAGCombinerInfo &DCI, 13283 const ARMSubtarget *ST) { 13284 SelectionDAG &DAG = DCI.DAG; 13285 EVT VT = N->getValueType(0); 13286 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 13287 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 13288 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 13289 SDValue N1 = N->getOperand(1); 13290 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 13291 SDValue N0 = N->getOperand(0); 13292 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 13293 DAG.MaskedValueIsZero(N0.getOperand(0), 13294 APInt::getHighBitsSet(32, 16))) 13295 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 13296 } 13297 } 13298 13299 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 13300 N->getOperand(0)->getOpcode() == ISD::AND && 13301 N->getOperand(0)->hasOneUse()) { 13302 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13303 return SDValue(); 13304 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 13305 // usually show up because instcombine prefers to canonicalize it to 13306 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 13307 // out of GEP lowering in some cases. 13308 SDValue N0 = N->getOperand(0); 13309 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13310 if (!ShiftAmtNode) 13311 return SDValue(); 13312 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 13313 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13314 if (!AndMaskNode) 13315 return SDValue(); 13316 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 13317 // Don't transform uxtb/uxth. 13318 if (AndMask == 255 || AndMask == 65535) 13319 return SDValue(); 13320 if (isMask_32(AndMask)) { 13321 uint32_t MaskedBits = countLeadingZeros(AndMask); 13322 if (MaskedBits > ShiftAmt) { 13323 SDLoc DL(N); 13324 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 13325 DAG.getConstant(MaskedBits, DL, MVT::i32)); 13326 return DAG.getNode( 13327 ISD::SRL, DL, MVT::i32, SHL, 13328 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 13329 } 13330 } 13331 } 13332 13333 // Nothing to be done for scalar shifts. 13334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13335 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 13336 return SDValue(); 13337 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64) 13338 return SDValue(); 13339 13340 int64_t Cnt; 13341 13342 switch (N->getOpcode()) { 13343 default: llvm_unreachable("unexpected shift opcode"); 13344 13345 case ISD::SHL: 13346 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 13347 SDLoc dl(N); 13348 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0), 13349 DAG.getConstant(Cnt, dl, MVT::i32)); 13350 } 13351 break; 13352 13353 case ISD::SRA: 13354 case ISD::SRL: 13355 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 13356 unsigned VShiftOpc = 13357 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM); 13358 SDLoc dl(N); 13359 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 13360 DAG.getConstant(Cnt, dl, MVT::i32)); 13361 } 13362 } 13363 return SDValue(); 13364 } 13365 13366 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 13367 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 13368 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 13369 const ARMSubtarget *ST) { 13370 SDValue N0 = N->getOperand(0); 13371 13372 // Check for sign- and zero-extensions of vector extract operations of 8- 13373 // and 16-bit vector elements. NEON supports these directly. They are 13374 // handled during DAG combining because type legalization will promote them 13375 // to 32-bit types and it is messy to recognize the operations after that. 13376 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13377 SDValue Vec = N0.getOperand(0); 13378 SDValue Lane = N0.getOperand(1); 13379 EVT VT = N->getValueType(0); 13380 EVT EltVT = N0.getValueType(); 13381 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13382 13383 if (VT == MVT::i32 && 13384 (EltVT == MVT::i8 || EltVT == MVT::i16) && 13385 TLI.isTypeLegal(Vec.getValueType()) && 13386 isa<ConstantSDNode>(Lane)) { 13387 13388 unsigned Opc = 0; 13389 switch (N->getOpcode()) { 13390 default: llvm_unreachable("unexpected opcode"); 13391 case ISD::SIGN_EXTEND: 13392 Opc = ARMISD::VGETLANEs; 13393 break; 13394 case ISD::ZERO_EXTEND: 13395 case ISD::ANY_EXTEND: 13396 Opc = ARMISD::VGETLANEu; 13397 break; 13398 } 13399 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 13400 } 13401 } 13402 13403 return SDValue(); 13404 } 13405 13406 static const APInt *isPowerOf2Constant(SDValue V) { 13407 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 13408 if (!C) 13409 return nullptr; 13410 const APInt *CV = &C->getAPIntValue(); 13411 return CV->isPowerOf2() ? CV : nullptr; 13412 } 13413 13414 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 13415 // If we have a CMOV, OR and AND combination such as: 13416 // if (x & CN) 13417 // y |= CM; 13418 // 13419 // And: 13420 // * CN is a single bit; 13421 // * All bits covered by CM are known zero in y 13422 // 13423 // Then we can convert this into a sequence of BFI instructions. This will 13424 // always be a win if CM is a single bit, will always be no worse than the 13425 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 13426 // three bits (due to the extra IT instruction). 13427 13428 SDValue Op0 = CMOV->getOperand(0); 13429 SDValue Op1 = CMOV->getOperand(1); 13430 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 13431 auto CC = CCNode->getAPIntValue().getLimitedValue(); 13432 SDValue CmpZ = CMOV->getOperand(4); 13433 13434 // The compare must be against zero. 13435 if (!isNullConstant(CmpZ->getOperand(1))) 13436 return SDValue(); 13437 13438 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 13439 SDValue And = CmpZ->getOperand(0); 13440 if (And->getOpcode() != ISD::AND) 13441 return SDValue(); 13442 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 13443 if (!AndC) 13444 return SDValue(); 13445 SDValue X = And->getOperand(0); 13446 13447 if (CC == ARMCC::EQ) { 13448 // We're performing an "equal to zero" compare. Swap the operands so we 13449 // canonicalize on a "not equal to zero" compare. 13450 std::swap(Op0, Op1); 13451 } else { 13452 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 13453 } 13454 13455 if (Op1->getOpcode() != ISD::OR) 13456 return SDValue(); 13457 13458 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 13459 if (!OrC) 13460 return SDValue(); 13461 SDValue Y = Op1->getOperand(0); 13462 13463 if (Op0 != Y) 13464 return SDValue(); 13465 13466 // Now, is it profitable to continue? 13467 APInt OrCI = OrC->getAPIntValue(); 13468 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 13469 if (OrCI.countPopulation() > Heuristic) 13470 return SDValue(); 13471 13472 // Lastly, can we determine that the bits defined by OrCI 13473 // are zero in Y? 13474 KnownBits Known = DAG.computeKnownBits(Y); 13475 if ((OrCI & Known.Zero) != OrCI) 13476 return SDValue(); 13477 13478 // OK, we can do the combine. 13479 SDValue V = Y; 13480 SDLoc dl(X); 13481 EVT VT = X.getValueType(); 13482 unsigned BitInX = AndC->logBase2(); 13483 13484 if (BitInX != 0) { 13485 // We must shift X first. 13486 X = DAG.getNode(ISD::SRL, dl, VT, X, 13487 DAG.getConstant(BitInX, dl, VT)); 13488 } 13489 13490 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 13491 BitInY < NumActiveBits; ++BitInY) { 13492 if (OrCI[BitInY] == 0) 13493 continue; 13494 APInt Mask(VT.getSizeInBits(), 0); 13495 Mask.setBit(BitInY); 13496 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 13497 // Confusingly, the operand is an *inverted* mask. 13498 DAG.getConstant(~Mask, dl, VT)); 13499 } 13500 13501 return V; 13502 } 13503 13504 // Given N, the value controlling the conditional branch, search for the loop 13505 // intrinsic, returning it, along with how the value is used. We need to handle 13506 // patterns such as the following: 13507 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit) 13508 // (brcond (setcc (loop.decrement), 0, eq), exit) 13509 // (brcond (setcc (loop.decrement), 0, ne), header) 13510 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, 13511 bool &Negate) { 13512 switch (N->getOpcode()) { 13513 default: 13514 break; 13515 case ISD::XOR: { 13516 if (!isa<ConstantSDNode>(N.getOperand(1))) 13517 return SDValue(); 13518 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne()) 13519 return SDValue(); 13520 Negate = !Negate; 13521 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate); 13522 } 13523 case ISD::SETCC: { 13524 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1)); 13525 if (!Const) 13526 return SDValue(); 13527 if (Const->isNullValue()) 13528 Imm = 0; 13529 else if (Const->isOne()) 13530 Imm = 1; 13531 else 13532 return SDValue(); 13533 CC = cast<CondCodeSDNode>(N.getOperand(2))->get(); 13534 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate); 13535 } 13536 case ISD::INTRINSIC_W_CHAIN: { 13537 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue(); 13538 if (IntOp != Intrinsic::test_set_loop_iterations && 13539 IntOp != Intrinsic::loop_decrement_reg) 13540 return SDValue(); 13541 return N; 13542 } 13543 } 13544 return SDValue(); 13545 } 13546 13547 static SDValue PerformHWLoopCombine(SDNode *N, 13548 TargetLowering::DAGCombinerInfo &DCI, 13549 const ARMSubtarget *ST) { 13550 13551 // The hwloop intrinsics that we're interested are used for control-flow, 13552 // either for entering or exiting the loop: 13553 // - test.set.loop.iterations will test whether its operand is zero. If it 13554 // is zero, the proceeding branch should not enter the loop. 13555 // - loop.decrement.reg also tests whether its operand is zero. If it is 13556 // zero, the proceeding branch should not branch back to the beginning of 13557 // the loop. 13558 // So here, we need to check that how the brcond is using the result of each 13559 // of the intrinsics to ensure that we're branching to the right place at the 13560 // right time. 13561 13562 ISD::CondCode CC; 13563 SDValue Cond; 13564 int Imm = 1; 13565 bool Negate = false; 13566 SDValue Chain = N->getOperand(0); 13567 SDValue Dest; 13568 13569 if (N->getOpcode() == ISD::BRCOND) { 13570 CC = ISD::SETEQ; 13571 Cond = N->getOperand(1); 13572 Dest = N->getOperand(2); 13573 } else { 13574 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!"); 13575 CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13576 Cond = N->getOperand(2); 13577 Dest = N->getOperand(4); 13578 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) { 13579 if (!Const->isOne() && !Const->isNullValue()) 13580 return SDValue(); 13581 Imm = Const->getZExtValue(); 13582 } else 13583 return SDValue(); 13584 } 13585 13586 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate); 13587 if (!Int) 13588 return SDValue(); 13589 13590 if (Negate) 13591 CC = ISD::getSetCCInverse(CC, true); 13592 13593 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) { 13594 return (CC == ISD::SETEQ && Imm == 0) || 13595 (CC == ISD::SETNE && Imm == 1) || 13596 (CC == ISD::SETLT && Imm == 1) || 13597 (CC == ISD::SETULT && Imm == 1); 13598 }; 13599 13600 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) { 13601 return (CC == ISD::SETEQ && Imm == 1) || 13602 (CC == ISD::SETNE && Imm == 0) || 13603 (CC == ISD::SETGT && Imm == 0) || 13604 (CC == ISD::SETUGT && Imm == 0) || 13605 (CC == ISD::SETGE && Imm == 1) || 13606 (CC == ISD::SETUGE && Imm == 1); 13607 }; 13608 13609 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && 13610 "unsupported condition"); 13611 13612 SDLoc dl(Int); 13613 SelectionDAG &DAG = DCI.DAG; 13614 SDValue Elements = Int.getOperand(2); 13615 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue(); 13616 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) 13617 && "expected single br user"); 13618 SDNode *Br = *N->use_begin(); 13619 SDValue OtherTarget = Br->getOperand(1); 13620 13621 // Update the unconditional branch to branch to the given Dest. 13622 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) { 13623 SDValue NewBrOps[] = { Br->getOperand(0), Dest }; 13624 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps); 13625 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr); 13626 }; 13627 13628 if (IntOp == Intrinsic::test_set_loop_iterations) { 13629 SDValue Res; 13630 // We expect this 'instruction' to branch when the counter is zero. 13631 if (IsTrueIfZero(CC, Imm)) { 13632 SDValue Ops[] = { Chain, Elements, Dest }; 13633 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 13634 } else { 13635 // The logic is the reverse of what we need for WLS, so find the other 13636 // basic block target: the target of the proceeding br. 13637 UpdateUncondBr(Br, Dest, DAG); 13638 13639 SDValue Ops[] = { Chain, Elements, OtherTarget }; 13640 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 13641 } 13642 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 13643 return Res; 13644 } else { 13645 SDValue Size = DAG.getTargetConstant( 13646 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32); 13647 SDValue Args[] = { Int.getOperand(0), Elements, Size, }; 13648 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl, 13649 DAG.getVTList(MVT::i32, MVT::Other), Args); 13650 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode()); 13651 13652 // We expect this instruction to branch when the count is not zero. 13653 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget; 13654 13655 // Update the unconditional branch to target the loop preheader if we've 13656 // found the condition has been reversed. 13657 if (Target == OtherTarget) 13658 UpdateUncondBr(Br, Dest, DAG); 13659 13660 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13661 SDValue(LoopDec.getNode(), 1), Chain); 13662 13663 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target }; 13664 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs); 13665 } 13666 return SDValue(); 13667 } 13668 13669 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 13670 SDValue 13671 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 13672 SDValue Cmp = N->getOperand(4); 13673 if (Cmp.getOpcode() != ARMISD::CMPZ) 13674 // Only looking at NE cases. 13675 return SDValue(); 13676 13677 EVT VT = N->getValueType(0); 13678 SDLoc dl(N); 13679 SDValue LHS = Cmp.getOperand(0); 13680 SDValue RHS = Cmp.getOperand(1); 13681 SDValue Chain = N->getOperand(0); 13682 SDValue BB = N->getOperand(1); 13683 SDValue ARMcc = N->getOperand(2); 13684 ARMCC::CondCodes CC = 13685 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13686 13687 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 13688 // -> (brcond Chain BB CC CPSR Cmp) 13689 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 13690 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 13691 LHS->getOperand(0)->hasOneUse()) { 13692 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 13693 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 13694 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13695 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13696 if ((LHS00C && LHS00C->getZExtValue() == 0) && 13697 (LHS01C && LHS01C->getZExtValue() == 1) && 13698 (LHS1C && LHS1C->getZExtValue() == 1) && 13699 (RHSC && RHSC->getZExtValue() == 0)) { 13700 return DAG.getNode( 13701 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 13702 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 13703 } 13704 } 13705 13706 return SDValue(); 13707 } 13708 13709 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 13710 SDValue 13711 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 13712 SDValue Cmp = N->getOperand(4); 13713 if (Cmp.getOpcode() != ARMISD::CMPZ) 13714 // Only looking at EQ and NE cases. 13715 return SDValue(); 13716 13717 EVT VT = N->getValueType(0); 13718 SDLoc dl(N); 13719 SDValue LHS = Cmp.getOperand(0); 13720 SDValue RHS = Cmp.getOperand(1); 13721 SDValue FalseVal = N->getOperand(0); 13722 SDValue TrueVal = N->getOperand(1); 13723 SDValue ARMcc = N->getOperand(2); 13724 ARMCC::CondCodes CC = 13725 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13726 13727 // BFI is only available on V6T2+. 13728 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 13729 SDValue R = PerformCMOVToBFICombine(N, DAG); 13730 if (R) 13731 return R; 13732 } 13733 13734 // Simplify 13735 // mov r1, r0 13736 // cmp r1, x 13737 // mov r0, y 13738 // moveq r0, x 13739 // to 13740 // cmp r0, x 13741 // movne r0, y 13742 // 13743 // mov r1, r0 13744 // cmp r1, x 13745 // mov r0, x 13746 // movne r0, y 13747 // to 13748 // cmp r0, x 13749 // movne r0, y 13750 /// FIXME: Turn this into a target neutral optimization? 13751 SDValue Res; 13752 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 13753 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 13754 N->getOperand(3), Cmp); 13755 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 13756 SDValue ARMcc; 13757 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 13758 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 13759 N->getOperand(3), NewCmp); 13760 } 13761 13762 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 13763 // -> (cmov F T CC CPSR Cmp) 13764 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 13765 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 13766 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13767 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13768 if ((LHS0C && LHS0C->getZExtValue() == 0) && 13769 (LHS1C && LHS1C->getZExtValue() == 1) && 13770 (RHSC && RHSC->getZExtValue() == 0)) { 13771 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 13772 LHS->getOperand(2), LHS->getOperand(3), 13773 LHS->getOperand(4)); 13774 } 13775 } 13776 13777 if (!VT.isInteger()) 13778 return SDValue(); 13779 13780 // Materialize a boolean comparison for integers so we can avoid branching. 13781 if (isNullConstant(FalseVal)) { 13782 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 13783 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 13784 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 13785 // right 5 bits will make that 32 be 1, otherwise it will be 0. 13786 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 13787 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13788 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 13789 DAG.getConstant(5, dl, MVT::i32)); 13790 } else { 13791 // CMOV 0, 1, ==, (CMPZ x, y) -> 13792 // (ADDCARRY (SUB x, y), t:0, t:1) 13793 // where t = (SUBCARRY 0, (SUB x, y), 0) 13794 // 13795 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 13796 // x != y. In other words, a carry C == 1 when x == y, C == 0 13797 // otherwise. 13798 // The final ADDCARRY computes 13799 // x - y + (0 - (x - y)) + C == C 13800 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13801 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13802 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 13803 // ISD::SUBCARRY returns a borrow but we want the carry here 13804 // actually. 13805 SDValue Carry = 13806 DAG.getNode(ISD::SUB, dl, MVT::i32, 13807 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 13808 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 13809 } 13810 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 13811 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 13812 // This seems pointless but will allow us to combine it further below. 13813 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13814 SDValue Sub = 13815 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13816 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13817 Sub.getValue(1), SDValue()); 13818 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 13819 N->getOperand(3), CPSRGlue.getValue(1)); 13820 FalseVal = Sub; 13821 } 13822 } else if (isNullConstant(TrueVal)) { 13823 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 13824 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 13825 // This seems pointless but will allow us to combine it further below 13826 // Note that we change == for != as this is the dual for the case above. 13827 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13828 SDValue Sub = 13829 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13830 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13831 Sub.getValue(1), SDValue()); 13832 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 13833 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 13834 N->getOperand(3), CPSRGlue.getValue(1)); 13835 FalseVal = Sub; 13836 } 13837 } 13838 13839 // On Thumb1, the DAG above may be further combined if z is a power of 2 13840 // (z == 2 ^ K). 13841 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 13842 // t1 = (USUBO (SUB x, y), 1) 13843 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 13844 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13845 // 13846 // This also handles the special case of comparing against zero; it's 13847 // essentially, the same pattern, except there's no SUBS: 13848 // CMOV x, z, !=, (CMPZ x, 0) -> 13849 // t1 = (USUBO x, 1) 13850 // t2 = (SUBCARRY x, t1:0, t1:1) 13851 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13852 const APInt *TrueConst; 13853 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 13854 ((FalseVal.getOpcode() == ARMISD::SUBS && 13855 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 13856 (FalseVal == LHS && isNullConstant(RHS))) && 13857 (TrueConst = isPowerOf2Constant(TrueVal))) { 13858 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13859 unsigned ShiftAmount = TrueConst->logBase2(); 13860 if (ShiftAmount) 13861 TrueVal = DAG.getConstant(1, dl, VT); 13862 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 13863 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 13864 13865 if (ShiftAmount) 13866 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 13867 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 13868 } 13869 13870 if (Res.getNode()) { 13871 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 13872 // Capture demanded bits information that would be otherwise lost. 13873 if (Known.Zero == 0xfffffffe) 13874 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13875 DAG.getValueType(MVT::i1)); 13876 else if (Known.Zero == 0xffffff00) 13877 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13878 DAG.getValueType(MVT::i8)); 13879 else if (Known.Zero == 0xffff0000) 13880 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13881 DAG.getValueType(MVT::i16)); 13882 } 13883 13884 return Res; 13885 } 13886 13887 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 13888 DAGCombinerInfo &DCI) const { 13889 switch (N->getOpcode()) { 13890 default: break; 13891 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 13892 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 13893 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 13894 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 13895 case ISD::SUB: return PerformSUBCombine(N, DCI); 13896 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 13897 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 13898 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 13899 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 13900 case ISD::BRCOND: 13901 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget); 13902 case ARMISD::ADDC: 13903 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 13904 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 13905 case ARMISD::BFI: return PerformBFICombine(N, DCI); 13906 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 13907 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 13908 case ISD::STORE: return PerformSTORECombine(N, DCI); 13909 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 13910 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 13911 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 13912 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 13913 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 13914 case ISD::FP_TO_SINT: 13915 case ISD::FP_TO_UINT: 13916 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 13917 case ISD::FDIV: 13918 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 13919 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 13920 case ISD::SHL: 13921 case ISD::SRA: 13922 case ISD::SRL: 13923 return PerformShiftCombine(N, DCI, Subtarget); 13924 case ISD::SIGN_EXTEND: 13925 case ISD::ZERO_EXTEND: 13926 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 13927 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 13928 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 13929 case ISD::LOAD: return PerformLOADCombine(N, DCI); 13930 case ARMISD::VLD1DUP: 13931 case ARMISD::VLD2DUP: 13932 case ARMISD::VLD3DUP: 13933 case ARMISD::VLD4DUP: 13934 return PerformVLDCombine(N, DCI); 13935 case ARMISD::BUILD_VECTOR: 13936 return PerformARMBUILD_VECTORCombine(N, DCI); 13937 case ARMISD::SMULWB: { 13938 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13939 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 13940 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 13941 return SDValue(); 13942 break; 13943 } 13944 case ARMISD::SMULWT: { 13945 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13946 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 13947 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 13948 return SDValue(); 13949 break; 13950 } 13951 case ARMISD::SMLALBB: { 13952 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13953 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 13954 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 13955 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 13956 return SDValue(); 13957 break; 13958 } 13959 case ARMISD::SMLALBT: { 13960 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 13961 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 13962 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 13963 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 13964 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 13965 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 13966 return SDValue(); 13967 break; 13968 } 13969 case ARMISD::SMLALTB: { 13970 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 13971 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 13972 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 13973 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 13974 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 13975 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 13976 return SDValue(); 13977 break; 13978 } 13979 case ARMISD::SMLALTT: { 13980 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13981 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 13982 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 13983 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 13984 return SDValue(); 13985 break; 13986 } 13987 case ISD::INTRINSIC_VOID: 13988 case ISD::INTRINSIC_W_CHAIN: 13989 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13990 case Intrinsic::arm_neon_vld1: 13991 case Intrinsic::arm_neon_vld1x2: 13992 case Intrinsic::arm_neon_vld1x3: 13993 case Intrinsic::arm_neon_vld1x4: 13994 case Intrinsic::arm_neon_vld2: 13995 case Intrinsic::arm_neon_vld3: 13996 case Intrinsic::arm_neon_vld4: 13997 case Intrinsic::arm_neon_vld2lane: 13998 case Intrinsic::arm_neon_vld3lane: 13999 case Intrinsic::arm_neon_vld4lane: 14000 case Intrinsic::arm_neon_vld2dup: 14001 case Intrinsic::arm_neon_vld3dup: 14002 case Intrinsic::arm_neon_vld4dup: 14003 case Intrinsic::arm_neon_vst1: 14004 case Intrinsic::arm_neon_vst1x2: 14005 case Intrinsic::arm_neon_vst1x3: 14006 case Intrinsic::arm_neon_vst1x4: 14007 case Intrinsic::arm_neon_vst2: 14008 case Intrinsic::arm_neon_vst3: 14009 case Intrinsic::arm_neon_vst4: 14010 case Intrinsic::arm_neon_vst2lane: 14011 case Intrinsic::arm_neon_vst3lane: 14012 case Intrinsic::arm_neon_vst4lane: 14013 return PerformVLDCombine(N, DCI); 14014 default: break; 14015 } 14016 break; 14017 } 14018 return SDValue(); 14019 } 14020 14021 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 14022 EVT VT) const { 14023 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 14024 } 14025 14026 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 14027 unsigned Alignment, 14028 MachineMemOperand::Flags, 14029 bool *Fast) const { 14030 // Depends what it gets converted into if the type is weird. 14031 if (!VT.isSimple()) 14032 return false; 14033 14034 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 14035 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 14036 auto Ty = VT.getSimpleVT().SimpleTy; 14037 14038 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 14039 // Unaligned access can use (for example) LRDB, LRDH, LDR 14040 if (AllowsUnaligned) { 14041 if (Fast) 14042 *Fast = Subtarget->hasV7Ops(); 14043 return true; 14044 } 14045 } 14046 14047 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 14048 // For any little-endian targets with neon, we can support unaligned ld/st 14049 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 14050 // A big-endian target may also explicitly support unaligned accesses 14051 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 14052 if (Fast) 14053 *Fast = true; 14054 return true; 14055 } 14056 } 14057 14058 if (!Subtarget->hasMVEIntegerOps()) 14059 return false; 14060 14061 // These are for predicates 14062 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) { 14063 if (Fast) 14064 *Fast = true; 14065 return true; 14066 } 14067 14068 if (Ty != MVT::v16i8 && Ty != MVT::v8i16 && Ty != MVT::v8f16 && 14069 Ty != MVT::v4i32 && Ty != MVT::v4f32 && Ty != MVT::v2i64 && 14070 Ty != MVT::v2f64 && 14071 // These are for truncated stores 14072 Ty != MVT::v4i8 && Ty != MVT::v8i8 && Ty != MVT::v4i16) 14073 return false; 14074 14075 if (Subtarget->isLittle()) { 14076 // In little-endian MVE, the store instructions VSTRB.U8, 14077 // VSTRH.U16 and VSTRW.U32 all store the vector register in 14078 // exactly the same format, and differ only in the range of 14079 // their immediate offset field and the required alignment. 14080 // 14081 // In particular, VSTRB.U8 can store a vector at byte alignment. 14082 // So at this stage we can simply say that loads/stores of all 14083 // 128-bit wide vector types are permitted at any alignment, 14084 // because we know at least _one_ instruction can manage that. 14085 // 14086 // Later on we might find that some of those loads are better 14087 // generated as VLDRW.U32 if alignment permits, to take 14088 // advantage of the larger immediate range. But for the moment, 14089 // all that matters is that if we don't lower the load then 14090 // _some_ instruction can handle it. 14091 if (Fast) 14092 *Fast = true; 14093 return true; 14094 } else { 14095 // In big-endian MVE, those instructions aren't so similar 14096 // after all, because they reorder the bytes of the vector 14097 // differently. So this time we can only store a particular 14098 // kind of vector if its alignment is at least the element 14099 // type. And we can't store vectors of i64 or f64 at all 14100 // without having to do some postprocessing, because there's 14101 // no VSTRD.U64. 14102 if (Ty == MVT::v16i8 || 14103 ((Ty == MVT::v8i16 || Ty == MVT::v8f16) && Alignment >= 2) || 14104 ((Ty == MVT::v4i32 || Ty == MVT::v4f32) && Alignment >= 4)) { 14105 if (Fast) 14106 *Fast = true; 14107 return true; 14108 } 14109 } 14110 14111 return false; 14112 } 14113 14114 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 14115 unsigned AlignCheck) { 14116 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 14117 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 14118 } 14119 14120 EVT ARMTargetLowering::getOptimalMemOpType( 14121 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14122 bool ZeroMemset, bool MemcpyStrSrc, 14123 const AttributeList &FuncAttributes) const { 14124 // See if we can use NEON instructions for this... 14125 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 14126 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14127 bool Fast; 14128 if (Size >= 16 && 14129 (memOpAlign(SrcAlign, DstAlign, 16) || 14130 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 14131 MachineMemOperand::MONone, &Fast) && 14132 Fast))) { 14133 return MVT::v2f64; 14134 } else if (Size >= 8 && 14135 (memOpAlign(SrcAlign, DstAlign, 8) || 14136 (allowsMisalignedMemoryAccesses( 14137 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 14138 Fast))) { 14139 return MVT::f64; 14140 } 14141 } 14142 14143 // Let the target-independent logic figure it out. 14144 return MVT::Other; 14145 } 14146 14147 // 64-bit integers are split into their high and low parts and held in two 14148 // different registers, so the trunc is free since the low register can just 14149 // be used. 14150 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 14151 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 14152 return false; 14153 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 14154 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 14155 return (SrcBits == 64 && DestBits == 32); 14156 } 14157 14158 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 14159 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 14160 !DstVT.isInteger()) 14161 return false; 14162 unsigned SrcBits = SrcVT.getSizeInBits(); 14163 unsigned DestBits = DstVT.getSizeInBits(); 14164 return (SrcBits == 64 && DestBits == 32); 14165 } 14166 14167 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14168 if (Val.getOpcode() != ISD::LOAD) 14169 return false; 14170 14171 EVT VT1 = Val.getValueType(); 14172 if (!VT1.isSimple() || !VT1.isInteger() || 14173 !VT2.isSimple() || !VT2.isInteger()) 14174 return false; 14175 14176 switch (VT1.getSimpleVT().SimpleTy) { 14177 default: break; 14178 case MVT::i1: 14179 case MVT::i8: 14180 case MVT::i16: 14181 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 14182 return true; 14183 } 14184 14185 return false; 14186 } 14187 14188 bool ARMTargetLowering::isFNegFree(EVT VT) const { 14189 if (!VT.isSimple()) 14190 return false; 14191 14192 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 14193 // negate values directly (fneg is free). So, we don't want to let the DAG 14194 // combiner rewrite fneg into xors and some other instructions. For f16 and 14195 // FullFP16 argument passing, some bitcast nodes may be introduced, 14196 // triggering this DAG combine rewrite, so we are avoiding that with this. 14197 switch (VT.getSimpleVT().SimpleTy) { 14198 default: break; 14199 case MVT::f16: 14200 return Subtarget->hasFullFP16(); 14201 } 14202 14203 return false; 14204 } 14205 14206 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 14207 /// of the vector elements. 14208 static bool areExtractExts(Value *Ext1, Value *Ext2) { 14209 auto areExtDoubled = [](Instruction *Ext) { 14210 return Ext->getType()->getScalarSizeInBits() == 14211 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 14212 }; 14213 14214 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 14215 !match(Ext2, m_ZExtOrSExt(m_Value())) || 14216 !areExtDoubled(cast<Instruction>(Ext1)) || 14217 !areExtDoubled(cast<Instruction>(Ext2))) 14218 return false; 14219 14220 return true; 14221 } 14222 14223 /// Check if sinking \p I's operands to I's basic block is profitable, because 14224 /// the operands can be folded into a target instruction, e.g. 14225 /// sext/zext can be folded into vsubl. 14226 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 14227 SmallVectorImpl<Use *> &Ops) const { 14228 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy()) 14229 return false; 14230 14231 switch (I->getOpcode()) { 14232 case Instruction::Sub: 14233 case Instruction::Add: { 14234 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 14235 return false; 14236 Ops.push_back(&I->getOperandUse(0)); 14237 Ops.push_back(&I->getOperandUse(1)); 14238 return true; 14239 } 14240 default: 14241 return false; 14242 } 14243 return false; 14244 } 14245 14246 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 14247 EVT VT = ExtVal.getValueType(); 14248 14249 if (!isTypeLegal(VT)) 14250 return false; 14251 14252 // Don't create a loadext if we can fold the extension into a wide/long 14253 // instruction. 14254 // If there's more than one user instruction, the loadext is desirable no 14255 // matter what. There can be two uses by the same instruction. 14256 if (ExtVal->use_empty() || 14257 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 14258 return true; 14259 14260 SDNode *U = *ExtVal->use_begin(); 14261 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 14262 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM)) 14263 return false; 14264 14265 return true; 14266 } 14267 14268 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 14269 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14270 return false; 14271 14272 if (!isTypeLegal(EVT::getEVT(Ty1))) 14273 return false; 14274 14275 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 14276 14277 // Assuming the caller doesn't have a zeroext or signext return parameter, 14278 // truncation all the way down to i1 is valid. 14279 return true; 14280 } 14281 14282 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 14283 const AddrMode &AM, Type *Ty, 14284 unsigned AS) const { 14285 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 14286 if (Subtarget->hasFPAO()) 14287 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 14288 return 0; 14289 } 14290 return -1; 14291 } 14292 14293 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 14294 if (V < 0) 14295 return false; 14296 14297 unsigned Scale = 1; 14298 switch (VT.getSimpleVT().SimpleTy) { 14299 case MVT::i1: 14300 case MVT::i8: 14301 // Scale == 1; 14302 break; 14303 case MVT::i16: 14304 // Scale == 2; 14305 Scale = 2; 14306 break; 14307 default: 14308 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 14309 // Scale == 4; 14310 Scale = 4; 14311 break; 14312 } 14313 14314 if ((V & (Scale - 1)) != 0) 14315 return false; 14316 return isUInt<5>(V / Scale); 14317 } 14318 14319 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 14320 const ARMSubtarget *Subtarget) { 14321 if (!VT.isInteger() && !VT.isFloatingPoint()) 14322 return false; 14323 if (VT.isVector() && Subtarget->hasNEON()) 14324 return false; 14325 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 14326 !Subtarget->hasMVEFloatOps()) 14327 return false; 14328 14329 bool IsNeg = false; 14330 if (V < 0) { 14331 IsNeg = true; 14332 V = -V; 14333 } 14334 14335 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U); 14336 14337 // MVE: size * imm7 14338 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 14339 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 14340 case MVT::i32: 14341 case MVT::f32: 14342 return isShiftedUInt<7,2>(V); 14343 case MVT::i16: 14344 case MVT::f16: 14345 return isShiftedUInt<7,1>(V); 14346 case MVT::i8: 14347 return isUInt<7>(V); 14348 default: 14349 return false; 14350 } 14351 } 14352 14353 // half VLDR: 2 * imm8 14354 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 14355 return isShiftedUInt<8, 1>(V); 14356 // VLDR and LDRD: 4 * imm8 14357 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 14358 return isShiftedUInt<8, 2>(V); 14359 14360 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 14361 // + imm12 or - imm8 14362 if (IsNeg) 14363 return isUInt<8>(V); 14364 return isUInt<12>(V); 14365 } 14366 14367 return false; 14368 } 14369 14370 /// isLegalAddressImmediate - Return true if the integer value can be used 14371 /// as the offset of the target addressing mode for load / store of the 14372 /// given type. 14373 static bool isLegalAddressImmediate(int64_t V, EVT VT, 14374 const ARMSubtarget *Subtarget) { 14375 if (V == 0) 14376 return true; 14377 14378 if (!VT.isSimple()) 14379 return false; 14380 14381 if (Subtarget->isThumb1Only()) 14382 return isLegalT1AddressImmediate(V, VT); 14383 else if (Subtarget->isThumb2()) 14384 return isLegalT2AddressImmediate(V, VT, Subtarget); 14385 14386 // ARM mode. 14387 if (V < 0) 14388 V = - V; 14389 switch (VT.getSimpleVT().SimpleTy) { 14390 default: return false; 14391 case MVT::i1: 14392 case MVT::i8: 14393 case MVT::i32: 14394 // +- imm12 14395 return isUInt<12>(V); 14396 case MVT::i16: 14397 // +- imm8 14398 return isUInt<8>(V); 14399 case MVT::f32: 14400 case MVT::f64: 14401 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 14402 return false; 14403 return isShiftedUInt<8, 2>(V); 14404 } 14405 } 14406 14407 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 14408 EVT VT) const { 14409 int Scale = AM.Scale; 14410 if (Scale < 0) 14411 return false; 14412 14413 switch (VT.getSimpleVT().SimpleTy) { 14414 default: return false; 14415 case MVT::i1: 14416 case MVT::i8: 14417 case MVT::i16: 14418 case MVT::i32: 14419 if (Scale == 1) 14420 return true; 14421 // r + r << imm 14422 Scale = Scale & ~1; 14423 return Scale == 2 || Scale == 4 || Scale == 8; 14424 case MVT::i64: 14425 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 14426 // version in Thumb mode. 14427 // r + r 14428 if (Scale == 1) 14429 return true; 14430 // r * 2 (this can be lowered to r + r). 14431 if (!AM.HasBaseReg && Scale == 2) 14432 return true; 14433 return false; 14434 case MVT::isVoid: 14435 // Note, we allow "void" uses (basically, uses that aren't loads or 14436 // stores), because arm allows folding a scale into many arithmetic 14437 // operations. This should be made more precise and revisited later. 14438 14439 // Allow r << imm, but the imm has to be a multiple of two. 14440 if (Scale & 1) return false; 14441 return isPowerOf2_32(Scale); 14442 } 14443 } 14444 14445 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 14446 EVT VT) const { 14447 const int Scale = AM.Scale; 14448 14449 // Negative scales are not supported in Thumb1. 14450 if (Scale < 0) 14451 return false; 14452 14453 // Thumb1 addressing modes do not support register scaling excepting the 14454 // following cases: 14455 // 1. Scale == 1 means no scaling. 14456 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 14457 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 14458 } 14459 14460 /// isLegalAddressingMode - Return true if the addressing mode represented 14461 /// by AM is legal for this target, for a load/store of the specified type. 14462 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14463 const AddrMode &AM, Type *Ty, 14464 unsigned AS, Instruction *I) const { 14465 EVT VT = getValueType(DL, Ty, true); 14466 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 14467 return false; 14468 14469 // Can never fold addr of global into load/store. 14470 if (AM.BaseGV) 14471 return false; 14472 14473 switch (AM.Scale) { 14474 case 0: // no scale reg, must be "r+i" or "r", or "i". 14475 break; 14476 default: 14477 // ARM doesn't support any R+R*scale+imm addr modes. 14478 if (AM.BaseOffs) 14479 return false; 14480 14481 if (!VT.isSimple()) 14482 return false; 14483 14484 if (Subtarget->isThumb1Only()) 14485 return isLegalT1ScaledAddressingMode(AM, VT); 14486 14487 if (Subtarget->isThumb2()) 14488 return isLegalT2ScaledAddressingMode(AM, VT); 14489 14490 int Scale = AM.Scale; 14491 switch (VT.getSimpleVT().SimpleTy) { 14492 default: return false; 14493 case MVT::i1: 14494 case MVT::i8: 14495 case MVT::i32: 14496 if (Scale < 0) Scale = -Scale; 14497 if (Scale == 1) 14498 return true; 14499 // r + r << imm 14500 return isPowerOf2_32(Scale & ~1); 14501 case MVT::i16: 14502 case MVT::i64: 14503 // r +/- r 14504 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 14505 return true; 14506 // r * 2 (this can be lowered to r + r). 14507 if (!AM.HasBaseReg && Scale == 2) 14508 return true; 14509 return false; 14510 14511 case MVT::isVoid: 14512 // Note, we allow "void" uses (basically, uses that aren't loads or 14513 // stores), because arm allows folding a scale into many arithmetic 14514 // operations. This should be made more precise and revisited later. 14515 14516 // Allow r << imm, but the imm has to be a multiple of two. 14517 if (Scale & 1) return false; 14518 return isPowerOf2_32(Scale); 14519 } 14520 } 14521 return true; 14522 } 14523 14524 /// isLegalICmpImmediate - Return true if the specified immediate is legal 14525 /// icmp immediate, that is the target has icmp instructions which can compare 14526 /// a register against the immediate without having to materialize the 14527 /// immediate into a register. 14528 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14529 // Thumb2 and ARM modes can use cmn for negative immediates. 14530 if (!Subtarget->isThumb()) 14531 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 14532 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 14533 if (Subtarget->isThumb2()) 14534 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 14535 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 14536 // Thumb1 doesn't have cmn, and only 8-bit immediates. 14537 return Imm >= 0 && Imm <= 255; 14538 } 14539 14540 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 14541 /// *or sub* immediate, that is the target has add or sub instructions which can 14542 /// add a register with the immediate without having to materialize the 14543 /// immediate into a register. 14544 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14545 // Same encoding for add/sub, just flip the sign. 14546 int64_t AbsImm = std::abs(Imm); 14547 if (!Subtarget->isThumb()) 14548 return ARM_AM::getSOImmVal(AbsImm) != -1; 14549 if (Subtarget->isThumb2()) 14550 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 14551 // Thumb1 only has 8-bit unsigned immediate. 14552 return AbsImm >= 0 && AbsImm <= 255; 14553 } 14554 14555 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 14556 bool isSEXTLoad, SDValue &Base, 14557 SDValue &Offset, bool &isInc, 14558 SelectionDAG &DAG) { 14559 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14560 return false; 14561 14562 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 14563 // AddressingMode 3 14564 Base = Ptr->getOperand(0); 14565 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14566 int RHSC = (int)RHS->getZExtValue(); 14567 if (RHSC < 0 && RHSC > -256) { 14568 assert(Ptr->getOpcode() == ISD::ADD); 14569 isInc = false; 14570 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14571 return true; 14572 } 14573 } 14574 isInc = (Ptr->getOpcode() == ISD::ADD); 14575 Offset = Ptr->getOperand(1); 14576 return true; 14577 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 14578 // AddressingMode 2 14579 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14580 int RHSC = (int)RHS->getZExtValue(); 14581 if (RHSC < 0 && RHSC > -0x1000) { 14582 assert(Ptr->getOpcode() == ISD::ADD); 14583 isInc = false; 14584 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14585 Base = Ptr->getOperand(0); 14586 return true; 14587 } 14588 } 14589 14590 if (Ptr->getOpcode() == ISD::ADD) { 14591 isInc = true; 14592 ARM_AM::ShiftOpc ShOpcVal= 14593 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 14594 if (ShOpcVal != ARM_AM::no_shift) { 14595 Base = Ptr->getOperand(1); 14596 Offset = Ptr->getOperand(0); 14597 } else { 14598 Base = Ptr->getOperand(0); 14599 Offset = Ptr->getOperand(1); 14600 } 14601 return true; 14602 } 14603 14604 isInc = (Ptr->getOpcode() == ISD::ADD); 14605 Base = Ptr->getOperand(0); 14606 Offset = Ptr->getOperand(1); 14607 return true; 14608 } 14609 14610 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 14611 return false; 14612 } 14613 14614 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 14615 bool isSEXTLoad, SDValue &Base, 14616 SDValue &Offset, bool &isInc, 14617 SelectionDAG &DAG) { 14618 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 14619 return false; 14620 14621 Base = Ptr->getOperand(0); 14622 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 14623 int RHSC = (int)RHS->getZExtValue(); 14624 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 14625 assert(Ptr->getOpcode() == ISD::ADD); 14626 isInc = false; 14627 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14628 return true; 14629 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 14630 isInc = Ptr->getOpcode() == ISD::ADD; 14631 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 14632 return true; 14633 } 14634 } 14635 14636 return false; 14637 } 14638 14639 /// getPreIndexedAddressParts - returns true by value, base pointer and 14640 /// offset pointer and addressing mode by reference if the node's address 14641 /// can be legally represented as pre-indexed load / store address. 14642 bool 14643 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 14644 SDValue &Offset, 14645 ISD::MemIndexedMode &AM, 14646 SelectionDAG &DAG) const { 14647 if (Subtarget->isThumb1Only()) 14648 return false; 14649 14650 EVT VT; 14651 SDValue Ptr; 14652 bool isSEXTLoad = false; 14653 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 14654 Ptr = LD->getBasePtr(); 14655 VT = LD->getMemoryVT(); 14656 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 14657 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 14658 Ptr = ST->getBasePtr(); 14659 VT = ST->getMemoryVT(); 14660 } else 14661 return false; 14662 14663 bool isInc; 14664 bool isLegal = false; 14665 if (Subtarget->isThumb2()) 14666 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 14667 Offset, isInc, DAG); 14668 else 14669 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 14670 Offset, isInc, DAG); 14671 if (!isLegal) 14672 return false; 14673 14674 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 14675 return true; 14676 } 14677 14678 /// getPostIndexedAddressParts - returns true by value, base pointer and 14679 /// offset pointer and addressing mode by reference if this node can be 14680 /// combined with a load / store to form a post-indexed load / store. 14681 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 14682 SDValue &Base, 14683 SDValue &Offset, 14684 ISD::MemIndexedMode &AM, 14685 SelectionDAG &DAG) const { 14686 EVT VT; 14687 SDValue Ptr; 14688 bool isSEXTLoad = false, isNonExt; 14689 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 14690 VT = LD->getMemoryVT(); 14691 Ptr = LD->getBasePtr(); 14692 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 14693 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 14694 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 14695 VT = ST->getMemoryVT(); 14696 Ptr = ST->getBasePtr(); 14697 isNonExt = !ST->isTruncatingStore(); 14698 } else 14699 return false; 14700 14701 if (Subtarget->isThumb1Only()) { 14702 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 14703 // must be non-extending/truncating, i32, with an offset of 4. 14704 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 14705 if (Op->getOpcode() != ISD::ADD || !isNonExt) 14706 return false; 14707 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 14708 if (!RHS || RHS->getZExtValue() != 4) 14709 return false; 14710 14711 Offset = Op->getOperand(1); 14712 Base = Op->getOperand(0); 14713 AM = ISD::POST_INC; 14714 return true; 14715 } 14716 14717 bool isInc; 14718 bool isLegal = false; 14719 if (Subtarget->isThumb2()) 14720 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14721 isInc, DAG); 14722 else 14723 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14724 isInc, DAG); 14725 if (!isLegal) 14726 return false; 14727 14728 if (Ptr != Base) { 14729 // Swap base ptr and offset to catch more post-index load / store when 14730 // it's legal. In Thumb2 mode, offset must be an immediate. 14731 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 14732 !Subtarget->isThumb2()) 14733 std::swap(Base, Offset); 14734 14735 // Post-indexed load / store update the base pointer. 14736 if (Ptr != Base) 14737 return false; 14738 } 14739 14740 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 14741 return true; 14742 } 14743 14744 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14745 KnownBits &Known, 14746 const APInt &DemandedElts, 14747 const SelectionDAG &DAG, 14748 unsigned Depth) const { 14749 unsigned BitWidth = Known.getBitWidth(); 14750 Known.resetAll(); 14751 switch (Op.getOpcode()) { 14752 default: break; 14753 case ARMISD::ADDC: 14754 case ARMISD::ADDE: 14755 case ARMISD::SUBC: 14756 case ARMISD::SUBE: 14757 // Special cases when we convert a carry to a boolean. 14758 if (Op.getResNo() == 0) { 14759 SDValue LHS = Op.getOperand(0); 14760 SDValue RHS = Op.getOperand(1); 14761 // (ADDE 0, 0, C) will give us a single bit. 14762 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 14763 isNullConstant(RHS)) { 14764 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 14765 return; 14766 } 14767 } 14768 break; 14769 case ARMISD::CMOV: { 14770 // Bits are known zero/one if known on the LHS and RHS. 14771 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 14772 if (Known.isUnknown()) 14773 return; 14774 14775 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 14776 Known.Zero &= KnownRHS.Zero; 14777 Known.One &= KnownRHS.One; 14778 return; 14779 } 14780 case ISD::INTRINSIC_W_CHAIN: { 14781 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 14782 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 14783 switch (IntID) { 14784 default: return; 14785 case Intrinsic::arm_ldaex: 14786 case Intrinsic::arm_ldrex: { 14787 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 14788 unsigned MemBits = VT.getScalarSizeInBits(); 14789 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 14790 return; 14791 } 14792 } 14793 } 14794 case ARMISD::BFI: { 14795 // Conservatively, we can recurse down the first operand 14796 // and just mask out all affected bits. 14797 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 14798 14799 // The operand to BFI is already a mask suitable for removing the bits it 14800 // sets. 14801 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 14802 const APInt &Mask = CI->getAPIntValue(); 14803 Known.Zero &= Mask; 14804 Known.One &= Mask; 14805 return; 14806 } 14807 case ARMISD::VGETLANEs: 14808 case ARMISD::VGETLANEu: { 14809 const SDValue &SrcSV = Op.getOperand(0); 14810 EVT VecVT = SrcSV.getValueType(); 14811 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 14812 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 14813 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 14814 assert(Pos->getAPIntValue().ult(NumSrcElts) && 14815 "VGETLANE index out of bounds"); 14816 unsigned Idx = Pos->getZExtValue(); 14817 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 14818 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 14819 14820 EVT VT = Op.getValueType(); 14821 const unsigned DstSz = VT.getScalarSizeInBits(); 14822 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 14823 (void)SrcSz; 14824 assert(SrcSz == Known.getBitWidth()); 14825 assert(DstSz > SrcSz); 14826 if (Op.getOpcode() == ARMISD::VGETLANEs) 14827 Known = Known.sext(DstSz); 14828 else { 14829 Known = Known.zext(DstSz, true /* extended bits are known zero */); 14830 } 14831 assert(DstSz == Known.getBitWidth()); 14832 break; 14833 } 14834 } 14835 } 14836 14837 bool 14838 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 14839 const APInt &DemandedAPInt, 14840 TargetLoweringOpt &TLO) const { 14841 // Delay optimization, so we don't have to deal with illegal types, or block 14842 // optimizations. 14843 if (!TLO.LegalOps) 14844 return false; 14845 14846 // Only optimize AND for now. 14847 if (Op.getOpcode() != ISD::AND) 14848 return false; 14849 14850 EVT VT = Op.getValueType(); 14851 14852 // Ignore vectors. 14853 if (VT.isVector()) 14854 return false; 14855 14856 assert(VT == MVT::i32 && "Unexpected integer type"); 14857 14858 // Make sure the RHS really is a constant. 14859 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14860 if (!C) 14861 return false; 14862 14863 unsigned Mask = C->getZExtValue(); 14864 14865 unsigned Demanded = DemandedAPInt.getZExtValue(); 14866 unsigned ShrunkMask = Mask & Demanded; 14867 unsigned ExpandedMask = Mask | ~Demanded; 14868 14869 // If the mask is all zeros, let the target-independent code replace the 14870 // result with zero. 14871 if (ShrunkMask == 0) 14872 return false; 14873 14874 // If the mask is all ones, erase the AND. (Currently, the target-independent 14875 // code won't do this, so we have to do it explicitly to avoid an infinite 14876 // loop in obscure cases.) 14877 if (ExpandedMask == ~0U) 14878 return TLO.CombineTo(Op, Op.getOperand(0)); 14879 14880 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 14881 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 14882 }; 14883 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 14884 if (NewMask == Mask) 14885 return true; 14886 SDLoc DL(Op); 14887 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 14888 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 14889 return TLO.CombineTo(Op, NewOp); 14890 }; 14891 14892 // Prefer uxtb mask. 14893 if (IsLegalMask(0xFF)) 14894 return UseMask(0xFF); 14895 14896 // Prefer uxth mask. 14897 if (IsLegalMask(0xFFFF)) 14898 return UseMask(0xFFFF); 14899 14900 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 14901 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 14902 if (ShrunkMask < 256) 14903 return UseMask(ShrunkMask); 14904 14905 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 14906 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 14907 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 14908 return UseMask(ExpandedMask); 14909 14910 // Potential improvements: 14911 // 14912 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 14913 // We could try to prefer Thumb1 immediates which can be lowered to a 14914 // two-instruction sequence. 14915 // We could try to recognize more legal ARM/Thumb2 immediates here. 14916 14917 return false; 14918 } 14919 14920 14921 //===----------------------------------------------------------------------===// 14922 // ARM Inline Assembly Support 14923 //===----------------------------------------------------------------------===// 14924 14925 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 14926 // Looking for "rev" which is V6+. 14927 if (!Subtarget->hasV6Ops()) 14928 return false; 14929 14930 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 14931 std::string AsmStr = IA->getAsmString(); 14932 SmallVector<StringRef, 4> AsmPieces; 14933 SplitString(AsmStr, AsmPieces, ";\n"); 14934 14935 switch (AsmPieces.size()) { 14936 default: return false; 14937 case 1: 14938 AsmStr = AsmPieces[0]; 14939 AsmPieces.clear(); 14940 SplitString(AsmStr, AsmPieces, " \t,"); 14941 14942 // rev $0, $1 14943 if (AsmPieces.size() == 3 && 14944 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 14945 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 14946 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14947 if (Ty && Ty->getBitWidth() == 32) 14948 return IntrinsicLowering::LowerToByteSwap(CI); 14949 } 14950 break; 14951 } 14952 14953 return false; 14954 } 14955 14956 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 14957 // At this point, we have to lower this constraint to something else, so we 14958 // lower it to an "r" or "w". However, by doing this we will force the result 14959 // to be in register, while the X constraint is much more permissive. 14960 // 14961 // Although we are correct (we are free to emit anything, without 14962 // constraints), we might break use cases that would expect us to be more 14963 // efficient and emit something else. 14964 if (!Subtarget->hasVFP2Base()) 14965 return "r"; 14966 if (ConstraintVT.isFloatingPoint()) 14967 return "w"; 14968 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 14969 (ConstraintVT.getSizeInBits() == 64 || 14970 ConstraintVT.getSizeInBits() == 128)) 14971 return "w"; 14972 14973 return "r"; 14974 } 14975 14976 /// getConstraintType - Given a constraint letter, return the type of 14977 /// constraint it is for this target. 14978 ARMTargetLowering::ConstraintType 14979 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 14980 unsigned S = Constraint.size(); 14981 if (S == 1) { 14982 switch (Constraint[0]) { 14983 default: break; 14984 case 'l': return C_RegisterClass; 14985 case 'w': return C_RegisterClass; 14986 case 'h': return C_RegisterClass; 14987 case 'x': return C_RegisterClass; 14988 case 't': return C_RegisterClass; 14989 case 'j': return C_Immediate; // Constant for movw. 14990 // An address with a single base register. Due to the way we 14991 // currently handle addresses it is the same as an 'r' memory constraint. 14992 case 'Q': return C_Memory; 14993 } 14994 } else if (S == 2) { 14995 switch (Constraint[0]) { 14996 default: break; 14997 case 'T': return C_RegisterClass; 14998 // All 'U+' constraints are addresses. 14999 case 'U': return C_Memory; 15000 } 15001 } 15002 return TargetLowering::getConstraintType(Constraint); 15003 } 15004 15005 /// Examine constraint type and operand type and determine a weight value. 15006 /// This object must already have been set up with the operand type 15007 /// and the current alternative constraint selected. 15008 TargetLowering::ConstraintWeight 15009 ARMTargetLowering::getSingleConstraintMatchWeight( 15010 AsmOperandInfo &info, const char *constraint) const { 15011 ConstraintWeight weight = CW_Invalid; 15012 Value *CallOperandVal = info.CallOperandVal; 15013 // If we don't have a value, we can't do a match, 15014 // but allow it at the lowest weight. 15015 if (!CallOperandVal) 15016 return CW_Default; 15017 Type *type = CallOperandVal->getType(); 15018 // Look at the constraint type. 15019 switch (*constraint) { 15020 default: 15021 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15022 break; 15023 case 'l': 15024 if (type->isIntegerTy()) { 15025 if (Subtarget->isThumb()) 15026 weight = CW_SpecificReg; 15027 else 15028 weight = CW_Register; 15029 } 15030 break; 15031 case 'w': 15032 if (type->isFloatingPointTy()) 15033 weight = CW_Register; 15034 break; 15035 } 15036 return weight; 15037 } 15038 15039 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 15040 15041 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 15042 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 15043 switch (Constraint.size()) { 15044 case 1: 15045 // GCC ARM Constraint Letters 15046 switch (Constraint[0]) { 15047 case 'l': // Low regs or general regs. 15048 if (Subtarget->isThumb()) 15049 return RCPair(0U, &ARM::tGPRRegClass); 15050 return RCPair(0U, &ARM::GPRRegClass); 15051 case 'h': // High regs or no regs. 15052 if (Subtarget->isThumb()) 15053 return RCPair(0U, &ARM::hGPRRegClass); 15054 break; 15055 case 'r': 15056 if (Subtarget->isThumb1Only()) 15057 return RCPair(0U, &ARM::tGPRRegClass); 15058 return RCPair(0U, &ARM::GPRRegClass); 15059 case 'w': 15060 if (VT == MVT::Other) 15061 break; 15062 if (VT == MVT::f32) 15063 return RCPair(0U, &ARM::SPRRegClass); 15064 if (VT.getSizeInBits() == 64) 15065 return RCPair(0U, &ARM::DPRRegClass); 15066 if (VT.getSizeInBits() == 128) 15067 return RCPair(0U, &ARM::QPRRegClass); 15068 break; 15069 case 'x': 15070 if (VT == MVT::Other) 15071 break; 15072 if (VT == MVT::f32) 15073 return RCPair(0U, &ARM::SPR_8RegClass); 15074 if (VT.getSizeInBits() == 64) 15075 return RCPair(0U, &ARM::DPR_8RegClass); 15076 if (VT.getSizeInBits() == 128) 15077 return RCPair(0U, &ARM::QPR_8RegClass); 15078 break; 15079 case 't': 15080 if (VT == MVT::Other) 15081 break; 15082 if (VT == MVT::f32 || VT == MVT::i32) 15083 return RCPair(0U, &ARM::SPRRegClass); 15084 if (VT.getSizeInBits() == 64) 15085 return RCPair(0U, &ARM::DPR_VFP2RegClass); 15086 if (VT.getSizeInBits() == 128) 15087 return RCPair(0U, &ARM::QPR_VFP2RegClass); 15088 break; 15089 } 15090 break; 15091 15092 case 2: 15093 if (Constraint[0] == 'T') { 15094 switch (Constraint[1]) { 15095 default: 15096 break; 15097 case 'e': 15098 return RCPair(0U, &ARM::tGPREvenRegClass); 15099 case 'o': 15100 return RCPair(0U, &ARM::tGPROddRegClass); 15101 } 15102 } 15103 break; 15104 15105 default: 15106 break; 15107 } 15108 15109 if (StringRef("{cc}").equals_lower(Constraint)) 15110 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 15111 15112 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15113 } 15114 15115 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15116 /// vector. If it is invalid, don't add anything to Ops. 15117 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15118 std::string &Constraint, 15119 std::vector<SDValue>&Ops, 15120 SelectionDAG &DAG) const { 15121 SDValue Result; 15122 15123 // Currently only support length 1 constraints. 15124 if (Constraint.length() != 1) return; 15125 15126 char ConstraintLetter = Constraint[0]; 15127 switch (ConstraintLetter) { 15128 default: break; 15129 case 'j': 15130 case 'I': case 'J': case 'K': case 'L': 15131 case 'M': case 'N': case 'O': 15132 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 15133 if (!C) 15134 return; 15135 15136 int64_t CVal64 = C->getSExtValue(); 15137 int CVal = (int) CVal64; 15138 // None of these constraints allow values larger than 32 bits. Check 15139 // that the value fits in an int. 15140 if (CVal != CVal64) 15141 return; 15142 15143 switch (ConstraintLetter) { 15144 case 'j': 15145 // Constant suitable for movw, must be between 0 and 15146 // 65535. 15147 if (Subtarget->hasV6T2Ops()) 15148 if (CVal >= 0 && CVal <= 65535) 15149 break; 15150 return; 15151 case 'I': 15152 if (Subtarget->isThumb1Only()) { 15153 // This must be a constant between 0 and 255, for ADD 15154 // immediates. 15155 if (CVal >= 0 && CVal <= 255) 15156 break; 15157 } else if (Subtarget->isThumb2()) { 15158 // A constant that can be used as an immediate value in a 15159 // data-processing instruction. 15160 if (ARM_AM::getT2SOImmVal(CVal) != -1) 15161 break; 15162 } else { 15163 // A constant that can be used as an immediate value in a 15164 // data-processing instruction. 15165 if (ARM_AM::getSOImmVal(CVal) != -1) 15166 break; 15167 } 15168 return; 15169 15170 case 'J': 15171 if (Subtarget->isThumb1Only()) { 15172 // This must be a constant between -255 and -1, for negated ADD 15173 // immediates. This can be used in GCC with an "n" modifier that 15174 // prints the negated value, for use with SUB instructions. It is 15175 // not useful otherwise but is implemented for compatibility. 15176 if (CVal >= -255 && CVal <= -1) 15177 break; 15178 } else { 15179 // This must be a constant between -4095 and 4095. It is not clear 15180 // what this constraint is intended for. Implemented for 15181 // compatibility with GCC. 15182 if (CVal >= -4095 && CVal <= 4095) 15183 break; 15184 } 15185 return; 15186 15187 case 'K': 15188 if (Subtarget->isThumb1Only()) { 15189 // A 32-bit value where only one byte has a nonzero value. Exclude 15190 // zero to match GCC. This constraint is used by GCC internally for 15191 // constants that can be loaded with a move/shift combination. 15192 // It is not useful otherwise but is implemented for compatibility. 15193 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 15194 break; 15195 } else if (Subtarget->isThumb2()) { 15196 // A constant whose bitwise inverse can be used as an immediate 15197 // value in a data-processing instruction. This can be used in GCC 15198 // with a "B" modifier that prints the inverted value, for use with 15199 // BIC and MVN instructions. It is not useful otherwise but is 15200 // implemented for compatibility. 15201 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 15202 break; 15203 } else { 15204 // A constant whose bitwise inverse can be used as an immediate 15205 // value in a data-processing instruction. This can be used in GCC 15206 // with a "B" modifier that prints the inverted value, for use with 15207 // BIC and MVN instructions. It is not useful otherwise but is 15208 // implemented for compatibility. 15209 if (ARM_AM::getSOImmVal(~CVal) != -1) 15210 break; 15211 } 15212 return; 15213 15214 case 'L': 15215 if (Subtarget->isThumb1Only()) { 15216 // This must be a constant between -7 and 7, 15217 // for 3-operand ADD/SUB immediate instructions. 15218 if (CVal >= -7 && CVal < 7) 15219 break; 15220 } else if (Subtarget->isThumb2()) { 15221 // A constant whose negation can be used as an immediate value in a 15222 // data-processing instruction. This can be used in GCC with an "n" 15223 // modifier that prints the negated value, for use with SUB 15224 // instructions. It is not useful otherwise but is implemented for 15225 // compatibility. 15226 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 15227 break; 15228 } else { 15229 // A constant whose negation can be used as an immediate value in a 15230 // data-processing instruction. This can be used in GCC with an "n" 15231 // modifier that prints the negated value, for use with SUB 15232 // instructions. It is not useful otherwise but is implemented for 15233 // compatibility. 15234 if (ARM_AM::getSOImmVal(-CVal) != -1) 15235 break; 15236 } 15237 return; 15238 15239 case 'M': 15240 if (Subtarget->isThumb1Only()) { 15241 // This must be a multiple of 4 between 0 and 1020, for 15242 // ADD sp + immediate. 15243 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 15244 break; 15245 } else { 15246 // A power of two or a constant between 0 and 32. This is used in 15247 // GCC for the shift amount on shifted register operands, but it is 15248 // useful in general for any shift amounts. 15249 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 15250 break; 15251 } 15252 return; 15253 15254 case 'N': 15255 if (Subtarget->isThumb()) { // FIXME thumb2 15256 // This must be a constant between 0 and 31, for shift amounts. 15257 if (CVal >= 0 && CVal <= 31) 15258 break; 15259 } 15260 return; 15261 15262 case 'O': 15263 if (Subtarget->isThumb()) { // FIXME thumb2 15264 // This must be a multiple of 4 between -508 and 508, for 15265 // ADD/SUB sp = sp + immediate. 15266 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 15267 break; 15268 } 15269 return; 15270 } 15271 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 15272 break; 15273 } 15274 15275 if (Result.getNode()) { 15276 Ops.push_back(Result); 15277 return; 15278 } 15279 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15280 } 15281 15282 static RTLIB::Libcall getDivRemLibcall( 15283 const SDNode *N, MVT::SimpleValueType SVT) { 15284 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 15285 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 15286 "Unhandled Opcode in getDivRemLibcall"); 15287 bool isSigned = N->getOpcode() == ISD::SDIVREM || 15288 N->getOpcode() == ISD::SREM; 15289 RTLIB::Libcall LC; 15290 switch (SVT) { 15291 default: llvm_unreachable("Unexpected request for libcall!"); 15292 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 15293 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 15294 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 15295 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 15296 } 15297 return LC; 15298 } 15299 15300 static TargetLowering::ArgListTy getDivRemArgList( 15301 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 15302 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 15303 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 15304 "Unhandled Opcode in getDivRemArgList"); 15305 bool isSigned = N->getOpcode() == ISD::SDIVREM || 15306 N->getOpcode() == ISD::SREM; 15307 TargetLowering::ArgListTy Args; 15308 TargetLowering::ArgListEntry Entry; 15309 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15310 EVT ArgVT = N->getOperand(i).getValueType(); 15311 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 15312 Entry.Node = N->getOperand(i); 15313 Entry.Ty = ArgTy; 15314 Entry.IsSExt = isSigned; 15315 Entry.IsZExt = !isSigned; 15316 Args.push_back(Entry); 15317 } 15318 if (Subtarget->isTargetWindows() && Args.size() >= 2) 15319 std::swap(Args[0], Args[1]); 15320 return Args; 15321 } 15322 15323 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 15324 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 15325 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 15326 Subtarget->isTargetWindows()) && 15327 "Register-based DivRem lowering only"); 15328 unsigned Opcode = Op->getOpcode(); 15329 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 15330 "Invalid opcode for Div/Rem lowering"); 15331 bool isSigned = (Opcode == ISD::SDIVREM); 15332 EVT VT = Op->getValueType(0); 15333 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 15334 SDLoc dl(Op); 15335 15336 // If the target has hardware divide, use divide + multiply + subtract: 15337 // div = a / b 15338 // rem = a - b * div 15339 // return {div, rem} 15340 // This should be lowered into UDIV/SDIV + MLS later on. 15341 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 15342 : Subtarget->hasDivideInARMMode(); 15343 if (hasDivide && Op->getValueType(0).isSimple() && 15344 Op->getSimpleValueType(0) == MVT::i32) { 15345 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 15346 const SDValue Dividend = Op->getOperand(0); 15347 const SDValue Divisor = Op->getOperand(1); 15348 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 15349 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 15350 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 15351 15352 SDValue Values[2] = {Div, Rem}; 15353 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 15354 } 15355 15356 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 15357 VT.getSimpleVT().SimpleTy); 15358 SDValue InChain = DAG.getEntryNode(); 15359 15360 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 15361 DAG.getContext(), 15362 Subtarget); 15363 15364 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 15365 getPointerTy(DAG.getDataLayout())); 15366 15367 Type *RetTy = StructType::get(Ty, Ty); 15368 15369 if (Subtarget->isTargetWindows()) 15370 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 15371 15372 TargetLowering::CallLoweringInfo CLI(DAG); 15373 CLI.setDebugLoc(dl).setChain(InChain) 15374 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 15375 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 15376 15377 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 15378 return CallInfo.first; 15379 } 15380 15381 // Lowers REM using divmod helpers 15382 // see RTABI section 4.2/4.3 15383 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 15384 // Build return types (div and rem) 15385 std::vector<Type*> RetTyParams; 15386 Type *RetTyElement; 15387 15388 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 15389 default: llvm_unreachable("Unexpected request for libcall!"); 15390 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 15391 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 15392 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 15393 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 15394 } 15395 15396 RetTyParams.push_back(RetTyElement); 15397 RetTyParams.push_back(RetTyElement); 15398 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 15399 Type *RetTy = StructType::get(*DAG.getContext(), ret); 15400 15401 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 15402 SimpleTy); 15403 SDValue InChain = DAG.getEntryNode(); 15404 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 15405 Subtarget); 15406 bool isSigned = N->getOpcode() == ISD::SREM; 15407 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 15408 getPointerTy(DAG.getDataLayout())); 15409 15410 if (Subtarget->isTargetWindows()) 15411 InChain = WinDBZCheckDenominator(DAG, N, InChain); 15412 15413 // Lower call 15414 CallLoweringInfo CLI(DAG); 15415 CLI.setChain(InChain) 15416 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 15417 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 15418 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 15419 15420 // Return second (rem) result operand (first contains div) 15421 SDNode *ResNode = CallResult.first.getNode(); 15422 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 15423 return ResNode->getOperand(1); 15424 } 15425 15426 SDValue 15427 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 15428 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 15429 SDLoc DL(Op); 15430 15431 // Get the inputs. 15432 SDValue Chain = Op.getOperand(0); 15433 SDValue Size = Op.getOperand(1); 15434 15435 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 15436 "no-stack-arg-probe")) { 15437 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 15438 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 15439 Chain = SP.getValue(1); 15440 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 15441 if (Align) 15442 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 15443 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 15444 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 15445 SDValue Ops[2] = { SP, Chain }; 15446 return DAG.getMergeValues(Ops, DL); 15447 } 15448 15449 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 15450 DAG.getConstant(2, DL, MVT::i32)); 15451 15452 SDValue Flag; 15453 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 15454 Flag = Chain.getValue(1); 15455 15456 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 15457 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 15458 15459 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 15460 Chain = NewSP.getValue(1); 15461 15462 SDValue Ops[2] = { NewSP, Chain }; 15463 return DAG.getMergeValues(Ops, DL); 15464 } 15465 15466 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 15467 SDValue SrcVal = Op.getOperand(0); 15468 const unsigned DstSz = Op.getValueType().getSizeInBits(); 15469 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 15470 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 15471 "Unexpected type for custom-lowering FP_EXTEND"); 15472 15473 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 15474 "With both FP DP and 16, any FP conversion is legal!"); 15475 15476 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 15477 "With FP16, 16 to 32 conversion is legal!"); 15478 15479 // Either we are converting from 16 -> 64, without FP16 and/or 15480 // FP.double-precision or without Armv8-fp. So we must do it in two 15481 // steps. 15482 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 15483 // without FP16. So we must do a function call. 15484 SDLoc Loc(Op); 15485 RTLIB::Libcall LC; 15486 if (SrcSz == 16) { 15487 // Instruction from 16 -> 32 15488 if (Subtarget->hasFP16()) 15489 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal); 15490 // Lib call from 16 -> 32 15491 else { 15492 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32); 15493 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15494 "Unexpected type for custom-lowering FP_EXTEND"); 15495 SrcVal = 15496 makeLibCall(DAG, LC, MVT::f32, SrcVal, /*isSigned*/ false, Loc).first; 15497 } 15498 } 15499 15500 if (DstSz != 64) 15501 return SrcVal; 15502 // For sure now SrcVal is 32 bits 15503 if (Subtarget->hasFP64()) // Instruction from 32 -> 64 15504 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal); 15505 15506 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64); 15507 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15508 "Unexpected type for custom-lowering FP_EXTEND"); 15509 return makeLibCall(DAG, LC, MVT::f64, SrcVal, /*isSigned*/ false, Loc).first; 15510 } 15511 15512 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 15513 SDValue SrcVal = Op.getOperand(0); 15514 EVT SrcVT = SrcVal.getValueType(); 15515 EVT DstVT = Op.getValueType(); 15516 const unsigned DstSz = Op.getValueType().getSizeInBits(); 15517 const unsigned SrcSz = SrcVT.getSizeInBits(); 15518 (void)DstSz; 15519 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 15520 "Unexpected type for custom-lowering FP_ROUND"); 15521 15522 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 15523 "With both FP DP and 16, any FP conversion is legal!"); 15524 15525 SDLoc Loc(Op); 15526 15527 // Instruction from 32 -> 16 if hasFP16 is valid 15528 if (SrcSz == 32 && Subtarget->hasFP16()) 15529 return Op; 15530 15531 // Lib call from 32 -> 16 / 64 -> [32, 16] 15532 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 15533 assert(LC != RTLIB::UNKNOWN_LIBCALL && 15534 "Unexpected type for custom-lowering FP_ROUND"); 15535 return makeLibCall(DAG, LC, DstVT, SrcVal, /*isSigned*/ false, Loc).first; 15536 } 15537 15538 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 15539 SelectionDAG &DAG) const { 15540 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 15541 MVT HalfT = MVT::i32; 15542 SDLoc dl(N); 15543 SDValue Hi, Lo, Tmp; 15544 15545 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 15546 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 15547 return ; 15548 15549 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 15550 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 15551 15552 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 15553 DAG.getConstant(0, dl, HalfT)); 15554 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 15555 DAG.getConstant(1, dl, HalfT)); 15556 15557 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 15558 DAG.getConstant(OpTypeBits - 1, dl, 15559 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 15560 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 15561 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 15562 SDValue(Lo.getNode(), 1)); 15563 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 15564 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 15565 15566 Results.push_back(Lo); 15567 Results.push_back(Hi); 15568 } 15569 15570 bool 15571 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15572 // The ARM target isn't yet aware of offsets. 15573 return false; 15574 } 15575 15576 bool ARM::isBitFieldInvertedMask(unsigned v) { 15577 if (v == 0xffffffff) 15578 return false; 15579 15580 // there can be 1's on either or both "outsides", all the "inside" 15581 // bits must be 0's 15582 return isShiftedMask_32(~v); 15583 } 15584 15585 /// isFPImmLegal - Returns true if the target can instruction select the 15586 /// specified FP immediate natively. If false, the legalizer will 15587 /// materialize the FP immediate as a load from a constant pool. 15588 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15589 bool ForCodeSize) const { 15590 if (!Subtarget->hasVFP3Base()) 15591 return false; 15592 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 15593 return ARM_AM::getFP16Imm(Imm) != -1; 15594 if (VT == MVT::f32) 15595 return ARM_AM::getFP32Imm(Imm) != -1; 15596 if (VT == MVT::f64 && Subtarget->hasFP64()) 15597 return ARM_AM::getFP64Imm(Imm) != -1; 15598 return false; 15599 } 15600 15601 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 15602 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 15603 /// specified in the intrinsic calls. 15604 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15605 const CallInst &I, 15606 MachineFunction &MF, 15607 unsigned Intrinsic) const { 15608 switch (Intrinsic) { 15609 case Intrinsic::arm_neon_vld1: 15610 case Intrinsic::arm_neon_vld2: 15611 case Intrinsic::arm_neon_vld3: 15612 case Intrinsic::arm_neon_vld4: 15613 case Intrinsic::arm_neon_vld2lane: 15614 case Intrinsic::arm_neon_vld3lane: 15615 case Intrinsic::arm_neon_vld4lane: 15616 case Intrinsic::arm_neon_vld2dup: 15617 case Intrinsic::arm_neon_vld3dup: 15618 case Intrinsic::arm_neon_vld4dup: { 15619 Info.opc = ISD::INTRINSIC_W_CHAIN; 15620 // Conservatively set memVT to the entire set of vectors loaded. 15621 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15622 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 15623 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15624 Info.ptrVal = I.getArgOperand(0); 15625 Info.offset = 0; 15626 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 15627 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 15628 // volatile loads with NEON intrinsics not supported 15629 Info.flags = MachineMemOperand::MOLoad; 15630 return true; 15631 } 15632 case Intrinsic::arm_neon_vld1x2: 15633 case Intrinsic::arm_neon_vld1x3: 15634 case Intrinsic::arm_neon_vld1x4: { 15635 Info.opc = ISD::INTRINSIC_W_CHAIN; 15636 // Conservatively set memVT to the entire set of vectors loaded. 15637 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15638 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 15639 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15640 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 15641 Info.offset = 0; 15642 Info.align.reset(); 15643 // volatile loads with NEON intrinsics not supported 15644 Info.flags = MachineMemOperand::MOLoad; 15645 return true; 15646 } 15647 case Intrinsic::arm_neon_vst1: 15648 case Intrinsic::arm_neon_vst2: 15649 case Intrinsic::arm_neon_vst3: 15650 case Intrinsic::arm_neon_vst4: 15651 case Intrinsic::arm_neon_vst2lane: 15652 case Intrinsic::arm_neon_vst3lane: 15653 case Intrinsic::arm_neon_vst4lane: { 15654 Info.opc = ISD::INTRINSIC_VOID; 15655 // Conservatively set memVT to the entire set of vectors stored. 15656 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15657 unsigned NumElts = 0; 15658 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 15659 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 15660 if (!ArgTy->isVectorTy()) 15661 break; 15662 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 15663 } 15664 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15665 Info.ptrVal = I.getArgOperand(0); 15666 Info.offset = 0; 15667 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 15668 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue()); 15669 // volatile stores with NEON intrinsics not supported 15670 Info.flags = MachineMemOperand::MOStore; 15671 return true; 15672 } 15673 case Intrinsic::arm_neon_vst1x2: 15674 case Intrinsic::arm_neon_vst1x3: 15675 case Intrinsic::arm_neon_vst1x4: { 15676 Info.opc = ISD::INTRINSIC_VOID; 15677 // Conservatively set memVT to the entire set of vectors stored. 15678 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15679 unsigned NumElts = 0; 15680 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 15681 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 15682 if (!ArgTy->isVectorTy()) 15683 break; 15684 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 15685 } 15686 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 15687 Info.ptrVal = I.getArgOperand(0); 15688 Info.offset = 0; 15689 Info.align.reset(); 15690 // volatile stores with NEON intrinsics not supported 15691 Info.flags = MachineMemOperand::MOStore; 15692 return true; 15693 } 15694 case Intrinsic::arm_ldaex: 15695 case Intrinsic::arm_ldrex: { 15696 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15697 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 15698 Info.opc = ISD::INTRINSIC_W_CHAIN; 15699 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15700 Info.ptrVal = I.getArgOperand(0); 15701 Info.offset = 0; 15702 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 15703 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15704 return true; 15705 } 15706 case Intrinsic::arm_stlex: 15707 case Intrinsic::arm_strex: { 15708 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15709 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 15710 Info.opc = ISD::INTRINSIC_W_CHAIN; 15711 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15712 Info.ptrVal = I.getArgOperand(1); 15713 Info.offset = 0; 15714 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 15715 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15716 return true; 15717 } 15718 case Intrinsic::arm_stlexd: 15719 case Intrinsic::arm_strexd: 15720 Info.opc = ISD::INTRINSIC_W_CHAIN; 15721 Info.memVT = MVT::i64; 15722 Info.ptrVal = I.getArgOperand(2); 15723 Info.offset = 0; 15724 Info.align = Align(8); 15725 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15726 return true; 15727 15728 case Intrinsic::arm_ldaexd: 15729 case Intrinsic::arm_ldrexd: 15730 Info.opc = ISD::INTRINSIC_W_CHAIN; 15731 Info.memVT = MVT::i64; 15732 Info.ptrVal = I.getArgOperand(0); 15733 Info.offset = 0; 15734 Info.align = Align(8); 15735 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15736 return true; 15737 15738 default: 15739 break; 15740 } 15741 15742 return false; 15743 } 15744 15745 /// Returns true if it is beneficial to convert a load of a constant 15746 /// to just the constant itself. 15747 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15748 Type *Ty) const { 15749 assert(Ty->isIntegerTy()); 15750 15751 unsigned Bits = Ty->getPrimitiveSizeInBits(); 15752 if (Bits == 0 || Bits > 32) 15753 return false; 15754 return true; 15755 } 15756 15757 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 15758 unsigned Index) const { 15759 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 15760 return false; 15761 15762 return (Index == 0 || Index == ResVT.getVectorNumElements()); 15763 } 15764 15765 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 15766 ARM_MB::MemBOpt Domain) const { 15767 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15768 15769 // First, if the target has no DMB, see what fallback we can use. 15770 if (!Subtarget->hasDataBarrier()) { 15771 // Some ARMv6 cpus can support data barriers with an mcr instruction. 15772 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 15773 // here. 15774 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 15775 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 15776 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 15777 Builder.getInt32(0), Builder.getInt32(7), 15778 Builder.getInt32(10), Builder.getInt32(5)}; 15779 return Builder.CreateCall(MCR, args); 15780 } else { 15781 // Instead of using barriers, atomic accesses on these subtargets use 15782 // libcalls. 15783 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 15784 } 15785 } else { 15786 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 15787 // Only a full system barrier exists in the M-class architectures. 15788 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 15789 Constant *CDomain = Builder.getInt32(Domain); 15790 return Builder.CreateCall(DMB, CDomain); 15791 } 15792 } 15793 15794 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 15795 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 15796 Instruction *Inst, 15797 AtomicOrdering Ord) const { 15798 switch (Ord) { 15799 case AtomicOrdering::NotAtomic: 15800 case AtomicOrdering::Unordered: 15801 llvm_unreachable("Invalid fence: unordered/non-atomic"); 15802 case AtomicOrdering::Monotonic: 15803 case AtomicOrdering::Acquire: 15804 return nullptr; // Nothing to do 15805 case AtomicOrdering::SequentiallyConsistent: 15806 if (!Inst->hasAtomicStore()) 15807 return nullptr; // Nothing to do 15808 LLVM_FALLTHROUGH; 15809 case AtomicOrdering::Release: 15810 case AtomicOrdering::AcquireRelease: 15811 if (Subtarget->preferISHSTBarriers()) 15812 return makeDMB(Builder, ARM_MB::ISHST); 15813 // FIXME: add a comment with a link to documentation justifying this. 15814 else 15815 return makeDMB(Builder, ARM_MB::ISH); 15816 } 15817 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 15818 } 15819 15820 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 15821 Instruction *Inst, 15822 AtomicOrdering Ord) const { 15823 switch (Ord) { 15824 case AtomicOrdering::NotAtomic: 15825 case AtomicOrdering::Unordered: 15826 llvm_unreachable("Invalid fence: unordered/not-atomic"); 15827 case AtomicOrdering::Monotonic: 15828 case AtomicOrdering::Release: 15829 return nullptr; // Nothing to do 15830 case AtomicOrdering::Acquire: 15831 case AtomicOrdering::AcquireRelease: 15832 case AtomicOrdering::SequentiallyConsistent: 15833 return makeDMB(Builder, ARM_MB::ISH); 15834 } 15835 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 15836 } 15837 15838 // Loads and stores less than 64-bits are already atomic; ones above that 15839 // are doomed anyway, so defer to the default libcall and blame the OS when 15840 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15841 // anything for those. 15842 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 15843 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 15844 return (Size == 64) && !Subtarget->isMClass(); 15845 } 15846 15847 // Loads and stores less than 64-bits are already atomic; ones above that 15848 // are doomed anyway, so defer to the default libcall and blame the OS when 15849 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15850 // anything for those. 15851 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 15852 // guarantee, see DDI0406C ARM architecture reference manual, 15853 // sections A8.8.72-74 LDRD) 15854 TargetLowering::AtomicExpansionKind 15855 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 15856 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 15857 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 15858 : AtomicExpansionKind::None; 15859 } 15860 15861 // For the real atomic operations, we have ldrex/strex up to 32 bits, 15862 // and up to 64 bits on the non-M profiles 15863 TargetLowering::AtomicExpansionKind 15864 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 15865 if (AI->isFloatingPointOperation()) 15866 return AtomicExpansionKind::CmpXChg; 15867 15868 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 15869 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 15870 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 15871 ? AtomicExpansionKind::LLSC 15872 : AtomicExpansionKind::None; 15873 } 15874 15875 TargetLowering::AtomicExpansionKind 15876 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 15877 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 15878 // implement cmpxchg without spilling. If the address being exchanged is also 15879 // on the stack and close enough to the spill slot, this can lead to a 15880 // situation where the monitor always gets cleared and the atomic operation 15881 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 15882 bool HasAtomicCmpXchg = 15883 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 15884 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 15885 return AtomicExpansionKind::LLSC; 15886 return AtomicExpansionKind::None; 15887 } 15888 15889 bool ARMTargetLowering::shouldInsertFencesForAtomic( 15890 const Instruction *I) const { 15891 return InsertFencesForAtomic; 15892 } 15893 15894 // This has so far only been implemented for MachO. 15895 bool ARMTargetLowering::useLoadStackGuardNode() const { 15896 return Subtarget->isTargetMachO(); 15897 } 15898 15899 void ARMTargetLowering::insertSSPDeclarations(Module &M) const { 15900 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 15901 return TargetLowering::insertSSPDeclarations(M); 15902 15903 // MSVC CRT has a global variable holding security cookie. 15904 M.getOrInsertGlobal("__security_cookie", 15905 Type::getInt8PtrTy(M.getContext())); 15906 15907 // MSVC CRT has a function to validate security cookie. 15908 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 15909 "__security_check_cookie", Type::getVoidTy(M.getContext()), 15910 Type::getInt8PtrTy(M.getContext())); 15911 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) 15912 F->addAttribute(1, Attribute::AttrKind::InReg); 15913 } 15914 15915 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const { 15916 // MSVC CRT has a global variable holding security cookie. 15917 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 15918 return M.getGlobalVariable("__security_cookie"); 15919 return TargetLowering::getSDagStackGuard(M); 15920 } 15921 15922 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const { 15923 // MSVC CRT has a function to validate security cookie. 15924 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 15925 return M.getFunction("__security_check_cookie"); 15926 return TargetLowering::getSSPStackGuardCheck(M); 15927 } 15928 15929 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 15930 unsigned &Cost) const { 15931 // If we do not have NEON, vector types are not natively supported. 15932 if (!Subtarget->hasNEON()) 15933 return false; 15934 15935 // Floating point values and vector values map to the same register file. 15936 // Therefore, although we could do a store extract of a vector type, this is 15937 // better to leave at float as we have more freedom in the addressing mode for 15938 // those. 15939 if (VectorTy->isFPOrFPVectorTy()) 15940 return false; 15941 15942 // If the index is unknown at compile time, this is very expensive to lower 15943 // and it is not possible to combine the store with the extract. 15944 if (!isa<ConstantInt>(Idx)) 15945 return false; 15946 15947 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 15948 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 15949 // We can do a store + vector extract on any vector that fits perfectly in a D 15950 // or Q register. 15951 if (BitWidth == 64 || BitWidth == 128) { 15952 Cost = 0; 15953 return true; 15954 } 15955 return false; 15956 } 15957 15958 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 15959 return Subtarget->hasV6T2Ops(); 15960 } 15961 15962 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 15963 return Subtarget->hasV6T2Ops(); 15964 } 15965 15966 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 15967 return !Subtarget->hasMinSize(); 15968 } 15969 15970 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 15971 AtomicOrdering Ord) const { 15972 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15973 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 15974 bool IsAcquire = isAcquireOrStronger(Ord); 15975 15976 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 15977 // intrinsic must return {i32, i32} and we have to recombine them into a 15978 // single i64 here. 15979 if (ValTy->getPrimitiveSizeInBits() == 64) { 15980 Intrinsic::ID Int = 15981 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 15982 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 15983 15984 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 15985 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 15986 15987 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 15988 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 15989 if (!Subtarget->isLittle()) 15990 std::swap (Lo, Hi); 15991 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 15992 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 15993 return Builder.CreateOr( 15994 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 15995 } 15996 15997 Type *Tys[] = { Addr->getType() }; 15998 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 15999 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 16000 16001 return Builder.CreateTruncOrBitCast( 16002 Builder.CreateCall(Ldrex, Addr), 16003 cast<PointerType>(Addr->getType())->getElementType()); 16004 } 16005 16006 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 16007 IRBuilder<> &Builder) const { 16008 if (!Subtarget->hasV7Ops()) 16009 return; 16010 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16011 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 16012 } 16013 16014 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 16015 Value *Addr, 16016 AtomicOrdering Ord) const { 16017 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16018 bool IsRelease = isReleaseOrStronger(Ord); 16019 16020 // Since the intrinsics must have legal type, the i64 intrinsics take two 16021 // parameters: "i32, i32". We must marshal Val into the appropriate form 16022 // before the call. 16023 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 16024 Intrinsic::ID Int = 16025 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 16026 Function *Strex = Intrinsic::getDeclaration(M, Int); 16027 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 16028 16029 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 16030 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 16031 if (!Subtarget->isLittle()) 16032 std::swap(Lo, Hi); 16033 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16034 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 16035 } 16036 16037 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 16038 Type *Tys[] = { Addr->getType() }; 16039 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 16040 16041 return Builder.CreateCall( 16042 Strex, {Builder.CreateZExtOrBitCast( 16043 Val, Strex->getFunctionType()->getParamType(0)), 16044 Addr}); 16045 } 16046 16047 16048 bool ARMTargetLowering::alignLoopsWithOptSize() const { 16049 return Subtarget->isMClass(); 16050 } 16051 16052 /// A helper function for determining the number of interleaved accesses we 16053 /// will generate when lowering accesses of the given type. 16054 unsigned 16055 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 16056 const DataLayout &DL) const { 16057 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 16058 } 16059 16060 bool ARMTargetLowering::isLegalInterleavedAccessType( 16061 VectorType *VecTy, const DataLayout &DL) const { 16062 16063 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 16064 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 16065 16066 // Ensure the vector doesn't have f16 elements. Even though we could do an 16067 // i16 vldN, we can't hold the f16 vectors and will end up converting via 16068 // f32. 16069 if (VecTy->getElementType()->isHalfTy()) 16070 return false; 16071 16072 // Ensure the number of vector elements is greater than 1. 16073 if (VecTy->getNumElements() < 2) 16074 return false; 16075 16076 // Ensure the element type is legal. 16077 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 16078 return false; 16079 16080 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 16081 // 128 will be split into multiple interleaved accesses. 16082 return VecSize == 64 || VecSize % 128 == 0; 16083 } 16084 16085 /// Lower an interleaved load into a vldN intrinsic. 16086 /// 16087 /// E.g. Lower an interleaved load (Factor = 2): 16088 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 16089 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 16090 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 16091 /// 16092 /// Into: 16093 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 16094 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 16095 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 16096 bool ARMTargetLowering::lowerInterleavedLoad( 16097 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 16098 ArrayRef<unsigned> Indices, unsigned Factor) const { 16099 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 16100 "Invalid interleave factor"); 16101 assert(!Shuffles.empty() && "Empty shufflevector input"); 16102 assert(Shuffles.size() == Indices.size() && 16103 "Unmatched number of shufflevectors and indices"); 16104 16105 VectorType *VecTy = Shuffles[0]->getType(); 16106 Type *EltTy = VecTy->getVectorElementType(); 16107 16108 const DataLayout &DL = LI->getModule()->getDataLayout(); 16109 16110 // Skip if we do not have NEON and skip illegal vector types. We can 16111 // "legalize" wide vector types into multiple interleaved accesses as long as 16112 // the vector types are divisible by 128. 16113 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 16114 return false; 16115 16116 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 16117 16118 // A pointer vector can not be the return type of the ldN intrinsics. Need to 16119 // load integer vectors first and then convert to pointer vectors. 16120 if (EltTy->isPointerTy()) 16121 VecTy = 16122 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 16123 16124 IRBuilder<> Builder(LI); 16125 16126 // The base address of the load. 16127 Value *BaseAddr = LI->getPointerOperand(); 16128 16129 if (NumLoads > 1) { 16130 // If we're going to generate more than one load, reset the sub-vector type 16131 // to something legal. 16132 VecTy = VectorType::get(VecTy->getVectorElementType(), 16133 VecTy->getVectorNumElements() / NumLoads); 16134 16135 // We will compute the pointer operand of each load from the original base 16136 // address using GEPs. Cast the base address to a pointer to the scalar 16137 // element type. 16138 BaseAddr = Builder.CreateBitCast( 16139 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 16140 LI->getPointerAddressSpace())); 16141 } 16142 16143 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 16144 16145 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 16146 Type *Tys[] = {VecTy, Int8Ptr}; 16147 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 16148 Intrinsic::arm_neon_vld3, 16149 Intrinsic::arm_neon_vld4}; 16150 Function *VldnFunc = 16151 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 16152 16153 // Holds sub-vectors extracted from the load intrinsic return values. The 16154 // sub-vectors are associated with the shufflevector instructions they will 16155 // replace. 16156 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 16157 16158 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 16159 // If we're generating more than one load, compute the base address of 16160 // subsequent loads as an offset from the previous. 16161 if (LoadCount > 0) 16162 BaseAddr = 16163 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 16164 VecTy->getVectorNumElements() * Factor); 16165 16166 SmallVector<Value *, 2> Ops; 16167 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 16168 Ops.push_back(Builder.getInt32(LI->getAlignment())); 16169 16170 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 16171 16172 // Replace uses of each shufflevector with the corresponding vector loaded 16173 // by ldN. 16174 for (unsigned i = 0; i < Shuffles.size(); i++) { 16175 ShuffleVectorInst *SV = Shuffles[i]; 16176 unsigned Index = Indices[i]; 16177 16178 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 16179 16180 // Convert the integer vector to pointer vector if the element is pointer. 16181 if (EltTy->isPointerTy()) 16182 SubVec = Builder.CreateIntToPtr( 16183 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 16184 VecTy->getVectorNumElements())); 16185 16186 SubVecs[SV].push_back(SubVec); 16187 } 16188 } 16189 16190 // Replace uses of the shufflevector instructions with the sub-vectors 16191 // returned by the load intrinsic. If a shufflevector instruction is 16192 // associated with more than one sub-vector, those sub-vectors will be 16193 // concatenated into a single wide vector. 16194 for (ShuffleVectorInst *SVI : Shuffles) { 16195 auto &SubVec = SubVecs[SVI]; 16196 auto *WideVec = 16197 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 16198 SVI->replaceAllUsesWith(WideVec); 16199 } 16200 16201 return true; 16202 } 16203 16204 /// Lower an interleaved store into a vstN intrinsic. 16205 /// 16206 /// E.g. Lower an interleaved store (Factor = 3): 16207 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 16208 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 16209 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 16210 /// 16211 /// Into: 16212 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 16213 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 16214 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 16215 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 16216 /// 16217 /// Note that the new shufflevectors will be removed and we'll only generate one 16218 /// vst3 instruction in CodeGen. 16219 /// 16220 /// Example for a more general valid mask (Factor 3). Lower: 16221 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 16222 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 16223 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 16224 /// 16225 /// Into: 16226 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 16227 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 16228 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 16229 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 16230 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 16231 ShuffleVectorInst *SVI, 16232 unsigned Factor) const { 16233 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 16234 "Invalid interleave factor"); 16235 16236 VectorType *VecTy = SVI->getType(); 16237 assert(VecTy->getVectorNumElements() % Factor == 0 && 16238 "Invalid interleaved store"); 16239 16240 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 16241 Type *EltTy = VecTy->getVectorElementType(); 16242 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 16243 16244 const DataLayout &DL = SI->getModule()->getDataLayout(); 16245 16246 // Skip if we do not have NEON and skip illegal vector types. We can 16247 // "legalize" wide vector types into multiple interleaved accesses as long as 16248 // the vector types are divisible by 128. 16249 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 16250 return false; 16251 16252 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 16253 16254 Value *Op0 = SVI->getOperand(0); 16255 Value *Op1 = SVI->getOperand(1); 16256 IRBuilder<> Builder(SI); 16257 16258 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 16259 // vectors to integer vectors. 16260 if (EltTy->isPointerTy()) { 16261 Type *IntTy = DL.getIntPtrType(EltTy); 16262 16263 // Convert to the corresponding integer vector. 16264 Type *IntVecTy = 16265 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 16266 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 16267 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 16268 16269 SubVecTy = VectorType::get(IntTy, LaneLen); 16270 } 16271 16272 // The base address of the store. 16273 Value *BaseAddr = SI->getPointerOperand(); 16274 16275 if (NumStores > 1) { 16276 // If we're going to generate more than one store, reset the lane length 16277 // and sub-vector type to something legal. 16278 LaneLen /= NumStores; 16279 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 16280 16281 // We will compute the pointer operand of each store from the original base 16282 // address using GEPs. Cast the base address to a pointer to the scalar 16283 // element type. 16284 BaseAddr = Builder.CreateBitCast( 16285 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 16286 SI->getPointerAddressSpace())); 16287 } 16288 16289 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 16290 16291 auto Mask = SVI->getShuffleMask(); 16292 16293 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 16294 Type *Tys[] = {Int8Ptr, SubVecTy}; 16295 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 16296 Intrinsic::arm_neon_vst3, 16297 Intrinsic::arm_neon_vst4}; 16298 16299 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 16300 // If we generating more than one store, we compute the base address of 16301 // subsequent stores as an offset from the previous. 16302 if (StoreCount > 0) 16303 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 16304 BaseAddr, LaneLen * Factor); 16305 16306 SmallVector<Value *, 6> Ops; 16307 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 16308 16309 Function *VstNFunc = 16310 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 16311 16312 // Split the shufflevector operands into sub vectors for the new vstN call. 16313 for (unsigned i = 0; i < Factor; i++) { 16314 unsigned IdxI = StoreCount * LaneLen * Factor + i; 16315 if (Mask[IdxI] >= 0) { 16316 Ops.push_back(Builder.CreateShuffleVector( 16317 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 16318 } else { 16319 unsigned StartMask = 0; 16320 for (unsigned j = 1; j < LaneLen; j++) { 16321 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 16322 if (Mask[IdxJ * Factor + IdxI] >= 0) { 16323 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 16324 break; 16325 } 16326 } 16327 // Note: If all elements in a chunk are undefs, StartMask=0! 16328 // Note: Filling undef gaps with random elements is ok, since 16329 // those elements were being written anyway (with undefs). 16330 // In the case of all undefs we're defaulting to using elems from 0 16331 // Note: StartMask cannot be negative, it's checked in 16332 // isReInterleaveMask 16333 Ops.push_back(Builder.CreateShuffleVector( 16334 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 16335 } 16336 } 16337 16338 Ops.push_back(Builder.getInt32(SI->getAlignment())); 16339 Builder.CreateCall(VstNFunc, Ops); 16340 } 16341 return true; 16342 } 16343 16344 enum HABaseType { 16345 HA_UNKNOWN = 0, 16346 HA_FLOAT, 16347 HA_DOUBLE, 16348 HA_VECT64, 16349 HA_VECT128 16350 }; 16351 16352 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 16353 uint64_t &Members) { 16354 if (auto *ST = dyn_cast<StructType>(Ty)) { 16355 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 16356 uint64_t SubMembers = 0; 16357 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 16358 return false; 16359 Members += SubMembers; 16360 } 16361 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 16362 uint64_t SubMembers = 0; 16363 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 16364 return false; 16365 Members += SubMembers * AT->getNumElements(); 16366 } else if (Ty->isFloatTy()) { 16367 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 16368 return false; 16369 Members = 1; 16370 Base = HA_FLOAT; 16371 } else if (Ty->isDoubleTy()) { 16372 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 16373 return false; 16374 Members = 1; 16375 Base = HA_DOUBLE; 16376 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 16377 Members = 1; 16378 switch (Base) { 16379 case HA_FLOAT: 16380 case HA_DOUBLE: 16381 return false; 16382 case HA_VECT64: 16383 return VT->getBitWidth() == 64; 16384 case HA_VECT128: 16385 return VT->getBitWidth() == 128; 16386 case HA_UNKNOWN: 16387 switch (VT->getBitWidth()) { 16388 case 64: 16389 Base = HA_VECT64; 16390 return true; 16391 case 128: 16392 Base = HA_VECT128; 16393 return true; 16394 default: 16395 return false; 16396 } 16397 } 16398 } 16399 16400 return (Members > 0 && Members <= 4); 16401 } 16402 16403 /// Return the correct alignment for the current calling convention. 16404 unsigned 16405 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 16406 DataLayout DL) const { 16407 if (!ArgTy->isVectorTy()) 16408 return DL.getABITypeAlignment(ArgTy); 16409 16410 // Avoid over-aligning vector parameters. It would require realigning the 16411 // stack and waste space for no real benefit. 16412 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 16413 } 16414 16415 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 16416 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 16417 /// passing according to AAPCS rules. 16418 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 16419 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 16420 if (getEffectiveCallingConv(CallConv, isVarArg) != 16421 CallingConv::ARM_AAPCS_VFP) 16422 return false; 16423 16424 HABaseType Base = HA_UNKNOWN; 16425 uint64_t Members = 0; 16426 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 16427 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 16428 16429 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 16430 return IsHA || IsIntArray; 16431 } 16432 16433 unsigned ARMTargetLowering::getExceptionPointerRegister( 16434 const Constant *PersonalityFn) const { 16435 // Platforms which do not use SjLj EH may return values in these registers 16436 // via the personality function. 16437 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 16438 } 16439 16440 unsigned ARMTargetLowering::getExceptionSelectorRegister( 16441 const Constant *PersonalityFn) const { 16442 // Platforms which do not use SjLj EH may return values in these registers 16443 // via the personality function. 16444 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 16445 } 16446 16447 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 16448 // Update IsSplitCSR in ARMFunctionInfo. 16449 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 16450 AFI->setIsSplitCSR(true); 16451 } 16452 16453 void ARMTargetLowering::insertCopiesSplitCSR( 16454 MachineBasicBlock *Entry, 16455 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 16456 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 16457 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 16458 if (!IStart) 16459 return; 16460 16461 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 16462 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 16463 MachineBasicBlock::iterator MBBI = Entry->begin(); 16464 for (const MCPhysReg *I = IStart; *I; ++I) { 16465 const TargetRegisterClass *RC = nullptr; 16466 if (ARM::GPRRegClass.contains(*I)) 16467 RC = &ARM::GPRRegClass; 16468 else if (ARM::DPRRegClass.contains(*I)) 16469 RC = &ARM::DPRRegClass; 16470 else 16471 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 16472 16473 unsigned NewVR = MRI->createVirtualRegister(RC); 16474 // Create copy from CSR to a virtual register. 16475 // FIXME: this currently does not emit CFI pseudo-instructions, it works 16476 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 16477 // nounwind. If we want to generalize this later, we may need to emit 16478 // CFI pseudo-instructions. 16479 assert(Entry->getParent()->getFunction().hasFnAttribute( 16480 Attribute::NoUnwind) && 16481 "Function should be nounwind in insertCopiesSplitCSR!"); 16482 Entry->addLiveIn(*I); 16483 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 16484 .addReg(*I); 16485 16486 // Insert the copy-back instructions right before the terminator. 16487 for (auto *Exit : Exits) 16488 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 16489 TII->get(TargetOpcode::COPY), *I) 16490 .addReg(NewVR); 16491 } 16492 } 16493 16494 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 16495 MF.getFrameInfo().computeMaxCallFrameSize(MF); 16496 TargetLoweringBase::finalizeLowering(MF); 16497 } 16498