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 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 225 const ARMSubtarget &STI) 226 : TargetLowering(TM), Subtarget(&STI) { 227 RegInfo = Subtarget->getRegisterInfo(); 228 Itins = Subtarget->getInstrItineraryData(); 229 230 setBooleanContents(ZeroOrOneBooleanContent); 231 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 232 233 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 234 !Subtarget->isTargetWatchOS()) { 235 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 236 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 237 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 238 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 239 : CallingConv::ARM_AAPCS); 240 } 241 242 if (Subtarget->isTargetMachO()) { 243 // Uses VFP for Thumb libfuncs if available. 244 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 245 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 246 static const struct { 247 const RTLIB::Libcall Op; 248 const char * const Name; 249 const ISD::CondCode Cond; 250 } LibraryCalls[] = { 251 // Single-precision floating-point arithmetic. 252 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 253 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 254 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 255 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 256 257 // Double-precision floating-point arithmetic. 258 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 259 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 260 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 261 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 262 263 // Single-precision comparisons. 264 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 265 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 266 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 267 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 268 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 269 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 270 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 271 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 272 273 // Double-precision comparisons. 274 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 275 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 276 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 277 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 278 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 279 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 280 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 281 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 282 283 // Floating-point to integer conversions. 284 // i64 conversions are done via library routines even when generating VFP 285 // instructions, so use the same ones. 286 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 287 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 288 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 289 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 290 291 // Conversions between floating types. 292 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 293 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 294 295 // Integer to floating-point conversions. 296 // i64 conversions are done via library routines even when generating VFP 297 // instructions, so use the same ones. 298 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 299 // e.g., __floatunsidf vs. __floatunssidfvfp. 300 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 301 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 302 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 303 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 304 }; 305 306 for (const auto &LC : LibraryCalls) { 307 setLibcallName(LC.Op, LC.Name); 308 if (LC.Cond != ISD::SETCC_INVALID) 309 setCmpLibcallCC(LC.Op, LC.Cond); 310 } 311 } 312 } 313 314 // These libcalls are not available in 32-bit. 315 setLibcallName(RTLIB::SHL_I128, nullptr); 316 setLibcallName(RTLIB::SRL_I128, nullptr); 317 setLibcallName(RTLIB::SRA_I128, nullptr); 318 319 // RTLIB 320 if (Subtarget->isAAPCS_ABI() && 321 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 322 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 323 static const struct { 324 const RTLIB::Libcall Op; 325 const char * const Name; 326 const CallingConv::ID CC; 327 const ISD::CondCode Cond; 328 } LibraryCalls[] = { 329 // Double-precision floating-point arithmetic helper functions 330 // RTABI chapter 4.1.2, Table 2 331 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 335 336 // Double-precision floating-point comparison helper functions 337 // RTABI chapter 4.1.2, Table 3 338 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 339 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 340 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 341 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 342 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 343 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 344 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 345 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 346 347 // Single-precision floating-point arithmetic helper functions 348 // RTABI chapter 4.1.2, Table 4 349 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 350 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 351 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 352 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 353 354 // Single-precision floating-point comparison helper functions 355 // RTABI chapter 4.1.2, Table 5 356 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 357 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 358 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 359 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 360 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 361 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 362 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 363 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 364 365 // Floating-point to integer conversions. 366 // RTABI chapter 4.1.2, Table 6 367 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 369 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 370 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 371 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 372 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 373 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 374 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 375 376 // Conversions between floating types. 377 // RTABI chapter 4.1.2, Table 7 378 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 382 // Integer to floating-point conversions. 383 // RTABI chapter 4.1.2, Table 8 384 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 385 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 386 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 388 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 389 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 390 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 391 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 392 393 // Long long helper functions 394 // RTABI chapter 4.2, Table 9 395 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 399 400 // Integer division functions 401 // RTABI chapter 4.3.1 402 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 403 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 406 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 407 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 408 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 409 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 410 }; 411 412 for (const auto &LC : LibraryCalls) { 413 setLibcallName(LC.Op, LC.Name); 414 setLibcallCallingConv(LC.Op, LC.CC); 415 if (LC.Cond != ISD::SETCC_INVALID) 416 setCmpLibcallCC(LC.Op, LC.Cond); 417 } 418 419 // EABI dependent RTLIB 420 if (TM.Options.EABIVersion == EABI::EABI4 || 421 TM.Options.EABIVersion == EABI::EABI5) { 422 static const struct { 423 const RTLIB::Libcall Op; 424 const char *const Name; 425 const CallingConv::ID CC; 426 const ISD::CondCode Cond; 427 } MemOpsLibraryCalls[] = { 428 // Memory operations 429 // RTABI chapter 4.3.4 430 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 431 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 432 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 433 }; 434 435 for (const auto &LC : MemOpsLibraryCalls) { 436 setLibcallName(LC.Op, LC.Name); 437 setLibcallCallingConv(LC.Op, LC.CC); 438 if (LC.Cond != ISD::SETCC_INVALID) 439 setCmpLibcallCC(LC.Op, LC.Cond); 440 } 441 } 442 } 443 444 if (Subtarget->isTargetWindows()) { 445 static const struct { 446 const RTLIB::Libcall Op; 447 const char * const Name; 448 const CallingConv::ID CC; 449 } LibraryCalls[] = { 450 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 451 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 452 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 453 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 454 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 455 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 456 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 457 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 458 }; 459 460 for (const auto &LC : LibraryCalls) { 461 setLibcallName(LC.Op, LC.Name); 462 setLibcallCallingConv(LC.Op, LC.CC); 463 } 464 } 465 466 // Use divmod compiler-rt calls for iOS 5.0 and later. 467 if (Subtarget->isTargetMachO() && 468 !(Subtarget->isTargetIOS() && 469 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 470 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 471 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 472 } 473 474 // The half <-> float conversion functions are always soft-float on 475 // non-watchos platforms, but are needed for some targets which use a 476 // hard-float calling convention by default. 477 if (!Subtarget->isTargetWatchABI()) { 478 if (Subtarget->isAAPCS_ABI()) { 479 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 480 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 481 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 482 } else { 483 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 484 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 485 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 486 } 487 } 488 489 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 490 // a __gnu_ prefix (which is the default). 491 if (Subtarget->isTargetAEABI()) { 492 static const struct { 493 const RTLIB::Libcall Op; 494 const char * const Name; 495 const CallingConv::ID CC; 496 } LibraryCalls[] = { 497 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 498 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 499 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 500 }; 501 502 for (const auto &LC : LibraryCalls) { 503 setLibcallName(LC.Op, LC.Name); 504 setLibcallCallingConv(LC.Op, LC.CC); 505 } 506 } 507 508 if (Subtarget->isThumb1Only()) 509 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 510 else 511 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 512 513 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 514 !Subtarget->isThumb1Only()) { 515 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 516 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 517 } 518 519 if (Subtarget->hasFullFP16()) { 520 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 521 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 522 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 523 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 524 525 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 526 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 527 } 528 529 for (MVT VT : MVT::vector_valuetypes()) { 530 for (MVT InnerVT : MVT::vector_valuetypes()) { 531 setTruncStoreAction(VT, InnerVT, Expand); 532 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 533 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 534 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 535 } 536 537 setOperationAction(ISD::MULHS, VT, Expand); 538 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 539 setOperationAction(ISD::MULHU, VT, Expand); 540 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 541 542 setOperationAction(ISD::BSWAP, VT, Expand); 543 } 544 545 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 546 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 547 548 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 549 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 550 551 if (Subtarget->hasNEON()) { 552 addDRTypeForNEON(MVT::v2f32); 553 addDRTypeForNEON(MVT::v8i8); 554 addDRTypeForNEON(MVT::v4i16); 555 addDRTypeForNEON(MVT::v2i32); 556 addDRTypeForNEON(MVT::v1i64); 557 558 addQRTypeForNEON(MVT::v4f32); 559 addQRTypeForNEON(MVT::v2f64); 560 addQRTypeForNEON(MVT::v16i8); 561 addQRTypeForNEON(MVT::v8i16); 562 addQRTypeForNEON(MVT::v4i32); 563 addQRTypeForNEON(MVT::v2i64); 564 565 if (Subtarget->hasFullFP16()) { 566 addQRTypeForNEON(MVT::v8f16); 567 addDRTypeForNEON(MVT::v4f16); 568 } 569 570 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 571 // neither Neon nor VFP support any arithmetic operations on it. 572 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 573 // supported for v4f32. 574 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 575 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 576 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 577 // FIXME: Code duplication: FDIV and FREM are expanded always, see 578 // ARMTargetLowering::addTypeForNEON method for details. 579 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 580 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 581 // FIXME: Create unittest. 582 // In another words, find a way when "copysign" appears in DAG with vector 583 // operands. 584 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 585 // FIXME: Code duplication: SETCC has custom operation action, see 586 // ARMTargetLowering::addTypeForNEON method for details. 587 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 588 // FIXME: Create unittest for FNEG and for FABS. 589 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 590 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 591 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 592 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 593 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 594 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 595 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 596 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 597 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 598 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 599 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 600 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 601 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 602 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 603 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 604 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 605 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 606 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 607 608 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 609 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 610 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 611 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 612 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 613 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 614 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 615 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 616 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 617 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 618 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 619 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 620 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 621 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 622 623 // Mark v2f32 intrinsics. 624 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 625 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 626 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 627 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 628 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 629 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 630 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 631 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 632 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 633 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 634 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 635 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 636 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 637 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 638 639 // Neon does not support some operations on v1i64 and v2i64 types. 640 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 641 // Custom handling for some quad-vector types to detect VMULL. 642 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 643 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 644 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 645 // Custom handling for some vector types to avoid expensive expansions 646 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 647 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 648 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 649 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 650 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 651 // a destination type that is wider than the source, and nor does 652 // it have a FP_TO_[SU]INT instruction with a narrower destination than 653 // source. 654 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 655 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 656 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 657 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 658 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 659 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 660 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 661 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 662 663 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 664 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 665 666 // NEON does not have single instruction CTPOP for vectors with element 667 // types wider than 8-bits. However, custom lowering can leverage the 668 // v8i8/v16i8 vcnt instruction. 669 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 670 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 671 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 672 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 673 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 674 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 675 676 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 677 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 678 679 // NEON does not have single instruction CTTZ for vectors. 680 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 681 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 682 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 683 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 684 685 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 686 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 687 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 688 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 689 690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 691 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 692 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 693 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 694 695 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 696 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 697 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 698 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 699 700 // NEON only has FMA instructions as of VFP4. 701 if (!Subtarget->hasVFP4()) { 702 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 703 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 704 } 705 706 setTargetDAGCombine(ISD::INTRINSIC_VOID); 707 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 708 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 709 setTargetDAGCombine(ISD::SHL); 710 setTargetDAGCombine(ISD::SRL); 711 setTargetDAGCombine(ISD::SRA); 712 setTargetDAGCombine(ISD::SIGN_EXTEND); 713 setTargetDAGCombine(ISD::ZERO_EXTEND); 714 setTargetDAGCombine(ISD::ANY_EXTEND); 715 setTargetDAGCombine(ISD::BUILD_VECTOR); 716 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 717 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 718 setTargetDAGCombine(ISD::STORE); 719 setTargetDAGCombine(ISD::FP_TO_SINT); 720 setTargetDAGCombine(ISD::FP_TO_UINT); 721 setTargetDAGCombine(ISD::FDIV); 722 setTargetDAGCombine(ISD::LOAD); 723 724 // It is legal to extload from v4i8 to v4i16 or v4i32. 725 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 726 MVT::v2i32}) { 727 for (MVT VT : MVT::integer_vector_valuetypes()) { 728 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 729 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 730 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 731 } 732 } 733 } 734 735 if (Subtarget->isFPOnlySP()) { 736 // When targeting a floating-point unit with only single-precision 737 // operations, f64 is legal for the few double-precision instructions which 738 // are present However, no double-precision operations other than moves, 739 // loads and stores are provided by the hardware. 740 setOperationAction(ISD::FADD, MVT::f64, Expand); 741 setOperationAction(ISD::FSUB, MVT::f64, Expand); 742 setOperationAction(ISD::FMUL, MVT::f64, Expand); 743 setOperationAction(ISD::FMA, MVT::f64, Expand); 744 setOperationAction(ISD::FDIV, MVT::f64, Expand); 745 setOperationAction(ISD::FREM, MVT::f64, Expand); 746 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 747 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 748 setOperationAction(ISD::FNEG, MVT::f64, Expand); 749 setOperationAction(ISD::FABS, MVT::f64, Expand); 750 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 751 setOperationAction(ISD::FSIN, MVT::f64, Expand); 752 setOperationAction(ISD::FCOS, MVT::f64, Expand); 753 setOperationAction(ISD::FPOW, MVT::f64, Expand); 754 setOperationAction(ISD::FLOG, MVT::f64, Expand); 755 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 756 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 757 setOperationAction(ISD::FEXP, MVT::f64, Expand); 758 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 759 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 760 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 761 setOperationAction(ISD::FRINT, MVT::f64, Expand); 762 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 763 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 764 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 765 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 766 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 767 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 768 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 769 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 770 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 771 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 772 } 773 774 computeRegisterProperties(Subtarget->getRegisterInfo()); 775 776 // ARM does not have floating-point extending loads. 777 for (MVT VT : MVT::fp_valuetypes()) { 778 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 779 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 780 } 781 782 // ... or truncating stores 783 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 784 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 785 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 786 787 // ARM does not have i1 sign extending load. 788 for (MVT VT : MVT::integer_valuetypes()) 789 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 790 791 // ARM supports all 4 flavors of integer indexed load / store. 792 if (!Subtarget->isThumb1Only()) { 793 for (unsigned im = (unsigned)ISD::PRE_INC; 794 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 795 setIndexedLoadAction(im, MVT::i1, Legal); 796 setIndexedLoadAction(im, MVT::i8, Legal); 797 setIndexedLoadAction(im, MVT::i16, Legal); 798 setIndexedLoadAction(im, MVT::i32, Legal); 799 setIndexedStoreAction(im, MVT::i1, Legal); 800 setIndexedStoreAction(im, MVT::i8, Legal); 801 setIndexedStoreAction(im, MVT::i16, Legal); 802 setIndexedStoreAction(im, MVT::i32, Legal); 803 } 804 } else { 805 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 806 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 807 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 808 } 809 810 setOperationAction(ISD::SADDO, MVT::i32, Custom); 811 setOperationAction(ISD::UADDO, MVT::i32, Custom); 812 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 813 setOperationAction(ISD::USUBO, MVT::i32, Custom); 814 815 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 816 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 817 818 // i64 operation support. 819 setOperationAction(ISD::MUL, MVT::i64, Expand); 820 setOperationAction(ISD::MULHU, MVT::i32, Expand); 821 if (Subtarget->isThumb1Only()) { 822 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 823 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 824 } 825 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 826 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 827 setOperationAction(ISD::MULHS, MVT::i32, Expand); 828 829 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 830 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 831 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 832 setOperationAction(ISD::SRL, MVT::i64, Custom); 833 setOperationAction(ISD::SRA, MVT::i64, Custom); 834 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 835 836 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 837 if (Subtarget->isThumb1Only()) { 838 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 839 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 840 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 841 } 842 843 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 844 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 845 846 // ARM does not have ROTL. 847 setOperationAction(ISD::ROTL, MVT::i32, Expand); 848 for (MVT VT : MVT::vector_valuetypes()) { 849 setOperationAction(ISD::ROTL, VT, Expand); 850 setOperationAction(ISD::ROTR, VT, Expand); 851 } 852 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 853 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 854 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 855 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 856 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 857 } 858 859 // @llvm.readcyclecounter requires the Performance Monitors extension. 860 // Default to the 0 expansion on unsupported platforms. 861 // FIXME: Technically there are older ARM CPUs that have 862 // implementation-specific ways of obtaining this information. 863 if (Subtarget->hasPerfMon()) 864 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 865 866 // Only ARMv6 has BSWAP. 867 if (!Subtarget->hasV6Ops()) 868 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 869 870 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 871 : Subtarget->hasDivideInARMMode(); 872 if (!hasDivide) { 873 // These are expanded into libcalls if the cpu doesn't have HW divider. 874 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 875 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 876 } 877 878 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 879 setOperationAction(ISD::SDIV, MVT::i32, Custom); 880 setOperationAction(ISD::UDIV, MVT::i32, Custom); 881 882 setOperationAction(ISD::SDIV, MVT::i64, Custom); 883 setOperationAction(ISD::UDIV, MVT::i64, Custom); 884 } 885 886 setOperationAction(ISD::SREM, MVT::i32, Expand); 887 setOperationAction(ISD::UREM, MVT::i32, Expand); 888 889 // Register based DivRem for AEABI (RTABI 4.2) 890 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 891 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 892 Subtarget->isTargetWindows()) { 893 setOperationAction(ISD::SREM, MVT::i64, Custom); 894 setOperationAction(ISD::UREM, MVT::i64, Custom); 895 HasStandaloneRem = false; 896 897 if (Subtarget->isTargetWindows()) { 898 const struct { 899 const RTLIB::Libcall Op; 900 const char * const Name; 901 const CallingConv::ID CC; 902 } LibraryCalls[] = { 903 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 904 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 905 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 906 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 907 908 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 909 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 910 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 911 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 912 }; 913 914 for (const auto &LC : LibraryCalls) { 915 setLibcallName(LC.Op, LC.Name); 916 setLibcallCallingConv(LC.Op, LC.CC); 917 } 918 } else { 919 const struct { 920 const RTLIB::Libcall Op; 921 const char * const Name; 922 const CallingConv::ID CC; 923 } LibraryCalls[] = { 924 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 925 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 926 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 927 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 928 929 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 930 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 931 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 932 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 933 }; 934 935 for (const auto &LC : LibraryCalls) { 936 setLibcallName(LC.Op, LC.Name); 937 setLibcallCallingConv(LC.Op, LC.CC); 938 } 939 } 940 941 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 942 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 943 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 944 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 945 } else { 946 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 947 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 948 } 949 950 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 951 for (auto &VT : {MVT::f32, MVT::f64}) 952 setOperationAction(ISD::FPOWI, VT, Custom); 953 954 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 955 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 956 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 957 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 958 959 setOperationAction(ISD::TRAP, MVT::Other, Legal); 960 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 961 962 // Use the default implementation. 963 setOperationAction(ISD::VASTART, MVT::Other, Custom); 964 setOperationAction(ISD::VAARG, MVT::Other, Expand); 965 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 966 setOperationAction(ISD::VAEND, MVT::Other, Expand); 967 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 968 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 969 970 if (Subtarget->isTargetWindows()) 971 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 972 else 973 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 974 975 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 976 // the default expansion. 977 InsertFencesForAtomic = false; 978 if (Subtarget->hasAnyDataBarrier() && 979 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 980 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 981 // to ldrex/strex loops already. 982 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 983 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 984 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 985 986 // On v8, we have particularly efficient implementations of atomic fences 987 // if they can be combined with nearby atomic loads and stores. 988 if (!Subtarget->hasAcquireRelease() || 989 getTargetMachine().getOptLevel() == 0) { 990 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 991 InsertFencesForAtomic = true; 992 } 993 } else { 994 // If there's anything we can use as a barrier, go through custom lowering 995 // for ATOMIC_FENCE. 996 // If target has DMB in thumb, Fences can be inserted. 997 if (Subtarget->hasDataBarrier()) 998 InsertFencesForAtomic = true; 999 1000 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1001 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1002 1003 // Set them all for expansion, which will force libcalls. 1004 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1005 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1006 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1007 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1008 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1009 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1010 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1011 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1012 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1013 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1014 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1015 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1016 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1017 // Unordered/Monotonic case. 1018 if (!InsertFencesForAtomic) { 1019 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1020 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1021 } 1022 } 1023 1024 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1025 1026 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1027 if (!Subtarget->hasV6Ops()) { 1028 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1029 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1030 } 1031 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1032 1033 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1034 !Subtarget->isThumb1Only()) { 1035 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1036 // iff target supports vfp2. 1037 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1038 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1039 } 1040 1041 // We want to custom lower some of our intrinsics. 1042 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1043 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1044 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1045 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1046 if (Subtarget->useSjLjEH()) 1047 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1048 1049 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1050 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1051 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1052 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1053 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1054 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1055 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1056 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1057 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1058 if (Subtarget->hasFullFP16()) { 1059 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1060 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1061 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1062 } 1063 1064 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1065 1066 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1067 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1068 if (Subtarget->hasFullFP16()) 1069 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1070 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1071 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1072 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1073 1074 // We don't support sin/cos/fmod/copysign/pow 1075 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1076 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1077 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1078 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1079 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1080 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1081 setOperationAction(ISD::FREM, MVT::f64, Expand); 1082 setOperationAction(ISD::FREM, MVT::f32, Expand); 1083 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1084 !Subtarget->isThumb1Only()) { 1085 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1086 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1087 } 1088 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1089 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1090 1091 if (!Subtarget->hasVFP4()) { 1092 setOperationAction(ISD::FMA, MVT::f64, Expand); 1093 setOperationAction(ISD::FMA, MVT::f32, Expand); 1094 } 1095 1096 // Various VFP goodness 1097 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1098 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1099 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1100 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1101 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1102 } 1103 1104 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1105 if (!Subtarget->hasFP16()) { 1106 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1107 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1108 } 1109 } 1110 1111 // Use __sincos_stret if available. 1112 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1113 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1114 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1115 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1116 } 1117 1118 // FP-ARMv8 implements a lot of rounding-like FP operations. 1119 if (Subtarget->hasFPARMv8()) { 1120 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1121 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1122 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1123 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1124 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1125 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1126 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1127 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1128 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1129 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1130 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1131 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1132 1133 if (!Subtarget->isFPOnlySP()) { 1134 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1135 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1136 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1137 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1138 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1139 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1140 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1141 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1142 } 1143 } 1144 1145 // FP16 often need to be promoted to call lib functions 1146 if (Subtarget->hasFullFP16()) { 1147 setOperationAction(ISD::FREM, MVT::f16, Promote); 1148 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1149 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1150 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1151 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1152 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1153 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1154 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1155 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1156 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1157 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1158 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1159 1160 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1161 } 1162 1163 if (Subtarget->hasNEON()) { 1164 // vmin and vmax aren't available in a scalar form, so we use 1165 // a NEON instruction with an undef lane instead. 1166 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1167 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1168 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1169 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1170 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1171 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1172 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1173 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1174 1175 if (Subtarget->hasFullFP16()) { 1176 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1177 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1178 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1179 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1180 1181 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1182 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1183 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1184 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1185 } 1186 } 1187 1188 // We have target-specific dag combine patterns for the following nodes: 1189 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1190 setTargetDAGCombine(ISD::ADD); 1191 setTargetDAGCombine(ISD::SUB); 1192 setTargetDAGCombine(ISD::MUL); 1193 setTargetDAGCombine(ISD::AND); 1194 setTargetDAGCombine(ISD::OR); 1195 setTargetDAGCombine(ISD::XOR); 1196 1197 if (Subtarget->hasV6Ops()) 1198 setTargetDAGCombine(ISD::SRL); 1199 if (Subtarget->isThumb1Only()) 1200 setTargetDAGCombine(ISD::SHL); 1201 1202 setStackPointerRegisterToSaveRestore(ARM::SP); 1203 1204 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1205 !Subtarget->hasVFP2() || Subtarget->hasMinSize()) 1206 setSchedulingPreference(Sched::RegPressure); 1207 else 1208 setSchedulingPreference(Sched::Hybrid); 1209 1210 //// temporary - rewrite interface to use type 1211 MaxStoresPerMemset = 8; 1212 MaxStoresPerMemsetOptSize = 4; 1213 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1214 MaxStoresPerMemcpyOptSize = 2; 1215 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1216 MaxStoresPerMemmoveOptSize = 2; 1217 1218 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1219 // are at least 4 bytes aligned. 1220 setMinStackArgumentAlignment(4); 1221 1222 // Prefer likely predicted branches to selects on out-of-order cores. 1223 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1224 1225 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment()); 1226 1227 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1228 1229 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1230 setTargetDAGCombine(ISD::ABS); 1231 } 1232 1233 bool ARMTargetLowering::useSoftFloat() const { 1234 return Subtarget->useSoftFloat(); 1235 } 1236 1237 // FIXME: It might make sense to define the representative register class as the 1238 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1239 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1240 // SPR's representative would be DPR_VFP2. This should work well if register 1241 // pressure tracking were modified such that a register use would increment the 1242 // pressure of the register class's representative and all of it's super 1243 // classes' representatives transitively. We have not implemented this because 1244 // of the difficulty prior to coalescing of modeling operand register classes 1245 // due to the common occurrence of cross class copies and subregister insertions 1246 // and extractions. 1247 std::pair<const TargetRegisterClass *, uint8_t> 1248 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1249 MVT VT) const { 1250 const TargetRegisterClass *RRC = nullptr; 1251 uint8_t Cost = 1; 1252 switch (VT.SimpleTy) { 1253 default: 1254 return TargetLowering::findRepresentativeClass(TRI, VT); 1255 // Use DPR as representative register class for all floating point 1256 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1257 // the cost is 1 for both f32 and f64. 1258 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1259 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1260 RRC = &ARM::DPRRegClass; 1261 // When NEON is used for SP, only half of the register file is available 1262 // because operations that define both SP and DP results will be constrained 1263 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1264 // coalescing by double-counting the SP regs. See the FIXME above. 1265 if (Subtarget->useNEONForSinglePrecisionFP()) 1266 Cost = 2; 1267 break; 1268 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1269 case MVT::v4f32: case MVT::v2f64: 1270 RRC = &ARM::DPRRegClass; 1271 Cost = 2; 1272 break; 1273 case MVT::v4i64: 1274 RRC = &ARM::DPRRegClass; 1275 Cost = 4; 1276 break; 1277 case MVT::v8i64: 1278 RRC = &ARM::DPRRegClass; 1279 Cost = 8; 1280 break; 1281 } 1282 return std::make_pair(RRC, Cost); 1283 } 1284 1285 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1286 switch ((ARMISD::NodeType)Opcode) { 1287 case ARMISD::FIRST_NUMBER: break; 1288 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1289 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1290 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1291 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1292 case ARMISD::CALL: return "ARMISD::CALL"; 1293 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1294 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1295 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1296 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1297 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1298 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1299 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1300 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1301 case ARMISD::CMP: return "ARMISD::CMP"; 1302 case ARMISD::CMN: return "ARMISD::CMN"; 1303 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1304 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1305 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1306 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1307 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1308 1309 case ARMISD::CMOV: return "ARMISD::CMOV"; 1310 case ARMISD::SUBS: return "ARMISD::SUBS"; 1311 1312 case ARMISD::SSAT: return "ARMISD::SSAT"; 1313 case ARMISD::USAT: return "ARMISD::USAT"; 1314 1315 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1316 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1317 case ARMISD::RRX: return "ARMISD::RRX"; 1318 1319 case ARMISD::ADDC: return "ARMISD::ADDC"; 1320 case ARMISD::ADDE: return "ARMISD::ADDE"; 1321 case ARMISD::SUBC: return "ARMISD::SUBC"; 1322 case ARMISD::SUBE: return "ARMISD::SUBE"; 1323 1324 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1325 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1326 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1327 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1328 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1329 1330 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1331 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1332 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1333 1334 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1335 1336 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1337 1338 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1339 1340 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1341 1342 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1343 1344 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1345 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1346 1347 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1348 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1349 case ARMISD::VCGE: return "ARMISD::VCGE"; 1350 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1351 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1352 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1353 case ARMISD::VCGT: return "ARMISD::VCGT"; 1354 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1355 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1356 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1357 case ARMISD::VTST: return "ARMISD::VTST"; 1358 1359 case ARMISD::VSHL: return "ARMISD::VSHL"; 1360 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1361 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1362 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1363 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1364 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1365 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1366 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1367 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1368 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1369 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1370 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1371 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1372 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1373 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1374 case ARMISD::VSLI: return "ARMISD::VSLI"; 1375 case ARMISD::VSRI: return "ARMISD::VSRI"; 1376 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1377 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1378 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1379 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1380 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1381 case ARMISD::VDUP: return "ARMISD::VDUP"; 1382 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1383 case ARMISD::VEXT: return "ARMISD::VEXT"; 1384 case ARMISD::VREV64: return "ARMISD::VREV64"; 1385 case ARMISD::VREV32: return "ARMISD::VREV32"; 1386 case ARMISD::VREV16: return "ARMISD::VREV16"; 1387 case ARMISD::VZIP: return "ARMISD::VZIP"; 1388 case ARMISD::VUZP: return "ARMISD::VUZP"; 1389 case ARMISD::VTRN: return "ARMISD::VTRN"; 1390 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1391 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1392 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1393 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1394 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1395 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1396 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1397 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1398 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1399 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1400 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1401 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1402 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1403 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1404 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1405 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1406 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1407 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1408 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1409 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1410 case ARMISD::BFI: return "ARMISD::BFI"; 1411 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1412 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1413 case ARMISD::VBSL: return "ARMISD::VBSL"; 1414 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1415 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1416 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1417 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1418 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1419 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1420 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1421 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1422 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1423 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1424 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1425 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1426 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1427 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1428 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1429 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1430 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1431 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1432 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1433 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1434 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1435 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1436 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1437 } 1438 return nullptr; 1439 } 1440 1441 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1442 EVT VT) const { 1443 if (!VT.isVector()) 1444 return getPointerTy(DL); 1445 return VT.changeVectorElementTypeToInteger(); 1446 } 1447 1448 /// getRegClassFor - Return the register class that should be used for the 1449 /// specified value type. 1450 const TargetRegisterClass * 1451 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1452 (void)isDivergent; 1453 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1454 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1455 // load / store 4 to 8 consecutive D registers. 1456 if (Subtarget->hasNEON()) { 1457 if (VT == MVT::v4i64) 1458 return &ARM::QQPRRegClass; 1459 if (VT == MVT::v8i64) 1460 return &ARM::QQQQPRRegClass; 1461 } 1462 return TargetLowering::getRegClassFor(VT); 1463 } 1464 1465 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1466 // source/dest is aligned and the copy size is large enough. We therefore want 1467 // to align such objects passed to memory intrinsics. 1468 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1469 unsigned &PrefAlign) const { 1470 if (!isa<MemIntrinsic>(CI)) 1471 return false; 1472 MinSize = 8; 1473 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1474 // cycle faster than 4-byte aligned LDM. 1475 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1476 return true; 1477 } 1478 1479 // Create a fast isel object. 1480 FastISel * 1481 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1482 const TargetLibraryInfo *libInfo) const { 1483 return ARM::createFastISel(funcInfo, libInfo); 1484 } 1485 1486 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1487 unsigned NumVals = N->getNumValues(); 1488 if (!NumVals) 1489 return Sched::RegPressure; 1490 1491 for (unsigned i = 0; i != NumVals; ++i) { 1492 EVT VT = N->getValueType(i); 1493 if (VT == MVT::Glue || VT == MVT::Other) 1494 continue; 1495 if (VT.isFloatingPoint() || VT.isVector()) 1496 return Sched::ILP; 1497 } 1498 1499 if (!N->isMachineOpcode()) 1500 return Sched::RegPressure; 1501 1502 // Load are scheduled for latency even if there instruction itinerary 1503 // is not available. 1504 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1505 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1506 1507 if (MCID.getNumDefs() == 0) 1508 return Sched::RegPressure; 1509 if (!Itins->isEmpty() && 1510 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1511 return Sched::ILP; 1512 1513 return Sched::RegPressure; 1514 } 1515 1516 //===----------------------------------------------------------------------===// 1517 // Lowering Code 1518 //===----------------------------------------------------------------------===// 1519 1520 static bool isSRL16(const SDValue &Op) { 1521 if (Op.getOpcode() != ISD::SRL) 1522 return false; 1523 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1524 return Const->getZExtValue() == 16; 1525 return false; 1526 } 1527 1528 static bool isSRA16(const SDValue &Op) { 1529 if (Op.getOpcode() != ISD::SRA) 1530 return false; 1531 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1532 return Const->getZExtValue() == 16; 1533 return false; 1534 } 1535 1536 static bool isSHL16(const SDValue &Op) { 1537 if (Op.getOpcode() != ISD::SHL) 1538 return false; 1539 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1540 return Const->getZExtValue() == 16; 1541 return false; 1542 } 1543 1544 // Check for a signed 16-bit value. We special case SRA because it makes it 1545 // more simple when also looking for SRAs that aren't sign extending a 1546 // smaller value. Without the check, we'd need to take extra care with 1547 // checking order for some operations. 1548 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1549 if (isSRA16(Op)) 1550 return isSHL16(Op.getOperand(0)); 1551 return DAG.ComputeNumSignBits(Op) == 17; 1552 } 1553 1554 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1555 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1556 switch (CC) { 1557 default: llvm_unreachable("Unknown condition code!"); 1558 case ISD::SETNE: return ARMCC::NE; 1559 case ISD::SETEQ: return ARMCC::EQ; 1560 case ISD::SETGT: return ARMCC::GT; 1561 case ISD::SETGE: return ARMCC::GE; 1562 case ISD::SETLT: return ARMCC::LT; 1563 case ISD::SETLE: return ARMCC::LE; 1564 case ISD::SETUGT: return ARMCC::HI; 1565 case ISD::SETUGE: return ARMCC::HS; 1566 case ISD::SETULT: return ARMCC::LO; 1567 case ISD::SETULE: return ARMCC::LS; 1568 } 1569 } 1570 1571 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1572 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1573 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1574 CondCode2 = ARMCC::AL; 1575 InvalidOnQNaN = true; 1576 switch (CC) { 1577 default: llvm_unreachable("Unknown FP condition!"); 1578 case ISD::SETEQ: 1579 case ISD::SETOEQ: 1580 CondCode = ARMCC::EQ; 1581 InvalidOnQNaN = false; 1582 break; 1583 case ISD::SETGT: 1584 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1585 case ISD::SETGE: 1586 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1587 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1588 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1589 case ISD::SETONE: 1590 CondCode = ARMCC::MI; 1591 CondCode2 = ARMCC::GT; 1592 InvalidOnQNaN = false; 1593 break; 1594 case ISD::SETO: CondCode = ARMCC::VC; break; 1595 case ISD::SETUO: CondCode = ARMCC::VS; break; 1596 case ISD::SETUEQ: 1597 CondCode = ARMCC::EQ; 1598 CondCode2 = ARMCC::VS; 1599 InvalidOnQNaN = false; 1600 break; 1601 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1602 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1603 case ISD::SETLT: 1604 case ISD::SETULT: CondCode = ARMCC::LT; break; 1605 case ISD::SETLE: 1606 case ISD::SETULE: CondCode = ARMCC::LE; break; 1607 case ISD::SETNE: 1608 case ISD::SETUNE: 1609 CondCode = ARMCC::NE; 1610 InvalidOnQNaN = false; 1611 break; 1612 } 1613 } 1614 1615 //===----------------------------------------------------------------------===// 1616 // Calling Convention Implementation 1617 //===----------------------------------------------------------------------===// 1618 1619 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1620 /// account presence of floating point hardware and calling convention 1621 /// limitations, such as support for variadic functions. 1622 CallingConv::ID 1623 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1624 bool isVarArg) const { 1625 switch (CC) { 1626 default: 1627 report_fatal_error("Unsupported calling convention"); 1628 case CallingConv::ARM_AAPCS: 1629 case CallingConv::ARM_APCS: 1630 case CallingConv::GHC: 1631 return CC; 1632 case CallingConv::PreserveMost: 1633 return CallingConv::PreserveMost; 1634 case CallingConv::ARM_AAPCS_VFP: 1635 case CallingConv::Swift: 1636 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1637 case CallingConv::C: 1638 if (!Subtarget->isAAPCS_ABI()) 1639 return CallingConv::ARM_APCS; 1640 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1641 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1642 !isVarArg) 1643 return CallingConv::ARM_AAPCS_VFP; 1644 else 1645 return CallingConv::ARM_AAPCS; 1646 case CallingConv::Fast: 1647 case CallingConv::CXX_FAST_TLS: 1648 if (!Subtarget->isAAPCS_ABI()) { 1649 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1650 return CallingConv::Fast; 1651 return CallingConv::ARM_APCS; 1652 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1653 return CallingConv::ARM_AAPCS_VFP; 1654 else 1655 return CallingConv::ARM_AAPCS; 1656 } 1657 } 1658 1659 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1660 bool isVarArg) const { 1661 return CCAssignFnForNode(CC, false, isVarArg); 1662 } 1663 1664 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1665 bool isVarArg) const { 1666 return CCAssignFnForNode(CC, true, isVarArg); 1667 } 1668 1669 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1670 /// CallingConvention. 1671 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1672 bool Return, 1673 bool isVarArg) const { 1674 switch (getEffectiveCallingConv(CC, isVarArg)) { 1675 default: 1676 report_fatal_error("Unsupported calling convention"); 1677 case CallingConv::ARM_APCS: 1678 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1679 case CallingConv::ARM_AAPCS: 1680 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1681 case CallingConv::ARM_AAPCS_VFP: 1682 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1683 case CallingConv::Fast: 1684 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1685 case CallingConv::GHC: 1686 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1687 case CallingConv::PreserveMost: 1688 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1689 } 1690 } 1691 1692 /// LowerCallResult - Lower the result values of a call into the 1693 /// appropriate copies out of appropriate physical registers. 1694 SDValue ARMTargetLowering::LowerCallResult( 1695 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1696 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1697 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1698 SDValue ThisVal) const { 1699 // Assign locations to each value returned by this call. 1700 SmallVector<CCValAssign, 16> RVLocs; 1701 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1702 *DAG.getContext()); 1703 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1704 1705 // Copy all of the result registers out of their specified physreg. 1706 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1707 CCValAssign VA = RVLocs[i]; 1708 1709 // Pass 'this' value directly from the argument to return value, to avoid 1710 // reg unit interference 1711 if (i == 0 && isThisReturn) { 1712 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1713 "unexpected return calling convention register assignment"); 1714 InVals.push_back(ThisVal); 1715 continue; 1716 } 1717 1718 SDValue Val; 1719 if (VA.needsCustom()) { 1720 // Handle f64 or half of a v2f64. 1721 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1722 InFlag); 1723 Chain = Lo.getValue(1); 1724 InFlag = Lo.getValue(2); 1725 VA = RVLocs[++i]; // skip ahead to next loc 1726 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1727 InFlag); 1728 Chain = Hi.getValue(1); 1729 InFlag = Hi.getValue(2); 1730 if (!Subtarget->isLittle()) 1731 std::swap (Lo, Hi); 1732 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1733 1734 if (VA.getLocVT() == MVT::v2f64) { 1735 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1736 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1737 DAG.getConstant(0, dl, MVT::i32)); 1738 1739 VA = RVLocs[++i]; // skip ahead to next loc 1740 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1741 Chain = Lo.getValue(1); 1742 InFlag = Lo.getValue(2); 1743 VA = RVLocs[++i]; // skip ahead to next loc 1744 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1745 Chain = Hi.getValue(1); 1746 InFlag = Hi.getValue(2); 1747 if (!Subtarget->isLittle()) 1748 std::swap (Lo, Hi); 1749 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1750 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1751 DAG.getConstant(1, dl, MVT::i32)); 1752 } 1753 } else { 1754 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1755 InFlag); 1756 Chain = Val.getValue(1); 1757 InFlag = Val.getValue(2); 1758 } 1759 1760 switch (VA.getLocInfo()) { 1761 default: llvm_unreachable("Unknown loc info!"); 1762 case CCValAssign::Full: break; 1763 case CCValAssign::BCvt: 1764 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1765 break; 1766 } 1767 1768 InVals.push_back(Val); 1769 } 1770 1771 return Chain; 1772 } 1773 1774 /// LowerMemOpCallTo - Store the argument to the stack. 1775 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1776 SDValue Arg, const SDLoc &dl, 1777 SelectionDAG &DAG, 1778 const CCValAssign &VA, 1779 ISD::ArgFlagsTy Flags) const { 1780 unsigned LocMemOffset = VA.getLocMemOffset(); 1781 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1782 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1783 StackPtr, PtrOff); 1784 return DAG.getStore( 1785 Chain, dl, Arg, PtrOff, 1786 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1787 } 1788 1789 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1790 SDValue Chain, SDValue &Arg, 1791 RegsToPassVector &RegsToPass, 1792 CCValAssign &VA, CCValAssign &NextVA, 1793 SDValue &StackPtr, 1794 SmallVectorImpl<SDValue> &MemOpChains, 1795 ISD::ArgFlagsTy Flags) const { 1796 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1797 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1798 unsigned id = Subtarget->isLittle() ? 0 : 1; 1799 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1800 1801 if (NextVA.isRegLoc()) 1802 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1803 else { 1804 assert(NextVA.isMemLoc()); 1805 if (!StackPtr.getNode()) 1806 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1807 getPointerTy(DAG.getDataLayout())); 1808 1809 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1810 dl, DAG, NextVA, 1811 Flags)); 1812 } 1813 } 1814 1815 /// LowerCall - Lowering a call into a callseq_start <- 1816 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1817 /// nodes. 1818 SDValue 1819 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1820 SmallVectorImpl<SDValue> &InVals) const { 1821 SelectionDAG &DAG = CLI.DAG; 1822 SDLoc &dl = CLI.DL; 1823 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1824 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1825 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1826 SDValue Chain = CLI.Chain; 1827 SDValue Callee = CLI.Callee; 1828 bool &isTailCall = CLI.IsTailCall; 1829 CallingConv::ID CallConv = CLI.CallConv; 1830 bool doesNotRet = CLI.DoesNotReturn; 1831 bool isVarArg = CLI.IsVarArg; 1832 1833 MachineFunction &MF = DAG.getMachineFunction(); 1834 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1835 bool isThisReturn = false; 1836 bool isSibCall = false; 1837 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1838 1839 // Disable tail calls if they're not supported. 1840 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1841 isTailCall = false; 1842 1843 if (isTailCall) { 1844 // Check if it's really possible to do a tail call. 1845 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1846 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1847 Outs, OutVals, Ins, DAG); 1848 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1849 report_fatal_error("failed to perform tail call elimination on a call " 1850 "site marked musttail"); 1851 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1852 // detected sibcalls. 1853 if (isTailCall) { 1854 ++NumTailCalls; 1855 isSibCall = true; 1856 } 1857 } 1858 1859 // Analyze operands of the call, assigning locations to each operand. 1860 SmallVector<CCValAssign, 16> ArgLocs; 1861 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1862 *DAG.getContext()); 1863 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1864 1865 // Get a count of how many bytes are to be pushed on the stack. 1866 unsigned NumBytes = CCInfo.getNextStackOffset(); 1867 1868 // For tail calls, memory operands are available in our caller's stack. 1869 if (isSibCall) 1870 NumBytes = 0; 1871 1872 // Adjust the stack pointer for the new arguments... 1873 // These operations are automatically eliminated by the prolog/epilog pass 1874 if (!isSibCall) 1875 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1876 1877 SDValue StackPtr = 1878 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1879 1880 RegsToPassVector RegsToPass; 1881 SmallVector<SDValue, 8> MemOpChains; 1882 1883 // Walk the register/memloc assignments, inserting copies/loads. In the case 1884 // of tail call optimization, arguments are handled later. 1885 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1886 i != e; 1887 ++i, ++realArgIdx) { 1888 CCValAssign &VA = ArgLocs[i]; 1889 SDValue Arg = OutVals[realArgIdx]; 1890 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1891 bool isByVal = Flags.isByVal(); 1892 1893 // Promote the value if needed. 1894 switch (VA.getLocInfo()) { 1895 default: llvm_unreachable("Unknown loc info!"); 1896 case CCValAssign::Full: break; 1897 case CCValAssign::SExt: 1898 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1899 break; 1900 case CCValAssign::ZExt: 1901 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1902 break; 1903 case CCValAssign::AExt: 1904 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1905 break; 1906 case CCValAssign::BCvt: 1907 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1908 break; 1909 } 1910 1911 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1912 if (VA.needsCustom()) { 1913 if (VA.getLocVT() == MVT::v2f64) { 1914 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1915 DAG.getConstant(0, dl, MVT::i32)); 1916 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1917 DAG.getConstant(1, dl, MVT::i32)); 1918 1919 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1920 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1921 1922 VA = ArgLocs[++i]; // skip ahead to next loc 1923 if (VA.isRegLoc()) { 1924 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1925 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1926 } else { 1927 assert(VA.isMemLoc()); 1928 1929 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1930 dl, DAG, VA, Flags)); 1931 } 1932 } else { 1933 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1934 StackPtr, MemOpChains, Flags); 1935 } 1936 } else if (VA.isRegLoc()) { 1937 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1938 Outs[0].VT == MVT::i32) { 1939 assert(VA.getLocVT() == MVT::i32 && 1940 "unexpected calling convention register assignment"); 1941 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1942 "unexpected use of 'returned'"); 1943 isThisReturn = true; 1944 } 1945 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1946 } else if (isByVal) { 1947 assert(VA.isMemLoc()); 1948 unsigned offset = 0; 1949 1950 // True if this byval aggregate will be split between registers 1951 // and memory. 1952 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1953 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1954 1955 if (CurByValIdx < ByValArgsCount) { 1956 1957 unsigned RegBegin, RegEnd; 1958 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1959 1960 EVT PtrVT = 1961 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1962 unsigned int i, j; 1963 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1964 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1965 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1966 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1967 MachinePointerInfo(), 1968 DAG.InferPtrAlignment(AddArg)); 1969 MemOpChains.push_back(Load.getValue(1)); 1970 RegsToPass.push_back(std::make_pair(j, Load)); 1971 } 1972 1973 // If parameter size outsides register area, "offset" value 1974 // helps us to calculate stack slot for remained part properly. 1975 offset = RegEnd - RegBegin; 1976 1977 CCInfo.nextInRegsParam(); 1978 } 1979 1980 if (Flags.getByValSize() > 4*offset) { 1981 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1982 unsigned LocMemOffset = VA.getLocMemOffset(); 1983 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1984 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1985 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1986 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1987 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1988 MVT::i32); 1989 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1990 MVT::i32); 1991 1992 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1993 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1994 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1995 Ops)); 1996 } 1997 } else if (!isSibCall) { 1998 assert(VA.isMemLoc()); 1999 2000 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2001 dl, DAG, VA, Flags)); 2002 } 2003 } 2004 2005 if (!MemOpChains.empty()) 2006 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2007 2008 // Build a sequence of copy-to-reg nodes chained together with token chain 2009 // and flag operands which copy the outgoing args into the appropriate regs. 2010 SDValue InFlag; 2011 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2012 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2013 RegsToPass[i].second, InFlag); 2014 InFlag = Chain.getValue(1); 2015 } 2016 2017 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2018 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2019 // node so that legalize doesn't hack it. 2020 bool isDirect = false; 2021 2022 const TargetMachine &TM = getTargetMachine(); 2023 const Module *Mod = MF.getFunction().getParent(); 2024 const GlobalValue *GV = nullptr; 2025 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2026 GV = G->getGlobal(); 2027 bool isStub = 2028 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2029 2030 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2031 bool isLocalARMFunc = false; 2032 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2033 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2034 2035 if (Subtarget->genLongCalls()) { 2036 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2037 "long-calls codegen is not position independent!"); 2038 // Handle a global address or an external symbol. If it's not one of 2039 // those, the target's already in a register, so we don't need to do 2040 // anything extra. 2041 if (isa<GlobalAddressSDNode>(Callee)) { 2042 // Create a constant pool entry for the callee address 2043 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2044 ARMConstantPoolValue *CPV = 2045 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2046 2047 // Get the address of the callee into a register 2048 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2049 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2050 Callee = DAG.getLoad( 2051 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2052 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2053 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2054 const char *Sym = S->getSymbol(); 2055 2056 // Create a constant pool entry for the callee address 2057 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2058 ARMConstantPoolValue *CPV = 2059 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2060 ARMPCLabelIndex, 0); 2061 // Get the address of the callee into a register 2062 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2063 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2064 Callee = DAG.getLoad( 2065 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2066 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2067 } 2068 } else if (isa<GlobalAddressSDNode>(Callee)) { 2069 // If we're optimizing for minimum size and the function is called three or 2070 // more times in this block, we can improve codesize by calling indirectly 2071 // as BLXr has a 16-bit encoding. 2072 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2073 auto *BB = CLI.CS.getParent(); 2074 bool PreferIndirect = 2075 Subtarget->isThumb() && Subtarget->hasMinSize() && 2076 count_if(GV->users(), [&BB](const User *U) { 2077 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2078 }) > 2; 2079 2080 if (!PreferIndirect) { 2081 isDirect = true; 2082 bool isDef = GV->isStrongDefinitionForLinker(); 2083 2084 // ARM call to a local ARM function is predicable. 2085 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2086 // tBX takes a register source operand. 2087 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2088 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2089 Callee = DAG.getNode( 2090 ARMISD::WrapperPIC, dl, PtrVt, 2091 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2092 Callee = DAG.getLoad( 2093 PtrVt, dl, DAG.getEntryNode(), Callee, 2094 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2095 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2096 MachineMemOperand::MOInvariant); 2097 } else if (Subtarget->isTargetCOFF()) { 2098 assert(Subtarget->isTargetWindows() && 2099 "Windows is the only supported COFF target"); 2100 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2101 ? ARMII::MO_DLLIMPORT 2102 : ARMII::MO_NO_FLAG; 2103 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2104 TargetFlags); 2105 if (GV->hasDLLImportStorageClass()) 2106 Callee = 2107 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2108 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2109 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2110 } else { 2111 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2112 } 2113 } 2114 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2115 isDirect = true; 2116 // tBX takes a register source operand. 2117 const char *Sym = S->getSymbol(); 2118 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2119 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2120 ARMConstantPoolValue *CPV = 2121 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2122 ARMPCLabelIndex, 4); 2123 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2124 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2125 Callee = DAG.getLoad( 2126 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2127 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2128 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2129 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2130 } else { 2131 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2132 } 2133 } 2134 2135 // FIXME: handle tail calls differently. 2136 unsigned CallOpc; 2137 if (Subtarget->isThumb()) { 2138 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2139 CallOpc = ARMISD::CALL_NOLINK; 2140 else 2141 CallOpc = ARMISD::CALL; 2142 } else { 2143 if (!isDirect && !Subtarget->hasV5TOps()) 2144 CallOpc = ARMISD::CALL_NOLINK; 2145 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2146 // Emit regular call when code size is the priority 2147 !Subtarget->hasMinSize()) 2148 // "mov lr, pc; b _foo" to avoid confusing the RSP 2149 CallOpc = ARMISD::CALL_NOLINK; 2150 else 2151 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2152 } 2153 2154 std::vector<SDValue> Ops; 2155 Ops.push_back(Chain); 2156 Ops.push_back(Callee); 2157 2158 // Add argument registers to the end of the list so that they are known live 2159 // into the call. 2160 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2161 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2162 RegsToPass[i].second.getValueType())); 2163 2164 // Add a register mask operand representing the call-preserved registers. 2165 if (!isTailCall) { 2166 const uint32_t *Mask; 2167 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2168 if (isThisReturn) { 2169 // For 'this' returns, use the R0-preserving mask if applicable 2170 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2171 if (!Mask) { 2172 // Set isThisReturn to false if the calling convention is not one that 2173 // allows 'returned' to be modeled in this way, so LowerCallResult does 2174 // not try to pass 'this' straight through 2175 isThisReturn = false; 2176 Mask = ARI->getCallPreservedMask(MF, CallConv); 2177 } 2178 } else 2179 Mask = ARI->getCallPreservedMask(MF, CallConv); 2180 2181 assert(Mask && "Missing call preserved mask for calling convention"); 2182 Ops.push_back(DAG.getRegisterMask(Mask)); 2183 } 2184 2185 if (InFlag.getNode()) 2186 Ops.push_back(InFlag); 2187 2188 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2189 if (isTailCall) { 2190 MF.getFrameInfo().setHasTailCall(); 2191 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2192 } 2193 2194 // Returns a chain and a flag for retval copy to use. 2195 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2196 InFlag = Chain.getValue(1); 2197 2198 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2199 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2200 if (!Ins.empty()) 2201 InFlag = Chain.getValue(1); 2202 2203 // Handle result values, copying them out of physregs into vregs that we 2204 // return. 2205 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2206 InVals, isThisReturn, 2207 isThisReturn ? OutVals[0] : SDValue()); 2208 } 2209 2210 /// HandleByVal - Every parameter *after* a byval parameter is passed 2211 /// on the stack. Remember the next parameter register to allocate, 2212 /// and then confiscate the rest of the parameter registers to insure 2213 /// this. 2214 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2215 unsigned Align) const { 2216 // Byval (as with any stack) slots are always at least 4 byte aligned. 2217 Align = std::max(Align, 4U); 2218 2219 unsigned Reg = State->AllocateReg(GPRArgRegs); 2220 if (!Reg) 2221 return; 2222 2223 unsigned AlignInRegs = Align / 4; 2224 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2225 for (unsigned i = 0; i < Waste; ++i) 2226 Reg = State->AllocateReg(GPRArgRegs); 2227 2228 if (!Reg) 2229 return; 2230 2231 unsigned Excess = 4 * (ARM::R4 - Reg); 2232 2233 // Special case when NSAA != SP and parameter size greater than size of 2234 // all remained GPR regs. In that case we can't split parameter, we must 2235 // send it to stack. We also must set NCRN to R4, so waste all 2236 // remained registers. 2237 const unsigned NSAAOffset = State->getNextStackOffset(); 2238 if (NSAAOffset != 0 && Size > Excess) { 2239 while (State->AllocateReg(GPRArgRegs)) 2240 ; 2241 return; 2242 } 2243 2244 // First register for byval parameter is the first register that wasn't 2245 // allocated before this method call, so it would be "reg". 2246 // If parameter is small enough to be saved in range [reg, r4), then 2247 // the end (first after last) register would be reg + param-size-in-regs, 2248 // else parameter would be splitted between registers and stack, 2249 // end register would be r4 in this case. 2250 unsigned ByValRegBegin = Reg; 2251 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2252 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2253 // Note, first register is allocated in the beginning of function already, 2254 // allocate remained amount of registers we need. 2255 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2256 State->AllocateReg(GPRArgRegs); 2257 // A byval parameter that is split between registers and memory needs its 2258 // size truncated here. 2259 // In the case where the entire structure fits in registers, we set the 2260 // size in memory to zero. 2261 Size = std::max<int>(Size - Excess, 0); 2262 } 2263 2264 /// MatchingStackOffset - Return true if the given stack call argument is 2265 /// already available in the same position (relatively) of the caller's 2266 /// incoming argument stack. 2267 static 2268 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2269 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2270 const TargetInstrInfo *TII) { 2271 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2272 int FI = std::numeric_limits<int>::max(); 2273 if (Arg.getOpcode() == ISD::CopyFromReg) { 2274 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2275 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2276 return false; 2277 MachineInstr *Def = MRI->getVRegDef(VR); 2278 if (!Def) 2279 return false; 2280 if (!Flags.isByVal()) { 2281 if (!TII->isLoadFromStackSlot(*Def, FI)) 2282 return false; 2283 } else { 2284 return false; 2285 } 2286 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2287 if (Flags.isByVal()) 2288 // ByVal argument is passed in as a pointer but it's now being 2289 // dereferenced. e.g. 2290 // define @foo(%struct.X* %A) { 2291 // tail call @bar(%struct.X* byval %A) 2292 // } 2293 return false; 2294 SDValue Ptr = Ld->getBasePtr(); 2295 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2296 if (!FINode) 2297 return false; 2298 FI = FINode->getIndex(); 2299 } else 2300 return false; 2301 2302 assert(FI != std::numeric_limits<int>::max()); 2303 if (!MFI.isFixedObjectIndex(FI)) 2304 return false; 2305 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2306 } 2307 2308 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2309 /// for tail call optimization. Targets which want to do tail call 2310 /// optimization should implement this function. 2311 bool 2312 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2313 CallingConv::ID CalleeCC, 2314 bool isVarArg, 2315 bool isCalleeStructRet, 2316 bool isCallerStructRet, 2317 const SmallVectorImpl<ISD::OutputArg> &Outs, 2318 const SmallVectorImpl<SDValue> &OutVals, 2319 const SmallVectorImpl<ISD::InputArg> &Ins, 2320 SelectionDAG& DAG) const { 2321 MachineFunction &MF = DAG.getMachineFunction(); 2322 const Function &CallerF = MF.getFunction(); 2323 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2324 2325 assert(Subtarget->supportsTailCall()); 2326 2327 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2328 // to the call take up r0-r3. The reason is that there are no legal registers 2329 // left to hold the pointer to the function to be called. 2330 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2331 !isa<GlobalAddressSDNode>(Callee.getNode())) 2332 return false; 2333 2334 // Look for obvious safe cases to perform tail call optimization that do not 2335 // require ABI changes. This is what gcc calls sibcall. 2336 2337 // Exception-handling functions need a special set of instructions to indicate 2338 // a return to the hardware. Tail-calling another function would probably 2339 // break this. 2340 if (CallerF.hasFnAttribute("interrupt")) 2341 return false; 2342 2343 // Also avoid sibcall optimization if either caller or callee uses struct 2344 // return semantics. 2345 if (isCalleeStructRet || isCallerStructRet) 2346 return false; 2347 2348 // Externally-defined functions with weak linkage should not be 2349 // tail-called on ARM when the OS does not support dynamic 2350 // pre-emption of symbols, as the AAELF spec requires normal calls 2351 // to undefined weak functions to be replaced with a NOP or jump to the 2352 // next instruction. The behaviour of branch instructions in this 2353 // situation (as used for tail calls) is implementation-defined, so we 2354 // cannot rely on the linker replacing the tail call with a return. 2355 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2356 const GlobalValue *GV = G->getGlobal(); 2357 const Triple &TT = getTargetMachine().getTargetTriple(); 2358 if (GV->hasExternalWeakLinkage() && 2359 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2360 return false; 2361 } 2362 2363 // Check that the call results are passed in the same way. 2364 LLVMContext &C = *DAG.getContext(); 2365 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2366 CCAssignFnForReturn(CalleeCC, isVarArg), 2367 CCAssignFnForReturn(CallerCC, isVarArg))) 2368 return false; 2369 // The callee has to preserve all registers the caller needs to preserve. 2370 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2371 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2372 if (CalleeCC != CallerCC) { 2373 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2374 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2375 return false; 2376 } 2377 2378 // If Caller's vararg or byval argument has been split between registers and 2379 // stack, do not perform tail call, since part of the argument is in caller's 2380 // local frame. 2381 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2382 if (AFI_Caller->getArgRegsSaveSize()) 2383 return false; 2384 2385 // If the callee takes no arguments then go on to check the results of the 2386 // call. 2387 if (!Outs.empty()) { 2388 // Check if stack adjustment is needed. For now, do not do this if any 2389 // argument is passed on the stack. 2390 SmallVector<CCValAssign, 16> ArgLocs; 2391 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2392 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2393 if (CCInfo.getNextStackOffset()) { 2394 // Check if the arguments are already laid out in the right way as 2395 // the caller's fixed stack objects. 2396 MachineFrameInfo &MFI = MF.getFrameInfo(); 2397 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2398 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2399 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2400 i != e; 2401 ++i, ++realArgIdx) { 2402 CCValAssign &VA = ArgLocs[i]; 2403 EVT RegVT = VA.getLocVT(); 2404 SDValue Arg = OutVals[realArgIdx]; 2405 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2406 if (VA.getLocInfo() == CCValAssign::Indirect) 2407 return false; 2408 if (VA.needsCustom()) { 2409 // f64 and vector types are split into multiple registers or 2410 // register/stack-slot combinations. The types will not match 2411 // the registers; give up on memory f64 refs until we figure 2412 // out what to do about this. 2413 if (!VA.isRegLoc()) 2414 return false; 2415 if (!ArgLocs[++i].isRegLoc()) 2416 return false; 2417 if (RegVT == MVT::v2f64) { 2418 if (!ArgLocs[++i].isRegLoc()) 2419 return false; 2420 if (!ArgLocs[++i].isRegLoc()) 2421 return false; 2422 } 2423 } else if (!VA.isRegLoc()) { 2424 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2425 MFI, MRI, TII)) 2426 return false; 2427 } 2428 } 2429 } 2430 2431 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2432 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2433 return false; 2434 } 2435 2436 return true; 2437 } 2438 2439 bool 2440 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2441 MachineFunction &MF, bool isVarArg, 2442 const SmallVectorImpl<ISD::OutputArg> &Outs, 2443 LLVMContext &Context) const { 2444 SmallVector<CCValAssign, 16> RVLocs; 2445 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2446 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2447 } 2448 2449 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2450 const SDLoc &DL, SelectionDAG &DAG) { 2451 const MachineFunction &MF = DAG.getMachineFunction(); 2452 const Function &F = MF.getFunction(); 2453 2454 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2455 2456 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2457 // version of the "preferred return address". These offsets affect the return 2458 // instruction if this is a return from PL1 without hypervisor extensions. 2459 // IRQ/FIQ: +4 "subs pc, lr, #4" 2460 // SWI: 0 "subs pc, lr, #0" 2461 // ABORT: +4 "subs pc, lr, #4" 2462 // UNDEF: +4/+2 "subs pc, lr, #0" 2463 // UNDEF varies depending on where the exception came from ARM or Thumb 2464 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2465 2466 int64_t LROffset; 2467 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2468 IntKind == "ABORT") 2469 LROffset = 4; 2470 else if (IntKind == "SWI" || IntKind == "UNDEF") 2471 LROffset = 0; 2472 else 2473 report_fatal_error("Unsupported interrupt attribute. If present, value " 2474 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2475 2476 RetOps.insert(RetOps.begin() + 1, 2477 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2478 2479 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2480 } 2481 2482 SDValue 2483 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2484 bool isVarArg, 2485 const SmallVectorImpl<ISD::OutputArg> &Outs, 2486 const SmallVectorImpl<SDValue> &OutVals, 2487 const SDLoc &dl, SelectionDAG &DAG) const { 2488 // CCValAssign - represent the assignment of the return value to a location. 2489 SmallVector<CCValAssign, 16> RVLocs; 2490 2491 // CCState - Info about the registers and stack slots. 2492 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2493 *DAG.getContext()); 2494 2495 // Analyze outgoing return values. 2496 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2497 2498 SDValue Flag; 2499 SmallVector<SDValue, 4> RetOps; 2500 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2501 bool isLittleEndian = Subtarget->isLittle(); 2502 2503 MachineFunction &MF = DAG.getMachineFunction(); 2504 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2505 AFI->setReturnRegsCount(RVLocs.size()); 2506 2507 // Copy the result values into the output registers. 2508 for (unsigned i = 0, realRVLocIdx = 0; 2509 i != RVLocs.size(); 2510 ++i, ++realRVLocIdx) { 2511 CCValAssign &VA = RVLocs[i]; 2512 assert(VA.isRegLoc() && "Can only return in registers!"); 2513 2514 SDValue Arg = OutVals[realRVLocIdx]; 2515 bool ReturnF16 = false; 2516 2517 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2518 // Half-precision return values can be returned like this: 2519 // 2520 // t11 f16 = fadd ... 2521 // t12: i16 = bitcast t11 2522 // t13: i32 = zero_extend t12 2523 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2524 // 2525 // to avoid code generation for bitcasts, we simply set Arg to the node 2526 // that produces the f16 value, t11 in this case. 2527 // 2528 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2529 SDValue ZE = Arg.getOperand(0); 2530 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2531 SDValue BC = ZE.getOperand(0); 2532 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2533 Arg = BC.getOperand(0); 2534 ReturnF16 = true; 2535 } 2536 } 2537 } 2538 } 2539 2540 switch (VA.getLocInfo()) { 2541 default: llvm_unreachable("Unknown loc info!"); 2542 case CCValAssign::Full: break; 2543 case CCValAssign::BCvt: 2544 if (!ReturnF16) 2545 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2546 break; 2547 } 2548 2549 if (VA.needsCustom()) { 2550 if (VA.getLocVT() == MVT::v2f64) { 2551 // Extract the first half and return it in two registers. 2552 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2553 DAG.getConstant(0, dl, MVT::i32)); 2554 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2555 DAG.getVTList(MVT::i32, MVT::i32), Half); 2556 2557 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2558 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2559 Flag); 2560 Flag = Chain.getValue(1); 2561 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2562 VA = RVLocs[++i]; // skip ahead to next loc 2563 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2564 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2565 Flag); 2566 Flag = Chain.getValue(1); 2567 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2568 VA = RVLocs[++i]; // skip ahead to next loc 2569 2570 // Extract the 2nd half and fall through to handle it as an f64 value. 2571 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2572 DAG.getConstant(1, dl, MVT::i32)); 2573 } 2574 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2575 // available. 2576 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2577 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2578 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2579 fmrrd.getValue(isLittleEndian ? 0 : 1), 2580 Flag); 2581 Flag = Chain.getValue(1); 2582 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2583 VA = RVLocs[++i]; // skip ahead to next loc 2584 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2585 fmrrd.getValue(isLittleEndian ? 1 : 0), 2586 Flag); 2587 } else 2588 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2589 2590 // Guarantee that all emitted copies are 2591 // stuck together, avoiding something bad. 2592 Flag = Chain.getValue(1); 2593 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2594 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2595 } 2596 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2597 const MCPhysReg *I = 2598 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2599 if (I) { 2600 for (; *I; ++I) { 2601 if (ARM::GPRRegClass.contains(*I)) 2602 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2603 else if (ARM::DPRRegClass.contains(*I)) 2604 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2605 else 2606 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2607 } 2608 } 2609 2610 // Update chain and glue. 2611 RetOps[0] = Chain; 2612 if (Flag.getNode()) 2613 RetOps.push_back(Flag); 2614 2615 // CPUs which aren't M-class use a special sequence to return from 2616 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2617 // though we use "subs pc, lr, #N"). 2618 // 2619 // M-class CPUs actually use a normal return sequence with a special 2620 // (hardware-provided) value in LR, so the normal code path works. 2621 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2622 !Subtarget->isMClass()) { 2623 if (Subtarget->isThumb1Only()) 2624 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2625 return LowerInterruptReturn(RetOps, dl, DAG); 2626 } 2627 2628 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2629 } 2630 2631 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2632 if (N->getNumValues() != 1) 2633 return false; 2634 if (!N->hasNUsesOfValue(1, 0)) 2635 return false; 2636 2637 SDValue TCChain = Chain; 2638 SDNode *Copy = *N->use_begin(); 2639 if (Copy->getOpcode() == ISD::CopyToReg) { 2640 // If the copy has a glue operand, we conservatively assume it isn't safe to 2641 // perform a tail call. 2642 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2643 return false; 2644 TCChain = Copy->getOperand(0); 2645 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2646 SDNode *VMov = Copy; 2647 // f64 returned in a pair of GPRs. 2648 SmallPtrSet<SDNode*, 2> Copies; 2649 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2650 UI != UE; ++UI) { 2651 if (UI->getOpcode() != ISD::CopyToReg) 2652 return false; 2653 Copies.insert(*UI); 2654 } 2655 if (Copies.size() > 2) 2656 return false; 2657 2658 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2659 UI != UE; ++UI) { 2660 SDValue UseChain = UI->getOperand(0); 2661 if (Copies.count(UseChain.getNode())) 2662 // Second CopyToReg 2663 Copy = *UI; 2664 else { 2665 // We are at the top of this chain. 2666 // If the copy has a glue operand, we conservatively assume it 2667 // isn't safe to perform a tail call. 2668 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2669 return false; 2670 // First CopyToReg 2671 TCChain = UseChain; 2672 } 2673 } 2674 } else if (Copy->getOpcode() == ISD::BITCAST) { 2675 // f32 returned in a single GPR. 2676 if (!Copy->hasOneUse()) 2677 return false; 2678 Copy = *Copy->use_begin(); 2679 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2680 return false; 2681 // If the copy has a glue operand, we conservatively assume it isn't safe to 2682 // perform a tail call. 2683 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2684 return false; 2685 TCChain = Copy->getOperand(0); 2686 } else { 2687 return false; 2688 } 2689 2690 bool HasRet = false; 2691 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2692 UI != UE; ++UI) { 2693 if (UI->getOpcode() != ARMISD::RET_FLAG && 2694 UI->getOpcode() != ARMISD::INTRET_FLAG) 2695 return false; 2696 HasRet = true; 2697 } 2698 2699 if (!HasRet) 2700 return false; 2701 2702 Chain = TCChain; 2703 return true; 2704 } 2705 2706 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2707 if (!Subtarget->supportsTailCall()) 2708 return false; 2709 2710 auto Attr = 2711 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2712 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2713 return false; 2714 2715 return true; 2716 } 2717 2718 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2719 // and pass the lower and high parts through. 2720 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2721 SDLoc DL(Op); 2722 SDValue WriteValue = Op->getOperand(2); 2723 2724 // This function is only supposed to be called for i64 type argument. 2725 assert(WriteValue.getValueType() == MVT::i64 2726 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2727 2728 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2729 DAG.getConstant(0, DL, MVT::i32)); 2730 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2731 DAG.getConstant(1, DL, MVT::i32)); 2732 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2733 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2734 } 2735 2736 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2737 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2738 // one of the above mentioned nodes. It has to be wrapped because otherwise 2739 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2740 // be used to form addressing mode. These wrapped nodes will be selected 2741 // into MOVi. 2742 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2743 SelectionDAG &DAG) const { 2744 EVT PtrVT = Op.getValueType(); 2745 // FIXME there is no actual debug info here 2746 SDLoc dl(Op); 2747 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2748 SDValue Res; 2749 2750 // When generating execute-only code Constant Pools must be promoted to the 2751 // global data section. It's a bit ugly that we can't share them across basic 2752 // blocks, but this way we guarantee that execute-only behaves correct with 2753 // position-independent addressing modes. 2754 if (Subtarget->genExecuteOnly()) { 2755 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2756 auto T = const_cast<Type*>(CP->getType()); 2757 auto C = const_cast<Constant*>(CP->getConstVal()); 2758 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2759 getFunction().getParent()); 2760 auto GV = new GlobalVariable( 2761 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2762 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2763 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2764 Twine(AFI->createPICLabelUId()) 2765 ); 2766 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2767 dl, PtrVT); 2768 return LowerGlobalAddress(GA, DAG); 2769 } 2770 2771 if (CP->isMachineConstantPoolEntry()) 2772 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2773 CP->getAlignment()); 2774 else 2775 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2776 CP->getAlignment()); 2777 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2778 } 2779 2780 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2781 return MachineJumpTableInfo::EK_Inline; 2782 } 2783 2784 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2785 SelectionDAG &DAG) const { 2786 MachineFunction &MF = DAG.getMachineFunction(); 2787 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2788 unsigned ARMPCLabelIndex = 0; 2789 SDLoc DL(Op); 2790 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2791 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2792 SDValue CPAddr; 2793 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2794 if (!IsPositionIndependent) { 2795 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2796 } else { 2797 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2798 ARMPCLabelIndex = AFI->createPICLabelUId(); 2799 ARMConstantPoolValue *CPV = 2800 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2801 ARMCP::CPBlockAddress, PCAdj); 2802 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2803 } 2804 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2805 SDValue Result = DAG.getLoad( 2806 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2807 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2808 if (!IsPositionIndependent) 2809 return Result; 2810 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2811 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2812 } 2813 2814 /// Convert a TLS address reference into the correct sequence of loads 2815 /// and calls to compute the variable's address for Darwin, and return an 2816 /// SDValue containing the final node. 2817 2818 /// Darwin only has one TLS scheme which must be capable of dealing with the 2819 /// fully general situation, in the worst case. This means: 2820 /// + "extern __thread" declaration. 2821 /// + Defined in a possibly unknown dynamic library. 2822 /// 2823 /// The general system is that each __thread variable has a [3 x i32] descriptor 2824 /// which contains information used by the runtime to calculate the address. The 2825 /// only part of this the compiler needs to know about is the first word, which 2826 /// contains a function pointer that must be called with the address of the 2827 /// entire descriptor in "r0". 2828 /// 2829 /// Since this descriptor may be in a different unit, in general access must 2830 /// proceed along the usual ARM rules. A common sequence to produce is: 2831 /// 2832 /// movw rT1, :lower16:_var$non_lazy_ptr 2833 /// movt rT1, :upper16:_var$non_lazy_ptr 2834 /// ldr r0, [rT1] 2835 /// ldr rT2, [r0] 2836 /// blx rT2 2837 /// [...address now in r0...] 2838 SDValue 2839 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2840 SelectionDAG &DAG) const { 2841 assert(Subtarget->isTargetDarwin() && 2842 "This function expects a Darwin target"); 2843 SDLoc DL(Op); 2844 2845 // First step is to get the address of the actua global symbol. This is where 2846 // the TLS descriptor lives. 2847 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2848 2849 // The first entry in the descriptor is a function pointer that we must call 2850 // to obtain the address of the variable. 2851 SDValue Chain = DAG.getEntryNode(); 2852 SDValue FuncTLVGet = DAG.getLoad( 2853 MVT::i32, DL, Chain, DescAddr, 2854 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2855 /* Alignment = */ 4, 2856 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2857 MachineMemOperand::MOInvariant); 2858 Chain = FuncTLVGet.getValue(1); 2859 2860 MachineFunction &F = DAG.getMachineFunction(); 2861 MachineFrameInfo &MFI = F.getFrameInfo(); 2862 MFI.setAdjustsStack(true); 2863 2864 // TLS calls preserve all registers except those that absolutely must be 2865 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2866 // silly). 2867 auto TRI = 2868 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2869 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2870 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2871 2872 // Finally, we can make the call. This is just a degenerate version of a 2873 // normal AArch64 call node: r0 takes the address of the descriptor, and 2874 // returns the address of the variable in this thread. 2875 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2876 Chain = 2877 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2878 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2879 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2880 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2881 } 2882 2883 SDValue 2884 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2885 SelectionDAG &DAG) const { 2886 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2887 2888 SDValue Chain = DAG.getEntryNode(); 2889 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2890 SDLoc DL(Op); 2891 2892 // Load the current TEB (thread environment block) 2893 SDValue Ops[] = {Chain, 2894 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2895 DAG.getConstant(15, DL, MVT::i32), 2896 DAG.getConstant(0, DL, MVT::i32), 2897 DAG.getConstant(13, DL, MVT::i32), 2898 DAG.getConstant(0, DL, MVT::i32), 2899 DAG.getConstant(2, DL, MVT::i32)}; 2900 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2901 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2902 2903 SDValue TEB = CurrentTEB.getValue(0); 2904 Chain = CurrentTEB.getValue(1); 2905 2906 // Load the ThreadLocalStoragePointer from the TEB 2907 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2908 SDValue TLSArray = 2909 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2910 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2911 2912 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2913 // offset into the TLSArray. 2914 2915 // Load the TLS index from the C runtime 2916 SDValue TLSIndex = 2917 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2918 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2919 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2920 2921 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2922 DAG.getConstant(2, DL, MVT::i32)); 2923 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2924 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2925 MachinePointerInfo()); 2926 2927 // Get the offset of the start of the .tls section (section base) 2928 const auto *GA = cast<GlobalAddressSDNode>(Op); 2929 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2930 SDValue Offset = DAG.getLoad( 2931 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2932 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2933 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2934 2935 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2936 } 2937 2938 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2939 SDValue 2940 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2941 SelectionDAG &DAG) const { 2942 SDLoc dl(GA); 2943 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2944 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2945 MachineFunction &MF = DAG.getMachineFunction(); 2946 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2947 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2948 ARMConstantPoolValue *CPV = 2949 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2950 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2951 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2952 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2953 Argument = DAG.getLoad( 2954 PtrVT, dl, DAG.getEntryNode(), Argument, 2955 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2956 SDValue Chain = Argument.getValue(1); 2957 2958 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2959 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2960 2961 // call __tls_get_addr. 2962 ArgListTy Args; 2963 ArgListEntry Entry; 2964 Entry.Node = Argument; 2965 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2966 Args.push_back(Entry); 2967 2968 // FIXME: is there useful debug info available here? 2969 TargetLowering::CallLoweringInfo CLI(DAG); 2970 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2971 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2972 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2973 2974 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2975 return CallResult.first; 2976 } 2977 2978 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2979 // "local exec" model. 2980 SDValue 2981 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2982 SelectionDAG &DAG, 2983 TLSModel::Model model) const { 2984 const GlobalValue *GV = GA->getGlobal(); 2985 SDLoc dl(GA); 2986 SDValue Offset; 2987 SDValue Chain = DAG.getEntryNode(); 2988 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2989 // Get the Thread Pointer 2990 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2991 2992 if (model == TLSModel::InitialExec) { 2993 MachineFunction &MF = DAG.getMachineFunction(); 2994 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2995 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2996 // Initial exec model. 2997 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2998 ARMConstantPoolValue *CPV = 2999 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3000 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3001 true); 3002 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3003 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3004 Offset = DAG.getLoad( 3005 PtrVT, dl, Chain, Offset, 3006 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3007 Chain = Offset.getValue(1); 3008 3009 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3010 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3011 3012 Offset = DAG.getLoad( 3013 PtrVT, dl, Chain, Offset, 3014 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3015 } else { 3016 // local exec model 3017 assert(model == TLSModel::LocalExec); 3018 ARMConstantPoolValue *CPV = 3019 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3020 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3021 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3022 Offset = DAG.getLoad( 3023 PtrVT, dl, Chain, Offset, 3024 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3025 } 3026 3027 // The address of the thread local variable is the add of the thread 3028 // pointer with the offset of the variable. 3029 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3030 } 3031 3032 SDValue 3033 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3034 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3035 if (DAG.getTarget().useEmulatedTLS()) 3036 return LowerToTLSEmulatedModel(GA, DAG); 3037 3038 if (Subtarget->isTargetDarwin()) 3039 return LowerGlobalTLSAddressDarwin(Op, DAG); 3040 3041 if (Subtarget->isTargetWindows()) 3042 return LowerGlobalTLSAddressWindows(Op, DAG); 3043 3044 // TODO: implement the "local dynamic" model 3045 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3046 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3047 3048 switch (model) { 3049 case TLSModel::GeneralDynamic: 3050 case TLSModel::LocalDynamic: 3051 return LowerToTLSGeneralDynamicModel(GA, DAG); 3052 case TLSModel::InitialExec: 3053 case TLSModel::LocalExec: 3054 return LowerToTLSExecModels(GA, DAG, model); 3055 } 3056 llvm_unreachable("bogus TLS model"); 3057 } 3058 3059 /// Return true if all users of V are within function F, looking through 3060 /// ConstantExprs. 3061 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3062 SmallVector<const User*,4> Worklist; 3063 for (auto *U : V->users()) 3064 Worklist.push_back(U); 3065 while (!Worklist.empty()) { 3066 auto *U = Worklist.pop_back_val(); 3067 if (isa<ConstantExpr>(U)) { 3068 for (auto *UU : U->users()) 3069 Worklist.push_back(UU); 3070 continue; 3071 } 3072 3073 auto *I = dyn_cast<Instruction>(U); 3074 if (!I || I->getParent()->getParent() != F) 3075 return false; 3076 } 3077 return true; 3078 } 3079 3080 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3081 const GlobalValue *GV, SelectionDAG &DAG, 3082 EVT PtrVT, const SDLoc &dl) { 3083 // If we're creating a pool entry for a constant global with unnamed address, 3084 // and the global is small enough, we can emit it inline into the constant pool 3085 // to save ourselves an indirection. 3086 // 3087 // This is a win if the constant is only used in one function (so it doesn't 3088 // need to be duplicated) or duplicating the constant wouldn't increase code 3089 // size (implying the constant is no larger than 4 bytes). 3090 const Function &F = DAG.getMachineFunction().getFunction(); 3091 3092 // We rely on this decision to inline being idemopotent and unrelated to the 3093 // use-site. We know that if we inline a variable at one use site, we'll 3094 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3095 // doesn't know about this optimization, so bail out if it's enabled else 3096 // we could decide to inline here (and thus never emit the GV) but require 3097 // the GV from fast-isel generated code. 3098 if (!EnableConstpoolPromotion || 3099 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3100 return SDValue(); 3101 3102 auto *GVar = dyn_cast<GlobalVariable>(GV); 3103 if (!GVar || !GVar->hasInitializer() || 3104 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3105 !GVar->hasLocalLinkage()) 3106 return SDValue(); 3107 3108 // If we inline a value that contains relocations, we move the relocations 3109 // from .data to .text. This is not allowed in position-independent code. 3110 auto *Init = GVar->getInitializer(); 3111 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3112 Init->needsRelocation()) 3113 return SDValue(); 3114 3115 // The constant islands pass can only really deal with alignment requests 3116 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3117 // any type wanting greater alignment requirements than 4 bytes. We also 3118 // can only promote constants that are multiples of 4 bytes in size or 3119 // are paddable to a multiple of 4. Currently we only try and pad constants 3120 // that are strings for simplicity. 3121 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3122 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3123 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3124 unsigned RequiredPadding = 4 - (Size % 4); 3125 bool PaddingPossible = 3126 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3127 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3128 Size == 0) 3129 return SDValue(); 3130 3131 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3132 MachineFunction &MF = DAG.getMachineFunction(); 3133 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3134 3135 // We can't bloat the constant pool too much, else the ConstantIslands pass 3136 // may fail to converge. If we haven't promoted this global yet (it may have 3137 // multiple uses), and promoting it would increase the constant pool size (Sz 3138 // > 4), ensure we have space to do so up to MaxTotal. 3139 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3140 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3141 ConstpoolPromotionMaxTotal) 3142 return SDValue(); 3143 3144 // This is only valid if all users are in a single function; we can't clone 3145 // the constant in general. The LLVM IR unnamed_addr allows merging 3146 // constants, but not cloning them. 3147 // 3148 // We could potentially allow cloning if we could prove all uses of the 3149 // constant in the current function don't care about the address, like 3150 // printf format strings. But that isn't implemented for now. 3151 if (!allUsersAreInFunction(GVar, &F)) 3152 return SDValue(); 3153 3154 // We're going to inline this global. Pad it out if needed. 3155 if (RequiredPadding != 4) { 3156 StringRef S = CDAInit->getAsString(); 3157 3158 SmallVector<uint8_t,16> V(S.size()); 3159 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3160 while (RequiredPadding--) 3161 V.push_back(0); 3162 Init = ConstantDataArray::get(*DAG.getContext(), V); 3163 } 3164 3165 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3166 SDValue CPAddr = 3167 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3168 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3169 AFI->markGlobalAsPromotedToConstantPool(GVar); 3170 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3171 PaddedSize - 4); 3172 } 3173 ++NumConstpoolPromoted; 3174 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3175 } 3176 3177 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3178 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3179 if (!(GV = GA->getBaseObject())) 3180 return false; 3181 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3182 return V->isConstant(); 3183 return isa<Function>(GV); 3184 } 3185 3186 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3187 SelectionDAG &DAG) const { 3188 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3189 default: llvm_unreachable("unknown object format"); 3190 case Triple::COFF: 3191 return LowerGlobalAddressWindows(Op, DAG); 3192 case Triple::ELF: 3193 return LowerGlobalAddressELF(Op, DAG); 3194 case Triple::MachO: 3195 return LowerGlobalAddressDarwin(Op, DAG); 3196 } 3197 } 3198 3199 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3200 SelectionDAG &DAG) const { 3201 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3202 SDLoc dl(Op); 3203 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3204 const TargetMachine &TM = getTargetMachine(); 3205 bool IsRO = isReadOnly(GV); 3206 3207 // promoteToConstantPool only if not generating XO text section 3208 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3209 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3210 return V; 3211 3212 if (isPositionIndependent()) { 3213 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3214 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3215 UseGOT_PREL ? ARMII::MO_GOT : 0); 3216 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3217 if (UseGOT_PREL) 3218 Result = 3219 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3220 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3221 return Result; 3222 } else if (Subtarget->isROPI() && IsRO) { 3223 // PC-relative. 3224 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3225 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3226 return Result; 3227 } else if (Subtarget->isRWPI() && !IsRO) { 3228 // SB-relative. 3229 SDValue RelAddr; 3230 if (Subtarget->useMovt()) { 3231 ++NumMovwMovt; 3232 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3233 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3234 } else { // use literal pool for address constant 3235 ARMConstantPoolValue *CPV = 3236 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3237 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3238 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3239 RelAddr = DAG.getLoad( 3240 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3241 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3242 } 3243 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3244 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3245 return Result; 3246 } 3247 3248 // If we have T2 ops, we can materialize the address directly via movt/movw 3249 // pair. This is always cheaper. 3250 if (Subtarget->useMovt()) { 3251 ++NumMovwMovt; 3252 // FIXME: Once remat is capable of dealing with instructions with register 3253 // operands, expand this into two nodes. 3254 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3255 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3256 } else { 3257 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3258 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3259 return DAG.getLoad( 3260 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3261 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3262 } 3263 } 3264 3265 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3266 SelectionDAG &DAG) const { 3267 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3268 "ROPI/RWPI not currently supported for Darwin"); 3269 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3270 SDLoc dl(Op); 3271 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3272 3273 if (Subtarget->useMovt()) 3274 ++NumMovwMovt; 3275 3276 // FIXME: Once remat is capable of dealing with instructions with register 3277 // operands, expand this into multiple nodes 3278 unsigned Wrapper = 3279 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3280 3281 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3282 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3283 3284 if (Subtarget->isGVIndirectSymbol(GV)) 3285 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3286 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3287 return Result; 3288 } 3289 3290 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3291 SelectionDAG &DAG) const { 3292 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3293 assert(Subtarget->useMovt() && 3294 "Windows on ARM expects to use movw/movt"); 3295 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3296 "ROPI/RWPI not currently supported for Windows"); 3297 3298 const TargetMachine &TM = getTargetMachine(); 3299 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3300 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3301 if (GV->hasDLLImportStorageClass()) 3302 TargetFlags = ARMII::MO_DLLIMPORT; 3303 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3304 TargetFlags = ARMII::MO_COFFSTUB; 3305 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3306 SDValue Result; 3307 SDLoc DL(Op); 3308 3309 ++NumMovwMovt; 3310 3311 // FIXME: Once remat is capable of dealing with instructions with register 3312 // operands, expand this into two nodes. 3313 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3314 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3315 TargetFlags)); 3316 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3317 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3318 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3319 return Result; 3320 } 3321 3322 SDValue 3323 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3324 SDLoc dl(Op); 3325 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3326 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3327 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3328 Op.getOperand(1), Val); 3329 } 3330 3331 SDValue 3332 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3333 SDLoc dl(Op); 3334 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3335 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3336 } 3337 3338 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3339 SelectionDAG &DAG) const { 3340 SDLoc dl(Op); 3341 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3342 Op.getOperand(0)); 3343 } 3344 3345 SDValue 3346 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3347 const ARMSubtarget *Subtarget) const { 3348 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3349 SDLoc dl(Op); 3350 switch (IntNo) { 3351 default: return SDValue(); // Don't custom lower most intrinsics. 3352 case Intrinsic::thread_pointer: { 3353 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3354 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3355 } 3356 case Intrinsic::eh_sjlj_lsda: { 3357 MachineFunction &MF = DAG.getMachineFunction(); 3358 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3359 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3360 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3361 SDValue CPAddr; 3362 bool IsPositionIndependent = isPositionIndependent(); 3363 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3364 ARMConstantPoolValue *CPV = 3365 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3366 ARMCP::CPLSDA, PCAdj); 3367 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3368 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3369 SDValue Result = DAG.getLoad( 3370 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3371 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3372 3373 if (IsPositionIndependent) { 3374 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3375 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3376 } 3377 return Result; 3378 } 3379 case Intrinsic::arm_neon_vabs: 3380 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3381 Op.getOperand(1)); 3382 case Intrinsic::arm_neon_vmulls: 3383 case Intrinsic::arm_neon_vmullu: { 3384 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3385 ? ARMISD::VMULLs : ARMISD::VMULLu; 3386 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3387 Op.getOperand(1), Op.getOperand(2)); 3388 } 3389 case Intrinsic::arm_neon_vminnm: 3390 case Intrinsic::arm_neon_vmaxnm: { 3391 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3392 ? ISD::FMINNUM : ISD::FMAXNUM; 3393 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3394 Op.getOperand(1), Op.getOperand(2)); 3395 } 3396 case Intrinsic::arm_neon_vminu: 3397 case Intrinsic::arm_neon_vmaxu: { 3398 if (Op.getValueType().isFloatingPoint()) 3399 return SDValue(); 3400 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3401 ? ISD::UMIN : ISD::UMAX; 3402 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3403 Op.getOperand(1), Op.getOperand(2)); 3404 } 3405 case Intrinsic::arm_neon_vmins: 3406 case Intrinsic::arm_neon_vmaxs: { 3407 // v{min,max}s is overloaded between signed integers and floats. 3408 if (!Op.getValueType().isFloatingPoint()) { 3409 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3410 ? ISD::SMIN : ISD::SMAX; 3411 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3412 Op.getOperand(1), Op.getOperand(2)); 3413 } 3414 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3415 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3416 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3417 Op.getOperand(1), Op.getOperand(2)); 3418 } 3419 case Intrinsic::arm_neon_vtbl1: 3420 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3421 Op.getOperand(1), Op.getOperand(2)); 3422 case Intrinsic::arm_neon_vtbl2: 3423 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3424 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3425 } 3426 } 3427 3428 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3429 const ARMSubtarget *Subtarget) { 3430 SDLoc dl(Op); 3431 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3432 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3433 if (SSID == SyncScope::SingleThread) 3434 return Op; 3435 3436 if (!Subtarget->hasDataBarrier()) { 3437 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3438 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3439 // here. 3440 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3441 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3442 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3443 DAG.getConstant(0, dl, MVT::i32)); 3444 } 3445 3446 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3447 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3448 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3449 if (Subtarget->isMClass()) { 3450 // Only a full system barrier exists in the M-class architectures. 3451 Domain = ARM_MB::SY; 3452 } else if (Subtarget->preferISHSTBarriers() && 3453 Ord == AtomicOrdering::Release) { 3454 // Swift happens to implement ISHST barriers in a way that's compatible with 3455 // Release semantics but weaker than ISH so we'd be fools not to use 3456 // it. Beware: other processors probably don't! 3457 Domain = ARM_MB::ISHST; 3458 } 3459 3460 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3461 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3462 DAG.getConstant(Domain, dl, MVT::i32)); 3463 } 3464 3465 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3466 const ARMSubtarget *Subtarget) { 3467 // ARM pre v5TE and Thumb1 does not have preload instructions. 3468 if (!(Subtarget->isThumb2() || 3469 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3470 // Just preserve the chain. 3471 return Op.getOperand(0); 3472 3473 SDLoc dl(Op); 3474 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3475 if (!isRead && 3476 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3477 // ARMv7 with MP extension has PLDW. 3478 return Op.getOperand(0); 3479 3480 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3481 if (Subtarget->isThumb()) { 3482 // Invert the bits. 3483 isRead = ~isRead & 1; 3484 isData = ~isData & 1; 3485 } 3486 3487 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3488 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3489 DAG.getConstant(isData, dl, MVT::i32)); 3490 } 3491 3492 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3493 MachineFunction &MF = DAG.getMachineFunction(); 3494 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3495 3496 // vastart just stores the address of the VarArgsFrameIndex slot into the 3497 // memory location argument. 3498 SDLoc dl(Op); 3499 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3500 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3501 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3502 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3503 MachinePointerInfo(SV)); 3504 } 3505 3506 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3507 CCValAssign &NextVA, 3508 SDValue &Root, 3509 SelectionDAG &DAG, 3510 const SDLoc &dl) const { 3511 MachineFunction &MF = DAG.getMachineFunction(); 3512 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3513 3514 const TargetRegisterClass *RC; 3515 if (AFI->isThumb1OnlyFunction()) 3516 RC = &ARM::tGPRRegClass; 3517 else 3518 RC = &ARM::GPRRegClass; 3519 3520 // Transform the arguments stored in physical registers into virtual ones. 3521 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3522 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3523 3524 SDValue ArgValue2; 3525 if (NextVA.isMemLoc()) { 3526 MachineFrameInfo &MFI = MF.getFrameInfo(); 3527 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3528 3529 // Create load node to retrieve arguments from the stack. 3530 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3531 ArgValue2 = DAG.getLoad( 3532 MVT::i32, dl, Root, FIN, 3533 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3534 } else { 3535 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3536 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3537 } 3538 if (!Subtarget->isLittle()) 3539 std::swap (ArgValue, ArgValue2); 3540 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3541 } 3542 3543 // The remaining GPRs hold either the beginning of variable-argument 3544 // data, or the beginning of an aggregate passed by value (usually 3545 // byval). Either way, we allocate stack slots adjacent to the data 3546 // provided by our caller, and store the unallocated registers there. 3547 // If this is a variadic function, the va_list pointer will begin with 3548 // these values; otherwise, this reassembles a (byval) structure that 3549 // was split between registers and memory. 3550 // Return: The frame index registers were stored into. 3551 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3552 const SDLoc &dl, SDValue &Chain, 3553 const Value *OrigArg, 3554 unsigned InRegsParamRecordIdx, 3555 int ArgOffset, unsigned ArgSize) const { 3556 // Currently, two use-cases possible: 3557 // Case #1. Non-var-args function, and we meet first byval parameter. 3558 // Setup first unallocated register as first byval register; 3559 // eat all remained registers 3560 // (these two actions are performed by HandleByVal method). 3561 // Then, here, we initialize stack frame with 3562 // "store-reg" instructions. 3563 // Case #2. Var-args function, that doesn't contain byval parameters. 3564 // The same: eat all remained unallocated registers, 3565 // initialize stack frame. 3566 3567 MachineFunction &MF = DAG.getMachineFunction(); 3568 MachineFrameInfo &MFI = MF.getFrameInfo(); 3569 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3570 unsigned RBegin, REnd; 3571 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3572 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3573 } else { 3574 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3575 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3576 REnd = ARM::R4; 3577 } 3578 3579 if (REnd != RBegin) 3580 ArgOffset = -4 * (ARM::R4 - RBegin); 3581 3582 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3583 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3584 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3585 3586 SmallVector<SDValue, 4> MemOps; 3587 const TargetRegisterClass *RC = 3588 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3589 3590 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3591 unsigned VReg = MF.addLiveIn(Reg, RC); 3592 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3593 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3594 MachinePointerInfo(OrigArg, 4 * i)); 3595 MemOps.push_back(Store); 3596 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3597 } 3598 3599 if (!MemOps.empty()) 3600 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3601 return FrameIndex; 3602 } 3603 3604 // Setup stack frame, the va_list pointer will start from. 3605 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3606 const SDLoc &dl, SDValue &Chain, 3607 unsigned ArgOffset, 3608 unsigned TotalArgRegsSaveSize, 3609 bool ForceMutable) const { 3610 MachineFunction &MF = DAG.getMachineFunction(); 3611 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3612 3613 // Try to store any remaining integer argument regs 3614 // to their spots on the stack so that they may be loaded by dereferencing 3615 // the result of va_next. 3616 // If there is no regs to be stored, just point address after last 3617 // argument passed via stack. 3618 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3619 CCInfo.getInRegsParamsCount(), 3620 CCInfo.getNextStackOffset(), 4); 3621 AFI->setVarArgsFrameIndex(FrameIndex); 3622 } 3623 3624 SDValue ARMTargetLowering::LowerFormalArguments( 3625 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3626 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3627 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3628 MachineFunction &MF = DAG.getMachineFunction(); 3629 MachineFrameInfo &MFI = MF.getFrameInfo(); 3630 3631 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3632 3633 // Assign locations to all of the incoming arguments. 3634 SmallVector<CCValAssign, 16> ArgLocs; 3635 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3636 *DAG.getContext()); 3637 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3638 3639 SmallVector<SDValue, 16> ArgValues; 3640 SDValue ArgValue; 3641 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3642 unsigned CurArgIdx = 0; 3643 3644 // Initially ArgRegsSaveSize is zero. 3645 // Then we increase this value each time we meet byval parameter. 3646 // We also increase this value in case of varargs function. 3647 AFI->setArgRegsSaveSize(0); 3648 3649 // Calculate the amount of stack space that we need to allocate to store 3650 // byval and variadic arguments that are passed in registers. 3651 // We need to know this before we allocate the first byval or variadic 3652 // argument, as they will be allocated a stack slot below the CFA (Canonical 3653 // Frame Address, the stack pointer at entry to the function). 3654 unsigned ArgRegBegin = ARM::R4; 3655 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3656 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3657 break; 3658 3659 CCValAssign &VA = ArgLocs[i]; 3660 unsigned Index = VA.getValNo(); 3661 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3662 if (!Flags.isByVal()) 3663 continue; 3664 3665 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3666 unsigned RBegin, REnd; 3667 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3668 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3669 3670 CCInfo.nextInRegsParam(); 3671 } 3672 CCInfo.rewindByValRegsInfo(); 3673 3674 int lastInsIndex = -1; 3675 if (isVarArg && MFI.hasVAStart()) { 3676 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3677 if (RegIdx != array_lengthof(GPRArgRegs)) 3678 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3679 } 3680 3681 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3682 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3683 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3684 3685 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3686 CCValAssign &VA = ArgLocs[i]; 3687 if (Ins[VA.getValNo()].isOrigArg()) { 3688 std::advance(CurOrigArg, 3689 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3690 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3691 } 3692 // Arguments stored in registers. 3693 if (VA.isRegLoc()) { 3694 EVT RegVT = VA.getLocVT(); 3695 3696 if (VA.needsCustom()) { 3697 // f64 and vector types are split up into multiple registers or 3698 // combinations of registers and stack slots. 3699 if (VA.getLocVT() == MVT::v2f64) { 3700 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3701 Chain, DAG, dl); 3702 VA = ArgLocs[++i]; // skip ahead to next loc 3703 SDValue ArgValue2; 3704 if (VA.isMemLoc()) { 3705 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3706 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3707 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3708 MachinePointerInfo::getFixedStack( 3709 DAG.getMachineFunction(), FI)); 3710 } else { 3711 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3712 Chain, DAG, dl); 3713 } 3714 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3715 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3716 ArgValue, ArgValue1, 3717 DAG.getIntPtrConstant(0, dl)); 3718 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3719 ArgValue, ArgValue2, 3720 DAG.getIntPtrConstant(1, dl)); 3721 } else 3722 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3723 } else { 3724 const TargetRegisterClass *RC; 3725 3726 3727 if (RegVT == MVT::f16) 3728 RC = &ARM::HPRRegClass; 3729 else if (RegVT == MVT::f32) 3730 RC = &ARM::SPRRegClass; 3731 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3732 RC = &ARM::DPRRegClass; 3733 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3734 RC = &ARM::QPRRegClass; 3735 else if (RegVT == MVT::i32) 3736 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3737 : &ARM::GPRRegClass; 3738 else 3739 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3740 3741 // Transform the arguments in physical registers into virtual ones. 3742 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3743 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3744 } 3745 3746 // If this is an 8 or 16-bit value, it is really passed promoted 3747 // to 32 bits. Insert an assert[sz]ext to capture this, then 3748 // truncate to the right size. 3749 switch (VA.getLocInfo()) { 3750 default: llvm_unreachable("Unknown loc info!"); 3751 case CCValAssign::Full: break; 3752 case CCValAssign::BCvt: 3753 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3754 break; 3755 case CCValAssign::SExt: 3756 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3757 DAG.getValueType(VA.getValVT())); 3758 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3759 break; 3760 case CCValAssign::ZExt: 3761 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3762 DAG.getValueType(VA.getValVT())); 3763 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3764 break; 3765 } 3766 3767 InVals.push_back(ArgValue); 3768 } else { // VA.isRegLoc() 3769 // sanity check 3770 assert(VA.isMemLoc()); 3771 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3772 3773 int index = VA.getValNo(); 3774 3775 // Some Ins[] entries become multiple ArgLoc[] entries. 3776 // Process them only once. 3777 if (index != lastInsIndex) 3778 { 3779 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3780 // FIXME: For now, all byval parameter objects are marked mutable. 3781 // This can be changed with more analysis. 3782 // In case of tail call optimization mark all arguments mutable. 3783 // Since they could be overwritten by lowering of arguments in case of 3784 // a tail call. 3785 if (Flags.isByVal()) { 3786 assert(Ins[index].isOrigArg() && 3787 "Byval arguments cannot be implicit"); 3788 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3789 3790 int FrameIndex = StoreByValRegs( 3791 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3792 VA.getLocMemOffset(), Flags.getByValSize()); 3793 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3794 CCInfo.nextInRegsParam(); 3795 } else { 3796 unsigned FIOffset = VA.getLocMemOffset(); 3797 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3798 FIOffset, true); 3799 3800 // Create load nodes to retrieve arguments from the stack. 3801 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3802 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3803 MachinePointerInfo::getFixedStack( 3804 DAG.getMachineFunction(), FI))); 3805 } 3806 lastInsIndex = index; 3807 } 3808 } 3809 } 3810 3811 // varargs 3812 if (isVarArg && MFI.hasVAStart()) 3813 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3814 CCInfo.getNextStackOffset(), 3815 TotalArgRegsSaveSize); 3816 3817 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3818 3819 return Chain; 3820 } 3821 3822 /// isFloatingPointZero - Return true if this is +0.0. 3823 static bool isFloatingPointZero(SDValue Op) { 3824 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3825 return CFP->getValueAPF().isPosZero(); 3826 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3827 // Maybe this has already been legalized into the constant pool? 3828 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3829 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3830 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3831 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3832 return CFP->getValueAPF().isPosZero(); 3833 } 3834 } else if (Op->getOpcode() == ISD::BITCAST && 3835 Op->getValueType(0) == MVT::f64) { 3836 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3837 // created by LowerConstantFP(). 3838 SDValue BitcastOp = Op->getOperand(0); 3839 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3840 isNullConstant(BitcastOp->getOperand(0))) 3841 return true; 3842 } 3843 return false; 3844 } 3845 3846 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3847 /// the given operands. 3848 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3849 SDValue &ARMcc, SelectionDAG &DAG, 3850 const SDLoc &dl) const { 3851 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3852 unsigned C = RHSC->getZExtValue(); 3853 if (!isLegalICmpImmediate((int32_t)C)) { 3854 // Constant does not fit, try adjusting it by one. 3855 switch (CC) { 3856 default: break; 3857 case ISD::SETLT: 3858 case ISD::SETGE: 3859 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3860 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3861 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3862 } 3863 break; 3864 case ISD::SETULT: 3865 case ISD::SETUGE: 3866 if (C != 0 && isLegalICmpImmediate(C-1)) { 3867 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3868 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3869 } 3870 break; 3871 case ISD::SETLE: 3872 case ISD::SETGT: 3873 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3874 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3875 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3876 } 3877 break; 3878 case ISD::SETULE: 3879 case ISD::SETUGT: 3880 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3881 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3882 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3883 } 3884 break; 3885 } 3886 } 3887 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3888 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3889 // In ARM and Thumb-2, the compare instructions can shift their second 3890 // operand. 3891 CC = ISD::getSetCCSwappedOperands(CC); 3892 std::swap(LHS, RHS); 3893 } 3894 3895 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3896 ARMISD::NodeType CompareType; 3897 switch (CondCode) { 3898 default: 3899 CompareType = ARMISD::CMP; 3900 break; 3901 case ARMCC::EQ: 3902 case ARMCC::NE: 3903 // Uses only Z Flag 3904 CompareType = ARMISD::CMPZ; 3905 break; 3906 } 3907 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3908 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3909 } 3910 3911 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3912 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3913 SelectionDAG &DAG, const SDLoc &dl, 3914 bool InvalidOnQNaN) const { 3915 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3916 SDValue Cmp; 3917 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3918 if (!isFloatingPointZero(RHS)) 3919 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3920 else 3921 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3922 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3923 } 3924 3925 /// duplicateCmp - Glue values can have only one use, so this function 3926 /// duplicates a comparison node. 3927 SDValue 3928 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3929 unsigned Opc = Cmp.getOpcode(); 3930 SDLoc DL(Cmp); 3931 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3932 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3933 3934 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3935 Cmp = Cmp.getOperand(0); 3936 Opc = Cmp.getOpcode(); 3937 if (Opc == ARMISD::CMPFP) 3938 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3939 Cmp.getOperand(1), Cmp.getOperand(2)); 3940 else { 3941 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3942 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3943 Cmp.getOperand(1)); 3944 } 3945 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3946 } 3947 3948 // This function returns three things: the arithmetic computation itself 3949 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 3950 // comparison and the condition code define the case in which the arithmetic 3951 // computation *does not* overflow. 3952 std::pair<SDValue, SDValue> 3953 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3954 SDValue &ARMcc) const { 3955 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3956 3957 SDValue Value, OverflowCmp; 3958 SDValue LHS = Op.getOperand(0); 3959 SDValue RHS = Op.getOperand(1); 3960 SDLoc dl(Op); 3961 3962 // FIXME: We are currently always generating CMPs because we don't support 3963 // generating CMN through the backend. This is not as good as the natural 3964 // CMP case because it causes a register dependency and cannot be folded 3965 // later. 3966 3967 switch (Op.getOpcode()) { 3968 default: 3969 llvm_unreachable("Unknown overflow instruction!"); 3970 case ISD::SADDO: 3971 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3972 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3973 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3974 break; 3975 case ISD::UADDO: 3976 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3977 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 3978 // We do not use it in the USUBO case as Value may not be used. 3979 Value = DAG.getNode(ARMISD::ADDC, dl, 3980 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 3981 .getValue(0); 3982 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3983 break; 3984 case ISD::SSUBO: 3985 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3986 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3987 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3988 break; 3989 case ISD::USUBO: 3990 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3991 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3992 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3993 break; 3994 case ISD::UMULO: 3995 // We generate a UMUL_LOHI and then check if the high word is 0. 3996 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 3997 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 3998 DAG.getVTList(Op.getValueType(), Op.getValueType()), 3999 LHS, RHS); 4000 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4001 DAG.getConstant(0, dl, MVT::i32)); 4002 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4003 break; 4004 case ISD::SMULO: 4005 // We generate a SMUL_LOHI and then check if all the bits of the high word 4006 // are the same as the sign bit of the low word. 4007 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4008 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4009 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4010 LHS, RHS); 4011 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4012 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4013 Value.getValue(0), 4014 DAG.getConstant(31, dl, MVT::i32))); 4015 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4016 break; 4017 } // switch (...) 4018 4019 return std::make_pair(Value, OverflowCmp); 4020 } 4021 4022 SDValue 4023 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4024 // Let legalize expand this if it isn't a legal type yet. 4025 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4026 return SDValue(); 4027 4028 SDValue Value, OverflowCmp; 4029 SDValue ARMcc; 4030 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4031 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4032 SDLoc dl(Op); 4033 // We use 0 and 1 as false and true values. 4034 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4035 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4036 EVT VT = Op.getValueType(); 4037 4038 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4039 ARMcc, CCR, OverflowCmp); 4040 4041 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4042 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4043 } 4044 4045 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4046 SelectionDAG &DAG) { 4047 SDLoc DL(BoolCarry); 4048 EVT CarryVT = BoolCarry.getValueType(); 4049 4050 // This converts the boolean value carry into the carry flag by doing 4051 // ARMISD::SUBC Carry, 1 4052 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4053 DAG.getVTList(CarryVT, MVT::i32), 4054 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4055 return Carry.getValue(1); 4056 } 4057 4058 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4059 SelectionDAG &DAG) { 4060 SDLoc DL(Flags); 4061 4062 // Now convert the carry flag into a boolean carry. We do this 4063 // using ARMISD:ADDE 0, 0, Carry 4064 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4065 DAG.getConstant(0, DL, MVT::i32), 4066 DAG.getConstant(0, DL, MVT::i32), Flags); 4067 } 4068 4069 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4070 SelectionDAG &DAG) const { 4071 // Let legalize expand this if it isn't a legal type yet. 4072 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4073 return SDValue(); 4074 4075 SDValue LHS = Op.getOperand(0); 4076 SDValue RHS = Op.getOperand(1); 4077 SDLoc dl(Op); 4078 4079 EVT VT = Op.getValueType(); 4080 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4081 SDValue Value; 4082 SDValue Overflow; 4083 switch (Op.getOpcode()) { 4084 default: 4085 llvm_unreachable("Unknown overflow instruction!"); 4086 case ISD::UADDO: 4087 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4088 // Convert the carry flag into a boolean value. 4089 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4090 break; 4091 case ISD::USUBO: { 4092 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4093 // Convert the carry flag into a boolean value. 4094 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4095 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4096 // value. So compute 1 - C. 4097 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4098 DAG.getConstant(1, dl, MVT::i32), Overflow); 4099 break; 4100 } 4101 } 4102 4103 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4104 } 4105 4106 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4107 SDValue Cond = Op.getOperand(0); 4108 SDValue SelectTrue = Op.getOperand(1); 4109 SDValue SelectFalse = Op.getOperand(2); 4110 SDLoc dl(Op); 4111 unsigned Opc = Cond.getOpcode(); 4112 4113 if (Cond.getResNo() == 1 && 4114 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4115 Opc == ISD::USUBO)) { 4116 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4117 return SDValue(); 4118 4119 SDValue Value, OverflowCmp; 4120 SDValue ARMcc; 4121 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4122 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4123 EVT VT = Op.getValueType(); 4124 4125 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4126 OverflowCmp, DAG); 4127 } 4128 4129 // Convert: 4130 // 4131 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4132 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4133 // 4134 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4135 const ConstantSDNode *CMOVTrue = 4136 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4137 const ConstantSDNode *CMOVFalse = 4138 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4139 4140 if (CMOVTrue && CMOVFalse) { 4141 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4142 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4143 4144 SDValue True; 4145 SDValue False; 4146 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4147 True = SelectTrue; 4148 False = SelectFalse; 4149 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4150 True = SelectFalse; 4151 False = SelectTrue; 4152 } 4153 4154 if (True.getNode() && False.getNode()) { 4155 EVT VT = Op.getValueType(); 4156 SDValue ARMcc = Cond.getOperand(2); 4157 SDValue CCR = Cond.getOperand(3); 4158 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4159 assert(True.getValueType() == VT); 4160 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4161 } 4162 } 4163 } 4164 4165 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4166 // undefined bits before doing a full-word comparison with zero. 4167 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4168 DAG.getConstant(1, dl, Cond.getValueType())); 4169 4170 return DAG.getSelectCC(dl, Cond, 4171 DAG.getConstant(0, dl, Cond.getValueType()), 4172 SelectTrue, SelectFalse, ISD::SETNE); 4173 } 4174 4175 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4176 bool &swpCmpOps, bool &swpVselOps) { 4177 // Start by selecting the GE condition code for opcodes that return true for 4178 // 'equality' 4179 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4180 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4181 CondCode = ARMCC::GE; 4182 4183 // and GT for opcodes that return false for 'equality'. 4184 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4185 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4186 CondCode = ARMCC::GT; 4187 4188 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4189 // to swap the compare operands. 4190 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4191 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4192 swpCmpOps = true; 4193 4194 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4195 // If we have an unordered opcode, we need to swap the operands to the VSEL 4196 // instruction (effectively negating the condition). 4197 // 4198 // This also has the effect of swapping which one of 'less' or 'greater' 4199 // returns true, so we also swap the compare operands. It also switches 4200 // whether we return true for 'equality', so we compensate by picking the 4201 // opposite condition code to our original choice. 4202 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4203 CC == ISD::SETUGT) { 4204 swpCmpOps = !swpCmpOps; 4205 swpVselOps = !swpVselOps; 4206 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4207 } 4208 4209 // 'ordered' is 'anything but unordered', so use the VS condition code and 4210 // swap the VSEL operands. 4211 if (CC == ISD::SETO) { 4212 CondCode = ARMCC::VS; 4213 swpVselOps = true; 4214 } 4215 4216 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4217 // code and swap the VSEL operands. Also do this if we don't care about the 4218 // unordered case. 4219 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4220 CondCode = ARMCC::EQ; 4221 swpVselOps = true; 4222 } 4223 } 4224 4225 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4226 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4227 SDValue Cmp, SelectionDAG &DAG) const { 4228 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4229 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4230 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4231 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4232 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4233 4234 SDValue TrueLow = TrueVal.getValue(0); 4235 SDValue TrueHigh = TrueVal.getValue(1); 4236 SDValue FalseLow = FalseVal.getValue(0); 4237 SDValue FalseHigh = FalseVal.getValue(1); 4238 4239 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4240 ARMcc, CCR, Cmp); 4241 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4242 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4243 4244 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4245 } else { 4246 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4247 Cmp); 4248 } 4249 } 4250 4251 static bool isGTorGE(ISD::CondCode CC) { 4252 return CC == ISD::SETGT || CC == ISD::SETGE; 4253 } 4254 4255 static bool isLTorLE(ISD::CondCode CC) { 4256 return CC == ISD::SETLT || CC == ISD::SETLE; 4257 } 4258 4259 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4260 // All of these conditions (and their <= and >= counterparts) will do: 4261 // x < k ? k : x 4262 // x > k ? x : k 4263 // k < x ? x : k 4264 // k > x ? k : x 4265 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4266 const SDValue TrueVal, const SDValue FalseVal, 4267 const ISD::CondCode CC, const SDValue K) { 4268 return (isGTorGE(CC) && 4269 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4270 (isLTorLE(CC) && 4271 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4272 } 4273 4274 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4275 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4276 const SDValue TrueVal, const SDValue FalseVal, 4277 const ISD::CondCode CC, const SDValue K) { 4278 return (isGTorGE(CC) && 4279 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4280 (isLTorLE(CC) && 4281 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4282 } 4283 4284 // Check if two chained conditionals could be converted into SSAT or USAT. 4285 // 4286 // SSAT can replace a set of two conditional selectors that bound a number to an 4287 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4288 // 4289 // x < -k ? -k : (x > k ? k : x) 4290 // x < -k ? -k : (x < k ? x : k) 4291 // x > -k ? (x > k ? k : x) : -k 4292 // x < k ? (x < -k ? -k : x) : k 4293 // etc. 4294 // 4295 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4296 // a power of 2. 4297 // 4298 // It returns true if the conversion can be done, false otherwise. 4299 // Additionally, the variable is returned in parameter V, the constant in K and 4300 // usat is set to true if the conditional represents an unsigned saturation 4301 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4302 uint64_t &K, bool &usat) { 4303 SDValue LHS1 = Op.getOperand(0); 4304 SDValue RHS1 = Op.getOperand(1); 4305 SDValue TrueVal1 = Op.getOperand(2); 4306 SDValue FalseVal1 = Op.getOperand(3); 4307 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4308 4309 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4310 if (Op2.getOpcode() != ISD::SELECT_CC) 4311 return false; 4312 4313 SDValue LHS2 = Op2.getOperand(0); 4314 SDValue RHS2 = Op2.getOperand(1); 4315 SDValue TrueVal2 = Op2.getOperand(2); 4316 SDValue FalseVal2 = Op2.getOperand(3); 4317 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4318 4319 // Find out which are the constants and which are the variables 4320 // in each conditional 4321 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4322 ? &RHS1 4323 : nullptr; 4324 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4325 ? &RHS2 4326 : nullptr; 4327 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4328 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4329 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4330 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4331 4332 // We must detect cases where the original operations worked with 16- or 4333 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4334 // must work with sign-extended values but the select operations return 4335 // the original non-extended value. 4336 SDValue V2TmpReg = V2Tmp; 4337 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4338 V2TmpReg = V2Tmp->getOperand(0); 4339 4340 // Check that the registers and the constants have the correct values 4341 // in both conditionals 4342 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4343 V2TmpReg != V2) 4344 return false; 4345 4346 // Figure out which conditional is saturating the lower/upper bound. 4347 const SDValue *LowerCheckOp = 4348 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4349 ? &Op 4350 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4351 ? &Op2 4352 : nullptr; 4353 const SDValue *UpperCheckOp = 4354 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4355 ? &Op 4356 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4357 ? &Op2 4358 : nullptr; 4359 4360 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4361 return false; 4362 4363 // Check that the constant in the lower-bound check is 4364 // the opposite of the constant in the upper-bound check 4365 // in 1's complement. 4366 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4367 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4368 int64_t PosVal = std::max(Val1, Val2); 4369 int64_t NegVal = std::min(Val1, Val2); 4370 4371 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4372 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4373 isPowerOf2_64(PosVal + 1)) { 4374 4375 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4376 if (Val1 == ~Val2) 4377 usat = false; 4378 else if (NegVal == 0) 4379 usat = true; 4380 else 4381 return false; 4382 4383 V = V2; 4384 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4385 4386 return true; 4387 } 4388 4389 return false; 4390 } 4391 4392 // Check if a condition of the type x < k ? k : x can be converted into a 4393 // bit operation instead of conditional moves. 4394 // Currently this is allowed given: 4395 // - The conditions and values match up 4396 // - k is 0 or -1 (all ones) 4397 // This function will not check the last condition, thats up to the caller 4398 // It returns true if the transformation can be made, and in such case 4399 // returns x in V, and k in SatK. 4400 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4401 SDValue &SatK) 4402 { 4403 SDValue LHS = Op.getOperand(0); 4404 SDValue RHS = Op.getOperand(1); 4405 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4406 SDValue TrueVal = Op.getOperand(2); 4407 SDValue FalseVal = Op.getOperand(3); 4408 4409 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4410 ? &RHS 4411 : nullptr; 4412 4413 // No constant operation in comparison, early out 4414 if (!K) 4415 return false; 4416 4417 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4418 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4419 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4420 4421 // If the constant on left and right side, or variable on left and right, 4422 // does not match, early out 4423 if (*K != KTmp || V != VTmp) 4424 return false; 4425 4426 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4427 SatK = *K; 4428 return true; 4429 } 4430 4431 return false; 4432 } 4433 4434 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4435 EVT VT = Op.getValueType(); 4436 SDLoc dl(Op); 4437 4438 // Try to convert two saturating conditional selects into a single SSAT 4439 SDValue SatValue; 4440 uint64_t SatConstant; 4441 bool SatUSat; 4442 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4443 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4444 if (SatUSat) 4445 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4446 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4447 else 4448 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4449 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4450 } 4451 4452 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4453 // into more efficient bit operations, which is possible when k is 0 or -1 4454 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4455 // single instructions. On Thumb the shift and the bit operation will be two 4456 // instructions. 4457 // Only allow this transformation on full-width (32-bit) operations 4458 SDValue LowerSatConstant; 4459 if (VT == MVT::i32 && 4460 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4461 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4462 DAG.getConstant(31, dl, VT)); 4463 if (isNullConstant(LowerSatConstant)) { 4464 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4465 DAG.getAllOnesConstant(dl, VT)); 4466 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4467 } else if (isAllOnesConstant(LowerSatConstant)) 4468 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4469 } 4470 4471 SDValue LHS = Op.getOperand(0); 4472 SDValue RHS = Op.getOperand(1); 4473 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4474 SDValue TrueVal = Op.getOperand(2); 4475 SDValue FalseVal = Op.getOperand(3); 4476 4477 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4478 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4479 dl); 4480 4481 // If softenSetCCOperands only returned one value, we should compare it to 4482 // zero. 4483 if (!RHS.getNode()) { 4484 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4485 CC = ISD::SETNE; 4486 } 4487 } 4488 4489 if (LHS.getValueType() == MVT::i32) { 4490 // Try to generate VSEL on ARMv8. 4491 // The VSEL instruction can't use all the usual ARM condition 4492 // codes: it only has two bits to select the condition code, so it's 4493 // constrained to use only GE, GT, VS and EQ. 4494 // 4495 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4496 // swap the operands of the previous compare instruction (effectively 4497 // inverting the compare condition, swapping 'less' and 'greater') and 4498 // sometimes need to swap the operands to the VSEL (which inverts the 4499 // condition in the sense of firing whenever the previous condition didn't) 4500 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f16 || 4501 TrueVal.getValueType() == MVT::f32 || 4502 TrueVal.getValueType() == MVT::f64)) { 4503 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4504 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4505 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4506 CC = ISD::getSetCCInverse(CC, true); 4507 std::swap(TrueVal, FalseVal); 4508 } 4509 } 4510 4511 SDValue ARMcc; 4512 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4513 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4514 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4515 } 4516 4517 ARMCC::CondCodes CondCode, CondCode2; 4518 bool InvalidOnQNaN; 4519 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4520 4521 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 4522 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 4523 // must use VSEL (limited condition codes), due to not having conditional f16 4524 // moves. 4525 if (Subtarget->hasFPARMv8() && 4526 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 4527 (TrueVal.getValueType() == MVT::f16 || 4528 TrueVal.getValueType() == MVT::f32 || 4529 TrueVal.getValueType() == MVT::f64)) { 4530 bool swpCmpOps = false; 4531 bool swpVselOps = false; 4532 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4533 4534 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4535 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4536 if (swpCmpOps) 4537 std::swap(LHS, RHS); 4538 if (swpVselOps) 4539 std::swap(TrueVal, FalseVal); 4540 } 4541 } 4542 4543 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4544 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4545 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4546 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4547 if (CondCode2 != ARMCC::AL) { 4548 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4549 // FIXME: Needs another CMP because flag can have but one use. 4550 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4551 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4552 } 4553 return Result; 4554 } 4555 4556 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4557 /// to morph to an integer compare sequence. 4558 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4559 const ARMSubtarget *Subtarget) { 4560 SDNode *N = Op.getNode(); 4561 if (!N->hasOneUse()) 4562 // Otherwise it requires moving the value from fp to integer registers. 4563 return false; 4564 if (!N->getNumValues()) 4565 return false; 4566 EVT VT = Op.getValueType(); 4567 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4568 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4569 // vmrs are very slow, e.g. cortex-a8. 4570 return false; 4571 4572 if (isFloatingPointZero(Op)) { 4573 SeenZero = true; 4574 return true; 4575 } 4576 return ISD::isNormalLoad(N); 4577 } 4578 4579 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4580 if (isFloatingPointZero(Op)) 4581 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4582 4583 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4584 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4585 Ld->getPointerInfo(), Ld->getAlignment(), 4586 Ld->getMemOperand()->getFlags()); 4587 4588 llvm_unreachable("Unknown VFP cmp argument!"); 4589 } 4590 4591 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4592 SDValue &RetVal1, SDValue &RetVal2) { 4593 SDLoc dl(Op); 4594 4595 if (isFloatingPointZero(Op)) { 4596 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4597 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4598 return; 4599 } 4600 4601 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4602 SDValue Ptr = Ld->getBasePtr(); 4603 RetVal1 = 4604 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4605 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4606 4607 EVT PtrType = Ptr.getValueType(); 4608 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4609 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4610 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4611 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4612 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4613 Ld->getMemOperand()->getFlags()); 4614 return; 4615 } 4616 4617 llvm_unreachable("Unknown VFP cmp argument!"); 4618 } 4619 4620 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4621 /// f32 and even f64 comparisons to integer ones. 4622 SDValue 4623 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4624 SDValue Chain = Op.getOperand(0); 4625 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4626 SDValue LHS = Op.getOperand(2); 4627 SDValue RHS = Op.getOperand(3); 4628 SDValue Dest = Op.getOperand(4); 4629 SDLoc dl(Op); 4630 4631 bool LHSSeenZero = false; 4632 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4633 bool RHSSeenZero = false; 4634 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4635 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4636 // If unsafe fp math optimization is enabled and there are no other uses of 4637 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4638 // to an integer comparison. 4639 if (CC == ISD::SETOEQ) 4640 CC = ISD::SETEQ; 4641 else if (CC == ISD::SETUNE) 4642 CC = ISD::SETNE; 4643 4644 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4645 SDValue ARMcc; 4646 if (LHS.getValueType() == MVT::f32) { 4647 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4648 bitcastf32Toi32(LHS, DAG), Mask); 4649 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4650 bitcastf32Toi32(RHS, DAG), Mask); 4651 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4652 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4653 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4654 Chain, Dest, ARMcc, CCR, Cmp); 4655 } 4656 4657 SDValue LHS1, LHS2; 4658 SDValue RHS1, RHS2; 4659 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4660 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4661 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4662 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4663 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4664 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4665 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4666 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4667 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4668 } 4669 4670 return SDValue(); 4671 } 4672 4673 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4674 SDValue Chain = Op.getOperand(0); 4675 SDValue Cond = Op.getOperand(1); 4676 SDValue Dest = Op.getOperand(2); 4677 SDLoc dl(Op); 4678 4679 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4680 // instruction. 4681 unsigned Opc = Cond.getOpcode(); 4682 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4683 !Subtarget->isThumb1Only(); 4684 if (Cond.getResNo() == 1 && 4685 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4686 Opc == ISD::USUBO || OptimizeMul)) { 4687 // Only lower legal XALUO ops. 4688 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4689 return SDValue(); 4690 4691 // The actual operation with overflow check. 4692 SDValue Value, OverflowCmp; 4693 SDValue ARMcc; 4694 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4695 4696 // Reverse the condition code. 4697 ARMCC::CondCodes CondCode = 4698 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4699 CondCode = ARMCC::getOppositeCondition(CondCode); 4700 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4701 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4702 4703 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4704 OverflowCmp); 4705 } 4706 4707 return SDValue(); 4708 } 4709 4710 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4711 SDValue Chain = Op.getOperand(0); 4712 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4713 SDValue LHS = Op.getOperand(2); 4714 SDValue RHS = Op.getOperand(3); 4715 SDValue Dest = Op.getOperand(4); 4716 SDLoc dl(Op); 4717 4718 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4719 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4720 dl); 4721 4722 // If softenSetCCOperands only returned one value, we should compare it to 4723 // zero. 4724 if (!RHS.getNode()) { 4725 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4726 CC = ISD::SETNE; 4727 } 4728 } 4729 4730 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4731 // instruction. 4732 unsigned Opc = LHS.getOpcode(); 4733 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4734 !Subtarget->isThumb1Only(); 4735 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4736 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4737 Opc == ISD::USUBO || OptimizeMul) && 4738 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4739 // Only lower legal XALUO ops. 4740 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4741 return SDValue(); 4742 4743 // The actual operation with overflow check. 4744 SDValue Value, OverflowCmp; 4745 SDValue ARMcc; 4746 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4747 4748 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4749 // Reverse the condition code. 4750 ARMCC::CondCodes CondCode = 4751 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4752 CondCode = ARMCC::getOppositeCondition(CondCode); 4753 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4754 } 4755 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4756 4757 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4758 OverflowCmp); 4759 } 4760 4761 if (LHS.getValueType() == MVT::i32) { 4762 SDValue ARMcc; 4763 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4764 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4765 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4766 Chain, Dest, ARMcc, CCR, Cmp); 4767 } 4768 4769 if (getTargetMachine().Options.UnsafeFPMath && 4770 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4771 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4772 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4773 return Result; 4774 } 4775 4776 ARMCC::CondCodes CondCode, CondCode2; 4777 bool InvalidOnQNaN; 4778 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4779 4780 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4781 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4782 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4783 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4784 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4785 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4786 if (CondCode2 != ARMCC::AL) { 4787 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4788 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4789 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4790 } 4791 return Res; 4792 } 4793 4794 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4795 SDValue Chain = Op.getOperand(0); 4796 SDValue Table = Op.getOperand(1); 4797 SDValue Index = Op.getOperand(2); 4798 SDLoc dl(Op); 4799 4800 EVT PTy = getPointerTy(DAG.getDataLayout()); 4801 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4802 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4803 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4804 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4805 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4806 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4807 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4808 // which does another jump to the destination. This also makes it easier 4809 // to translate it to TBB / TBH later (Thumb2 only). 4810 // FIXME: This might not work if the function is extremely large. 4811 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4812 Addr, Op.getOperand(2), JTI); 4813 } 4814 if (isPositionIndependent() || Subtarget->isROPI()) { 4815 Addr = 4816 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4817 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4818 Chain = Addr.getValue(1); 4819 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4820 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4821 } else { 4822 Addr = 4823 DAG.getLoad(PTy, dl, Chain, Addr, 4824 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4825 Chain = Addr.getValue(1); 4826 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4827 } 4828 } 4829 4830 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4831 EVT VT = Op.getValueType(); 4832 SDLoc dl(Op); 4833 4834 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4835 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4836 return Op; 4837 return DAG.UnrollVectorOp(Op.getNode()); 4838 } 4839 4840 const bool HasFullFP16 = 4841 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 4842 4843 EVT NewTy; 4844 const EVT OpTy = Op.getOperand(0).getValueType(); 4845 if (OpTy == MVT::v4f32) 4846 NewTy = MVT::v4i32; 4847 else if (OpTy == MVT::v4f16 && HasFullFP16) 4848 NewTy = MVT::v4i16; 4849 else if (OpTy == MVT::v8f16 && HasFullFP16) 4850 NewTy = MVT::v8i16; 4851 else 4852 llvm_unreachable("Invalid type for custom lowering!"); 4853 4854 if (VT != MVT::v4i16 && VT != MVT::v8i16) 4855 return DAG.UnrollVectorOp(Op.getNode()); 4856 4857 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 4858 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4859 } 4860 4861 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4862 EVT VT = Op.getValueType(); 4863 if (VT.isVector()) 4864 return LowerVectorFP_TO_INT(Op, DAG); 4865 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4866 RTLIB::Libcall LC; 4867 if (Op.getOpcode() == ISD::FP_TO_SINT) 4868 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4869 Op.getValueType()); 4870 else 4871 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4872 Op.getValueType()); 4873 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4874 /*isSigned*/ false, SDLoc(Op)).first; 4875 } 4876 4877 return Op; 4878 } 4879 4880 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4881 EVT VT = Op.getValueType(); 4882 SDLoc dl(Op); 4883 4884 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4885 if (VT.getVectorElementType() == MVT::f32) 4886 return Op; 4887 return DAG.UnrollVectorOp(Op.getNode()); 4888 } 4889 4890 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 4891 Op.getOperand(0).getValueType() == MVT::v8i16) && 4892 "Invalid type for custom lowering!"); 4893 4894 const bool HasFullFP16 = 4895 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 4896 4897 EVT DestVecType; 4898 if (VT == MVT::v4f32) 4899 DestVecType = MVT::v4i32; 4900 else if (VT == MVT::v4f16 && HasFullFP16) 4901 DestVecType = MVT::v4i16; 4902 else if (VT == MVT::v8f16 && HasFullFP16) 4903 DestVecType = MVT::v8i16; 4904 else 4905 return DAG.UnrollVectorOp(Op.getNode()); 4906 4907 unsigned CastOpc; 4908 unsigned Opc; 4909 switch (Op.getOpcode()) { 4910 default: llvm_unreachable("Invalid opcode!"); 4911 case ISD::SINT_TO_FP: 4912 CastOpc = ISD::SIGN_EXTEND; 4913 Opc = ISD::SINT_TO_FP; 4914 break; 4915 case ISD::UINT_TO_FP: 4916 CastOpc = ISD::ZERO_EXTEND; 4917 Opc = ISD::UINT_TO_FP; 4918 break; 4919 } 4920 4921 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 4922 return DAG.getNode(Opc, dl, VT, Op); 4923 } 4924 4925 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4926 EVT VT = Op.getValueType(); 4927 if (VT.isVector()) 4928 return LowerVectorINT_TO_FP(Op, DAG); 4929 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4930 RTLIB::Libcall LC; 4931 if (Op.getOpcode() == ISD::SINT_TO_FP) 4932 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4933 Op.getValueType()); 4934 else 4935 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4936 Op.getValueType()); 4937 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4938 /*isSigned*/ false, SDLoc(Op)).first; 4939 } 4940 4941 return Op; 4942 } 4943 4944 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4945 // Implement fcopysign with a fabs and a conditional fneg. 4946 SDValue Tmp0 = Op.getOperand(0); 4947 SDValue Tmp1 = Op.getOperand(1); 4948 SDLoc dl(Op); 4949 EVT VT = Op.getValueType(); 4950 EVT SrcVT = Tmp1.getValueType(); 4951 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4952 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4953 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4954 4955 if (UseNEON) { 4956 // Use VBSL to copy the sign bit. 4957 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4958 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4959 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4960 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4961 if (VT == MVT::f64) 4962 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4963 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4964 DAG.getConstant(32, dl, MVT::i32)); 4965 else /*if (VT == MVT::f32)*/ 4966 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4967 if (SrcVT == MVT::f32) { 4968 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4969 if (VT == MVT::f64) 4970 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4971 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4972 DAG.getConstant(32, dl, MVT::i32)); 4973 } else if (VT == MVT::f32) 4974 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4975 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4976 DAG.getConstant(32, dl, MVT::i32)); 4977 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4978 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4979 4980 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4981 dl, MVT::i32); 4982 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4983 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4984 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4985 4986 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4987 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4988 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4989 if (VT == MVT::f32) { 4990 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4991 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4992 DAG.getConstant(0, dl, MVT::i32)); 4993 } else { 4994 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4995 } 4996 4997 return Res; 4998 } 4999 5000 // Bitcast operand 1 to i32. 5001 if (SrcVT == MVT::f64) 5002 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5003 Tmp1).getValue(1); 5004 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5005 5006 // Or in the signbit with integer operations. 5007 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5008 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5009 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5010 if (VT == MVT::f32) { 5011 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5012 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5013 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5014 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5015 } 5016 5017 // f64: Or the high part with signbit and then combine two parts. 5018 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5019 Tmp0); 5020 SDValue Lo = Tmp0.getValue(0); 5021 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5022 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5023 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5024 } 5025 5026 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5027 MachineFunction &MF = DAG.getMachineFunction(); 5028 MachineFrameInfo &MFI = MF.getFrameInfo(); 5029 MFI.setReturnAddressIsTaken(true); 5030 5031 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5032 return SDValue(); 5033 5034 EVT VT = Op.getValueType(); 5035 SDLoc dl(Op); 5036 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5037 if (Depth) { 5038 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5039 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5040 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5041 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5042 MachinePointerInfo()); 5043 } 5044 5045 // Return LR, which contains the return address. Mark it an implicit live-in. 5046 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5047 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5048 } 5049 5050 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5051 const ARMBaseRegisterInfo &ARI = 5052 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5053 MachineFunction &MF = DAG.getMachineFunction(); 5054 MachineFrameInfo &MFI = MF.getFrameInfo(); 5055 MFI.setFrameAddressIsTaken(true); 5056 5057 EVT VT = Op.getValueType(); 5058 SDLoc dl(Op); // FIXME probably not meaningful 5059 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5060 unsigned FrameReg = ARI.getFrameRegister(MF); 5061 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5062 while (Depth--) 5063 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5064 MachinePointerInfo()); 5065 return FrameAddr; 5066 } 5067 5068 // FIXME? Maybe this could be a TableGen attribute on some registers and 5069 // this table could be generated automatically from RegInfo. 5070 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5071 SelectionDAG &DAG) const { 5072 unsigned Reg = StringSwitch<unsigned>(RegName) 5073 .Case("sp", ARM::SP) 5074 .Default(0); 5075 if (Reg) 5076 return Reg; 5077 report_fatal_error(Twine("Invalid register name \"" 5078 + StringRef(RegName) + "\".")); 5079 } 5080 5081 // Result is 64 bit value so split into two 32 bit values and return as a 5082 // pair of values. 5083 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5084 SelectionDAG &DAG) { 5085 SDLoc DL(N); 5086 5087 // This function is only supposed to be called for i64 type destination. 5088 assert(N->getValueType(0) == MVT::i64 5089 && "ExpandREAD_REGISTER called for non-i64 type result."); 5090 5091 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5092 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5093 N->getOperand(0), 5094 N->getOperand(1)); 5095 5096 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5097 Read.getValue(1))); 5098 Results.push_back(Read.getOperand(0)); 5099 } 5100 5101 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5102 /// When \p DstVT, the destination type of \p BC, is on the vector 5103 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5104 /// it might be possible to combine them, such that everything stays on the 5105 /// vector register bank. 5106 /// \p return The node that would replace \p BT, if the combine 5107 /// is possible. 5108 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5109 SelectionDAG &DAG) { 5110 SDValue Op = BC->getOperand(0); 5111 EVT DstVT = BC->getValueType(0); 5112 5113 // The only vector instruction that can produce a scalar (remember, 5114 // since the bitcast was about to be turned into VMOVDRR, the source 5115 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5116 // Moreover, we can do this combine only if there is one use. 5117 // Finally, if the destination type is not a vector, there is not 5118 // much point on forcing everything on the vector bank. 5119 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5120 !Op.hasOneUse()) 5121 return SDValue(); 5122 5123 // If the index is not constant, we will introduce an additional 5124 // multiply that will stick. 5125 // Give up in that case. 5126 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5127 if (!Index) 5128 return SDValue(); 5129 unsigned DstNumElt = DstVT.getVectorNumElements(); 5130 5131 // Compute the new index. 5132 const APInt &APIntIndex = Index->getAPIntValue(); 5133 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5134 NewIndex *= APIntIndex; 5135 // Check if the new constant index fits into i32. 5136 if (NewIndex.getBitWidth() > 32) 5137 return SDValue(); 5138 5139 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5140 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5141 SDLoc dl(Op); 5142 SDValue ExtractSrc = Op.getOperand(0); 5143 EVT VecVT = EVT::getVectorVT( 5144 *DAG.getContext(), DstVT.getScalarType(), 5145 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5146 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5147 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5148 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5149 } 5150 5151 /// ExpandBITCAST - If the target supports VFP, this function is called to 5152 /// expand a bit convert where either the source or destination type is i64 to 5153 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5154 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5155 /// vectors), since the legalizer won't know what to do with that. 5156 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5157 const ARMSubtarget *Subtarget) { 5158 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5159 SDLoc dl(N); 5160 SDValue Op = N->getOperand(0); 5161 5162 // This function is only supposed to be called for i64 types, either as the 5163 // source or destination of the bit convert. 5164 EVT SrcVT = Op.getValueType(); 5165 EVT DstVT = N->getValueType(0); 5166 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5167 5168 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5169 // FullFP16: half values are passed in S-registers, and we don't 5170 // need any of the bitcast and moves: 5171 // 5172 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5173 // t5: i32 = bitcast t2 5174 // t18: f16 = ARMISD::VMOVhr t5 5175 if (Op.getOpcode() != ISD::CopyFromReg || 5176 Op.getValueType() != MVT::f32) 5177 return SDValue(); 5178 5179 auto Move = N->use_begin(); 5180 if (Move->getOpcode() != ARMISD::VMOVhr) 5181 return SDValue(); 5182 5183 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5184 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5185 DAG.ReplaceAllUsesWith(*Move, &Copy); 5186 return Copy; 5187 } 5188 5189 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5190 if (!HasFullFP16) 5191 return SDValue(); 5192 // SoftFP: read half-precision arguments: 5193 // 5194 // t2: i32,ch = ... 5195 // t7: i16 = truncate t2 <~~~~ Op 5196 // t8: f16 = bitcast t7 <~~~~ N 5197 // 5198 if (Op.getOperand(0).getValueType() == MVT::i32) 5199 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5200 MVT::f16, Op.getOperand(0)); 5201 5202 return SDValue(); 5203 } 5204 5205 // Half-precision return values 5206 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5207 if (!HasFullFP16) 5208 return SDValue(); 5209 // 5210 // t11: f16 = fadd t8, t10 5211 // t12: i16 = bitcast t11 <~~~ SDNode N 5212 // t13: i32 = zero_extend t12 5213 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5214 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5215 // 5216 // transform this into: 5217 // 5218 // t20: i32 = ARMISD::VMOVrh t11 5219 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5220 // 5221 auto ZeroExtend = N->use_begin(); 5222 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5223 ZeroExtend->getValueType(0) != MVT::i32) 5224 return SDValue(); 5225 5226 auto Copy = ZeroExtend->use_begin(); 5227 if (Copy->getOpcode() == ISD::CopyToReg && 5228 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5229 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5230 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5231 return Cvt; 5232 } 5233 return SDValue(); 5234 } 5235 5236 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5237 return SDValue(); 5238 5239 // Turn i64->f64 into VMOVDRR. 5240 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5241 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5242 // if we can combine the bitcast with its source. 5243 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5244 return Val; 5245 5246 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5247 DAG.getConstant(0, dl, MVT::i32)); 5248 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5249 DAG.getConstant(1, dl, MVT::i32)); 5250 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5251 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5252 } 5253 5254 // Turn f64->i64 into VMOVRRD. 5255 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5256 SDValue Cvt; 5257 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5258 SrcVT.getVectorNumElements() > 1) 5259 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5260 DAG.getVTList(MVT::i32, MVT::i32), 5261 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5262 else 5263 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5264 DAG.getVTList(MVT::i32, MVT::i32), Op); 5265 // Merge the pieces into a single i64 value. 5266 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5267 } 5268 5269 return SDValue(); 5270 } 5271 5272 /// getZeroVector - Returns a vector of specified type with all zero elements. 5273 /// Zero vectors are used to represent vector negation and in those cases 5274 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5275 /// not support i64 elements, so sometimes the zero vectors will need to be 5276 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5277 /// zero vector. 5278 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5279 assert(VT.isVector() && "Expected a vector type"); 5280 // The canonical modified immediate encoding of a zero vector is....0! 5281 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5282 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5283 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5284 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5285 } 5286 5287 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5288 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5289 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5290 SelectionDAG &DAG) const { 5291 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5292 EVT VT = Op.getValueType(); 5293 unsigned VTBits = VT.getSizeInBits(); 5294 SDLoc dl(Op); 5295 SDValue ShOpLo = Op.getOperand(0); 5296 SDValue ShOpHi = Op.getOperand(1); 5297 SDValue ShAmt = Op.getOperand(2); 5298 SDValue ARMcc; 5299 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5300 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5301 5302 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5303 5304 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5305 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5306 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5307 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5308 DAG.getConstant(VTBits, dl, MVT::i32)); 5309 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5310 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5311 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5312 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5313 ISD::SETGE, ARMcc, DAG, dl); 5314 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5315 ARMcc, CCR, CmpLo); 5316 5317 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5318 SDValue HiBigShift = Opc == ISD::SRA 5319 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5320 DAG.getConstant(VTBits - 1, dl, VT)) 5321 : DAG.getConstant(0, dl, VT); 5322 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5323 ISD::SETGE, ARMcc, DAG, dl); 5324 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5325 ARMcc, CCR, CmpHi); 5326 5327 SDValue Ops[2] = { Lo, Hi }; 5328 return DAG.getMergeValues(Ops, dl); 5329 } 5330 5331 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5332 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5333 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5334 SelectionDAG &DAG) const { 5335 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5336 EVT VT = Op.getValueType(); 5337 unsigned VTBits = VT.getSizeInBits(); 5338 SDLoc dl(Op); 5339 SDValue ShOpLo = Op.getOperand(0); 5340 SDValue ShOpHi = Op.getOperand(1); 5341 SDValue ShAmt = Op.getOperand(2); 5342 SDValue ARMcc; 5343 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5344 5345 assert(Op.getOpcode() == ISD::SHL_PARTS); 5346 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5347 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5348 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5349 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5350 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5351 5352 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5353 DAG.getConstant(VTBits, dl, MVT::i32)); 5354 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5355 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5356 ISD::SETGE, ARMcc, DAG, dl); 5357 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5358 ARMcc, CCR, CmpHi); 5359 5360 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5361 ISD::SETGE, ARMcc, DAG, dl); 5362 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5363 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5364 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5365 5366 SDValue Ops[2] = { Lo, Hi }; 5367 return DAG.getMergeValues(Ops, dl); 5368 } 5369 5370 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5371 SelectionDAG &DAG) const { 5372 // The rounding mode is in bits 23:22 of the FPSCR. 5373 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5374 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5375 // so that the shift + and get folded into a bitfield extract. 5376 SDLoc dl(Op); 5377 SDValue Ops[] = { DAG.getEntryNode(), 5378 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5379 5380 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5381 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5382 DAG.getConstant(1U << 22, dl, MVT::i32)); 5383 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5384 DAG.getConstant(22, dl, MVT::i32)); 5385 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5386 DAG.getConstant(3, dl, MVT::i32)); 5387 } 5388 5389 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5390 const ARMSubtarget *ST) { 5391 SDLoc dl(N); 5392 EVT VT = N->getValueType(0); 5393 if (VT.isVector()) { 5394 assert(ST->hasNEON()); 5395 5396 // Compute the least significant set bit: LSB = X & -X 5397 SDValue X = N->getOperand(0); 5398 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5399 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5400 5401 EVT ElemTy = VT.getVectorElementType(); 5402 5403 if (ElemTy == MVT::i8) { 5404 // Compute with: cttz(x) = ctpop(lsb - 1) 5405 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5406 DAG.getTargetConstant(1, dl, ElemTy)); 5407 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5408 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5409 } 5410 5411 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5412 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5413 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5414 unsigned NumBits = ElemTy.getSizeInBits(); 5415 SDValue WidthMinus1 = 5416 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5417 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5418 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5419 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5420 } 5421 5422 // Compute with: cttz(x) = ctpop(lsb - 1) 5423 5424 // Compute LSB - 1. 5425 SDValue Bits; 5426 if (ElemTy == MVT::i64) { 5427 // Load constant 0xffff'ffff'ffff'ffff to register. 5428 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5429 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5430 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5431 } else { 5432 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5433 DAG.getTargetConstant(1, dl, ElemTy)); 5434 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5435 } 5436 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5437 } 5438 5439 if (!ST->hasV6T2Ops()) 5440 return SDValue(); 5441 5442 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5443 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5444 } 5445 5446 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5447 const ARMSubtarget *ST) { 5448 EVT VT = N->getValueType(0); 5449 SDLoc DL(N); 5450 5451 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5452 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5453 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5454 "Unexpected type for custom ctpop lowering"); 5455 5456 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5457 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5458 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 5459 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 5460 5461 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5462 unsigned EltSize = 8; 5463 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5464 while (EltSize != VT.getScalarSizeInBits()) { 5465 SmallVector<SDValue, 8> Ops; 5466 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 5467 TLI.getPointerTy(DAG.getDataLayout()))); 5468 Ops.push_back(Res); 5469 5470 EltSize *= 2; 5471 NumElts /= 2; 5472 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5473 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 5474 } 5475 5476 return Res; 5477 } 5478 5479 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5480 const ARMSubtarget *ST) { 5481 EVT VT = N->getValueType(0); 5482 SDLoc dl(N); 5483 5484 if (!VT.isVector()) 5485 return SDValue(); 5486 5487 // Lower vector shifts on NEON to use VSHL. 5488 assert(ST->hasNEON() && "unexpected vector shift"); 5489 5490 // Left shifts translate directly to the vshiftu intrinsic. 5491 if (N->getOpcode() == ISD::SHL) 5492 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5493 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5494 MVT::i32), 5495 N->getOperand(0), N->getOperand(1)); 5496 5497 assert((N->getOpcode() == ISD::SRA || 5498 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5499 5500 // NEON uses the same intrinsics for both left and right shifts. For 5501 // right shifts, the shift amounts are negative, so negate the vector of 5502 // shift amounts. 5503 EVT ShiftVT = N->getOperand(1).getValueType(); 5504 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5505 getZeroVector(ShiftVT, DAG, dl), 5506 N->getOperand(1)); 5507 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5508 Intrinsic::arm_neon_vshifts : 5509 Intrinsic::arm_neon_vshiftu); 5510 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5511 DAG.getConstant(vshiftInt, dl, MVT::i32), 5512 N->getOperand(0), NegatedCount); 5513 } 5514 5515 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5516 const ARMSubtarget *ST) { 5517 EVT VT = N->getValueType(0); 5518 SDLoc dl(N); 5519 5520 // We can get here for a node like i32 = ISD::SHL i32, i64 5521 if (VT != MVT::i64) 5522 return SDValue(); 5523 5524 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5525 "Unknown shift to lower!"); 5526 5527 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5528 if (!isOneConstant(N->getOperand(1))) 5529 return SDValue(); 5530 5531 // If we are in thumb mode, we don't have RRX. 5532 if (ST->isThumb1Only()) return SDValue(); 5533 5534 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5535 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5536 DAG.getConstant(0, dl, MVT::i32)); 5537 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5538 DAG.getConstant(1, dl, MVT::i32)); 5539 5540 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5541 // captures the result into a carry flag. 5542 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5543 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5544 5545 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5546 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5547 5548 // Merge the pieces into a single i64 value. 5549 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5550 } 5551 5552 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5553 SDValue TmpOp0, TmpOp1; 5554 bool Invert = false; 5555 bool Swap = false; 5556 unsigned Opc = 0; 5557 5558 SDValue Op0 = Op.getOperand(0); 5559 SDValue Op1 = Op.getOperand(1); 5560 SDValue CC = Op.getOperand(2); 5561 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5562 EVT VT = Op.getValueType(); 5563 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5564 SDLoc dl(Op); 5565 5566 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5567 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5568 // Special-case integer 64-bit equality comparisons. They aren't legal, 5569 // but they can be lowered with a few vector instructions. 5570 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5571 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5572 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5573 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5574 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5575 DAG.getCondCode(ISD::SETEQ)); 5576 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5577 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5578 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5579 if (SetCCOpcode == ISD::SETNE) 5580 Merged = DAG.getNOT(dl, Merged, CmpVT); 5581 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5582 return Merged; 5583 } 5584 5585 if (CmpVT.getVectorElementType() == MVT::i64) 5586 // 64-bit comparisons are not legal in general. 5587 return SDValue(); 5588 5589 if (Op1.getValueType().isFloatingPoint()) { 5590 switch (SetCCOpcode) { 5591 default: llvm_unreachable("Illegal FP comparison"); 5592 case ISD::SETUNE: 5593 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5594 case ISD::SETOEQ: 5595 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5596 case ISD::SETOLT: 5597 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5598 case ISD::SETOGT: 5599 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5600 case ISD::SETOLE: 5601 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5602 case ISD::SETOGE: 5603 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5604 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5605 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5606 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5607 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5608 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5609 case ISD::SETONE: 5610 // Expand this to (OLT | OGT). 5611 TmpOp0 = Op0; 5612 TmpOp1 = Op1; 5613 Opc = ISD::OR; 5614 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5615 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5616 break; 5617 case ISD::SETUO: 5618 Invert = true; 5619 LLVM_FALLTHROUGH; 5620 case ISD::SETO: 5621 // Expand this to (OLT | OGE). 5622 TmpOp0 = Op0; 5623 TmpOp1 = Op1; 5624 Opc = ISD::OR; 5625 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5626 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5627 break; 5628 } 5629 } else { 5630 // Integer comparisons. 5631 switch (SetCCOpcode) { 5632 default: llvm_unreachable("Illegal integer comparison"); 5633 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5634 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5635 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5636 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5637 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5638 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5639 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5640 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5641 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5642 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5643 } 5644 5645 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5646 if (Opc == ARMISD::VCEQ) { 5647 SDValue AndOp; 5648 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5649 AndOp = Op0; 5650 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5651 AndOp = Op1; 5652 5653 // Ignore bitconvert. 5654 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5655 AndOp = AndOp.getOperand(0); 5656 5657 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5658 Opc = ARMISD::VTST; 5659 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5660 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5661 Invert = !Invert; 5662 } 5663 } 5664 } 5665 5666 if (Swap) 5667 std::swap(Op0, Op1); 5668 5669 // If one of the operands is a constant vector zero, attempt to fold the 5670 // comparison to a specialized compare-against-zero form. 5671 SDValue SingleOp; 5672 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5673 SingleOp = Op0; 5674 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5675 if (Opc == ARMISD::VCGE) 5676 Opc = ARMISD::VCLEZ; 5677 else if (Opc == ARMISD::VCGT) 5678 Opc = ARMISD::VCLTZ; 5679 SingleOp = Op1; 5680 } 5681 5682 SDValue Result; 5683 if (SingleOp.getNode()) { 5684 switch (Opc) { 5685 case ARMISD::VCEQ: 5686 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5687 case ARMISD::VCGE: 5688 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5689 case ARMISD::VCLEZ: 5690 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5691 case ARMISD::VCGT: 5692 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5693 case ARMISD::VCLTZ: 5694 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5695 default: 5696 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5697 } 5698 } else { 5699 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5700 } 5701 5702 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5703 5704 if (Invert) 5705 Result = DAG.getNOT(dl, Result, VT); 5706 5707 return Result; 5708 } 5709 5710 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 5711 SDValue LHS = Op.getOperand(0); 5712 SDValue RHS = Op.getOperand(1); 5713 SDValue Carry = Op.getOperand(2); 5714 SDValue Cond = Op.getOperand(3); 5715 SDLoc DL(Op); 5716 5717 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 5718 5719 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 5720 // have to invert the carry first. 5721 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 5722 DAG.getConstant(1, DL, MVT::i32), Carry); 5723 // This converts the boolean value carry into the carry flag. 5724 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 5725 5726 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5727 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5728 5729 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5730 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5731 SDValue ARMcc = DAG.getConstant( 5732 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5733 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5734 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5735 Cmp.getValue(1), SDValue()); 5736 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5737 CCR, Chain.getValue(1)); 5738 } 5739 5740 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5741 /// valid vector constant for a NEON instruction with a "modified immediate" 5742 /// operand (e.g., VMOV). If so, return the encoded value. 5743 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5744 unsigned SplatBitSize, SelectionDAG &DAG, 5745 const SDLoc &dl, EVT &VT, bool is128Bits, 5746 NEONModImmType type) { 5747 unsigned OpCmode, Imm; 5748 5749 // SplatBitSize is set to the smallest size that splats the vector, so a 5750 // zero vector will always have SplatBitSize == 8. However, NEON modified 5751 // immediate instructions others than VMOV do not support the 8-bit encoding 5752 // of a zero vector, and the default encoding of zero is supposed to be the 5753 // 32-bit version. 5754 if (SplatBits == 0) 5755 SplatBitSize = 32; 5756 5757 switch (SplatBitSize) { 5758 case 8: 5759 if (type != VMOVModImm) 5760 return SDValue(); 5761 // Any 1-byte value is OK. Op=0, Cmode=1110. 5762 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5763 OpCmode = 0xe; 5764 Imm = SplatBits; 5765 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5766 break; 5767 5768 case 16: 5769 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5770 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5771 if ((SplatBits & ~0xff) == 0) { 5772 // Value = 0x00nn: Op=x, Cmode=100x. 5773 OpCmode = 0x8; 5774 Imm = SplatBits; 5775 break; 5776 } 5777 if ((SplatBits & ~0xff00) == 0) { 5778 // Value = 0xnn00: Op=x, Cmode=101x. 5779 OpCmode = 0xa; 5780 Imm = SplatBits >> 8; 5781 break; 5782 } 5783 return SDValue(); 5784 5785 case 32: 5786 // NEON's 32-bit VMOV supports splat values where: 5787 // * only one byte is nonzero, or 5788 // * the least significant byte is 0xff and the second byte is nonzero, or 5789 // * the least significant 2 bytes are 0xff and the third is nonzero. 5790 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5791 if ((SplatBits & ~0xff) == 0) { 5792 // Value = 0x000000nn: Op=x, Cmode=000x. 5793 OpCmode = 0; 5794 Imm = SplatBits; 5795 break; 5796 } 5797 if ((SplatBits & ~0xff00) == 0) { 5798 // Value = 0x0000nn00: Op=x, Cmode=001x. 5799 OpCmode = 0x2; 5800 Imm = SplatBits >> 8; 5801 break; 5802 } 5803 if ((SplatBits & ~0xff0000) == 0) { 5804 // Value = 0x00nn0000: Op=x, Cmode=010x. 5805 OpCmode = 0x4; 5806 Imm = SplatBits >> 16; 5807 break; 5808 } 5809 if ((SplatBits & ~0xff000000) == 0) { 5810 // Value = 0xnn000000: Op=x, Cmode=011x. 5811 OpCmode = 0x6; 5812 Imm = SplatBits >> 24; 5813 break; 5814 } 5815 5816 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5817 if (type == OtherModImm) return SDValue(); 5818 5819 if ((SplatBits & ~0xffff) == 0 && 5820 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5821 // Value = 0x0000nnff: Op=x, Cmode=1100. 5822 OpCmode = 0xc; 5823 Imm = SplatBits >> 8; 5824 break; 5825 } 5826 5827 if ((SplatBits & ~0xffffff) == 0 && 5828 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5829 // Value = 0x00nnffff: Op=x, Cmode=1101. 5830 OpCmode = 0xd; 5831 Imm = SplatBits >> 16; 5832 break; 5833 } 5834 5835 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5836 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5837 // VMOV.I32. A (very) minor optimization would be to replicate the value 5838 // and fall through here to test for a valid 64-bit splat. But, then the 5839 // caller would also need to check and handle the change in size. 5840 return SDValue(); 5841 5842 case 64: { 5843 if (type != VMOVModImm) 5844 return SDValue(); 5845 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5846 uint64_t BitMask = 0xff; 5847 uint64_t Val = 0; 5848 unsigned ImmMask = 1; 5849 Imm = 0; 5850 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5851 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5852 Val |= BitMask; 5853 Imm |= ImmMask; 5854 } else if ((SplatBits & BitMask) != 0) { 5855 return SDValue(); 5856 } 5857 BitMask <<= 8; 5858 ImmMask <<= 1; 5859 } 5860 5861 if (DAG.getDataLayout().isBigEndian()) 5862 // swap higher and lower 32 bit word 5863 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5864 5865 // Op=1, Cmode=1110. 5866 OpCmode = 0x1e; 5867 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5868 break; 5869 } 5870 5871 default: 5872 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5873 } 5874 5875 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5876 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5877 } 5878 5879 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5880 const ARMSubtarget *ST) const { 5881 EVT VT = Op.getValueType(); 5882 bool IsDouble = (VT == MVT::f64); 5883 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5884 const APFloat &FPVal = CFP->getValueAPF(); 5885 5886 // Prevent floating-point constants from using literal loads 5887 // when execute-only is enabled. 5888 if (ST->genExecuteOnly()) { 5889 // If we can represent the constant as an immediate, don't lower it 5890 if (isFPImmLegal(FPVal, VT)) 5891 return Op; 5892 // Otherwise, construct as integer, and move to float register 5893 APInt INTVal = FPVal.bitcastToAPInt(); 5894 SDLoc DL(CFP); 5895 switch (VT.getSimpleVT().SimpleTy) { 5896 default: 5897 llvm_unreachable("Unknown floating point type!"); 5898 break; 5899 case MVT::f64: { 5900 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5901 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5902 if (!ST->isLittle()) 5903 std::swap(Lo, Hi); 5904 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5905 } 5906 case MVT::f32: 5907 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 5908 DAG.getConstant(INTVal, DL, MVT::i32)); 5909 } 5910 } 5911 5912 if (!ST->hasVFP3()) 5913 return SDValue(); 5914 5915 // Use the default (constant pool) lowering for double constants when we have 5916 // an SP-only FPU 5917 if (IsDouble && Subtarget->isFPOnlySP()) 5918 return SDValue(); 5919 5920 // Try splatting with a VMOV.f32... 5921 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5922 5923 if (ImmVal != -1) { 5924 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5925 // We have code in place to select a valid ConstantFP already, no need to 5926 // do any mangling. 5927 return Op; 5928 } 5929 5930 // It's a float and we are trying to use NEON operations where 5931 // possible. Lower it to a splat followed by an extract. 5932 SDLoc DL(Op); 5933 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5934 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5935 NewVal); 5936 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5937 DAG.getConstant(0, DL, MVT::i32)); 5938 } 5939 5940 // The rest of our options are NEON only, make sure that's allowed before 5941 // proceeding.. 5942 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5943 return SDValue(); 5944 5945 EVT VMovVT; 5946 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5947 5948 // It wouldn't really be worth bothering for doubles except for one very 5949 // important value, which does happen to match: 0.0. So make sure we don't do 5950 // anything stupid. 5951 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5952 return SDValue(); 5953 5954 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5955 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5956 VMovVT, false, VMOVModImm); 5957 if (NewVal != SDValue()) { 5958 SDLoc DL(Op); 5959 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5960 NewVal); 5961 if (IsDouble) 5962 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5963 5964 // It's a float: cast and extract a vector element. 5965 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5966 VecConstant); 5967 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5968 DAG.getConstant(0, DL, MVT::i32)); 5969 } 5970 5971 // Finally, try a VMVN.i32 5972 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5973 false, VMVNModImm); 5974 if (NewVal != SDValue()) { 5975 SDLoc DL(Op); 5976 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5977 5978 if (IsDouble) 5979 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5980 5981 // It's a float: cast and extract a vector element. 5982 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5983 VecConstant); 5984 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5985 DAG.getConstant(0, DL, MVT::i32)); 5986 } 5987 5988 return SDValue(); 5989 } 5990 5991 // check if an VEXT instruction can handle the shuffle mask when the 5992 // vector sources of the shuffle are the same. 5993 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5994 unsigned NumElts = VT.getVectorNumElements(); 5995 5996 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5997 if (M[0] < 0) 5998 return false; 5999 6000 Imm = M[0]; 6001 6002 // If this is a VEXT shuffle, the immediate value is the index of the first 6003 // element. The other shuffle indices must be the successive elements after 6004 // the first one. 6005 unsigned ExpectedElt = Imm; 6006 for (unsigned i = 1; i < NumElts; ++i) { 6007 // Increment the expected index. If it wraps around, just follow it 6008 // back to index zero and keep going. 6009 ++ExpectedElt; 6010 if (ExpectedElt == NumElts) 6011 ExpectedElt = 0; 6012 6013 if (M[i] < 0) continue; // ignore UNDEF indices 6014 if (ExpectedElt != static_cast<unsigned>(M[i])) 6015 return false; 6016 } 6017 6018 return true; 6019 } 6020 6021 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6022 bool &ReverseVEXT, unsigned &Imm) { 6023 unsigned NumElts = VT.getVectorNumElements(); 6024 ReverseVEXT = false; 6025 6026 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6027 if (M[0] < 0) 6028 return false; 6029 6030 Imm = M[0]; 6031 6032 // If this is a VEXT shuffle, the immediate value is the index of the first 6033 // element. The other shuffle indices must be the successive elements after 6034 // the first one. 6035 unsigned ExpectedElt = Imm; 6036 for (unsigned i = 1; i < NumElts; ++i) { 6037 // Increment the expected index. If it wraps around, it may still be 6038 // a VEXT but the source vectors must be swapped. 6039 ExpectedElt += 1; 6040 if (ExpectedElt == NumElts * 2) { 6041 ExpectedElt = 0; 6042 ReverseVEXT = true; 6043 } 6044 6045 if (M[i] < 0) continue; // ignore UNDEF indices 6046 if (ExpectedElt != static_cast<unsigned>(M[i])) 6047 return false; 6048 } 6049 6050 // Adjust the index value if the source operands will be swapped. 6051 if (ReverseVEXT) 6052 Imm -= NumElts; 6053 6054 return true; 6055 } 6056 6057 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6058 /// instruction with the specified blocksize. (The order of the elements 6059 /// within each block of the vector is reversed.) 6060 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6061 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6062 "Only possible block sizes for VREV are: 16, 32, 64"); 6063 6064 unsigned EltSz = VT.getScalarSizeInBits(); 6065 if (EltSz == 64) 6066 return false; 6067 6068 unsigned NumElts = VT.getVectorNumElements(); 6069 unsigned BlockElts = M[0] + 1; 6070 // If the first shuffle index is UNDEF, be optimistic. 6071 if (M[0] < 0) 6072 BlockElts = BlockSize / EltSz; 6073 6074 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6075 return false; 6076 6077 for (unsigned i = 0; i < NumElts; ++i) { 6078 if (M[i] < 0) continue; // ignore UNDEF indices 6079 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6080 return false; 6081 } 6082 6083 return true; 6084 } 6085 6086 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6087 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6088 // range, then 0 is placed into the resulting vector. So pretty much any mask 6089 // of 8 elements can work here. 6090 return VT == MVT::v8i8 && M.size() == 8; 6091 } 6092 6093 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6094 unsigned Index) { 6095 if (Mask.size() == Elements * 2) 6096 return Index / Elements; 6097 return Mask[Index] == 0 ? 0 : 1; 6098 } 6099 6100 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6101 // checking that pairs of elements in the shuffle mask represent the same index 6102 // in each vector, incrementing the expected index by 2 at each step. 6103 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6104 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6105 // v2={e,f,g,h} 6106 // WhichResult gives the offset for each element in the mask based on which 6107 // of the two results it belongs to. 6108 // 6109 // The transpose can be represented either as: 6110 // result1 = shufflevector v1, v2, result1_shuffle_mask 6111 // result2 = shufflevector v1, v2, result2_shuffle_mask 6112 // where v1/v2 and the shuffle masks have the same number of elements 6113 // (here WhichResult (see below) indicates which result is being checked) 6114 // 6115 // or as: 6116 // results = shufflevector v1, v2, shuffle_mask 6117 // where both results are returned in one vector and the shuffle mask has twice 6118 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6119 // want to check the low half and high half of the shuffle mask as if it were 6120 // the other case 6121 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6122 unsigned EltSz = VT.getScalarSizeInBits(); 6123 if (EltSz == 64) 6124 return false; 6125 6126 unsigned NumElts = VT.getVectorNumElements(); 6127 if (M.size() != NumElts && M.size() != NumElts*2) 6128 return false; 6129 6130 // If the mask is twice as long as the input vector then we need to check the 6131 // upper and lower parts of the mask with a matching value for WhichResult 6132 // FIXME: A mask with only even values will be rejected in case the first 6133 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6134 // M[0] is used to determine WhichResult 6135 for (unsigned i = 0; i < M.size(); i += NumElts) { 6136 WhichResult = SelectPairHalf(NumElts, M, i); 6137 for (unsigned j = 0; j < NumElts; j += 2) { 6138 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6139 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6140 return false; 6141 } 6142 } 6143 6144 if (M.size() == NumElts*2) 6145 WhichResult = 0; 6146 6147 return true; 6148 } 6149 6150 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6151 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6152 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6153 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6154 unsigned EltSz = VT.getScalarSizeInBits(); 6155 if (EltSz == 64) 6156 return false; 6157 6158 unsigned NumElts = VT.getVectorNumElements(); 6159 if (M.size() != NumElts && M.size() != NumElts*2) 6160 return false; 6161 6162 for (unsigned i = 0; i < M.size(); i += NumElts) { 6163 WhichResult = SelectPairHalf(NumElts, M, i); 6164 for (unsigned j = 0; j < NumElts; j += 2) { 6165 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6166 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6167 return false; 6168 } 6169 } 6170 6171 if (M.size() == NumElts*2) 6172 WhichResult = 0; 6173 6174 return true; 6175 } 6176 6177 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6178 // that the mask elements are either all even and in steps of size 2 or all odd 6179 // and in steps of size 2. 6180 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6181 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6182 // v2={e,f,g,h} 6183 // Requires similar checks to that of isVTRNMask with 6184 // respect the how results are returned. 6185 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6186 unsigned EltSz = VT.getScalarSizeInBits(); 6187 if (EltSz == 64) 6188 return false; 6189 6190 unsigned NumElts = VT.getVectorNumElements(); 6191 if (M.size() != NumElts && M.size() != NumElts*2) 6192 return false; 6193 6194 for (unsigned i = 0; i < M.size(); i += NumElts) { 6195 WhichResult = SelectPairHalf(NumElts, M, i); 6196 for (unsigned j = 0; j < NumElts; ++j) { 6197 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6198 return false; 6199 } 6200 } 6201 6202 if (M.size() == NumElts*2) 6203 WhichResult = 0; 6204 6205 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6206 if (VT.is64BitVector() && EltSz == 32) 6207 return false; 6208 6209 return true; 6210 } 6211 6212 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6213 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6214 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6215 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6216 unsigned EltSz = VT.getScalarSizeInBits(); 6217 if (EltSz == 64) 6218 return false; 6219 6220 unsigned NumElts = VT.getVectorNumElements(); 6221 if (M.size() != NumElts && M.size() != NumElts*2) 6222 return false; 6223 6224 unsigned Half = NumElts / 2; 6225 for (unsigned i = 0; i < M.size(); i += NumElts) { 6226 WhichResult = SelectPairHalf(NumElts, M, i); 6227 for (unsigned j = 0; j < NumElts; j += Half) { 6228 unsigned Idx = WhichResult; 6229 for (unsigned k = 0; k < Half; ++k) { 6230 int MIdx = M[i + j + k]; 6231 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6232 return false; 6233 Idx += 2; 6234 } 6235 } 6236 } 6237 6238 if (M.size() == NumElts*2) 6239 WhichResult = 0; 6240 6241 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6242 if (VT.is64BitVector() && EltSz == 32) 6243 return false; 6244 6245 return true; 6246 } 6247 6248 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6249 // that pairs of elements of the shufflemask represent the same index in each 6250 // vector incrementing sequentially through the vectors. 6251 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6252 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6253 // v2={e,f,g,h} 6254 // Requires similar checks to that of isVTRNMask with respect the how results 6255 // are returned. 6256 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6257 unsigned EltSz = VT.getScalarSizeInBits(); 6258 if (EltSz == 64) 6259 return false; 6260 6261 unsigned NumElts = VT.getVectorNumElements(); 6262 if (M.size() != NumElts && M.size() != NumElts*2) 6263 return false; 6264 6265 for (unsigned i = 0; i < M.size(); i += NumElts) { 6266 WhichResult = SelectPairHalf(NumElts, M, i); 6267 unsigned Idx = WhichResult * NumElts / 2; 6268 for (unsigned j = 0; j < NumElts; j += 2) { 6269 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6270 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6271 return false; 6272 Idx += 1; 6273 } 6274 } 6275 6276 if (M.size() == NumElts*2) 6277 WhichResult = 0; 6278 6279 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6280 if (VT.is64BitVector() && EltSz == 32) 6281 return false; 6282 6283 return true; 6284 } 6285 6286 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6287 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6288 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6289 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6290 unsigned EltSz = VT.getScalarSizeInBits(); 6291 if (EltSz == 64) 6292 return false; 6293 6294 unsigned NumElts = VT.getVectorNumElements(); 6295 if (M.size() != NumElts && M.size() != NumElts*2) 6296 return false; 6297 6298 for (unsigned i = 0; i < M.size(); i += NumElts) { 6299 WhichResult = SelectPairHalf(NumElts, M, i); 6300 unsigned Idx = WhichResult * NumElts / 2; 6301 for (unsigned j = 0; j < NumElts; j += 2) { 6302 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6303 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6304 return false; 6305 Idx += 1; 6306 } 6307 } 6308 6309 if (M.size() == NumElts*2) 6310 WhichResult = 0; 6311 6312 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6313 if (VT.is64BitVector() && EltSz == 32) 6314 return false; 6315 6316 return true; 6317 } 6318 6319 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6320 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6321 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6322 unsigned &WhichResult, 6323 bool &isV_UNDEF) { 6324 isV_UNDEF = false; 6325 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6326 return ARMISD::VTRN; 6327 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6328 return ARMISD::VUZP; 6329 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6330 return ARMISD::VZIP; 6331 6332 isV_UNDEF = true; 6333 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6334 return ARMISD::VTRN; 6335 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6336 return ARMISD::VUZP; 6337 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6338 return ARMISD::VZIP; 6339 6340 return 0; 6341 } 6342 6343 /// \return true if this is a reverse operation on an vector. 6344 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6345 unsigned NumElts = VT.getVectorNumElements(); 6346 // Make sure the mask has the right size. 6347 if (NumElts != M.size()) 6348 return false; 6349 6350 // Look for <15, ..., 3, -1, 1, 0>. 6351 for (unsigned i = 0; i != NumElts; ++i) 6352 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6353 return false; 6354 6355 return true; 6356 } 6357 6358 // If N is an integer constant that can be moved into a register in one 6359 // instruction, return an SDValue of such a constant (will become a MOV 6360 // instruction). Otherwise return null. 6361 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6362 const ARMSubtarget *ST, const SDLoc &dl) { 6363 uint64_t Val; 6364 if (!isa<ConstantSDNode>(N)) 6365 return SDValue(); 6366 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6367 6368 if (ST->isThumb1Only()) { 6369 if (Val <= 255 || ~Val <= 255) 6370 return DAG.getConstant(Val, dl, MVT::i32); 6371 } else { 6372 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6373 return DAG.getConstant(Val, dl, MVT::i32); 6374 } 6375 return SDValue(); 6376 } 6377 6378 // If this is a case we can't handle, return null and let the default 6379 // expansion code take care of it. 6380 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6381 const ARMSubtarget *ST) const { 6382 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6383 SDLoc dl(Op); 6384 EVT VT = Op.getValueType(); 6385 6386 APInt SplatBits, SplatUndef; 6387 unsigned SplatBitSize; 6388 bool HasAnyUndefs; 6389 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6390 if (SplatUndef.isAllOnesValue()) 6391 return DAG.getUNDEF(VT); 6392 6393 if (SplatBitSize <= 64) { 6394 // Check if an immediate VMOV works. 6395 EVT VmovVT; 6396 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6397 SplatUndef.getZExtValue(), SplatBitSize, 6398 DAG, dl, VmovVT, VT.is128BitVector(), 6399 VMOVModImm); 6400 if (Val.getNode()) { 6401 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6402 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6403 } 6404 6405 // Try an immediate VMVN. 6406 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6407 Val = isNEONModifiedImm(NegatedImm, 6408 SplatUndef.getZExtValue(), SplatBitSize, 6409 DAG, dl, VmovVT, VT.is128BitVector(), 6410 VMVNModImm); 6411 if (Val.getNode()) { 6412 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6413 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6414 } 6415 6416 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6417 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6418 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6419 if (ImmVal != -1) { 6420 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6421 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6422 } 6423 } 6424 } 6425 } 6426 6427 // Scan through the operands to see if only one value is used. 6428 // 6429 // As an optimisation, even if more than one value is used it may be more 6430 // profitable to splat with one value then change some lanes. 6431 // 6432 // Heuristically we decide to do this if the vector has a "dominant" value, 6433 // defined as splatted to more than half of the lanes. 6434 unsigned NumElts = VT.getVectorNumElements(); 6435 bool isOnlyLowElement = true; 6436 bool usesOnlyOneValue = true; 6437 bool hasDominantValue = false; 6438 bool isConstant = true; 6439 6440 // Map of the number of times a particular SDValue appears in the 6441 // element list. 6442 DenseMap<SDValue, unsigned> ValueCounts; 6443 SDValue Value; 6444 for (unsigned i = 0; i < NumElts; ++i) { 6445 SDValue V = Op.getOperand(i); 6446 if (V.isUndef()) 6447 continue; 6448 if (i > 0) 6449 isOnlyLowElement = false; 6450 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6451 isConstant = false; 6452 6453 ValueCounts.insert(std::make_pair(V, 0)); 6454 unsigned &Count = ValueCounts[V]; 6455 6456 // Is this value dominant? (takes up more than half of the lanes) 6457 if (++Count > (NumElts / 2)) { 6458 hasDominantValue = true; 6459 Value = V; 6460 } 6461 } 6462 if (ValueCounts.size() != 1) 6463 usesOnlyOneValue = false; 6464 if (!Value.getNode() && !ValueCounts.empty()) 6465 Value = ValueCounts.begin()->first; 6466 6467 if (ValueCounts.empty()) 6468 return DAG.getUNDEF(VT); 6469 6470 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6471 // Keep going if we are hitting this case. 6472 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6473 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6474 6475 unsigned EltSize = VT.getScalarSizeInBits(); 6476 6477 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6478 // i32 and try again. 6479 if (hasDominantValue && EltSize <= 32) { 6480 if (!isConstant) { 6481 SDValue N; 6482 6483 // If we are VDUPing a value that comes directly from a vector, that will 6484 // cause an unnecessary move to and from a GPR, where instead we could 6485 // just use VDUPLANE. We can only do this if the lane being extracted 6486 // is at a constant index, as the VDUP from lane instructions only have 6487 // constant-index forms. 6488 ConstantSDNode *constIndex; 6489 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6490 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6491 // We need to create a new undef vector to use for the VDUPLANE if the 6492 // size of the vector from which we get the value is different than the 6493 // size of the vector that we need to create. We will insert the element 6494 // such that the register coalescer will remove unnecessary copies. 6495 if (VT != Value->getOperand(0).getValueType()) { 6496 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6497 VT.getVectorNumElements(); 6498 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6499 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6500 Value, DAG.getConstant(index, dl, MVT::i32)), 6501 DAG.getConstant(index, dl, MVT::i32)); 6502 } else 6503 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6504 Value->getOperand(0), Value->getOperand(1)); 6505 } else 6506 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6507 6508 if (!usesOnlyOneValue) { 6509 // The dominant value was splatted as 'N', but we now have to insert 6510 // all differing elements. 6511 for (unsigned I = 0; I < NumElts; ++I) { 6512 if (Op.getOperand(I) == Value) 6513 continue; 6514 SmallVector<SDValue, 3> Ops; 6515 Ops.push_back(N); 6516 Ops.push_back(Op.getOperand(I)); 6517 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6518 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6519 } 6520 } 6521 return N; 6522 } 6523 if (VT.getVectorElementType().isFloatingPoint()) { 6524 SmallVector<SDValue, 8> Ops; 6525 for (unsigned i = 0; i < NumElts; ++i) 6526 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6527 Op.getOperand(i))); 6528 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6529 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6530 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6531 if (Val.getNode()) 6532 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6533 } 6534 if (usesOnlyOneValue) { 6535 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6536 if (isConstant && Val.getNode()) 6537 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6538 } 6539 } 6540 6541 // If all elements are constants and the case above didn't get hit, fall back 6542 // to the default expansion, which will generate a load from the constant 6543 // pool. 6544 if (isConstant) 6545 return SDValue(); 6546 6547 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6548 if (NumElts >= 4) { 6549 SDValue shuffle = ReconstructShuffle(Op, DAG); 6550 if (shuffle != SDValue()) 6551 return shuffle; 6552 } 6553 6554 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6555 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6556 // into two 64-bit vectors; we might discover a better way to lower it. 6557 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6558 EVT ExtVT = VT.getVectorElementType(); 6559 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6560 SDValue Lower = 6561 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6562 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6563 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6564 SDValue Upper = DAG.getBuildVector( 6565 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6566 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6567 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6568 if (Lower && Upper) 6569 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6570 } 6571 6572 // Vectors with 32- or 64-bit elements can be built by directly assigning 6573 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6574 // will be legalized. 6575 if (EltSize >= 32) { 6576 // Do the expansion with floating-point types, since that is what the VFP 6577 // registers are defined to use, and since i64 is not legal. 6578 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6579 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6580 SmallVector<SDValue, 8> Ops; 6581 for (unsigned i = 0; i < NumElts; ++i) 6582 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6583 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6584 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6585 } 6586 6587 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6588 // know the default expansion would otherwise fall back on something even 6589 // worse. For a vector with one or two non-undef values, that's 6590 // scalar_to_vector for the elements followed by a shuffle (provided the 6591 // shuffle is valid for the target) and materialization element by element 6592 // on the stack followed by a load for everything else. 6593 if (!isConstant && !usesOnlyOneValue) { 6594 SDValue Vec = DAG.getUNDEF(VT); 6595 for (unsigned i = 0 ; i < NumElts; ++i) { 6596 SDValue V = Op.getOperand(i); 6597 if (V.isUndef()) 6598 continue; 6599 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6600 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6601 } 6602 return Vec; 6603 } 6604 6605 return SDValue(); 6606 } 6607 6608 // Gather data to see if the operation can be modelled as a 6609 // shuffle in combination with VEXTs. 6610 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6611 SelectionDAG &DAG) const { 6612 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6613 SDLoc dl(Op); 6614 EVT VT = Op.getValueType(); 6615 unsigned NumElts = VT.getVectorNumElements(); 6616 6617 struct ShuffleSourceInfo { 6618 SDValue Vec; 6619 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6620 unsigned MaxElt = 0; 6621 6622 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6623 // be compatible with the shuffle we intend to construct. As a result 6624 // ShuffleVec will be some sliding window into the original Vec. 6625 SDValue ShuffleVec; 6626 6627 // Code should guarantee that element i in Vec starts at element "WindowBase 6628 // + i * WindowScale in ShuffleVec". 6629 int WindowBase = 0; 6630 int WindowScale = 1; 6631 6632 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6633 6634 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6635 }; 6636 6637 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6638 // node. 6639 SmallVector<ShuffleSourceInfo, 2> Sources; 6640 for (unsigned i = 0; i < NumElts; ++i) { 6641 SDValue V = Op.getOperand(i); 6642 if (V.isUndef()) 6643 continue; 6644 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6645 // A shuffle can only come from building a vector from various 6646 // elements of other vectors. 6647 return SDValue(); 6648 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6649 // Furthermore, shuffles require a constant mask, whereas extractelts 6650 // accept variable indices. 6651 return SDValue(); 6652 } 6653 6654 // Add this element source to the list if it's not already there. 6655 SDValue SourceVec = V.getOperand(0); 6656 auto Source = llvm::find(Sources, SourceVec); 6657 if (Source == Sources.end()) 6658 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6659 6660 // Update the minimum and maximum lane number seen. 6661 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6662 Source->MinElt = std::min(Source->MinElt, EltNo); 6663 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6664 } 6665 6666 // Currently only do something sane when at most two source vectors 6667 // are involved. 6668 if (Sources.size() > 2) 6669 return SDValue(); 6670 6671 // Find out the smallest element size among result and two sources, and use 6672 // it as element size to build the shuffle_vector. 6673 EVT SmallestEltTy = VT.getVectorElementType(); 6674 for (auto &Source : Sources) { 6675 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6676 if (SrcEltTy.bitsLT(SmallestEltTy)) 6677 SmallestEltTy = SrcEltTy; 6678 } 6679 unsigned ResMultiplier = 6680 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6681 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6682 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6683 6684 // If the source vector is too wide or too narrow, we may nevertheless be able 6685 // to construct a compatible shuffle either by concatenating it with UNDEF or 6686 // extracting a suitable range of elements. 6687 for (auto &Src : Sources) { 6688 EVT SrcVT = Src.ShuffleVec.getValueType(); 6689 6690 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6691 continue; 6692 6693 // This stage of the search produces a source with the same element type as 6694 // the original, but with a total width matching the BUILD_VECTOR output. 6695 EVT EltVT = SrcVT.getVectorElementType(); 6696 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6697 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6698 6699 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6700 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6701 return SDValue(); 6702 // We can pad out the smaller vector for free, so if it's part of a 6703 // shuffle... 6704 Src.ShuffleVec = 6705 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6706 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6707 continue; 6708 } 6709 6710 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6711 return SDValue(); 6712 6713 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6714 // Span too large for a VEXT to cope 6715 return SDValue(); 6716 } 6717 6718 if (Src.MinElt >= NumSrcElts) { 6719 // The extraction can just take the second half 6720 Src.ShuffleVec = 6721 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6722 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6723 Src.WindowBase = -NumSrcElts; 6724 } else if (Src.MaxElt < NumSrcElts) { 6725 // The extraction can just take the first half 6726 Src.ShuffleVec = 6727 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6728 DAG.getConstant(0, dl, MVT::i32)); 6729 } else { 6730 // An actual VEXT is needed 6731 SDValue VEXTSrc1 = 6732 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6733 DAG.getConstant(0, dl, MVT::i32)); 6734 SDValue VEXTSrc2 = 6735 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6736 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6737 6738 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6739 VEXTSrc2, 6740 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6741 Src.WindowBase = -Src.MinElt; 6742 } 6743 } 6744 6745 // Another possible incompatibility occurs from the vector element types. We 6746 // can fix this by bitcasting the source vectors to the same type we intend 6747 // for the shuffle. 6748 for (auto &Src : Sources) { 6749 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6750 if (SrcEltTy == SmallestEltTy) 6751 continue; 6752 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6753 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6754 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6755 Src.WindowBase *= Src.WindowScale; 6756 } 6757 6758 // Final sanity check before we try to actually produce a shuffle. 6759 LLVM_DEBUG(for (auto Src 6760 : Sources) 6761 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6762 6763 // The stars all align, our next step is to produce the mask for the shuffle. 6764 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6765 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6766 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6767 SDValue Entry = Op.getOperand(i); 6768 if (Entry.isUndef()) 6769 continue; 6770 6771 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6772 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6773 6774 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6775 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6776 // segment. 6777 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6778 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6779 VT.getScalarSizeInBits()); 6780 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6781 6782 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6783 // starting at the appropriate offset. 6784 int *LaneMask = &Mask[i * ResMultiplier]; 6785 6786 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6787 ExtractBase += NumElts * (Src - Sources.begin()); 6788 for (int j = 0; j < LanesDefined; ++j) 6789 LaneMask[j] = ExtractBase + j; 6790 } 6791 6792 // Final check before we try to produce nonsense... 6793 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6794 return SDValue(); 6795 6796 // We can't handle more than two sources. This should have already 6797 // been checked before this point. 6798 assert(Sources.size() <= 2 && "Too many sources!"); 6799 6800 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6801 for (unsigned i = 0; i < Sources.size(); ++i) 6802 ShuffleOps[i] = Sources[i].ShuffleVec; 6803 6804 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6805 ShuffleOps[1], Mask); 6806 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6807 } 6808 6809 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6810 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6811 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6812 /// are assumed to be legal. 6813 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6814 if (VT.getVectorNumElements() == 4 && 6815 (VT.is128BitVector() || VT.is64BitVector())) { 6816 unsigned PFIndexes[4]; 6817 for (unsigned i = 0; i != 4; ++i) { 6818 if (M[i] < 0) 6819 PFIndexes[i] = 8; 6820 else 6821 PFIndexes[i] = M[i]; 6822 } 6823 6824 // Compute the index in the perfect shuffle table. 6825 unsigned PFTableIndex = 6826 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6827 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6828 unsigned Cost = (PFEntry >> 30); 6829 6830 if (Cost <= 4) 6831 return true; 6832 } 6833 6834 bool ReverseVEXT, isV_UNDEF; 6835 unsigned Imm, WhichResult; 6836 6837 unsigned EltSize = VT.getScalarSizeInBits(); 6838 return (EltSize >= 32 || 6839 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6840 isVREVMask(M, VT, 64) || 6841 isVREVMask(M, VT, 32) || 6842 isVREVMask(M, VT, 16) || 6843 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6844 isVTBLMask(M, VT) || 6845 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6846 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6847 } 6848 6849 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6850 /// the specified operations to build the shuffle. 6851 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6852 SDValue RHS, SelectionDAG &DAG, 6853 const SDLoc &dl) { 6854 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6855 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6856 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6857 6858 enum { 6859 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6860 OP_VREV, 6861 OP_VDUP0, 6862 OP_VDUP1, 6863 OP_VDUP2, 6864 OP_VDUP3, 6865 OP_VEXT1, 6866 OP_VEXT2, 6867 OP_VEXT3, 6868 OP_VUZPL, // VUZP, left result 6869 OP_VUZPR, // VUZP, right result 6870 OP_VZIPL, // VZIP, left result 6871 OP_VZIPR, // VZIP, right result 6872 OP_VTRNL, // VTRN, left result 6873 OP_VTRNR // VTRN, right result 6874 }; 6875 6876 if (OpNum == OP_COPY) { 6877 if (LHSID == (1*9+2)*9+3) return LHS; 6878 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6879 return RHS; 6880 } 6881 6882 SDValue OpLHS, OpRHS; 6883 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6884 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6885 EVT VT = OpLHS.getValueType(); 6886 6887 switch (OpNum) { 6888 default: llvm_unreachable("Unknown shuffle opcode!"); 6889 case OP_VREV: 6890 // VREV divides the vector in half and swaps within the half. 6891 if (VT.getVectorElementType() == MVT::i32 || 6892 VT.getVectorElementType() == MVT::f32) 6893 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6894 // vrev <4 x i16> -> VREV32 6895 if (VT.getVectorElementType() == MVT::i16) 6896 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6897 // vrev <4 x i8> -> VREV16 6898 assert(VT.getVectorElementType() == MVT::i8); 6899 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6900 case OP_VDUP0: 6901 case OP_VDUP1: 6902 case OP_VDUP2: 6903 case OP_VDUP3: 6904 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6905 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6906 case OP_VEXT1: 6907 case OP_VEXT2: 6908 case OP_VEXT3: 6909 return DAG.getNode(ARMISD::VEXT, dl, VT, 6910 OpLHS, OpRHS, 6911 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6912 case OP_VUZPL: 6913 case OP_VUZPR: 6914 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6915 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6916 case OP_VZIPL: 6917 case OP_VZIPR: 6918 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6919 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6920 case OP_VTRNL: 6921 case OP_VTRNR: 6922 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6923 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6924 } 6925 } 6926 6927 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6928 ArrayRef<int> ShuffleMask, 6929 SelectionDAG &DAG) { 6930 // Check to see if we can use the VTBL instruction. 6931 SDValue V1 = Op.getOperand(0); 6932 SDValue V2 = Op.getOperand(1); 6933 SDLoc DL(Op); 6934 6935 SmallVector<SDValue, 8> VTBLMask; 6936 for (ArrayRef<int>::iterator 6937 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6938 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6939 6940 if (V2.getNode()->isUndef()) 6941 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6942 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6943 6944 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6945 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6946 } 6947 6948 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6949 SelectionDAG &DAG) { 6950 SDLoc DL(Op); 6951 SDValue OpLHS = Op.getOperand(0); 6952 EVT VT = OpLHS.getValueType(); 6953 6954 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6955 "Expect an v8i16/v16i8 type"); 6956 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6957 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6958 // extract the first 8 bytes into the top double word and the last 8 bytes 6959 // into the bottom double word. The v8i16 case is similar. 6960 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6961 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6962 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6963 } 6964 6965 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6966 SDValue V1 = Op.getOperand(0); 6967 SDValue V2 = Op.getOperand(1); 6968 SDLoc dl(Op); 6969 EVT VT = Op.getValueType(); 6970 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6971 6972 // Convert shuffles that are directly supported on NEON to target-specific 6973 // DAG nodes, instead of keeping them as shuffles and matching them again 6974 // during code selection. This is more efficient and avoids the possibility 6975 // of inconsistencies between legalization and selection. 6976 // FIXME: floating-point vectors should be canonicalized to integer vectors 6977 // of the same time so that they get CSEd properly. 6978 ArrayRef<int> ShuffleMask = SVN->getMask(); 6979 6980 unsigned EltSize = VT.getScalarSizeInBits(); 6981 if (EltSize <= 32) { 6982 if (SVN->isSplat()) { 6983 int Lane = SVN->getSplatIndex(); 6984 // If this is undef splat, generate it via "just" vdup, if possible. 6985 if (Lane == -1) Lane = 0; 6986 6987 // Test if V1 is a SCALAR_TO_VECTOR. 6988 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6989 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6990 } 6991 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6992 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6993 // reaches it). 6994 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6995 !isa<ConstantSDNode>(V1.getOperand(0))) { 6996 bool IsScalarToVector = true; 6997 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6998 if (!V1.getOperand(i).isUndef()) { 6999 IsScalarToVector = false; 7000 break; 7001 } 7002 if (IsScalarToVector) 7003 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7004 } 7005 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7006 DAG.getConstant(Lane, dl, MVT::i32)); 7007 } 7008 7009 bool ReverseVEXT; 7010 unsigned Imm; 7011 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7012 if (ReverseVEXT) 7013 std::swap(V1, V2); 7014 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7015 DAG.getConstant(Imm, dl, MVT::i32)); 7016 } 7017 7018 if (isVREVMask(ShuffleMask, VT, 64)) 7019 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7020 if (isVREVMask(ShuffleMask, VT, 32)) 7021 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7022 if (isVREVMask(ShuffleMask, VT, 16)) 7023 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7024 7025 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7026 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7027 DAG.getConstant(Imm, dl, MVT::i32)); 7028 } 7029 7030 // Check for Neon shuffles that modify both input vectors in place. 7031 // If both results are used, i.e., if there are two shuffles with the same 7032 // source operands and with masks corresponding to both results of one of 7033 // these operations, DAG memoization will ensure that a single node is 7034 // used for both shuffles. 7035 unsigned WhichResult; 7036 bool isV_UNDEF; 7037 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7038 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7039 if (isV_UNDEF) 7040 V2 = V1; 7041 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7042 .getValue(WhichResult); 7043 } 7044 7045 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7046 // shuffles that produce a result larger than their operands with: 7047 // shuffle(concat(v1, undef), concat(v2, undef)) 7048 // -> 7049 // shuffle(concat(v1, v2), undef) 7050 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7051 // 7052 // This is useful in the general case, but there are special cases where 7053 // native shuffles produce larger results: the two-result ops. 7054 // 7055 // Look through the concat when lowering them: 7056 // shuffle(concat(v1, v2), undef) 7057 // -> 7058 // concat(VZIP(v1, v2):0, :1) 7059 // 7060 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7061 SDValue SubV1 = V1->getOperand(0); 7062 SDValue SubV2 = V1->getOperand(1); 7063 EVT SubVT = SubV1.getValueType(); 7064 7065 // We expect these to have been canonicalized to -1. 7066 assert(llvm::all_of(ShuffleMask, [&](int i) { 7067 return i < (int)VT.getVectorNumElements(); 7068 }) && "Unexpected shuffle index into UNDEF operand!"); 7069 7070 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7071 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7072 if (isV_UNDEF) 7073 SubV2 = SubV1; 7074 assert((WhichResult == 0) && 7075 "In-place shuffle of concat can only have one result!"); 7076 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7077 SubV1, SubV2); 7078 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7079 Res.getValue(1)); 7080 } 7081 } 7082 } 7083 7084 // If the shuffle is not directly supported and it has 4 elements, use 7085 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7086 unsigned NumElts = VT.getVectorNumElements(); 7087 if (NumElts == 4) { 7088 unsigned PFIndexes[4]; 7089 for (unsigned i = 0; i != 4; ++i) { 7090 if (ShuffleMask[i] < 0) 7091 PFIndexes[i] = 8; 7092 else 7093 PFIndexes[i] = ShuffleMask[i]; 7094 } 7095 7096 // Compute the index in the perfect shuffle table. 7097 unsigned PFTableIndex = 7098 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7099 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7100 unsigned Cost = (PFEntry >> 30); 7101 7102 if (Cost <= 4) 7103 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7104 } 7105 7106 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7107 if (EltSize >= 32) { 7108 // Do the expansion with floating-point types, since that is what the VFP 7109 // registers are defined to use, and since i64 is not legal. 7110 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7111 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7112 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7113 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7114 SmallVector<SDValue, 8> Ops; 7115 for (unsigned i = 0; i < NumElts; ++i) { 7116 if (ShuffleMask[i] < 0) 7117 Ops.push_back(DAG.getUNDEF(EltVT)); 7118 else 7119 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7120 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7121 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7122 dl, MVT::i32))); 7123 } 7124 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7125 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7126 } 7127 7128 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7129 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7130 7131 if (VT == MVT::v8i8) 7132 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7133 return NewOp; 7134 7135 return SDValue(); 7136 } 7137 7138 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7139 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7140 SDValue Lane = Op.getOperand(2); 7141 if (!isa<ConstantSDNode>(Lane)) 7142 return SDValue(); 7143 7144 return Op; 7145 } 7146 7147 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7148 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7149 SDValue Lane = Op.getOperand(1); 7150 if (!isa<ConstantSDNode>(Lane)) 7151 return SDValue(); 7152 7153 SDValue Vec = Op.getOperand(0); 7154 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7155 SDLoc dl(Op); 7156 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7157 } 7158 7159 return Op; 7160 } 7161 7162 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7163 // The only time a CONCAT_VECTORS operation can have legal types is when 7164 // two 64-bit vectors are concatenated to a 128-bit vector. 7165 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7166 "unexpected CONCAT_VECTORS"); 7167 SDLoc dl(Op); 7168 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7169 SDValue Op0 = Op.getOperand(0); 7170 SDValue Op1 = Op.getOperand(1); 7171 if (!Op0.isUndef()) 7172 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7173 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7174 DAG.getIntPtrConstant(0, dl)); 7175 if (!Op1.isUndef()) 7176 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7177 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7178 DAG.getIntPtrConstant(1, dl)); 7179 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7180 } 7181 7182 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7183 /// element has been zero/sign-extended, depending on the isSigned parameter, 7184 /// from an integer type half its size. 7185 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7186 bool isSigned) { 7187 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7188 EVT VT = N->getValueType(0); 7189 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7190 SDNode *BVN = N->getOperand(0).getNode(); 7191 if (BVN->getValueType(0) != MVT::v4i32 || 7192 BVN->getOpcode() != ISD::BUILD_VECTOR) 7193 return false; 7194 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7195 unsigned HiElt = 1 - LoElt; 7196 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7197 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7198 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7199 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7200 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7201 return false; 7202 if (isSigned) { 7203 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7204 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7205 return true; 7206 } else { 7207 if (Hi0->isNullValue() && Hi1->isNullValue()) 7208 return true; 7209 } 7210 return false; 7211 } 7212 7213 if (N->getOpcode() != ISD::BUILD_VECTOR) 7214 return false; 7215 7216 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7217 SDNode *Elt = N->getOperand(i).getNode(); 7218 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7219 unsigned EltSize = VT.getScalarSizeInBits(); 7220 unsigned HalfSize = EltSize / 2; 7221 if (isSigned) { 7222 if (!isIntN(HalfSize, C->getSExtValue())) 7223 return false; 7224 } else { 7225 if (!isUIntN(HalfSize, C->getZExtValue())) 7226 return false; 7227 } 7228 continue; 7229 } 7230 return false; 7231 } 7232 7233 return true; 7234 } 7235 7236 /// isSignExtended - Check if a node is a vector value that is sign-extended 7237 /// or a constant BUILD_VECTOR with sign-extended elements. 7238 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7239 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7240 return true; 7241 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7242 return true; 7243 return false; 7244 } 7245 7246 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7247 /// or a constant BUILD_VECTOR with zero-extended elements. 7248 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7249 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7250 return true; 7251 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7252 return true; 7253 return false; 7254 } 7255 7256 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7257 if (OrigVT.getSizeInBits() >= 64) 7258 return OrigVT; 7259 7260 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7261 7262 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7263 switch (OrigSimpleTy) { 7264 default: llvm_unreachable("Unexpected Vector Type"); 7265 case MVT::v2i8: 7266 case MVT::v2i16: 7267 return MVT::v2i32; 7268 case MVT::v4i8: 7269 return MVT::v4i16; 7270 } 7271 } 7272 7273 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7274 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7275 /// We insert the required extension here to get the vector to fill a D register. 7276 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7277 const EVT &OrigTy, 7278 const EVT &ExtTy, 7279 unsigned ExtOpcode) { 7280 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7281 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7282 // 64-bits we need to insert a new extension so that it will be 64-bits. 7283 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7284 if (OrigTy.getSizeInBits() >= 64) 7285 return N; 7286 7287 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7288 EVT NewVT = getExtensionTo64Bits(OrigTy); 7289 7290 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7291 } 7292 7293 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7294 /// does not do any sign/zero extension. If the original vector is less 7295 /// than 64 bits, an appropriate extension will be added after the load to 7296 /// reach a total size of 64 bits. We have to add the extension separately 7297 /// because ARM does not have a sign/zero extending load for vectors. 7298 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7299 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7300 7301 // The load already has the right type. 7302 if (ExtendedTy == LD->getMemoryVT()) 7303 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7304 LD->getBasePtr(), LD->getPointerInfo(), 7305 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7306 7307 // We need to create a zextload/sextload. We cannot just create a load 7308 // followed by a zext/zext node because LowerMUL is also run during normal 7309 // operation legalization where we can't create illegal types. 7310 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7311 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7312 LD->getMemoryVT(), LD->getAlignment(), 7313 LD->getMemOperand()->getFlags()); 7314 } 7315 7316 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7317 /// extending load, or BUILD_VECTOR with extended elements, return the 7318 /// unextended value. The unextended vector should be 64 bits so that it can 7319 /// be used as an operand to a VMULL instruction. If the original vector size 7320 /// before extension is less than 64 bits we add a an extension to resize 7321 /// the vector to 64 bits. 7322 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7323 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7324 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7325 N->getOperand(0)->getValueType(0), 7326 N->getValueType(0), 7327 N->getOpcode()); 7328 7329 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7330 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7331 "Expected extending load"); 7332 7333 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7334 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7335 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7336 SDValue extLoad = 7337 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7338 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7339 7340 return newLoad; 7341 } 7342 7343 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7344 // have been legalized as a BITCAST from v4i32. 7345 if (N->getOpcode() == ISD::BITCAST) { 7346 SDNode *BVN = N->getOperand(0).getNode(); 7347 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7348 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7349 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7350 return DAG.getBuildVector( 7351 MVT::v2i32, SDLoc(N), 7352 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7353 } 7354 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7355 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7356 EVT VT = N->getValueType(0); 7357 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7358 unsigned NumElts = VT.getVectorNumElements(); 7359 MVT TruncVT = MVT::getIntegerVT(EltSize); 7360 SmallVector<SDValue, 8> Ops; 7361 SDLoc dl(N); 7362 for (unsigned i = 0; i != NumElts; ++i) { 7363 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7364 const APInt &CInt = C->getAPIntValue(); 7365 // Element types smaller than 32 bits are not legal, so use i32 elements. 7366 // The values are implicitly truncated so sext vs. zext doesn't matter. 7367 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7368 } 7369 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7370 } 7371 7372 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7373 unsigned Opcode = N->getOpcode(); 7374 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7375 SDNode *N0 = N->getOperand(0).getNode(); 7376 SDNode *N1 = N->getOperand(1).getNode(); 7377 return N0->hasOneUse() && N1->hasOneUse() && 7378 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7379 } 7380 return false; 7381 } 7382 7383 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7384 unsigned Opcode = N->getOpcode(); 7385 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7386 SDNode *N0 = N->getOperand(0).getNode(); 7387 SDNode *N1 = N->getOperand(1).getNode(); 7388 return N0->hasOneUse() && N1->hasOneUse() && 7389 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7390 } 7391 return false; 7392 } 7393 7394 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7395 // Multiplications are only custom-lowered for 128-bit vectors so that 7396 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7397 EVT VT = Op.getValueType(); 7398 assert(VT.is128BitVector() && VT.isInteger() && 7399 "unexpected type for custom-lowering ISD::MUL"); 7400 SDNode *N0 = Op.getOperand(0).getNode(); 7401 SDNode *N1 = Op.getOperand(1).getNode(); 7402 unsigned NewOpc = 0; 7403 bool isMLA = false; 7404 bool isN0SExt = isSignExtended(N0, DAG); 7405 bool isN1SExt = isSignExtended(N1, DAG); 7406 if (isN0SExt && isN1SExt) 7407 NewOpc = ARMISD::VMULLs; 7408 else { 7409 bool isN0ZExt = isZeroExtended(N0, DAG); 7410 bool isN1ZExt = isZeroExtended(N1, DAG); 7411 if (isN0ZExt && isN1ZExt) 7412 NewOpc = ARMISD::VMULLu; 7413 else if (isN1SExt || isN1ZExt) { 7414 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7415 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7416 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7417 NewOpc = ARMISD::VMULLs; 7418 isMLA = true; 7419 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7420 NewOpc = ARMISD::VMULLu; 7421 isMLA = true; 7422 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7423 std::swap(N0, N1); 7424 NewOpc = ARMISD::VMULLu; 7425 isMLA = true; 7426 } 7427 } 7428 7429 if (!NewOpc) { 7430 if (VT == MVT::v2i64) 7431 // Fall through to expand this. It is not legal. 7432 return SDValue(); 7433 else 7434 // Other vector multiplications are legal. 7435 return Op; 7436 } 7437 } 7438 7439 // Legalize to a VMULL instruction. 7440 SDLoc DL(Op); 7441 SDValue Op0; 7442 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7443 if (!isMLA) { 7444 Op0 = SkipExtensionForVMULL(N0, DAG); 7445 assert(Op0.getValueType().is64BitVector() && 7446 Op1.getValueType().is64BitVector() && 7447 "unexpected types for extended operands to VMULL"); 7448 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7449 } 7450 7451 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7452 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7453 // vmull q0, d4, d6 7454 // vmlal q0, d5, d6 7455 // is faster than 7456 // vaddl q0, d4, d5 7457 // vmovl q1, d6 7458 // vmul q0, q0, q1 7459 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7460 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7461 EVT Op1VT = Op1.getValueType(); 7462 return DAG.getNode(N0->getOpcode(), DL, VT, 7463 DAG.getNode(NewOpc, DL, VT, 7464 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7465 DAG.getNode(NewOpc, DL, VT, 7466 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7467 } 7468 7469 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7470 SelectionDAG &DAG) { 7471 // TODO: Should this propagate fast-math-flags? 7472 7473 // Convert to float 7474 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7475 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7476 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7477 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7478 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7479 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7480 // Get reciprocal estimate. 7481 // float4 recip = vrecpeq_f32(yf); 7482 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7483 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7484 Y); 7485 // Because char has a smaller range than uchar, we can actually get away 7486 // without any newton steps. This requires that we use a weird bias 7487 // of 0xb000, however (again, this has been exhaustively tested). 7488 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7489 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7490 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7491 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7492 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7493 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7494 // Convert back to short. 7495 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7496 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7497 return X; 7498 } 7499 7500 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7501 SelectionDAG &DAG) { 7502 // TODO: Should this propagate fast-math-flags? 7503 7504 SDValue N2; 7505 // Convert to float. 7506 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7507 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7508 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7509 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7510 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7511 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7512 7513 // Use reciprocal estimate and one refinement step. 7514 // float4 recip = vrecpeq_f32(yf); 7515 // recip *= vrecpsq_f32(yf, recip); 7516 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7517 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7518 N1); 7519 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7520 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7521 N1, N2); 7522 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7523 // Because short has a smaller range than ushort, we can actually get away 7524 // with only a single newton step. This requires that we use a weird bias 7525 // of 89, however (again, this has been exhaustively tested). 7526 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7527 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7528 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7529 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7530 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7531 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7532 // Convert back to integer and return. 7533 // return vmovn_s32(vcvt_s32_f32(result)); 7534 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7535 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7536 return N0; 7537 } 7538 7539 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7540 EVT VT = Op.getValueType(); 7541 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7542 "unexpected type for custom-lowering ISD::SDIV"); 7543 7544 SDLoc dl(Op); 7545 SDValue N0 = Op.getOperand(0); 7546 SDValue N1 = Op.getOperand(1); 7547 SDValue N2, N3; 7548 7549 if (VT == MVT::v8i8) { 7550 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7551 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7552 7553 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7554 DAG.getIntPtrConstant(4, dl)); 7555 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7556 DAG.getIntPtrConstant(4, dl)); 7557 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7558 DAG.getIntPtrConstant(0, dl)); 7559 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7560 DAG.getIntPtrConstant(0, dl)); 7561 7562 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7563 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7564 7565 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7566 N0 = LowerCONCAT_VECTORS(N0, DAG); 7567 7568 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7569 return N0; 7570 } 7571 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7572 } 7573 7574 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7575 // TODO: Should this propagate fast-math-flags? 7576 EVT VT = Op.getValueType(); 7577 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7578 "unexpected type for custom-lowering ISD::UDIV"); 7579 7580 SDLoc dl(Op); 7581 SDValue N0 = Op.getOperand(0); 7582 SDValue N1 = Op.getOperand(1); 7583 SDValue N2, N3; 7584 7585 if (VT == MVT::v8i8) { 7586 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7587 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7588 7589 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7590 DAG.getIntPtrConstant(4, dl)); 7591 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7592 DAG.getIntPtrConstant(4, dl)); 7593 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7594 DAG.getIntPtrConstant(0, dl)); 7595 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7596 DAG.getIntPtrConstant(0, dl)); 7597 7598 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7599 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7600 7601 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7602 N0 = LowerCONCAT_VECTORS(N0, DAG); 7603 7604 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7605 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7606 MVT::i32), 7607 N0); 7608 return N0; 7609 } 7610 7611 // v4i16 sdiv ... Convert to float. 7612 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7613 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7614 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7615 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7616 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7617 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7618 7619 // Use reciprocal estimate and two refinement steps. 7620 // float4 recip = vrecpeq_f32(yf); 7621 // recip *= vrecpsq_f32(yf, recip); 7622 // recip *= vrecpsq_f32(yf, recip); 7623 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7624 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7625 BN1); 7626 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7627 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7628 BN1, N2); 7629 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7630 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7631 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7632 BN1, N2); 7633 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7634 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7635 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7636 // and that it will never cause us to return an answer too large). 7637 // float4 result = as_float4(as_int4(xf*recip) + 2); 7638 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7639 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7640 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7641 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7642 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7643 // Convert back to integer and return. 7644 // return vmovn_u32(vcvt_s32_f32(result)); 7645 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7646 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7647 return N0; 7648 } 7649 7650 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7651 SDNode *N = Op.getNode(); 7652 EVT VT = N->getValueType(0); 7653 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7654 7655 SDValue Carry = Op.getOperand(2); 7656 7657 SDLoc DL(Op); 7658 7659 SDValue Result; 7660 if (Op.getOpcode() == ISD::ADDCARRY) { 7661 // This converts the boolean value carry into the carry flag. 7662 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7663 7664 // Do the addition proper using the carry flag we wanted. 7665 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7666 Op.getOperand(1), Carry); 7667 7668 // Now convert the carry flag into a boolean value. 7669 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7670 } else { 7671 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7672 // have to invert the carry first. 7673 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7674 DAG.getConstant(1, DL, MVT::i32), Carry); 7675 // This converts the boolean value carry into the carry flag. 7676 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7677 7678 // Do the subtraction proper using the carry flag we wanted. 7679 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7680 Op.getOperand(1), Carry); 7681 7682 // Now convert the carry flag into a boolean value. 7683 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7684 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7685 // by ISD::SUBCARRY, so compute 1 - C. 7686 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7687 DAG.getConstant(1, DL, MVT::i32), Carry); 7688 } 7689 7690 // Return both values. 7691 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7692 } 7693 7694 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7695 assert(Subtarget->isTargetDarwin()); 7696 7697 // For iOS, we want to call an alternative entry point: __sincos_stret, 7698 // return values are passed via sret. 7699 SDLoc dl(Op); 7700 SDValue Arg = Op.getOperand(0); 7701 EVT ArgVT = Arg.getValueType(); 7702 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7703 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7704 7705 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7706 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7707 7708 // Pair of floats / doubles used to pass the result. 7709 Type *RetTy = StructType::get(ArgTy, ArgTy); 7710 auto &DL = DAG.getDataLayout(); 7711 7712 ArgListTy Args; 7713 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7714 SDValue SRet; 7715 if (ShouldUseSRet) { 7716 // Create stack object for sret. 7717 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7718 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7719 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7720 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7721 7722 ArgListEntry Entry; 7723 Entry.Node = SRet; 7724 Entry.Ty = RetTy->getPointerTo(); 7725 Entry.IsSExt = false; 7726 Entry.IsZExt = false; 7727 Entry.IsSRet = true; 7728 Args.push_back(Entry); 7729 RetTy = Type::getVoidTy(*DAG.getContext()); 7730 } 7731 7732 ArgListEntry Entry; 7733 Entry.Node = Arg; 7734 Entry.Ty = ArgTy; 7735 Entry.IsSExt = false; 7736 Entry.IsZExt = false; 7737 Args.push_back(Entry); 7738 7739 RTLIB::Libcall LC = 7740 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7741 const char *LibcallName = getLibcallName(LC); 7742 CallingConv::ID CC = getLibcallCallingConv(LC); 7743 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7744 7745 TargetLowering::CallLoweringInfo CLI(DAG); 7746 CLI.setDebugLoc(dl) 7747 .setChain(DAG.getEntryNode()) 7748 .setCallee(CC, RetTy, Callee, std::move(Args)) 7749 .setDiscardResult(ShouldUseSRet); 7750 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7751 7752 if (!ShouldUseSRet) 7753 return CallResult.first; 7754 7755 SDValue LoadSin = 7756 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7757 7758 // Address of cos field. 7759 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7760 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7761 SDValue LoadCos = 7762 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7763 7764 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7765 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7766 LoadSin.getValue(0), LoadCos.getValue(0)); 7767 } 7768 7769 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7770 bool Signed, 7771 SDValue &Chain) const { 7772 EVT VT = Op.getValueType(); 7773 assert((VT == MVT::i32 || VT == MVT::i64) && 7774 "unexpected type for custom lowering DIV"); 7775 SDLoc dl(Op); 7776 7777 const auto &DL = DAG.getDataLayout(); 7778 const auto &TLI = DAG.getTargetLoweringInfo(); 7779 7780 const char *Name = nullptr; 7781 if (Signed) 7782 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7783 else 7784 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7785 7786 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7787 7788 ARMTargetLowering::ArgListTy Args; 7789 7790 for (auto AI : {1, 0}) { 7791 ArgListEntry Arg; 7792 Arg.Node = Op.getOperand(AI); 7793 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7794 Args.push_back(Arg); 7795 } 7796 7797 CallLoweringInfo CLI(DAG); 7798 CLI.setDebugLoc(dl) 7799 .setChain(Chain) 7800 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7801 ES, std::move(Args)); 7802 7803 return LowerCallTo(CLI).first; 7804 } 7805 7806 // This is a code size optimisation: return the original SDIV node to 7807 // DAGCombiner when we don't want to expand SDIV into a sequence of 7808 // instructions, and an empty node otherwise which will cause the 7809 // SDIV to be expanded in DAGCombine. 7810 SDValue 7811 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 7812 SelectionDAG &DAG, 7813 SmallVectorImpl<SDNode *> &Created) const { 7814 // TODO: Support SREM 7815 if (N->getOpcode() != ISD::SDIV) 7816 return SDValue(); 7817 7818 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 7819 const bool MinSize = ST.hasMinSize(); 7820 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 7821 : ST.hasDivideInARMMode(); 7822 7823 // Don't touch vector types; rewriting this may lead to scalarizing 7824 // the int divs. 7825 if (N->getOperand(0).getValueType().isVector()) 7826 return SDValue(); 7827 7828 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 7829 // hwdiv support for this to be really profitable. 7830 if (!(MinSize && HasDivide)) 7831 return SDValue(); 7832 7833 // ARM mode is a bit simpler than Thumb: we can handle large power 7834 // of 2 immediates with 1 mov instruction; no further checks required, 7835 // just return the sdiv node. 7836 if (!ST.isThumb()) 7837 return SDValue(N, 0); 7838 7839 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 7840 // and thus lose the code size benefits of a MOVS that requires only 2. 7841 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 7842 // but as it's doing exactly this, it's not worth the trouble to get TTI. 7843 if (Divisor.sgt(128)) 7844 return SDValue(); 7845 7846 return SDValue(N, 0); 7847 } 7848 7849 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7850 bool Signed) const { 7851 assert(Op.getValueType() == MVT::i32 && 7852 "unexpected type for custom lowering DIV"); 7853 SDLoc dl(Op); 7854 7855 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7856 DAG.getEntryNode(), Op.getOperand(1)); 7857 7858 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7859 } 7860 7861 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7862 SDLoc DL(N); 7863 SDValue Op = N->getOperand(1); 7864 if (N->getValueType(0) == MVT::i32) 7865 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7866 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7867 DAG.getConstant(0, DL, MVT::i32)); 7868 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7869 DAG.getConstant(1, DL, MVT::i32)); 7870 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7871 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7872 } 7873 7874 void ARMTargetLowering::ExpandDIV_Windows( 7875 SDValue Op, SelectionDAG &DAG, bool Signed, 7876 SmallVectorImpl<SDValue> &Results) const { 7877 const auto &DL = DAG.getDataLayout(); 7878 const auto &TLI = DAG.getTargetLoweringInfo(); 7879 7880 assert(Op.getValueType() == MVT::i64 && 7881 "unexpected type for custom lowering DIV"); 7882 SDLoc dl(Op); 7883 7884 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7885 7886 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7887 7888 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7889 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7890 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7891 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7892 7893 Results.push_back(Lower); 7894 Results.push_back(Upper); 7895 } 7896 7897 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7898 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7899 // Acquire/Release load/store is not legal for targets without a dmb or 7900 // equivalent available. 7901 return SDValue(); 7902 7903 // Monotonic load/store is legal for all targets. 7904 return Op; 7905 } 7906 7907 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7908 SmallVectorImpl<SDValue> &Results, 7909 SelectionDAG &DAG, 7910 const ARMSubtarget *Subtarget) { 7911 SDLoc DL(N); 7912 // Under Power Management extensions, the cycle-count is: 7913 // mrc p15, #0, <Rt>, c9, c13, #0 7914 SDValue Ops[] = { N->getOperand(0), // Chain 7915 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7916 DAG.getConstant(15, DL, MVT::i32), 7917 DAG.getConstant(0, DL, MVT::i32), 7918 DAG.getConstant(9, DL, MVT::i32), 7919 DAG.getConstant(13, DL, MVT::i32), 7920 DAG.getConstant(0, DL, MVT::i32) 7921 }; 7922 7923 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7924 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7925 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7926 DAG.getConstant(0, DL, MVT::i32))); 7927 Results.push_back(Cycles32.getValue(1)); 7928 } 7929 7930 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7931 SDLoc dl(V.getNode()); 7932 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7933 SDValue VHi = DAG.getAnyExtOrTrunc( 7934 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7935 dl, MVT::i32); 7936 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7937 if (isBigEndian) 7938 std::swap (VLo, VHi); 7939 SDValue RegClass = 7940 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7941 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7942 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7943 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7944 return SDValue( 7945 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7946 } 7947 7948 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7949 SmallVectorImpl<SDValue> & Results, 7950 SelectionDAG &DAG) { 7951 assert(N->getValueType(0) == MVT::i64 && 7952 "AtomicCmpSwap on types less than 64 should be legal"); 7953 SDValue Ops[] = {N->getOperand(1), 7954 createGPRPairNode(DAG, N->getOperand(2)), 7955 createGPRPairNode(DAG, N->getOperand(3)), 7956 N->getOperand(0)}; 7957 SDNode *CmpSwap = DAG.getMachineNode( 7958 ARM::CMP_SWAP_64, SDLoc(N), 7959 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7960 7961 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 7962 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 7963 7964 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7965 7966 Results.push_back( 7967 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 7968 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7969 Results.push_back( 7970 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 7971 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7972 Results.push_back(SDValue(CmpSwap, 2)); 7973 } 7974 7975 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7976 SelectionDAG &DAG) { 7977 const auto &TLI = DAG.getTargetLoweringInfo(); 7978 7979 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7980 "Custom lowering is MSVCRT specific!"); 7981 7982 SDLoc dl(Op); 7983 SDValue Val = Op.getOperand(0); 7984 MVT Ty = Val->getSimpleValueType(0); 7985 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7986 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7987 TLI.getPointerTy(DAG.getDataLayout())); 7988 7989 TargetLowering::ArgListTy Args; 7990 TargetLowering::ArgListEntry Entry; 7991 7992 Entry.Node = Val; 7993 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7994 Entry.IsZExt = true; 7995 Args.push_back(Entry); 7996 7997 Entry.Node = Exponent; 7998 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7999 Entry.IsZExt = true; 8000 Args.push_back(Entry); 8001 8002 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8003 8004 // In the in-chain to the call is the entry node If we are emitting a 8005 // tailcall, the chain will be mutated if the node has a non-entry input 8006 // chain. 8007 SDValue InChain = DAG.getEntryNode(); 8008 SDValue TCChain = InChain; 8009 8010 const Function &F = DAG.getMachineFunction().getFunction(); 8011 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8012 F.getReturnType() == LCRTy; 8013 if (IsTC) 8014 InChain = TCChain; 8015 8016 TargetLowering::CallLoweringInfo CLI(DAG); 8017 CLI.setDebugLoc(dl) 8018 .setChain(InChain) 8019 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8020 .setTailCall(IsTC); 8021 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8022 8023 // Return the chain (the DAG root) if it is a tail call 8024 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8025 } 8026 8027 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8028 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8029 switch (Op.getOpcode()) { 8030 default: llvm_unreachable("Don't know how to custom lower this!"); 8031 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8032 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8033 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8034 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8035 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8036 case ISD::SELECT: return LowerSELECT(Op, DAG); 8037 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8038 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8039 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8040 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8041 case ISD::VASTART: return LowerVASTART(Op, DAG); 8042 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8043 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8044 case ISD::SINT_TO_FP: 8045 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8046 case ISD::FP_TO_SINT: 8047 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8048 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8049 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8050 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8051 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8052 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8053 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8054 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8055 Subtarget); 8056 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8057 case ISD::SHL: 8058 case ISD::SRL: 8059 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8060 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8061 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8062 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8063 case ISD::SRL_PARTS: 8064 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8065 case ISD::CTTZ: 8066 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8067 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8068 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8069 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8070 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8071 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8072 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8073 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8074 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8075 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8076 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8077 case ISD::MUL: return LowerMUL(Op, DAG); 8078 case ISD::SDIV: 8079 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8080 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8081 return LowerSDIV(Op, DAG); 8082 case ISD::UDIV: 8083 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8084 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8085 return LowerUDIV(Op, DAG); 8086 case ISD::ADDCARRY: 8087 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8088 case ISD::SADDO: 8089 case ISD::SSUBO: 8090 return LowerSignedALUO(Op, DAG); 8091 case ISD::UADDO: 8092 case ISD::USUBO: 8093 return LowerUnsignedALUO(Op, DAG); 8094 case ISD::ATOMIC_LOAD: 8095 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8096 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8097 case ISD::SDIVREM: 8098 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8099 case ISD::DYNAMIC_STACKALLOC: 8100 if (Subtarget->isTargetWindows()) 8101 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8102 llvm_unreachable("Don't know how to custom lower this!"); 8103 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8104 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8105 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8106 case ARMISD::WIN__DBZCHK: return SDValue(); 8107 } 8108 } 8109 8110 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8111 SelectionDAG &DAG) { 8112 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8113 unsigned Opc = 0; 8114 if (IntNo == Intrinsic::arm_smlald) 8115 Opc = ARMISD::SMLALD; 8116 else if (IntNo == Intrinsic::arm_smlaldx) 8117 Opc = ARMISD::SMLALDX; 8118 else if (IntNo == Intrinsic::arm_smlsld) 8119 Opc = ARMISD::SMLSLD; 8120 else if (IntNo == Intrinsic::arm_smlsldx) 8121 Opc = ARMISD::SMLSLDX; 8122 else 8123 return; 8124 8125 SDLoc dl(N); 8126 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8127 N->getOperand(3), 8128 DAG.getConstant(0, dl, MVT::i32)); 8129 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8130 N->getOperand(3), 8131 DAG.getConstant(1, dl, MVT::i32)); 8132 8133 SDValue LongMul = DAG.getNode(Opc, dl, 8134 DAG.getVTList(MVT::i32, MVT::i32), 8135 N->getOperand(1), N->getOperand(2), 8136 Lo, Hi); 8137 Results.push_back(LongMul.getValue(0)); 8138 Results.push_back(LongMul.getValue(1)); 8139 } 8140 8141 /// ReplaceNodeResults - Replace the results of node with an illegal result 8142 /// type with new values built out of custom code. 8143 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8144 SmallVectorImpl<SDValue> &Results, 8145 SelectionDAG &DAG) const { 8146 SDValue Res; 8147 switch (N->getOpcode()) { 8148 default: 8149 llvm_unreachable("Don't know how to custom expand this!"); 8150 case ISD::READ_REGISTER: 8151 ExpandREAD_REGISTER(N, Results, DAG); 8152 break; 8153 case ISD::BITCAST: 8154 Res = ExpandBITCAST(N, DAG, Subtarget); 8155 break; 8156 case ISD::SRL: 8157 case ISD::SRA: 8158 Res = Expand64BitShift(N, DAG, Subtarget); 8159 break; 8160 case ISD::SREM: 8161 case ISD::UREM: 8162 Res = LowerREM(N, DAG); 8163 break; 8164 case ISD::SDIVREM: 8165 case ISD::UDIVREM: 8166 Res = LowerDivRem(SDValue(N, 0), DAG); 8167 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8168 Results.push_back(Res.getValue(0)); 8169 Results.push_back(Res.getValue(1)); 8170 return; 8171 case ISD::READCYCLECOUNTER: 8172 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8173 return; 8174 case ISD::UDIV: 8175 case ISD::SDIV: 8176 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8177 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8178 Results); 8179 case ISD::ATOMIC_CMP_SWAP: 8180 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8181 return; 8182 case ISD::INTRINSIC_WO_CHAIN: 8183 return ReplaceLongIntrinsic(N, Results, DAG); 8184 case ISD::ABS: 8185 lowerABS(N, Results, DAG); 8186 return ; 8187 8188 } 8189 if (Res.getNode()) 8190 Results.push_back(Res); 8191 } 8192 8193 //===----------------------------------------------------------------------===// 8194 // ARM Scheduler Hooks 8195 //===----------------------------------------------------------------------===// 8196 8197 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8198 /// registers the function context. 8199 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8200 MachineBasicBlock *MBB, 8201 MachineBasicBlock *DispatchBB, 8202 int FI) const { 8203 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8204 "ROPI/RWPI not currently supported with SjLj"); 8205 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8206 DebugLoc dl = MI.getDebugLoc(); 8207 MachineFunction *MF = MBB->getParent(); 8208 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8209 MachineConstantPool *MCP = MF->getConstantPool(); 8210 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8211 const Function &F = MF->getFunction(); 8212 8213 bool isThumb = Subtarget->isThumb(); 8214 bool isThumb2 = Subtarget->isThumb2(); 8215 8216 unsigned PCLabelId = AFI->createPICLabelUId(); 8217 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8218 ARMConstantPoolValue *CPV = 8219 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8220 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8221 8222 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8223 : &ARM::GPRRegClass; 8224 8225 // Grab constant pool and fixed stack memory operands. 8226 MachineMemOperand *CPMMO = 8227 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8228 MachineMemOperand::MOLoad, 4, 4); 8229 8230 MachineMemOperand *FIMMOSt = 8231 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8232 MachineMemOperand::MOStore, 4, 4); 8233 8234 // Load the address of the dispatch MBB into the jump buffer. 8235 if (isThumb2) { 8236 // Incoming value: jbuf 8237 // ldr.n r5, LCPI1_1 8238 // orr r5, r5, #1 8239 // add r5, pc 8240 // str r5, [$jbuf, #+4] ; &jbuf[1] 8241 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8242 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8243 .addConstantPoolIndex(CPI) 8244 .addMemOperand(CPMMO) 8245 .add(predOps(ARMCC::AL)); 8246 // Set the low bit because of thumb mode. 8247 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8248 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8249 .addReg(NewVReg1, RegState::Kill) 8250 .addImm(0x01) 8251 .add(predOps(ARMCC::AL)) 8252 .add(condCodeOp()); 8253 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8254 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8255 .addReg(NewVReg2, RegState::Kill) 8256 .addImm(PCLabelId); 8257 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8258 .addReg(NewVReg3, RegState::Kill) 8259 .addFrameIndex(FI) 8260 .addImm(36) // &jbuf[1] :: pc 8261 .addMemOperand(FIMMOSt) 8262 .add(predOps(ARMCC::AL)); 8263 } else if (isThumb) { 8264 // Incoming value: jbuf 8265 // ldr.n r1, LCPI1_4 8266 // add r1, pc 8267 // mov r2, #1 8268 // orrs r1, r2 8269 // add r2, $jbuf, #+4 ; &jbuf[1] 8270 // str r1, [r2] 8271 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8272 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8273 .addConstantPoolIndex(CPI) 8274 .addMemOperand(CPMMO) 8275 .add(predOps(ARMCC::AL)); 8276 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8277 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8278 .addReg(NewVReg1, RegState::Kill) 8279 .addImm(PCLabelId); 8280 // Set the low bit because of thumb mode. 8281 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8282 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8283 .addReg(ARM::CPSR, RegState::Define) 8284 .addImm(1) 8285 .add(predOps(ARMCC::AL)); 8286 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8287 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8288 .addReg(ARM::CPSR, RegState::Define) 8289 .addReg(NewVReg2, RegState::Kill) 8290 .addReg(NewVReg3, RegState::Kill) 8291 .add(predOps(ARMCC::AL)); 8292 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8293 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8294 .addFrameIndex(FI) 8295 .addImm(36); // &jbuf[1] :: pc 8296 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8297 .addReg(NewVReg4, RegState::Kill) 8298 .addReg(NewVReg5, RegState::Kill) 8299 .addImm(0) 8300 .addMemOperand(FIMMOSt) 8301 .add(predOps(ARMCC::AL)); 8302 } else { 8303 // Incoming value: jbuf 8304 // ldr r1, LCPI1_1 8305 // add r1, pc, r1 8306 // str r1, [$jbuf, #+4] ; &jbuf[1] 8307 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8308 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8309 .addConstantPoolIndex(CPI) 8310 .addImm(0) 8311 .addMemOperand(CPMMO) 8312 .add(predOps(ARMCC::AL)); 8313 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8314 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8315 .addReg(NewVReg1, RegState::Kill) 8316 .addImm(PCLabelId) 8317 .add(predOps(ARMCC::AL)); 8318 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8319 .addReg(NewVReg2, RegState::Kill) 8320 .addFrameIndex(FI) 8321 .addImm(36) // &jbuf[1] :: pc 8322 .addMemOperand(FIMMOSt) 8323 .add(predOps(ARMCC::AL)); 8324 } 8325 } 8326 8327 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8328 MachineBasicBlock *MBB) const { 8329 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8330 DebugLoc dl = MI.getDebugLoc(); 8331 MachineFunction *MF = MBB->getParent(); 8332 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8333 MachineFrameInfo &MFI = MF->getFrameInfo(); 8334 int FI = MFI.getFunctionContextIndex(); 8335 8336 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8337 : &ARM::GPRnopcRegClass; 8338 8339 // Get a mapping of the call site numbers to all of the landing pads they're 8340 // associated with. 8341 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8342 unsigned MaxCSNum = 0; 8343 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8344 ++BB) { 8345 if (!BB->isEHPad()) continue; 8346 8347 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8348 // pad. 8349 for (MachineBasicBlock::iterator 8350 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8351 if (!II->isEHLabel()) continue; 8352 8353 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8354 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8355 8356 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8357 for (SmallVectorImpl<unsigned>::iterator 8358 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8359 CSI != CSE; ++CSI) { 8360 CallSiteNumToLPad[*CSI].push_back(&*BB); 8361 MaxCSNum = std::max(MaxCSNum, *CSI); 8362 } 8363 break; 8364 } 8365 } 8366 8367 // Get an ordered list of the machine basic blocks for the jump table. 8368 std::vector<MachineBasicBlock*> LPadList; 8369 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8370 LPadList.reserve(CallSiteNumToLPad.size()); 8371 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8372 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8373 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8374 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8375 LPadList.push_back(*II); 8376 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8377 } 8378 } 8379 8380 assert(!LPadList.empty() && 8381 "No landing pad destinations for the dispatch jump table!"); 8382 8383 // Create the jump table and associated information. 8384 MachineJumpTableInfo *JTI = 8385 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8386 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8387 8388 // Create the MBBs for the dispatch code. 8389 8390 // Shove the dispatch's address into the return slot in the function context. 8391 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8392 DispatchBB->setIsEHPad(); 8393 8394 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8395 unsigned trap_opcode; 8396 if (Subtarget->isThumb()) 8397 trap_opcode = ARM::tTRAP; 8398 else 8399 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8400 8401 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8402 DispatchBB->addSuccessor(TrapBB); 8403 8404 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8405 DispatchBB->addSuccessor(DispContBB); 8406 8407 // Insert and MBBs. 8408 MF->insert(MF->end(), DispatchBB); 8409 MF->insert(MF->end(), DispContBB); 8410 MF->insert(MF->end(), TrapBB); 8411 8412 // Insert code into the entry block that creates and registers the function 8413 // context. 8414 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8415 8416 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8417 MachinePointerInfo::getFixedStack(*MF, FI), 8418 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8419 8420 MachineInstrBuilder MIB; 8421 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8422 8423 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8424 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8425 8426 // Add a register mask with no preserved registers. This results in all 8427 // registers being marked as clobbered. This can't work if the dispatch block 8428 // is in a Thumb1 function and is linked with ARM code which uses the FP 8429 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8430 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8431 8432 bool IsPositionIndependent = isPositionIndependent(); 8433 unsigned NumLPads = LPadList.size(); 8434 if (Subtarget->isThumb2()) { 8435 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8436 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8437 .addFrameIndex(FI) 8438 .addImm(4) 8439 .addMemOperand(FIMMOLd) 8440 .add(predOps(ARMCC::AL)); 8441 8442 if (NumLPads < 256) { 8443 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8444 .addReg(NewVReg1) 8445 .addImm(LPadList.size()) 8446 .add(predOps(ARMCC::AL)); 8447 } else { 8448 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8449 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8450 .addImm(NumLPads & 0xFFFF) 8451 .add(predOps(ARMCC::AL)); 8452 8453 unsigned VReg2 = VReg1; 8454 if ((NumLPads & 0xFFFF0000) != 0) { 8455 VReg2 = MRI->createVirtualRegister(TRC); 8456 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8457 .addReg(VReg1) 8458 .addImm(NumLPads >> 16) 8459 .add(predOps(ARMCC::AL)); 8460 } 8461 8462 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8463 .addReg(NewVReg1) 8464 .addReg(VReg2) 8465 .add(predOps(ARMCC::AL)); 8466 } 8467 8468 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8469 .addMBB(TrapBB) 8470 .addImm(ARMCC::HI) 8471 .addReg(ARM::CPSR); 8472 8473 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8474 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8475 .addJumpTableIndex(MJTI) 8476 .add(predOps(ARMCC::AL)); 8477 8478 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8479 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8480 .addReg(NewVReg3, RegState::Kill) 8481 .addReg(NewVReg1) 8482 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8483 .add(predOps(ARMCC::AL)) 8484 .add(condCodeOp()); 8485 8486 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8487 .addReg(NewVReg4, RegState::Kill) 8488 .addReg(NewVReg1) 8489 .addJumpTableIndex(MJTI); 8490 } else if (Subtarget->isThumb()) { 8491 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8492 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8493 .addFrameIndex(FI) 8494 .addImm(1) 8495 .addMemOperand(FIMMOLd) 8496 .add(predOps(ARMCC::AL)); 8497 8498 if (NumLPads < 256) { 8499 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8500 .addReg(NewVReg1) 8501 .addImm(NumLPads) 8502 .add(predOps(ARMCC::AL)); 8503 } else { 8504 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8505 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8506 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8507 8508 // MachineConstantPool wants an explicit alignment. 8509 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8510 if (Align == 0) 8511 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8512 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8513 8514 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8515 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8516 .addReg(VReg1, RegState::Define) 8517 .addConstantPoolIndex(Idx) 8518 .add(predOps(ARMCC::AL)); 8519 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8520 .addReg(NewVReg1) 8521 .addReg(VReg1) 8522 .add(predOps(ARMCC::AL)); 8523 } 8524 8525 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8526 .addMBB(TrapBB) 8527 .addImm(ARMCC::HI) 8528 .addReg(ARM::CPSR); 8529 8530 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8531 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8532 .addReg(ARM::CPSR, RegState::Define) 8533 .addReg(NewVReg1) 8534 .addImm(2) 8535 .add(predOps(ARMCC::AL)); 8536 8537 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8538 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8539 .addJumpTableIndex(MJTI) 8540 .add(predOps(ARMCC::AL)); 8541 8542 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8543 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8544 .addReg(ARM::CPSR, RegState::Define) 8545 .addReg(NewVReg2, RegState::Kill) 8546 .addReg(NewVReg3) 8547 .add(predOps(ARMCC::AL)); 8548 8549 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8550 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8551 8552 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8553 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8554 .addReg(NewVReg4, RegState::Kill) 8555 .addImm(0) 8556 .addMemOperand(JTMMOLd) 8557 .add(predOps(ARMCC::AL)); 8558 8559 unsigned NewVReg6 = NewVReg5; 8560 if (IsPositionIndependent) { 8561 NewVReg6 = MRI->createVirtualRegister(TRC); 8562 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8563 .addReg(ARM::CPSR, RegState::Define) 8564 .addReg(NewVReg5, RegState::Kill) 8565 .addReg(NewVReg3) 8566 .add(predOps(ARMCC::AL)); 8567 } 8568 8569 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8570 .addReg(NewVReg6, RegState::Kill) 8571 .addJumpTableIndex(MJTI); 8572 } else { 8573 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8574 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8575 .addFrameIndex(FI) 8576 .addImm(4) 8577 .addMemOperand(FIMMOLd) 8578 .add(predOps(ARMCC::AL)); 8579 8580 if (NumLPads < 256) { 8581 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8582 .addReg(NewVReg1) 8583 .addImm(NumLPads) 8584 .add(predOps(ARMCC::AL)); 8585 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8586 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8587 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8588 .addImm(NumLPads & 0xFFFF) 8589 .add(predOps(ARMCC::AL)); 8590 8591 unsigned VReg2 = VReg1; 8592 if ((NumLPads & 0xFFFF0000) != 0) { 8593 VReg2 = MRI->createVirtualRegister(TRC); 8594 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8595 .addReg(VReg1) 8596 .addImm(NumLPads >> 16) 8597 .add(predOps(ARMCC::AL)); 8598 } 8599 8600 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8601 .addReg(NewVReg1) 8602 .addReg(VReg2) 8603 .add(predOps(ARMCC::AL)); 8604 } else { 8605 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8606 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8607 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8608 8609 // MachineConstantPool wants an explicit alignment. 8610 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8611 if (Align == 0) 8612 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8613 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8614 8615 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8616 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8617 .addReg(VReg1, RegState::Define) 8618 .addConstantPoolIndex(Idx) 8619 .addImm(0) 8620 .add(predOps(ARMCC::AL)); 8621 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8622 .addReg(NewVReg1) 8623 .addReg(VReg1, RegState::Kill) 8624 .add(predOps(ARMCC::AL)); 8625 } 8626 8627 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8628 .addMBB(TrapBB) 8629 .addImm(ARMCC::HI) 8630 .addReg(ARM::CPSR); 8631 8632 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8633 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8634 .addReg(NewVReg1) 8635 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8636 .add(predOps(ARMCC::AL)) 8637 .add(condCodeOp()); 8638 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8639 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8640 .addJumpTableIndex(MJTI) 8641 .add(predOps(ARMCC::AL)); 8642 8643 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8644 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8645 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8646 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8647 .addReg(NewVReg3, RegState::Kill) 8648 .addReg(NewVReg4) 8649 .addImm(0) 8650 .addMemOperand(JTMMOLd) 8651 .add(predOps(ARMCC::AL)); 8652 8653 if (IsPositionIndependent) { 8654 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8655 .addReg(NewVReg5, RegState::Kill) 8656 .addReg(NewVReg4) 8657 .addJumpTableIndex(MJTI); 8658 } else { 8659 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8660 .addReg(NewVReg5, RegState::Kill) 8661 .addJumpTableIndex(MJTI); 8662 } 8663 } 8664 8665 // Add the jump table entries as successors to the MBB. 8666 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8667 for (std::vector<MachineBasicBlock*>::iterator 8668 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8669 MachineBasicBlock *CurMBB = *I; 8670 if (SeenMBBs.insert(CurMBB).second) 8671 DispContBB->addSuccessor(CurMBB); 8672 } 8673 8674 // N.B. the order the invoke BBs are processed in doesn't matter here. 8675 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8676 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8677 for (MachineBasicBlock *BB : InvokeBBs) { 8678 8679 // Remove the landing pad successor from the invoke block and replace it 8680 // with the new dispatch block. 8681 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8682 BB->succ_end()); 8683 while (!Successors.empty()) { 8684 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8685 if (SMBB->isEHPad()) { 8686 BB->removeSuccessor(SMBB); 8687 MBBLPads.push_back(SMBB); 8688 } 8689 } 8690 8691 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8692 BB->normalizeSuccProbs(); 8693 8694 // Find the invoke call and mark all of the callee-saved registers as 8695 // 'implicit defined' so that they're spilled. This prevents code from 8696 // moving instructions to before the EH block, where they will never be 8697 // executed. 8698 for (MachineBasicBlock::reverse_iterator 8699 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8700 if (!II->isCall()) continue; 8701 8702 DenseMap<unsigned, bool> DefRegs; 8703 for (MachineInstr::mop_iterator 8704 OI = II->operands_begin(), OE = II->operands_end(); 8705 OI != OE; ++OI) { 8706 if (!OI->isReg()) continue; 8707 DefRegs[OI->getReg()] = true; 8708 } 8709 8710 MachineInstrBuilder MIB(*MF, &*II); 8711 8712 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8713 unsigned Reg = SavedRegs[i]; 8714 if (Subtarget->isThumb2() && 8715 !ARM::tGPRRegClass.contains(Reg) && 8716 !ARM::hGPRRegClass.contains(Reg)) 8717 continue; 8718 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8719 continue; 8720 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8721 continue; 8722 if (!DefRegs[Reg]) 8723 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8724 } 8725 8726 break; 8727 } 8728 } 8729 8730 // Mark all former landing pads as non-landing pads. The dispatch is the only 8731 // landing pad now. 8732 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8733 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8734 (*I)->setIsEHPad(false); 8735 8736 // The instruction is gone now. 8737 MI.eraseFromParent(); 8738 } 8739 8740 static 8741 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8742 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8743 E = MBB->succ_end(); I != E; ++I) 8744 if (*I != Succ) 8745 return *I; 8746 llvm_unreachable("Expecting a BB with two successors!"); 8747 } 8748 8749 /// Return the load opcode for a given load size. If load size >= 8, 8750 /// neon opcode will be returned. 8751 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8752 if (LdSize >= 8) 8753 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8754 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8755 if (IsThumb1) 8756 return LdSize == 4 ? ARM::tLDRi 8757 : LdSize == 2 ? ARM::tLDRHi 8758 : LdSize == 1 ? ARM::tLDRBi : 0; 8759 if (IsThumb2) 8760 return LdSize == 4 ? ARM::t2LDR_POST 8761 : LdSize == 2 ? ARM::t2LDRH_POST 8762 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8763 return LdSize == 4 ? ARM::LDR_POST_IMM 8764 : LdSize == 2 ? ARM::LDRH_POST 8765 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8766 } 8767 8768 /// Return the store opcode for a given store size. If store size >= 8, 8769 /// neon opcode will be returned. 8770 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8771 if (StSize >= 8) 8772 return StSize == 16 ? ARM::VST1q32wb_fixed 8773 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8774 if (IsThumb1) 8775 return StSize == 4 ? ARM::tSTRi 8776 : StSize == 2 ? ARM::tSTRHi 8777 : StSize == 1 ? ARM::tSTRBi : 0; 8778 if (IsThumb2) 8779 return StSize == 4 ? ARM::t2STR_POST 8780 : StSize == 2 ? ARM::t2STRH_POST 8781 : StSize == 1 ? ARM::t2STRB_POST : 0; 8782 return StSize == 4 ? ARM::STR_POST_IMM 8783 : StSize == 2 ? ARM::STRH_POST 8784 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8785 } 8786 8787 /// Emit a post-increment load operation with given size. The instructions 8788 /// will be added to BB at Pos. 8789 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8790 const TargetInstrInfo *TII, const DebugLoc &dl, 8791 unsigned LdSize, unsigned Data, unsigned AddrIn, 8792 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8793 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8794 assert(LdOpc != 0 && "Should have a load opcode"); 8795 if (LdSize >= 8) { 8796 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8797 .addReg(AddrOut, RegState::Define) 8798 .addReg(AddrIn) 8799 .addImm(0) 8800 .add(predOps(ARMCC::AL)); 8801 } else if (IsThumb1) { 8802 // load + update AddrIn 8803 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8804 .addReg(AddrIn) 8805 .addImm(0) 8806 .add(predOps(ARMCC::AL)); 8807 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8808 .add(t1CondCodeOp()) 8809 .addReg(AddrIn) 8810 .addImm(LdSize) 8811 .add(predOps(ARMCC::AL)); 8812 } else if (IsThumb2) { 8813 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8814 .addReg(AddrOut, RegState::Define) 8815 .addReg(AddrIn) 8816 .addImm(LdSize) 8817 .add(predOps(ARMCC::AL)); 8818 } else { // arm 8819 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8820 .addReg(AddrOut, RegState::Define) 8821 .addReg(AddrIn) 8822 .addReg(0) 8823 .addImm(LdSize) 8824 .add(predOps(ARMCC::AL)); 8825 } 8826 } 8827 8828 /// Emit a post-increment store operation with given size. The instructions 8829 /// will be added to BB at Pos. 8830 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8831 const TargetInstrInfo *TII, const DebugLoc &dl, 8832 unsigned StSize, unsigned Data, unsigned AddrIn, 8833 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8834 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8835 assert(StOpc != 0 && "Should have a store opcode"); 8836 if (StSize >= 8) { 8837 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8838 .addReg(AddrIn) 8839 .addImm(0) 8840 .addReg(Data) 8841 .add(predOps(ARMCC::AL)); 8842 } else if (IsThumb1) { 8843 // store + update AddrIn 8844 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8845 .addReg(Data) 8846 .addReg(AddrIn) 8847 .addImm(0) 8848 .add(predOps(ARMCC::AL)); 8849 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8850 .add(t1CondCodeOp()) 8851 .addReg(AddrIn) 8852 .addImm(StSize) 8853 .add(predOps(ARMCC::AL)); 8854 } else if (IsThumb2) { 8855 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8856 .addReg(Data) 8857 .addReg(AddrIn) 8858 .addImm(StSize) 8859 .add(predOps(ARMCC::AL)); 8860 } else { // arm 8861 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8862 .addReg(Data) 8863 .addReg(AddrIn) 8864 .addReg(0) 8865 .addImm(StSize) 8866 .add(predOps(ARMCC::AL)); 8867 } 8868 } 8869 8870 MachineBasicBlock * 8871 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8872 MachineBasicBlock *BB) const { 8873 // This pseudo instruction has 3 operands: dst, src, size 8874 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8875 // Otherwise, we will generate unrolled scalar copies. 8876 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8877 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8878 MachineFunction::iterator It = ++BB->getIterator(); 8879 8880 unsigned dest = MI.getOperand(0).getReg(); 8881 unsigned src = MI.getOperand(1).getReg(); 8882 unsigned SizeVal = MI.getOperand(2).getImm(); 8883 unsigned Align = MI.getOperand(3).getImm(); 8884 DebugLoc dl = MI.getDebugLoc(); 8885 8886 MachineFunction *MF = BB->getParent(); 8887 MachineRegisterInfo &MRI = MF->getRegInfo(); 8888 unsigned UnitSize = 0; 8889 const TargetRegisterClass *TRC = nullptr; 8890 const TargetRegisterClass *VecTRC = nullptr; 8891 8892 bool IsThumb1 = Subtarget->isThumb1Only(); 8893 bool IsThumb2 = Subtarget->isThumb2(); 8894 bool IsThumb = Subtarget->isThumb(); 8895 8896 if (Align & 1) { 8897 UnitSize = 1; 8898 } else if (Align & 2) { 8899 UnitSize = 2; 8900 } else { 8901 // Check whether we can use NEON instructions. 8902 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8903 Subtarget->hasNEON()) { 8904 if ((Align % 16 == 0) && SizeVal >= 16) 8905 UnitSize = 16; 8906 else if ((Align % 8 == 0) && SizeVal >= 8) 8907 UnitSize = 8; 8908 } 8909 // Can't use NEON instructions. 8910 if (UnitSize == 0) 8911 UnitSize = 4; 8912 } 8913 8914 // Select the correct opcode and register class for unit size load/store 8915 bool IsNeon = UnitSize >= 8; 8916 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8917 if (IsNeon) 8918 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8919 : UnitSize == 8 ? &ARM::DPRRegClass 8920 : nullptr; 8921 8922 unsigned BytesLeft = SizeVal % UnitSize; 8923 unsigned LoopSize = SizeVal - BytesLeft; 8924 8925 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8926 // Use LDR and STR to copy. 8927 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8928 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8929 unsigned srcIn = src; 8930 unsigned destIn = dest; 8931 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8932 unsigned srcOut = MRI.createVirtualRegister(TRC); 8933 unsigned destOut = MRI.createVirtualRegister(TRC); 8934 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8935 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8936 IsThumb1, IsThumb2); 8937 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8938 IsThumb1, IsThumb2); 8939 srcIn = srcOut; 8940 destIn = destOut; 8941 } 8942 8943 // Handle the leftover bytes with LDRB and STRB. 8944 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8945 // [destOut] = STRB_POST(scratch, destIn, 1) 8946 for (unsigned i = 0; i < BytesLeft; i++) { 8947 unsigned srcOut = MRI.createVirtualRegister(TRC); 8948 unsigned destOut = MRI.createVirtualRegister(TRC); 8949 unsigned scratch = MRI.createVirtualRegister(TRC); 8950 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8951 IsThumb1, IsThumb2); 8952 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8953 IsThumb1, IsThumb2); 8954 srcIn = srcOut; 8955 destIn = destOut; 8956 } 8957 MI.eraseFromParent(); // The instruction is gone now. 8958 return BB; 8959 } 8960 8961 // Expand the pseudo op to a loop. 8962 // thisMBB: 8963 // ... 8964 // movw varEnd, # --> with thumb2 8965 // movt varEnd, # 8966 // ldrcp varEnd, idx --> without thumb2 8967 // fallthrough --> loopMBB 8968 // loopMBB: 8969 // PHI varPhi, varEnd, varLoop 8970 // PHI srcPhi, src, srcLoop 8971 // PHI destPhi, dst, destLoop 8972 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8973 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8974 // subs varLoop, varPhi, #UnitSize 8975 // bne loopMBB 8976 // fallthrough --> exitMBB 8977 // exitMBB: 8978 // epilogue to handle left-over bytes 8979 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8980 // [destOut] = STRB_POST(scratch, destLoop, 1) 8981 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8982 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8983 MF->insert(It, loopMBB); 8984 MF->insert(It, exitMBB); 8985 8986 // Transfer the remainder of BB and its successor edges to exitMBB. 8987 exitMBB->splice(exitMBB->begin(), BB, 8988 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8989 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8990 8991 // Load an immediate to varEnd. 8992 unsigned varEnd = MRI.createVirtualRegister(TRC); 8993 if (Subtarget->useMovt()) { 8994 unsigned Vtmp = varEnd; 8995 if ((LoopSize & 0xFFFF0000) != 0) 8996 Vtmp = MRI.createVirtualRegister(TRC); 8997 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8998 .addImm(LoopSize & 0xFFFF) 8999 .add(predOps(ARMCC::AL)); 9000 9001 if ((LoopSize & 0xFFFF0000) != 0) 9002 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9003 .addReg(Vtmp) 9004 .addImm(LoopSize >> 16) 9005 .add(predOps(ARMCC::AL)); 9006 } else { 9007 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9008 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9009 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9010 9011 // MachineConstantPool wants an explicit alignment. 9012 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9013 if (Align == 0) 9014 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9015 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9016 MachineMemOperand *CPMMO = 9017 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9018 MachineMemOperand::MOLoad, 4, 4); 9019 9020 if (IsThumb) 9021 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9022 .addReg(varEnd, RegState::Define) 9023 .addConstantPoolIndex(Idx) 9024 .add(predOps(ARMCC::AL)) 9025 .addMemOperand(CPMMO); 9026 else 9027 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9028 .addReg(varEnd, RegState::Define) 9029 .addConstantPoolIndex(Idx) 9030 .addImm(0) 9031 .add(predOps(ARMCC::AL)) 9032 .addMemOperand(CPMMO); 9033 } 9034 BB->addSuccessor(loopMBB); 9035 9036 // Generate the loop body: 9037 // varPhi = PHI(varLoop, varEnd) 9038 // srcPhi = PHI(srcLoop, src) 9039 // destPhi = PHI(destLoop, dst) 9040 MachineBasicBlock *entryBB = BB; 9041 BB = loopMBB; 9042 unsigned varLoop = MRI.createVirtualRegister(TRC); 9043 unsigned varPhi = MRI.createVirtualRegister(TRC); 9044 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9045 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9046 unsigned destLoop = MRI.createVirtualRegister(TRC); 9047 unsigned destPhi = MRI.createVirtualRegister(TRC); 9048 9049 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9050 .addReg(varLoop).addMBB(loopMBB) 9051 .addReg(varEnd).addMBB(entryBB); 9052 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9053 .addReg(srcLoop).addMBB(loopMBB) 9054 .addReg(src).addMBB(entryBB); 9055 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9056 .addReg(destLoop).addMBB(loopMBB) 9057 .addReg(dest).addMBB(entryBB); 9058 9059 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9060 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9061 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9062 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9063 IsThumb1, IsThumb2); 9064 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9065 IsThumb1, IsThumb2); 9066 9067 // Decrement loop variable by UnitSize. 9068 if (IsThumb1) { 9069 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9070 .add(t1CondCodeOp()) 9071 .addReg(varPhi) 9072 .addImm(UnitSize) 9073 .add(predOps(ARMCC::AL)); 9074 } else { 9075 MachineInstrBuilder MIB = 9076 BuildMI(*BB, BB->end(), dl, 9077 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9078 MIB.addReg(varPhi) 9079 .addImm(UnitSize) 9080 .add(predOps(ARMCC::AL)) 9081 .add(condCodeOp()); 9082 MIB->getOperand(5).setReg(ARM::CPSR); 9083 MIB->getOperand(5).setIsDef(true); 9084 } 9085 BuildMI(*BB, BB->end(), dl, 9086 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9087 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9088 9089 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9090 BB->addSuccessor(loopMBB); 9091 BB->addSuccessor(exitMBB); 9092 9093 // Add epilogue to handle BytesLeft. 9094 BB = exitMBB; 9095 auto StartOfExit = exitMBB->begin(); 9096 9097 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9098 // [destOut] = STRB_POST(scratch, destLoop, 1) 9099 unsigned srcIn = srcLoop; 9100 unsigned destIn = destLoop; 9101 for (unsigned i = 0; i < BytesLeft; i++) { 9102 unsigned srcOut = MRI.createVirtualRegister(TRC); 9103 unsigned destOut = MRI.createVirtualRegister(TRC); 9104 unsigned scratch = MRI.createVirtualRegister(TRC); 9105 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9106 IsThumb1, IsThumb2); 9107 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9108 IsThumb1, IsThumb2); 9109 srcIn = srcOut; 9110 destIn = destOut; 9111 } 9112 9113 MI.eraseFromParent(); // The instruction is gone now. 9114 return BB; 9115 } 9116 9117 MachineBasicBlock * 9118 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9119 MachineBasicBlock *MBB) const { 9120 const TargetMachine &TM = getTargetMachine(); 9121 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9122 DebugLoc DL = MI.getDebugLoc(); 9123 9124 assert(Subtarget->isTargetWindows() && 9125 "__chkstk is only supported on Windows"); 9126 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9127 9128 // __chkstk takes the number of words to allocate on the stack in R4, and 9129 // returns the stack adjustment in number of bytes in R4. This will not 9130 // clober any other registers (other than the obvious lr). 9131 // 9132 // Although, technically, IP should be considered a register which may be 9133 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9134 // thumb-2 environment, so there is no interworking required. As a result, we 9135 // do not expect a veneer to be emitted by the linker, clobbering IP. 9136 // 9137 // Each module receives its own copy of __chkstk, so no import thunk is 9138 // required, again, ensuring that IP is not clobbered. 9139 // 9140 // Finally, although some linkers may theoretically provide a trampoline for 9141 // out of range calls (which is quite common due to a 32M range limitation of 9142 // branches for Thumb), we can generate the long-call version via 9143 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9144 // IP. 9145 9146 switch (TM.getCodeModel()) { 9147 case CodeModel::Tiny: 9148 llvm_unreachable("Tiny code model not available on ARM."); 9149 case CodeModel::Small: 9150 case CodeModel::Medium: 9151 case CodeModel::Kernel: 9152 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9153 .add(predOps(ARMCC::AL)) 9154 .addExternalSymbol("__chkstk") 9155 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9156 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9157 .addReg(ARM::R12, 9158 RegState::Implicit | RegState::Define | RegState::Dead) 9159 .addReg(ARM::CPSR, 9160 RegState::Implicit | RegState::Define | RegState::Dead); 9161 break; 9162 case CodeModel::Large: { 9163 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9164 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9165 9166 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9167 .addExternalSymbol("__chkstk"); 9168 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9169 .add(predOps(ARMCC::AL)) 9170 .addReg(Reg, RegState::Kill) 9171 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9172 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9173 .addReg(ARM::R12, 9174 RegState::Implicit | RegState::Define | RegState::Dead) 9175 .addReg(ARM::CPSR, 9176 RegState::Implicit | RegState::Define | RegState::Dead); 9177 break; 9178 } 9179 } 9180 9181 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9182 .addReg(ARM::SP, RegState::Kill) 9183 .addReg(ARM::R4, RegState::Kill) 9184 .setMIFlags(MachineInstr::FrameSetup) 9185 .add(predOps(ARMCC::AL)) 9186 .add(condCodeOp()); 9187 9188 MI.eraseFromParent(); 9189 return MBB; 9190 } 9191 9192 MachineBasicBlock * 9193 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9194 MachineBasicBlock *MBB) const { 9195 DebugLoc DL = MI.getDebugLoc(); 9196 MachineFunction *MF = MBB->getParent(); 9197 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9198 9199 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9200 MF->insert(++MBB->getIterator(), ContBB); 9201 ContBB->splice(ContBB->begin(), MBB, 9202 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9203 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9204 MBB->addSuccessor(ContBB); 9205 9206 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9207 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9208 MF->push_back(TrapBB); 9209 MBB->addSuccessor(TrapBB); 9210 9211 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9212 .addReg(MI.getOperand(0).getReg()) 9213 .addImm(0) 9214 .add(predOps(ARMCC::AL)); 9215 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9216 .addMBB(TrapBB) 9217 .addImm(ARMCC::EQ) 9218 .addReg(ARM::CPSR); 9219 9220 MI.eraseFromParent(); 9221 return ContBB; 9222 } 9223 9224 // The CPSR operand of SelectItr might be missing a kill marker 9225 // because there were multiple uses of CPSR, and ISel didn't know 9226 // which to mark. Figure out whether SelectItr should have had a 9227 // kill marker, and set it if it should. Returns the correct kill 9228 // marker value. 9229 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 9230 MachineBasicBlock* BB, 9231 const TargetRegisterInfo* TRI) { 9232 // Scan forward through BB for a use/def of CPSR. 9233 MachineBasicBlock::iterator miI(std::next(SelectItr)); 9234 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 9235 const MachineInstr& mi = *miI; 9236 if (mi.readsRegister(ARM::CPSR)) 9237 return false; 9238 if (mi.definesRegister(ARM::CPSR)) 9239 break; // Should have kill-flag - update below. 9240 } 9241 9242 // If we hit the end of the block, check whether CPSR is live into a 9243 // successor. 9244 if (miI == BB->end()) { 9245 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 9246 sEnd = BB->succ_end(); 9247 sItr != sEnd; ++sItr) { 9248 MachineBasicBlock* succ = *sItr; 9249 if (succ->isLiveIn(ARM::CPSR)) 9250 return false; 9251 } 9252 } 9253 9254 // We found a def, or hit the end of the basic block and CPSR wasn't live 9255 // out. SelectMI should have a kill flag on CPSR. 9256 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 9257 return true; 9258 } 9259 9260 MachineBasicBlock * 9261 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9262 MachineBasicBlock *BB) const { 9263 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9264 DebugLoc dl = MI.getDebugLoc(); 9265 bool isThumb2 = Subtarget->isThumb2(); 9266 switch (MI.getOpcode()) { 9267 default: { 9268 MI.print(errs()); 9269 llvm_unreachable("Unexpected instr type to insert"); 9270 } 9271 9272 // Thumb1 post-indexed loads are really just single-register LDMs. 9273 case ARM::tLDR_postidx: { 9274 MachineOperand Def(MI.getOperand(1)); 9275 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9276 .add(Def) // Rn_wb 9277 .add(MI.getOperand(2)) // Rn 9278 .add(MI.getOperand(3)) // PredImm 9279 .add(MI.getOperand(4)) // PredReg 9280 .add(MI.getOperand(0)) // Rt 9281 .cloneMemRefs(MI); 9282 MI.eraseFromParent(); 9283 return BB; 9284 } 9285 9286 // The Thumb2 pre-indexed stores have the same MI operands, they just 9287 // define them differently in the .td files from the isel patterns, so 9288 // they need pseudos. 9289 case ARM::t2STR_preidx: 9290 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9291 return BB; 9292 case ARM::t2STRB_preidx: 9293 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9294 return BB; 9295 case ARM::t2STRH_preidx: 9296 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9297 return BB; 9298 9299 case ARM::STRi_preidx: 9300 case ARM::STRBi_preidx: { 9301 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9302 : ARM::STRB_PRE_IMM; 9303 // Decode the offset. 9304 unsigned Offset = MI.getOperand(4).getImm(); 9305 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9306 Offset = ARM_AM::getAM2Offset(Offset); 9307 if (isSub) 9308 Offset = -Offset; 9309 9310 MachineMemOperand *MMO = *MI.memoperands_begin(); 9311 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9312 .add(MI.getOperand(0)) // Rn_wb 9313 .add(MI.getOperand(1)) // Rt 9314 .add(MI.getOperand(2)) // Rn 9315 .addImm(Offset) // offset (skip GPR==zero_reg) 9316 .add(MI.getOperand(5)) // pred 9317 .add(MI.getOperand(6)) 9318 .addMemOperand(MMO); 9319 MI.eraseFromParent(); 9320 return BB; 9321 } 9322 case ARM::STRr_preidx: 9323 case ARM::STRBr_preidx: 9324 case ARM::STRH_preidx: { 9325 unsigned NewOpc; 9326 switch (MI.getOpcode()) { 9327 default: llvm_unreachable("unexpected opcode!"); 9328 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9329 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9330 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9331 } 9332 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9333 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9334 MIB.add(MI.getOperand(i)); 9335 MI.eraseFromParent(); 9336 return BB; 9337 } 9338 9339 case ARM::tMOVCCr_pseudo: { 9340 // To "insert" a SELECT_CC instruction, we actually have to insert the 9341 // diamond control-flow pattern. The incoming instruction knows the 9342 // destination vreg to set, the condition code register to branch on, the 9343 // true/false values to select between, and a branch opcode to use. 9344 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9345 MachineFunction::iterator It = ++BB->getIterator(); 9346 9347 // thisMBB: 9348 // ... 9349 // TrueVal = ... 9350 // cmpTY ccX, r1, r2 9351 // bCC copy1MBB 9352 // fallthrough --> copy0MBB 9353 MachineBasicBlock *thisMBB = BB; 9354 MachineFunction *F = BB->getParent(); 9355 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9356 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9357 F->insert(It, copy0MBB); 9358 F->insert(It, sinkMBB); 9359 9360 // Check whether CPSR is live past the tMOVCCr_pseudo. 9361 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 9362 if (!MI.killsRegister(ARM::CPSR) && 9363 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 9364 copy0MBB->addLiveIn(ARM::CPSR); 9365 sinkMBB->addLiveIn(ARM::CPSR); 9366 } 9367 9368 // Transfer the remainder of BB and its successor edges to sinkMBB. 9369 sinkMBB->splice(sinkMBB->begin(), BB, 9370 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9371 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9372 9373 BB->addSuccessor(copy0MBB); 9374 BB->addSuccessor(sinkMBB); 9375 9376 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9377 .addMBB(sinkMBB) 9378 .addImm(MI.getOperand(3).getImm()) 9379 .addReg(MI.getOperand(4).getReg()); 9380 9381 // copy0MBB: 9382 // %FalseValue = ... 9383 // # fallthrough to sinkMBB 9384 BB = copy0MBB; 9385 9386 // Update machine-CFG edges 9387 BB->addSuccessor(sinkMBB); 9388 9389 // sinkMBB: 9390 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9391 // ... 9392 BB = sinkMBB; 9393 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9394 .addReg(MI.getOperand(1).getReg()) 9395 .addMBB(copy0MBB) 9396 .addReg(MI.getOperand(2).getReg()) 9397 .addMBB(thisMBB); 9398 9399 MI.eraseFromParent(); // The pseudo instruction is gone now. 9400 return BB; 9401 } 9402 9403 case ARM::BCCi64: 9404 case ARM::BCCZi64: { 9405 // If there is an unconditional branch to the other successor, remove it. 9406 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9407 9408 // Compare both parts that make up the double comparison separately for 9409 // equality. 9410 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9411 9412 unsigned LHS1 = MI.getOperand(1).getReg(); 9413 unsigned LHS2 = MI.getOperand(2).getReg(); 9414 if (RHSisZero) { 9415 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9416 .addReg(LHS1) 9417 .addImm(0) 9418 .add(predOps(ARMCC::AL)); 9419 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9420 .addReg(LHS2).addImm(0) 9421 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9422 } else { 9423 unsigned RHS1 = MI.getOperand(3).getReg(); 9424 unsigned RHS2 = MI.getOperand(4).getReg(); 9425 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9426 .addReg(LHS1) 9427 .addReg(RHS1) 9428 .add(predOps(ARMCC::AL)); 9429 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9430 .addReg(LHS2).addReg(RHS2) 9431 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9432 } 9433 9434 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9435 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9436 if (MI.getOperand(0).getImm() == ARMCC::NE) 9437 std::swap(destMBB, exitMBB); 9438 9439 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9440 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9441 if (isThumb2) 9442 BuildMI(BB, dl, TII->get(ARM::t2B)) 9443 .addMBB(exitMBB) 9444 .add(predOps(ARMCC::AL)); 9445 else 9446 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9447 9448 MI.eraseFromParent(); // The pseudo instruction is gone now. 9449 return BB; 9450 } 9451 9452 case ARM::Int_eh_sjlj_setjmp: 9453 case ARM::Int_eh_sjlj_setjmp_nofp: 9454 case ARM::tInt_eh_sjlj_setjmp: 9455 case ARM::t2Int_eh_sjlj_setjmp: 9456 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9457 return BB; 9458 9459 case ARM::Int_eh_sjlj_setup_dispatch: 9460 EmitSjLjDispatchBlock(MI, BB); 9461 return BB; 9462 9463 case ARM::ABS: 9464 case ARM::t2ABS: { 9465 // To insert an ABS instruction, we have to insert the 9466 // diamond control-flow pattern. The incoming instruction knows the 9467 // source vreg to test against 0, the destination vreg to set, 9468 // the condition code register to branch on, the 9469 // true/false values to select between, and a branch opcode to use. 9470 // It transforms 9471 // V1 = ABS V0 9472 // into 9473 // V2 = MOVS V0 9474 // BCC (branch to SinkBB if V0 >= 0) 9475 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9476 // SinkBB: V1 = PHI(V2, V3) 9477 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9478 MachineFunction::iterator BBI = ++BB->getIterator(); 9479 MachineFunction *Fn = BB->getParent(); 9480 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9481 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9482 Fn->insert(BBI, RSBBB); 9483 Fn->insert(BBI, SinkBB); 9484 9485 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9486 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9487 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9488 bool isThumb2 = Subtarget->isThumb2(); 9489 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9490 // In Thumb mode S must not be specified if source register is the SP or 9491 // PC and if destination register is the SP, so restrict register class 9492 unsigned NewRsbDstReg = 9493 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9494 9495 // Transfer the remainder of BB and its successor edges to sinkMBB. 9496 SinkBB->splice(SinkBB->begin(), BB, 9497 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9498 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9499 9500 BB->addSuccessor(RSBBB); 9501 BB->addSuccessor(SinkBB); 9502 9503 // fall through to SinkMBB 9504 RSBBB->addSuccessor(SinkBB); 9505 9506 // insert a cmp at the end of BB 9507 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9508 .addReg(ABSSrcReg) 9509 .addImm(0) 9510 .add(predOps(ARMCC::AL)); 9511 9512 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9513 BuildMI(BB, dl, 9514 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9515 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9516 9517 // insert rsbri in RSBBB 9518 // Note: BCC and rsbri will be converted into predicated rsbmi 9519 // by if-conversion pass 9520 BuildMI(*RSBBB, RSBBB->begin(), dl, 9521 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9522 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9523 .addImm(0) 9524 .add(predOps(ARMCC::AL)) 9525 .add(condCodeOp()); 9526 9527 // insert PHI in SinkBB, 9528 // reuse ABSDstReg to not change uses of ABS instruction 9529 BuildMI(*SinkBB, SinkBB->begin(), dl, 9530 TII->get(ARM::PHI), ABSDstReg) 9531 .addReg(NewRsbDstReg).addMBB(RSBBB) 9532 .addReg(ABSSrcReg).addMBB(BB); 9533 9534 // remove ABS instruction 9535 MI.eraseFromParent(); 9536 9537 // return last added BB 9538 return SinkBB; 9539 } 9540 case ARM::COPY_STRUCT_BYVAL_I32: 9541 ++NumLoopByVals; 9542 return EmitStructByval(MI, BB); 9543 case ARM::WIN__CHKSTK: 9544 return EmitLowered__chkstk(MI, BB); 9545 case ARM::WIN__DBZCHK: 9546 return EmitLowered__dbzchk(MI, BB); 9547 } 9548 } 9549 9550 /// Attaches vregs to MEMCPY that it will use as scratch registers 9551 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9552 /// instead of as a custom inserter because we need the use list from the SDNode. 9553 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9554 MachineInstr &MI, const SDNode *Node) { 9555 bool isThumb1 = Subtarget->isThumb1Only(); 9556 9557 DebugLoc DL = MI.getDebugLoc(); 9558 MachineFunction *MF = MI.getParent()->getParent(); 9559 MachineRegisterInfo &MRI = MF->getRegInfo(); 9560 MachineInstrBuilder MIB(*MF, MI); 9561 9562 // If the new dst/src is unused mark it as dead. 9563 if (!Node->hasAnyUseOfValue(0)) { 9564 MI.getOperand(0).setIsDead(true); 9565 } 9566 if (!Node->hasAnyUseOfValue(1)) { 9567 MI.getOperand(1).setIsDead(true); 9568 } 9569 9570 // The MEMCPY both defines and kills the scratch registers. 9571 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9572 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9573 : &ARM::GPRRegClass); 9574 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9575 } 9576 } 9577 9578 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9579 SDNode *Node) const { 9580 if (MI.getOpcode() == ARM::MEMCPY) { 9581 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9582 return; 9583 } 9584 9585 const MCInstrDesc *MCID = &MI.getDesc(); 9586 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9587 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9588 // operand is still set to noreg. If needed, set the optional operand's 9589 // register to CPSR, and remove the redundant implicit def. 9590 // 9591 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9592 9593 // Rename pseudo opcodes. 9594 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9595 unsigned ccOutIdx; 9596 if (NewOpc) { 9597 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9598 MCID = &TII->get(NewOpc); 9599 9600 assert(MCID->getNumOperands() == 9601 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9602 && "converted opcode should be the same except for cc_out" 9603 " (and, on Thumb1, pred)"); 9604 9605 MI.setDesc(*MCID); 9606 9607 // Add the optional cc_out operand 9608 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9609 9610 // On Thumb1, move all input operands to the end, then add the predicate 9611 if (Subtarget->isThumb1Only()) { 9612 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9613 MI.addOperand(MI.getOperand(1)); 9614 MI.RemoveOperand(1); 9615 } 9616 9617 // Restore the ties 9618 for (unsigned i = MI.getNumOperands(); i--;) { 9619 const MachineOperand& op = MI.getOperand(i); 9620 if (op.isReg() && op.isUse()) { 9621 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9622 if (DefIdx != -1) 9623 MI.tieOperands(DefIdx, i); 9624 } 9625 } 9626 9627 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9628 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9629 ccOutIdx = 1; 9630 } else 9631 ccOutIdx = MCID->getNumOperands() - 1; 9632 } else 9633 ccOutIdx = MCID->getNumOperands() - 1; 9634 9635 // Any ARM instruction that sets the 's' bit should specify an optional 9636 // "cc_out" operand in the last operand position. 9637 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9638 assert(!NewOpc && "Optional cc_out operand required"); 9639 return; 9640 } 9641 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9642 // since we already have an optional CPSR def. 9643 bool definesCPSR = false; 9644 bool deadCPSR = false; 9645 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9646 ++i) { 9647 const MachineOperand &MO = MI.getOperand(i); 9648 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9649 definesCPSR = true; 9650 if (MO.isDead()) 9651 deadCPSR = true; 9652 MI.RemoveOperand(i); 9653 break; 9654 } 9655 } 9656 if (!definesCPSR) { 9657 assert(!NewOpc && "Optional cc_out operand required"); 9658 return; 9659 } 9660 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9661 if (deadCPSR) { 9662 assert(!MI.getOperand(ccOutIdx).getReg() && 9663 "expect uninitialized optional cc_out operand"); 9664 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9665 if (!Subtarget->isThumb1Only()) 9666 return; 9667 } 9668 9669 // If this instruction was defined with an optional CPSR def and its dag node 9670 // had a live implicit CPSR def, then activate the optional CPSR def. 9671 MachineOperand &MO = MI.getOperand(ccOutIdx); 9672 MO.setReg(ARM::CPSR); 9673 MO.setIsDef(true); 9674 } 9675 9676 //===----------------------------------------------------------------------===// 9677 // ARM Optimization Hooks 9678 //===----------------------------------------------------------------------===// 9679 9680 // Helper function that checks if N is a null or all ones constant. 9681 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9682 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9683 } 9684 9685 // Return true if N is conditionally 0 or all ones. 9686 // Detects these expressions where cc is an i1 value: 9687 // 9688 // (select cc 0, y) [AllOnes=0] 9689 // (select cc y, 0) [AllOnes=0] 9690 // (zext cc) [AllOnes=0] 9691 // (sext cc) [AllOnes=0/1] 9692 // (select cc -1, y) [AllOnes=1] 9693 // (select cc y, -1) [AllOnes=1] 9694 // 9695 // Invert is set when N is the null/all ones constant when CC is false. 9696 // OtherOp is set to the alternative value of N. 9697 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9698 SDValue &CC, bool &Invert, 9699 SDValue &OtherOp, 9700 SelectionDAG &DAG) { 9701 switch (N->getOpcode()) { 9702 default: return false; 9703 case ISD::SELECT: { 9704 CC = N->getOperand(0); 9705 SDValue N1 = N->getOperand(1); 9706 SDValue N2 = N->getOperand(2); 9707 if (isZeroOrAllOnes(N1, AllOnes)) { 9708 Invert = false; 9709 OtherOp = N2; 9710 return true; 9711 } 9712 if (isZeroOrAllOnes(N2, AllOnes)) { 9713 Invert = true; 9714 OtherOp = N1; 9715 return true; 9716 } 9717 return false; 9718 } 9719 case ISD::ZERO_EXTEND: 9720 // (zext cc) can never be the all ones value. 9721 if (AllOnes) 9722 return false; 9723 LLVM_FALLTHROUGH; 9724 case ISD::SIGN_EXTEND: { 9725 SDLoc dl(N); 9726 EVT VT = N->getValueType(0); 9727 CC = N->getOperand(0); 9728 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9729 return false; 9730 Invert = !AllOnes; 9731 if (AllOnes) 9732 // When looking for an AllOnes constant, N is an sext, and the 'other' 9733 // value is 0. 9734 OtherOp = DAG.getConstant(0, dl, VT); 9735 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9736 // When looking for a 0 constant, N can be zext or sext. 9737 OtherOp = DAG.getConstant(1, dl, VT); 9738 else 9739 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9740 VT); 9741 return true; 9742 } 9743 } 9744 } 9745 9746 // Combine a constant select operand into its use: 9747 // 9748 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9749 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9750 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9751 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9752 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9753 // 9754 // The transform is rejected if the select doesn't have a constant operand that 9755 // is null, or all ones when AllOnes is set. 9756 // 9757 // Also recognize sext/zext from i1: 9758 // 9759 // (add (zext cc), x) -> (select cc (add x, 1), x) 9760 // (add (sext cc), x) -> (select cc (add x, -1), x) 9761 // 9762 // These transformations eventually create predicated instructions. 9763 // 9764 // @param N The node to transform. 9765 // @param Slct The N operand that is a select. 9766 // @param OtherOp The other N operand (x above). 9767 // @param DCI Context. 9768 // @param AllOnes Require the select constant to be all ones instead of null. 9769 // @returns The new node, or SDValue() on failure. 9770 static 9771 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9772 TargetLowering::DAGCombinerInfo &DCI, 9773 bool AllOnes = false) { 9774 SelectionDAG &DAG = DCI.DAG; 9775 EVT VT = N->getValueType(0); 9776 SDValue NonConstantVal; 9777 SDValue CCOp; 9778 bool SwapSelectOps; 9779 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9780 NonConstantVal, DAG)) 9781 return SDValue(); 9782 9783 // Slct is now know to be the desired identity constant when CC is true. 9784 SDValue TrueVal = OtherOp; 9785 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9786 OtherOp, NonConstantVal); 9787 // Unless SwapSelectOps says CC should be false. 9788 if (SwapSelectOps) 9789 std::swap(TrueVal, FalseVal); 9790 9791 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9792 CCOp, TrueVal, FalseVal); 9793 } 9794 9795 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9796 static 9797 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9798 TargetLowering::DAGCombinerInfo &DCI) { 9799 SDValue N0 = N->getOperand(0); 9800 SDValue N1 = N->getOperand(1); 9801 if (N0.getNode()->hasOneUse()) 9802 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9803 return Result; 9804 if (N1.getNode()->hasOneUse()) 9805 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9806 return Result; 9807 return SDValue(); 9808 } 9809 9810 static bool IsVUZPShuffleNode(SDNode *N) { 9811 // VUZP shuffle node. 9812 if (N->getOpcode() == ARMISD::VUZP) 9813 return true; 9814 9815 // "VUZP" on i32 is an alias for VTRN. 9816 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9817 return true; 9818 9819 return false; 9820 } 9821 9822 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9823 TargetLowering::DAGCombinerInfo &DCI, 9824 const ARMSubtarget *Subtarget) { 9825 // Look for ADD(VUZP.0, VUZP.1). 9826 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9827 N0 == N1) 9828 return SDValue(); 9829 9830 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9831 if (!N->getValueType(0).is64BitVector()) 9832 return SDValue(); 9833 9834 // Generate vpadd. 9835 SelectionDAG &DAG = DCI.DAG; 9836 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9837 SDLoc dl(N); 9838 SDNode *Unzip = N0.getNode(); 9839 EVT VT = N->getValueType(0); 9840 9841 SmallVector<SDValue, 8> Ops; 9842 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9843 TLI.getPointerTy(DAG.getDataLayout()))); 9844 Ops.push_back(Unzip->getOperand(0)); 9845 Ops.push_back(Unzip->getOperand(1)); 9846 9847 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9848 } 9849 9850 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9851 TargetLowering::DAGCombinerInfo &DCI, 9852 const ARMSubtarget *Subtarget) { 9853 // Check for two extended operands. 9854 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9855 N1.getOpcode() == ISD::SIGN_EXTEND) && 9856 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9857 N1.getOpcode() == ISD::ZERO_EXTEND)) 9858 return SDValue(); 9859 9860 SDValue N00 = N0.getOperand(0); 9861 SDValue N10 = N1.getOperand(0); 9862 9863 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9864 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9865 N00 == N10) 9866 return SDValue(); 9867 9868 // We only recognize Q register paddl here; this can't be reached until 9869 // after type legalization. 9870 if (!N00.getValueType().is64BitVector() || 9871 !N0.getValueType().is128BitVector()) 9872 return SDValue(); 9873 9874 // Generate vpaddl. 9875 SelectionDAG &DAG = DCI.DAG; 9876 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9877 SDLoc dl(N); 9878 EVT VT = N->getValueType(0); 9879 9880 SmallVector<SDValue, 8> Ops; 9881 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9882 unsigned Opcode; 9883 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9884 Opcode = Intrinsic::arm_neon_vpaddls; 9885 else 9886 Opcode = Intrinsic::arm_neon_vpaddlu; 9887 Ops.push_back(DAG.getConstant(Opcode, dl, 9888 TLI.getPointerTy(DAG.getDataLayout()))); 9889 EVT ElemTy = N00.getValueType().getVectorElementType(); 9890 unsigned NumElts = VT.getVectorNumElements(); 9891 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9892 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9893 N00.getOperand(0), N00.getOperand(1)); 9894 Ops.push_back(Concat); 9895 9896 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9897 } 9898 9899 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9900 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9901 // much easier to match. 9902 static SDValue 9903 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9904 TargetLowering::DAGCombinerInfo &DCI, 9905 const ARMSubtarget *Subtarget) { 9906 // Only perform optimization if after legalize, and if NEON is available. We 9907 // also expected both operands to be BUILD_VECTORs. 9908 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9909 || N0.getOpcode() != ISD::BUILD_VECTOR 9910 || N1.getOpcode() != ISD::BUILD_VECTOR) 9911 return SDValue(); 9912 9913 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9914 EVT VT = N->getValueType(0); 9915 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9916 return SDValue(); 9917 9918 // Check that the vector operands are of the right form. 9919 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9920 // operands, where N is the size of the formed vector. 9921 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9922 // index such that we have a pair wise add pattern. 9923 9924 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9925 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9926 return SDValue(); 9927 SDValue Vec = N0->getOperand(0)->getOperand(0); 9928 SDNode *V = Vec.getNode(); 9929 unsigned nextIndex = 0; 9930 9931 // For each operands to the ADD which are BUILD_VECTORs, 9932 // check to see if each of their operands are an EXTRACT_VECTOR with 9933 // the same vector and appropriate index. 9934 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9935 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9936 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9937 9938 SDValue ExtVec0 = N0->getOperand(i); 9939 SDValue ExtVec1 = N1->getOperand(i); 9940 9941 // First operand is the vector, verify its the same. 9942 if (V != ExtVec0->getOperand(0).getNode() || 9943 V != ExtVec1->getOperand(0).getNode()) 9944 return SDValue(); 9945 9946 // Second is the constant, verify its correct. 9947 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9948 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9949 9950 // For the constant, we want to see all the even or all the odd. 9951 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9952 || C1->getZExtValue() != nextIndex+1) 9953 return SDValue(); 9954 9955 // Increment index. 9956 nextIndex+=2; 9957 } else 9958 return SDValue(); 9959 } 9960 9961 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9962 // we're using the entire input vector, otherwise there's a size/legality 9963 // mismatch somewhere. 9964 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9965 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9966 return SDValue(); 9967 9968 // Create VPADDL node. 9969 SelectionDAG &DAG = DCI.DAG; 9970 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9971 9972 SDLoc dl(N); 9973 9974 // Build operand list. 9975 SmallVector<SDValue, 8> Ops; 9976 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9977 TLI.getPointerTy(DAG.getDataLayout()))); 9978 9979 // Input is the vector. 9980 Ops.push_back(Vec); 9981 9982 // Get widened type and narrowed type. 9983 MVT widenType; 9984 unsigned numElem = VT.getVectorNumElements(); 9985 9986 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9987 switch (inputLaneType.getSimpleVT().SimpleTy) { 9988 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9989 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9990 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9991 default: 9992 llvm_unreachable("Invalid vector element type for padd optimization."); 9993 } 9994 9995 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9996 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9997 return DAG.getNode(ExtOp, dl, VT, tmp); 9998 } 9999 10000 static SDValue findMUL_LOHI(SDValue V) { 10001 if (V->getOpcode() == ISD::UMUL_LOHI || 10002 V->getOpcode() == ISD::SMUL_LOHI) 10003 return V; 10004 return SDValue(); 10005 } 10006 10007 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 10008 TargetLowering::DAGCombinerInfo &DCI, 10009 const ARMSubtarget *Subtarget) { 10010 if (Subtarget->isThumb()) { 10011 if (!Subtarget->hasDSP()) 10012 return SDValue(); 10013 } else if (!Subtarget->hasV5TEOps()) 10014 return SDValue(); 10015 10016 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 10017 // accumulates the product into a 64-bit value. The 16-bit values will 10018 // be sign extended somehow or SRA'd into 32-bit values 10019 // (addc (adde (mul 16bit, 16bit), lo), hi) 10020 SDValue Mul = AddcNode->getOperand(0); 10021 SDValue Lo = AddcNode->getOperand(1); 10022 if (Mul.getOpcode() != ISD::MUL) { 10023 Lo = AddcNode->getOperand(0); 10024 Mul = AddcNode->getOperand(1); 10025 if (Mul.getOpcode() != ISD::MUL) 10026 return SDValue(); 10027 } 10028 10029 SDValue SRA = AddeNode->getOperand(0); 10030 SDValue Hi = AddeNode->getOperand(1); 10031 if (SRA.getOpcode() != ISD::SRA) { 10032 SRA = AddeNode->getOperand(1); 10033 Hi = AddeNode->getOperand(0); 10034 if (SRA.getOpcode() != ISD::SRA) 10035 return SDValue(); 10036 } 10037 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10038 if (Const->getZExtValue() != 31) 10039 return SDValue(); 10040 } else 10041 return SDValue(); 10042 10043 if (SRA.getOperand(0) != Mul) 10044 return SDValue(); 10045 10046 SelectionDAG &DAG = DCI.DAG; 10047 SDLoc dl(AddcNode); 10048 unsigned Opcode = 0; 10049 SDValue Op0; 10050 SDValue Op1; 10051 10052 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10053 Opcode = ARMISD::SMLALBB; 10054 Op0 = Mul.getOperand(0); 10055 Op1 = Mul.getOperand(1); 10056 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10057 Opcode = ARMISD::SMLALBT; 10058 Op0 = Mul.getOperand(0); 10059 Op1 = Mul.getOperand(1).getOperand(0); 10060 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10061 Opcode = ARMISD::SMLALTB; 10062 Op0 = Mul.getOperand(0).getOperand(0); 10063 Op1 = Mul.getOperand(1); 10064 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10065 Opcode = ARMISD::SMLALTT; 10066 Op0 = Mul->getOperand(0).getOperand(0); 10067 Op1 = Mul->getOperand(1).getOperand(0); 10068 } 10069 10070 if (!Op0 || !Op1) 10071 return SDValue(); 10072 10073 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10074 Op0, Op1, Lo, Hi); 10075 // Replace the ADDs' nodes uses by the MLA node's values. 10076 SDValue HiMLALResult(SMLAL.getNode(), 1); 10077 SDValue LoMLALResult(SMLAL.getNode(), 0); 10078 10079 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10080 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10081 10082 // Return original node to notify the driver to stop replacing. 10083 SDValue resNode(AddcNode, 0); 10084 return resNode; 10085 } 10086 10087 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10088 TargetLowering::DAGCombinerInfo &DCI, 10089 const ARMSubtarget *Subtarget) { 10090 // Look for multiply add opportunities. 10091 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10092 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10093 // a glue link from the first add to the second add. 10094 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10095 // a S/UMLAL instruction. 10096 // UMUL_LOHI 10097 // / :lo \ :hi 10098 // V \ [no multiline comment] 10099 // loAdd -> ADDC | 10100 // \ :carry / 10101 // V V 10102 // ADDE <- hiAdd 10103 // 10104 // In the special case where only the higher part of a signed result is used 10105 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10106 // a constant with the exact value of 0x80000000, we recognize we are dealing 10107 // with a "rounded multiply and add" (or subtract) and transform it into 10108 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10109 10110 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10111 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10112 "Expect an ADDE or SUBE"); 10113 10114 assert(AddeSubeNode->getNumOperands() == 3 && 10115 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10116 "ADDE node has the wrong inputs"); 10117 10118 // Check that we are chained to the right ADDC or SUBC node. 10119 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10120 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10121 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10122 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10123 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10124 return SDValue(); 10125 10126 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10127 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10128 10129 // Check if the two operands are from the same mul_lohi node. 10130 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10131 return SDValue(); 10132 10133 assert(AddcSubcNode->getNumValues() == 2 && 10134 AddcSubcNode->getValueType(0) == MVT::i32 && 10135 "Expect ADDC with two result values. First: i32"); 10136 10137 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10138 // maybe a SMLAL which multiplies two 16-bit values. 10139 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10140 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10141 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10142 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10143 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10144 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10145 10146 // Check for the triangle shape. 10147 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10148 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10149 10150 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10151 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10152 return SDValue(); 10153 10154 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10155 bool IsLeftOperandMUL = false; 10156 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10157 if (MULOp == SDValue()) 10158 MULOp = findMUL_LOHI(AddeSubeOp1); 10159 else 10160 IsLeftOperandMUL = true; 10161 if (MULOp == SDValue()) 10162 return SDValue(); 10163 10164 // Figure out the right opcode. 10165 unsigned Opc = MULOp->getOpcode(); 10166 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10167 10168 // Figure out the high and low input values to the MLAL node. 10169 SDValue *HiAddSub = nullptr; 10170 SDValue *LoMul = nullptr; 10171 SDValue *LowAddSub = nullptr; 10172 10173 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10174 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10175 return SDValue(); 10176 10177 if (IsLeftOperandMUL) 10178 HiAddSub = &AddeSubeOp1; 10179 else 10180 HiAddSub = &AddeSubeOp0; 10181 10182 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10183 // whose low result is fed to the ADDC/SUBC we are checking. 10184 10185 if (AddcSubcOp0 == MULOp.getValue(0)) { 10186 LoMul = &AddcSubcOp0; 10187 LowAddSub = &AddcSubcOp1; 10188 } 10189 if (AddcSubcOp1 == MULOp.getValue(0)) { 10190 LoMul = &AddcSubcOp1; 10191 LowAddSub = &AddcSubcOp0; 10192 } 10193 10194 if (!LoMul) 10195 return SDValue(); 10196 10197 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10198 // the replacement below will create a cycle. 10199 if (AddcSubcNode == HiAddSub->getNode() || 10200 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10201 return SDValue(); 10202 10203 // Create the merged node. 10204 SelectionDAG &DAG = DCI.DAG; 10205 10206 // Start building operand list. 10207 SmallVector<SDValue, 8> Ops; 10208 Ops.push_back(LoMul->getOperand(0)); 10209 Ops.push_back(LoMul->getOperand(1)); 10210 10211 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10212 // the case, we must be doing signed multiplication and only use the higher 10213 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10214 // addition or subtraction with the value of 0x800000. 10215 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10216 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10217 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10218 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10219 0x80000000) { 10220 Ops.push_back(*HiAddSub); 10221 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10222 FinalOpc = ARMISD::SMMLSR; 10223 } else { 10224 FinalOpc = ARMISD::SMMLAR; 10225 } 10226 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10227 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10228 10229 return SDValue(AddeSubeNode, 0); 10230 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10231 // SMMLS is generated during instruction selection and the rest of this 10232 // function can not handle the case where AddcSubcNode is a SUBC. 10233 return SDValue(); 10234 10235 // Finish building the operand list for {U/S}MLAL 10236 Ops.push_back(*LowAddSub); 10237 Ops.push_back(*HiAddSub); 10238 10239 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10240 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10241 10242 // Replace the ADDs' nodes uses by the MLA node's values. 10243 SDValue HiMLALResult(MLALNode.getNode(), 1); 10244 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10245 10246 SDValue LoMLALResult(MLALNode.getNode(), 0); 10247 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10248 10249 // Return original node to notify the driver to stop replacing. 10250 return SDValue(AddeSubeNode, 0); 10251 } 10252 10253 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10254 TargetLowering::DAGCombinerInfo &DCI, 10255 const ARMSubtarget *Subtarget) { 10256 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10257 // While trying to combine for the other MLAL nodes, first search for the 10258 // chance to use UMAAL. Check if Addc uses a node which has already 10259 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10260 // as the addend, and it's handled in PerformUMLALCombine. 10261 10262 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10263 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10264 10265 // Check that we have a glued ADDC node. 10266 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10267 if (AddcNode->getOpcode() != ARMISD::ADDC) 10268 return SDValue(); 10269 10270 // Find the converted UMAAL or quit if it doesn't exist. 10271 SDNode *UmlalNode = nullptr; 10272 SDValue AddHi; 10273 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10274 UmlalNode = AddcNode->getOperand(0).getNode(); 10275 AddHi = AddcNode->getOperand(1); 10276 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10277 UmlalNode = AddcNode->getOperand(1).getNode(); 10278 AddHi = AddcNode->getOperand(0); 10279 } else { 10280 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10281 } 10282 10283 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10284 // the ADDC as well as Zero. 10285 if (!isNullConstant(UmlalNode->getOperand(3))) 10286 return SDValue(); 10287 10288 if ((isNullConstant(AddeNode->getOperand(0)) && 10289 AddeNode->getOperand(1).getNode() == UmlalNode) || 10290 (AddeNode->getOperand(0).getNode() == UmlalNode && 10291 isNullConstant(AddeNode->getOperand(1)))) { 10292 SelectionDAG &DAG = DCI.DAG; 10293 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10294 UmlalNode->getOperand(2), AddHi }; 10295 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10296 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10297 10298 // Replace the ADDs' nodes uses by the UMAAL node's values. 10299 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10300 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10301 10302 // Return original node to notify the driver to stop replacing. 10303 return SDValue(AddeNode, 0); 10304 } 10305 return SDValue(); 10306 } 10307 10308 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10309 const ARMSubtarget *Subtarget) { 10310 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10311 return SDValue(); 10312 10313 // Check that we have a pair of ADDC and ADDE as operands. 10314 // Both addends of the ADDE must be zero. 10315 SDNode* AddcNode = N->getOperand(2).getNode(); 10316 SDNode* AddeNode = N->getOperand(3).getNode(); 10317 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10318 (AddeNode->getOpcode() == ARMISD::ADDE) && 10319 isNullConstant(AddeNode->getOperand(0)) && 10320 isNullConstant(AddeNode->getOperand(1)) && 10321 (AddeNode->getOperand(2).getNode() == AddcNode)) 10322 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10323 DAG.getVTList(MVT::i32, MVT::i32), 10324 {N->getOperand(0), N->getOperand(1), 10325 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10326 else 10327 return SDValue(); 10328 } 10329 10330 static SDValue PerformAddcSubcCombine(SDNode *N, 10331 TargetLowering::DAGCombinerInfo &DCI, 10332 const ARMSubtarget *Subtarget) { 10333 SelectionDAG &DAG(DCI.DAG); 10334 10335 if (N->getOpcode() == ARMISD::SUBC) { 10336 // (SUBC (ADDE 0, 0, C), 1) -> C 10337 SDValue LHS = N->getOperand(0); 10338 SDValue RHS = N->getOperand(1); 10339 if (LHS->getOpcode() == ARMISD::ADDE && 10340 isNullConstant(LHS->getOperand(0)) && 10341 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 10342 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10343 } 10344 } 10345 10346 if (Subtarget->isThumb1Only()) { 10347 SDValue RHS = N->getOperand(1); 10348 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10349 int32_t imm = C->getSExtValue(); 10350 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10351 SDLoc DL(N); 10352 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10353 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10354 : ARMISD::ADDC; 10355 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10356 } 10357 } 10358 } 10359 10360 return SDValue(); 10361 } 10362 10363 static SDValue PerformAddeSubeCombine(SDNode *N, 10364 TargetLowering::DAGCombinerInfo &DCI, 10365 const ARMSubtarget *Subtarget) { 10366 if (Subtarget->isThumb1Only()) { 10367 SelectionDAG &DAG = DCI.DAG; 10368 SDValue RHS = N->getOperand(1); 10369 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10370 int64_t imm = C->getSExtValue(); 10371 if (imm < 0) { 10372 SDLoc DL(N); 10373 10374 // The with-carry-in form matches bitwise not instead of the negation. 10375 // Effectively, the inverse interpretation of the carry flag already 10376 // accounts for part of the negation. 10377 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10378 10379 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10380 : ARMISD::ADDE; 10381 return DAG.getNode(Opcode, DL, N->getVTList(), 10382 N->getOperand(0), RHS, N->getOperand(2)); 10383 } 10384 } 10385 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10386 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10387 } 10388 return SDValue(); 10389 } 10390 10391 static SDValue PerformABSCombine(SDNode *N, 10392 TargetLowering::DAGCombinerInfo &DCI, 10393 const ARMSubtarget *Subtarget) { 10394 SDValue res; 10395 SelectionDAG &DAG = DCI.DAG; 10396 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10397 10398 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 10399 return SDValue(); 10400 10401 if (!TLI.expandABS(N, res, DAG)) 10402 return SDValue(); 10403 10404 return res; 10405 } 10406 10407 /// PerformADDECombine - Target-specific dag combine transform from 10408 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10409 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10410 static SDValue PerformADDECombine(SDNode *N, 10411 TargetLowering::DAGCombinerInfo &DCI, 10412 const ARMSubtarget *Subtarget) { 10413 // Only ARM and Thumb2 support UMLAL/SMLAL. 10414 if (Subtarget->isThumb1Only()) 10415 return PerformAddeSubeCombine(N, DCI, Subtarget); 10416 10417 // Only perform the checks after legalize when the pattern is available. 10418 if (DCI.isBeforeLegalize()) return SDValue(); 10419 10420 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10421 } 10422 10423 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10424 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10425 /// called with the default operands, and if that fails, with commuted 10426 /// operands. 10427 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10428 TargetLowering::DAGCombinerInfo &DCI, 10429 const ARMSubtarget *Subtarget){ 10430 // Attempt to create vpadd for this add. 10431 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10432 return Result; 10433 10434 // Attempt to create vpaddl for this add. 10435 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10436 return Result; 10437 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10438 Subtarget)) 10439 return Result; 10440 10441 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10442 if (N0.getNode()->hasOneUse()) 10443 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10444 return Result; 10445 return SDValue(); 10446 } 10447 10448 bool 10449 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 10450 CombineLevel Level) const { 10451 if (Level == BeforeLegalizeTypes) 10452 return true; 10453 10454 if (N->getOpcode() != ISD::SHL) 10455 return true; 10456 10457 if (Subtarget->isThumb1Only()) { 10458 // Avoid making expensive immediates by commuting shifts. (This logic 10459 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 10460 // for free.) 10461 if (N->getOpcode() != ISD::SHL) 10462 return true; 10463 SDValue N1 = N->getOperand(0); 10464 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 10465 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 10466 return true; 10467 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 10468 if (Const->getAPIntValue().ult(256)) 10469 return false; 10470 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 10471 Const->getAPIntValue().sgt(-256)) 10472 return false; 10473 } 10474 return true; 10475 } 10476 10477 // Turn off commute-with-shift transform after legalization, so it doesn't 10478 // conflict with PerformSHLSimplify. (We could try to detect when 10479 // PerformSHLSimplify would trigger more precisely, but it isn't 10480 // really necessary.) 10481 return false; 10482 } 10483 10484 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 10485 const SDNode *N, CombineLevel Level) const { 10486 if (!Subtarget->isThumb1Only()) 10487 return true; 10488 10489 if (Level == BeforeLegalizeTypes) 10490 return true; 10491 10492 return false; 10493 } 10494 10495 static SDValue PerformSHLSimplify(SDNode *N, 10496 TargetLowering::DAGCombinerInfo &DCI, 10497 const ARMSubtarget *ST) { 10498 // Allow the generic combiner to identify potential bswaps. 10499 if (DCI.isBeforeLegalize()) 10500 return SDValue(); 10501 10502 // DAG combiner will fold: 10503 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10504 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10505 // Other code patterns that can be also be modified have the following form: 10506 // b + ((a << 1) | 510) 10507 // b + ((a << 1) & 510) 10508 // b + ((a << 1) ^ 510) 10509 // b + ((a << 1) + 510) 10510 10511 // Many instructions can perform the shift for free, but it requires both 10512 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10513 // instruction will needed. So, unfold back to the original pattern if: 10514 // - if c1 and c2 are small enough that they don't require mov imms. 10515 // - the user(s) of the node can perform an shl 10516 10517 // No shifted operands for 16-bit instructions. 10518 if (ST->isThumb() && ST->isThumb1Only()) 10519 return SDValue(); 10520 10521 // Check that all the users could perform the shl themselves. 10522 for (auto U : N->uses()) { 10523 switch(U->getOpcode()) { 10524 default: 10525 return SDValue(); 10526 case ISD::SUB: 10527 case ISD::ADD: 10528 case ISD::AND: 10529 case ISD::OR: 10530 case ISD::XOR: 10531 case ISD::SETCC: 10532 case ARMISD::CMP: 10533 // Check that the user isn't already using a constant because there 10534 // aren't any instructions that support an immediate operand and a 10535 // shifted operand. 10536 if (isa<ConstantSDNode>(U->getOperand(0)) || 10537 isa<ConstantSDNode>(U->getOperand(1))) 10538 return SDValue(); 10539 10540 // Check that it's not already using a shift. 10541 if (U->getOperand(0).getOpcode() == ISD::SHL || 10542 U->getOperand(1).getOpcode() == ISD::SHL) 10543 return SDValue(); 10544 break; 10545 } 10546 } 10547 10548 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10549 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10550 return SDValue(); 10551 10552 if (N->getOperand(0).getOpcode() != ISD::SHL) 10553 return SDValue(); 10554 10555 SDValue SHL = N->getOperand(0); 10556 10557 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10558 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10559 if (!C1ShlC2 || !C2) 10560 return SDValue(); 10561 10562 APInt C2Int = C2->getAPIntValue(); 10563 APInt C1Int = C1ShlC2->getAPIntValue(); 10564 10565 // Check that performing a lshr will not lose any information. 10566 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10567 C2Int.getBitWidth() - C2->getZExtValue()); 10568 if ((C1Int & Mask) != C1Int) 10569 return SDValue(); 10570 10571 // Shift the first constant. 10572 C1Int.lshrInPlace(C2Int); 10573 10574 // The immediates are encoded as an 8-bit value that can be rotated. 10575 auto LargeImm = [](const APInt &Imm) { 10576 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 10577 return Imm.getBitWidth() - Zeros > 8; 10578 }; 10579 10580 if (LargeImm(C1Int) || LargeImm(C2Int)) 10581 return SDValue(); 10582 10583 SelectionDAG &DAG = DCI.DAG; 10584 SDLoc dl(N); 10585 SDValue X = SHL.getOperand(0); 10586 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10587 DAG.getConstant(C1Int, dl, MVT::i32)); 10588 // Shift left to compensate for the lshr of C1Int. 10589 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10590 10591 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 10592 SHL.dump(); N->dump()); 10593 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 10594 return Res; 10595 } 10596 10597 10598 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10599 /// 10600 static SDValue PerformADDCombine(SDNode *N, 10601 TargetLowering::DAGCombinerInfo &DCI, 10602 const ARMSubtarget *Subtarget) { 10603 SDValue N0 = N->getOperand(0); 10604 SDValue N1 = N->getOperand(1); 10605 10606 // Only works one way, because it needs an immediate operand. 10607 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10608 return Result; 10609 10610 // First try with the default operand order. 10611 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10612 return Result; 10613 10614 // If that didn't work, try again with the operands commuted. 10615 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10616 } 10617 10618 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10619 /// 10620 static SDValue PerformSUBCombine(SDNode *N, 10621 TargetLowering::DAGCombinerInfo &DCI) { 10622 SDValue N0 = N->getOperand(0); 10623 SDValue N1 = N->getOperand(1); 10624 10625 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10626 if (N1.getNode()->hasOneUse()) 10627 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10628 return Result; 10629 10630 return SDValue(); 10631 } 10632 10633 /// PerformVMULCombine 10634 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10635 /// special multiplier accumulator forwarding. 10636 /// vmul d3, d0, d2 10637 /// vmla d3, d1, d2 10638 /// is faster than 10639 /// vadd d3, d0, d1 10640 /// vmul d3, d3, d2 10641 // However, for (A + B) * (A + B), 10642 // vadd d2, d0, d1 10643 // vmul d3, d0, d2 10644 // vmla d3, d1, d2 10645 // is slower than 10646 // vadd d2, d0, d1 10647 // vmul d3, d2, d2 10648 static SDValue PerformVMULCombine(SDNode *N, 10649 TargetLowering::DAGCombinerInfo &DCI, 10650 const ARMSubtarget *Subtarget) { 10651 if (!Subtarget->hasVMLxForwarding()) 10652 return SDValue(); 10653 10654 SelectionDAG &DAG = DCI.DAG; 10655 SDValue N0 = N->getOperand(0); 10656 SDValue N1 = N->getOperand(1); 10657 unsigned Opcode = N0.getOpcode(); 10658 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10659 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10660 Opcode = N1.getOpcode(); 10661 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10662 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10663 return SDValue(); 10664 std::swap(N0, N1); 10665 } 10666 10667 if (N0 == N1) 10668 return SDValue(); 10669 10670 EVT VT = N->getValueType(0); 10671 SDLoc DL(N); 10672 SDValue N00 = N0->getOperand(0); 10673 SDValue N01 = N0->getOperand(1); 10674 return DAG.getNode(Opcode, DL, VT, 10675 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10676 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10677 } 10678 10679 static SDValue PerformMULCombine(SDNode *N, 10680 TargetLowering::DAGCombinerInfo &DCI, 10681 const ARMSubtarget *Subtarget) { 10682 SelectionDAG &DAG = DCI.DAG; 10683 10684 if (Subtarget->isThumb1Only()) 10685 return SDValue(); 10686 10687 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10688 return SDValue(); 10689 10690 EVT VT = N->getValueType(0); 10691 if (VT.is64BitVector() || VT.is128BitVector()) 10692 return PerformVMULCombine(N, DCI, Subtarget); 10693 if (VT != MVT::i32) 10694 return SDValue(); 10695 10696 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10697 if (!C) 10698 return SDValue(); 10699 10700 int64_t MulAmt = C->getSExtValue(); 10701 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10702 10703 ShiftAmt = ShiftAmt & (32 - 1); 10704 SDValue V = N->getOperand(0); 10705 SDLoc DL(N); 10706 10707 SDValue Res; 10708 MulAmt >>= ShiftAmt; 10709 10710 if (MulAmt >= 0) { 10711 if (isPowerOf2_32(MulAmt - 1)) { 10712 // (mul x, 2^N + 1) => (add (shl x, N), x) 10713 Res = DAG.getNode(ISD::ADD, DL, VT, 10714 V, 10715 DAG.getNode(ISD::SHL, DL, VT, 10716 V, 10717 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10718 MVT::i32))); 10719 } else if (isPowerOf2_32(MulAmt + 1)) { 10720 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10721 Res = DAG.getNode(ISD::SUB, DL, VT, 10722 DAG.getNode(ISD::SHL, DL, VT, 10723 V, 10724 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10725 MVT::i32)), 10726 V); 10727 } else 10728 return SDValue(); 10729 } else { 10730 uint64_t MulAmtAbs = -MulAmt; 10731 if (isPowerOf2_32(MulAmtAbs + 1)) { 10732 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10733 Res = DAG.getNode(ISD::SUB, DL, VT, 10734 V, 10735 DAG.getNode(ISD::SHL, DL, VT, 10736 V, 10737 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10738 MVT::i32))); 10739 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10740 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10741 Res = DAG.getNode(ISD::ADD, DL, VT, 10742 V, 10743 DAG.getNode(ISD::SHL, DL, VT, 10744 V, 10745 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10746 MVT::i32))); 10747 Res = DAG.getNode(ISD::SUB, DL, VT, 10748 DAG.getConstant(0, DL, MVT::i32), Res); 10749 } else 10750 return SDValue(); 10751 } 10752 10753 if (ShiftAmt != 0) 10754 Res = DAG.getNode(ISD::SHL, DL, VT, 10755 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10756 10757 // Do not add new nodes to DAG combiner worklist. 10758 DCI.CombineTo(N, Res, false); 10759 return SDValue(); 10760 } 10761 10762 static SDValue CombineANDShift(SDNode *N, 10763 TargetLowering::DAGCombinerInfo &DCI, 10764 const ARMSubtarget *Subtarget) { 10765 // Allow DAGCombine to pattern-match before we touch the canonical form. 10766 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10767 return SDValue(); 10768 10769 if (N->getValueType(0) != MVT::i32) 10770 return SDValue(); 10771 10772 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10773 if (!N1C) 10774 return SDValue(); 10775 10776 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 10777 // Don't transform uxtb/uxth. 10778 if (C1 == 255 || C1 == 65535) 10779 return SDValue(); 10780 10781 SDNode *N0 = N->getOperand(0).getNode(); 10782 if (!N0->hasOneUse()) 10783 return SDValue(); 10784 10785 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 10786 return SDValue(); 10787 10788 bool LeftShift = N0->getOpcode() == ISD::SHL; 10789 10790 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 10791 if (!N01C) 10792 return SDValue(); 10793 10794 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 10795 if (!C2 || C2 >= 32) 10796 return SDValue(); 10797 10798 // Clear irrelevant bits in the mask. 10799 if (LeftShift) 10800 C1 &= (-1U << C2); 10801 else 10802 C1 &= (-1U >> C2); 10803 10804 SelectionDAG &DAG = DCI.DAG; 10805 SDLoc DL(N); 10806 10807 // We have a pattern of the form "(and (shl x, c2) c1)" or 10808 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 10809 // transform to a pair of shifts, to save materializing c1. 10810 10811 // First pattern: right shift, then mask off leading bits. 10812 // FIXME: Use demanded bits? 10813 if (!LeftShift && isMask_32(C1)) { 10814 uint32_t C3 = countLeadingZeros(C1); 10815 if (C2 < C3) { 10816 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 10817 DAG.getConstant(C3 - C2, DL, MVT::i32)); 10818 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 10819 DAG.getConstant(C3, DL, MVT::i32)); 10820 } 10821 } 10822 10823 // First pattern, reversed: left shift, then mask off trailing bits. 10824 if (LeftShift && isMask_32(~C1)) { 10825 uint32_t C3 = countTrailingZeros(C1); 10826 if (C2 < C3) { 10827 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 10828 DAG.getConstant(C3 - C2, DL, MVT::i32)); 10829 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 10830 DAG.getConstant(C3, DL, MVT::i32)); 10831 } 10832 } 10833 10834 // Second pattern: left shift, then mask off leading bits. 10835 // FIXME: Use demanded bits? 10836 if (LeftShift && isShiftedMask_32(C1)) { 10837 uint32_t Trailing = countTrailingZeros(C1); 10838 uint32_t C3 = countLeadingZeros(C1); 10839 if (Trailing == C2 && C2 + C3 < 32) { 10840 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 10841 DAG.getConstant(C2 + C3, DL, MVT::i32)); 10842 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 10843 DAG.getConstant(C3, DL, MVT::i32)); 10844 } 10845 } 10846 10847 // Second pattern, reversed: right shift, then mask off trailing bits. 10848 // FIXME: Handle other patterns of known/demanded bits. 10849 if (!LeftShift && isShiftedMask_32(C1)) { 10850 uint32_t Leading = countLeadingZeros(C1); 10851 uint32_t C3 = countTrailingZeros(C1); 10852 if (Leading == C2 && C2 + C3 < 32) { 10853 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 10854 DAG.getConstant(C2 + C3, DL, MVT::i32)); 10855 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 10856 DAG.getConstant(C3, DL, MVT::i32)); 10857 } 10858 } 10859 10860 // FIXME: Transform "(and (shl x, c2) c1)" -> 10861 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 10862 // c1. 10863 return SDValue(); 10864 } 10865 10866 static SDValue PerformANDCombine(SDNode *N, 10867 TargetLowering::DAGCombinerInfo &DCI, 10868 const ARMSubtarget *Subtarget) { 10869 // Attempt to use immediate-form VBIC 10870 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10871 SDLoc dl(N); 10872 EVT VT = N->getValueType(0); 10873 SelectionDAG &DAG = DCI.DAG; 10874 10875 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10876 return SDValue(); 10877 10878 APInt SplatBits, SplatUndef; 10879 unsigned SplatBitSize; 10880 bool HasAnyUndefs; 10881 if (BVN && 10882 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10883 if (SplatBitSize <= 64) { 10884 EVT VbicVT; 10885 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10886 SplatUndef.getZExtValue(), SplatBitSize, 10887 DAG, dl, VbicVT, VT.is128BitVector(), 10888 OtherModImm); 10889 if (Val.getNode()) { 10890 SDValue Input = 10891 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10892 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10893 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10894 } 10895 } 10896 } 10897 10898 if (!Subtarget->isThumb1Only()) { 10899 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10900 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10901 return Result; 10902 10903 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10904 return Result; 10905 } 10906 10907 if (Subtarget->isThumb1Only()) 10908 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 10909 return Result; 10910 10911 return SDValue(); 10912 } 10913 10914 // Try combining OR nodes to SMULWB, SMULWT. 10915 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10916 TargetLowering::DAGCombinerInfo &DCI, 10917 const ARMSubtarget *Subtarget) { 10918 if (!Subtarget->hasV6Ops() || 10919 (Subtarget->isThumb() && 10920 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10921 return SDValue(); 10922 10923 SDValue SRL = OR->getOperand(0); 10924 SDValue SHL = OR->getOperand(1); 10925 10926 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10927 SRL = OR->getOperand(1); 10928 SHL = OR->getOperand(0); 10929 } 10930 if (!isSRL16(SRL) || !isSHL16(SHL)) 10931 return SDValue(); 10932 10933 // The first operands to the shifts need to be the two results from the 10934 // same smul_lohi node. 10935 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10936 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10937 return SDValue(); 10938 10939 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10940 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10941 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10942 return SDValue(); 10943 10944 // Now we have: 10945 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10946 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10947 // For SMUWB the 16-bit value will signed extended somehow. 10948 // For SMULWT only the SRA is required. 10949 // Check both sides of SMUL_LOHI 10950 SDValue OpS16 = SMULLOHI->getOperand(0); 10951 SDValue OpS32 = SMULLOHI->getOperand(1); 10952 10953 SelectionDAG &DAG = DCI.DAG; 10954 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10955 OpS16 = OpS32; 10956 OpS32 = SMULLOHI->getOperand(0); 10957 } 10958 10959 SDLoc dl(OR); 10960 unsigned Opcode = 0; 10961 if (isS16(OpS16, DAG)) 10962 Opcode = ARMISD::SMULWB; 10963 else if (isSRA16(OpS16)) { 10964 Opcode = ARMISD::SMULWT; 10965 OpS16 = OpS16->getOperand(0); 10966 } 10967 else 10968 return SDValue(); 10969 10970 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10971 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10972 return SDValue(OR, 0); 10973 } 10974 10975 static SDValue PerformORCombineToBFI(SDNode *N, 10976 TargetLowering::DAGCombinerInfo &DCI, 10977 const ARMSubtarget *Subtarget) { 10978 // BFI is only available on V6T2+ 10979 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10980 return SDValue(); 10981 10982 EVT VT = N->getValueType(0); 10983 SDValue N0 = N->getOperand(0); 10984 SDValue N1 = N->getOperand(1); 10985 SelectionDAG &DAG = DCI.DAG; 10986 SDLoc DL(N); 10987 // 1) or (and A, mask), val => ARMbfi A, val, mask 10988 // iff (val & mask) == val 10989 // 10990 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10991 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10992 // && mask == ~mask2 10993 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10994 // && ~mask == mask2 10995 // (i.e., copy a bitfield value into another bitfield of the same width) 10996 10997 if (VT != MVT::i32) 10998 return SDValue(); 10999 11000 SDValue N00 = N0.getOperand(0); 11001 11002 // The value and the mask need to be constants so we can verify this is 11003 // actually a bitfield set. If the mask is 0xffff, we can do better 11004 // via a movt instruction, so don't use BFI in that case. 11005 SDValue MaskOp = N0.getOperand(1); 11006 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 11007 if (!MaskC) 11008 return SDValue(); 11009 unsigned Mask = MaskC->getZExtValue(); 11010 if (Mask == 0xffff) 11011 return SDValue(); 11012 SDValue Res; 11013 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 11014 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11015 if (N1C) { 11016 unsigned Val = N1C->getZExtValue(); 11017 if ((Val & ~Mask) != Val) 11018 return SDValue(); 11019 11020 if (ARM::isBitFieldInvertedMask(Mask)) { 11021 Val >>= countTrailingZeros(~Mask); 11022 11023 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 11024 DAG.getConstant(Val, DL, MVT::i32), 11025 DAG.getConstant(Mask, DL, MVT::i32)); 11026 11027 DCI.CombineTo(N, Res, false); 11028 // Return value from the original node to inform the combiner than N is 11029 // now dead. 11030 return SDValue(N, 0); 11031 } 11032 } else if (N1.getOpcode() == ISD::AND) { 11033 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11034 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11035 if (!N11C) 11036 return SDValue(); 11037 unsigned Mask2 = N11C->getZExtValue(); 11038 11039 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 11040 // as is to match. 11041 if (ARM::isBitFieldInvertedMask(Mask) && 11042 (Mask == ~Mask2)) { 11043 // The pack halfword instruction works better for masks that fit it, 11044 // so use that when it's available. 11045 if (Subtarget->hasDSP() && 11046 (Mask == 0xffff || Mask == 0xffff0000)) 11047 return SDValue(); 11048 // 2a 11049 unsigned amt = countTrailingZeros(Mask2); 11050 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 11051 DAG.getConstant(amt, DL, MVT::i32)); 11052 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 11053 DAG.getConstant(Mask, DL, MVT::i32)); 11054 DCI.CombineTo(N, Res, false); 11055 // Return value from the original node to inform the combiner than N is 11056 // now dead. 11057 return SDValue(N, 0); 11058 } else if (ARM::isBitFieldInvertedMask(~Mask) && 11059 (~Mask == Mask2)) { 11060 // The pack halfword instruction works better for masks that fit it, 11061 // so use that when it's available. 11062 if (Subtarget->hasDSP() && 11063 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 11064 return SDValue(); 11065 // 2b 11066 unsigned lsb = countTrailingZeros(Mask); 11067 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 11068 DAG.getConstant(lsb, DL, MVT::i32)); 11069 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 11070 DAG.getConstant(Mask2, DL, MVT::i32)); 11071 DCI.CombineTo(N, Res, false); 11072 // Return value from the original node to inform the combiner than N is 11073 // now dead. 11074 return SDValue(N, 0); 11075 } 11076 } 11077 11078 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 11079 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 11080 ARM::isBitFieldInvertedMask(~Mask)) { 11081 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 11082 // where lsb(mask) == #shamt and masked bits of B are known zero. 11083 SDValue ShAmt = N00.getOperand(1); 11084 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 11085 unsigned LSB = countTrailingZeros(Mask); 11086 if (ShAmtC != LSB) 11087 return SDValue(); 11088 11089 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 11090 DAG.getConstant(~Mask, DL, MVT::i32)); 11091 11092 DCI.CombineTo(N, Res, false); 11093 // Return value from the original node to inform the combiner than N is 11094 // now dead. 11095 return SDValue(N, 0); 11096 } 11097 11098 return SDValue(); 11099 } 11100 11101 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 11102 static SDValue PerformORCombine(SDNode *N, 11103 TargetLowering::DAGCombinerInfo &DCI, 11104 const ARMSubtarget *Subtarget) { 11105 // Attempt to use immediate-form VORR 11106 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11107 SDLoc dl(N); 11108 EVT VT = N->getValueType(0); 11109 SelectionDAG &DAG = DCI.DAG; 11110 11111 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11112 return SDValue(); 11113 11114 APInt SplatBits, SplatUndef; 11115 unsigned SplatBitSize; 11116 bool HasAnyUndefs; 11117 if (BVN && Subtarget->hasNEON() && 11118 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11119 if (SplatBitSize <= 64) { 11120 EVT VorrVT; 11121 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 11122 SplatUndef.getZExtValue(), SplatBitSize, 11123 DAG, dl, VorrVT, VT.is128BitVector(), 11124 OtherModImm); 11125 if (Val.getNode()) { 11126 SDValue Input = 11127 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 11128 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 11129 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 11130 } 11131 } 11132 } 11133 11134 if (!Subtarget->isThumb1Only()) { 11135 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11136 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11137 return Result; 11138 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 11139 return Result; 11140 } 11141 11142 SDValue N0 = N->getOperand(0); 11143 SDValue N1 = N->getOperand(1); 11144 11145 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 11146 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 11147 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 11148 11149 // The code below optimizes (or (and X, Y), Z). 11150 // The AND operand needs to have a single user to make these optimizations 11151 // profitable. 11152 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 11153 return SDValue(); 11154 11155 APInt SplatUndef; 11156 unsigned SplatBitSize; 11157 bool HasAnyUndefs; 11158 11159 APInt SplatBits0, SplatBits1; 11160 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 11161 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 11162 // Ensure that the second operand of both ands are constants 11163 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 11164 HasAnyUndefs) && !HasAnyUndefs) { 11165 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 11166 HasAnyUndefs) && !HasAnyUndefs) { 11167 // Ensure that the bit width of the constants are the same and that 11168 // the splat arguments are logical inverses as per the pattern we 11169 // are trying to simplify. 11170 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 11171 SplatBits0 == ~SplatBits1) { 11172 // Canonicalize the vector type to make instruction selection 11173 // simpler. 11174 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 11175 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 11176 N0->getOperand(1), 11177 N0->getOperand(0), 11178 N1->getOperand(0)); 11179 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 11180 } 11181 } 11182 } 11183 } 11184 11185 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 11186 // reasonable. 11187 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 11188 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 11189 return Res; 11190 } 11191 11192 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11193 return Result; 11194 11195 return SDValue(); 11196 } 11197 11198 static SDValue PerformXORCombine(SDNode *N, 11199 TargetLowering::DAGCombinerInfo &DCI, 11200 const ARMSubtarget *Subtarget) { 11201 EVT VT = N->getValueType(0); 11202 SelectionDAG &DAG = DCI.DAG; 11203 11204 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11205 return SDValue(); 11206 11207 if (!Subtarget->isThumb1Only()) { 11208 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11209 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11210 return Result; 11211 11212 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11213 return Result; 11214 } 11215 11216 return SDValue(); 11217 } 11218 11219 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 11220 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 11221 // their position in "to" (Rd). 11222 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 11223 assert(N->getOpcode() == ARMISD::BFI); 11224 11225 SDValue From = N->getOperand(1); 11226 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 11227 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 11228 11229 // If the Base came from a SHR #C, we can deduce that it is really testing bit 11230 // #C in the base of the SHR. 11231 if (From->getOpcode() == ISD::SRL && 11232 isa<ConstantSDNode>(From->getOperand(1))) { 11233 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 11234 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 11235 FromMask <<= Shift.getLimitedValue(31); 11236 From = From->getOperand(0); 11237 } 11238 11239 return From; 11240 } 11241 11242 // If A and B contain one contiguous set of bits, does A | B == A . B? 11243 // 11244 // Neither A nor B must be zero. 11245 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11246 unsigned LastActiveBitInA = A.countTrailingZeros(); 11247 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11248 return LastActiveBitInA - 1 == FirstActiveBitInB; 11249 } 11250 11251 static SDValue FindBFIToCombineWith(SDNode *N) { 11252 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11253 // if one exists. 11254 APInt ToMask, FromMask; 11255 SDValue From = ParseBFI(N, ToMask, FromMask); 11256 SDValue To = N->getOperand(0); 11257 11258 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11259 // aren't compatible, but not if they set the same bit in their destination as 11260 // we do (or that of any BFI we're going to combine with). 11261 SDValue V = To; 11262 APInt CombinedToMask = ToMask; 11263 while (V.getOpcode() == ARMISD::BFI) { 11264 APInt NewToMask, NewFromMask; 11265 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11266 if (NewFrom != From) { 11267 // This BFI has a different base. Keep going. 11268 CombinedToMask |= NewToMask; 11269 V = V.getOperand(0); 11270 continue; 11271 } 11272 11273 // Do the written bits conflict with any we've seen so far? 11274 if ((NewToMask & CombinedToMask).getBoolValue()) 11275 // Conflicting bits - bail out because going further is unsafe. 11276 return SDValue(); 11277 11278 // Are the new bits contiguous when combined with the old bits? 11279 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11280 BitsProperlyConcatenate(FromMask, NewFromMask)) 11281 return V; 11282 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11283 BitsProperlyConcatenate(NewFromMask, FromMask)) 11284 return V; 11285 11286 // We've seen a write to some bits, so track it. 11287 CombinedToMask |= NewToMask; 11288 // Keep going... 11289 V = V.getOperand(0); 11290 } 11291 11292 return SDValue(); 11293 } 11294 11295 static SDValue PerformBFICombine(SDNode *N, 11296 TargetLowering::DAGCombinerInfo &DCI) { 11297 SDValue N1 = N->getOperand(1); 11298 if (N1.getOpcode() == ISD::AND) { 11299 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11300 // the bits being cleared by the AND are not demanded by the BFI. 11301 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11302 if (!N11C) 11303 return SDValue(); 11304 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11305 unsigned LSB = countTrailingZeros(~InvMask); 11306 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11307 assert(Width < 11308 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11309 "undefined behavior"); 11310 unsigned Mask = (1u << Width) - 1; 11311 unsigned Mask2 = N11C->getZExtValue(); 11312 if ((Mask & (~Mask2)) == 0) 11313 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11314 N->getOperand(0), N1.getOperand(0), 11315 N->getOperand(2)); 11316 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11317 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11318 // Keep track of any consecutive bits set that all come from the same base 11319 // value. We can combine these together into a single BFI. 11320 SDValue CombineBFI = FindBFIToCombineWith(N); 11321 if (CombineBFI == SDValue()) 11322 return SDValue(); 11323 11324 // We've found a BFI. 11325 APInt ToMask1, FromMask1; 11326 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11327 11328 APInt ToMask2, FromMask2; 11329 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11330 assert(From1 == From2); 11331 (void)From2; 11332 11333 // First, unlink CombineBFI. 11334 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11335 // Then create a new BFI, combining the two together. 11336 APInt NewFromMask = FromMask1 | FromMask2; 11337 APInt NewToMask = ToMask1 | ToMask2; 11338 11339 EVT VT = N->getValueType(0); 11340 SDLoc dl(N); 11341 11342 if (NewFromMask[0] == 0) 11343 From1 = DCI.DAG.getNode( 11344 ISD::SRL, dl, VT, From1, 11345 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11346 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11347 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11348 } 11349 return SDValue(); 11350 } 11351 11352 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11353 /// ARMISD::VMOVRRD. 11354 static SDValue PerformVMOVRRDCombine(SDNode *N, 11355 TargetLowering::DAGCombinerInfo &DCI, 11356 const ARMSubtarget *Subtarget) { 11357 // vmovrrd(vmovdrr x, y) -> x,y 11358 SDValue InDouble = N->getOperand(0); 11359 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 11360 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11361 11362 // vmovrrd(load f64) -> (load i32), (load i32) 11363 SDNode *InNode = InDouble.getNode(); 11364 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11365 InNode->getValueType(0) == MVT::f64 && 11366 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11367 !cast<LoadSDNode>(InNode)->isVolatile()) { 11368 // TODO: Should this be done for non-FrameIndex operands? 11369 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11370 11371 SelectionDAG &DAG = DCI.DAG; 11372 SDLoc DL(LD); 11373 SDValue BasePtr = LD->getBasePtr(); 11374 SDValue NewLD1 = 11375 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11376 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11377 11378 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11379 DAG.getConstant(4, DL, MVT::i32)); 11380 SDValue NewLD2 = DAG.getLoad( 11381 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 11382 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 11383 11384 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11385 if (DCI.DAG.getDataLayout().isBigEndian()) 11386 std::swap (NewLD1, NewLD2); 11387 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11388 return Result; 11389 } 11390 11391 return SDValue(); 11392 } 11393 11394 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11395 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11396 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11397 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11398 SDValue Op0 = N->getOperand(0); 11399 SDValue Op1 = N->getOperand(1); 11400 if (Op0.getOpcode() == ISD::BITCAST) 11401 Op0 = Op0.getOperand(0); 11402 if (Op1.getOpcode() == ISD::BITCAST) 11403 Op1 = Op1.getOperand(0); 11404 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11405 Op0.getNode() == Op1.getNode() && 11406 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11407 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11408 N->getValueType(0), Op0.getOperand(0)); 11409 return SDValue(); 11410 } 11411 11412 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11413 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11414 /// i64 vector to have f64 elements, since the value can then be loaded 11415 /// directly into a VFP register. 11416 static bool hasNormalLoadOperand(SDNode *N) { 11417 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11418 for (unsigned i = 0; i < NumElts; ++i) { 11419 SDNode *Elt = N->getOperand(i).getNode(); 11420 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11421 return true; 11422 } 11423 return false; 11424 } 11425 11426 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11427 /// ISD::BUILD_VECTOR. 11428 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11429 TargetLowering::DAGCombinerInfo &DCI, 11430 const ARMSubtarget *Subtarget) { 11431 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11432 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11433 // into a pair of GPRs, which is fine when the value is used as a scalar, 11434 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11435 SelectionDAG &DAG = DCI.DAG; 11436 if (N->getNumOperands() == 2) 11437 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11438 return RV; 11439 11440 // Load i64 elements as f64 values so that type legalization does not split 11441 // them up into i32 values. 11442 EVT VT = N->getValueType(0); 11443 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11444 return SDValue(); 11445 SDLoc dl(N); 11446 SmallVector<SDValue, 8> Ops; 11447 unsigned NumElts = VT.getVectorNumElements(); 11448 for (unsigned i = 0; i < NumElts; ++i) { 11449 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11450 Ops.push_back(V); 11451 // Make the DAGCombiner fold the bitcast. 11452 DCI.AddToWorklist(V.getNode()); 11453 } 11454 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11455 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11456 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11457 } 11458 11459 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11460 static SDValue 11461 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11462 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11463 // At that time, we may have inserted bitcasts from integer to float. 11464 // If these bitcasts have survived DAGCombine, change the lowering of this 11465 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11466 // force to use floating point types. 11467 11468 // Make sure we can change the type of the vector. 11469 // This is possible iff: 11470 // 1. The vector is only used in a bitcast to a integer type. I.e., 11471 // 1.1. Vector is used only once. 11472 // 1.2. Use is a bit convert to an integer type. 11473 // 2. The size of its operands are 32-bits (64-bits are not legal). 11474 EVT VT = N->getValueType(0); 11475 EVT EltVT = VT.getVectorElementType(); 11476 11477 // Check 1.1. and 2. 11478 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11479 return SDValue(); 11480 11481 // By construction, the input type must be float. 11482 assert(EltVT == MVT::f32 && "Unexpected type!"); 11483 11484 // Check 1.2. 11485 SDNode *Use = *N->use_begin(); 11486 if (Use->getOpcode() != ISD::BITCAST || 11487 Use->getValueType(0).isFloatingPoint()) 11488 return SDValue(); 11489 11490 // Check profitability. 11491 // Model is, if more than half of the relevant operands are bitcast from 11492 // i32, turn the build_vector into a sequence of insert_vector_elt. 11493 // Relevant operands are everything that is not statically 11494 // (i.e., at compile time) bitcasted. 11495 unsigned NumOfBitCastedElts = 0; 11496 unsigned NumElts = VT.getVectorNumElements(); 11497 unsigned NumOfRelevantElts = NumElts; 11498 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11499 SDValue Elt = N->getOperand(Idx); 11500 if (Elt->getOpcode() == ISD::BITCAST) { 11501 // Assume only bit cast to i32 will go away. 11502 if (Elt->getOperand(0).getValueType() == MVT::i32) 11503 ++NumOfBitCastedElts; 11504 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11505 // Constants are statically casted, thus do not count them as 11506 // relevant operands. 11507 --NumOfRelevantElts; 11508 } 11509 11510 // Check if more than half of the elements require a non-free bitcast. 11511 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11512 return SDValue(); 11513 11514 SelectionDAG &DAG = DCI.DAG; 11515 // Create the new vector type. 11516 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11517 // Check if the type is legal. 11518 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11519 if (!TLI.isTypeLegal(VecVT)) 11520 return SDValue(); 11521 11522 // Combine: 11523 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11524 // => BITCAST INSERT_VECTOR_ELT 11525 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11526 // (BITCAST EN), N. 11527 SDValue Vec = DAG.getUNDEF(VecVT); 11528 SDLoc dl(N); 11529 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11530 SDValue V = N->getOperand(Idx); 11531 if (V.isUndef()) 11532 continue; 11533 if (V.getOpcode() == ISD::BITCAST && 11534 V->getOperand(0).getValueType() == MVT::i32) 11535 // Fold obvious case. 11536 V = V.getOperand(0); 11537 else { 11538 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11539 // Make the DAGCombiner fold the bitcasts. 11540 DCI.AddToWorklist(V.getNode()); 11541 } 11542 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11543 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11544 } 11545 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11546 // Make the DAGCombiner fold the bitcasts. 11547 DCI.AddToWorklist(Vec.getNode()); 11548 return Vec; 11549 } 11550 11551 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11552 /// ISD::INSERT_VECTOR_ELT. 11553 static SDValue PerformInsertEltCombine(SDNode *N, 11554 TargetLowering::DAGCombinerInfo &DCI) { 11555 // Bitcast an i64 load inserted into a vector to f64. 11556 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11557 EVT VT = N->getValueType(0); 11558 SDNode *Elt = N->getOperand(1).getNode(); 11559 if (VT.getVectorElementType() != MVT::i64 || 11560 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11561 return SDValue(); 11562 11563 SelectionDAG &DAG = DCI.DAG; 11564 SDLoc dl(N); 11565 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11566 VT.getVectorNumElements()); 11567 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11568 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11569 // Make the DAGCombiner fold the bitcasts. 11570 DCI.AddToWorklist(Vec.getNode()); 11571 DCI.AddToWorklist(V.getNode()); 11572 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11573 Vec, V, N->getOperand(2)); 11574 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11575 } 11576 11577 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11578 /// ISD::VECTOR_SHUFFLE. 11579 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11580 // The LLVM shufflevector instruction does not require the shuffle mask 11581 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11582 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11583 // operands do not match the mask length, they are extended by concatenating 11584 // them with undef vectors. That is probably the right thing for other 11585 // targets, but for NEON it is better to concatenate two double-register 11586 // size vector operands into a single quad-register size vector. Do that 11587 // transformation here: 11588 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11589 // shuffle(concat(v1, v2), undef) 11590 SDValue Op0 = N->getOperand(0); 11591 SDValue Op1 = N->getOperand(1); 11592 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11593 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11594 Op0.getNumOperands() != 2 || 11595 Op1.getNumOperands() != 2) 11596 return SDValue(); 11597 SDValue Concat0Op1 = Op0.getOperand(1); 11598 SDValue Concat1Op1 = Op1.getOperand(1); 11599 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11600 return SDValue(); 11601 // Skip the transformation if any of the types are illegal. 11602 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11603 EVT VT = N->getValueType(0); 11604 if (!TLI.isTypeLegal(VT) || 11605 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11606 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11607 return SDValue(); 11608 11609 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11610 Op0.getOperand(0), Op1.getOperand(0)); 11611 // Translate the shuffle mask. 11612 SmallVector<int, 16> NewMask; 11613 unsigned NumElts = VT.getVectorNumElements(); 11614 unsigned HalfElts = NumElts/2; 11615 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11616 for (unsigned n = 0; n < NumElts; ++n) { 11617 int MaskElt = SVN->getMaskElt(n); 11618 int NewElt = -1; 11619 if (MaskElt < (int)HalfElts) 11620 NewElt = MaskElt; 11621 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11622 NewElt = HalfElts + MaskElt - NumElts; 11623 NewMask.push_back(NewElt); 11624 } 11625 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11626 DAG.getUNDEF(VT), NewMask); 11627 } 11628 11629 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11630 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11631 /// base address updates. 11632 /// For generic load/stores, the memory type is assumed to be a vector. 11633 /// The caller is assumed to have checked legality. 11634 static SDValue CombineBaseUpdate(SDNode *N, 11635 TargetLowering::DAGCombinerInfo &DCI) { 11636 SelectionDAG &DAG = DCI.DAG; 11637 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11638 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11639 const bool isStore = N->getOpcode() == ISD::STORE; 11640 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11641 SDValue Addr = N->getOperand(AddrOpIdx); 11642 MemSDNode *MemN = cast<MemSDNode>(N); 11643 SDLoc dl(N); 11644 11645 // Search for a use of the address operand that is an increment. 11646 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11647 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11648 SDNode *User = *UI; 11649 if (User->getOpcode() != ISD::ADD || 11650 UI.getUse().getResNo() != Addr.getResNo()) 11651 continue; 11652 11653 // Check that the add is independent of the load/store. Otherwise, folding 11654 // it would create a cycle. We can avoid searching through Addr as it's a 11655 // predecessor to both. 11656 SmallPtrSet<const SDNode *, 32> Visited; 11657 SmallVector<const SDNode *, 16> Worklist; 11658 Visited.insert(Addr.getNode()); 11659 Worklist.push_back(N); 11660 Worklist.push_back(User); 11661 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 11662 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 11663 continue; 11664 11665 // Find the new opcode for the updating load/store. 11666 bool isLoadOp = true; 11667 bool isLaneOp = false; 11668 unsigned NewOpc = 0; 11669 unsigned NumVecs = 0; 11670 if (isIntrinsic) { 11671 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11672 switch (IntNo) { 11673 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11674 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11675 NumVecs = 1; break; 11676 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11677 NumVecs = 2; break; 11678 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11679 NumVecs = 3; break; 11680 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11681 NumVecs = 4; break; 11682 case Intrinsic::arm_neon_vld2dup: 11683 case Intrinsic::arm_neon_vld3dup: 11684 case Intrinsic::arm_neon_vld4dup: 11685 // TODO: Support updating VLDxDUP nodes. For now, we just skip 11686 // combining base updates for such intrinsics. 11687 continue; 11688 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11689 NumVecs = 2; isLaneOp = true; break; 11690 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11691 NumVecs = 3; isLaneOp = true; break; 11692 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11693 NumVecs = 4; isLaneOp = true; break; 11694 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11695 NumVecs = 1; isLoadOp = false; break; 11696 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11697 NumVecs = 2; isLoadOp = false; break; 11698 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11699 NumVecs = 3; isLoadOp = false; break; 11700 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11701 NumVecs = 4; isLoadOp = false; break; 11702 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11703 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11704 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11705 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11706 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11707 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11708 } 11709 } else { 11710 isLaneOp = true; 11711 switch (N->getOpcode()) { 11712 default: llvm_unreachable("unexpected opcode for Neon base update"); 11713 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11714 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11715 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11716 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11717 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11718 NumVecs = 1; isLaneOp = false; break; 11719 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11720 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11721 } 11722 } 11723 11724 // Find the size of memory referenced by the load/store. 11725 EVT VecTy; 11726 if (isLoadOp) { 11727 VecTy = N->getValueType(0); 11728 } else if (isIntrinsic) { 11729 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11730 } else { 11731 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11732 VecTy = N->getOperand(1).getValueType(); 11733 } 11734 11735 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11736 if (isLaneOp) 11737 NumBytes /= VecTy.getVectorNumElements(); 11738 11739 // If the increment is a constant, it must match the memory ref size. 11740 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11741 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11742 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11743 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11744 // separate instructions that make it harder to use a non-constant update. 11745 continue; 11746 } 11747 11748 // OK, we found an ADD we can fold into the base update. 11749 // Now, create a _UPD node, taking care of not breaking alignment. 11750 11751 EVT AlignedVecTy = VecTy; 11752 unsigned Alignment = MemN->getAlignment(); 11753 11754 // If this is a less-than-standard-aligned load/store, change the type to 11755 // match the standard alignment. 11756 // The alignment is overlooked when selecting _UPD variants; and it's 11757 // easier to introduce bitcasts here than fix that. 11758 // There are 3 ways to get to this base-update combine: 11759 // - intrinsics: they are assumed to be properly aligned (to the standard 11760 // alignment of the memory type), so we don't need to do anything. 11761 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11762 // intrinsics, so, likewise, there's nothing to do. 11763 // - generic load/store instructions: the alignment is specified as an 11764 // explicit operand, rather than implicitly as the standard alignment 11765 // of the memory type (like the intrisics). We need to change the 11766 // memory type to match the explicit alignment. That way, we don't 11767 // generate non-standard-aligned ARMISD::VLDx nodes. 11768 if (isa<LSBaseSDNode>(N)) { 11769 if (Alignment == 0) 11770 Alignment = 1; 11771 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11772 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11773 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11774 assert(!isLaneOp && "Unexpected generic load/store lane."); 11775 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11776 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11777 } 11778 // Don't set an explicit alignment on regular load/stores that we want 11779 // to transform to VLD/VST 1_UPD nodes. 11780 // This matches the behavior of regular load/stores, which only get an 11781 // explicit alignment if the MMO alignment is larger than the standard 11782 // alignment of the memory type. 11783 // Intrinsics, however, always get an explicit alignment, set to the 11784 // alignment of the MMO. 11785 Alignment = 1; 11786 } 11787 11788 // Create the new updating load/store node. 11789 // First, create an SDVTList for the new updating node's results. 11790 EVT Tys[6]; 11791 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11792 unsigned n; 11793 for (n = 0; n < NumResultVecs; ++n) 11794 Tys[n] = AlignedVecTy; 11795 Tys[n++] = MVT::i32; 11796 Tys[n] = MVT::Other; 11797 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11798 11799 // Then, gather the new node's operands. 11800 SmallVector<SDValue, 8> Ops; 11801 Ops.push_back(N->getOperand(0)); // incoming chain 11802 Ops.push_back(N->getOperand(AddrOpIdx)); 11803 Ops.push_back(Inc); 11804 11805 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11806 // Try to match the intrinsic's signature 11807 Ops.push_back(StN->getValue()); 11808 } else { 11809 // Loads (and of course intrinsics) match the intrinsics' signature, 11810 // so just add all but the alignment operand. 11811 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11812 Ops.push_back(N->getOperand(i)); 11813 } 11814 11815 // For all node types, the alignment operand is always the last one. 11816 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11817 11818 // If this is a non-standard-aligned STORE, the penultimate operand is the 11819 // stored value. Bitcast it to the aligned type. 11820 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11821 SDValue &StVal = Ops[Ops.size()-2]; 11822 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11823 } 11824 11825 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11826 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11827 MemN->getMemOperand()); 11828 11829 // Update the uses. 11830 SmallVector<SDValue, 5> NewResults; 11831 for (unsigned i = 0; i < NumResultVecs; ++i) 11832 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11833 11834 // If this is an non-standard-aligned LOAD, the first result is the loaded 11835 // value. Bitcast it to the expected result type. 11836 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11837 SDValue &LdVal = NewResults[0]; 11838 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11839 } 11840 11841 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11842 DCI.CombineTo(N, NewResults); 11843 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11844 11845 break; 11846 } 11847 return SDValue(); 11848 } 11849 11850 static SDValue PerformVLDCombine(SDNode *N, 11851 TargetLowering::DAGCombinerInfo &DCI) { 11852 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11853 return SDValue(); 11854 11855 return CombineBaseUpdate(N, DCI); 11856 } 11857 11858 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11859 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11860 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11861 /// return true. 11862 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11863 SelectionDAG &DAG = DCI.DAG; 11864 EVT VT = N->getValueType(0); 11865 // vldN-dup instructions only support 64-bit vectors for N > 1. 11866 if (!VT.is64BitVector()) 11867 return false; 11868 11869 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11870 SDNode *VLD = N->getOperand(0).getNode(); 11871 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11872 return false; 11873 unsigned NumVecs = 0; 11874 unsigned NewOpc = 0; 11875 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11876 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11877 NumVecs = 2; 11878 NewOpc = ARMISD::VLD2DUP; 11879 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11880 NumVecs = 3; 11881 NewOpc = ARMISD::VLD3DUP; 11882 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11883 NumVecs = 4; 11884 NewOpc = ARMISD::VLD4DUP; 11885 } else { 11886 return false; 11887 } 11888 11889 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11890 // numbers match the load. 11891 unsigned VLDLaneNo = 11892 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11893 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11894 UI != UE; ++UI) { 11895 // Ignore uses of the chain result. 11896 if (UI.getUse().getResNo() == NumVecs) 11897 continue; 11898 SDNode *User = *UI; 11899 if (User->getOpcode() != ARMISD::VDUPLANE || 11900 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11901 return false; 11902 } 11903 11904 // Create the vldN-dup node. 11905 EVT Tys[5]; 11906 unsigned n; 11907 for (n = 0; n < NumVecs; ++n) 11908 Tys[n] = VT; 11909 Tys[n] = MVT::Other; 11910 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11911 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11912 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11913 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11914 Ops, VLDMemInt->getMemoryVT(), 11915 VLDMemInt->getMemOperand()); 11916 11917 // Update the uses. 11918 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11919 UI != UE; ++UI) { 11920 unsigned ResNo = UI.getUse().getResNo(); 11921 // Ignore uses of the chain result. 11922 if (ResNo == NumVecs) 11923 continue; 11924 SDNode *User = *UI; 11925 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11926 } 11927 11928 // Now the vldN-lane intrinsic is dead except for its chain result. 11929 // Update uses of the chain. 11930 std::vector<SDValue> VLDDupResults; 11931 for (unsigned n = 0; n < NumVecs; ++n) 11932 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11933 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11934 DCI.CombineTo(VLD, VLDDupResults); 11935 11936 return true; 11937 } 11938 11939 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11940 /// ARMISD::VDUPLANE. 11941 static SDValue PerformVDUPLANECombine(SDNode *N, 11942 TargetLowering::DAGCombinerInfo &DCI) { 11943 SDValue Op = N->getOperand(0); 11944 11945 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11946 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11947 if (CombineVLDDUP(N, DCI)) 11948 return SDValue(N, 0); 11949 11950 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11951 // redundant. Ignore bit_converts for now; element sizes are checked below. 11952 while (Op.getOpcode() == ISD::BITCAST) 11953 Op = Op.getOperand(0); 11954 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11955 return SDValue(); 11956 11957 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11958 unsigned EltSize = Op.getScalarValueSizeInBits(); 11959 // The canonical VMOV for a zero vector uses a 32-bit element size. 11960 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11961 unsigned EltBits; 11962 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11963 EltSize = 8; 11964 EVT VT = N->getValueType(0); 11965 if (EltSize > VT.getScalarSizeInBits()) 11966 return SDValue(); 11967 11968 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11969 } 11970 11971 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11972 static SDValue PerformVDUPCombine(SDNode *N, 11973 TargetLowering::DAGCombinerInfo &DCI) { 11974 SelectionDAG &DAG = DCI.DAG; 11975 SDValue Op = N->getOperand(0); 11976 11977 // Match VDUP(LOAD) -> VLD1DUP. 11978 // We match this pattern here rather than waiting for isel because the 11979 // transform is only legal for unindexed loads. 11980 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11981 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11982 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11983 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11984 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11985 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11986 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11987 Ops, LD->getMemoryVT(), 11988 LD->getMemOperand()); 11989 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11990 return VLDDup; 11991 } 11992 11993 return SDValue(); 11994 } 11995 11996 static SDValue PerformLOADCombine(SDNode *N, 11997 TargetLowering::DAGCombinerInfo &DCI) { 11998 EVT VT = N->getValueType(0); 11999 12000 // If this is a legal vector load, try to combine it into a VLD1_UPD. 12001 if (ISD::isNormalLoad(N) && VT.isVector() && 12002 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12003 return CombineBaseUpdate(N, DCI); 12004 12005 return SDValue(); 12006 } 12007 12008 /// PerformSTORECombine - Target-specific dag combine xforms for 12009 /// ISD::STORE. 12010 static SDValue PerformSTORECombine(SDNode *N, 12011 TargetLowering::DAGCombinerInfo &DCI) { 12012 StoreSDNode *St = cast<StoreSDNode>(N); 12013 if (St->isVolatile()) 12014 return SDValue(); 12015 12016 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 12017 // pack all of the elements in one place. Next, store to memory in fewer 12018 // chunks. 12019 SDValue StVal = St->getValue(); 12020 EVT VT = StVal.getValueType(); 12021 if (St->isTruncatingStore() && VT.isVector()) { 12022 SelectionDAG &DAG = DCI.DAG; 12023 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12024 EVT StVT = St->getMemoryVT(); 12025 unsigned NumElems = VT.getVectorNumElements(); 12026 assert(StVT != VT && "Cannot truncate to the same type"); 12027 unsigned FromEltSz = VT.getScalarSizeInBits(); 12028 unsigned ToEltSz = StVT.getScalarSizeInBits(); 12029 12030 // From, To sizes and ElemCount must be pow of two 12031 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 12032 12033 // We are going to use the original vector elt for storing. 12034 // Accumulated smaller vector elements must be a multiple of the store size. 12035 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 12036 12037 unsigned SizeRatio = FromEltSz / ToEltSz; 12038 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 12039 12040 // Create a type on which we perform the shuffle. 12041 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 12042 NumElems*SizeRatio); 12043 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 12044 12045 SDLoc DL(St); 12046 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 12047 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 12048 for (unsigned i = 0; i < NumElems; ++i) 12049 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 12050 ? (i + 1) * SizeRatio - 1 12051 : i * SizeRatio; 12052 12053 // Can't shuffle using an illegal type. 12054 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 12055 12056 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 12057 DAG.getUNDEF(WideVec.getValueType()), 12058 ShuffleVec); 12059 // At this point all of the data is stored at the bottom of the 12060 // register. We now need to save it to mem. 12061 12062 // Find the largest store unit 12063 MVT StoreType = MVT::i8; 12064 for (MVT Tp : MVT::integer_valuetypes()) { 12065 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 12066 StoreType = Tp; 12067 } 12068 // Didn't find a legal store type. 12069 if (!TLI.isTypeLegal(StoreType)) 12070 return SDValue(); 12071 12072 // Bitcast the original vector into a vector of store-size units 12073 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 12074 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 12075 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 12076 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 12077 SmallVector<SDValue, 8> Chains; 12078 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 12079 TLI.getPointerTy(DAG.getDataLayout())); 12080 SDValue BasePtr = St->getBasePtr(); 12081 12082 // Perform one or more big stores into memory. 12083 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 12084 for (unsigned I = 0; I < E; I++) { 12085 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 12086 StoreType, ShuffWide, 12087 DAG.getIntPtrConstant(I, DL)); 12088 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 12089 St->getPointerInfo(), St->getAlignment(), 12090 St->getMemOperand()->getFlags()); 12091 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 12092 Increment); 12093 Chains.push_back(Ch); 12094 } 12095 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 12096 } 12097 12098 if (!ISD::isNormalStore(St)) 12099 return SDValue(); 12100 12101 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 12102 // ARM stores of arguments in the same cache line. 12103 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 12104 StVal.getNode()->hasOneUse()) { 12105 SelectionDAG &DAG = DCI.DAG; 12106 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 12107 SDLoc DL(St); 12108 SDValue BasePtr = St->getBasePtr(); 12109 SDValue NewST1 = DAG.getStore( 12110 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 12111 BasePtr, St->getPointerInfo(), St->getAlignment(), 12112 St->getMemOperand()->getFlags()); 12113 12114 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12115 DAG.getConstant(4, DL, MVT::i32)); 12116 return DAG.getStore(NewST1.getValue(0), DL, 12117 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 12118 OffsetPtr, St->getPointerInfo(), 12119 std::min(4U, St->getAlignment() / 2), 12120 St->getMemOperand()->getFlags()); 12121 } 12122 12123 if (StVal.getValueType() == MVT::i64 && 12124 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12125 12126 // Bitcast an i64 store extracted from a vector to f64. 12127 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12128 SelectionDAG &DAG = DCI.DAG; 12129 SDLoc dl(StVal); 12130 SDValue IntVec = StVal.getOperand(0); 12131 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12132 IntVec.getValueType().getVectorNumElements()); 12133 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 12134 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 12135 Vec, StVal.getOperand(1)); 12136 dl = SDLoc(N); 12137 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 12138 // Make the DAGCombiner fold the bitcasts. 12139 DCI.AddToWorklist(Vec.getNode()); 12140 DCI.AddToWorklist(ExtElt.getNode()); 12141 DCI.AddToWorklist(V.getNode()); 12142 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 12143 St->getPointerInfo(), St->getAlignment(), 12144 St->getMemOperand()->getFlags(), St->getAAInfo()); 12145 } 12146 12147 // If this is a legal vector store, try to combine it into a VST1_UPD. 12148 if (ISD::isNormalStore(N) && VT.isVector() && 12149 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12150 return CombineBaseUpdate(N, DCI); 12151 12152 return SDValue(); 12153 } 12154 12155 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 12156 /// can replace combinations of VMUL and VCVT (floating-point to integer) 12157 /// when the VMUL has a constant operand that is a power of 2. 12158 /// 12159 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12160 /// vmul.f32 d16, d17, d16 12161 /// vcvt.s32.f32 d16, d16 12162 /// becomes: 12163 /// vcvt.s32.f32 d16, d16, #3 12164 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 12165 const ARMSubtarget *Subtarget) { 12166 if (!Subtarget->hasNEON()) 12167 return SDValue(); 12168 12169 SDValue Op = N->getOperand(0); 12170 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12171 Op.getOpcode() != ISD::FMUL) 12172 return SDValue(); 12173 12174 SDValue ConstVec = Op->getOperand(1); 12175 if (!isa<BuildVectorSDNode>(ConstVec)) 12176 return SDValue(); 12177 12178 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12179 uint32_t FloatBits = FloatTy.getSizeInBits(); 12180 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12181 uint32_t IntBits = IntTy.getSizeInBits(); 12182 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12183 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 12184 // These instructions only exist converting from f32 to i32. We can handle 12185 // smaller integers by generating an extra truncate, but larger ones would 12186 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 12187 // these intructions only support v2i32/v4i32 types. 12188 return SDValue(); 12189 } 12190 12191 BitVector UndefElements; 12192 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12193 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12194 if (C == -1 || C == 0 || C > 32) 12195 return SDValue(); 12196 12197 SDLoc dl(N); 12198 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 12199 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 12200 Intrinsic::arm_neon_vcvtfp2fxu; 12201 SDValue FixConv = DAG.getNode( 12202 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12203 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 12204 DAG.getConstant(C, dl, MVT::i32)); 12205 12206 if (IntBits < FloatBits) 12207 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 12208 12209 return FixConv; 12210 } 12211 12212 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 12213 /// can replace combinations of VCVT (integer to floating-point) and VDIV 12214 /// when the VDIV has a constant operand that is a power of 2. 12215 /// 12216 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12217 /// vcvt.f32.s32 d16, d16 12218 /// vdiv.f32 d16, d17, d16 12219 /// becomes: 12220 /// vcvt.f32.s32 d16, d16, #3 12221 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 12222 const ARMSubtarget *Subtarget) { 12223 if (!Subtarget->hasNEON()) 12224 return SDValue(); 12225 12226 SDValue Op = N->getOperand(0); 12227 unsigned OpOpcode = Op.getNode()->getOpcode(); 12228 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 12229 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 12230 return SDValue(); 12231 12232 SDValue ConstVec = N->getOperand(1); 12233 if (!isa<BuildVectorSDNode>(ConstVec)) 12234 return SDValue(); 12235 12236 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12237 uint32_t FloatBits = FloatTy.getSizeInBits(); 12238 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12239 uint32_t IntBits = IntTy.getSizeInBits(); 12240 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12241 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 12242 // These instructions only exist converting from i32 to f32. We can handle 12243 // smaller integers by generating an extra extend, but larger ones would 12244 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 12245 // these intructions only support v2i32/v4i32 types. 12246 return SDValue(); 12247 } 12248 12249 BitVector UndefElements; 12250 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12251 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12252 if (C == -1 || C == 0 || C > 32) 12253 return SDValue(); 12254 12255 SDLoc dl(N); 12256 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12257 SDValue ConvInput = Op.getOperand(0); 12258 if (IntBits < FloatBits) 12259 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12260 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12261 ConvInput); 12262 12263 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12264 Intrinsic::arm_neon_vcvtfxu2fp; 12265 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12266 Op.getValueType(), 12267 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12268 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12269 } 12270 12271 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 12272 /// operand of a vector shift operation, where all the elements of the 12273 /// build_vector must have the same constant integer value. 12274 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 12275 // Ignore bit_converts. 12276 while (Op.getOpcode() == ISD::BITCAST) 12277 Op = Op.getOperand(0); 12278 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 12279 APInt SplatBits, SplatUndef; 12280 unsigned SplatBitSize; 12281 bool HasAnyUndefs; 12282 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 12283 HasAnyUndefs, ElementBits) || 12284 SplatBitSize > ElementBits) 12285 return false; 12286 Cnt = SplatBits.getSExtValue(); 12287 return true; 12288 } 12289 12290 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 12291 /// operand of a vector shift left operation. That value must be in the range: 12292 /// 0 <= Value < ElementBits for a left shift; or 12293 /// 0 <= Value <= ElementBits for a long left shift. 12294 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 12295 assert(VT.isVector() && "vector shift count is not a vector type"); 12296 int64_t ElementBits = VT.getScalarSizeInBits(); 12297 if (! getVShiftImm(Op, ElementBits, Cnt)) 12298 return false; 12299 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 12300 } 12301 12302 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 12303 /// operand of a vector shift right operation. For a shift opcode, the value 12304 /// is positive, but for an intrinsic the value count must be negative. The 12305 /// absolute value must be in the range: 12306 /// 1 <= |Value| <= ElementBits for a right shift; or 12307 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 12308 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 12309 int64_t &Cnt) { 12310 assert(VT.isVector() && "vector shift count is not a vector type"); 12311 int64_t ElementBits = VT.getScalarSizeInBits(); 12312 if (! getVShiftImm(Op, ElementBits, Cnt)) 12313 return false; 12314 if (!isIntrinsic) 12315 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 12316 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 12317 Cnt = -Cnt; 12318 return true; 12319 } 12320 return false; 12321 } 12322 12323 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12324 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12325 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12326 switch (IntNo) { 12327 default: 12328 // Don't do anything for most intrinsics. 12329 break; 12330 12331 // Vector shifts: check for immediate versions and lower them. 12332 // Note: This is done during DAG combining instead of DAG legalizing because 12333 // the build_vectors for 64-bit vector element shift counts are generally 12334 // not legal, and it is hard to see their values after they get legalized to 12335 // loads from a constant pool. 12336 case Intrinsic::arm_neon_vshifts: 12337 case Intrinsic::arm_neon_vshiftu: 12338 case Intrinsic::arm_neon_vrshifts: 12339 case Intrinsic::arm_neon_vrshiftu: 12340 case Intrinsic::arm_neon_vrshiftn: 12341 case Intrinsic::arm_neon_vqshifts: 12342 case Intrinsic::arm_neon_vqshiftu: 12343 case Intrinsic::arm_neon_vqshiftsu: 12344 case Intrinsic::arm_neon_vqshiftns: 12345 case Intrinsic::arm_neon_vqshiftnu: 12346 case Intrinsic::arm_neon_vqshiftnsu: 12347 case Intrinsic::arm_neon_vqrshiftns: 12348 case Intrinsic::arm_neon_vqrshiftnu: 12349 case Intrinsic::arm_neon_vqrshiftnsu: { 12350 EVT VT = N->getOperand(1).getValueType(); 12351 int64_t Cnt; 12352 unsigned VShiftOpc = 0; 12353 12354 switch (IntNo) { 12355 case Intrinsic::arm_neon_vshifts: 12356 case Intrinsic::arm_neon_vshiftu: 12357 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12358 VShiftOpc = ARMISD::VSHL; 12359 break; 12360 } 12361 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12362 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 12363 ARMISD::VSHRs : ARMISD::VSHRu); 12364 break; 12365 } 12366 return SDValue(); 12367 12368 case Intrinsic::arm_neon_vrshifts: 12369 case Intrinsic::arm_neon_vrshiftu: 12370 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12371 break; 12372 return SDValue(); 12373 12374 case Intrinsic::arm_neon_vqshifts: 12375 case Intrinsic::arm_neon_vqshiftu: 12376 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12377 break; 12378 return SDValue(); 12379 12380 case Intrinsic::arm_neon_vqshiftsu: 12381 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12382 break; 12383 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12384 12385 case Intrinsic::arm_neon_vrshiftn: 12386 case Intrinsic::arm_neon_vqshiftns: 12387 case Intrinsic::arm_neon_vqshiftnu: 12388 case Intrinsic::arm_neon_vqshiftnsu: 12389 case Intrinsic::arm_neon_vqrshiftns: 12390 case Intrinsic::arm_neon_vqrshiftnu: 12391 case Intrinsic::arm_neon_vqrshiftnsu: 12392 // Narrowing shifts require an immediate right shift. 12393 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12394 break; 12395 llvm_unreachable("invalid shift count for narrowing vector shift " 12396 "intrinsic"); 12397 12398 default: 12399 llvm_unreachable("unhandled vector shift"); 12400 } 12401 12402 switch (IntNo) { 12403 case Intrinsic::arm_neon_vshifts: 12404 case Intrinsic::arm_neon_vshiftu: 12405 // Opcode already set above. 12406 break; 12407 case Intrinsic::arm_neon_vrshifts: 12408 VShiftOpc = ARMISD::VRSHRs; break; 12409 case Intrinsic::arm_neon_vrshiftu: 12410 VShiftOpc = ARMISD::VRSHRu; break; 12411 case Intrinsic::arm_neon_vrshiftn: 12412 VShiftOpc = ARMISD::VRSHRN; break; 12413 case Intrinsic::arm_neon_vqshifts: 12414 VShiftOpc = ARMISD::VQSHLs; break; 12415 case Intrinsic::arm_neon_vqshiftu: 12416 VShiftOpc = ARMISD::VQSHLu; break; 12417 case Intrinsic::arm_neon_vqshiftsu: 12418 VShiftOpc = ARMISD::VQSHLsu; break; 12419 case Intrinsic::arm_neon_vqshiftns: 12420 VShiftOpc = ARMISD::VQSHRNs; break; 12421 case Intrinsic::arm_neon_vqshiftnu: 12422 VShiftOpc = ARMISD::VQSHRNu; break; 12423 case Intrinsic::arm_neon_vqshiftnsu: 12424 VShiftOpc = ARMISD::VQSHRNsu; break; 12425 case Intrinsic::arm_neon_vqrshiftns: 12426 VShiftOpc = ARMISD::VQRSHRNs; break; 12427 case Intrinsic::arm_neon_vqrshiftnu: 12428 VShiftOpc = ARMISD::VQRSHRNu; break; 12429 case Intrinsic::arm_neon_vqrshiftnsu: 12430 VShiftOpc = ARMISD::VQRSHRNsu; break; 12431 } 12432 12433 SDLoc dl(N); 12434 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12435 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12436 } 12437 12438 case Intrinsic::arm_neon_vshiftins: { 12439 EVT VT = N->getOperand(1).getValueType(); 12440 int64_t Cnt; 12441 unsigned VShiftOpc = 0; 12442 12443 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12444 VShiftOpc = ARMISD::VSLI; 12445 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12446 VShiftOpc = ARMISD::VSRI; 12447 else { 12448 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12449 } 12450 12451 SDLoc dl(N); 12452 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12453 N->getOperand(1), N->getOperand(2), 12454 DAG.getConstant(Cnt, dl, MVT::i32)); 12455 } 12456 12457 case Intrinsic::arm_neon_vqrshifts: 12458 case Intrinsic::arm_neon_vqrshiftu: 12459 // No immediate versions of these to check for. 12460 break; 12461 } 12462 12463 return SDValue(); 12464 } 12465 12466 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12467 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12468 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12469 /// vector element shift counts are generally not legal, and it is hard to see 12470 /// their values after they get legalized to loads from a constant pool. 12471 static SDValue PerformShiftCombine(SDNode *N, 12472 TargetLowering::DAGCombinerInfo &DCI, 12473 const ARMSubtarget *ST) { 12474 SelectionDAG &DAG = DCI.DAG; 12475 EVT VT = N->getValueType(0); 12476 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12477 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12478 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12479 SDValue N1 = N->getOperand(1); 12480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12481 SDValue N0 = N->getOperand(0); 12482 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12483 DAG.MaskedValueIsZero(N0.getOperand(0), 12484 APInt::getHighBitsSet(32, 16))) 12485 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12486 } 12487 } 12488 12489 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 12490 N->getOperand(0)->getOpcode() == ISD::AND && 12491 N->getOperand(0)->hasOneUse()) { 12492 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12493 return SDValue(); 12494 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 12495 // usually show up because instcombine prefers to canonicalize it to 12496 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 12497 // out of GEP lowering in some cases. 12498 SDValue N0 = N->getOperand(0); 12499 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12500 if (!ShiftAmtNode) 12501 return SDValue(); 12502 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 12503 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12504 if (!AndMaskNode) 12505 return SDValue(); 12506 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 12507 // Don't transform uxtb/uxth. 12508 if (AndMask == 255 || AndMask == 65535) 12509 return SDValue(); 12510 if (isMask_32(AndMask)) { 12511 uint32_t MaskedBits = countLeadingZeros(AndMask); 12512 if (MaskedBits > ShiftAmt) { 12513 SDLoc DL(N); 12514 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12515 DAG.getConstant(MaskedBits, DL, MVT::i32)); 12516 return DAG.getNode( 12517 ISD::SRL, DL, MVT::i32, SHL, 12518 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 12519 } 12520 } 12521 } 12522 12523 // Nothing to be done for scalar shifts. 12524 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12525 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12526 return SDValue(); 12527 12528 assert(ST->hasNEON() && "unexpected vector shift"); 12529 int64_t Cnt; 12530 12531 switch (N->getOpcode()) { 12532 default: llvm_unreachable("unexpected shift opcode"); 12533 12534 case ISD::SHL: 12535 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12536 SDLoc dl(N); 12537 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12538 DAG.getConstant(Cnt, dl, MVT::i32)); 12539 } 12540 break; 12541 12542 case ISD::SRA: 12543 case ISD::SRL: 12544 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12545 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12546 ARMISD::VSHRs : ARMISD::VSHRu); 12547 SDLoc dl(N); 12548 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12549 DAG.getConstant(Cnt, dl, MVT::i32)); 12550 } 12551 } 12552 return SDValue(); 12553 } 12554 12555 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12556 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12557 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12558 const ARMSubtarget *ST) { 12559 SDValue N0 = N->getOperand(0); 12560 12561 // Check for sign- and zero-extensions of vector extract operations of 8- 12562 // and 16-bit vector elements. NEON supports these directly. They are 12563 // handled during DAG combining because type legalization will promote them 12564 // to 32-bit types and it is messy to recognize the operations after that. 12565 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12566 SDValue Vec = N0.getOperand(0); 12567 SDValue Lane = N0.getOperand(1); 12568 EVT VT = N->getValueType(0); 12569 EVT EltVT = N0.getValueType(); 12570 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12571 12572 if (VT == MVT::i32 && 12573 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12574 TLI.isTypeLegal(Vec.getValueType()) && 12575 isa<ConstantSDNode>(Lane)) { 12576 12577 unsigned Opc = 0; 12578 switch (N->getOpcode()) { 12579 default: llvm_unreachable("unexpected opcode"); 12580 case ISD::SIGN_EXTEND: 12581 Opc = ARMISD::VGETLANEs; 12582 break; 12583 case ISD::ZERO_EXTEND: 12584 case ISD::ANY_EXTEND: 12585 Opc = ARMISD::VGETLANEu; 12586 break; 12587 } 12588 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12589 } 12590 } 12591 12592 return SDValue(); 12593 } 12594 12595 static const APInt *isPowerOf2Constant(SDValue V) { 12596 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12597 if (!C) 12598 return nullptr; 12599 const APInt *CV = &C->getAPIntValue(); 12600 return CV->isPowerOf2() ? CV : nullptr; 12601 } 12602 12603 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12604 // If we have a CMOV, OR and AND combination such as: 12605 // if (x & CN) 12606 // y |= CM; 12607 // 12608 // And: 12609 // * CN is a single bit; 12610 // * All bits covered by CM are known zero in y 12611 // 12612 // Then we can convert this into a sequence of BFI instructions. This will 12613 // always be a win if CM is a single bit, will always be no worse than the 12614 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12615 // three bits (due to the extra IT instruction). 12616 12617 SDValue Op0 = CMOV->getOperand(0); 12618 SDValue Op1 = CMOV->getOperand(1); 12619 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12620 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12621 SDValue CmpZ = CMOV->getOperand(4); 12622 12623 // The compare must be against zero. 12624 if (!isNullConstant(CmpZ->getOperand(1))) 12625 return SDValue(); 12626 12627 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12628 SDValue And = CmpZ->getOperand(0); 12629 if (And->getOpcode() != ISD::AND) 12630 return SDValue(); 12631 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12632 if (!AndC) 12633 return SDValue(); 12634 SDValue X = And->getOperand(0); 12635 12636 if (CC == ARMCC::EQ) { 12637 // We're performing an "equal to zero" compare. Swap the operands so we 12638 // canonicalize on a "not equal to zero" compare. 12639 std::swap(Op0, Op1); 12640 } else { 12641 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12642 } 12643 12644 if (Op1->getOpcode() != ISD::OR) 12645 return SDValue(); 12646 12647 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12648 if (!OrC) 12649 return SDValue(); 12650 SDValue Y = Op1->getOperand(0); 12651 12652 if (Op0 != Y) 12653 return SDValue(); 12654 12655 // Now, is it profitable to continue? 12656 APInt OrCI = OrC->getAPIntValue(); 12657 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12658 if (OrCI.countPopulation() > Heuristic) 12659 return SDValue(); 12660 12661 // Lastly, can we determine that the bits defined by OrCI 12662 // are zero in Y? 12663 KnownBits Known = DAG.computeKnownBits(Y); 12664 if ((OrCI & Known.Zero) != OrCI) 12665 return SDValue(); 12666 12667 // OK, we can do the combine. 12668 SDValue V = Y; 12669 SDLoc dl(X); 12670 EVT VT = X.getValueType(); 12671 unsigned BitInX = AndC->logBase2(); 12672 12673 if (BitInX != 0) { 12674 // We must shift X first. 12675 X = DAG.getNode(ISD::SRL, dl, VT, X, 12676 DAG.getConstant(BitInX, dl, VT)); 12677 } 12678 12679 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12680 BitInY < NumActiveBits; ++BitInY) { 12681 if (OrCI[BitInY] == 0) 12682 continue; 12683 APInt Mask(VT.getSizeInBits(), 0); 12684 Mask.setBit(BitInY); 12685 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12686 // Confusingly, the operand is an *inverted* mask. 12687 DAG.getConstant(~Mask, dl, VT)); 12688 } 12689 12690 return V; 12691 } 12692 12693 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12694 SDValue 12695 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12696 SDValue Cmp = N->getOperand(4); 12697 if (Cmp.getOpcode() != ARMISD::CMPZ) 12698 // Only looking at NE cases. 12699 return SDValue(); 12700 12701 EVT VT = N->getValueType(0); 12702 SDLoc dl(N); 12703 SDValue LHS = Cmp.getOperand(0); 12704 SDValue RHS = Cmp.getOperand(1); 12705 SDValue Chain = N->getOperand(0); 12706 SDValue BB = N->getOperand(1); 12707 SDValue ARMcc = N->getOperand(2); 12708 ARMCC::CondCodes CC = 12709 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12710 12711 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12712 // -> (brcond Chain BB CC CPSR Cmp) 12713 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12714 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12715 LHS->getOperand(0)->hasOneUse()) { 12716 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12717 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12718 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12719 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12720 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12721 (LHS01C && LHS01C->getZExtValue() == 1) && 12722 (LHS1C && LHS1C->getZExtValue() == 1) && 12723 (RHSC && RHSC->getZExtValue() == 0)) { 12724 return DAG.getNode( 12725 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12726 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12727 } 12728 } 12729 12730 return SDValue(); 12731 } 12732 12733 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12734 SDValue 12735 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12736 SDValue Cmp = N->getOperand(4); 12737 if (Cmp.getOpcode() != ARMISD::CMPZ) 12738 // Only looking at EQ and NE cases. 12739 return SDValue(); 12740 12741 EVT VT = N->getValueType(0); 12742 SDLoc dl(N); 12743 SDValue LHS = Cmp.getOperand(0); 12744 SDValue RHS = Cmp.getOperand(1); 12745 SDValue FalseVal = N->getOperand(0); 12746 SDValue TrueVal = N->getOperand(1); 12747 SDValue ARMcc = N->getOperand(2); 12748 ARMCC::CondCodes CC = 12749 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12750 12751 // BFI is only available on V6T2+. 12752 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12753 SDValue R = PerformCMOVToBFICombine(N, DAG); 12754 if (R) 12755 return R; 12756 } 12757 12758 // Simplify 12759 // mov r1, r0 12760 // cmp r1, x 12761 // mov r0, y 12762 // moveq r0, x 12763 // to 12764 // cmp r0, x 12765 // movne r0, y 12766 // 12767 // mov r1, r0 12768 // cmp r1, x 12769 // mov r0, x 12770 // movne r0, y 12771 // to 12772 // cmp r0, x 12773 // movne r0, y 12774 /// FIXME: Turn this into a target neutral optimization? 12775 SDValue Res; 12776 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12777 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12778 N->getOperand(3), Cmp); 12779 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12780 SDValue ARMcc; 12781 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12782 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12783 N->getOperand(3), NewCmp); 12784 } 12785 12786 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12787 // -> (cmov F T CC CPSR Cmp) 12788 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12789 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12790 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12791 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12792 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12793 (LHS1C && LHS1C->getZExtValue() == 1) && 12794 (RHSC && RHSC->getZExtValue() == 0)) { 12795 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12796 LHS->getOperand(2), LHS->getOperand(3), 12797 LHS->getOperand(4)); 12798 } 12799 } 12800 12801 if (!VT.isInteger()) 12802 return SDValue(); 12803 12804 // Materialize a boolean comparison for integers so we can avoid branching. 12805 if (isNullConstant(FalseVal)) { 12806 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 12807 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 12808 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 12809 // right 5 bits will make that 32 be 1, otherwise it will be 0. 12810 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 12811 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12812 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 12813 DAG.getConstant(5, dl, MVT::i32)); 12814 } else { 12815 // CMOV 0, 1, ==, (CMPZ x, y) -> 12816 // (ADDCARRY (SUB x, y), t:0, t:1) 12817 // where t = (SUBCARRY 0, (SUB x, y), 0) 12818 // 12819 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 12820 // x != y. In other words, a carry C == 1 when x == y, C == 0 12821 // otherwise. 12822 // The final ADDCARRY computes 12823 // x - y + (0 - (x - y)) + C == C 12824 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12825 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12826 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 12827 // ISD::SUBCARRY returns a borrow but we want the carry here 12828 // actually. 12829 SDValue Carry = 12830 DAG.getNode(ISD::SUB, dl, MVT::i32, 12831 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 12832 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 12833 } 12834 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 12835 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 12836 // This seems pointless but will allow us to combine it further below. 12837 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 12838 SDValue Sub = 12839 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 12840 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 12841 Sub.getValue(1), SDValue()); 12842 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 12843 N->getOperand(3), CPSRGlue.getValue(1)); 12844 FalseVal = Sub; 12845 } 12846 } else if (isNullConstant(TrueVal)) { 12847 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 12848 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 12849 // This seems pointless but will allow us to combine it further below 12850 // Note that we change == for != as this is the dual for the case above. 12851 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 12852 SDValue Sub = 12853 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 12854 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 12855 Sub.getValue(1), SDValue()); 12856 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 12857 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 12858 N->getOperand(3), CPSRGlue.getValue(1)); 12859 FalseVal = Sub; 12860 } 12861 } 12862 12863 // On Thumb1, the DAG above may be further combined if z is a power of 2 12864 // (z == 2 ^ K). 12865 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 12866 // t1 = (USUBO (SUB x, y), 1) 12867 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 12868 // Result = if K != 0 then (SHL t2:0, K) else t2:0 12869 // 12870 // This also handles the special case of comparing against zero; it's 12871 // essentially, the same pattern, except there's no SUBS: 12872 // CMOV x, z, !=, (CMPZ x, 0) -> 12873 // t1 = (USUBO x, 1) 12874 // t2 = (SUBCARRY x, t1:0, t1:1) 12875 // Result = if K != 0 then (SHL t2:0, K) else t2:0 12876 const APInt *TrueConst; 12877 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 12878 ((FalseVal.getOpcode() == ARMISD::SUBS && 12879 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 12880 (FalseVal == LHS && isNullConstant(RHS))) && 12881 (TrueConst = isPowerOf2Constant(TrueVal))) { 12882 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12883 unsigned ShiftAmount = TrueConst->logBase2(); 12884 if (ShiftAmount) 12885 TrueVal = DAG.getConstant(1, dl, VT); 12886 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 12887 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 12888 12889 if (ShiftAmount) 12890 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 12891 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 12892 } 12893 12894 if (Res.getNode()) { 12895 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 12896 // Capture demanded bits information that would be otherwise lost. 12897 if (Known.Zero == 0xfffffffe) 12898 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12899 DAG.getValueType(MVT::i1)); 12900 else if (Known.Zero == 0xffffff00) 12901 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12902 DAG.getValueType(MVT::i8)); 12903 else if (Known.Zero == 0xffff0000) 12904 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12905 DAG.getValueType(MVT::i16)); 12906 } 12907 12908 return Res; 12909 } 12910 12911 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12912 DAGCombinerInfo &DCI) const { 12913 switch (N->getOpcode()) { 12914 default: break; 12915 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 12916 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12917 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12918 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12919 case ISD::SUB: return PerformSUBCombine(N, DCI); 12920 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12921 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12922 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12923 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12924 case ARMISD::ADDC: 12925 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12926 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 12927 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12928 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12929 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12930 case ISD::STORE: return PerformSTORECombine(N, DCI); 12931 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12932 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12933 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12934 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12935 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12936 case ISD::FP_TO_SINT: 12937 case ISD::FP_TO_UINT: 12938 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12939 case ISD::FDIV: 12940 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12941 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12942 case ISD::SHL: 12943 case ISD::SRA: 12944 case ISD::SRL: 12945 return PerformShiftCombine(N, DCI, Subtarget); 12946 case ISD::SIGN_EXTEND: 12947 case ISD::ZERO_EXTEND: 12948 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12949 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12950 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12951 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12952 case ARMISD::VLD1DUP: 12953 case ARMISD::VLD2DUP: 12954 case ARMISD::VLD3DUP: 12955 case ARMISD::VLD4DUP: 12956 return PerformVLDCombine(N, DCI); 12957 case ARMISD::BUILD_VECTOR: 12958 return PerformARMBUILD_VECTORCombine(N, DCI); 12959 case ARMISD::SMULWB: { 12960 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12961 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12962 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12963 return SDValue(); 12964 break; 12965 } 12966 case ARMISD::SMULWT: { 12967 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12968 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12969 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12970 return SDValue(); 12971 break; 12972 } 12973 case ARMISD::SMLALBB: { 12974 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12975 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12976 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12977 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12978 return SDValue(); 12979 break; 12980 } 12981 case ARMISD::SMLALBT: { 12982 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12983 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12984 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12985 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12986 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12987 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12988 return SDValue(); 12989 break; 12990 } 12991 case ARMISD::SMLALTB: { 12992 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12993 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12994 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12995 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12996 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12997 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12998 return SDValue(); 12999 break; 13000 } 13001 case ARMISD::SMLALTT: { 13002 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13003 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 13004 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 13005 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 13006 return SDValue(); 13007 break; 13008 } 13009 case ISD::INTRINSIC_VOID: 13010 case ISD::INTRINSIC_W_CHAIN: 13011 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13012 case Intrinsic::arm_neon_vld1: 13013 case Intrinsic::arm_neon_vld1x2: 13014 case Intrinsic::arm_neon_vld1x3: 13015 case Intrinsic::arm_neon_vld1x4: 13016 case Intrinsic::arm_neon_vld2: 13017 case Intrinsic::arm_neon_vld3: 13018 case Intrinsic::arm_neon_vld4: 13019 case Intrinsic::arm_neon_vld2lane: 13020 case Intrinsic::arm_neon_vld3lane: 13021 case Intrinsic::arm_neon_vld4lane: 13022 case Intrinsic::arm_neon_vld2dup: 13023 case Intrinsic::arm_neon_vld3dup: 13024 case Intrinsic::arm_neon_vld4dup: 13025 case Intrinsic::arm_neon_vst1: 13026 case Intrinsic::arm_neon_vst1x2: 13027 case Intrinsic::arm_neon_vst1x3: 13028 case Intrinsic::arm_neon_vst1x4: 13029 case Intrinsic::arm_neon_vst2: 13030 case Intrinsic::arm_neon_vst3: 13031 case Intrinsic::arm_neon_vst4: 13032 case Intrinsic::arm_neon_vst2lane: 13033 case Intrinsic::arm_neon_vst3lane: 13034 case Intrinsic::arm_neon_vst4lane: 13035 return PerformVLDCombine(N, DCI); 13036 default: break; 13037 } 13038 break; 13039 } 13040 return SDValue(); 13041 } 13042 13043 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 13044 EVT VT) const { 13045 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 13046 } 13047 13048 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 13049 unsigned, 13050 unsigned, 13051 bool *Fast) const { 13052 // Depends what it gets converted into if the type is weird. 13053 if (!VT.isSimple()) 13054 return false; 13055 13056 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 13057 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 13058 13059 switch (VT.getSimpleVT().SimpleTy) { 13060 default: 13061 return false; 13062 case MVT::i8: 13063 case MVT::i16: 13064 case MVT::i32: { 13065 // Unaligned access can use (for example) LRDB, LRDH, LDR 13066 if (AllowsUnaligned) { 13067 if (Fast) 13068 *Fast = Subtarget->hasV7Ops(); 13069 return true; 13070 } 13071 return false; 13072 } 13073 case MVT::f64: 13074 case MVT::v2f64: { 13075 // For any little-endian targets with neon, we can support unaligned ld/st 13076 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 13077 // A big-endian target may also explicitly support unaligned accesses 13078 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 13079 if (Fast) 13080 *Fast = true; 13081 return true; 13082 } 13083 return false; 13084 } 13085 } 13086 } 13087 13088 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 13089 unsigned AlignCheck) { 13090 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 13091 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 13092 } 13093 13094 EVT ARMTargetLowering::getOptimalMemOpType( 13095 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 13096 bool ZeroMemset, bool MemcpyStrSrc, 13097 const AttributeList &FuncAttributes) const { 13098 // See if we can use NEON instructions for this... 13099 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 13100 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 13101 bool Fast; 13102 if (Size >= 16 && 13103 (memOpAlign(SrcAlign, DstAlign, 16) || 13104 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 13105 return MVT::v2f64; 13106 } else if (Size >= 8 && 13107 (memOpAlign(SrcAlign, DstAlign, 8) || 13108 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 13109 Fast))) { 13110 return MVT::f64; 13111 } 13112 } 13113 13114 // Let the target-independent logic figure it out. 13115 return MVT::Other; 13116 } 13117 13118 // 64-bit integers are split into their high and low parts and held in two 13119 // different registers, so the trunc is free since the low register can just 13120 // be used. 13121 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 13122 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 13123 return false; 13124 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 13125 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 13126 return (SrcBits == 64 && DestBits == 32); 13127 } 13128 13129 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 13130 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 13131 !DstVT.isInteger()) 13132 return false; 13133 unsigned SrcBits = SrcVT.getSizeInBits(); 13134 unsigned DestBits = DstVT.getSizeInBits(); 13135 return (SrcBits == 64 && DestBits == 32); 13136 } 13137 13138 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13139 if (Val.getOpcode() != ISD::LOAD) 13140 return false; 13141 13142 EVT VT1 = Val.getValueType(); 13143 if (!VT1.isSimple() || !VT1.isInteger() || 13144 !VT2.isSimple() || !VT2.isInteger()) 13145 return false; 13146 13147 switch (VT1.getSimpleVT().SimpleTy) { 13148 default: break; 13149 case MVT::i1: 13150 case MVT::i8: 13151 case MVT::i16: 13152 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 13153 return true; 13154 } 13155 13156 return false; 13157 } 13158 13159 bool ARMTargetLowering::isFNegFree(EVT VT) const { 13160 if (!VT.isSimple()) 13161 return false; 13162 13163 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 13164 // negate values directly (fneg is free). So, we don't want to let the DAG 13165 // combiner rewrite fneg into xors and some other instructions. For f16 and 13166 // FullFP16 argument passing, some bitcast nodes may be introduced, 13167 // triggering this DAG combine rewrite, so we are avoiding that with this. 13168 switch (VT.getSimpleVT().SimpleTy) { 13169 default: break; 13170 case MVT::f16: 13171 return Subtarget->hasFullFP16(); 13172 } 13173 13174 return false; 13175 } 13176 13177 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 13178 /// of the vector elements. 13179 static bool areExtractExts(Value *Ext1, Value *Ext2) { 13180 auto areExtDoubled = [](Instruction *Ext) { 13181 return Ext->getType()->getScalarSizeInBits() == 13182 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 13183 }; 13184 13185 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 13186 !match(Ext2, m_ZExtOrSExt(m_Value())) || 13187 !areExtDoubled(cast<Instruction>(Ext1)) || 13188 !areExtDoubled(cast<Instruction>(Ext2))) 13189 return false; 13190 13191 return true; 13192 } 13193 13194 /// Check if sinking \p I's operands to I's basic block is profitable, because 13195 /// the operands can be folded into a target instruction, e.g. 13196 /// sext/zext can be folded into vsubl. 13197 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 13198 SmallVectorImpl<Use *> &Ops) const { 13199 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy()) 13200 return false; 13201 13202 switch (I->getOpcode()) { 13203 case Instruction::Sub: 13204 case Instruction::Add: { 13205 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 13206 return false; 13207 Ops.push_back(&I->getOperandUse(0)); 13208 Ops.push_back(&I->getOperandUse(1)); 13209 return true; 13210 } 13211 default: 13212 return false; 13213 } 13214 return false; 13215 } 13216 13217 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 13218 EVT VT = ExtVal.getValueType(); 13219 13220 if (!isTypeLegal(VT)) 13221 return false; 13222 13223 // Don't create a loadext if we can fold the extension into a wide/long 13224 // instruction. 13225 // If there's more than one user instruction, the loadext is desirable no 13226 // matter what. There can be two uses by the same instruction. 13227 if (ExtVal->use_empty() || 13228 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 13229 return true; 13230 13231 SDNode *U = *ExtVal->use_begin(); 13232 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 13233 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 13234 return false; 13235 13236 return true; 13237 } 13238 13239 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 13240 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13241 return false; 13242 13243 if (!isTypeLegal(EVT::getEVT(Ty1))) 13244 return false; 13245 13246 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 13247 13248 // Assuming the caller doesn't have a zeroext or signext return parameter, 13249 // truncation all the way down to i1 is valid. 13250 return true; 13251 } 13252 13253 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 13254 const AddrMode &AM, Type *Ty, 13255 unsigned AS) const { 13256 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 13257 if (Subtarget->hasFPAO()) 13258 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 13259 return 0; 13260 } 13261 return -1; 13262 } 13263 13264 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 13265 if (V < 0) 13266 return false; 13267 13268 unsigned Scale = 1; 13269 switch (VT.getSimpleVT().SimpleTy) { 13270 default: return false; 13271 case MVT::i1: 13272 case MVT::i8: 13273 // Scale == 1; 13274 break; 13275 case MVT::i16: 13276 // Scale == 2; 13277 Scale = 2; 13278 break; 13279 case MVT::i32: 13280 // Scale == 4; 13281 Scale = 4; 13282 break; 13283 } 13284 13285 if ((V & (Scale - 1)) != 0) 13286 return false; 13287 return isUInt<5>(V / Scale); 13288 } 13289 13290 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 13291 const ARMSubtarget *Subtarget) { 13292 if (!VT.isInteger() && !VT.isFloatingPoint()) 13293 return false; 13294 if (Subtarget->hasNEON() && VT.isVector()) 13295 return false; 13296 13297 bool IsNeg = false; 13298 if (V < 0) { 13299 IsNeg = true; 13300 V = -V; 13301 } 13302 13303 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U); 13304 13305 // VLDR and LDRD: 4 * imm8 13306 if ((VT.isFloatingPoint() && Subtarget->hasVFP2()) || NumBytes == 8) 13307 return isShiftedUInt<8, 2>(V); 13308 13309 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 13310 // + imm12 or - imm8 13311 if (IsNeg) 13312 return isUInt<8>(V); 13313 return isUInt<12>(V); 13314 } 13315 13316 return false; 13317 } 13318 13319 /// isLegalAddressImmediate - Return true if the integer value can be used 13320 /// as the offset of the target addressing mode for load / store of the 13321 /// given type. 13322 static bool isLegalAddressImmediate(int64_t V, EVT VT, 13323 const ARMSubtarget *Subtarget) { 13324 if (V == 0) 13325 return true; 13326 13327 if (!VT.isSimple()) 13328 return false; 13329 13330 if (Subtarget->isThumb1Only()) 13331 return isLegalT1AddressImmediate(V, VT); 13332 else if (Subtarget->isThumb2()) 13333 return isLegalT2AddressImmediate(V, VT, Subtarget); 13334 13335 // ARM mode. 13336 if (V < 0) 13337 V = - V; 13338 switch (VT.getSimpleVT().SimpleTy) { 13339 default: return false; 13340 case MVT::i1: 13341 case MVT::i8: 13342 case MVT::i32: 13343 // +- imm12 13344 return isUInt<12>(V); 13345 case MVT::i16: 13346 // +- imm8 13347 return isUInt<8>(V); 13348 case MVT::f32: 13349 case MVT::f64: 13350 if (!Subtarget->hasVFP2()) // FIXME: NEON? 13351 return false; 13352 return isShiftedUInt<8, 2>(V); 13353 } 13354 } 13355 13356 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 13357 EVT VT) const { 13358 int Scale = AM.Scale; 13359 if (Scale < 0) 13360 return false; 13361 13362 switch (VT.getSimpleVT().SimpleTy) { 13363 default: return false; 13364 case MVT::i1: 13365 case MVT::i8: 13366 case MVT::i16: 13367 case MVT::i32: 13368 if (Scale == 1) 13369 return true; 13370 // r + r << imm 13371 Scale = Scale & ~1; 13372 return Scale == 2 || Scale == 4 || Scale == 8; 13373 case MVT::i64: 13374 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 13375 // version in Thumb mode. 13376 // r + r 13377 if (Scale == 1) 13378 return true; 13379 // r * 2 (this can be lowered to r + r). 13380 if (!AM.HasBaseReg && Scale == 2) 13381 return true; 13382 return false; 13383 case MVT::isVoid: 13384 // Note, we allow "void" uses (basically, uses that aren't loads or 13385 // stores), because arm allows folding a scale into many arithmetic 13386 // operations. This should be made more precise and revisited later. 13387 13388 // Allow r << imm, but the imm has to be a multiple of two. 13389 if (Scale & 1) return false; 13390 return isPowerOf2_32(Scale); 13391 } 13392 } 13393 13394 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 13395 EVT VT) const { 13396 const int Scale = AM.Scale; 13397 13398 // Negative scales are not supported in Thumb1. 13399 if (Scale < 0) 13400 return false; 13401 13402 // Thumb1 addressing modes do not support register scaling excepting the 13403 // following cases: 13404 // 1. Scale == 1 means no scaling. 13405 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 13406 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 13407 } 13408 13409 /// isLegalAddressingMode - Return true if the addressing mode represented 13410 /// by AM is legal for this target, for a load/store of the specified type. 13411 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13412 const AddrMode &AM, Type *Ty, 13413 unsigned AS, Instruction *I) const { 13414 EVT VT = getValueType(DL, Ty, true); 13415 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 13416 return false; 13417 13418 // Can never fold addr of global into load/store. 13419 if (AM.BaseGV) 13420 return false; 13421 13422 switch (AM.Scale) { 13423 case 0: // no scale reg, must be "r+i" or "r", or "i". 13424 break; 13425 default: 13426 // ARM doesn't support any R+R*scale+imm addr modes. 13427 if (AM.BaseOffs) 13428 return false; 13429 13430 if (!VT.isSimple()) 13431 return false; 13432 13433 if (Subtarget->isThumb1Only()) 13434 return isLegalT1ScaledAddressingMode(AM, VT); 13435 13436 if (Subtarget->isThumb2()) 13437 return isLegalT2ScaledAddressingMode(AM, VT); 13438 13439 int Scale = AM.Scale; 13440 switch (VT.getSimpleVT().SimpleTy) { 13441 default: return false; 13442 case MVT::i1: 13443 case MVT::i8: 13444 case MVT::i32: 13445 if (Scale < 0) Scale = -Scale; 13446 if (Scale == 1) 13447 return true; 13448 // r + r << imm 13449 return isPowerOf2_32(Scale & ~1); 13450 case MVT::i16: 13451 case MVT::i64: 13452 // r +/- r 13453 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 13454 return true; 13455 // r * 2 (this can be lowered to r + r). 13456 if (!AM.HasBaseReg && Scale == 2) 13457 return true; 13458 return false; 13459 13460 case MVT::isVoid: 13461 // Note, we allow "void" uses (basically, uses that aren't loads or 13462 // stores), because arm allows folding a scale into many arithmetic 13463 // operations. This should be made more precise and revisited later. 13464 13465 // Allow r << imm, but the imm has to be a multiple of two. 13466 if (Scale & 1) return false; 13467 return isPowerOf2_32(Scale); 13468 } 13469 } 13470 return true; 13471 } 13472 13473 /// isLegalICmpImmediate - Return true if the specified immediate is legal 13474 /// icmp immediate, that is the target has icmp instructions which can compare 13475 /// a register against the immediate without having to materialize the 13476 /// immediate into a register. 13477 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13478 // Thumb2 and ARM modes can use cmn for negative immediates. 13479 if (!Subtarget->isThumb()) 13480 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 13481 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 13482 if (Subtarget->isThumb2()) 13483 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 13484 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 13485 // Thumb1 doesn't have cmn, and only 8-bit immediates. 13486 return Imm >= 0 && Imm <= 255; 13487 } 13488 13489 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 13490 /// *or sub* immediate, that is the target has add or sub instructions which can 13491 /// add a register with the immediate without having to materialize the 13492 /// immediate into a register. 13493 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13494 // Same encoding for add/sub, just flip the sign. 13495 int64_t AbsImm = std::abs(Imm); 13496 if (!Subtarget->isThumb()) 13497 return ARM_AM::getSOImmVal(AbsImm) != -1; 13498 if (Subtarget->isThumb2()) 13499 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 13500 // Thumb1 only has 8-bit unsigned immediate. 13501 return AbsImm >= 0 && AbsImm <= 255; 13502 } 13503 13504 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 13505 bool isSEXTLoad, SDValue &Base, 13506 SDValue &Offset, bool &isInc, 13507 SelectionDAG &DAG) { 13508 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13509 return false; 13510 13511 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 13512 // AddressingMode 3 13513 Base = Ptr->getOperand(0); 13514 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13515 int RHSC = (int)RHS->getZExtValue(); 13516 if (RHSC < 0 && RHSC > -256) { 13517 assert(Ptr->getOpcode() == ISD::ADD); 13518 isInc = false; 13519 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13520 return true; 13521 } 13522 } 13523 isInc = (Ptr->getOpcode() == ISD::ADD); 13524 Offset = Ptr->getOperand(1); 13525 return true; 13526 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 13527 // AddressingMode 2 13528 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13529 int RHSC = (int)RHS->getZExtValue(); 13530 if (RHSC < 0 && RHSC > -0x1000) { 13531 assert(Ptr->getOpcode() == ISD::ADD); 13532 isInc = false; 13533 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13534 Base = Ptr->getOperand(0); 13535 return true; 13536 } 13537 } 13538 13539 if (Ptr->getOpcode() == ISD::ADD) { 13540 isInc = true; 13541 ARM_AM::ShiftOpc ShOpcVal= 13542 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 13543 if (ShOpcVal != ARM_AM::no_shift) { 13544 Base = Ptr->getOperand(1); 13545 Offset = Ptr->getOperand(0); 13546 } else { 13547 Base = Ptr->getOperand(0); 13548 Offset = Ptr->getOperand(1); 13549 } 13550 return true; 13551 } 13552 13553 isInc = (Ptr->getOpcode() == ISD::ADD); 13554 Base = Ptr->getOperand(0); 13555 Offset = Ptr->getOperand(1); 13556 return true; 13557 } 13558 13559 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 13560 return false; 13561 } 13562 13563 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 13564 bool isSEXTLoad, SDValue &Base, 13565 SDValue &Offset, bool &isInc, 13566 SelectionDAG &DAG) { 13567 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13568 return false; 13569 13570 Base = Ptr->getOperand(0); 13571 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13572 int RHSC = (int)RHS->getZExtValue(); 13573 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 13574 assert(Ptr->getOpcode() == ISD::ADD); 13575 isInc = false; 13576 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13577 return true; 13578 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 13579 isInc = Ptr->getOpcode() == ISD::ADD; 13580 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13581 return true; 13582 } 13583 } 13584 13585 return false; 13586 } 13587 13588 /// getPreIndexedAddressParts - returns true by value, base pointer and 13589 /// offset pointer and addressing mode by reference if the node's address 13590 /// can be legally represented as pre-indexed load / store address. 13591 bool 13592 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13593 SDValue &Offset, 13594 ISD::MemIndexedMode &AM, 13595 SelectionDAG &DAG) const { 13596 if (Subtarget->isThumb1Only()) 13597 return false; 13598 13599 EVT VT; 13600 SDValue Ptr; 13601 bool isSEXTLoad = false; 13602 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13603 Ptr = LD->getBasePtr(); 13604 VT = LD->getMemoryVT(); 13605 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13606 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13607 Ptr = ST->getBasePtr(); 13608 VT = ST->getMemoryVT(); 13609 } else 13610 return false; 13611 13612 bool isInc; 13613 bool isLegal = false; 13614 if (Subtarget->isThumb2()) 13615 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13616 Offset, isInc, DAG); 13617 else 13618 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13619 Offset, isInc, DAG); 13620 if (!isLegal) 13621 return false; 13622 13623 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 13624 return true; 13625 } 13626 13627 /// getPostIndexedAddressParts - returns true by value, base pointer and 13628 /// offset pointer and addressing mode by reference if this node can be 13629 /// combined with a load / store to form a post-indexed load / store. 13630 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 13631 SDValue &Base, 13632 SDValue &Offset, 13633 ISD::MemIndexedMode &AM, 13634 SelectionDAG &DAG) const { 13635 EVT VT; 13636 SDValue Ptr; 13637 bool isSEXTLoad = false, isNonExt; 13638 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13639 VT = LD->getMemoryVT(); 13640 Ptr = LD->getBasePtr(); 13641 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13642 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 13643 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13644 VT = ST->getMemoryVT(); 13645 Ptr = ST->getBasePtr(); 13646 isNonExt = !ST->isTruncatingStore(); 13647 } else 13648 return false; 13649 13650 if (Subtarget->isThumb1Only()) { 13651 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 13652 // must be non-extending/truncating, i32, with an offset of 4. 13653 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 13654 if (Op->getOpcode() != ISD::ADD || !isNonExt) 13655 return false; 13656 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 13657 if (!RHS || RHS->getZExtValue() != 4) 13658 return false; 13659 13660 Offset = Op->getOperand(1); 13661 Base = Op->getOperand(0); 13662 AM = ISD::POST_INC; 13663 return true; 13664 } 13665 13666 bool isInc; 13667 bool isLegal = false; 13668 if (Subtarget->isThumb2()) 13669 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13670 isInc, DAG); 13671 else 13672 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13673 isInc, DAG); 13674 if (!isLegal) 13675 return false; 13676 13677 if (Ptr != Base) { 13678 // Swap base ptr and offset to catch more post-index load / store when 13679 // it's legal. In Thumb2 mode, offset must be an immediate. 13680 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 13681 !Subtarget->isThumb2()) 13682 std::swap(Base, Offset); 13683 13684 // Post-indexed load / store update the base pointer. 13685 if (Ptr != Base) 13686 return false; 13687 } 13688 13689 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 13690 return true; 13691 } 13692 13693 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13694 KnownBits &Known, 13695 const APInt &DemandedElts, 13696 const SelectionDAG &DAG, 13697 unsigned Depth) const { 13698 unsigned BitWidth = Known.getBitWidth(); 13699 Known.resetAll(); 13700 switch (Op.getOpcode()) { 13701 default: break; 13702 case ARMISD::ADDC: 13703 case ARMISD::ADDE: 13704 case ARMISD::SUBC: 13705 case ARMISD::SUBE: 13706 // Special cases when we convert a carry to a boolean. 13707 if (Op.getResNo() == 0) { 13708 SDValue LHS = Op.getOperand(0); 13709 SDValue RHS = Op.getOperand(1); 13710 // (ADDE 0, 0, C) will give us a single bit. 13711 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 13712 isNullConstant(RHS)) { 13713 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 13714 return; 13715 } 13716 } 13717 break; 13718 case ARMISD::CMOV: { 13719 // Bits are known zero/one if known on the LHS and RHS. 13720 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 13721 if (Known.isUnknown()) 13722 return; 13723 13724 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 13725 Known.Zero &= KnownRHS.Zero; 13726 Known.One &= KnownRHS.One; 13727 return; 13728 } 13729 case ISD::INTRINSIC_W_CHAIN: { 13730 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13731 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13732 switch (IntID) { 13733 default: return; 13734 case Intrinsic::arm_ldaex: 13735 case Intrinsic::arm_ldrex: { 13736 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13737 unsigned MemBits = VT.getScalarSizeInBits(); 13738 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13739 return; 13740 } 13741 } 13742 } 13743 case ARMISD::BFI: { 13744 // Conservatively, we can recurse down the first operand 13745 // and just mask out all affected bits. 13746 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 13747 13748 // The operand to BFI is already a mask suitable for removing the bits it 13749 // sets. 13750 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13751 const APInt &Mask = CI->getAPIntValue(); 13752 Known.Zero &= Mask; 13753 Known.One &= Mask; 13754 return; 13755 } 13756 case ARMISD::VGETLANEs: 13757 case ARMISD::VGETLANEu: { 13758 const SDValue &SrcSV = Op.getOperand(0); 13759 EVT VecVT = SrcSV.getValueType(); 13760 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 13761 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 13762 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 13763 assert(Pos->getAPIntValue().ult(NumSrcElts) && 13764 "VGETLANE index out of bounds"); 13765 unsigned Idx = Pos->getZExtValue(); 13766 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 13767 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 13768 13769 EVT VT = Op.getValueType(); 13770 const unsigned DstSz = VT.getScalarSizeInBits(); 13771 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 13772 (void)SrcSz; 13773 assert(SrcSz == Known.getBitWidth()); 13774 assert(DstSz > SrcSz); 13775 if (Op.getOpcode() == ARMISD::VGETLANEs) 13776 Known = Known.sext(DstSz); 13777 else { 13778 Known = Known.zext(DstSz, true /* extended bits are known zero */); 13779 } 13780 assert(DstSz == Known.getBitWidth()); 13781 break; 13782 } 13783 } 13784 } 13785 13786 bool 13787 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 13788 const APInt &DemandedAPInt, 13789 TargetLoweringOpt &TLO) const { 13790 // Delay optimization, so we don't have to deal with illegal types, or block 13791 // optimizations. 13792 if (!TLO.LegalOps) 13793 return false; 13794 13795 // Only optimize AND for now. 13796 if (Op.getOpcode() != ISD::AND) 13797 return false; 13798 13799 EVT VT = Op.getValueType(); 13800 13801 // Ignore vectors. 13802 if (VT.isVector()) 13803 return false; 13804 13805 assert(VT == MVT::i32 && "Unexpected integer type"); 13806 13807 // Make sure the RHS really is a constant. 13808 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13809 if (!C) 13810 return false; 13811 13812 unsigned Mask = C->getZExtValue(); 13813 13814 unsigned Demanded = DemandedAPInt.getZExtValue(); 13815 unsigned ShrunkMask = Mask & Demanded; 13816 unsigned ExpandedMask = Mask | ~Demanded; 13817 13818 // If the mask is all zeros, let the target-independent code replace the 13819 // result with zero. 13820 if (ShrunkMask == 0) 13821 return false; 13822 13823 // If the mask is all ones, erase the AND. (Currently, the target-independent 13824 // code won't do this, so we have to do it explicitly to avoid an infinite 13825 // loop in obscure cases.) 13826 if (ExpandedMask == ~0U) 13827 return TLO.CombineTo(Op, Op.getOperand(0)); 13828 13829 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 13830 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 13831 }; 13832 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 13833 if (NewMask == Mask) 13834 return true; 13835 SDLoc DL(Op); 13836 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 13837 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 13838 return TLO.CombineTo(Op, NewOp); 13839 }; 13840 13841 // Prefer uxtb mask. 13842 if (IsLegalMask(0xFF)) 13843 return UseMask(0xFF); 13844 13845 // Prefer uxth mask. 13846 if (IsLegalMask(0xFFFF)) 13847 return UseMask(0xFFFF); 13848 13849 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 13850 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 13851 if (ShrunkMask < 256) 13852 return UseMask(ShrunkMask); 13853 13854 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 13855 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 13856 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 13857 return UseMask(ExpandedMask); 13858 13859 // Potential improvements: 13860 // 13861 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 13862 // We could try to prefer Thumb1 immediates which can be lowered to a 13863 // two-instruction sequence. 13864 // We could try to recognize more legal ARM/Thumb2 immediates here. 13865 13866 return false; 13867 } 13868 13869 13870 //===----------------------------------------------------------------------===// 13871 // ARM Inline Assembly Support 13872 //===----------------------------------------------------------------------===// 13873 13874 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13875 // Looking for "rev" which is V6+. 13876 if (!Subtarget->hasV6Ops()) 13877 return false; 13878 13879 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13880 std::string AsmStr = IA->getAsmString(); 13881 SmallVector<StringRef, 4> AsmPieces; 13882 SplitString(AsmStr, AsmPieces, ";\n"); 13883 13884 switch (AsmPieces.size()) { 13885 default: return false; 13886 case 1: 13887 AsmStr = AsmPieces[0]; 13888 AsmPieces.clear(); 13889 SplitString(AsmStr, AsmPieces, " \t,"); 13890 13891 // rev $0, $1 13892 if (AsmPieces.size() == 3 && 13893 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13894 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13895 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13896 if (Ty && Ty->getBitWidth() == 32) 13897 return IntrinsicLowering::LowerToByteSwap(CI); 13898 } 13899 break; 13900 } 13901 13902 return false; 13903 } 13904 13905 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13906 // At this point, we have to lower this constraint to something else, so we 13907 // lower it to an "r" or "w". However, by doing this we will force the result 13908 // to be in register, while the X constraint is much more permissive. 13909 // 13910 // Although we are correct (we are free to emit anything, without 13911 // constraints), we might break use cases that would expect us to be more 13912 // efficient and emit something else. 13913 if (!Subtarget->hasVFP2()) 13914 return "r"; 13915 if (ConstraintVT.isFloatingPoint()) 13916 return "w"; 13917 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13918 (ConstraintVT.getSizeInBits() == 64 || 13919 ConstraintVT.getSizeInBits() == 128)) 13920 return "w"; 13921 13922 return "r"; 13923 } 13924 13925 /// getConstraintType - Given a constraint letter, return the type of 13926 /// constraint it is for this target. 13927 ARMTargetLowering::ConstraintType 13928 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13929 if (Constraint.size() == 1) { 13930 switch (Constraint[0]) { 13931 default: break; 13932 case 'l': return C_RegisterClass; 13933 case 'w': return C_RegisterClass; 13934 case 'h': return C_RegisterClass; 13935 case 'x': return C_RegisterClass; 13936 case 't': return C_RegisterClass; 13937 case 'j': return C_Other; // Constant for movw. 13938 // An address with a single base register. Due to the way we 13939 // currently handle addresses it is the same as an 'r' memory constraint. 13940 case 'Q': return C_Memory; 13941 } 13942 } else if (Constraint.size() == 2) { 13943 switch (Constraint[0]) { 13944 default: break; 13945 // All 'U+' constraints are addresses. 13946 case 'U': return C_Memory; 13947 } 13948 } 13949 return TargetLowering::getConstraintType(Constraint); 13950 } 13951 13952 /// Examine constraint type and operand type and determine a weight value. 13953 /// This object must already have been set up with the operand type 13954 /// and the current alternative constraint selected. 13955 TargetLowering::ConstraintWeight 13956 ARMTargetLowering::getSingleConstraintMatchWeight( 13957 AsmOperandInfo &info, const char *constraint) const { 13958 ConstraintWeight weight = CW_Invalid; 13959 Value *CallOperandVal = info.CallOperandVal; 13960 // If we don't have a value, we can't do a match, 13961 // but allow it at the lowest weight. 13962 if (!CallOperandVal) 13963 return CW_Default; 13964 Type *type = CallOperandVal->getType(); 13965 // Look at the constraint type. 13966 switch (*constraint) { 13967 default: 13968 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13969 break; 13970 case 'l': 13971 if (type->isIntegerTy()) { 13972 if (Subtarget->isThumb()) 13973 weight = CW_SpecificReg; 13974 else 13975 weight = CW_Register; 13976 } 13977 break; 13978 case 'w': 13979 if (type->isFloatingPointTy()) 13980 weight = CW_Register; 13981 break; 13982 } 13983 return weight; 13984 } 13985 13986 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13987 13988 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13989 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13990 if (Constraint.size() == 1) { 13991 // GCC ARM Constraint Letters 13992 switch (Constraint[0]) { 13993 case 'l': // Low regs or general regs. 13994 if (Subtarget->isThumb()) 13995 return RCPair(0U, &ARM::tGPRRegClass); 13996 return RCPair(0U, &ARM::GPRRegClass); 13997 case 'h': // High regs or no regs. 13998 if (Subtarget->isThumb()) 13999 return RCPair(0U, &ARM::hGPRRegClass); 14000 break; 14001 case 'r': 14002 if (Subtarget->isThumb1Only()) 14003 return RCPair(0U, &ARM::tGPRRegClass); 14004 return RCPair(0U, &ARM::GPRRegClass); 14005 case 'w': 14006 if (VT == MVT::Other) 14007 break; 14008 if (VT == MVT::f32) 14009 return RCPair(0U, &ARM::SPRRegClass); 14010 if (VT.getSizeInBits() == 64) 14011 return RCPair(0U, &ARM::DPRRegClass); 14012 if (VT.getSizeInBits() == 128) 14013 return RCPair(0U, &ARM::QPRRegClass); 14014 break; 14015 case 'x': 14016 if (VT == MVT::Other) 14017 break; 14018 if (VT == MVT::f32) 14019 return RCPair(0U, &ARM::SPR_8RegClass); 14020 if (VT.getSizeInBits() == 64) 14021 return RCPair(0U, &ARM::DPR_8RegClass); 14022 if (VT.getSizeInBits() == 128) 14023 return RCPair(0U, &ARM::QPR_8RegClass); 14024 break; 14025 case 't': 14026 if (VT == MVT::Other) 14027 break; 14028 if (VT == MVT::f32 || VT == MVT::i32) 14029 return RCPair(0U, &ARM::SPRRegClass); 14030 if (VT.getSizeInBits() == 64) 14031 return RCPair(0U, &ARM::DPR_VFP2RegClass); 14032 if (VT.getSizeInBits() == 128) 14033 return RCPair(0U, &ARM::QPR_VFP2RegClass); 14034 break; 14035 } 14036 } 14037 if (StringRef("{cc}").equals_lower(Constraint)) 14038 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 14039 14040 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14041 } 14042 14043 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14044 /// vector. If it is invalid, don't add anything to Ops. 14045 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14046 std::string &Constraint, 14047 std::vector<SDValue>&Ops, 14048 SelectionDAG &DAG) const { 14049 SDValue Result; 14050 14051 // Currently only support length 1 constraints. 14052 if (Constraint.length() != 1) return; 14053 14054 char ConstraintLetter = Constraint[0]; 14055 switch (ConstraintLetter) { 14056 default: break; 14057 case 'j': 14058 case 'I': case 'J': case 'K': case 'L': 14059 case 'M': case 'N': case 'O': 14060 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 14061 if (!C) 14062 return; 14063 14064 int64_t CVal64 = C->getSExtValue(); 14065 int CVal = (int) CVal64; 14066 // None of these constraints allow values larger than 32 bits. Check 14067 // that the value fits in an int. 14068 if (CVal != CVal64) 14069 return; 14070 14071 switch (ConstraintLetter) { 14072 case 'j': 14073 // Constant suitable for movw, must be between 0 and 14074 // 65535. 14075 if (Subtarget->hasV6T2Ops()) 14076 if (CVal >= 0 && CVal <= 65535) 14077 break; 14078 return; 14079 case 'I': 14080 if (Subtarget->isThumb1Only()) { 14081 // This must be a constant between 0 and 255, for ADD 14082 // immediates. 14083 if (CVal >= 0 && CVal <= 255) 14084 break; 14085 } else if (Subtarget->isThumb2()) { 14086 // A constant that can be used as an immediate value in a 14087 // data-processing instruction. 14088 if (ARM_AM::getT2SOImmVal(CVal) != -1) 14089 break; 14090 } else { 14091 // A constant that can be used as an immediate value in a 14092 // data-processing instruction. 14093 if (ARM_AM::getSOImmVal(CVal) != -1) 14094 break; 14095 } 14096 return; 14097 14098 case 'J': 14099 if (Subtarget->isThumb1Only()) { 14100 // This must be a constant between -255 and -1, for negated ADD 14101 // immediates. This can be used in GCC with an "n" modifier that 14102 // prints the negated value, for use with SUB instructions. It is 14103 // not useful otherwise but is implemented for compatibility. 14104 if (CVal >= -255 && CVal <= -1) 14105 break; 14106 } else { 14107 // This must be a constant between -4095 and 4095. It is not clear 14108 // what this constraint is intended for. Implemented for 14109 // compatibility with GCC. 14110 if (CVal >= -4095 && CVal <= 4095) 14111 break; 14112 } 14113 return; 14114 14115 case 'K': 14116 if (Subtarget->isThumb1Only()) { 14117 // A 32-bit value where only one byte has a nonzero value. Exclude 14118 // zero to match GCC. This constraint is used by GCC internally for 14119 // constants that can be loaded with a move/shift combination. 14120 // It is not useful otherwise but is implemented for compatibility. 14121 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 14122 break; 14123 } else if (Subtarget->isThumb2()) { 14124 // A constant whose bitwise inverse can be used as an immediate 14125 // value in a data-processing instruction. This can be used in GCC 14126 // with a "B" modifier that prints the inverted value, for use with 14127 // BIC and MVN instructions. It is not useful otherwise but is 14128 // implemented for compatibility. 14129 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 14130 break; 14131 } else { 14132 // A constant whose bitwise inverse can be used as an immediate 14133 // value in a data-processing instruction. This can be used in GCC 14134 // with a "B" modifier that prints the inverted value, for use with 14135 // BIC and MVN instructions. It is not useful otherwise but is 14136 // implemented for compatibility. 14137 if (ARM_AM::getSOImmVal(~CVal) != -1) 14138 break; 14139 } 14140 return; 14141 14142 case 'L': 14143 if (Subtarget->isThumb1Only()) { 14144 // This must be a constant between -7 and 7, 14145 // for 3-operand ADD/SUB immediate instructions. 14146 if (CVal >= -7 && CVal < 7) 14147 break; 14148 } else if (Subtarget->isThumb2()) { 14149 // A constant whose negation can be used as an immediate value in a 14150 // data-processing instruction. This can be used in GCC with an "n" 14151 // modifier that prints the negated value, for use with SUB 14152 // instructions. It is not useful otherwise but is implemented for 14153 // compatibility. 14154 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 14155 break; 14156 } else { 14157 // A constant whose negation can be used as an immediate value in a 14158 // data-processing instruction. This can be used in GCC with an "n" 14159 // modifier that prints the negated value, for use with SUB 14160 // instructions. It is not useful otherwise but is implemented for 14161 // compatibility. 14162 if (ARM_AM::getSOImmVal(-CVal) != -1) 14163 break; 14164 } 14165 return; 14166 14167 case 'M': 14168 if (Subtarget->isThumb1Only()) { 14169 // This must be a multiple of 4 between 0 and 1020, for 14170 // ADD sp + immediate. 14171 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 14172 break; 14173 } else { 14174 // A power of two or a constant between 0 and 32. This is used in 14175 // GCC for the shift amount on shifted register operands, but it is 14176 // useful in general for any shift amounts. 14177 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 14178 break; 14179 } 14180 return; 14181 14182 case 'N': 14183 if (Subtarget->isThumb()) { // FIXME thumb2 14184 // This must be a constant between 0 and 31, for shift amounts. 14185 if (CVal >= 0 && CVal <= 31) 14186 break; 14187 } 14188 return; 14189 14190 case 'O': 14191 if (Subtarget->isThumb()) { // FIXME thumb2 14192 // This must be a multiple of 4 between -508 and 508, for 14193 // ADD/SUB sp = sp + immediate. 14194 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 14195 break; 14196 } 14197 return; 14198 } 14199 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 14200 break; 14201 } 14202 14203 if (Result.getNode()) { 14204 Ops.push_back(Result); 14205 return; 14206 } 14207 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14208 } 14209 14210 static RTLIB::Libcall getDivRemLibcall( 14211 const SDNode *N, MVT::SimpleValueType SVT) { 14212 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14213 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14214 "Unhandled Opcode in getDivRemLibcall"); 14215 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14216 N->getOpcode() == ISD::SREM; 14217 RTLIB::Libcall LC; 14218 switch (SVT) { 14219 default: llvm_unreachable("Unexpected request for libcall!"); 14220 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 14221 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 14222 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 14223 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 14224 } 14225 return LC; 14226 } 14227 14228 static TargetLowering::ArgListTy getDivRemArgList( 14229 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 14230 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14231 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14232 "Unhandled Opcode in getDivRemArgList"); 14233 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14234 N->getOpcode() == ISD::SREM; 14235 TargetLowering::ArgListTy Args; 14236 TargetLowering::ArgListEntry Entry; 14237 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14238 EVT ArgVT = N->getOperand(i).getValueType(); 14239 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 14240 Entry.Node = N->getOperand(i); 14241 Entry.Ty = ArgTy; 14242 Entry.IsSExt = isSigned; 14243 Entry.IsZExt = !isSigned; 14244 Args.push_back(Entry); 14245 } 14246 if (Subtarget->isTargetWindows() && Args.size() >= 2) 14247 std::swap(Args[0], Args[1]); 14248 return Args; 14249 } 14250 14251 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 14252 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 14253 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 14254 Subtarget->isTargetWindows()) && 14255 "Register-based DivRem lowering only"); 14256 unsigned Opcode = Op->getOpcode(); 14257 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 14258 "Invalid opcode for Div/Rem lowering"); 14259 bool isSigned = (Opcode == ISD::SDIVREM); 14260 EVT VT = Op->getValueType(0); 14261 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 14262 SDLoc dl(Op); 14263 14264 // If the target has hardware divide, use divide + multiply + subtract: 14265 // div = a / b 14266 // rem = a - b * div 14267 // return {div, rem} 14268 // This should be lowered into UDIV/SDIV + MLS later on. 14269 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 14270 : Subtarget->hasDivideInARMMode(); 14271 if (hasDivide && Op->getValueType(0).isSimple() && 14272 Op->getSimpleValueType(0) == MVT::i32) { 14273 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 14274 const SDValue Dividend = Op->getOperand(0); 14275 const SDValue Divisor = Op->getOperand(1); 14276 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 14277 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 14278 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 14279 14280 SDValue Values[2] = {Div, Rem}; 14281 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 14282 } 14283 14284 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 14285 VT.getSimpleVT().SimpleTy); 14286 SDValue InChain = DAG.getEntryNode(); 14287 14288 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 14289 DAG.getContext(), 14290 Subtarget); 14291 14292 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14293 getPointerTy(DAG.getDataLayout())); 14294 14295 Type *RetTy = StructType::get(Ty, Ty); 14296 14297 if (Subtarget->isTargetWindows()) 14298 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 14299 14300 TargetLowering::CallLoweringInfo CLI(DAG); 14301 CLI.setDebugLoc(dl).setChain(InChain) 14302 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 14303 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 14304 14305 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 14306 return CallInfo.first; 14307 } 14308 14309 // Lowers REM using divmod helpers 14310 // see RTABI section 4.2/4.3 14311 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 14312 // Build return types (div and rem) 14313 std::vector<Type*> RetTyParams; 14314 Type *RetTyElement; 14315 14316 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 14317 default: llvm_unreachable("Unexpected request for libcall!"); 14318 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 14319 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 14320 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 14321 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 14322 } 14323 14324 RetTyParams.push_back(RetTyElement); 14325 RetTyParams.push_back(RetTyElement); 14326 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 14327 Type *RetTy = StructType::get(*DAG.getContext(), ret); 14328 14329 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 14330 SimpleTy); 14331 SDValue InChain = DAG.getEntryNode(); 14332 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 14333 Subtarget); 14334 bool isSigned = N->getOpcode() == ISD::SREM; 14335 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14336 getPointerTy(DAG.getDataLayout())); 14337 14338 if (Subtarget->isTargetWindows()) 14339 InChain = WinDBZCheckDenominator(DAG, N, InChain); 14340 14341 // Lower call 14342 CallLoweringInfo CLI(DAG); 14343 CLI.setChain(InChain) 14344 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 14345 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 14346 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 14347 14348 // Return second (rem) result operand (first contains div) 14349 SDNode *ResNode = CallResult.first.getNode(); 14350 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 14351 return ResNode->getOperand(1); 14352 } 14353 14354 SDValue 14355 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 14356 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 14357 SDLoc DL(Op); 14358 14359 // Get the inputs. 14360 SDValue Chain = Op.getOperand(0); 14361 SDValue Size = Op.getOperand(1); 14362 14363 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 14364 "no-stack-arg-probe")) { 14365 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 14366 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14367 Chain = SP.getValue(1); 14368 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 14369 if (Align) 14370 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 14371 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 14372 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 14373 SDValue Ops[2] = { SP, Chain }; 14374 return DAG.getMergeValues(Ops, DL); 14375 } 14376 14377 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 14378 DAG.getConstant(2, DL, MVT::i32)); 14379 14380 SDValue Flag; 14381 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 14382 Flag = Chain.getValue(1); 14383 14384 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 14385 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 14386 14387 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14388 Chain = NewSP.getValue(1); 14389 14390 SDValue Ops[2] = { NewSP, Chain }; 14391 return DAG.getMergeValues(Ops, DL); 14392 } 14393 14394 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 14395 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 14396 "Unexpected type for custom-lowering FP_EXTEND"); 14397 14398 RTLIB::Libcall LC; 14399 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 14400 14401 SDValue SrcVal = Op.getOperand(0); 14402 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14403 SDLoc(Op)).first; 14404 } 14405 14406 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 14407 assert(Op.getOperand(0).getValueType() == MVT::f64 && 14408 Subtarget->isFPOnlySP() && 14409 "Unexpected type for custom-lowering FP_ROUND"); 14410 14411 RTLIB::Libcall LC; 14412 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 14413 14414 SDValue SrcVal = Op.getOperand(0); 14415 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14416 SDLoc(Op)).first; 14417 } 14418 14419 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 14420 SelectionDAG &DAG) const { 14421 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 14422 MVT HalfT = MVT::i32; 14423 SDLoc dl(N); 14424 SDValue Hi, Lo, Tmp; 14425 14426 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 14427 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 14428 return ; 14429 14430 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 14431 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 14432 14433 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 14434 DAG.getConstant(0, dl, HalfT)); 14435 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 14436 DAG.getConstant(1, dl, HalfT)); 14437 14438 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 14439 DAG.getConstant(OpTypeBits - 1, dl, 14440 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 14441 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 14442 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 14443 SDValue(Lo.getNode(), 1)); 14444 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 14445 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 14446 14447 Results.push_back(Lo); 14448 Results.push_back(Hi); 14449 } 14450 14451 bool 14452 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14453 // The ARM target isn't yet aware of offsets. 14454 return false; 14455 } 14456 14457 bool ARM::isBitFieldInvertedMask(unsigned v) { 14458 if (v == 0xffffffff) 14459 return false; 14460 14461 // there can be 1's on either or both "outsides", all the "inside" 14462 // bits must be 0's 14463 return isShiftedMask_32(~v); 14464 } 14465 14466 /// isFPImmLegal - Returns true if the target can instruction select the 14467 /// specified FP immediate natively. If false, the legalizer will 14468 /// materialize the FP immediate as a load from a constant pool. 14469 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14470 bool ForCodeSize) const { 14471 if (!Subtarget->hasVFP3()) 14472 return false; 14473 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 14474 return ARM_AM::getFP16Imm(Imm) != -1; 14475 if (VT == MVT::f32) 14476 return ARM_AM::getFP32Imm(Imm) != -1; 14477 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 14478 return ARM_AM::getFP64Imm(Imm) != -1; 14479 return false; 14480 } 14481 14482 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 14483 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 14484 /// specified in the intrinsic calls. 14485 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14486 const CallInst &I, 14487 MachineFunction &MF, 14488 unsigned Intrinsic) const { 14489 switch (Intrinsic) { 14490 case Intrinsic::arm_neon_vld1: 14491 case Intrinsic::arm_neon_vld2: 14492 case Intrinsic::arm_neon_vld3: 14493 case Intrinsic::arm_neon_vld4: 14494 case Intrinsic::arm_neon_vld2lane: 14495 case Intrinsic::arm_neon_vld3lane: 14496 case Intrinsic::arm_neon_vld4lane: 14497 case Intrinsic::arm_neon_vld2dup: 14498 case Intrinsic::arm_neon_vld3dup: 14499 case Intrinsic::arm_neon_vld4dup: { 14500 Info.opc = ISD::INTRINSIC_W_CHAIN; 14501 // Conservatively set memVT to the entire set of vectors loaded. 14502 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14503 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14504 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14505 Info.ptrVal = I.getArgOperand(0); 14506 Info.offset = 0; 14507 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14508 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14509 // volatile loads with NEON intrinsics not supported 14510 Info.flags = MachineMemOperand::MOLoad; 14511 return true; 14512 } 14513 case Intrinsic::arm_neon_vld1x2: 14514 case Intrinsic::arm_neon_vld1x3: 14515 case Intrinsic::arm_neon_vld1x4: { 14516 Info.opc = ISD::INTRINSIC_W_CHAIN; 14517 // Conservatively set memVT to the entire set of vectors loaded. 14518 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14519 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14520 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14521 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 14522 Info.offset = 0; 14523 Info.align = 0; 14524 // volatile loads with NEON intrinsics not supported 14525 Info.flags = MachineMemOperand::MOLoad; 14526 return true; 14527 } 14528 case Intrinsic::arm_neon_vst1: 14529 case Intrinsic::arm_neon_vst2: 14530 case Intrinsic::arm_neon_vst3: 14531 case Intrinsic::arm_neon_vst4: 14532 case Intrinsic::arm_neon_vst2lane: 14533 case Intrinsic::arm_neon_vst3lane: 14534 case Intrinsic::arm_neon_vst4lane: { 14535 Info.opc = ISD::INTRINSIC_VOID; 14536 // Conservatively set memVT to the entire set of vectors stored. 14537 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14538 unsigned NumElts = 0; 14539 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14540 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14541 if (!ArgTy->isVectorTy()) 14542 break; 14543 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14544 } 14545 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14546 Info.ptrVal = I.getArgOperand(0); 14547 Info.offset = 0; 14548 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14549 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14550 // volatile stores with NEON intrinsics not supported 14551 Info.flags = MachineMemOperand::MOStore; 14552 return true; 14553 } 14554 case Intrinsic::arm_neon_vst1x2: 14555 case Intrinsic::arm_neon_vst1x3: 14556 case Intrinsic::arm_neon_vst1x4: { 14557 Info.opc = ISD::INTRINSIC_VOID; 14558 // Conservatively set memVT to the entire set of vectors stored. 14559 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14560 unsigned NumElts = 0; 14561 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14562 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14563 if (!ArgTy->isVectorTy()) 14564 break; 14565 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14566 } 14567 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14568 Info.ptrVal = I.getArgOperand(0); 14569 Info.offset = 0; 14570 Info.align = 0; 14571 // volatile stores with NEON intrinsics not supported 14572 Info.flags = MachineMemOperand::MOStore; 14573 return true; 14574 } 14575 case Intrinsic::arm_ldaex: 14576 case Intrinsic::arm_ldrex: { 14577 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14578 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 14579 Info.opc = ISD::INTRINSIC_W_CHAIN; 14580 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14581 Info.ptrVal = I.getArgOperand(0); 14582 Info.offset = 0; 14583 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14584 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14585 return true; 14586 } 14587 case Intrinsic::arm_stlex: 14588 case Intrinsic::arm_strex: { 14589 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14590 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 14591 Info.opc = ISD::INTRINSIC_W_CHAIN; 14592 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14593 Info.ptrVal = I.getArgOperand(1); 14594 Info.offset = 0; 14595 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14596 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14597 return true; 14598 } 14599 case Intrinsic::arm_stlexd: 14600 case Intrinsic::arm_strexd: 14601 Info.opc = ISD::INTRINSIC_W_CHAIN; 14602 Info.memVT = MVT::i64; 14603 Info.ptrVal = I.getArgOperand(2); 14604 Info.offset = 0; 14605 Info.align = 8; 14606 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14607 return true; 14608 14609 case Intrinsic::arm_ldaexd: 14610 case Intrinsic::arm_ldrexd: 14611 Info.opc = ISD::INTRINSIC_W_CHAIN; 14612 Info.memVT = MVT::i64; 14613 Info.ptrVal = I.getArgOperand(0); 14614 Info.offset = 0; 14615 Info.align = 8; 14616 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14617 return true; 14618 14619 default: 14620 break; 14621 } 14622 14623 return false; 14624 } 14625 14626 /// Returns true if it is beneficial to convert a load of a constant 14627 /// to just the constant itself. 14628 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14629 Type *Ty) const { 14630 assert(Ty->isIntegerTy()); 14631 14632 unsigned Bits = Ty->getPrimitiveSizeInBits(); 14633 if (Bits == 0 || Bits > 32) 14634 return false; 14635 return true; 14636 } 14637 14638 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 14639 unsigned Index) const { 14640 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 14641 return false; 14642 14643 return (Index == 0 || Index == ResVT.getVectorNumElements()); 14644 } 14645 14646 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 14647 ARM_MB::MemBOpt Domain) const { 14648 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14649 14650 // First, if the target has no DMB, see what fallback we can use. 14651 if (!Subtarget->hasDataBarrier()) { 14652 // Some ARMv6 cpus can support data barriers with an mcr instruction. 14653 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 14654 // here. 14655 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 14656 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 14657 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 14658 Builder.getInt32(0), Builder.getInt32(7), 14659 Builder.getInt32(10), Builder.getInt32(5)}; 14660 return Builder.CreateCall(MCR, args); 14661 } else { 14662 // Instead of using barriers, atomic accesses on these subtargets use 14663 // libcalls. 14664 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 14665 } 14666 } else { 14667 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 14668 // Only a full system barrier exists in the M-class architectures. 14669 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 14670 Constant *CDomain = Builder.getInt32(Domain); 14671 return Builder.CreateCall(DMB, CDomain); 14672 } 14673 } 14674 14675 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 14676 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 14677 Instruction *Inst, 14678 AtomicOrdering Ord) const { 14679 switch (Ord) { 14680 case AtomicOrdering::NotAtomic: 14681 case AtomicOrdering::Unordered: 14682 llvm_unreachable("Invalid fence: unordered/non-atomic"); 14683 case AtomicOrdering::Monotonic: 14684 case AtomicOrdering::Acquire: 14685 return nullptr; // Nothing to do 14686 case AtomicOrdering::SequentiallyConsistent: 14687 if (!Inst->hasAtomicStore()) 14688 return nullptr; // Nothing to do 14689 LLVM_FALLTHROUGH; 14690 case AtomicOrdering::Release: 14691 case AtomicOrdering::AcquireRelease: 14692 if (Subtarget->preferISHSTBarriers()) 14693 return makeDMB(Builder, ARM_MB::ISHST); 14694 // FIXME: add a comment with a link to documentation justifying this. 14695 else 14696 return makeDMB(Builder, ARM_MB::ISH); 14697 } 14698 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 14699 } 14700 14701 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 14702 Instruction *Inst, 14703 AtomicOrdering Ord) const { 14704 switch (Ord) { 14705 case AtomicOrdering::NotAtomic: 14706 case AtomicOrdering::Unordered: 14707 llvm_unreachable("Invalid fence: unordered/not-atomic"); 14708 case AtomicOrdering::Monotonic: 14709 case AtomicOrdering::Release: 14710 return nullptr; // Nothing to do 14711 case AtomicOrdering::Acquire: 14712 case AtomicOrdering::AcquireRelease: 14713 case AtomicOrdering::SequentiallyConsistent: 14714 return makeDMB(Builder, ARM_MB::ISH); 14715 } 14716 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 14717 } 14718 14719 // Loads and stores less than 64-bits are already atomic; ones above that 14720 // are doomed anyway, so defer to the default libcall and blame the OS when 14721 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14722 // anything for those. 14723 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 14724 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 14725 return (Size == 64) && !Subtarget->isMClass(); 14726 } 14727 14728 // Loads and stores less than 64-bits are already atomic; ones above that 14729 // are doomed anyway, so defer to the default libcall and blame the OS when 14730 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14731 // anything for those. 14732 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 14733 // guarantee, see DDI0406C ARM architecture reference manual, 14734 // sections A8.8.72-74 LDRD) 14735 TargetLowering::AtomicExpansionKind 14736 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 14737 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 14738 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 14739 : AtomicExpansionKind::None; 14740 } 14741 14742 // For the real atomic operations, we have ldrex/strex up to 32 bits, 14743 // and up to 64 bits on the non-M profiles 14744 TargetLowering::AtomicExpansionKind 14745 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 14746 if (AI->isFloatingPointOperation()) 14747 return AtomicExpansionKind::CmpXChg; 14748 14749 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 14750 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14751 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 14752 ? AtomicExpansionKind::LLSC 14753 : AtomicExpansionKind::None; 14754 } 14755 14756 TargetLowering::AtomicExpansionKind 14757 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 14758 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 14759 // implement cmpxchg without spilling. If the address being exchanged is also 14760 // on the stack and close enough to the spill slot, this can lead to a 14761 // situation where the monitor always gets cleared and the atomic operation 14762 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 14763 bool HasAtomicCmpXchg = 14764 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14765 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 14766 return AtomicExpansionKind::LLSC; 14767 return AtomicExpansionKind::None; 14768 } 14769 14770 bool ARMTargetLowering::shouldInsertFencesForAtomic( 14771 const Instruction *I) const { 14772 return InsertFencesForAtomic; 14773 } 14774 14775 // This has so far only been implemented for MachO. 14776 bool ARMTargetLowering::useLoadStackGuardNode() const { 14777 return Subtarget->isTargetMachO(); 14778 } 14779 14780 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 14781 unsigned &Cost) const { 14782 // If we do not have NEON, vector types are not natively supported. 14783 if (!Subtarget->hasNEON()) 14784 return false; 14785 14786 // Floating point values and vector values map to the same register file. 14787 // Therefore, although we could do a store extract of a vector type, this is 14788 // better to leave at float as we have more freedom in the addressing mode for 14789 // those. 14790 if (VectorTy->isFPOrFPVectorTy()) 14791 return false; 14792 14793 // If the index is unknown at compile time, this is very expensive to lower 14794 // and it is not possible to combine the store with the extract. 14795 if (!isa<ConstantInt>(Idx)) 14796 return false; 14797 14798 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 14799 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 14800 // We can do a store + vector extract on any vector that fits perfectly in a D 14801 // or Q register. 14802 if (BitWidth == 64 || BitWidth == 128) { 14803 Cost = 0; 14804 return true; 14805 } 14806 return false; 14807 } 14808 14809 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 14810 return Subtarget->hasV6T2Ops(); 14811 } 14812 14813 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 14814 return Subtarget->hasV6T2Ops(); 14815 } 14816 14817 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 14818 return !Subtarget->hasMinSize(); 14819 } 14820 14821 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 14822 AtomicOrdering Ord) const { 14823 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14824 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 14825 bool IsAcquire = isAcquireOrStronger(Ord); 14826 14827 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 14828 // intrinsic must return {i32, i32} and we have to recombine them into a 14829 // single i64 here. 14830 if (ValTy->getPrimitiveSizeInBits() == 64) { 14831 Intrinsic::ID Int = 14832 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 14833 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 14834 14835 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14836 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 14837 14838 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 14839 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 14840 if (!Subtarget->isLittle()) 14841 std::swap (Lo, Hi); 14842 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 14843 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 14844 return Builder.CreateOr( 14845 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 14846 } 14847 14848 Type *Tys[] = { Addr->getType() }; 14849 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 14850 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 14851 14852 return Builder.CreateTruncOrBitCast( 14853 Builder.CreateCall(Ldrex, Addr), 14854 cast<PointerType>(Addr->getType())->getElementType()); 14855 } 14856 14857 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 14858 IRBuilder<> &Builder) const { 14859 if (!Subtarget->hasV7Ops()) 14860 return; 14861 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14862 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 14863 } 14864 14865 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 14866 Value *Addr, 14867 AtomicOrdering Ord) const { 14868 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14869 bool IsRelease = isReleaseOrStronger(Ord); 14870 14871 // Since the intrinsics must have legal type, the i64 intrinsics take two 14872 // parameters: "i32, i32". We must marshal Val into the appropriate form 14873 // before the call. 14874 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 14875 Intrinsic::ID Int = 14876 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 14877 Function *Strex = Intrinsic::getDeclaration(M, Int); 14878 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 14879 14880 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 14881 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 14882 if (!Subtarget->isLittle()) 14883 std::swap(Lo, Hi); 14884 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14885 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 14886 } 14887 14888 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 14889 Type *Tys[] = { Addr->getType() }; 14890 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 14891 14892 return Builder.CreateCall( 14893 Strex, {Builder.CreateZExtOrBitCast( 14894 Val, Strex->getFunctionType()->getParamType(0)), 14895 Addr}); 14896 } 14897 14898 14899 bool ARMTargetLowering::alignLoopsWithOptSize() const { 14900 return Subtarget->isMClass(); 14901 } 14902 14903 /// A helper function for determining the number of interleaved accesses we 14904 /// will generate when lowering accesses of the given type. 14905 unsigned 14906 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 14907 const DataLayout &DL) const { 14908 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 14909 } 14910 14911 bool ARMTargetLowering::isLegalInterleavedAccessType( 14912 VectorType *VecTy, const DataLayout &DL) const { 14913 14914 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 14915 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 14916 14917 // Ensure the vector doesn't have f16 elements. Even though we could do an 14918 // i16 vldN, we can't hold the f16 vectors and will end up converting via 14919 // f32. 14920 if (VecTy->getElementType()->isHalfTy()) 14921 return false; 14922 14923 // Ensure the number of vector elements is greater than 1. 14924 if (VecTy->getNumElements() < 2) 14925 return false; 14926 14927 // Ensure the element type is legal. 14928 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 14929 return false; 14930 14931 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 14932 // 128 will be split into multiple interleaved accesses. 14933 return VecSize == 64 || VecSize % 128 == 0; 14934 } 14935 14936 /// Lower an interleaved load into a vldN intrinsic. 14937 /// 14938 /// E.g. Lower an interleaved load (Factor = 2): 14939 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 14940 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 14941 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 14942 /// 14943 /// Into: 14944 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 14945 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 14946 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 14947 bool ARMTargetLowering::lowerInterleavedLoad( 14948 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14949 ArrayRef<unsigned> Indices, unsigned Factor) const { 14950 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14951 "Invalid interleave factor"); 14952 assert(!Shuffles.empty() && "Empty shufflevector input"); 14953 assert(Shuffles.size() == Indices.size() && 14954 "Unmatched number of shufflevectors and indices"); 14955 14956 VectorType *VecTy = Shuffles[0]->getType(); 14957 Type *EltTy = VecTy->getVectorElementType(); 14958 14959 const DataLayout &DL = LI->getModule()->getDataLayout(); 14960 14961 // Skip if we do not have NEON and skip illegal vector types. We can 14962 // "legalize" wide vector types into multiple interleaved accesses as long as 14963 // the vector types are divisible by 128. 14964 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14965 return false; 14966 14967 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14968 14969 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14970 // load integer vectors first and then convert to pointer vectors. 14971 if (EltTy->isPointerTy()) 14972 VecTy = 14973 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14974 14975 IRBuilder<> Builder(LI); 14976 14977 // The base address of the load. 14978 Value *BaseAddr = LI->getPointerOperand(); 14979 14980 if (NumLoads > 1) { 14981 // If we're going to generate more than one load, reset the sub-vector type 14982 // to something legal. 14983 VecTy = VectorType::get(VecTy->getVectorElementType(), 14984 VecTy->getVectorNumElements() / NumLoads); 14985 14986 // We will compute the pointer operand of each load from the original base 14987 // address using GEPs. Cast the base address to a pointer to the scalar 14988 // element type. 14989 BaseAddr = Builder.CreateBitCast( 14990 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14991 LI->getPointerAddressSpace())); 14992 } 14993 14994 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14995 14996 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14997 Type *Tys[] = {VecTy, Int8Ptr}; 14998 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14999 Intrinsic::arm_neon_vld3, 15000 Intrinsic::arm_neon_vld4}; 15001 Function *VldnFunc = 15002 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 15003 15004 // Holds sub-vectors extracted from the load intrinsic return values. The 15005 // sub-vectors are associated with the shufflevector instructions they will 15006 // replace. 15007 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 15008 15009 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 15010 // If we're generating more than one load, compute the base address of 15011 // subsequent loads as an offset from the previous. 15012 if (LoadCount > 0) 15013 BaseAddr = 15014 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 15015 VecTy->getVectorNumElements() * Factor); 15016 15017 SmallVector<Value *, 2> Ops; 15018 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 15019 Ops.push_back(Builder.getInt32(LI->getAlignment())); 15020 15021 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 15022 15023 // Replace uses of each shufflevector with the corresponding vector loaded 15024 // by ldN. 15025 for (unsigned i = 0; i < Shuffles.size(); i++) { 15026 ShuffleVectorInst *SV = Shuffles[i]; 15027 unsigned Index = Indices[i]; 15028 15029 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 15030 15031 // Convert the integer vector to pointer vector if the element is pointer. 15032 if (EltTy->isPointerTy()) 15033 SubVec = Builder.CreateIntToPtr( 15034 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 15035 VecTy->getVectorNumElements())); 15036 15037 SubVecs[SV].push_back(SubVec); 15038 } 15039 } 15040 15041 // Replace uses of the shufflevector instructions with the sub-vectors 15042 // returned by the load intrinsic. If a shufflevector instruction is 15043 // associated with more than one sub-vector, those sub-vectors will be 15044 // concatenated into a single wide vector. 15045 for (ShuffleVectorInst *SVI : Shuffles) { 15046 auto &SubVec = SubVecs[SVI]; 15047 auto *WideVec = 15048 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 15049 SVI->replaceAllUsesWith(WideVec); 15050 } 15051 15052 return true; 15053 } 15054 15055 /// Lower an interleaved store into a vstN intrinsic. 15056 /// 15057 /// E.g. Lower an interleaved store (Factor = 3): 15058 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 15059 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 15060 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 15061 /// 15062 /// Into: 15063 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 15064 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 15065 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 15066 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 15067 /// 15068 /// Note that the new shufflevectors will be removed and we'll only generate one 15069 /// vst3 instruction in CodeGen. 15070 /// 15071 /// Example for a more general valid mask (Factor 3). Lower: 15072 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 15073 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 15074 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 15075 /// 15076 /// Into: 15077 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 15078 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 15079 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 15080 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 15081 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 15082 ShuffleVectorInst *SVI, 15083 unsigned Factor) const { 15084 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 15085 "Invalid interleave factor"); 15086 15087 VectorType *VecTy = SVI->getType(); 15088 assert(VecTy->getVectorNumElements() % Factor == 0 && 15089 "Invalid interleaved store"); 15090 15091 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 15092 Type *EltTy = VecTy->getVectorElementType(); 15093 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 15094 15095 const DataLayout &DL = SI->getModule()->getDataLayout(); 15096 15097 // Skip if we do not have NEON and skip illegal vector types. We can 15098 // "legalize" wide vector types into multiple interleaved accesses as long as 15099 // the vector types are divisible by 128. 15100 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 15101 return false; 15102 15103 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 15104 15105 Value *Op0 = SVI->getOperand(0); 15106 Value *Op1 = SVI->getOperand(1); 15107 IRBuilder<> Builder(SI); 15108 15109 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 15110 // vectors to integer vectors. 15111 if (EltTy->isPointerTy()) { 15112 Type *IntTy = DL.getIntPtrType(EltTy); 15113 15114 // Convert to the corresponding integer vector. 15115 Type *IntVecTy = 15116 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 15117 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 15118 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 15119 15120 SubVecTy = VectorType::get(IntTy, LaneLen); 15121 } 15122 15123 // The base address of the store. 15124 Value *BaseAddr = SI->getPointerOperand(); 15125 15126 if (NumStores > 1) { 15127 // If we're going to generate more than one store, reset the lane length 15128 // and sub-vector type to something legal. 15129 LaneLen /= NumStores; 15130 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 15131 15132 // We will compute the pointer operand of each store from the original base 15133 // address using GEPs. Cast the base address to a pointer to the scalar 15134 // element type. 15135 BaseAddr = Builder.CreateBitCast( 15136 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 15137 SI->getPointerAddressSpace())); 15138 } 15139 15140 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 15141 15142 auto Mask = SVI->getShuffleMask(); 15143 15144 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 15145 Type *Tys[] = {Int8Ptr, SubVecTy}; 15146 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 15147 Intrinsic::arm_neon_vst3, 15148 Intrinsic::arm_neon_vst4}; 15149 15150 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 15151 // If we generating more than one store, we compute the base address of 15152 // subsequent stores as an offset from the previous. 15153 if (StoreCount > 0) 15154 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 15155 BaseAddr, LaneLen * Factor); 15156 15157 SmallVector<Value *, 6> Ops; 15158 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 15159 15160 Function *VstNFunc = 15161 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 15162 15163 // Split the shufflevector operands into sub vectors for the new vstN call. 15164 for (unsigned i = 0; i < Factor; i++) { 15165 unsigned IdxI = StoreCount * LaneLen * Factor + i; 15166 if (Mask[IdxI] >= 0) { 15167 Ops.push_back(Builder.CreateShuffleVector( 15168 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 15169 } else { 15170 unsigned StartMask = 0; 15171 for (unsigned j = 1; j < LaneLen; j++) { 15172 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 15173 if (Mask[IdxJ * Factor + IdxI] >= 0) { 15174 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 15175 break; 15176 } 15177 } 15178 // Note: If all elements in a chunk are undefs, StartMask=0! 15179 // Note: Filling undef gaps with random elements is ok, since 15180 // those elements were being written anyway (with undefs). 15181 // In the case of all undefs we're defaulting to using elems from 0 15182 // Note: StartMask cannot be negative, it's checked in 15183 // isReInterleaveMask 15184 Ops.push_back(Builder.CreateShuffleVector( 15185 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 15186 } 15187 } 15188 15189 Ops.push_back(Builder.getInt32(SI->getAlignment())); 15190 Builder.CreateCall(VstNFunc, Ops); 15191 } 15192 return true; 15193 } 15194 15195 enum HABaseType { 15196 HA_UNKNOWN = 0, 15197 HA_FLOAT, 15198 HA_DOUBLE, 15199 HA_VECT64, 15200 HA_VECT128 15201 }; 15202 15203 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 15204 uint64_t &Members) { 15205 if (auto *ST = dyn_cast<StructType>(Ty)) { 15206 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 15207 uint64_t SubMembers = 0; 15208 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 15209 return false; 15210 Members += SubMembers; 15211 } 15212 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 15213 uint64_t SubMembers = 0; 15214 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 15215 return false; 15216 Members += SubMembers * AT->getNumElements(); 15217 } else if (Ty->isFloatTy()) { 15218 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 15219 return false; 15220 Members = 1; 15221 Base = HA_FLOAT; 15222 } else if (Ty->isDoubleTy()) { 15223 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 15224 return false; 15225 Members = 1; 15226 Base = HA_DOUBLE; 15227 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 15228 Members = 1; 15229 switch (Base) { 15230 case HA_FLOAT: 15231 case HA_DOUBLE: 15232 return false; 15233 case HA_VECT64: 15234 return VT->getBitWidth() == 64; 15235 case HA_VECT128: 15236 return VT->getBitWidth() == 128; 15237 case HA_UNKNOWN: 15238 switch (VT->getBitWidth()) { 15239 case 64: 15240 Base = HA_VECT64; 15241 return true; 15242 case 128: 15243 Base = HA_VECT128; 15244 return true; 15245 default: 15246 return false; 15247 } 15248 } 15249 } 15250 15251 return (Members > 0 && Members <= 4); 15252 } 15253 15254 /// Return the correct alignment for the current calling convention. 15255 unsigned 15256 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 15257 DataLayout DL) const { 15258 if (!ArgTy->isVectorTy()) 15259 return DL.getABITypeAlignment(ArgTy); 15260 15261 // Avoid over-aligning vector parameters. It would require realigning the 15262 // stack and waste space for no real benefit. 15263 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 15264 } 15265 15266 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 15267 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 15268 /// passing according to AAPCS rules. 15269 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 15270 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 15271 if (getEffectiveCallingConv(CallConv, isVarArg) != 15272 CallingConv::ARM_AAPCS_VFP) 15273 return false; 15274 15275 HABaseType Base = HA_UNKNOWN; 15276 uint64_t Members = 0; 15277 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 15278 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 15279 15280 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 15281 return IsHA || IsIntArray; 15282 } 15283 15284 unsigned ARMTargetLowering::getExceptionPointerRegister( 15285 const Constant *PersonalityFn) const { 15286 // Platforms which do not use SjLj EH may return values in these registers 15287 // via the personality function. 15288 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 15289 } 15290 15291 unsigned ARMTargetLowering::getExceptionSelectorRegister( 15292 const Constant *PersonalityFn) const { 15293 // Platforms which do not use SjLj EH may return values in these registers 15294 // via the personality function. 15295 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 15296 } 15297 15298 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15299 // Update IsSplitCSR in ARMFunctionInfo. 15300 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 15301 AFI->setIsSplitCSR(true); 15302 } 15303 15304 void ARMTargetLowering::insertCopiesSplitCSR( 15305 MachineBasicBlock *Entry, 15306 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15307 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 15308 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15309 if (!IStart) 15310 return; 15311 15312 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 15313 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15314 MachineBasicBlock::iterator MBBI = Entry->begin(); 15315 for (const MCPhysReg *I = IStart; *I; ++I) { 15316 const TargetRegisterClass *RC = nullptr; 15317 if (ARM::GPRRegClass.contains(*I)) 15318 RC = &ARM::GPRRegClass; 15319 else if (ARM::DPRRegClass.contains(*I)) 15320 RC = &ARM::DPRRegClass; 15321 else 15322 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15323 15324 unsigned NewVR = MRI->createVirtualRegister(RC); 15325 // Create copy from CSR to a virtual register. 15326 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15327 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15328 // nounwind. If we want to generalize this later, we may need to emit 15329 // CFI pseudo-instructions. 15330 assert(Entry->getParent()->getFunction().hasFnAttribute( 15331 Attribute::NoUnwind) && 15332 "Function should be nounwind in insertCopiesSplitCSR!"); 15333 Entry->addLiveIn(*I); 15334 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15335 .addReg(*I); 15336 15337 // Insert the copy-back instructions right before the terminator. 15338 for (auto *Exit : Exits) 15339 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15340 TII->get(TargetOpcode::COPY), *I) 15341 .addReg(NewVR); 15342 } 15343 } 15344 15345 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 15346 MF.getFrameInfo().computeMaxCallFrameSize(MF); 15347 TargetLoweringBase::finalizeLowering(MF); 15348 } 15349