1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMCallingConv.h" 18 #include "ARMConstantPoolValue.h" 19 #include "ARMISelLowering.h" 20 #include "ARMMachineFunctionInfo.h" 21 #include "ARMPerfectShuffle.h" 22 #include "ARMRegisterInfo.h" 23 #include "ARMSelectionDAGInfo.h" 24 #include "ARMSubtarget.h" 25 #include "MCTargetDesc/ARMAddressingModes.h" 26 #include "MCTargetDesc/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/SmallPtrSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/ADT/StringRef.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/MachineValueType.h" 56 #include "llvm/CodeGen/RuntimeLibcalls.h" 57 #include "llvm/CodeGen/SelectionDAG.h" 58 #include "llvm/CodeGen/SelectionDAGNodes.h" 59 #include "llvm/CodeGen/ValueTypes.h" 60 #include "llvm/IR/Attributes.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugLoc.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/Function.h" 69 #include "llvm/IR/GlobalAlias.h" 70 #include "llvm/IR/GlobalValue.h" 71 #include "llvm/IR/GlobalVariable.h" 72 #include "llvm/IR/IRBuilder.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/Instruction.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/Module.h" 79 #include "llvm/IR/Type.h" 80 #include "llvm/IR/User.h" 81 #include "llvm/IR/Value.h" 82 #include "llvm/MC/MCInstrDesc.h" 83 #include "llvm/MC/MCInstrItineraries.h" 84 #include "llvm/MC/MCRegisterInfo.h" 85 #include "llvm/MC/MCSchedule.h" 86 #include "llvm/Support/AtomicOrdering.h" 87 #include "llvm/Support/BranchProbability.h" 88 #include "llvm/Support/Casting.h" 89 #include "llvm/Support/CodeGen.h" 90 #include "llvm/Support/CommandLine.h" 91 #include "llvm/Support/Compiler.h" 92 #include "llvm/Support/Debug.h" 93 #include "llvm/Support/ErrorHandling.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetInstrInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include <algorithm> 100 #include <cassert> 101 #include <cstdint> 102 #include <cstdlib> 103 #include <iterator> 104 #include <limits> 105 #include <tuple> 106 #include <string> 107 #include <utility> 108 #include <vector> 109 110 using namespace llvm; 111 112 #define DEBUG_TYPE "arm-isel" 113 114 STATISTIC(NumTailCalls, "Number of tail calls"); 115 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 116 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 117 STATISTIC(NumConstpoolPromoted, 118 "Number of constants with their storage promoted into constant pools"); 119 120 static cl::opt<bool> 121 ARMInterworking("arm-interworking", cl::Hidden, 122 cl::desc("Enable / disable ARM interworking (for debugging only)"), 123 cl::init(true)); 124 125 static cl::opt<bool> EnableConstpoolPromotion( 126 "arm-promote-constant", cl::Hidden, 127 cl::desc("Enable / disable promotion of unnamed_addr constants into " 128 "constant pools"), 129 cl::init(true)); 130 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 131 "arm-promote-constant-max-size", cl::Hidden, 132 cl::desc("Maximum size of constant to promote into a constant pool"), 133 cl::init(64)); 134 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 135 "arm-promote-constant-max-total", cl::Hidden, 136 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 137 cl::init(128)); 138 139 // The APCS parameter registers. 140 static const MCPhysReg GPRArgRegs[] = { 141 ARM::R0, ARM::R1, ARM::R2, ARM::R3 142 }; 143 144 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 145 MVT PromotedBitwiseVT) { 146 if (VT != PromotedLdStVT) { 147 setOperationAction(ISD::LOAD, VT, Promote); 148 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 149 150 setOperationAction(ISD::STORE, VT, Promote); 151 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 152 } 153 154 MVT ElemTy = VT.getVectorElementType(); 155 if (ElemTy != MVT::f64) 156 setOperationAction(ISD::SETCC, VT, Custom); 157 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 158 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 159 if (ElemTy == MVT::i32) { 160 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 161 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 162 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 163 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 164 } else { 165 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 166 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 167 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 168 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 169 } 170 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 171 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 172 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 173 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 174 setOperationAction(ISD::SELECT, VT, Expand); 175 setOperationAction(ISD::SELECT_CC, VT, Expand); 176 setOperationAction(ISD::VSELECT, VT, Expand); 177 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 178 if (VT.isInteger()) { 179 setOperationAction(ISD::SHL, VT, Custom); 180 setOperationAction(ISD::SRA, VT, Custom); 181 setOperationAction(ISD::SRL, VT, Custom); 182 } 183 184 // Promote all bit-wise operations. 185 if (VT.isInteger() && VT != PromotedBitwiseVT) { 186 setOperationAction(ISD::AND, VT, Promote); 187 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 188 setOperationAction(ISD::OR, VT, Promote); 189 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 190 setOperationAction(ISD::XOR, VT, Promote); 191 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 192 } 193 194 // Neon does not support vector divide/remainder operations. 195 setOperationAction(ISD::SDIV, VT, Expand); 196 setOperationAction(ISD::UDIV, VT, Expand); 197 setOperationAction(ISD::FDIV, VT, Expand); 198 setOperationAction(ISD::SREM, VT, Expand); 199 setOperationAction(ISD::UREM, VT, Expand); 200 setOperationAction(ISD::FREM, VT, Expand); 201 202 if (!VT.isFloatingPoint() && 203 VT != MVT::v2i64 && VT != MVT::v1i64) 204 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 205 setOperationAction(Opcode, VT, Legal); 206 } 207 208 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 209 addRegisterClass(VT, &ARM::DPRRegClass); 210 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 211 } 212 213 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 214 addRegisterClass(VT, &ARM::DPairRegClass); 215 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 216 } 217 218 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 219 const ARMSubtarget &STI) 220 : TargetLowering(TM), Subtarget(&STI) { 221 RegInfo = Subtarget->getRegisterInfo(); 222 Itins = Subtarget->getInstrItineraryData(); 223 224 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 225 226 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 227 !Subtarget->isTargetWatchOS()) { 228 const auto &E = Subtarget->getTargetTriple().getEnvironment(); 229 230 bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF || 231 E == Triple::MuslEABIHF; 232 // Windows is a special case. Technically, we will replace all of the "GNU" 233 // calls with calls to MSVCRT if appropriate and adjust the calling 234 // convention then. 235 IsHFTarget = IsHFTarget || Subtarget->isTargetWindows(); 236 237 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 238 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 239 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 240 : CallingConv::ARM_AAPCS); 241 } 242 243 if (Subtarget->isTargetMachO()) { 244 // Uses VFP for Thumb libfuncs if available. 245 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 246 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 247 static const struct { 248 const RTLIB::Libcall Op; 249 const char * const Name; 250 const ISD::CondCode Cond; 251 } LibraryCalls[] = { 252 // Single-precision floating-point arithmetic. 253 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 254 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 255 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 256 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 257 258 // Double-precision floating-point arithmetic. 259 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 260 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 261 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 262 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 263 264 // Single-precision comparisons. 265 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 266 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 267 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 268 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 269 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 270 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 271 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 272 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 273 274 // Double-precision comparisons. 275 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 276 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 277 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 278 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 279 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 280 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 281 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 282 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 283 284 // Floating-point to integer conversions. 285 // i64 conversions are done via library routines even when generating VFP 286 // instructions, so use the same ones. 287 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 288 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 289 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 290 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 291 292 // Conversions between floating types. 293 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 294 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 295 296 // Integer to floating-point conversions. 297 // i64 conversions are done via library routines even when generating VFP 298 // instructions, so use the same ones. 299 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 300 // e.g., __floatunsidf vs. __floatunssidfvfp. 301 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 302 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 303 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 304 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 305 }; 306 307 for (const auto &LC : LibraryCalls) { 308 setLibcallName(LC.Op, LC.Name); 309 if (LC.Cond != ISD::SETCC_INVALID) 310 setCmpLibcallCC(LC.Op, LC.Cond); 311 } 312 } 313 314 // Set the correct calling convention for ARMv7k WatchOS. It's just 315 // AAPCS_VFP for functions as simple as libcalls. 316 if (Subtarget->isTargetWatchABI()) { 317 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 318 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 319 } 320 } 321 322 // These libcalls are not available in 32-bit. 323 setLibcallName(RTLIB::SHL_I128, nullptr); 324 setLibcallName(RTLIB::SRL_I128, nullptr); 325 setLibcallName(RTLIB::SRA_I128, nullptr); 326 327 // RTLIB 328 if (Subtarget->isAAPCS_ABI() && 329 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 330 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 331 static const struct { 332 const RTLIB::Libcall Op; 333 const char * const Name; 334 const CallingConv::ID CC; 335 const ISD::CondCode Cond; 336 } LibraryCalls[] = { 337 // Double-precision floating-point arithmetic helper functions 338 // RTABI chapter 4.1.2, Table 2 339 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 344 // Double-precision floating-point comparison helper functions 345 // RTABI chapter 4.1.2, Table 3 346 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 347 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 348 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 349 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 350 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 351 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 352 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 353 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 354 355 // Single-precision floating-point arithmetic helper functions 356 // RTABI chapter 4.1.2, Table 4 357 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 358 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 359 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 360 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 361 362 // Single-precision floating-point comparison helper functions 363 // RTABI chapter 4.1.2, Table 5 364 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 365 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 366 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 367 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 368 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 369 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 370 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 371 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 372 373 // Floating-point to integer conversions. 374 // RTABI chapter 4.1.2, Table 6 375 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 376 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 377 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 378 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 382 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 383 384 // Conversions between floating types. 385 // RTABI chapter 4.1.2, Table 7 386 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 388 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 389 390 // Integer to floating-point conversions. 391 // RTABI chapter 4.1.2, Table 8 392 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 393 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 394 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 395 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 399 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 400 401 // Long long helper functions 402 // RTABI chapter 4.2, Table 9 403 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 406 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 407 408 // Integer division functions 409 // RTABI chapter 4.3.1 410 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 411 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 412 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 413 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 414 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 415 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 416 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 417 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 418 }; 419 420 for (const auto &LC : LibraryCalls) { 421 setLibcallName(LC.Op, LC.Name); 422 setLibcallCallingConv(LC.Op, LC.CC); 423 if (LC.Cond != ISD::SETCC_INVALID) 424 setCmpLibcallCC(LC.Op, LC.Cond); 425 } 426 427 // EABI dependent RTLIB 428 if (TM.Options.EABIVersion == EABI::EABI4 || 429 TM.Options.EABIVersion == EABI::EABI5) { 430 static const struct { 431 const RTLIB::Libcall Op; 432 const char *const Name; 433 const CallingConv::ID CC; 434 const ISD::CondCode Cond; 435 } MemOpsLibraryCalls[] = { 436 // Memory operations 437 // RTABI chapter 4.3.4 438 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 439 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 440 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 441 }; 442 443 for (const auto &LC : MemOpsLibraryCalls) { 444 setLibcallName(LC.Op, LC.Name); 445 setLibcallCallingConv(LC.Op, LC.CC); 446 if (LC.Cond != ISD::SETCC_INVALID) 447 setCmpLibcallCC(LC.Op, LC.Cond); 448 } 449 } 450 } 451 452 if (Subtarget->isTargetWindows()) { 453 static const struct { 454 const RTLIB::Libcall Op; 455 const char * const Name; 456 const CallingConv::ID CC; 457 } LibraryCalls[] = { 458 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 459 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 460 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 461 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 462 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 463 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 464 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 465 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 466 }; 467 468 for (const auto &LC : LibraryCalls) { 469 setLibcallName(LC.Op, LC.Name); 470 setLibcallCallingConv(LC.Op, LC.CC); 471 } 472 } 473 474 // Use divmod compiler-rt calls for iOS 5.0 and later. 475 if (Subtarget->isTargetWatchOS() || 476 (Subtarget->isTargetIOS() && 477 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 478 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 479 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 480 } 481 482 // The half <-> float conversion functions are always soft-float on 483 // non-watchos platforms, but are needed for some targets which use a 484 // hard-float calling convention by default. 485 if (!Subtarget->isTargetWatchABI()) { 486 if (Subtarget->isAAPCS_ABI()) { 487 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 488 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 489 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 490 } else { 491 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 492 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 493 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 494 } 495 } 496 497 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 498 // a __gnu_ prefix (which is the default). 499 if (Subtarget->isTargetAEABI()) { 500 static const struct { 501 const RTLIB::Libcall Op; 502 const char * const Name; 503 const CallingConv::ID CC; 504 } LibraryCalls[] = { 505 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 506 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 507 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 508 }; 509 510 for (const auto &LC : LibraryCalls) { 511 setLibcallName(LC.Op, LC.Name); 512 setLibcallCallingConv(LC.Op, LC.CC); 513 } 514 } 515 516 if (Subtarget->isThumb1Only()) 517 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 518 else 519 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 520 521 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 522 !Subtarget->isThumb1Only()) { 523 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 524 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 525 } 526 527 for (MVT VT : MVT::vector_valuetypes()) { 528 for (MVT InnerVT : MVT::vector_valuetypes()) { 529 setTruncStoreAction(VT, InnerVT, Expand); 530 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 531 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 532 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 533 } 534 535 setOperationAction(ISD::MULHS, VT, Expand); 536 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 537 setOperationAction(ISD::MULHU, VT, Expand); 538 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 539 540 setOperationAction(ISD::BSWAP, VT, Expand); 541 } 542 543 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 544 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 545 546 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 547 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 548 549 if (Subtarget->hasNEON()) { 550 addDRTypeForNEON(MVT::v2f32); 551 addDRTypeForNEON(MVT::v8i8); 552 addDRTypeForNEON(MVT::v4i16); 553 addDRTypeForNEON(MVT::v2i32); 554 addDRTypeForNEON(MVT::v1i64); 555 556 addQRTypeForNEON(MVT::v4f32); 557 addQRTypeForNEON(MVT::v2f64); 558 addQRTypeForNEON(MVT::v16i8); 559 addQRTypeForNEON(MVT::v8i16); 560 addQRTypeForNEON(MVT::v4i32); 561 addQRTypeForNEON(MVT::v2i64); 562 563 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 564 // neither Neon nor VFP support any arithmetic operations on it. 565 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 566 // supported for v4f32. 567 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 568 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 569 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 570 // FIXME: Code duplication: FDIV and FREM are expanded always, see 571 // ARMTargetLowering::addTypeForNEON method for details. 572 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 573 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 574 // FIXME: Create unittest. 575 // In another words, find a way when "copysign" appears in DAG with vector 576 // operands. 577 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 578 // FIXME: Code duplication: SETCC has custom operation action, see 579 // ARMTargetLowering::addTypeForNEON method for details. 580 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 581 // FIXME: Create unittest for FNEG and for FABS. 582 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 583 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 584 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 585 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 586 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 587 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 588 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 589 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 590 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 591 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 592 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 593 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 594 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 595 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 596 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 597 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 598 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 599 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 600 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 601 602 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 603 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 604 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 605 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 606 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 607 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 608 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 609 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 610 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 611 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 612 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 613 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 614 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 615 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 616 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 617 618 // Mark v2f32 intrinsics. 619 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 620 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 621 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 622 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 623 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 624 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 625 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 626 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 627 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 628 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 629 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 630 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 631 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 632 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 633 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 634 635 // Neon does not support some operations on v1i64 and v2i64 types. 636 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 637 // Custom handling for some quad-vector types to detect VMULL. 638 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 639 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 640 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 641 // Custom handling for some vector types to avoid expensive expansions 642 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 643 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 644 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 645 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 646 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 647 // a destination type that is wider than the source, and nor does 648 // it have a FP_TO_[SU]INT instruction with a narrower destination than 649 // source. 650 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 651 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 652 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 653 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 654 655 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 656 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 657 658 // NEON does not have single instruction CTPOP for vectors with element 659 // types wider than 8-bits. However, custom lowering can leverage the 660 // v8i8/v16i8 vcnt instruction. 661 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 662 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 663 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 664 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 665 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 666 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 667 668 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 669 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 670 671 // NEON does not have single instruction CTTZ for vectors. 672 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 673 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 674 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 675 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 676 677 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 678 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 679 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 680 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 681 682 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 686 687 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 688 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 691 692 // NEON only has FMA instructions as of VFP4. 693 if (!Subtarget->hasVFP4()) { 694 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 695 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 696 } 697 698 setTargetDAGCombine(ISD::INTRINSIC_VOID); 699 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 700 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 701 setTargetDAGCombine(ISD::SHL); 702 setTargetDAGCombine(ISD::SRL); 703 setTargetDAGCombine(ISD::SRA); 704 setTargetDAGCombine(ISD::SIGN_EXTEND); 705 setTargetDAGCombine(ISD::ZERO_EXTEND); 706 setTargetDAGCombine(ISD::ANY_EXTEND); 707 setTargetDAGCombine(ISD::BUILD_VECTOR); 708 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 709 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 710 setTargetDAGCombine(ISD::STORE); 711 setTargetDAGCombine(ISD::FP_TO_SINT); 712 setTargetDAGCombine(ISD::FP_TO_UINT); 713 setTargetDAGCombine(ISD::FDIV); 714 setTargetDAGCombine(ISD::LOAD); 715 716 // It is legal to extload from v4i8 to v4i16 or v4i32. 717 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 718 MVT::v2i32}) { 719 for (MVT VT : MVT::integer_vector_valuetypes()) { 720 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 721 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 722 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 723 } 724 } 725 } 726 727 if (Subtarget->isFPOnlySP()) { 728 // When targeting a floating-point unit with only single-precision 729 // operations, f64 is legal for the few double-precision instructions which 730 // are present However, no double-precision operations other than moves, 731 // loads and stores are provided by the hardware. 732 setOperationAction(ISD::FADD, MVT::f64, Expand); 733 setOperationAction(ISD::FSUB, MVT::f64, Expand); 734 setOperationAction(ISD::FMUL, MVT::f64, Expand); 735 setOperationAction(ISD::FMA, MVT::f64, Expand); 736 setOperationAction(ISD::FDIV, MVT::f64, Expand); 737 setOperationAction(ISD::FREM, MVT::f64, Expand); 738 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 739 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 740 setOperationAction(ISD::FNEG, MVT::f64, Expand); 741 setOperationAction(ISD::FABS, MVT::f64, Expand); 742 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 743 setOperationAction(ISD::FSIN, MVT::f64, Expand); 744 setOperationAction(ISD::FCOS, MVT::f64, Expand); 745 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 746 setOperationAction(ISD::FPOW, MVT::f64, Expand); 747 setOperationAction(ISD::FLOG, MVT::f64, Expand); 748 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 749 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 750 setOperationAction(ISD::FEXP, MVT::f64, Expand); 751 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 752 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 753 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 754 setOperationAction(ISD::FRINT, MVT::f64, Expand); 755 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 756 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 757 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 758 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 759 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 760 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 761 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 762 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 763 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 764 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 765 } 766 767 computeRegisterProperties(Subtarget->getRegisterInfo()); 768 769 // ARM does not have floating-point extending loads. 770 for (MVT VT : MVT::fp_valuetypes()) { 771 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 772 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 773 } 774 775 // ... or truncating stores 776 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 777 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 778 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 779 780 // ARM does not have i1 sign extending load. 781 for (MVT VT : MVT::integer_valuetypes()) 782 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 783 784 // ARM supports all 4 flavors of integer indexed load / store. 785 if (!Subtarget->isThumb1Only()) { 786 for (unsigned im = (unsigned)ISD::PRE_INC; 787 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 788 setIndexedLoadAction(im, MVT::i1, Legal); 789 setIndexedLoadAction(im, MVT::i8, Legal); 790 setIndexedLoadAction(im, MVT::i16, Legal); 791 setIndexedLoadAction(im, MVT::i32, Legal); 792 setIndexedStoreAction(im, MVT::i1, Legal); 793 setIndexedStoreAction(im, MVT::i8, Legal); 794 setIndexedStoreAction(im, MVT::i16, Legal); 795 setIndexedStoreAction(im, MVT::i32, Legal); 796 } 797 } else { 798 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 799 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 800 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 801 } 802 803 setOperationAction(ISD::SADDO, MVT::i32, Custom); 804 setOperationAction(ISD::UADDO, MVT::i32, Custom); 805 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 806 setOperationAction(ISD::USUBO, MVT::i32, Custom); 807 808 // i64 operation support. 809 setOperationAction(ISD::MUL, MVT::i64, Expand); 810 setOperationAction(ISD::MULHU, MVT::i32, Expand); 811 if (Subtarget->isThumb1Only()) { 812 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 813 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 814 } 815 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 816 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 817 setOperationAction(ISD::MULHS, MVT::i32, Expand); 818 819 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 820 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 821 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 822 setOperationAction(ISD::SRL, MVT::i64, Custom); 823 setOperationAction(ISD::SRA, MVT::i64, Custom); 824 825 setOperationAction(ISD::ADDC, MVT::i32, Custom); 826 setOperationAction(ISD::ADDE, MVT::i32, Custom); 827 setOperationAction(ISD::SUBC, MVT::i32, Custom); 828 setOperationAction(ISD::SUBE, MVT::i32, Custom); 829 830 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 831 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 832 833 // ARM does not have ROTL. 834 setOperationAction(ISD::ROTL, MVT::i32, Expand); 835 for (MVT VT : MVT::vector_valuetypes()) { 836 setOperationAction(ISD::ROTL, VT, Expand); 837 setOperationAction(ISD::ROTR, VT, Expand); 838 } 839 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 840 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 841 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 842 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 843 844 // @llvm.readcyclecounter requires the Performance Monitors extension. 845 // Default to the 0 expansion on unsupported platforms. 846 // FIXME: Technically there are older ARM CPUs that have 847 // implementation-specific ways of obtaining this information. 848 if (Subtarget->hasPerfMon()) 849 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 850 851 // Only ARMv6 has BSWAP. 852 if (!Subtarget->hasV6Ops()) 853 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 854 855 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 856 : Subtarget->hasDivideInARMMode(); 857 if (!hasDivide) { 858 // These are expanded into libcalls if the cpu doesn't have HW divider. 859 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 860 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 861 } 862 863 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 864 setOperationAction(ISD::SDIV, MVT::i32, Custom); 865 setOperationAction(ISD::UDIV, MVT::i32, Custom); 866 867 setOperationAction(ISD::SDIV, MVT::i64, Custom); 868 setOperationAction(ISD::UDIV, MVT::i64, Custom); 869 } 870 871 setOperationAction(ISD::SREM, MVT::i32, Expand); 872 setOperationAction(ISD::UREM, MVT::i32, Expand); 873 874 // Register based DivRem for AEABI (RTABI 4.2) 875 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 876 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 877 Subtarget->isTargetWindows()) { 878 setOperationAction(ISD::SREM, MVT::i64, Custom); 879 setOperationAction(ISD::UREM, MVT::i64, Custom); 880 HasStandaloneRem = false; 881 882 if (Subtarget->isTargetWindows()) { 883 const struct { 884 const RTLIB::Libcall Op; 885 const char * const Name; 886 const CallingConv::ID CC; 887 } LibraryCalls[] = { 888 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 889 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 890 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 891 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 892 893 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 894 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 895 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 896 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 897 }; 898 899 for (const auto &LC : LibraryCalls) { 900 setLibcallName(LC.Op, LC.Name); 901 setLibcallCallingConv(LC.Op, LC.CC); 902 } 903 } else { 904 const struct { 905 const RTLIB::Libcall Op; 906 const char * const Name; 907 const CallingConv::ID CC; 908 } LibraryCalls[] = { 909 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 910 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 911 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 912 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 913 914 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 915 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 916 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 917 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 918 }; 919 920 for (const auto &LC : LibraryCalls) { 921 setLibcallName(LC.Op, LC.Name); 922 setLibcallCallingConv(LC.Op, LC.CC); 923 } 924 } 925 926 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 927 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 928 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 929 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 930 } else { 931 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 932 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 933 } 934 935 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 936 for (auto &VT : {MVT::f32, MVT::f64}) 937 setOperationAction(ISD::FPOWI, VT, Custom); 938 939 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 940 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 941 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 942 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 943 944 setOperationAction(ISD::TRAP, MVT::Other, Legal); 945 946 // Use the default implementation. 947 setOperationAction(ISD::VASTART, MVT::Other, Custom); 948 setOperationAction(ISD::VAARG, MVT::Other, Expand); 949 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 950 setOperationAction(ISD::VAEND, MVT::Other, Expand); 951 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 952 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 953 954 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 955 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 956 else 957 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 958 959 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 960 // the default expansion. 961 InsertFencesForAtomic = false; 962 if (Subtarget->hasAnyDataBarrier() && 963 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 964 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 965 // to ldrex/strex loops already. 966 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 967 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 968 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 969 970 // On v8, we have particularly efficient implementations of atomic fences 971 // if they can be combined with nearby atomic loads and stores. 972 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 973 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 974 InsertFencesForAtomic = true; 975 } 976 } else { 977 // If there's anything we can use as a barrier, go through custom lowering 978 // for ATOMIC_FENCE. 979 // If target has DMB in thumb, Fences can be inserted. 980 if (Subtarget->hasDataBarrier()) 981 InsertFencesForAtomic = true; 982 983 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 984 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 985 986 // Set them all for expansion, which will force libcalls. 987 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 988 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 989 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 990 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 991 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 992 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 993 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 994 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 995 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 996 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 997 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 998 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 999 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1000 // Unordered/Monotonic case. 1001 if (!InsertFencesForAtomic) { 1002 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1003 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1004 } 1005 } 1006 1007 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1008 1009 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1010 if (!Subtarget->hasV6Ops()) { 1011 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1012 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1013 } 1014 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1015 1016 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1017 !Subtarget->isThumb1Only()) { 1018 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1019 // iff target supports vfp2. 1020 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1021 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1022 } 1023 1024 // We want to custom lower some of our intrinsics. 1025 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1026 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1027 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1028 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1029 if (Subtarget->useSjLjEH()) 1030 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1031 1032 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1033 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1034 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1035 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1036 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1037 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1038 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1039 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1040 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1041 1042 // Thumb-1 cannot currently select ARMISD::SUBE. 1043 if (!Subtarget->isThumb1Only()) 1044 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1045 1046 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 1047 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1048 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1049 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1050 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1051 1052 // We don't support sin/cos/fmod/copysign/pow 1053 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1054 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1055 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1056 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1057 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1058 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1059 setOperationAction(ISD::FREM, MVT::f64, Expand); 1060 setOperationAction(ISD::FREM, MVT::f32, Expand); 1061 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1062 !Subtarget->isThumb1Only()) { 1063 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1064 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1065 } 1066 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1067 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1068 1069 if (!Subtarget->hasVFP4()) { 1070 setOperationAction(ISD::FMA, MVT::f64, Expand); 1071 setOperationAction(ISD::FMA, MVT::f32, Expand); 1072 } 1073 1074 // Various VFP goodness 1075 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1076 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1077 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1078 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1079 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1080 } 1081 1082 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1083 if (!Subtarget->hasFP16()) { 1084 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1085 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1086 } 1087 } 1088 1089 // Combine sin / cos into one node or libcall if possible. 1090 if (Subtarget->hasSinCos()) { 1091 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1092 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1093 if (Subtarget->isTargetWatchABI()) { 1094 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 1095 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 1096 } 1097 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 1098 // For iOS, we don't want to the normal expansion of a libcall to 1099 // sincos. We want to issue a libcall to __sincos_stret. 1100 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1101 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1102 } 1103 } 1104 1105 // FP-ARMv8 implements a lot of rounding-like FP operations. 1106 if (Subtarget->hasFPARMv8()) { 1107 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1108 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1109 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1110 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1111 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1112 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1113 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1114 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1115 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1116 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1117 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1118 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1119 1120 if (!Subtarget->isFPOnlySP()) { 1121 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1122 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1123 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1124 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1125 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1126 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1127 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1128 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1129 } 1130 } 1131 1132 if (Subtarget->hasNEON()) { 1133 // vmin and vmax aren't available in a scalar form, so we use 1134 // a NEON instruction with an undef lane instead. 1135 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1136 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1137 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1138 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1139 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1140 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1141 } 1142 1143 // We have target-specific dag combine patterns for the following nodes: 1144 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1145 setTargetDAGCombine(ISD::ADD); 1146 setTargetDAGCombine(ISD::SUB); 1147 setTargetDAGCombine(ISD::MUL); 1148 setTargetDAGCombine(ISD::AND); 1149 setTargetDAGCombine(ISD::OR); 1150 setTargetDAGCombine(ISD::XOR); 1151 1152 if (Subtarget->hasV6Ops()) 1153 setTargetDAGCombine(ISD::SRL); 1154 1155 setStackPointerRegisterToSaveRestore(ARM::SP); 1156 1157 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1158 !Subtarget->hasVFP2()) 1159 setSchedulingPreference(Sched::RegPressure); 1160 else 1161 setSchedulingPreference(Sched::Hybrid); 1162 1163 //// temporary - rewrite interface to use type 1164 MaxStoresPerMemset = 8; 1165 MaxStoresPerMemsetOptSize = 4; 1166 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1167 MaxStoresPerMemcpyOptSize = 2; 1168 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1169 MaxStoresPerMemmoveOptSize = 2; 1170 1171 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1172 // are at least 4 bytes aligned. 1173 setMinStackArgumentAlignment(4); 1174 1175 // Prefer likely predicted branches to selects on out-of-order cores. 1176 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1177 1178 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1179 } 1180 1181 bool ARMTargetLowering::useSoftFloat() const { 1182 return Subtarget->useSoftFloat(); 1183 } 1184 1185 // FIXME: It might make sense to define the representative register class as the 1186 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1187 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1188 // SPR's representative would be DPR_VFP2. This should work well if register 1189 // pressure tracking were modified such that a register use would increment the 1190 // pressure of the register class's representative and all of it's super 1191 // classes' representatives transitively. We have not implemented this because 1192 // of the difficulty prior to coalescing of modeling operand register classes 1193 // due to the common occurrence of cross class copies and subregister insertions 1194 // and extractions. 1195 std::pair<const TargetRegisterClass *, uint8_t> 1196 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1197 MVT VT) const { 1198 const TargetRegisterClass *RRC = nullptr; 1199 uint8_t Cost = 1; 1200 switch (VT.SimpleTy) { 1201 default: 1202 return TargetLowering::findRepresentativeClass(TRI, VT); 1203 // Use DPR as representative register class for all floating point 1204 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1205 // the cost is 1 for both f32 and f64. 1206 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1207 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1208 RRC = &ARM::DPRRegClass; 1209 // When NEON is used for SP, only half of the register file is available 1210 // because operations that define both SP and DP results will be constrained 1211 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1212 // coalescing by double-counting the SP regs. See the FIXME above. 1213 if (Subtarget->useNEONForSinglePrecisionFP()) 1214 Cost = 2; 1215 break; 1216 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1217 case MVT::v4f32: case MVT::v2f64: 1218 RRC = &ARM::DPRRegClass; 1219 Cost = 2; 1220 break; 1221 case MVT::v4i64: 1222 RRC = &ARM::DPRRegClass; 1223 Cost = 4; 1224 break; 1225 case MVT::v8i64: 1226 RRC = &ARM::DPRRegClass; 1227 Cost = 8; 1228 break; 1229 } 1230 return std::make_pair(RRC, Cost); 1231 } 1232 1233 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1234 switch ((ARMISD::NodeType)Opcode) { 1235 case ARMISD::FIRST_NUMBER: break; 1236 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1237 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1238 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1239 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1240 case ARMISD::CALL: return "ARMISD::CALL"; 1241 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1242 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1243 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1244 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1245 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1246 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1247 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1248 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1249 case ARMISD::CMP: return "ARMISD::CMP"; 1250 case ARMISD::CMN: return "ARMISD::CMN"; 1251 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1252 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1253 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1254 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1255 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1256 1257 case ARMISD::CMOV: return "ARMISD::CMOV"; 1258 1259 case ARMISD::SSAT: return "ARMISD::SSAT"; 1260 1261 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1262 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1263 case ARMISD::RRX: return "ARMISD::RRX"; 1264 1265 case ARMISD::ADDC: return "ARMISD::ADDC"; 1266 case ARMISD::ADDE: return "ARMISD::ADDE"; 1267 case ARMISD::SUBC: return "ARMISD::SUBC"; 1268 case ARMISD::SUBE: return "ARMISD::SUBE"; 1269 1270 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1271 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1272 1273 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1274 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1275 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1276 1277 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1278 1279 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1280 1281 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1282 1283 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1284 1285 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1286 1287 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1288 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1289 1290 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1291 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1292 case ARMISD::VCGE: return "ARMISD::VCGE"; 1293 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1294 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1295 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1296 case ARMISD::VCGT: return "ARMISD::VCGT"; 1297 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1298 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1299 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1300 case ARMISD::VTST: return "ARMISD::VTST"; 1301 1302 case ARMISD::VSHL: return "ARMISD::VSHL"; 1303 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1304 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1305 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1306 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1307 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1308 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1309 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1310 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1311 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1312 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1313 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1314 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1315 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1316 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1317 case ARMISD::VSLI: return "ARMISD::VSLI"; 1318 case ARMISD::VSRI: return "ARMISD::VSRI"; 1319 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1320 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1321 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1322 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1323 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1324 case ARMISD::VDUP: return "ARMISD::VDUP"; 1325 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1326 case ARMISD::VEXT: return "ARMISD::VEXT"; 1327 case ARMISD::VREV64: return "ARMISD::VREV64"; 1328 case ARMISD::VREV32: return "ARMISD::VREV32"; 1329 case ARMISD::VREV16: return "ARMISD::VREV16"; 1330 case ARMISD::VZIP: return "ARMISD::VZIP"; 1331 case ARMISD::VUZP: return "ARMISD::VUZP"; 1332 case ARMISD::VTRN: return "ARMISD::VTRN"; 1333 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1334 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1335 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1336 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1337 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1338 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1339 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1340 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1341 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1342 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1343 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1344 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1345 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1346 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1347 case ARMISD::BFI: return "ARMISD::BFI"; 1348 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1349 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1350 case ARMISD::VBSL: return "ARMISD::VBSL"; 1351 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1352 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1353 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1354 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1355 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1356 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1357 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1358 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1359 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1360 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1361 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1362 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1363 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1364 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1365 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1366 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1367 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1368 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1369 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1370 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1371 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1372 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1373 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1374 } 1375 return nullptr; 1376 } 1377 1378 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1379 EVT VT) const { 1380 if (!VT.isVector()) 1381 return getPointerTy(DL); 1382 return VT.changeVectorElementTypeToInteger(); 1383 } 1384 1385 /// getRegClassFor - Return the register class that should be used for the 1386 /// specified value type. 1387 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1388 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1389 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1390 // load / store 4 to 8 consecutive D registers. 1391 if (Subtarget->hasNEON()) { 1392 if (VT == MVT::v4i64) 1393 return &ARM::QQPRRegClass; 1394 if (VT == MVT::v8i64) 1395 return &ARM::QQQQPRRegClass; 1396 } 1397 return TargetLowering::getRegClassFor(VT); 1398 } 1399 1400 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1401 // source/dest is aligned and the copy size is large enough. We therefore want 1402 // to align such objects passed to memory intrinsics. 1403 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1404 unsigned &PrefAlign) const { 1405 if (!isa<MemIntrinsic>(CI)) 1406 return false; 1407 MinSize = 8; 1408 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1409 // cycle faster than 4-byte aligned LDM. 1410 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1411 return true; 1412 } 1413 1414 // Create a fast isel object. 1415 FastISel * 1416 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1417 const TargetLibraryInfo *libInfo) const { 1418 return ARM::createFastISel(funcInfo, libInfo); 1419 } 1420 1421 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1422 unsigned NumVals = N->getNumValues(); 1423 if (!NumVals) 1424 return Sched::RegPressure; 1425 1426 for (unsigned i = 0; i != NumVals; ++i) { 1427 EVT VT = N->getValueType(i); 1428 if (VT == MVT::Glue || VT == MVT::Other) 1429 continue; 1430 if (VT.isFloatingPoint() || VT.isVector()) 1431 return Sched::ILP; 1432 } 1433 1434 if (!N->isMachineOpcode()) 1435 return Sched::RegPressure; 1436 1437 // Load are scheduled for latency even if there instruction itinerary 1438 // is not available. 1439 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1440 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1441 1442 if (MCID.getNumDefs() == 0) 1443 return Sched::RegPressure; 1444 if (!Itins->isEmpty() && 1445 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1446 return Sched::ILP; 1447 1448 return Sched::RegPressure; 1449 } 1450 1451 //===----------------------------------------------------------------------===// 1452 // Lowering Code 1453 //===----------------------------------------------------------------------===// 1454 1455 static bool isSRL16(const SDValue &Op) { 1456 if (Op.getOpcode() != ISD::SRL) 1457 return false; 1458 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1459 return Const->getZExtValue() == 16; 1460 return false; 1461 } 1462 1463 static bool isSRA16(const SDValue &Op) { 1464 if (Op.getOpcode() != ISD::SRA) 1465 return false; 1466 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1467 return Const->getZExtValue() == 16; 1468 return false; 1469 } 1470 1471 static bool isSHL16(const SDValue &Op) { 1472 if (Op.getOpcode() != ISD::SHL) 1473 return false; 1474 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1475 return Const->getZExtValue() == 16; 1476 return false; 1477 } 1478 1479 // Check for a signed 16-bit value. We special case SRA because it makes it 1480 // more simple when also looking for SRAs that aren't sign extending a 1481 // smaller value. Without the check, we'd need to take extra care with 1482 // checking order for some operations. 1483 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1484 if (isSRA16(Op)) 1485 return isSHL16(Op.getOperand(0)); 1486 return DAG.ComputeNumSignBits(Op) == 17; 1487 } 1488 1489 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1490 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1491 switch (CC) { 1492 default: llvm_unreachable("Unknown condition code!"); 1493 case ISD::SETNE: return ARMCC::NE; 1494 case ISD::SETEQ: return ARMCC::EQ; 1495 case ISD::SETGT: return ARMCC::GT; 1496 case ISD::SETGE: return ARMCC::GE; 1497 case ISD::SETLT: return ARMCC::LT; 1498 case ISD::SETLE: return ARMCC::LE; 1499 case ISD::SETUGT: return ARMCC::HI; 1500 case ISD::SETUGE: return ARMCC::HS; 1501 case ISD::SETULT: return ARMCC::LO; 1502 case ISD::SETULE: return ARMCC::LS; 1503 } 1504 } 1505 1506 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1507 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1508 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1509 CondCode2 = ARMCC::AL; 1510 InvalidOnQNaN = true; 1511 switch (CC) { 1512 default: llvm_unreachable("Unknown FP condition!"); 1513 case ISD::SETEQ: 1514 case ISD::SETOEQ: 1515 CondCode = ARMCC::EQ; 1516 InvalidOnQNaN = false; 1517 break; 1518 case ISD::SETGT: 1519 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1520 case ISD::SETGE: 1521 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1522 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1523 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1524 case ISD::SETONE: 1525 CondCode = ARMCC::MI; 1526 CondCode2 = ARMCC::GT; 1527 InvalidOnQNaN = false; 1528 break; 1529 case ISD::SETO: CondCode = ARMCC::VC; break; 1530 case ISD::SETUO: CondCode = ARMCC::VS; break; 1531 case ISD::SETUEQ: 1532 CondCode = ARMCC::EQ; 1533 CondCode2 = ARMCC::VS; 1534 InvalidOnQNaN = false; 1535 break; 1536 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1537 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1538 case ISD::SETLT: 1539 case ISD::SETULT: CondCode = ARMCC::LT; break; 1540 case ISD::SETLE: 1541 case ISD::SETULE: CondCode = ARMCC::LE; break; 1542 case ISD::SETNE: 1543 case ISD::SETUNE: 1544 CondCode = ARMCC::NE; 1545 InvalidOnQNaN = false; 1546 break; 1547 } 1548 } 1549 1550 //===----------------------------------------------------------------------===// 1551 // Calling Convention Implementation 1552 //===----------------------------------------------------------------------===// 1553 1554 #include "ARMGenCallingConv.inc" 1555 1556 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1557 /// account presence of floating point hardware and calling convention 1558 /// limitations, such as support for variadic functions. 1559 CallingConv::ID 1560 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1561 bool isVarArg) const { 1562 switch (CC) { 1563 default: 1564 llvm_unreachable("Unsupported calling convention"); 1565 case CallingConv::ARM_AAPCS: 1566 case CallingConv::ARM_APCS: 1567 case CallingConv::GHC: 1568 return CC; 1569 case CallingConv::PreserveMost: 1570 return CallingConv::PreserveMost; 1571 case CallingConv::ARM_AAPCS_VFP: 1572 case CallingConv::Swift: 1573 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1574 case CallingConv::C: 1575 if (!Subtarget->isAAPCS_ABI()) 1576 return CallingConv::ARM_APCS; 1577 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1578 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1579 !isVarArg) 1580 return CallingConv::ARM_AAPCS_VFP; 1581 else 1582 return CallingConv::ARM_AAPCS; 1583 case CallingConv::Fast: 1584 case CallingConv::CXX_FAST_TLS: 1585 if (!Subtarget->isAAPCS_ABI()) { 1586 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1587 return CallingConv::Fast; 1588 return CallingConv::ARM_APCS; 1589 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1590 return CallingConv::ARM_AAPCS_VFP; 1591 else 1592 return CallingConv::ARM_AAPCS; 1593 } 1594 } 1595 1596 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1597 bool isVarArg) const { 1598 return CCAssignFnForNode(CC, false, isVarArg); 1599 } 1600 1601 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1602 bool isVarArg) const { 1603 return CCAssignFnForNode(CC, true, isVarArg); 1604 } 1605 1606 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1607 /// CallingConvention. 1608 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1609 bool Return, 1610 bool isVarArg) const { 1611 switch (getEffectiveCallingConv(CC, isVarArg)) { 1612 default: 1613 llvm_unreachable("Unsupported calling convention"); 1614 case CallingConv::ARM_APCS: 1615 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1616 case CallingConv::ARM_AAPCS: 1617 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1618 case CallingConv::ARM_AAPCS_VFP: 1619 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1620 case CallingConv::Fast: 1621 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1622 case CallingConv::GHC: 1623 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1624 case CallingConv::PreserveMost: 1625 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1626 } 1627 } 1628 1629 /// LowerCallResult - Lower the result values of a call into the 1630 /// appropriate copies out of appropriate physical registers. 1631 SDValue ARMTargetLowering::LowerCallResult( 1632 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1633 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1634 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1635 SDValue ThisVal) const { 1636 1637 // Assign locations to each value returned by this call. 1638 SmallVector<CCValAssign, 16> RVLocs; 1639 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1640 *DAG.getContext()); 1641 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1642 1643 // Copy all of the result registers out of their specified physreg. 1644 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1645 CCValAssign VA = RVLocs[i]; 1646 1647 // Pass 'this' value directly from the argument to return value, to avoid 1648 // reg unit interference 1649 if (i == 0 && isThisReturn) { 1650 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1651 "unexpected return calling convention register assignment"); 1652 InVals.push_back(ThisVal); 1653 continue; 1654 } 1655 1656 SDValue Val; 1657 if (VA.needsCustom()) { 1658 // Handle f64 or half of a v2f64. 1659 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1660 InFlag); 1661 Chain = Lo.getValue(1); 1662 InFlag = Lo.getValue(2); 1663 VA = RVLocs[++i]; // skip ahead to next loc 1664 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1665 InFlag); 1666 Chain = Hi.getValue(1); 1667 InFlag = Hi.getValue(2); 1668 if (!Subtarget->isLittle()) 1669 std::swap (Lo, Hi); 1670 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1671 1672 if (VA.getLocVT() == MVT::v2f64) { 1673 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1674 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1675 DAG.getConstant(0, dl, MVT::i32)); 1676 1677 VA = RVLocs[++i]; // skip ahead to next loc 1678 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1679 Chain = Lo.getValue(1); 1680 InFlag = Lo.getValue(2); 1681 VA = RVLocs[++i]; // skip ahead to next loc 1682 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1683 Chain = Hi.getValue(1); 1684 InFlag = Hi.getValue(2); 1685 if (!Subtarget->isLittle()) 1686 std::swap (Lo, Hi); 1687 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1688 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1689 DAG.getConstant(1, dl, MVT::i32)); 1690 } 1691 } else { 1692 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1693 InFlag); 1694 Chain = Val.getValue(1); 1695 InFlag = Val.getValue(2); 1696 } 1697 1698 switch (VA.getLocInfo()) { 1699 default: llvm_unreachable("Unknown loc info!"); 1700 case CCValAssign::Full: break; 1701 case CCValAssign::BCvt: 1702 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1703 break; 1704 } 1705 1706 InVals.push_back(Val); 1707 } 1708 1709 return Chain; 1710 } 1711 1712 /// LowerMemOpCallTo - Store the argument to the stack. 1713 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1714 SDValue Arg, const SDLoc &dl, 1715 SelectionDAG &DAG, 1716 const CCValAssign &VA, 1717 ISD::ArgFlagsTy Flags) const { 1718 unsigned LocMemOffset = VA.getLocMemOffset(); 1719 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1720 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1721 StackPtr, PtrOff); 1722 return DAG.getStore( 1723 Chain, dl, Arg, PtrOff, 1724 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1725 } 1726 1727 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1728 SDValue Chain, SDValue &Arg, 1729 RegsToPassVector &RegsToPass, 1730 CCValAssign &VA, CCValAssign &NextVA, 1731 SDValue &StackPtr, 1732 SmallVectorImpl<SDValue> &MemOpChains, 1733 ISD::ArgFlagsTy Flags) const { 1734 1735 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1736 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1737 unsigned id = Subtarget->isLittle() ? 0 : 1; 1738 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1739 1740 if (NextVA.isRegLoc()) 1741 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1742 else { 1743 assert(NextVA.isMemLoc()); 1744 if (!StackPtr.getNode()) 1745 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1746 getPointerTy(DAG.getDataLayout())); 1747 1748 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1749 dl, DAG, NextVA, 1750 Flags)); 1751 } 1752 } 1753 1754 /// LowerCall - Lowering a call into a callseq_start <- 1755 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1756 /// nodes. 1757 SDValue 1758 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1759 SmallVectorImpl<SDValue> &InVals) const { 1760 SelectionDAG &DAG = CLI.DAG; 1761 SDLoc &dl = CLI.DL; 1762 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1763 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1764 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1765 SDValue Chain = CLI.Chain; 1766 SDValue Callee = CLI.Callee; 1767 bool &isTailCall = CLI.IsTailCall; 1768 CallingConv::ID CallConv = CLI.CallConv; 1769 bool doesNotRet = CLI.DoesNotReturn; 1770 bool isVarArg = CLI.IsVarArg; 1771 1772 MachineFunction &MF = DAG.getMachineFunction(); 1773 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1774 bool isThisReturn = false; 1775 bool isSibCall = false; 1776 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1777 1778 // Disable tail calls if they're not supported. 1779 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1780 isTailCall = false; 1781 1782 if (isTailCall) { 1783 // Check if it's really possible to do a tail call. 1784 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1785 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1786 Outs, OutVals, Ins, DAG); 1787 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1788 report_fatal_error("failed to perform tail call elimination on a call " 1789 "site marked musttail"); 1790 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1791 // detected sibcalls. 1792 if (isTailCall) { 1793 ++NumTailCalls; 1794 isSibCall = true; 1795 } 1796 } 1797 1798 // Analyze operands of the call, assigning locations to each operand. 1799 SmallVector<CCValAssign, 16> ArgLocs; 1800 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1801 *DAG.getContext()); 1802 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1803 1804 // Get a count of how many bytes are to be pushed on the stack. 1805 unsigned NumBytes = CCInfo.getNextStackOffset(); 1806 1807 // For tail calls, memory operands are available in our caller's stack. 1808 if (isSibCall) 1809 NumBytes = 0; 1810 1811 // Adjust the stack pointer for the new arguments... 1812 // These operations are automatically eliminated by the prolog/epilog pass 1813 if (!isSibCall) 1814 Chain = DAG.getCALLSEQ_START(Chain, 1815 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1816 1817 SDValue StackPtr = 1818 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1819 1820 RegsToPassVector RegsToPass; 1821 SmallVector<SDValue, 8> MemOpChains; 1822 1823 // Walk the register/memloc assignments, inserting copies/loads. In the case 1824 // of tail call optimization, arguments are handled later. 1825 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1826 i != e; 1827 ++i, ++realArgIdx) { 1828 CCValAssign &VA = ArgLocs[i]; 1829 SDValue Arg = OutVals[realArgIdx]; 1830 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1831 bool isByVal = Flags.isByVal(); 1832 1833 // Promote the value if needed. 1834 switch (VA.getLocInfo()) { 1835 default: llvm_unreachable("Unknown loc info!"); 1836 case CCValAssign::Full: break; 1837 case CCValAssign::SExt: 1838 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1839 break; 1840 case CCValAssign::ZExt: 1841 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1842 break; 1843 case CCValAssign::AExt: 1844 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1845 break; 1846 case CCValAssign::BCvt: 1847 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1848 break; 1849 } 1850 1851 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1852 if (VA.needsCustom()) { 1853 if (VA.getLocVT() == MVT::v2f64) { 1854 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1855 DAG.getConstant(0, dl, MVT::i32)); 1856 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1857 DAG.getConstant(1, dl, MVT::i32)); 1858 1859 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1860 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1861 1862 VA = ArgLocs[++i]; // skip ahead to next loc 1863 if (VA.isRegLoc()) { 1864 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1865 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1866 } else { 1867 assert(VA.isMemLoc()); 1868 1869 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1870 dl, DAG, VA, Flags)); 1871 } 1872 } else { 1873 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1874 StackPtr, MemOpChains, Flags); 1875 } 1876 } else if (VA.isRegLoc()) { 1877 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1878 Outs[0].VT == MVT::i32) { 1879 assert(VA.getLocVT() == MVT::i32 && 1880 "unexpected calling convention register assignment"); 1881 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1882 "unexpected use of 'returned'"); 1883 isThisReturn = true; 1884 } 1885 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1886 } else if (isByVal) { 1887 assert(VA.isMemLoc()); 1888 unsigned offset = 0; 1889 1890 // True if this byval aggregate will be split between registers 1891 // and memory. 1892 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1893 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1894 1895 if (CurByValIdx < ByValArgsCount) { 1896 1897 unsigned RegBegin, RegEnd; 1898 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1899 1900 EVT PtrVT = 1901 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1902 unsigned int i, j; 1903 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1904 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1905 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1906 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1907 MachinePointerInfo(), 1908 DAG.InferPtrAlignment(AddArg)); 1909 MemOpChains.push_back(Load.getValue(1)); 1910 RegsToPass.push_back(std::make_pair(j, Load)); 1911 } 1912 1913 // If parameter size outsides register area, "offset" value 1914 // helps us to calculate stack slot for remained part properly. 1915 offset = RegEnd - RegBegin; 1916 1917 CCInfo.nextInRegsParam(); 1918 } 1919 1920 if (Flags.getByValSize() > 4*offset) { 1921 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1922 unsigned LocMemOffset = VA.getLocMemOffset(); 1923 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1924 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1925 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1926 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1927 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1928 MVT::i32); 1929 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1930 MVT::i32); 1931 1932 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1933 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1934 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1935 Ops)); 1936 } 1937 } else if (!isSibCall) { 1938 assert(VA.isMemLoc()); 1939 1940 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1941 dl, DAG, VA, Flags)); 1942 } 1943 } 1944 1945 if (!MemOpChains.empty()) 1946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1947 1948 // Build a sequence of copy-to-reg nodes chained together with token chain 1949 // and flag operands which copy the outgoing args into the appropriate regs. 1950 SDValue InFlag; 1951 // Tail call byval lowering might overwrite argument registers so in case of 1952 // tail call optimization the copies to registers are lowered later. 1953 if (!isTailCall) 1954 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1955 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1956 RegsToPass[i].second, InFlag); 1957 InFlag = Chain.getValue(1); 1958 } 1959 1960 // For tail calls lower the arguments to the 'real' stack slot. 1961 if (isTailCall) { 1962 // Force all the incoming stack arguments to be loaded from the stack 1963 // before any new outgoing arguments are stored to the stack, because the 1964 // outgoing stack slots may alias the incoming argument stack slots, and 1965 // the alias isn't otherwise explicit. This is slightly more conservative 1966 // than necessary, because it means that each store effectively depends 1967 // on every argument instead of just those arguments it would clobber. 1968 1969 // Do not flag preceding copytoreg stuff together with the following stuff. 1970 InFlag = SDValue(); 1971 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1972 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1973 RegsToPass[i].second, InFlag); 1974 InFlag = Chain.getValue(1); 1975 } 1976 InFlag = SDValue(); 1977 } 1978 1979 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1980 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1981 // node so that legalize doesn't hack it. 1982 bool isDirect = false; 1983 1984 const TargetMachine &TM = getTargetMachine(); 1985 const Module *Mod = MF.getFunction()->getParent(); 1986 const GlobalValue *GV = nullptr; 1987 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1988 GV = G->getGlobal(); 1989 bool isStub = 1990 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1991 1992 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1993 bool isLocalARMFunc = false; 1994 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1995 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1996 1997 if (Subtarget->genLongCalls()) { 1998 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1999 "long-calls codegen is not position independent!"); 2000 // Handle a global address or an external symbol. If it's not one of 2001 // those, the target's already in a register, so we don't need to do 2002 // anything extra. 2003 if (isa<GlobalAddressSDNode>(Callee)) { 2004 // Create a constant pool entry for the callee address 2005 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2006 ARMConstantPoolValue *CPV = 2007 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2008 2009 // Get the address of the callee into a register 2010 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2011 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2012 Callee = DAG.getLoad( 2013 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2014 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2015 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2016 const char *Sym = S->getSymbol(); 2017 2018 // Create a constant pool entry for the callee address 2019 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2020 ARMConstantPoolValue *CPV = 2021 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2022 ARMPCLabelIndex, 0); 2023 // Get the address of the callee into a register 2024 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2025 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2026 Callee = DAG.getLoad( 2027 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2028 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2029 } 2030 } else if (isa<GlobalAddressSDNode>(Callee)) { 2031 // If we're optimizing for minimum size and the function is called three or 2032 // more times in this block, we can improve codesize by calling indirectly 2033 // as BLXr has a 16-bit encoding. 2034 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2035 auto *BB = CLI.CS->getParent(); 2036 bool PreferIndirect = 2037 Subtarget->isThumb() && MF.getFunction()->optForMinSize() && 2038 count_if(GV->users(), [&BB](const User *U) { 2039 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2040 }) > 2; 2041 2042 if (!PreferIndirect) { 2043 isDirect = true; 2044 bool isDef = GV->isStrongDefinitionForLinker(); 2045 2046 // ARM call to a local ARM function is predicable. 2047 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2048 // tBX takes a register source operand. 2049 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2050 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2051 Callee = DAG.getNode( 2052 ARMISD::WrapperPIC, dl, PtrVt, 2053 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2054 Callee = DAG.getLoad( 2055 PtrVt, dl, DAG.getEntryNode(), Callee, 2056 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2057 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2058 MachineMemOperand::MOInvariant); 2059 } else if (Subtarget->isTargetCOFF()) { 2060 assert(Subtarget->isTargetWindows() && 2061 "Windows is the only supported COFF target"); 2062 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2063 ? ARMII::MO_DLLIMPORT 2064 : ARMII::MO_NO_FLAG; 2065 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2066 TargetFlags); 2067 if (GV->hasDLLImportStorageClass()) 2068 Callee = 2069 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2070 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2071 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2072 } else { 2073 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2074 } 2075 } 2076 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2077 isDirect = true; 2078 // tBX takes a register source operand. 2079 const char *Sym = S->getSymbol(); 2080 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2081 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2082 ARMConstantPoolValue *CPV = 2083 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2084 ARMPCLabelIndex, 4); 2085 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2086 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2087 Callee = DAG.getLoad( 2088 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2089 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2090 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2091 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2092 } else { 2093 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2094 } 2095 } 2096 2097 // FIXME: handle tail calls differently. 2098 unsigned CallOpc; 2099 if (Subtarget->isThumb()) { 2100 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2101 CallOpc = ARMISD::CALL_NOLINK; 2102 else 2103 CallOpc = ARMISD::CALL; 2104 } else { 2105 if (!isDirect && !Subtarget->hasV5TOps()) 2106 CallOpc = ARMISD::CALL_NOLINK; 2107 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2108 // Emit regular call when code size is the priority 2109 !MF.getFunction()->optForMinSize()) 2110 // "mov lr, pc; b _foo" to avoid confusing the RSP 2111 CallOpc = ARMISD::CALL_NOLINK; 2112 else 2113 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2114 } 2115 2116 std::vector<SDValue> Ops; 2117 Ops.push_back(Chain); 2118 Ops.push_back(Callee); 2119 2120 // Add argument registers to the end of the list so that they are known live 2121 // into the call. 2122 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2123 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2124 RegsToPass[i].second.getValueType())); 2125 2126 // Add a register mask operand representing the call-preserved registers. 2127 if (!isTailCall) { 2128 const uint32_t *Mask; 2129 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2130 if (isThisReturn) { 2131 // For 'this' returns, use the R0-preserving mask if applicable 2132 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2133 if (!Mask) { 2134 // Set isThisReturn to false if the calling convention is not one that 2135 // allows 'returned' to be modeled in this way, so LowerCallResult does 2136 // not try to pass 'this' straight through 2137 isThisReturn = false; 2138 Mask = ARI->getCallPreservedMask(MF, CallConv); 2139 } 2140 } else 2141 Mask = ARI->getCallPreservedMask(MF, CallConv); 2142 2143 assert(Mask && "Missing call preserved mask for calling convention"); 2144 Ops.push_back(DAG.getRegisterMask(Mask)); 2145 } 2146 2147 if (InFlag.getNode()) 2148 Ops.push_back(InFlag); 2149 2150 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2151 if (isTailCall) { 2152 MF.getFrameInfo().setHasTailCall(); 2153 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2154 } 2155 2156 // Returns a chain and a flag for retval copy to use. 2157 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2158 InFlag = Chain.getValue(1); 2159 2160 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2161 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2162 if (!Ins.empty()) 2163 InFlag = Chain.getValue(1); 2164 2165 // Handle result values, copying them out of physregs into vregs that we 2166 // return. 2167 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2168 InVals, isThisReturn, 2169 isThisReturn ? OutVals[0] : SDValue()); 2170 } 2171 2172 /// HandleByVal - Every parameter *after* a byval parameter is passed 2173 /// on the stack. Remember the next parameter register to allocate, 2174 /// and then confiscate the rest of the parameter registers to insure 2175 /// this. 2176 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2177 unsigned Align) const { 2178 // Byval (as with any stack) slots are always at least 4 byte aligned. 2179 Align = std::max(Align, 4U); 2180 2181 unsigned Reg = State->AllocateReg(GPRArgRegs); 2182 if (!Reg) 2183 return; 2184 2185 unsigned AlignInRegs = Align / 4; 2186 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2187 for (unsigned i = 0; i < Waste; ++i) 2188 Reg = State->AllocateReg(GPRArgRegs); 2189 2190 if (!Reg) 2191 return; 2192 2193 unsigned Excess = 4 * (ARM::R4 - Reg); 2194 2195 // Special case when NSAA != SP and parameter size greater than size of 2196 // all remained GPR regs. In that case we can't split parameter, we must 2197 // send it to stack. We also must set NCRN to R4, so waste all 2198 // remained registers. 2199 const unsigned NSAAOffset = State->getNextStackOffset(); 2200 if (NSAAOffset != 0 && Size > Excess) { 2201 while (State->AllocateReg(GPRArgRegs)) 2202 ; 2203 return; 2204 } 2205 2206 // First register for byval parameter is the first register that wasn't 2207 // allocated before this method call, so it would be "reg". 2208 // If parameter is small enough to be saved in range [reg, r4), then 2209 // the end (first after last) register would be reg + param-size-in-regs, 2210 // else parameter would be splitted between registers and stack, 2211 // end register would be r4 in this case. 2212 unsigned ByValRegBegin = Reg; 2213 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2214 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2215 // Note, first register is allocated in the beginning of function already, 2216 // allocate remained amount of registers we need. 2217 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2218 State->AllocateReg(GPRArgRegs); 2219 // A byval parameter that is split between registers and memory needs its 2220 // size truncated here. 2221 // In the case where the entire structure fits in registers, we set the 2222 // size in memory to zero. 2223 Size = std::max<int>(Size - Excess, 0); 2224 } 2225 2226 /// MatchingStackOffset - Return true if the given stack call argument is 2227 /// already available in the same position (relatively) of the caller's 2228 /// incoming argument stack. 2229 static 2230 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2231 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2232 const TargetInstrInfo *TII) { 2233 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2234 int FI = std::numeric_limits<int>::max(); 2235 if (Arg.getOpcode() == ISD::CopyFromReg) { 2236 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2237 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2238 return false; 2239 MachineInstr *Def = MRI->getVRegDef(VR); 2240 if (!Def) 2241 return false; 2242 if (!Flags.isByVal()) { 2243 if (!TII->isLoadFromStackSlot(*Def, FI)) 2244 return false; 2245 } else { 2246 return false; 2247 } 2248 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2249 if (Flags.isByVal()) 2250 // ByVal argument is passed in as a pointer but it's now being 2251 // dereferenced. e.g. 2252 // define @foo(%struct.X* %A) { 2253 // tail call @bar(%struct.X* byval %A) 2254 // } 2255 return false; 2256 SDValue Ptr = Ld->getBasePtr(); 2257 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2258 if (!FINode) 2259 return false; 2260 FI = FINode->getIndex(); 2261 } else 2262 return false; 2263 2264 assert(FI != std::numeric_limits<int>::max()); 2265 if (!MFI.isFixedObjectIndex(FI)) 2266 return false; 2267 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2268 } 2269 2270 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2271 /// for tail call optimization. Targets which want to do tail call 2272 /// optimization should implement this function. 2273 bool 2274 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2275 CallingConv::ID CalleeCC, 2276 bool isVarArg, 2277 bool isCalleeStructRet, 2278 bool isCallerStructRet, 2279 const SmallVectorImpl<ISD::OutputArg> &Outs, 2280 const SmallVectorImpl<SDValue> &OutVals, 2281 const SmallVectorImpl<ISD::InputArg> &Ins, 2282 SelectionDAG& DAG) const { 2283 MachineFunction &MF = DAG.getMachineFunction(); 2284 const Function *CallerF = MF.getFunction(); 2285 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2286 2287 assert(Subtarget->supportsTailCall()); 2288 2289 // Look for obvious safe cases to perform tail call optimization that do not 2290 // require ABI changes. This is what gcc calls sibcall. 2291 2292 // Exception-handling functions need a special set of instructions to indicate 2293 // a return to the hardware. Tail-calling another function would probably 2294 // break this. 2295 if (CallerF->hasFnAttribute("interrupt")) 2296 return false; 2297 2298 // Also avoid sibcall optimization if either caller or callee uses struct 2299 // return semantics. 2300 if (isCalleeStructRet || isCallerStructRet) 2301 return false; 2302 2303 // Externally-defined functions with weak linkage should not be 2304 // tail-called on ARM when the OS does not support dynamic 2305 // pre-emption of symbols, as the AAELF spec requires normal calls 2306 // to undefined weak functions to be replaced with a NOP or jump to the 2307 // next instruction. The behaviour of branch instructions in this 2308 // situation (as used for tail calls) is implementation-defined, so we 2309 // cannot rely on the linker replacing the tail call with a return. 2310 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2311 const GlobalValue *GV = G->getGlobal(); 2312 const Triple &TT = getTargetMachine().getTargetTriple(); 2313 if (GV->hasExternalWeakLinkage() && 2314 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2315 return false; 2316 } 2317 2318 // Check that the call results are passed in the same way. 2319 LLVMContext &C = *DAG.getContext(); 2320 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2321 CCAssignFnForReturn(CalleeCC, isVarArg), 2322 CCAssignFnForReturn(CallerCC, isVarArg))) 2323 return false; 2324 // The callee has to preserve all registers the caller needs to preserve. 2325 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2326 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2327 if (CalleeCC != CallerCC) { 2328 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2329 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2330 return false; 2331 } 2332 2333 // If Caller's vararg or byval argument has been split between registers and 2334 // stack, do not perform tail call, since part of the argument is in caller's 2335 // local frame. 2336 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2337 if (AFI_Caller->getArgRegsSaveSize()) 2338 return false; 2339 2340 // If the callee takes no arguments then go on to check the results of the 2341 // call. 2342 if (!Outs.empty()) { 2343 // Check if stack adjustment is needed. For now, do not do this if any 2344 // argument is passed on the stack. 2345 SmallVector<CCValAssign, 16> ArgLocs; 2346 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2347 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2348 if (CCInfo.getNextStackOffset()) { 2349 // Check if the arguments are already laid out in the right way as 2350 // the caller's fixed stack objects. 2351 MachineFrameInfo &MFI = MF.getFrameInfo(); 2352 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2353 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2354 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2355 i != e; 2356 ++i, ++realArgIdx) { 2357 CCValAssign &VA = ArgLocs[i]; 2358 EVT RegVT = VA.getLocVT(); 2359 SDValue Arg = OutVals[realArgIdx]; 2360 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2361 if (VA.getLocInfo() == CCValAssign::Indirect) 2362 return false; 2363 if (VA.needsCustom()) { 2364 // f64 and vector types are split into multiple registers or 2365 // register/stack-slot combinations. The types will not match 2366 // the registers; give up on memory f64 refs until we figure 2367 // out what to do about this. 2368 if (!VA.isRegLoc()) 2369 return false; 2370 if (!ArgLocs[++i].isRegLoc()) 2371 return false; 2372 if (RegVT == MVT::v2f64) { 2373 if (!ArgLocs[++i].isRegLoc()) 2374 return false; 2375 if (!ArgLocs[++i].isRegLoc()) 2376 return false; 2377 } 2378 } else if (!VA.isRegLoc()) { 2379 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2380 MFI, MRI, TII)) 2381 return false; 2382 } 2383 } 2384 } 2385 2386 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2387 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2388 return false; 2389 } 2390 2391 return true; 2392 } 2393 2394 bool 2395 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2396 MachineFunction &MF, bool isVarArg, 2397 const SmallVectorImpl<ISD::OutputArg> &Outs, 2398 LLVMContext &Context) const { 2399 SmallVector<CCValAssign, 16> RVLocs; 2400 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2401 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2402 } 2403 2404 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2405 const SDLoc &DL, SelectionDAG &DAG) { 2406 const MachineFunction &MF = DAG.getMachineFunction(); 2407 const Function *F = MF.getFunction(); 2408 2409 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2410 2411 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2412 // version of the "preferred return address". These offsets affect the return 2413 // instruction if this is a return from PL1 without hypervisor extensions. 2414 // IRQ/FIQ: +4 "subs pc, lr, #4" 2415 // SWI: 0 "subs pc, lr, #0" 2416 // ABORT: +4 "subs pc, lr, #4" 2417 // UNDEF: +4/+2 "subs pc, lr, #0" 2418 // UNDEF varies depending on where the exception came from ARM or Thumb 2419 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2420 2421 int64_t LROffset; 2422 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2423 IntKind == "ABORT") 2424 LROffset = 4; 2425 else if (IntKind == "SWI" || IntKind == "UNDEF") 2426 LROffset = 0; 2427 else 2428 report_fatal_error("Unsupported interrupt attribute. If present, value " 2429 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2430 2431 RetOps.insert(RetOps.begin() + 1, 2432 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2433 2434 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2435 } 2436 2437 SDValue 2438 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2439 bool isVarArg, 2440 const SmallVectorImpl<ISD::OutputArg> &Outs, 2441 const SmallVectorImpl<SDValue> &OutVals, 2442 const SDLoc &dl, SelectionDAG &DAG) const { 2443 2444 // CCValAssign - represent the assignment of the return value to a location. 2445 SmallVector<CCValAssign, 16> RVLocs; 2446 2447 // CCState - Info about the registers and stack slots. 2448 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2449 *DAG.getContext()); 2450 2451 // Analyze outgoing return values. 2452 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2453 2454 SDValue Flag; 2455 SmallVector<SDValue, 4> RetOps; 2456 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2457 bool isLittleEndian = Subtarget->isLittle(); 2458 2459 MachineFunction &MF = DAG.getMachineFunction(); 2460 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2461 AFI->setReturnRegsCount(RVLocs.size()); 2462 2463 // Copy the result values into the output registers. 2464 for (unsigned i = 0, realRVLocIdx = 0; 2465 i != RVLocs.size(); 2466 ++i, ++realRVLocIdx) { 2467 CCValAssign &VA = RVLocs[i]; 2468 assert(VA.isRegLoc() && "Can only return in registers!"); 2469 2470 SDValue Arg = OutVals[realRVLocIdx]; 2471 2472 switch (VA.getLocInfo()) { 2473 default: llvm_unreachable("Unknown loc info!"); 2474 case CCValAssign::Full: break; 2475 case CCValAssign::BCvt: 2476 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2477 break; 2478 } 2479 2480 if (VA.needsCustom()) { 2481 if (VA.getLocVT() == MVT::v2f64) { 2482 // Extract the first half and return it in two registers. 2483 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2484 DAG.getConstant(0, dl, MVT::i32)); 2485 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2486 DAG.getVTList(MVT::i32, MVT::i32), Half); 2487 2488 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2489 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2490 Flag); 2491 Flag = Chain.getValue(1); 2492 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2493 VA = RVLocs[++i]; // skip ahead to next loc 2494 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2495 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2496 Flag); 2497 Flag = Chain.getValue(1); 2498 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2499 VA = RVLocs[++i]; // skip ahead to next loc 2500 2501 // Extract the 2nd half and fall through to handle it as an f64 value. 2502 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2503 DAG.getConstant(1, dl, MVT::i32)); 2504 } 2505 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2506 // available. 2507 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2508 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2509 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2510 fmrrd.getValue(isLittleEndian ? 0 : 1), 2511 Flag); 2512 Flag = Chain.getValue(1); 2513 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2514 VA = RVLocs[++i]; // skip ahead to next loc 2515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2516 fmrrd.getValue(isLittleEndian ? 1 : 0), 2517 Flag); 2518 } else 2519 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2520 2521 // Guarantee that all emitted copies are 2522 // stuck together, avoiding something bad. 2523 Flag = Chain.getValue(1); 2524 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2525 } 2526 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2527 const MCPhysReg *I = 2528 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2529 if (I) { 2530 for (; *I; ++I) { 2531 if (ARM::GPRRegClass.contains(*I)) 2532 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2533 else if (ARM::DPRRegClass.contains(*I)) 2534 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2535 else 2536 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2537 } 2538 } 2539 2540 // Update chain and glue. 2541 RetOps[0] = Chain; 2542 if (Flag.getNode()) 2543 RetOps.push_back(Flag); 2544 2545 // CPUs which aren't M-class use a special sequence to return from 2546 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2547 // though we use "subs pc, lr, #N"). 2548 // 2549 // M-class CPUs actually use a normal return sequence with a special 2550 // (hardware-provided) value in LR, so the normal code path works. 2551 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2552 !Subtarget->isMClass()) { 2553 if (Subtarget->isThumb1Only()) 2554 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2555 return LowerInterruptReturn(RetOps, dl, DAG); 2556 } 2557 2558 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2559 } 2560 2561 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2562 if (N->getNumValues() != 1) 2563 return false; 2564 if (!N->hasNUsesOfValue(1, 0)) 2565 return false; 2566 2567 SDValue TCChain = Chain; 2568 SDNode *Copy = *N->use_begin(); 2569 if (Copy->getOpcode() == ISD::CopyToReg) { 2570 // If the copy has a glue operand, we conservatively assume it isn't safe to 2571 // perform a tail call. 2572 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2573 return false; 2574 TCChain = Copy->getOperand(0); 2575 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2576 SDNode *VMov = Copy; 2577 // f64 returned in a pair of GPRs. 2578 SmallPtrSet<SDNode*, 2> Copies; 2579 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2580 UI != UE; ++UI) { 2581 if (UI->getOpcode() != ISD::CopyToReg) 2582 return false; 2583 Copies.insert(*UI); 2584 } 2585 if (Copies.size() > 2) 2586 return false; 2587 2588 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2589 UI != UE; ++UI) { 2590 SDValue UseChain = UI->getOperand(0); 2591 if (Copies.count(UseChain.getNode())) 2592 // Second CopyToReg 2593 Copy = *UI; 2594 else { 2595 // We are at the top of this chain. 2596 // If the copy has a glue operand, we conservatively assume it 2597 // isn't safe to perform a tail call. 2598 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2599 return false; 2600 // First CopyToReg 2601 TCChain = UseChain; 2602 } 2603 } 2604 } else if (Copy->getOpcode() == ISD::BITCAST) { 2605 // f32 returned in a single GPR. 2606 if (!Copy->hasOneUse()) 2607 return false; 2608 Copy = *Copy->use_begin(); 2609 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2610 return false; 2611 // If the copy has a glue operand, we conservatively assume it isn't safe to 2612 // perform a tail call. 2613 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2614 return false; 2615 TCChain = Copy->getOperand(0); 2616 } else { 2617 return false; 2618 } 2619 2620 bool HasRet = false; 2621 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2622 UI != UE; ++UI) { 2623 if (UI->getOpcode() != ARMISD::RET_FLAG && 2624 UI->getOpcode() != ARMISD::INTRET_FLAG) 2625 return false; 2626 HasRet = true; 2627 } 2628 2629 if (!HasRet) 2630 return false; 2631 2632 Chain = TCChain; 2633 return true; 2634 } 2635 2636 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2637 if (!Subtarget->supportsTailCall()) 2638 return false; 2639 2640 auto Attr = 2641 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2642 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2643 return false; 2644 2645 return true; 2646 } 2647 2648 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2649 // and pass the lower and high parts through. 2650 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2651 SDLoc DL(Op); 2652 SDValue WriteValue = Op->getOperand(2); 2653 2654 // This function is only supposed to be called for i64 type argument. 2655 assert(WriteValue.getValueType() == MVT::i64 2656 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2657 2658 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2659 DAG.getConstant(0, DL, MVT::i32)); 2660 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2661 DAG.getConstant(1, DL, MVT::i32)); 2662 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2663 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2664 } 2665 2666 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2667 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2668 // one of the above mentioned nodes. It has to be wrapped because otherwise 2669 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2670 // be used to form addressing mode. These wrapped nodes will be selected 2671 // into MOVi. 2672 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2673 EVT PtrVT = Op.getValueType(); 2674 // FIXME there is no actual debug info here 2675 SDLoc dl(Op); 2676 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2677 SDValue Res; 2678 if (CP->isMachineConstantPoolEntry()) 2679 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2680 CP->getAlignment()); 2681 else 2682 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2683 CP->getAlignment()); 2684 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2685 } 2686 2687 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2688 return MachineJumpTableInfo::EK_Inline; 2689 } 2690 2691 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2692 SelectionDAG &DAG) const { 2693 MachineFunction &MF = DAG.getMachineFunction(); 2694 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2695 unsigned ARMPCLabelIndex = 0; 2696 SDLoc DL(Op); 2697 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2698 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2699 SDValue CPAddr; 2700 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2701 if (!IsPositionIndependent) { 2702 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2703 } else { 2704 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2705 ARMPCLabelIndex = AFI->createPICLabelUId(); 2706 ARMConstantPoolValue *CPV = 2707 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2708 ARMCP::CPBlockAddress, PCAdj); 2709 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2710 } 2711 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2712 SDValue Result = DAG.getLoad( 2713 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2714 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2715 if (!IsPositionIndependent) 2716 return Result; 2717 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2718 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2719 } 2720 2721 /// \brief Convert a TLS address reference into the correct sequence of loads 2722 /// and calls to compute the variable's address for Darwin, and return an 2723 /// SDValue containing the final node. 2724 2725 /// Darwin only has one TLS scheme which must be capable of dealing with the 2726 /// fully general situation, in the worst case. This means: 2727 /// + "extern __thread" declaration. 2728 /// + Defined in a possibly unknown dynamic library. 2729 /// 2730 /// The general system is that each __thread variable has a [3 x i32] descriptor 2731 /// which contains information used by the runtime to calculate the address. The 2732 /// only part of this the compiler needs to know about is the first word, which 2733 /// contains a function pointer that must be called with the address of the 2734 /// entire descriptor in "r0". 2735 /// 2736 /// Since this descriptor may be in a different unit, in general access must 2737 /// proceed along the usual ARM rules. A common sequence to produce is: 2738 /// 2739 /// movw rT1, :lower16:_var$non_lazy_ptr 2740 /// movt rT1, :upper16:_var$non_lazy_ptr 2741 /// ldr r0, [rT1] 2742 /// ldr rT2, [r0] 2743 /// blx rT2 2744 /// [...address now in r0...] 2745 SDValue 2746 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2747 SelectionDAG &DAG) const { 2748 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2749 SDLoc DL(Op); 2750 2751 // First step is to get the address of the actua global symbol. This is where 2752 // the TLS descriptor lives. 2753 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2754 2755 // The first entry in the descriptor is a function pointer that we must call 2756 // to obtain the address of the variable. 2757 SDValue Chain = DAG.getEntryNode(); 2758 SDValue FuncTLVGet = DAG.getLoad( 2759 MVT::i32, DL, Chain, DescAddr, 2760 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2761 /* Alignment = */ 4, 2762 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2763 MachineMemOperand::MOInvariant); 2764 Chain = FuncTLVGet.getValue(1); 2765 2766 MachineFunction &F = DAG.getMachineFunction(); 2767 MachineFrameInfo &MFI = F.getFrameInfo(); 2768 MFI.setAdjustsStack(true); 2769 2770 // TLS calls preserve all registers except those that absolutely must be 2771 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2772 // silly). 2773 auto TRI = 2774 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2775 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2776 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2777 2778 // Finally, we can make the call. This is just a degenerate version of a 2779 // normal AArch64 call node: r0 takes the address of the descriptor, and 2780 // returns the address of the variable in this thread. 2781 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2782 Chain = 2783 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2784 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2785 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2786 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2787 } 2788 2789 SDValue 2790 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2791 SelectionDAG &DAG) const { 2792 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2793 2794 SDValue Chain = DAG.getEntryNode(); 2795 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2796 SDLoc DL(Op); 2797 2798 // Load the current TEB (thread environment block) 2799 SDValue Ops[] = {Chain, 2800 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2801 DAG.getConstant(15, DL, MVT::i32), 2802 DAG.getConstant(0, DL, MVT::i32), 2803 DAG.getConstant(13, DL, MVT::i32), 2804 DAG.getConstant(0, DL, MVT::i32), 2805 DAG.getConstant(2, DL, MVT::i32)}; 2806 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2807 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2808 2809 SDValue TEB = CurrentTEB.getValue(0); 2810 Chain = CurrentTEB.getValue(1); 2811 2812 // Load the ThreadLocalStoragePointer from the TEB 2813 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2814 SDValue TLSArray = 2815 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2816 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2817 2818 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2819 // offset into the TLSArray. 2820 2821 // Load the TLS index from the C runtime 2822 SDValue TLSIndex = 2823 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2824 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2825 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2826 2827 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2828 DAG.getConstant(2, DL, MVT::i32)); 2829 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2830 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2831 MachinePointerInfo()); 2832 2833 // Get the offset of the start of the .tls section (section base) 2834 const auto *GA = cast<GlobalAddressSDNode>(Op); 2835 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2836 SDValue Offset = DAG.getLoad( 2837 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2838 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2839 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2840 2841 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2842 } 2843 2844 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2845 SDValue 2846 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2847 SelectionDAG &DAG) const { 2848 SDLoc dl(GA); 2849 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2850 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2851 MachineFunction &MF = DAG.getMachineFunction(); 2852 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2853 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2854 ARMConstantPoolValue *CPV = 2855 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2856 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2857 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2858 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2859 Argument = DAG.getLoad( 2860 PtrVT, dl, DAG.getEntryNode(), Argument, 2861 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2862 SDValue Chain = Argument.getValue(1); 2863 2864 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2865 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2866 2867 // call __tls_get_addr. 2868 ArgListTy Args; 2869 ArgListEntry Entry; 2870 Entry.Node = Argument; 2871 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2872 Args.push_back(Entry); 2873 2874 // FIXME: is there useful debug info available here? 2875 TargetLowering::CallLoweringInfo CLI(DAG); 2876 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2877 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2878 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2879 2880 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2881 return CallResult.first; 2882 } 2883 2884 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2885 // "local exec" model. 2886 SDValue 2887 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2888 SelectionDAG &DAG, 2889 TLSModel::Model model) const { 2890 const GlobalValue *GV = GA->getGlobal(); 2891 SDLoc dl(GA); 2892 SDValue Offset; 2893 SDValue Chain = DAG.getEntryNode(); 2894 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2895 // Get the Thread Pointer 2896 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2897 2898 if (model == TLSModel::InitialExec) { 2899 MachineFunction &MF = DAG.getMachineFunction(); 2900 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2901 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2902 // Initial exec model. 2903 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2904 ARMConstantPoolValue *CPV = 2905 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2906 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2907 true); 2908 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2909 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2910 Offset = DAG.getLoad( 2911 PtrVT, dl, Chain, Offset, 2912 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2913 Chain = Offset.getValue(1); 2914 2915 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2916 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2917 2918 Offset = DAG.getLoad( 2919 PtrVT, dl, Chain, Offset, 2920 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2921 } else { 2922 // local exec model 2923 assert(model == TLSModel::LocalExec); 2924 ARMConstantPoolValue *CPV = 2925 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2926 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2927 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2928 Offset = DAG.getLoad( 2929 PtrVT, dl, Chain, Offset, 2930 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2931 } 2932 2933 // The address of the thread local variable is the add of the thread 2934 // pointer with the offset of the variable. 2935 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2936 } 2937 2938 SDValue 2939 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2940 if (Subtarget->isTargetDarwin()) 2941 return LowerGlobalTLSAddressDarwin(Op, DAG); 2942 2943 if (Subtarget->isTargetWindows()) 2944 return LowerGlobalTLSAddressWindows(Op, DAG); 2945 2946 // TODO: implement the "local dynamic" model 2947 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2948 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2949 if (DAG.getTarget().Options.EmulatedTLS) 2950 return LowerToTLSEmulatedModel(GA, DAG); 2951 2952 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2953 2954 switch (model) { 2955 case TLSModel::GeneralDynamic: 2956 case TLSModel::LocalDynamic: 2957 return LowerToTLSGeneralDynamicModel(GA, DAG); 2958 case TLSModel::InitialExec: 2959 case TLSModel::LocalExec: 2960 return LowerToTLSExecModels(GA, DAG, model); 2961 } 2962 llvm_unreachable("bogus TLS model"); 2963 } 2964 2965 /// Return true if all users of V are within function F, looking through 2966 /// ConstantExprs. 2967 static bool allUsersAreInFunction(const Value *V, const Function *F) { 2968 SmallVector<const User*,4> Worklist; 2969 for (auto *U : V->users()) 2970 Worklist.push_back(U); 2971 while (!Worklist.empty()) { 2972 auto *U = Worklist.pop_back_val(); 2973 if (isa<ConstantExpr>(U)) { 2974 for (auto *UU : U->users()) 2975 Worklist.push_back(UU); 2976 continue; 2977 } 2978 2979 auto *I = dyn_cast<Instruction>(U); 2980 if (!I || I->getParent()->getParent() != F) 2981 return false; 2982 } 2983 return true; 2984 } 2985 2986 /// Return true if all users of V are within some (any) function, looking through 2987 /// ConstantExprs. In other words, are there any global constant users? 2988 static bool allUsersAreInFunctions(const Value *V) { 2989 SmallVector<const User*,4> Worklist; 2990 for (auto *U : V->users()) 2991 Worklist.push_back(U); 2992 while (!Worklist.empty()) { 2993 auto *U = Worklist.pop_back_val(); 2994 if (isa<ConstantExpr>(U)) { 2995 for (auto *UU : U->users()) 2996 Worklist.push_back(UU); 2997 continue; 2998 } 2999 3000 if (!isa<Instruction>(U)) 3001 return false; 3002 } 3003 return true; 3004 } 3005 3006 // Return true if T is an integer, float or an array/vector of either. 3007 static bool isSimpleType(Type *T) { 3008 if (T->isIntegerTy() || T->isFloatingPointTy()) 3009 return true; 3010 Type *SubT = nullptr; 3011 if (T->isArrayTy()) 3012 SubT = T->getArrayElementType(); 3013 else if (T->isVectorTy()) 3014 SubT = T->getVectorElementType(); 3015 else 3016 return false; 3017 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3018 } 3019 3020 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3021 EVT PtrVT, const SDLoc &dl) { 3022 // If we're creating a pool entry for a constant global with unnamed address, 3023 // and the global is small enough, we can emit it inline into the constant pool 3024 // to save ourselves an indirection. 3025 // 3026 // This is a win if the constant is only used in one function (so it doesn't 3027 // need to be duplicated) or duplicating the constant wouldn't increase code 3028 // size (implying the constant is no larger than 4 bytes). 3029 const Function *F = DAG.getMachineFunction().getFunction(); 3030 3031 // We rely on this decision to inline being idemopotent and unrelated to the 3032 // use-site. We know that if we inline a variable at one use site, we'll 3033 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3034 // doesn't know about this optimization, so bail out if it's enabled else 3035 // we could decide to inline here (and thus never emit the GV) but require 3036 // the GV from fast-isel generated code. 3037 if (!EnableConstpoolPromotion || 3038 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3039 return SDValue(); 3040 3041 auto *GVar = dyn_cast<GlobalVariable>(GV); 3042 if (!GVar || !GVar->hasInitializer() || 3043 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3044 !GVar->hasLocalLinkage()) 3045 return SDValue(); 3046 3047 // Ensure that we don't try and inline any type that contains pointers. If 3048 // we inline a value that contains relocations, we move the relocations from 3049 // .data to .text which is not ideal. 3050 auto *Init = GVar->getInitializer(); 3051 if (!isSimpleType(Init->getType())) 3052 return SDValue(); 3053 3054 // The constant islands pass can only really deal with alignment requests 3055 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3056 // any type wanting greater alignment requirements than 4 bytes. We also 3057 // can only promote constants that are multiples of 4 bytes in size or 3058 // are paddable to a multiple of 4. Currently we only try and pad constants 3059 // that are strings for simplicity. 3060 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3061 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3062 unsigned Align = GVar->getAlignment(); 3063 unsigned RequiredPadding = 4 - (Size % 4); 3064 bool PaddingPossible = 3065 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3066 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3067 Size == 0) 3068 return SDValue(); 3069 3070 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3071 MachineFunction &MF = DAG.getMachineFunction(); 3072 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3073 3074 // We can't bloat the constant pool too much, else the ConstantIslands pass 3075 // may fail to converge. If we haven't promoted this global yet (it may have 3076 // multiple uses), and promoting it would increase the constant pool size (Sz 3077 // > 4), ensure we have space to do so up to MaxTotal. 3078 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3079 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3080 ConstpoolPromotionMaxTotal) 3081 return SDValue(); 3082 3083 // This is only valid if all users are in a single function OR it has users 3084 // in multiple functions but it no larger than a pointer. We also check if 3085 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3086 // address taken. 3087 if (!allUsersAreInFunction(GVar, F) && 3088 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3089 return SDValue(); 3090 3091 // We're going to inline this global. Pad it out if needed. 3092 if (RequiredPadding != 4) { 3093 StringRef S = CDAInit->getAsString(); 3094 3095 SmallVector<uint8_t,16> V(S.size()); 3096 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3097 while (RequiredPadding--) 3098 V.push_back(0); 3099 Init = ConstantDataArray::get(*DAG.getContext(), V); 3100 } 3101 3102 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3103 SDValue CPAddr = 3104 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3105 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3106 AFI->markGlobalAsPromotedToConstantPool(GVar); 3107 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3108 PaddedSize - 4); 3109 } 3110 ++NumConstpoolPromoted; 3111 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3112 } 3113 3114 static bool isReadOnly(const GlobalValue *GV) { 3115 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3116 GV = GA->getBaseObject(); 3117 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3118 isa<Function>(GV); 3119 } 3120 3121 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3122 SelectionDAG &DAG) const { 3123 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3124 SDLoc dl(Op); 3125 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3126 const TargetMachine &TM = getTargetMachine(); 3127 bool IsRO = isReadOnly(GV); 3128 3129 // promoteToConstantPool only if not generating XO text section 3130 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3131 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3132 return V; 3133 3134 if (isPositionIndependent()) { 3135 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3136 3137 MachineFunction &MF = DAG.getMachineFunction(); 3138 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3139 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3140 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3141 SDLoc dl(Op); 3142 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3143 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 3144 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 3145 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 3146 /*AddCurrentAddress=*/UseGOT_PREL); 3147 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3148 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3149 SDValue Result = DAG.getLoad( 3150 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3151 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3152 SDValue Chain = Result.getValue(1); 3153 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3154 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3155 if (UseGOT_PREL) 3156 Result = 3157 DAG.getLoad(PtrVT, dl, Chain, Result, 3158 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3159 return Result; 3160 } else if (Subtarget->isROPI() && IsRO) { 3161 // PC-relative. 3162 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3163 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3164 return Result; 3165 } else if (Subtarget->isRWPI() && !IsRO) { 3166 // SB-relative. 3167 SDValue RelAddr; 3168 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3169 ++NumMovwMovt; 3170 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3171 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3172 } else { // use literal pool for address constant 3173 ARMConstantPoolValue *CPV = 3174 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3175 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3176 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3177 RelAddr = DAG.getLoad( 3178 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3179 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3180 } 3181 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3182 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3183 return Result; 3184 } 3185 3186 // If we have T2 ops, we can materialize the address directly via movt/movw 3187 // pair. This is always cheaper. 3188 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3189 ++NumMovwMovt; 3190 // FIXME: Once remat is capable of dealing with instructions with register 3191 // operands, expand this into two nodes. 3192 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3193 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3194 } else { 3195 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3196 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3197 return DAG.getLoad( 3198 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3199 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3200 } 3201 } 3202 3203 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3204 SelectionDAG &DAG) const { 3205 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3206 "ROPI/RWPI not currently supported for Darwin"); 3207 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3208 SDLoc dl(Op); 3209 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3210 3211 if (Subtarget->useMovt(DAG.getMachineFunction())) 3212 ++NumMovwMovt; 3213 3214 // FIXME: Once remat is capable of dealing with instructions with register 3215 // operands, expand this into multiple nodes 3216 unsigned Wrapper = 3217 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3218 3219 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3220 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3221 3222 if (Subtarget->isGVIndirectSymbol(GV)) 3223 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3224 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3225 return Result; 3226 } 3227 3228 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3229 SelectionDAG &DAG) const { 3230 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3231 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3232 "Windows on ARM expects to use movw/movt"); 3233 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3234 "ROPI/RWPI not currently supported for Windows"); 3235 3236 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3237 const ARMII::TOF TargetFlags = 3238 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3239 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3240 SDValue Result; 3241 SDLoc DL(Op); 3242 3243 ++NumMovwMovt; 3244 3245 // FIXME: Once remat is capable of dealing with instructions with register 3246 // operands, expand this into two nodes. 3247 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3248 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3249 TargetFlags)); 3250 if (GV->hasDLLImportStorageClass()) 3251 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3252 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3253 return Result; 3254 } 3255 3256 SDValue 3257 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3258 SDLoc dl(Op); 3259 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3260 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3261 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3262 Op.getOperand(1), Val); 3263 } 3264 3265 SDValue 3266 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3267 SDLoc dl(Op); 3268 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3269 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3270 } 3271 3272 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3273 SelectionDAG &DAG) const { 3274 SDLoc dl(Op); 3275 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3276 Op.getOperand(0)); 3277 } 3278 3279 SDValue 3280 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3281 const ARMSubtarget *Subtarget) const { 3282 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3283 SDLoc dl(Op); 3284 switch (IntNo) { 3285 default: return SDValue(); // Don't custom lower most intrinsics. 3286 case Intrinsic::thread_pointer: { 3287 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3288 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3289 } 3290 case Intrinsic::eh_sjlj_lsda: { 3291 MachineFunction &MF = DAG.getMachineFunction(); 3292 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3293 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3294 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3295 SDValue CPAddr; 3296 bool IsPositionIndependent = isPositionIndependent(); 3297 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3298 ARMConstantPoolValue *CPV = 3299 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 3300 ARMCP::CPLSDA, PCAdj); 3301 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3302 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3303 SDValue Result = DAG.getLoad( 3304 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3305 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3306 3307 if (IsPositionIndependent) { 3308 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3309 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3310 } 3311 return Result; 3312 } 3313 case Intrinsic::arm_neon_vmulls: 3314 case Intrinsic::arm_neon_vmullu: { 3315 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3316 ? ARMISD::VMULLs : ARMISD::VMULLu; 3317 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3318 Op.getOperand(1), Op.getOperand(2)); 3319 } 3320 case Intrinsic::arm_neon_vminnm: 3321 case Intrinsic::arm_neon_vmaxnm: { 3322 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3323 ? ISD::FMINNUM : ISD::FMAXNUM; 3324 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3325 Op.getOperand(1), Op.getOperand(2)); 3326 } 3327 case Intrinsic::arm_neon_vminu: 3328 case Intrinsic::arm_neon_vmaxu: { 3329 if (Op.getValueType().isFloatingPoint()) 3330 return SDValue(); 3331 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3332 ? ISD::UMIN : ISD::UMAX; 3333 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3334 Op.getOperand(1), Op.getOperand(2)); 3335 } 3336 case Intrinsic::arm_neon_vmins: 3337 case Intrinsic::arm_neon_vmaxs: { 3338 // v{min,max}s is overloaded between signed integers and floats. 3339 if (!Op.getValueType().isFloatingPoint()) { 3340 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3341 ? ISD::SMIN : ISD::SMAX; 3342 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3343 Op.getOperand(1), Op.getOperand(2)); 3344 } 3345 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3346 ? ISD::FMINNAN : ISD::FMAXNAN; 3347 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3348 Op.getOperand(1), Op.getOperand(2)); 3349 } 3350 case Intrinsic::arm_neon_vtbl1: 3351 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3352 Op.getOperand(1), Op.getOperand(2)); 3353 case Intrinsic::arm_neon_vtbl2: 3354 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3355 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3356 } 3357 } 3358 3359 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3360 const ARMSubtarget *Subtarget) { 3361 SDLoc dl(Op); 3362 ConstantSDNode *ScopeN = cast<ConstantSDNode>(Op.getOperand(2)); 3363 auto Scope = static_cast<SynchronizationScope>(ScopeN->getZExtValue()); 3364 if (Scope == SynchronizationScope::SingleThread) 3365 return Op; 3366 3367 if (!Subtarget->hasDataBarrier()) { 3368 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3369 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3370 // here. 3371 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3372 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3373 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3374 DAG.getConstant(0, dl, MVT::i32)); 3375 } 3376 3377 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3378 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3379 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3380 if (Subtarget->isMClass()) { 3381 // Only a full system barrier exists in the M-class architectures. 3382 Domain = ARM_MB::SY; 3383 } else if (Subtarget->preferISHSTBarriers() && 3384 Ord == AtomicOrdering::Release) { 3385 // Swift happens to implement ISHST barriers in a way that's compatible with 3386 // Release semantics but weaker than ISH so we'd be fools not to use 3387 // it. Beware: other processors probably don't! 3388 Domain = ARM_MB::ISHST; 3389 } 3390 3391 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3392 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3393 DAG.getConstant(Domain, dl, MVT::i32)); 3394 } 3395 3396 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3397 const ARMSubtarget *Subtarget) { 3398 // ARM pre v5TE and Thumb1 does not have preload instructions. 3399 if (!(Subtarget->isThumb2() || 3400 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3401 // Just preserve the chain. 3402 return Op.getOperand(0); 3403 3404 SDLoc dl(Op); 3405 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3406 if (!isRead && 3407 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3408 // ARMv7 with MP extension has PLDW. 3409 return Op.getOperand(0); 3410 3411 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3412 if (Subtarget->isThumb()) { 3413 // Invert the bits. 3414 isRead = ~isRead & 1; 3415 isData = ~isData & 1; 3416 } 3417 3418 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3419 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3420 DAG.getConstant(isData, dl, MVT::i32)); 3421 } 3422 3423 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3424 MachineFunction &MF = DAG.getMachineFunction(); 3425 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3426 3427 // vastart just stores the address of the VarArgsFrameIndex slot into the 3428 // memory location argument. 3429 SDLoc dl(Op); 3430 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3431 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3432 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3433 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3434 MachinePointerInfo(SV)); 3435 } 3436 3437 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3438 CCValAssign &NextVA, 3439 SDValue &Root, 3440 SelectionDAG &DAG, 3441 const SDLoc &dl) const { 3442 MachineFunction &MF = DAG.getMachineFunction(); 3443 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3444 3445 const TargetRegisterClass *RC; 3446 if (AFI->isThumb1OnlyFunction()) 3447 RC = &ARM::tGPRRegClass; 3448 else 3449 RC = &ARM::GPRRegClass; 3450 3451 // Transform the arguments stored in physical registers into virtual ones. 3452 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3453 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3454 3455 SDValue ArgValue2; 3456 if (NextVA.isMemLoc()) { 3457 MachineFrameInfo &MFI = MF.getFrameInfo(); 3458 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3459 3460 // Create load node to retrieve arguments from the stack. 3461 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3462 ArgValue2 = DAG.getLoad( 3463 MVT::i32, dl, Root, FIN, 3464 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3465 } else { 3466 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3467 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3468 } 3469 if (!Subtarget->isLittle()) 3470 std::swap (ArgValue, ArgValue2); 3471 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3472 } 3473 3474 // The remaining GPRs hold either the beginning of variable-argument 3475 // data, or the beginning of an aggregate passed by value (usually 3476 // byval). Either way, we allocate stack slots adjacent to the data 3477 // provided by our caller, and store the unallocated registers there. 3478 // If this is a variadic function, the va_list pointer will begin with 3479 // these values; otherwise, this reassembles a (byval) structure that 3480 // was split between registers and memory. 3481 // Return: The frame index registers were stored into. 3482 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3483 const SDLoc &dl, SDValue &Chain, 3484 const Value *OrigArg, 3485 unsigned InRegsParamRecordIdx, 3486 int ArgOffset, unsigned ArgSize) const { 3487 // Currently, two use-cases possible: 3488 // Case #1. Non-var-args function, and we meet first byval parameter. 3489 // Setup first unallocated register as first byval register; 3490 // eat all remained registers 3491 // (these two actions are performed by HandleByVal method). 3492 // Then, here, we initialize stack frame with 3493 // "store-reg" instructions. 3494 // Case #2. Var-args function, that doesn't contain byval parameters. 3495 // The same: eat all remained unallocated registers, 3496 // initialize stack frame. 3497 3498 MachineFunction &MF = DAG.getMachineFunction(); 3499 MachineFrameInfo &MFI = MF.getFrameInfo(); 3500 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3501 unsigned RBegin, REnd; 3502 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3503 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3504 } else { 3505 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3506 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3507 REnd = ARM::R4; 3508 } 3509 3510 if (REnd != RBegin) 3511 ArgOffset = -4 * (ARM::R4 - RBegin); 3512 3513 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3514 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3515 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3516 3517 SmallVector<SDValue, 4> MemOps; 3518 const TargetRegisterClass *RC = 3519 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3520 3521 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3522 unsigned VReg = MF.addLiveIn(Reg, RC); 3523 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3524 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3525 MachinePointerInfo(OrigArg, 4 * i)); 3526 MemOps.push_back(Store); 3527 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3528 } 3529 3530 if (!MemOps.empty()) 3531 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3532 return FrameIndex; 3533 } 3534 3535 // Setup stack frame, the va_list pointer will start from. 3536 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3537 const SDLoc &dl, SDValue &Chain, 3538 unsigned ArgOffset, 3539 unsigned TotalArgRegsSaveSize, 3540 bool ForceMutable) const { 3541 MachineFunction &MF = DAG.getMachineFunction(); 3542 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3543 3544 // Try to store any remaining integer argument regs 3545 // to their spots on the stack so that they may be loaded by dereferencing 3546 // the result of va_next. 3547 // If there is no regs to be stored, just point address after last 3548 // argument passed via stack. 3549 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3550 CCInfo.getInRegsParamsCount(), 3551 CCInfo.getNextStackOffset(), 4); 3552 AFI->setVarArgsFrameIndex(FrameIndex); 3553 } 3554 3555 SDValue ARMTargetLowering::LowerFormalArguments( 3556 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3557 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3558 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3559 MachineFunction &MF = DAG.getMachineFunction(); 3560 MachineFrameInfo &MFI = MF.getFrameInfo(); 3561 3562 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3563 3564 // Assign locations to all of the incoming arguments. 3565 SmallVector<CCValAssign, 16> ArgLocs; 3566 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3567 *DAG.getContext()); 3568 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3569 3570 SmallVector<SDValue, 16> ArgValues; 3571 SDValue ArgValue; 3572 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3573 unsigned CurArgIdx = 0; 3574 3575 // Initially ArgRegsSaveSize is zero. 3576 // Then we increase this value each time we meet byval parameter. 3577 // We also increase this value in case of varargs function. 3578 AFI->setArgRegsSaveSize(0); 3579 3580 // Calculate the amount of stack space that we need to allocate to store 3581 // byval and variadic arguments that are passed in registers. 3582 // We need to know this before we allocate the first byval or variadic 3583 // argument, as they will be allocated a stack slot below the CFA (Canonical 3584 // Frame Address, the stack pointer at entry to the function). 3585 unsigned ArgRegBegin = ARM::R4; 3586 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3587 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3588 break; 3589 3590 CCValAssign &VA = ArgLocs[i]; 3591 unsigned Index = VA.getValNo(); 3592 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3593 if (!Flags.isByVal()) 3594 continue; 3595 3596 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3597 unsigned RBegin, REnd; 3598 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3599 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3600 3601 CCInfo.nextInRegsParam(); 3602 } 3603 CCInfo.rewindByValRegsInfo(); 3604 3605 int lastInsIndex = -1; 3606 if (isVarArg && MFI.hasVAStart()) { 3607 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3608 if (RegIdx != array_lengthof(GPRArgRegs)) 3609 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3610 } 3611 3612 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3613 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3614 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3615 3616 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3617 CCValAssign &VA = ArgLocs[i]; 3618 if (Ins[VA.getValNo()].isOrigArg()) { 3619 std::advance(CurOrigArg, 3620 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3621 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3622 } 3623 // Arguments stored in registers. 3624 if (VA.isRegLoc()) { 3625 EVT RegVT = VA.getLocVT(); 3626 3627 if (VA.needsCustom()) { 3628 // f64 and vector types are split up into multiple registers or 3629 // combinations of registers and stack slots. 3630 if (VA.getLocVT() == MVT::v2f64) { 3631 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3632 Chain, DAG, dl); 3633 VA = ArgLocs[++i]; // skip ahead to next loc 3634 SDValue ArgValue2; 3635 if (VA.isMemLoc()) { 3636 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3637 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3638 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3639 MachinePointerInfo::getFixedStack( 3640 DAG.getMachineFunction(), FI)); 3641 } else { 3642 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3643 Chain, DAG, dl); 3644 } 3645 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3646 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3647 ArgValue, ArgValue1, 3648 DAG.getIntPtrConstant(0, dl)); 3649 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3650 ArgValue, ArgValue2, 3651 DAG.getIntPtrConstant(1, dl)); 3652 } else 3653 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3654 3655 } else { 3656 const TargetRegisterClass *RC; 3657 3658 if (RegVT == MVT::f32) 3659 RC = &ARM::SPRRegClass; 3660 else if (RegVT == MVT::f64) 3661 RC = &ARM::DPRRegClass; 3662 else if (RegVT == MVT::v2f64) 3663 RC = &ARM::QPRRegClass; 3664 else if (RegVT == MVT::i32) 3665 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3666 : &ARM::GPRRegClass; 3667 else 3668 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3669 3670 // Transform the arguments in physical registers into virtual ones. 3671 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3672 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3673 } 3674 3675 // If this is an 8 or 16-bit value, it is really passed promoted 3676 // to 32 bits. Insert an assert[sz]ext to capture this, then 3677 // truncate to the right size. 3678 switch (VA.getLocInfo()) { 3679 default: llvm_unreachable("Unknown loc info!"); 3680 case CCValAssign::Full: break; 3681 case CCValAssign::BCvt: 3682 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3683 break; 3684 case CCValAssign::SExt: 3685 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3686 DAG.getValueType(VA.getValVT())); 3687 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3688 break; 3689 case CCValAssign::ZExt: 3690 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3691 DAG.getValueType(VA.getValVT())); 3692 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3693 break; 3694 } 3695 3696 InVals.push_back(ArgValue); 3697 3698 } else { // VA.isRegLoc() 3699 // sanity check 3700 assert(VA.isMemLoc()); 3701 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3702 3703 int index = VA.getValNo(); 3704 3705 // Some Ins[] entries become multiple ArgLoc[] entries. 3706 // Process them only once. 3707 if (index != lastInsIndex) 3708 { 3709 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3710 // FIXME: For now, all byval parameter objects are marked mutable. 3711 // This can be changed with more analysis. 3712 // In case of tail call optimization mark all arguments mutable. 3713 // Since they could be overwritten by lowering of arguments in case of 3714 // a tail call. 3715 if (Flags.isByVal()) { 3716 assert(Ins[index].isOrigArg() && 3717 "Byval arguments cannot be implicit"); 3718 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3719 3720 int FrameIndex = StoreByValRegs( 3721 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3722 VA.getLocMemOffset(), Flags.getByValSize()); 3723 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3724 CCInfo.nextInRegsParam(); 3725 } else { 3726 unsigned FIOffset = VA.getLocMemOffset(); 3727 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3728 FIOffset, true); 3729 3730 // Create load nodes to retrieve arguments from the stack. 3731 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3732 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3733 MachinePointerInfo::getFixedStack( 3734 DAG.getMachineFunction(), FI))); 3735 } 3736 lastInsIndex = index; 3737 } 3738 } 3739 } 3740 3741 // varargs 3742 if (isVarArg && MFI.hasVAStart()) 3743 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3744 CCInfo.getNextStackOffset(), 3745 TotalArgRegsSaveSize); 3746 3747 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3748 3749 return Chain; 3750 } 3751 3752 /// isFloatingPointZero - Return true if this is +0.0. 3753 static bool isFloatingPointZero(SDValue Op) { 3754 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3755 return CFP->getValueAPF().isPosZero(); 3756 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3757 // Maybe this has already been legalized into the constant pool? 3758 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3759 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3760 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3761 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3762 return CFP->getValueAPF().isPosZero(); 3763 } 3764 } else if (Op->getOpcode() == ISD::BITCAST && 3765 Op->getValueType(0) == MVT::f64) { 3766 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3767 // created by LowerConstantFP(). 3768 SDValue BitcastOp = Op->getOperand(0); 3769 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3770 isNullConstant(BitcastOp->getOperand(0))) 3771 return true; 3772 } 3773 return false; 3774 } 3775 3776 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3777 /// the given operands. 3778 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3779 SDValue &ARMcc, SelectionDAG &DAG, 3780 const SDLoc &dl) const { 3781 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3782 unsigned C = RHSC->getZExtValue(); 3783 if (!isLegalICmpImmediate(C)) { 3784 // Constant does not fit, try adjusting it by one? 3785 switch (CC) { 3786 default: break; 3787 case ISD::SETLT: 3788 case ISD::SETGE: 3789 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3790 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3791 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3792 } 3793 break; 3794 case ISD::SETULT: 3795 case ISD::SETUGE: 3796 if (C != 0 && isLegalICmpImmediate(C-1)) { 3797 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3798 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3799 } 3800 break; 3801 case ISD::SETLE: 3802 case ISD::SETGT: 3803 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3804 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3805 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3806 } 3807 break; 3808 case ISD::SETULE: 3809 case ISD::SETUGT: 3810 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3811 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3812 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3813 } 3814 break; 3815 } 3816 } 3817 } 3818 3819 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3820 ARMISD::NodeType CompareType; 3821 switch (CondCode) { 3822 default: 3823 CompareType = ARMISD::CMP; 3824 break; 3825 case ARMCC::EQ: 3826 case ARMCC::NE: 3827 // Uses only Z Flag 3828 CompareType = ARMISD::CMPZ; 3829 break; 3830 } 3831 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3832 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3833 } 3834 3835 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3836 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3837 SelectionDAG &DAG, const SDLoc &dl, 3838 bool InvalidOnQNaN) const { 3839 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3840 SDValue Cmp; 3841 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3842 if (!isFloatingPointZero(RHS)) 3843 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3844 else 3845 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3846 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3847 } 3848 3849 /// duplicateCmp - Glue values can have only one use, so this function 3850 /// duplicates a comparison node. 3851 SDValue 3852 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3853 unsigned Opc = Cmp.getOpcode(); 3854 SDLoc DL(Cmp); 3855 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3856 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3857 3858 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3859 Cmp = Cmp.getOperand(0); 3860 Opc = Cmp.getOpcode(); 3861 if (Opc == ARMISD::CMPFP) 3862 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3863 Cmp.getOperand(1), Cmp.getOperand(2)); 3864 else { 3865 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3866 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3867 Cmp.getOperand(1)); 3868 } 3869 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3870 } 3871 3872 std::pair<SDValue, SDValue> 3873 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3874 SDValue &ARMcc) const { 3875 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3876 3877 SDValue Value, OverflowCmp; 3878 SDValue LHS = Op.getOperand(0); 3879 SDValue RHS = Op.getOperand(1); 3880 SDLoc dl(Op); 3881 3882 // FIXME: We are currently always generating CMPs because we don't support 3883 // generating CMN through the backend. This is not as good as the natural 3884 // CMP case because it causes a register dependency and cannot be folded 3885 // later. 3886 3887 switch (Op.getOpcode()) { 3888 default: 3889 llvm_unreachable("Unknown overflow instruction!"); 3890 case ISD::SADDO: 3891 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3892 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3893 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3894 break; 3895 case ISD::UADDO: 3896 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3897 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3898 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3899 break; 3900 case ISD::SSUBO: 3901 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3902 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3903 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3904 break; 3905 case ISD::USUBO: 3906 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3907 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3908 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3909 break; 3910 } // switch (...) 3911 3912 return std::make_pair(Value, OverflowCmp); 3913 } 3914 3915 SDValue 3916 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3917 // Let legalize expand this if it isn't a legal type yet. 3918 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3919 return SDValue(); 3920 3921 SDValue Value, OverflowCmp; 3922 SDValue ARMcc; 3923 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3924 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3925 SDLoc dl(Op); 3926 // We use 0 and 1 as false and true values. 3927 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3928 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3929 EVT VT = Op.getValueType(); 3930 3931 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3932 ARMcc, CCR, OverflowCmp); 3933 3934 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3935 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3936 } 3937 3938 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3939 SDValue Cond = Op.getOperand(0); 3940 SDValue SelectTrue = Op.getOperand(1); 3941 SDValue SelectFalse = Op.getOperand(2); 3942 SDLoc dl(Op); 3943 unsigned Opc = Cond.getOpcode(); 3944 3945 if (Cond.getResNo() == 1 && 3946 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3947 Opc == ISD::USUBO)) { 3948 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3949 return SDValue(); 3950 3951 SDValue Value, OverflowCmp; 3952 SDValue ARMcc; 3953 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3954 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3955 EVT VT = Op.getValueType(); 3956 3957 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3958 OverflowCmp, DAG); 3959 } 3960 3961 // Convert: 3962 // 3963 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3964 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3965 // 3966 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3967 const ConstantSDNode *CMOVTrue = 3968 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3969 const ConstantSDNode *CMOVFalse = 3970 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3971 3972 if (CMOVTrue && CMOVFalse) { 3973 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3974 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3975 3976 SDValue True; 3977 SDValue False; 3978 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3979 True = SelectTrue; 3980 False = SelectFalse; 3981 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3982 True = SelectFalse; 3983 False = SelectTrue; 3984 } 3985 3986 if (True.getNode() && False.getNode()) { 3987 EVT VT = Op.getValueType(); 3988 SDValue ARMcc = Cond.getOperand(2); 3989 SDValue CCR = Cond.getOperand(3); 3990 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3991 assert(True.getValueType() == VT); 3992 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3993 } 3994 } 3995 } 3996 3997 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3998 // undefined bits before doing a full-word comparison with zero. 3999 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4000 DAG.getConstant(1, dl, Cond.getValueType())); 4001 4002 return DAG.getSelectCC(dl, Cond, 4003 DAG.getConstant(0, dl, Cond.getValueType()), 4004 SelectTrue, SelectFalse, ISD::SETNE); 4005 } 4006 4007 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4008 bool &swpCmpOps, bool &swpVselOps) { 4009 // Start by selecting the GE condition code for opcodes that return true for 4010 // 'equality' 4011 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4012 CC == ISD::SETULE) 4013 CondCode = ARMCC::GE; 4014 4015 // and GT for opcodes that return false for 'equality'. 4016 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4017 CC == ISD::SETULT) 4018 CondCode = ARMCC::GT; 4019 4020 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4021 // to swap the compare operands. 4022 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4023 CC == ISD::SETULT) 4024 swpCmpOps = true; 4025 4026 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4027 // If we have an unordered opcode, we need to swap the operands to the VSEL 4028 // instruction (effectively negating the condition). 4029 // 4030 // This also has the effect of swapping which one of 'less' or 'greater' 4031 // returns true, so we also swap the compare operands. It also switches 4032 // whether we return true for 'equality', so we compensate by picking the 4033 // opposite condition code to our original choice. 4034 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4035 CC == ISD::SETUGT) { 4036 swpCmpOps = !swpCmpOps; 4037 swpVselOps = !swpVselOps; 4038 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4039 } 4040 4041 // 'ordered' is 'anything but unordered', so use the VS condition code and 4042 // swap the VSEL operands. 4043 if (CC == ISD::SETO) { 4044 CondCode = ARMCC::VS; 4045 swpVselOps = true; 4046 } 4047 4048 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4049 // code and swap the VSEL operands. 4050 if (CC == ISD::SETUNE) { 4051 CondCode = ARMCC::EQ; 4052 swpVselOps = true; 4053 } 4054 } 4055 4056 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4057 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4058 SDValue Cmp, SelectionDAG &DAG) const { 4059 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4060 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4061 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4062 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4063 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4064 4065 SDValue TrueLow = TrueVal.getValue(0); 4066 SDValue TrueHigh = TrueVal.getValue(1); 4067 SDValue FalseLow = FalseVal.getValue(0); 4068 SDValue FalseHigh = FalseVal.getValue(1); 4069 4070 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4071 ARMcc, CCR, Cmp); 4072 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4073 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4074 4075 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4076 } else { 4077 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4078 Cmp); 4079 } 4080 } 4081 4082 static bool isGTorGE(ISD::CondCode CC) { 4083 return CC == ISD::SETGT || CC == ISD::SETGE; 4084 } 4085 4086 static bool isLTorLE(ISD::CondCode CC) { 4087 return CC == ISD::SETLT || CC == ISD::SETLE; 4088 } 4089 4090 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4091 // All of these conditions (and their <= and >= counterparts) will do: 4092 // x < k ? k : x 4093 // x > k ? x : k 4094 // k < x ? x : k 4095 // k > x ? k : x 4096 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4097 const SDValue TrueVal, const SDValue FalseVal, 4098 const ISD::CondCode CC, const SDValue K) { 4099 return (isGTorGE(CC) && 4100 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4101 (isLTorLE(CC) && 4102 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4103 } 4104 4105 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4106 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4107 const SDValue TrueVal, const SDValue FalseVal, 4108 const ISD::CondCode CC, const SDValue K) { 4109 return (isGTorGE(CC) && 4110 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4111 (isLTorLE(CC) && 4112 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4113 } 4114 4115 // Check if two chained conditionals could be converted into SSAT. 4116 // 4117 // SSAT can replace a set of two conditional selectors that bound a number to an 4118 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4119 // 4120 // x < -k ? -k : (x > k ? k : x) 4121 // x < -k ? -k : (x < k ? x : k) 4122 // x > -k ? (x > k ? k : x) : -k 4123 // x < k ? (x < -k ? -k : x) : k 4124 // etc. 4125 // 4126 // It returns true if the conversion can be done, false otherwise. 4127 // Additionally, the variable is returned in parameter V and the constant in K. 4128 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4129 uint64_t &K) { 4130 SDValue LHS1 = Op.getOperand(0); 4131 SDValue RHS1 = Op.getOperand(1); 4132 SDValue TrueVal1 = Op.getOperand(2); 4133 SDValue FalseVal1 = Op.getOperand(3); 4134 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4135 4136 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4137 if (Op2.getOpcode() != ISD::SELECT_CC) 4138 return false; 4139 4140 SDValue LHS2 = Op2.getOperand(0); 4141 SDValue RHS2 = Op2.getOperand(1); 4142 SDValue TrueVal2 = Op2.getOperand(2); 4143 SDValue FalseVal2 = Op2.getOperand(3); 4144 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4145 4146 // Find out which are the constants and which are the variables 4147 // in each conditional 4148 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4149 ? &RHS1 4150 : nullptr; 4151 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4152 ? &RHS2 4153 : nullptr; 4154 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4155 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4156 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4157 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4158 4159 // We must detect cases where the original operations worked with 16- or 4160 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4161 // must work with sign-extended values but the select operations return 4162 // the original non-extended value. 4163 SDValue V2TmpReg = V2Tmp; 4164 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4165 V2TmpReg = V2Tmp->getOperand(0); 4166 4167 // Check that the registers and the constants have the correct values 4168 // in both conditionals 4169 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4170 V2TmpReg != V2) 4171 return false; 4172 4173 // Figure out which conditional is saturating the lower/upper bound. 4174 const SDValue *LowerCheckOp = 4175 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4176 ? &Op 4177 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4178 ? &Op2 4179 : nullptr; 4180 const SDValue *UpperCheckOp = 4181 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4182 ? &Op 4183 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4184 ? &Op2 4185 : nullptr; 4186 4187 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4188 return false; 4189 4190 // Check that the constant in the lower-bound check is 4191 // the opposite of the constant in the upper-bound check 4192 // in 1's complement. 4193 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4194 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4195 int64_t PosVal = std::max(Val1, Val2); 4196 4197 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4198 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4199 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 4200 4201 V = V2; 4202 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4203 return true; 4204 } 4205 4206 return false; 4207 } 4208 4209 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4210 EVT VT = Op.getValueType(); 4211 SDLoc dl(Op); 4212 4213 // Try to convert two saturating conditional selects into a single SSAT 4214 SDValue SatValue; 4215 uint64_t SatConstant; 4216 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4217 isSaturatingConditional(Op, SatValue, SatConstant)) 4218 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4219 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4220 4221 SDValue LHS = Op.getOperand(0); 4222 SDValue RHS = Op.getOperand(1); 4223 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4224 SDValue TrueVal = Op.getOperand(2); 4225 SDValue FalseVal = Op.getOperand(3); 4226 4227 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4228 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4229 dl); 4230 4231 // If softenSetCCOperands only returned one value, we should compare it to 4232 // zero. 4233 if (!RHS.getNode()) { 4234 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4235 CC = ISD::SETNE; 4236 } 4237 } 4238 4239 if (LHS.getValueType() == MVT::i32) { 4240 // Try to generate VSEL on ARMv8. 4241 // The VSEL instruction can't use all the usual ARM condition 4242 // codes: it only has two bits to select the condition code, so it's 4243 // constrained to use only GE, GT, VS and EQ. 4244 // 4245 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4246 // swap the operands of the previous compare instruction (effectively 4247 // inverting the compare condition, swapping 'less' and 'greater') and 4248 // sometimes need to swap the operands to the VSEL (which inverts the 4249 // condition in the sense of firing whenever the previous condition didn't) 4250 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4251 TrueVal.getValueType() == MVT::f64)) { 4252 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4253 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4254 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4255 CC = ISD::getSetCCInverse(CC, true); 4256 std::swap(TrueVal, FalseVal); 4257 } 4258 } 4259 4260 SDValue ARMcc; 4261 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4262 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4263 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4264 } 4265 4266 ARMCC::CondCodes CondCode, CondCode2; 4267 bool InvalidOnQNaN; 4268 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4269 4270 // Try to generate VMAXNM/VMINNM on ARMv8. 4271 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4272 TrueVal.getValueType() == MVT::f64)) { 4273 bool swpCmpOps = false; 4274 bool swpVselOps = false; 4275 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4276 4277 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4278 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4279 if (swpCmpOps) 4280 std::swap(LHS, RHS); 4281 if (swpVselOps) 4282 std::swap(TrueVal, FalseVal); 4283 } 4284 } 4285 4286 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4287 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4288 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4289 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4290 if (CondCode2 != ARMCC::AL) { 4291 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4292 // FIXME: Needs another CMP because flag can have but one use. 4293 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4294 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4295 } 4296 return Result; 4297 } 4298 4299 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4300 /// to morph to an integer compare sequence. 4301 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4302 const ARMSubtarget *Subtarget) { 4303 SDNode *N = Op.getNode(); 4304 if (!N->hasOneUse()) 4305 // Otherwise it requires moving the value from fp to integer registers. 4306 return false; 4307 if (!N->getNumValues()) 4308 return false; 4309 EVT VT = Op.getValueType(); 4310 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4311 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4312 // vmrs are very slow, e.g. cortex-a8. 4313 return false; 4314 4315 if (isFloatingPointZero(Op)) { 4316 SeenZero = true; 4317 return true; 4318 } 4319 return ISD::isNormalLoad(N); 4320 } 4321 4322 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4323 if (isFloatingPointZero(Op)) 4324 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4325 4326 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4327 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4328 Ld->getPointerInfo(), Ld->getAlignment(), 4329 Ld->getMemOperand()->getFlags()); 4330 4331 llvm_unreachable("Unknown VFP cmp argument!"); 4332 } 4333 4334 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4335 SDValue &RetVal1, SDValue &RetVal2) { 4336 SDLoc dl(Op); 4337 4338 if (isFloatingPointZero(Op)) { 4339 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4340 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4341 return; 4342 } 4343 4344 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4345 SDValue Ptr = Ld->getBasePtr(); 4346 RetVal1 = 4347 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4348 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4349 4350 EVT PtrType = Ptr.getValueType(); 4351 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4352 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4353 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4354 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4355 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4356 Ld->getMemOperand()->getFlags()); 4357 return; 4358 } 4359 4360 llvm_unreachable("Unknown VFP cmp argument!"); 4361 } 4362 4363 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4364 /// f32 and even f64 comparisons to integer ones. 4365 SDValue 4366 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4367 SDValue Chain = Op.getOperand(0); 4368 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4369 SDValue LHS = Op.getOperand(2); 4370 SDValue RHS = Op.getOperand(3); 4371 SDValue Dest = Op.getOperand(4); 4372 SDLoc dl(Op); 4373 4374 bool LHSSeenZero = false; 4375 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4376 bool RHSSeenZero = false; 4377 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4378 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4379 // If unsafe fp math optimization is enabled and there are no other uses of 4380 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4381 // to an integer comparison. 4382 if (CC == ISD::SETOEQ) 4383 CC = ISD::SETEQ; 4384 else if (CC == ISD::SETUNE) 4385 CC = ISD::SETNE; 4386 4387 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4388 SDValue ARMcc; 4389 if (LHS.getValueType() == MVT::f32) { 4390 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4391 bitcastf32Toi32(LHS, DAG), Mask); 4392 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4393 bitcastf32Toi32(RHS, DAG), Mask); 4394 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4395 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4396 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4397 Chain, Dest, ARMcc, CCR, Cmp); 4398 } 4399 4400 SDValue LHS1, LHS2; 4401 SDValue RHS1, RHS2; 4402 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4403 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4404 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4405 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4406 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4407 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4408 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4409 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4410 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4411 } 4412 4413 return SDValue(); 4414 } 4415 4416 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4417 SDValue Chain = Op.getOperand(0); 4418 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4419 SDValue LHS = Op.getOperand(2); 4420 SDValue RHS = Op.getOperand(3); 4421 SDValue Dest = Op.getOperand(4); 4422 SDLoc dl(Op); 4423 4424 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4425 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4426 dl); 4427 4428 // If softenSetCCOperands only returned one value, we should compare it to 4429 // zero. 4430 if (!RHS.getNode()) { 4431 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4432 CC = ISD::SETNE; 4433 } 4434 } 4435 4436 if (LHS.getValueType() == MVT::i32) { 4437 SDValue ARMcc; 4438 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4439 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4440 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4441 Chain, Dest, ARMcc, CCR, Cmp); 4442 } 4443 4444 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4445 4446 if (getTargetMachine().Options.UnsafeFPMath && 4447 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4448 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4449 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4450 return Result; 4451 } 4452 4453 ARMCC::CondCodes CondCode, CondCode2; 4454 bool InvalidOnQNaN; 4455 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4456 4457 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4458 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4459 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4460 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4461 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4462 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4463 if (CondCode2 != ARMCC::AL) { 4464 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4465 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4466 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4467 } 4468 return Res; 4469 } 4470 4471 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4472 SDValue Chain = Op.getOperand(0); 4473 SDValue Table = Op.getOperand(1); 4474 SDValue Index = Op.getOperand(2); 4475 SDLoc dl(Op); 4476 4477 EVT PTy = getPointerTy(DAG.getDataLayout()); 4478 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4479 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4480 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4481 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4482 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4483 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4484 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4485 // which does another jump to the destination. This also makes it easier 4486 // to translate it to TBB / TBH later (Thumb2 only). 4487 // FIXME: This might not work if the function is extremely large. 4488 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4489 Addr, Op.getOperand(2), JTI); 4490 } 4491 if (isPositionIndependent() || Subtarget->isROPI()) { 4492 Addr = 4493 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4494 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4495 Chain = Addr.getValue(1); 4496 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4497 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4498 } else { 4499 Addr = 4500 DAG.getLoad(PTy, dl, Chain, Addr, 4501 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4502 Chain = Addr.getValue(1); 4503 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4504 } 4505 } 4506 4507 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4508 EVT VT = Op.getValueType(); 4509 SDLoc dl(Op); 4510 4511 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4512 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4513 return Op; 4514 return DAG.UnrollVectorOp(Op.getNode()); 4515 } 4516 4517 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4518 "Invalid type for custom lowering!"); 4519 if (VT != MVT::v4i16) 4520 return DAG.UnrollVectorOp(Op.getNode()); 4521 4522 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4523 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4524 } 4525 4526 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4527 EVT VT = Op.getValueType(); 4528 if (VT.isVector()) 4529 return LowerVectorFP_TO_INT(Op, DAG); 4530 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4531 RTLIB::Libcall LC; 4532 if (Op.getOpcode() == ISD::FP_TO_SINT) 4533 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4534 Op.getValueType()); 4535 else 4536 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4537 Op.getValueType()); 4538 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4539 /*isSigned*/ false, SDLoc(Op)).first; 4540 } 4541 4542 return Op; 4543 } 4544 4545 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4546 EVT VT = Op.getValueType(); 4547 SDLoc dl(Op); 4548 4549 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4550 if (VT.getVectorElementType() == MVT::f32) 4551 return Op; 4552 return DAG.UnrollVectorOp(Op.getNode()); 4553 } 4554 4555 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4556 "Invalid type for custom lowering!"); 4557 if (VT != MVT::v4f32) 4558 return DAG.UnrollVectorOp(Op.getNode()); 4559 4560 unsigned CastOpc; 4561 unsigned Opc; 4562 switch (Op.getOpcode()) { 4563 default: llvm_unreachable("Invalid opcode!"); 4564 case ISD::SINT_TO_FP: 4565 CastOpc = ISD::SIGN_EXTEND; 4566 Opc = ISD::SINT_TO_FP; 4567 break; 4568 case ISD::UINT_TO_FP: 4569 CastOpc = ISD::ZERO_EXTEND; 4570 Opc = ISD::UINT_TO_FP; 4571 break; 4572 } 4573 4574 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4575 return DAG.getNode(Opc, dl, VT, Op); 4576 } 4577 4578 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4579 EVT VT = Op.getValueType(); 4580 if (VT.isVector()) 4581 return LowerVectorINT_TO_FP(Op, DAG); 4582 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4583 RTLIB::Libcall LC; 4584 if (Op.getOpcode() == ISD::SINT_TO_FP) 4585 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4586 Op.getValueType()); 4587 else 4588 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4589 Op.getValueType()); 4590 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4591 /*isSigned*/ false, SDLoc(Op)).first; 4592 } 4593 4594 return Op; 4595 } 4596 4597 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4598 // Implement fcopysign with a fabs and a conditional fneg. 4599 SDValue Tmp0 = Op.getOperand(0); 4600 SDValue Tmp1 = Op.getOperand(1); 4601 SDLoc dl(Op); 4602 EVT VT = Op.getValueType(); 4603 EVT SrcVT = Tmp1.getValueType(); 4604 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4605 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4606 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4607 4608 if (UseNEON) { 4609 // Use VBSL to copy the sign bit. 4610 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4611 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4612 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4613 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4614 if (VT == MVT::f64) 4615 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4616 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4617 DAG.getConstant(32, dl, MVT::i32)); 4618 else /*if (VT == MVT::f32)*/ 4619 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4620 if (SrcVT == MVT::f32) { 4621 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4622 if (VT == MVT::f64) 4623 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4624 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4625 DAG.getConstant(32, dl, MVT::i32)); 4626 } else if (VT == MVT::f32) 4627 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4628 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4629 DAG.getConstant(32, dl, MVT::i32)); 4630 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4631 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4632 4633 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4634 dl, MVT::i32); 4635 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4636 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4637 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4638 4639 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4640 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4641 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4642 if (VT == MVT::f32) { 4643 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4644 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4645 DAG.getConstant(0, dl, MVT::i32)); 4646 } else { 4647 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4648 } 4649 4650 return Res; 4651 } 4652 4653 // Bitcast operand 1 to i32. 4654 if (SrcVT == MVT::f64) 4655 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4656 Tmp1).getValue(1); 4657 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4658 4659 // Or in the signbit with integer operations. 4660 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4661 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4662 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4663 if (VT == MVT::f32) { 4664 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4665 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4666 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4667 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4668 } 4669 4670 // f64: Or the high part with signbit and then combine two parts. 4671 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4672 Tmp0); 4673 SDValue Lo = Tmp0.getValue(0); 4674 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4675 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4676 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4677 } 4678 4679 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4680 MachineFunction &MF = DAG.getMachineFunction(); 4681 MachineFrameInfo &MFI = MF.getFrameInfo(); 4682 MFI.setReturnAddressIsTaken(true); 4683 4684 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4685 return SDValue(); 4686 4687 EVT VT = Op.getValueType(); 4688 SDLoc dl(Op); 4689 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4690 if (Depth) { 4691 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4692 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4693 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4694 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4695 MachinePointerInfo()); 4696 } 4697 4698 // Return LR, which contains the return address. Mark it an implicit live-in. 4699 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4700 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4701 } 4702 4703 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4704 const ARMBaseRegisterInfo &ARI = 4705 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4706 MachineFunction &MF = DAG.getMachineFunction(); 4707 MachineFrameInfo &MFI = MF.getFrameInfo(); 4708 MFI.setFrameAddressIsTaken(true); 4709 4710 EVT VT = Op.getValueType(); 4711 SDLoc dl(Op); // FIXME probably not meaningful 4712 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4713 unsigned FrameReg = ARI.getFrameRegister(MF); 4714 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4715 while (Depth--) 4716 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4717 MachinePointerInfo()); 4718 return FrameAddr; 4719 } 4720 4721 // FIXME? Maybe this could be a TableGen attribute on some registers and 4722 // this table could be generated automatically from RegInfo. 4723 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4724 SelectionDAG &DAG) const { 4725 unsigned Reg = StringSwitch<unsigned>(RegName) 4726 .Case("sp", ARM::SP) 4727 .Default(0); 4728 if (Reg) 4729 return Reg; 4730 report_fatal_error(Twine("Invalid register name \"" 4731 + StringRef(RegName) + "\".")); 4732 } 4733 4734 // Result is 64 bit value so split into two 32 bit values and return as a 4735 // pair of values. 4736 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4737 SelectionDAG &DAG) { 4738 SDLoc DL(N); 4739 4740 // This function is only supposed to be called for i64 type destination. 4741 assert(N->getValueType(0) == MVT::i64 4742 && "ExpandREAD_REGISTER called for non-i64 type result."); 4743 4744 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4745 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4746 N->getOperand(0), 4747 N->getOperand(1)); 4748 4749 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4750 Read.getValue(1))); 4751 Results.push_back(Read.getOperand(0)); 4752 } 4753 4754 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4755 /// When \p DstVT, the destination type of \p BC, is on the vector 4756 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4757 /// it might be possible to combine them, such that everything stays on the 4758 /// vector register bank. 4759 /// \p return The node that would replace \p BT, if the combine 4760 /// is possible. 4761 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4762 SelectionDAG &DAG) { 4763 SDValue Op = BC->getOperand(0); 4764 EVT DstVT = BC->getValueType(0); 4765 4766 // The only vector instruction that can produce a scalar (remember, 4767 // since the bitcast was about to be turned into VMOVDRR, the source 4768 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4769 // Moreover, we can do this combine only if there is one use. 4770 // Finally, if the destination type is not a vector, there is not 4771 // much point on forcing everything on the vector bank. 4772 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4773 !Op.hasOneUse()) 4774 return SDValue(); 4775 4776 // If the index is not constant, we will introduce an additional 4777 // multiply that will stick. 4778 // Give up in that case. 4779 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4780 if (!Index) 4781 return SDValue(); 4782 unsigned DstNumElt = DstVT.getVectorNumElements(); 4783 4784 // Compute the new index. 4785 const APInt &APIntIndex = Index->getAPIntValue(); 4786 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4787 NewIndex *= APIntIndex; 4788 // Check if the new constant index fits into i32. 4789 if (NewIndex.getBitWidth() > 32) 4790 return SDValue(); 4791 4792 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4793 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4794 SDLoc dl(Op); 4795 SDValue ExtractSrc = Op.getOperand(0); 4796 EVT VecVT = EVT::getVectorVT( 4797 *DAG.getContext(), DstVT.getScalarType(), 4798 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4799 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4800 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4801 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4802 } 4803 4804 /// ExpandBITCAST - If the target supports VFP, this function is called to 4805 /// expand a bit convert where either the source or destination type is i64 to 4806 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4807 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4808 /// vectors), since the legalizer won't know what to do with that. 4809 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4810 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4811 SDLoc dl(N); 4812 SDValue Op = N->getOperand(0); 4813 4814 // This function is only supposed to be called for i64 types, either as the 4815 // source or destination of the bit convert. 4816 EVT SrcVT = Op.getValueType(); 4817 EVT DstVT = N->getValueType(0); 4818 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4819 "ExpandBITCAST called for non-i64 type"); 4820 4821 // Turn i64->f64 into VMOVDRR. 4822 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4823 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4824 // if we can combine the bitcast with its source. 4825 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4826 return Val; 4827 4828 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4829 DAG.getConstant(0, dl, MVT::i32)); 4830 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4831 DAG.getConstant(1, dl, MVT::i32)); 4832 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4833 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4834 } 4835 4836 // Turn f64->i64 into VMOVRRD. 4837 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4838 SDValue Cvt; 4839 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4840 SrcVT.getVectorNumElements() > 1) 4841 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4842 DAG.getVTList(MVT::i32, MVT::i32), 4843 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4844 else 4845 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4846 DAG.getVTList(MVT::i32, MVT::i32), Op); 4847 // Merge the pieces into a single i64 value. 4848 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4849 } 4850 4851 return SDValue(); 4852 } 4853 4854 /// getZeroVector - Returns a vector of specified type with all zero elements. 4855 /// Zero vectors are used to represent vector negation and in those cases 4856 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4857 /// not support i64 elements, so sometimes the zero vectors will need to be 4858 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4859 /// zero vector. 4860 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4861 assert(VT.isVector() && "Expected a vector type"); 4862 // The canonical modified immediate encoding of a zero vector is....0! 4863 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4864 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4865 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4866 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4867 } 4868 4869 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4870 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4871 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4872 SelectionDAG &DAG) const { 4873 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4874 EVT VT = Op.getValueType(); 4875 unsigned VTBits = VT.getSizeInBits(); 4876 SDLoc dl(Op); 4877 SDValue ShOpLo = Op.getOperand(0); 4878 SDValue ShOpHi = Op.getOperand(1); 4879 SDValue ShAmt = Op.getOperand(2); 4880 SDValue ARMcc; 4881 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4882 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4883 4884 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4885 4886 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4887 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4888 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4889 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4890 DAG.getConstant(VTBits, dl, MVT::i32)); 4891 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4892 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4893 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4894 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4895 ISD::SETGE, ARMcc, DAG, dl); 4896 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 4897 ARMcc, CCR, CmpLo); 4898 4899 4900 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4901 SDValue HiBigShift = Opc == ISD::SRA 4902 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4903 DAG.getConstant(VTBits - 1, dl, VT)) 4904 : DAG.getConstant(0, dl, VT); 4905 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4906 ISD::SETGE, ARMcc, DAG, dl); 4907 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4908 ARMcc, CCR, CmpHi); 4909 4910 SDValue Ops[2] = { Lo, Hi }; 4911 return DAG.getMergeValues(Ops, dl); 4912 } 4913 4914 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4915 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4916 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4917 SelectionDAG &DAG) const { 4918 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4919 EVT VT = Op.getValueType(); 4920 unsigned VTBits = VT.getSizeInBits(); 4921 SDLoc dl(Op); 4922 SDValue ShOpLo = Op.getOperand(0); 4923 SDValue ShOpHi = Op.getOperand(1); 4924 SDValue ShAmt = Op.getOperand(2); 4925 SDValue ARMcc; 4926 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4927 4928 assert(Op.getOpcode() == ISD::SHL_PARTS); 4929 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4930 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4931 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4932 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4933 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4934 4935 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4936 DAG.getConstant(VTBits, dl, MVT::i32)); 4937 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4938 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4939 ISD::SETGE, ARMcc, DAG, dl); 4940 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4941 ARMcc, CCR, CmpHi); 4942 4943 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4944 ISD::SETGE, ARMcc, DAG, dl); 4945 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4946 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 4947 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 4948 4949 SDValue Ops[2] = { Lo, Hi }; 4950 return DAG.getMergeValues(Ops, dl); 4951 } 4952 4953 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4954 SelectionDAG &DAG) const { 4955 // The rounding mode is in bits 23:22 of the FPSCR. 4956 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4957 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4958 // so that the shift + and get folded into a bitfield extract. 4959 SDLoc dl(Op); 4960 SDValue Ops[] = { DAG.getEntryNode(), 4961 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 4962 4963 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 4964 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4965 DAG.getConstant(1U << 22, dl, MVT::i32)); 4966 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4967 DAG.getConstant(22, dl, MVT::i32)); 4968 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4969 DAG.getConstant(3, dl, MVT::i32)); 4970 } 4971 4972 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4973 const ARMSubtarget *ST) { 4974 SDLoc dl(N); 4975 EVT VT = N->getValueType(0); 4976 if (VT.isVector()) { 4977 assert(ST->hasNEON()); 4978 4979 // Compute the least significant set bit: LSB = X & -X 4980 SDValue X = N->getOperand(0); 4981 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4982 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4983 4984 EVT ElemTy = VT.getVectorElementType(); 4985 4986 if (ElemTy == MVT::i8) { 4987 // Compute with: cttz(x) = ctpop(lsb - 1) 4988 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4989 DAG.getTargetConstant(1, dl, ElemTy)); 4990 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4991 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4992 } 4993 4994 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4995 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4996 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4997 unsigned NumBits = ElemTy.getSizeInBits(); 4998 SDValue WidthMinus1 = 4999 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5000 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5001 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5002 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5003 } 5004 5005 // Compute with: cttz(x) = ctpop(lsb - 1) 5006 5007 // Since we can only compute the number of bits in a byte with vcnt.8, we 5008 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5009 // and i64. 5010 5011 // Compute LSB - 1. 5012 SDValue Bits; 5013 if (ElemTy == MVT::i64) { 5014 // Load constant 0xffff'ffff'ffff'ffff to register. 5015 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5016 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5017 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5018 } else { 5019 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5020 DAG.getTargetConstant(1, dl, ElemTy)); 5021 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5022 } 5023 5024 // Count #bits with vcnt.8. 5025 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5026 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5027 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5028 5029 // Gather the #bits with vpaddl (pairwise add.) 5030 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5031 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5032 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5033 Cnt8); 5034 if (ElemTy == MVT::i16) 5035 return Cnt16; 5036 5037 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5038 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5039 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5040 Cnt16); 5041 if (ElemTy == MVT::i32) 5042 return Cnt32; 5043 5044 assert(ElemTy == MVT::i64); 5045 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5046 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5047 Cnt32); 5048 return Cnt64; 5049 } 5050 5051 if (!ST->hasV6T2Ops()) 5052 return SDValue(); 5053 5054 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5055 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5056 } 5057 5058 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5059 /// for each 16-bit element from operand, repeated. The basic idea is to 5060 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5061 /// 5062 /// Trace for v4i16: 5063 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5064 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5065 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5066 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5067 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5068 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5069 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5070 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5071 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5072 EVT VT = N->getValueType(0); 5073 SDLoc DL(N); 5074 5075 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5076 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5077 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5078 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5079 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5080 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5081 } 5082 5083 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5084 /// bit-count for each 16-bit element from the operand. We need slightly 5085 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5086 /// 64/128-bit registers. 5087 /// 5088 /// Trace for v4i16: 5089 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5090 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5091 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5092 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5093 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5094 EVT VT = N->getValueType(0); 5095 SDLoc DL(N); 5096 5097 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5098 if (VT.is64BitVector()) { 5099 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5100 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5101 DAG.getIntPtrConstant(0, DL)); 5102 } else { 5103 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5104 BitCounts, DAG.getIntPtrConstant(0, DL)); 5105 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5106 } 5107 } 5108 5109 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5110 /// bit-count for each 32-bit element from the operand. The idea here is 5111 /// to split the vector into 16-bit elements, leverage the 16-bit count 5112 /// routine, and then combine the results. 5113 /// 5114 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5115 /// input = [v0 v1 ] (vi: 32-bit elements) 5116 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5117 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5118 /// vrev: N0 = [k1 k0 k3 k2 ] 5119 /// [k0 k1 k2 k3 ] 5120 /// N1 =+[k1 k0 k3 k2 ] 5121 /// [k0 k2 k1 k3 ] 5122 /// N2 =+[k1 k3 k0 k2 ] 5123 /// [k0 k2 k1 k3 ] 5124 /// Extended =+[k1 k3 k0 k2 ] 5125 /// [k0 k2 ] 5126 /// Extracted=+[k1 k3 ] 5127 /// 5128 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5129 EVT VT = N->getValueType(0); 5130 SDLoc DL(N); 5131 5132 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5133 5134 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5135 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5136 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5137 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5138 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5139 5140 if (VT.is64BitVector()) { 5141 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5142 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5143 DAG.getIntPtrConstant(0, DL)); 5144 } else { 5145 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5146 DAG.getIntPtrConstant(0, DL)); 5147 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5148 } 5149 } 5150 5151 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5152 const ARMSubtarget *ST) { 5153 EVT VT = N->getValueType(0); 5154 5155 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5156 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5157 VT == MVT::v4i16 || VT == MVT::v8i16) && 5158 "Unexpected type for custom ctpop lowering"); 5159 5160 if (VT.getVectorElementType() == MVT::i32) 5161 return lowerCTPOP32BitElements(N, DAG); 5162 else 5163 return lowerCTPOP16BitElements(N, DAG); 5164 } 5165 5166 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5167 const ARMSubtarget *ST) { 5168 EVT VT = N->getValueType(0); 5169 SDLoc dl(N); 5170 5171 if (!VT.isVector()) 5172 return SDValue(); 5173 5174 // Lower vector shifts on NEON to use VSHL. 5175 assert(ST->hasNEON() && "unexpected vector shift"); 5176 5177 // Left shifts translate directly to the vshiftu intrinsic. 5178 if (N->getOpcode() == ISD::SHL) 5179 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5180 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5181 MVT::i32), 5182 N->getOperand(0), N->getOperand(1)); 5183 5184 assert((N->getOpcode() == ISD::SRA || 5185 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5186 5187 // NEON uses the same intrinsics for both left and right shifts. For 5188 // right shifts, the shift amounts are negative, so negate the vector of 5189 // shift amounts. 5190 EVT ShiftVT = N->getOperand(1).getValueType(); 5191 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5192 getZeroVector(ShiftVT, DAG, dl), 5193 N->getOperand(1)); 5194 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5195 Intrinsic::arm_neon_vshifts : 5196 Intrinsic::arm_neon_vshiftu); 5197 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5198 DAG.getConstant(vshiftInt, dl, MVT::i32), 5199 N->getOperand(0), NegatedCount); 5200 } 5201 5202 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5203 const ARMSubtarget *ST) { 5204 EVT VT = N->getValueType(0); 5205 SDLoc dl(N); 5206 5207 // We can get here for a node like i32 = ISD::SHL i32, i64 5208 if (VT != MVT::i64) 5209 return SDValue(); 5210 5211 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5212 "Unknown shift to lower!"); 5213 5214 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5215 if (!isOneConstant(N->getOperand(1))) 5216 return SDValue(); 5217 5218 // If we are in thumb mode, we don't have RRX. 5219 if (ST->isThumb1Only()) return SDValue(); 5220 5221 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5222 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5223 DAG.getConstant(0, dl, MVT::i32)); 5224 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5225 DAG.getConstant(1, dl, MVT::i32)); 5226 5227 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5228 // captures the result into a carry flag. 5229 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5230 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5231 5232 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5233 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5234 5235 // Merge the pieces into a single i64 value. 5236 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5237 } 5238 5239 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5240 SDValue TmpOp0, TmpOp1; 5241 bool Invert = false; 5242 bool Swap = false; 5243 unsigned Opc = 0; 5244 5245 SDValue Op0 = Op.getOperand(0); 5246 SDValue Op1 = Op.getOperand(1); 5247 SDValue CC = Op.getOperand(2); 5248 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5249 EVT VT = Op.getValueType(); 5250 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5251 SDLoc dl(Op); 5252 5253 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5254 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5255 // Special-case integer 64-bit equality comparisons. They aren't legal, 5256 // but they can be lowered with a few vector instructions. 5257 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5258 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5259 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5260 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5261 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5262 DAG.getCondCode(ISD::SETEQ)); 5263 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5264 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5265 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5266 if (SetCCOpcode == ISD::SETNE) 5267 Merged = DAG.getNOT(dl, Merged, CmpVT); 5268 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5269 return Merged; 5270 } 5271 5272 if (CmpVT.getVectorElementType() == MVT::i64) 5273 // 64-bit comparisons are not legal in general. 5274 return SDValue(); 5275 5276 if (Op1.getValueType().isFloatingPoint()) { 5277 switch (SetCCOpcode) { 5278 default: llvm_unreachable("Illegal FP comparison"); 5279 case ISD::SETUNE: 5280 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5281 case ISD::SETOEQ: 5282 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5283 case ISD::SETOLT: 5284 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5285 case ISD::SETOGT: 5286 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5287 case ISD::SETOLE: 5288 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5289 case ISD::SETOGE: 5290 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5291 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5292 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5293 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5294 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5295 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5296 case ISD::SETONE: 5297 // Expand this to (OLT | OGT). 5298 TmpOp0 = Op0; 5299 TmpOp1 = Op1; 5300 Opc = ISD::OR; 5301 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5302 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5303 break; 5304 case ISD::SETUO: 5305 Invert = true; 5306 LLVM_FALLTHROUGH; 5307 case ISD::SETO: 5308 // Expand this to (OLT | OGE). 5309 TmpOp0 = Op0; 5310 TmpOp1 = Op1; 5311 Opc = ISD::OR; 5312 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5313 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5314 break; 5315 } 5316 } else { 5317 // Integer comparisons. 5318 switch (SetCCOpcode) { 5319 default: llvm_unreachable("Illegal integer comparison"); 5320 case ISD::SETNE: Invert = true; 5321 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5322 case ISD::SETLT: Swap = true; 5323 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5324 case ISD::SETLE: Swap = true; 5325 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5326 case ISD::SETULT: Swap = true; 5327 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5328 case ISD::SETULE: Swap = true; 5329 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5330 } 5331 5332 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5333 if (Opc == ARMISD::VCEQ) { 5334 5335 SDValue AndOp; 5336 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5337 AndOp = Op0; 5338 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5339 AndOp = Op1; 5340 5341 // Ignore bitconvert. 5342 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5343 AndOp = AndOp.getOperand(0); 5344 5345 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5346 Opc = ARMISD::VTST; 5347 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5348 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5349 Invert = !Invert; 5350 } 5351 } 5352 } 5353 5354 if (Swap) 5355 std::swap(Op0, Op1); 5356 5357 // If one of the operands is a constant vector zero, attempt to fold the 5358 // comparison to a specialized compare-against-zero form. 5359 SDValue SingleOp; 5360 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5361 SingleOp = Op0; 5362 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5363 if (Opc == ARMISD::VCGE) 5364 Opc = ARMISD::VCLEZ; 5365 else if (Opc == ARMISD::VCGT) 5366 Opc = ARMISD::VCLTZ; 5367 SingleOp = Op1; 5368 } 5369 5370 SDValue Result; 5371 if (SingleOp.getNode()) { 5372 switch (Opc) { 5373 case ARMISD::VCEQ: 5374 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5375 case ARMISD::VCGE: 5376 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5377 case ARMISD::VCLEZ: 5378 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5379 case ARMISD::VCGT: 5380 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5381 case ARMISD::VCLTZ: 5382 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5383 default: 5384 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5385 } 5386 } else { 5387 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5388 } 5389 5390 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5391 5392 if (Invert) 5393 Result = DAG.getNOT(dl, Result, VT); 5394 5395 return Result; 5396 } 5397 5398 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5399 SDValue LHS = Op.getOperand(0); 5400 SDValue RHS = Op.getOperand(1); 5401 SDValue Carry = Op.getOperand(2); 5402 SDValue Cond = Op.getOperand(3); 5403 SDLoc DL(Op); 5404 5405 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5406 5407 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5408 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5409 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5410 5411 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5412 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5413 SDValue ARMcc = DAG.getConstant( 5414 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5415 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5416 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5417 Cmp.getValue(1), SDValue()); 5418 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5419 CCR, Chain.getValue(1)); 5420 } 5421 5422 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5423 /// valid vector constant for a NEON instruction with a "modified immediate" 5424 /// operand (e.g., VMOV). If so, return the encoded value. 5425 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5426 unsigned SplatBitSize, SelectionDAG &DAG, 5427 const SDLoc &dl, EVT &VT, bool is128Bits, 5428 NEONModImmType type) { 5429 unsigned OpCmode, Imm; 5430 5431 // SplatBitSize is set to the smallest size that splats the vector, so a 5432 // zero vector will always have SplatBitSize == 8. However, NEON modified 5433 // immediate instructions others than VMOV do not support the 8-bit encoding 5434 // of a zero vector, and the default encoding of zero is supposed to be the 5435 // 32-bit version. 5436 if (SplatBits == 0) 5437 SplatBitSize = 32; 5438 5439 switch (SplatBitSize) { 5440 case 8: 5441 if (type != VMOVModImm) 5442 return SDValue(); 5443 // Any 1-byte value is OK. Op=0, Cmode=1110. 5444 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5445 OpCmode = 0xe; 5446 Imm = SplatBits; 5447 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5448 break; 5449 5450 case 16: 5451 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5452 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5453 if ((SplatBits & ~0xff) == 0) { 5454 // Value = 0x00nn: Op=x, Cmode=100x. 5455 OpCmode = 0x8; 5456 Imm = SplatBits; 5457 break; 5458 } 5459 if ((SplatBits & ~0xff00) == 0) { 5460 // Value = 0xnn00: Op=x, Cmode=101x. 5461 OpCmode = 0xa; 5462 Imm = SplatBits >> 8; 5463 break; 5464 } 5465 return SDValue(); 5466 5467 case 32: 5468 // NEON's 32-bit VMOV supports splat values where: 5469 // * only one byte is nonzero, or 5470 // * the least significant byte is 0xff and the second byte is nonzero, or 5471 // * the least significant 2 bytes are 0xff and the third is nonzero. 5472 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5473 if ((SplatBits & ~0xff) == 0) { 5474 // Value = 0x000000nn: Op=x, Cmode=000x. 5475 OpCmode = 0; 5476 Imm = SplatBits; 5477 break; 5478 } 5479 if ((SplatBits & ~0xff00) == 0) { 5480 // Value = 0x0000nn00: Op=x, Cmode=001x. 5481 OpCmode = 0x2; 5482 Imm = SplatBits >> 8; 5483 break; 5484 } 5485 if ((SplatBits & ~0xff0000) == 0) { 5486 // Value = 0x00nn0000: Op=x, Cmode=010x. 5487 OpCmode = 0x4; 5488 Imm = SplatBits >> 16; 5489 break; 5490 } 5491 if ((SplatBits & ~0xff000000) == 0) { 5492 // Value = 0xnn000000: Op=x, Cmode=011x. 5493 OpCmode = 0x6; 5494 Imm = SplatBits >> 24; 5495 break; 5496 } 5497 5498 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5499 if (type == OtherModImm) return SDValue(); 5500 5501 if ((SplatBits & ~0xffff) == 0 && 5502 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5503 // Value = 0x0000nnff: Op=x, Cmode=1100. 5504 OpCmode = 0xc; 5505 Imm = SplatBits >> 8; 5506 break; 5507 } 5508 5509 if ((SplatBits & ~0xffffff) == 0 && 5510 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5511 // Value = 0x00nnffff: Op=x, Cmode=1101. 5512 OpCmode = 0xd; 5513 Imm = SplatBits >> 16; 5514 break; 5515 } 5516 5517 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5518 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5519 // VMOV.I32. A (very) minor optimization would be to replicate the value 5520 // and fall through here to test for a valid 64-bit splat. But, then the 5521 // caller would also need to check and handle the change in size. 5522 return SDValue(); 5523 5524 case 64: { 5525 if (type != VMOVModImm) 5526 return SDValue(); 5527 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5528 uint64_t BitMask = 0xff; 5529 uint64_t Val = 0; 5530 unsigned ImmMask = 1; 5531 Imm = 0; 5532 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5533 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5534 Val |= BitMask; 5535 Imm |= ImmMask; 5536 } else if ((SplatBits & BitMask) != 0) { 5537 return SDValue(); 5538 } 5539 BitMask <<= 8; 5540 ImmMask <<= 1; 5541 } 5542 5543 if (DAG.getDataLayout().isBigEndian()) 5544 // swap higher and lower 32 bit word 5545 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5546 5547 // Op=1, Cmode=1110. 5548 OpCmode = 0x1e; 5549 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5550 break; 5551 } 5552 5553 default: 5554 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5555 } 5556 5557 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5558 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5559 } 5560 5561 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5562 const ARMSubtarget *ST) const { 5563 bool IsDouble = Op.getValueType() == MVT::f64; 5564 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5565 const APFloat &FPVal = CFP->getValueAPF(); 5566 5567 // Prevent floating-point constants from using literal loads 5568 // when execute-only is enabled. 5569 if (ST->genExecuteOnly()) { 5570 APInt INTVal = FPVal.bitcastToAPInt(); 5571 SDLoc DL(CFP); 5572 if (IsDouble) { 5573 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5574 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5575 if (!ST->isLittle()) 5576 std::swap(Lo, Hi); 5577 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5578 } else { 5579 return DAG.getConstant(INTVal, DL, MVT::i32); 5580 } 5581 } 5582 5583 if (!ST->hasVFP3()) 5584 return SDValue(); 5585 5586 // Use the default (constant pool) lowering for double constants when we have 5587 // an SP-only FPU 5588 if (IsDouble && Subtarget->isFPOnlySP()) 5589 return SDValue(); 5590 5591 // Try splatting with a VMOV.f32... 5592 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5593 5594 if (ImmVal != -1) { 5595 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5596 // We have code in place to select a valid ConstantFP already, no need to 5597 // do any mangling. 5598 return Op; 5599 } 5600 5601 // It's a float and we are trying to use NEON operations where 5602 // possible. Lower it to a splat followed by an extract. 5603 SDLoc DL(Op); 5604 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5605 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5606 NewVal); 5607 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5608 DAG.getConstant(0, DL, MVT::i32)); 5609 } 5610 5611 // The rest of our options are NEON only, make sure that's allowed before 5612 // proceeding.. 5613 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5614 return SDValue(); 5615 5616 EVT VMovVT; 5617 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5618 5619 // It wouldn't really be worth bothering for doubles except for one very 5620 // important value, which does happen to match: 0.0. So make sure we don't do 5621 // anything stupid. 5622 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5623 return SDValue(); 5624 5625 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5626 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5627 VMovVT, false, VMOVModImm); 5628 if (NewVal != SDValue()) { 5629 SDLoc DL(Op); 5630 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5631 NewVal); 5632 if (IsDouble) 5633 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5634 5635 // It's a float: cast and extract a vector element. 5636 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5637 VecConstant); 5638 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5639 DAG.getConstant(0, DL, MVT::i32)); 5640 } 5641 5642 // Finally, try a VMVN.i32 5643 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5644 false, VMVNModImm); 5645 if (NewVal != SDValue()) { 5646 SDLoc DL(Op); 5647 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5648 5649 if (IsDouble) 5650 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5651 5652 // It's a float: cast and extract a vector element. 5653 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5654 VecConstant); 5655 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5656 DAG.getConstant(0, DL, MVT::i32)); 5657 } 5658 5659 return SDValue(); 5660 } 5661 5662 // check if an VEXT instruction can handle the shuffle mask when the 5663 // vector sources of the shuffle are the same. 5664 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5665 unsigned NumElts = VT.getVectorNumElements(); 5666 5667 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5668 if (M[0] < 0) 5669 return false; 5670 5671 Imm = M[0]; 5672 5673 // If this is a VEXT shuffle, the immediate value is the index of the first 5674 // element. The other shuffle indices must be the successive elements after 5675 // the first one. 5676 unsigned ExpectedElt = Imm; 5677 for (unsigned i = 1; i < NumElts; ++i) { 5678 // Increment the expected index. If it wraps around, just follow it 5679 // back to index zero and keep going. 5680 ++ExpectedElt; 5681 if (ExpectedElt == NumElts) 5682 ExpectedElt = 0; 5683 5684 if (M[i] < 0) continue; // ignore UNDEF indices 5685 if (ExpectedElt != static_cast<unsigned>(M[i])) 5686 return false; 5687 } 5688 5689 return true; 5690 } 5691 5692 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5693 bool &ReverseVEXT, unsigned &Imm) { 5694 unsigned NumElts = VT.getVectorNumElements(); 5695 ReverseVEXT = false; 5696 5697 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5698 if (M[0] < 0) 5699 return false; 5700 5701 Imm = M[0]; 5702 5703 // If this is a VEXT shuffle, the immediate value is the index of the first 5704 // element. The other shuffle indices must be the successive elements after 5705 // the first one. 5706 unsigned ExpectedElt = Imm; 5707 for (unsigned i = 1; i < NumElts; ++i) { 5708 // Increment the expected index. If it wraps around, it may still be 5709 // a VEXT but the source vectors must be swapped. 5710 ExpectedElt += 1; 5711 if (ExpectedElt == NumElts * 2) { 5712 ExpectedElt = 0; 5713 ReverseVEXT = true; 5714 } 5715 5716 if (M[i] < 0) continue; // ignore UNDEF indices 5717 if (ExpectedElt != static_cast<unsigned>(M[i])) 5718 return false; 5719 } 5720 5721 // Adjust the index value if the source operands will be swapped. 5722 if (ReverseVEXT) 5723 Imm -= NumElts; 5724 5725 return true; 5726 } 5727 5728 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5729 /// instruction with the specified blocksize. (The order of the elements 5730 /// within each block of the vector is reversed.) 5731 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5732 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5733 "Only possible block sizes for VREV are: 16, 32, 64"); 5734 5735 unsigned EltSz = VT.getScalarSizeInBits(); 5736 if (EltSz == 64) 5737 return false; 5738 5739 unsigned NumElts = VT.getVectorNumElements(); 5740 unsigned BlockElts = M[0] + 1; 5741 // If the first shuffle index is UNDEF, be optimistic. 5742 if (M[0] < 0) 5743 BlockElts = BlockSize / EltSz; 5744 5745 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5746 return false; 5747 5748 for (unsigned i = 0; i < NumElts; ++i) { 5749 if (M[i] < 0) continue; // ignore UNDEF indices 5750 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5751 return false; 5752 } 5753 5754 return true; 5755 } 5756 5757 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5758 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5759 // range, then 0 is placed into the resulting vector. So pretty much any mask 5760 // of 8 elements can work here. 5761 return VT == MVT::v8i8 && M.size() == 8; 5762 } 5763 5764 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5765 // checking that pairs of elements in the shuffle mask represent the same index 5766 // in each vector, incrementing the expected index by 2 at each step. 5767 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5768 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5769 // v2={e,f,g,h} 5770 // WhichResult gives the offset for each element in the mask based on which 5771 // of the two results it belongs to. 5772 // 5773 // The transpose can be represented either as: 5774 // result1 = shufflevector v1, v2, result1_shuffle_mask 5775 // result2 = shufflevector v1, v2, result2_shuffle_mask 5776 // where v1/v2 and the shuffle masks have the same number of elements 5777 // (here WhichResult (see below) indicates which result is being checked) 5778 // 5779 // or as: 5780 // results = shufflevector v1, v2, shuffle_mask 5781 // where both results are returned in one vector and the shuffle mask has twice 5782 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5783 // want to check the low half and high half of the shuffle mask as if it were 5784 // the other case 5785 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5786 unsigned EltSz = VT.getScalarSizeInBits(); 5787 if (EltSz == 64) 5788 return false; 5789 5790 unsigned NumElts = VT.getVectorNumElements(); 5791 if (M.size() != NumElts && M.size() != NumElts*2) 5792 return false; 5793 5794 // If the mask is twice as long as the input vector then we need to check the 5795 // upper and lower parts of the mask with a matching value for WhichResult 5796 // FIXME: A mask with only even values will be rejected in case the first 5797 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5798 // M[0] is used to determine WhichResult 5799 for (unsigned i = 0; i < M.size(); i += NumElts) { 5800 if (M.size() == NumElts * 2) 5801 WhichResult = i / NumElts; 5802 else 5803 WhichResult = M[i] == 0 ? 0 : 1; 5804 for (unsigned j = 0; j < NumElts; j += 2) { 5805 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5806 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5807 return false; 5808 } 5809 } 5810 5811 if (M.size() == NumElts*2) 5812 WhichResult = 0; 5813 5814 return true; 5815 } 5816 5817 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5818 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5819 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5820 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5821 unsigned EltSz = VT.getScalarSizeInBits(); 5822 if (EltSz == 64) 5823 return false; 5824 5825 unsigned NumElts = VT.getVectorNumElements(); 5826 if (M.size() != NumElts && M.size() != NumElts*2) 5827 return false; 5828 5829 for (unsigned i = 0; i < M.size(); i += NumElts) { 5830 if (M.size() == NumElts * 2) 5831 WhichResult = i / NumElts; 5832 else 5833 WhichResult = M[i] == 0 ? 0 : 1; 5834 for (unsigned j = 0; j < NumElts; j += 2) { 5835 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5836 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5837 return false; 5838 } 5839 } 5840 5841 if (M.size() == NumElts*2) 5842 WhichResult = 0; 5843 5844 return true; 5845 } 5846 5847 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5848 // that the mask elements are either all even and in steps of size 2 or all odd 5849 // and in steps of size 2. 5850 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5851 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5852 // v2={e,f,g,h} 5853 // Requires similar checks to that of isVTRNMask with 5854 // respect the how results are returned. 5855 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5856 unsigned EltSz = VT.getScalarSizeInBits(); 5857 if (EltSz == 64) 5858 return false; 5859 5860 unsigned NumElts = VT.getVectorNumElements(); 5861 if (M.size() != NumElts && M.size() != NumElts*2) 5862 return false; 5863 5864 for (unsigned i = 0; i < M.size(); i += NumElts) { 5865 WhichResult = M[i] == 0 ? 0 : 1; 5866 for (unsigned j = 0; j < NumElts; ++j) { 5867 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5868 return false; 5869 } 5870 } 5871 5872 if (M.size() == NumElts*2) 5873 WhichResult = 0; 5874 5875 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5876 if (VT.is64BitVector() && EltSz == 32) 5877 return false; 5878 5879 return true; 5880 } 5881 5882 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5883 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5884 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5885 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5886 unsigned EltSz = VT.getScalarSizeInBits(); 5887 if (EltSz == 64) 5888 return false; 5889 5890 unsigned NumElts = VT.getVectorNumElements(); 5891 if (M.size() != NumElts && M.size() != NumElts*2) 5892 return false; 5893 5894 unsigned Half = NumElts / 2; 5895 for (unsigned i = 0; i < M.size(); i += NumElts) { 5896 WhichResult = M[i] == 0 ? 0 : 1; 5897 for (unsigned j = 0; j < NumElts; j += Half) { 5898 unsigned Idx = WhichResult; 5899 for (unsigned k = 0; k < Half; ++k) { 5900 int MIdx = M[i + j + k]; 5901 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5902 return false; 5903 Idx += 2; 5904 } 5905 } 5906 } 5907 5908 if (M.size() == NumElts*2) 5909 WhichResult = 0; 5910 5911 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5912 if (VT.is64BitVector() && EltSz == 32) 5913 return false; 5914 5915 return true; 5916 } 5917 5918 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5919 // that pairs of elements of the shufflemask represent the same index in each 5920 // vector incrementing sequentially through the vectors. 5921 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5922 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5923 // v2={e,f,g,h} 5924 // Requires similar checks to that of isVTRNMask with respect the how results 5925 // are returned. 5926 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5927 unsigned EltSz = VT.getScalarSizeInBits(); 5928 if (EltSz == 64) 5929 return false; 5930 5931 unsigned NumElts = VT.getVectorNumElements(); 5932 if (M.size() != NumElts && M.size() != NumElts*2) 5933 return false; 5934 5935 for (unsigned i = 0; i < M.size(); i += NumElts) { 5936 WhichResult = M[i] == 0 ? 0 : 1; 5937 unsigned Idx = WhichResult * NumElts / 2; 5938 for (unsigned j = 0; j < NumElts; j += 2) { 5939 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5940 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5941 return false; 5942 Idx += 1; 5943 } 5944 } 5945 5946 if (M.size() == NumElts*2) 5947 WhichResult = 0; 5948 5949 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5950 if (VT.is64BitVector() && EltSz == 32) 5951 return false; 5952 5953 return true; 5954 } 5955 5956 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5957 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5958 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5959 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5960 unsigned EltSz = VT.getScalarSizeInBits(); 5961 if (EltSz == 64) 5962 return false; 5963 5964 unsigned NumElts = VT.getVectorNumElements(); 5965 if (M.size() != NumElts && M.size() != NumElts*2) 5966 return false; 5967 5968 for (unsigned i = 0; i < M.size(); i += NumElts) { 5969 WhichResult = M[i] == 0 ? 0 : 1; 5970 unsigned Idx = WhichResult * NumElts / 2; 5971 for (unsigned j = 0; j < NumElts; j += 2) { 5972 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5973 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5974 return false; 5975 Idx += 1; 5976 } 5977 } 5978 5979 if (M.size() == NumElts*2) 5980 WhichResult = 0; 5981 5982 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5983 if (VT.is64BitVector() && EltSz == 32) 5984 return false; 5985 5986 return true; 5987 } 5988 5989 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5990 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5991 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5992 unsigned &WhichResult, 5993 bool &isV_UNDEF) { 5994 isV_UNDEF = false; 5995 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5996 return ARMISD::VTRN; 5997 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5998 return ARMISD::VUZP; 5999 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6000 return ARMISD::VZIP; 6001 6002 isV_UNDEF = true; 6003 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6004 return ARMISD::VTRN; 6005 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6006 return ARMISD::VUZP; 6007 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6008 return ARMISD::VZIP; 6009 6010 return 0; 6011 } 6012 6013 /// \return true if this is a reverse operation on an vector. 6014 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6015 unsigned NumElts = VT.getVectorNumElements(); 6016 // Make sure the mask has the right size. 6017 if (NumElts != M.size()) 6018 return false; 6019 6020 // Look for <15, ..., 3, -1, 1, 0>. 6021 for (unsigned i = 0; i != NumElts; ++i) 6022 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6023 return false; 6024 6025 return true; 6026 } 6027 6028 // If N is an integer constant that can be moved into a register in one 6029 // instruction, return an SDValue of such a constant (will become a MOV 6030 // instruction). Otherwise return null. 6031 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6032 const ARMSubtarget *ST, const SDLoc &dl) { 6033 uint64_t Val; 6034 if (!isa<ConstantSDNode>(N)) 6035 return SDValue(); 6036 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6037 6038 if (ST->isThumb1Only()) { 6039 if (Val <= 255 || ~Val <= 255) 6040 return DAG.getConstant(Val, dl, MVT::i32); 6041 } else { 6042 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6043 return DAG.getConstant(Val, dl, MVT::i32); 6044 } 6045 return SDValue(); 6046 } 6047 6048 // If this is a case we can't handle, return null and let the default 6049 // expansion code take care of it. 6050 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6051 const ARMSubtarget *ST) const { 6052 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6053 SDLoc dl(Op); 6054 EVT VT = Op.getValueType(); 6055 6056 APInt SplatBits, SplatUndef; 6057 unsigned SplatBitSize; 6058 bool HasAnyUndefs; 6059 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6060 if (SplatUndef.isAllOnesValue()) 6061 return DAG.getUNDEF(VT); 6062 6063 if (SplatBitSize <= 64) { 6064 // Check if an immediate VMOV works. 6065 EVT VmovVT; 6066 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6067 SplatUndef.getZExtValue(), SplatBitSize, 6068 DAG, dl, VmovVT, VT.is128BitVector(), 6069 VMOVModImm); 6070 if (Val.getNode()) { 6071 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6072 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6073 } 6074 6075 // Try an immediate VMVN. 6076 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6077 Val = isNEONModifiedImm(NegatedImm, 6078 SplatUndef.getZExtValue(), SplatBitSize, 6079 DAG, dl, VmovVT, VT.is128BitVector(), 6080 VMVNModImm); 6081 if (Val.getNode()) { 6082 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6083 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6084 } 6085 6086 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6087 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6088 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6089 if (ImmVal != -1) { 6090 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6091 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6092 } 6093 } 6094 } 6095 } 6096 6097 // Scan through the operands to see if only one value is used. 6098 // 6099 // As an optimisation, even if more than one value is used it may be more 6100 // profitable to splat with one value then change some lanes. 6101 // 6102 // Heuristically we decide to do this if the vector has a "dominant" value, 6103 // defined as splatted to more than half of the lanes. 6104 unsigned NumElts = VT.getVectorNumElements(); 6105 bool isOnlyLowElement = true; 6106 bool usesOnlyOneValue = true; 6107 bool hasDominantValue = false; 6108 bool isConstant = true; 6109 6110 // Map of the number of times a particular SDValue appears in the 6111 // element list. 6112 DenseMap<SDValue, unsigned> ValueCounts; 6113 SDValue Value; 6114 for (unsigned i = 0; i < NumElts; ++i) { 6115 SDValue V = Op.getOperand(i); 6116 if (V.isUndef()) 6117 continue; 6118 if (i > 0) 6119 isOnlyLowElement = false; 6120 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6121 isConstant = false; 6122 6123 ValueCounts.insert(std::make_pair(V, 0)); 6124 unsigned &Count = ValueCounts[V]; 6125 6126 // Is this value dominant? (takes up more than half of the lanes) 6127 if (++Count > (NumElts / 2)) { 6128 hasDominantValue = true; 6129 Value = V; 6130 } 6131 } 6132 if (ValueCounts.size() != 1) 6133 usesOnlyOneValue = false; 6134 if (!Value.getNode() && !ValueCounts.empty()) 6135 Value = ValueCounts.begin()->first; 6136 6137 if (ValueCounts.empty()) 6138 return DAG.getUNDEF(VT); 6139 6140 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6141 // Keep going if we are hitting this case. 6142 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6143 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6144 6145 unsigned EltSize = VT.getScalarSizeInBits(); 6146 6147 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6148 // i32 and try again. 6149 if (hasDominantValue && EltSize <= 32) { 6150 if (!isConstant) { 6151 SDValue N; 6152 6153 // If we are VDUPing a value that comes directly from a vector, that will 6154 // cause an unnecessary move to and from a GPR, where instead we could 6155 // just use VDUPLANE. We can only do this if the lane being extracted 6156 // is at a constant index, as the VDUP from lane instructions only have 6157 // constant-index forms. 6158 ConstantSDNode *constIndex; 6159 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6160 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6161 // We need to create a new undef vector to use for the VDUPLANE if the 6162 // size of the vector from which we get the value is different than the 6163 // size of the vector that we need to create. We will insert the element 6164 // such that the register coalescer will remove unnecessary copies. 6165 if (VT != Value->getOperand(0).getValueType()) { 6166 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6167 VT.getVectorNumElements(); 6168 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6169 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6170 Value, DAG.getConstant(index, dl, MVT::i32)), 6171 DAG.getConstant(index, dl, MVT::i32)); 6172 } else 6173 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6174 Value->getOperand(0), Value->getOperand(1)); 6175 } else 6176 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6177 6178 if (!usesOnlyOneValue) { 6179 // The dominant value was splatted as 'N', but we now have to insert 6180 // all differing elements. 6181 for (unsigned I = 0; I < NumElts; ++I) { 6182 if (Op.getOperand(I) == Value) 6183 continue; 6184 SmallVector<SDValue, 3> Ops; 6185 Ops.push_back(N); 6186 Ops.push_back(Op.getOperand(I)); 6187 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6188 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6189 } 6190 } 6191 return N; 6192 } 6193 if (VT.getVectorElementType().isFloatingPoint()) { 6194 SmallVector<SDValue, 8> Ops; 6195 for (unsigned i = 0; i < NumElts; ++i) 6196 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6197 Op.getOperand(i))); 6198 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6199 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6200 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6201 if (Val.getNode()) 6202 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6203 } 6204 if (usesOnlyOneValue) { 6205 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6206 if (isConstant && Val.getNode()) 6207 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6208 } 6209 } 6210 6211 // If all elements are constants and the case above didn't get hit, fall back 6212 // to the default expansion, which will generate a load from the constant 6213 // pool. 6214 if (isConstant) 6215 return SDValue(); 6216 6217 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6218 if (NumElts >= 4) { 6219 SDValue shuffle = ReconstructShuffle(Op, DAG); 6220 if (shuffle != SDValue()) 6221 return shuffle; 6222 } 6223 6224 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6225 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6226 // into two 64-bit vectors; we might discover a better way to lower it. 6227 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6228 EVT ExtVT = VT.getVectorElementType(); 6229 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6230 SDValue Lower = 6231 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6232 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6233 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6234 SDValue Upper = DAG.getBuildVector( 6235 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6236 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6237 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6238 if (Lower && Upper) 6239 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6240 } 6241 6242 // Vectors with 32- or 64-bit elements can be built by directly assigning 6243 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6244 // will be legalized. 6245 if (EltSize >= 32) { 6246 // Do the expansion with floating-point types, since that is what the VFP 6247 // registers are defined to use, and since i64 is not legal. 6248 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6249 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6250 SmallVector<SDValue, 8> Ops; 6251 for (unsigned i = 0; i < NumElts; ++i) 6252 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6253 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6254 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6255 } 6256 6257 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6258 // know the default expansion would otherwise fall back on something even 6259 // worse. For a vector with one or two non-undef values, that's 6260 // scalar_to_vector for the elements followed by a shuffle (provided the 6261 // shuffle is valid for the target) and materialization element by element 6262 // on the stack followed by a load for everything else. 6263 if (!isConstant && !usesOnlyOneValue) { 6264 SDValue Vec = DAG.getUNDEF(VT); 6265 for (unsigned i = 0 ; i < NumElts; ++i) { 6266 SDValue V = Op.getOperand(i); 6267 if (V.isUndef()) 6268 continue; 6269 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6270 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6271 } 6272 return Vec; 6273 } 6274 6275 return SDValue(); 6276 } 6277 6278 // Gather data to see if the operation can be modelled as a 6279 // shuffle in combination with VEXTs. 6280 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6281 SelectionDAG &DAG) const { 6282 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6283 SDLoc dl(Op); 6284 EVT VT = Op.getValueType(); 6285 unsigned NumElts = VT.getVectorNumElements(); 6286 6287 struct ShuffleSourceInfo { 6288 SDValue Vec; 6289 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6290 unsigned MaxElt = 0; 6291 6292 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6293 // be compatible with the shuffle we intend to construct. As a result 6294 // ShuffleVec will be some sliding window into the original Vec. 6295 SDValue ShuffleVec; 6296 6297 // Code should guarantee that element i in Vec starts at element "WindowBase 6298 // + i * WindowScale in ShuffleVec". 6299 int WindowBase = 0; 6300 int WindowScale = 1; 6301 6302 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6303 6304 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6305 }; 6306 6307 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6308 // node. 6309 SmallVector<ShuffleSourceInfo, 2> Sources; 6310 for (unsigned i = 0; i < NumElts; ++i) { 6311 SDValue V = Op.getOperand(i); 6312 if (V.isUndef()) 6313 continue; 6314 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6315 // A shuffle can only come from building a vector from various 6316 // elements of other vectors. 6317 return SDValue(); 6318 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6319 // Furthermore, shuffles require a constant mask, whereas extractelts 6320 // accept variable indices. 6321 return SDValue(); 6322 } 6323 6324 // Add this element source to the list if it's not already there. 6325 SDValue SourceVec = V.getOperand(0); 6326 auto Source = llvm::find(Sources, SourceVec); 6327 if (Source == Sources.end()) 6328 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6329 6330 // Update the minimum and maximum lane number seen. 6331 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6332 Source->MinElt = std::min(Source->MinElt, EltNo); 6333 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6334 } 6335 6336 // Currently only do something sane when at most two source vectors 6337 // are involved. 6338 if (Sources.size() > 2) 6339 return SDValue(); 6340 6341 // Find out the smallest element size among result and two sources, and use 6342 // it as element size to build the shuffle_vector. 6343 EVT SmallestEltTy = VT.getVectorElementType(); 6344 for (auto &Source : Sources) { 6345 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6346 if (SrcEltTy.bitsLT(SmallestEltTy)) 6347 SmallestEltTy = SrcEltTy; 6348 } 6349 unsigned ResMultiplier = 6350 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6351 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6352 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6353 6354 // If the source vector is too wide or too narrow, we may nevertheless be able 6355 // to construct a compatible shuffle either by concatenating it with UNDEF or 6356 // extracting a suitable range of elements. 6357 for (auto &Src : Sources) { 6358 EVT SrcVT = Src.ShuffleVec.getValueType(); 6359 6360 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6361 continue; 6362 6363 // This stage of the search produces a source with the same element type as 6364 // the original, but with a total width matching the BUILD_VECTOR output. 6365 EVT EltVT = SrcVT.getVectorElementType(); 6366 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6367 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6368 6369 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6370 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6371 return SDValue(); 6372 // We can pad out the smaller vector for free, so if it's part of a 6373 // shuffle... 6374 Src.ShuffleVec = 6375 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6376 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6377 continue; 6378 } 6379 6380 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6381 return SDValue(); 6382 6383 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6384 // Span too large for a VEXT to cope 6385 return SDValue(); 6386 } 6387 6388 if (Src.MinElt >= NumSrcElts) { 6389 // The extraction can just take the second half 6390 Src.ShuffleVec = 6391 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6392 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6393 Src.WindowBase = -NumSrcElts; 6394 } else if (Src.MaxElt < NumSrcElts) { 6395 // The extraction can just take the first half 6396 Src.ShuffleVec = 6397 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6398 DAG.getConstant(0, dl, MVT::i32)); 6399 } else { 6400 // An actual VEXT is needed 6401 SDValue VEXTSrc1 = 6402 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6403 DAG.getConstant(0, dl, MVT::i32)); 6404 SDValue VEXTSrc2 = 6405 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6406 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6407 6408 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6409 VEXTSrc2, 6410 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6411 Src.WindowBase = -Src.MinElt; 6412 } 6413 } 6414 6415 // Another possible incompatibility occurs from the vector element types. We 6416 // can fix this by bitcasting the source vectors to the same type we intend 6417 // for the shuffle. 6418 for (auto &Src : Sources) { 6419 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6420 if (SrcEltTy == SmallestEltTy) 6421 continue; 6422 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6423 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6424 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6425 Src.WindowBase *= Src.WindowScale; 6426 } 6427 6428 // Final sanity check before we try to actually produce a shuffle. 6429 DEBUG( 6430 for (auto Src : Sources) 6431 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6432 ); 6433 6434 // The stars all align, our next step is to produce the mask for the shuffle. 6435 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6436 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6437 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6438 SDValue Entry = Op.getOperand(i); 6439 if (Entry.isUndef()) 6440 continue; 6441 6442 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6443 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6444 6445 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6446 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6447 // segment. 6448 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6449 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6450 VT.getScalarSizeInBits()); 6451 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6452 6453 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6454 // starting at the appropriate offset. 6455 int *LaneMask = &Mask[i * ResMultiplier]; 6456 6457 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6458 ExtractBase += NumElts * (Src - Sources.begin()); 6459 for (int j = 0; j < LanesDefined; ++j) 6460 LaneMask[j] = ExtractBase + j; 6461 } 6462 6463 // Final check before we try to produce nonsense... 6464 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6465 return SDValue(); 6466 6467 // We can't handle more than two sources. This should have already 6468 // been checked before this point. 6469 assert(Sources.size() <= 2 && "Too many sources!"); 6470 6471 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6472 for (unsigned i = 0; i < Sources.size(); ++i) 6473 ShuffleOps[i] = Sources[i].ShuffleVec; 6474 6475 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6476 ShuffleOps[1], Mask); 6477 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6478 } 6479 6480 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6481 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6482 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6483 /// are assumed to be legal. 6484 bool 6485 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6486 EVT VT) const { 6487 if (VT.getVectorNumElements() == 4 && 6488 (VT.is128BitVector() || VT.is64BitVector())) { 6489 unsigned PFIndexes[4]; 6490 for (unsigned i = 0; i != 4; ++i) { 6491 if (M[i] < 0) 6492 PFIndexes[i] = 8; 6493 else 6494 PFIndexes[i] = M[i]; 6495 } 6496 6497 // Compute the index in the perfect shuffle table. 6498 unsigned PFTableIndex = 6499 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6500 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6501 unsigned Cost = (PFEntry >> 30); 6502 6503 if (Cost <= 4) 6504 return true; 6505 } 6506 6507 bool ReverseVEXT, isV_UNDEF; 6508 unsigned Imm, WhichResult; 6509 6510 unsigned EltSize = VT.getScalarSizeInBits(); 6511 return (EltSize >= 32 || 6512 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6513 isVREVMask(M, VT, 64) || 6514 isVREVMask(M, VT, 32) || 6515 isVREVMask(M, VT, 16) || 6516 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6517 isVTBLMask(M, VT) || 6518 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6519 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6520 } 6521 6522 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6523 /// the specified operations to build the shuffle. 6524 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6525 SDValue RHS, SelectionDAG &DAG, 6526 const SDLoc &dl) { 6527 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6528 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6529 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6530 6531 enum { 6532 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6533 OP_VREV, 6534 OP_VDUP0, 6535 OP_VDUP1, 6536 OP_VDUP2, 6537 OP_VDUP3, 6538 OP_VEXT1, 6539 OP_VEXT2, 6540 OP_VEXT3, 6541 OP_VUZPL, // VUZP, left result 6542 OP_VUZPR, // VUZP, right result 6543 OP_VZIPL, // VZIP, left result 6544 OP_VZIPR, // VZIP, right result 6545 OP_VTRNL, // VTRN, left result 6546 OP_VTRNR // VTRN, right result 6547 }; 6548 6549 if (OpNum == OP_COPY) { 6550 if (LHSID == (1*9+2)*9+3) return LHS; 6551 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6552 return RHS; 6553 } 6554 6555 SDValue OpLHS, OpRHS; 6556 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6557 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6558 EVT VT = OpLHS.getValueType(); 6559 6560 switch (OpNum) { 6561 default: llvm_unreachable("Unknown shuffle opcode!"); 6562 case OP_VREV: 6563 // VREV divides the vector in half and swaps within the half. 6564 if (VT.getVectorElementType() == MVT::i32 || 6565 VT.getVectorElementType() == MVT::f32) 6566 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6567 // vrev <4 x i16> -> VREV32 6568 if (VT.getVectorElementType() == MVT::i16) 6569 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6570 // vrev <4 x i8> -> VREV16 6571 assert(VT.getVectorElementType() == MVT::i8); 6572 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6573 case OP_VDUP0: 6574 case OP_VDUP1: 6575 case OP_VDUP2: 6576 case OP_VDUP3: 6577 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6578 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6579 case OP_VEXT1: 6580 case OP_VEXT2: 6581 case OP_VEXT3: 6582 return DAG.getNode(ARMISD::VEXT, dl, VT, 6583 OpLHS, OpRHS, 6584 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6585 case OP_VUZPL: 6586 case OP_VUZPR: 6587 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6588 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6589 case OP_VZIPL: 6590 case OP_VZIPR: 6591 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6592 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6593 case OP_VTRNL: 6594 case OP_VTRNR: 6595 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6596 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6597 } 6598 } 6599 6600 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6601 ArrayRef<int> ShuffleMask, 6602 SelectionDAG &DAG) { 6603 // Check to see if we can use the VTBL instruction. 6604 SDValue V1 = Op.getOperand(0); 6605 SDValue V2 = Op.getOperand(1); 6606 SDLoc DL(Op); 6607 6608 SmallVector<SDValue, 8> VTBLMask; 6609 for (ArrayRef<int>::iterator 6610 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6611 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6612 6613 if (V2.getNode()->isUndef()) 6614 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6615 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6616 6617 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6618 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6619 } 6620 6621 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6622 SelectionDAG &DAG) { 6623 SDLoc DL(Op); 6624 SDValue OpLHS = Op.getOperand(0); 6625 EVT VT = OpLHS.getValueType(); 6626 6627 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6628 "Expect an v8i16/v16i8 type"); 6629 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6630 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6631 // extract the first 8 bytes into the top double word and the last 8 bytes 6632 // into the bottom double word. The v8i16 case is similar. 6633 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6634 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6635 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6636 } 6637 6638 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6639 SDValue V1 = Op.getOperand(0); 6640 SDValue V2 = Op.getOperand(1); 6641 SDLoc dl(Op); 6642 EVT VT = Op.getValueType(); 6643 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6644 6645 // Convert shuffles that are directly supported on NEON to target-specific 6646 // DAG nodes, instead of keeping them as shuffles and matching them again 6647 // during code selection. This is more efficient and avoids the possibility 6648 // of inconsistencies between legalization and selection. 6649 // FIXME: floating-point vectors should be canonicalized to integer vectors 6650 // of the same time so that they get CSEd properly. 6651 ArrayRef<int> ShuffleMask = SVN->getMask(); 6652 6653 unsigned EltSize = VT.getScalarSizeInBits(); 6654 if (EltSize <= 32) { 6655 if (SVN->isSplat()) { 6656 int Lane = SVN->getSplatIndex(); 6657 // If this is undef splat, generate it via "just" vdup, if possible. 6658 if (Lane == -1) Lane = 0; 6659 6660 // Test if V1 is a SCALAR_TO_VECTOR. 6661 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6662 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6663 } 6664 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6665 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6666 // reaches it). 6667 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6668 !isa<ConstantSDNode>(V1.getOperand(0))) { 6669 bool IsScalarToVector = true; 6670 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6671 if (!V1.getOperand(i).isUndef()) { 6672 IsScalarToVector = false; 6673 break; 6674 } 6675 if (IsScalarToVector) 6676 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6677 } 6678 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6679 DAG.getConstant(Lane, dl, MVT::i32)); 6680 } 6681 6682 bool ReverseVEXT; 6683 unsigned Imm; 6684 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6685 if (ReverseVEXT) 6686 std::swap(V1, V2); 6687 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6688 DAG.getConstant(Imm, dl, MVT::i32)); 6689 } 6690 6691 if (isVREVMask(ShuffleMask, VT, 64)) 6692 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6693 if (isVREVMask(ShuffleMask, VT, 32)) 6694 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6695 if (isVREVMask(ShuffleMask, VT, 16)) 6696 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6697 6698 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6699 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6700 DAG.getConstant(Imm, dl, MVT::i32)); 6701 } 6702 6703 // Check for Neon shuffles that modify both input vectors in place. 6704 // If both results are used, i.e., if there are two shuffles with the same 6705 // source operands and with masks corresponding to both results of one of 6706 // these operations, DAG memoization will ensure that a single node is 6707 // used for both shuffles. 6708 unsigned WhichResult; 6709 bool isV_UNDEF; 6710 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6711 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6712 if (isV_UNDEF) 6713 V2 = V1; 6714 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6715 .getValue(WhichResult); 6716 } 6717 6718 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6719 // shuffles that produce a result larger than their operands with: 6720 // shuffle(concat(v1, undef), concat(v2, undef)) 6721 // -> 6722 // shuffle(concat(v1, v2), undef) 6723 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6724 // 6725 // This is useful in the general case, but there are special cases where 6726 // native shuffles produce larger results: the two-result ops. 6727 // 6728 // Look through the concat when lowering them: 6729 // shuffle(concat(v1, v2), undef) 6730 // -> 6731 // concat(VZIP(v1, v2):0, :1) 6732 // 6733 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6734 SDValue SubV1 = V1->getOperand(0); 6735 SDValue SubV2 = V1->getOperand(1); 6736 EVT SubVT = SubV1.getValueType(); 6737 6738 // We expect these to have been canonicalized to -1. 6739 assert(llvm::all_of(ShuffleMask, [&](int i) { 6740 return i < (int)VT.getVectorNumElements(); 6741 }) && "Unexpected shuffle index into UNDEF operand!"); 6742 6743 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6744 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6745 if (isV_UNDEF) 6746 SubV2 = SubV1; 6747 assert((WhichResult == 0) && 6748 "In-place shuffle of concat can only have one result!"); 6749 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6750 SubV1, SubV2); 6751 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6752 Res.getValue(1)); 6753 } 6754 } 6755 } 6756 6757 // If the shuffle is not directly supported and it has 4 elements, use 6758 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6759 unsigned NumElts = VT.getVectorNumElements(); 6760 if (NumElts == 4) { 6761 unsigned PFIndexes[4]; 6762 for (unsigned i = 0; i != 4; ++i) { 6763 if (ShuffleMask[i] < 0) 6764 PFIndexes[i] = 8; 6765 else 6766 PFIndexes[i] = ShuffleMask[i]; 6767 } 6768 6769 // Compute the index in the perfect shuffle table. 6770 unsigned PFTableIndex = 6771 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6772 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6773 unsigned Cost = (PFEntry >> 30); 6774 6775 if (Cost <= 4) 6776 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6777 } 6778 6779 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6780 if (EltSize >= 32) { 6781 // Do the expansion with floating-point types, since that is what the VFP 6782 // registers are defined to use, and since i64 is not legal. 6783 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6784 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6785 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6786 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6787 SmallVector<SDValue, 8> Ops; 6788 for (unsigned i = 0; i < NumElts; ++i) { 6789 if (ShuffleMask[i] < 0) 6790 Ops.push_back(DAG.getUNDEF(EltVT)); 6791 else 6792 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6793 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6794 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6795 dl, MVT::i32))); 6796 } 6797 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6798 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6799 } 6800 6801 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6802 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6803 6804 if (VT == MVT::v8i8) 6805 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6806 return NewOp; 6807 6808 return SDValue(); 6809 } 6810 6811 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6812 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6813 SDValue Lane = Op.getOperand(2); 6814 if (!isa<ConstantSDNode>(Lane)) 6815 return SDValue(); 6816 6817 return Op; 6818 } 6819 6820 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6821 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6822 SDValue Lane = Op.getOperand(1); 6823 if (!isa<ConstantSDNode>(Lane)) 6824 return SDValue(); 6825 6826 SDValue Vec = Op.getOperand(0); 6827 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 6828 SDLoc dl(Op); 6829 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6830 } 6831 6832 return Op; 6833 } 6834 6835 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6836 // The only time a CONCAT_VECTORS operation can have legal types is when 6837 // two 64-bit vectors are concatenated to a 128-bit vector. 6838 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6839 "unexpected CONCAT_VECTORS"); 6840 SDLoc dl(Op); 6841 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6842 SDValue Op0 = Op.getOperand(0); 6843 SDValue Op1 = Op.getOperand(1); 6844 if (!Op0.isUndef()) 6845 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6846 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6847 DAG.getIntPtrConstant(0, dl)); 6848 if (!Op1.isUndef()) 6849 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6850 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6851 DAG.getIntPtrConstant(1, dl)); 6852 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6853 } 6854 6855 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6856 /// element has been zero/sign-extended, depending on the isSigned parameter, 6857 /// from an integer type half its size. 6858 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6859 bool isSigned) { 6860 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6861 EVT VT = N->getValueType(0); 6862 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6863 SDNode *BVN = N->getOperand(0).getNode(); 6864 if (BVN->getValueType(0) != MVT::v4i32 || 6865 BVN->getOpcode() != ISD::BUILD_VECTOR) 6866 return false; 6867 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6868 unsigned HiElt = 1 - LoElt; 6869 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6870 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6871 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6872 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6873 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6874 return false; 6875 if (isSigned) { 6876 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6877 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6878 return true; 6879 } else { 6880 if (Hi0->isNullValue() && Hi1->isNullValue()) 6881 return true; 6882 } 6883 return false; 6884 } 6885 6886 if (N->getOpcode() != ISD::BUILD_VECTOR) 6887 return false; 6888 6889 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6890 SDNode *Elt = N->getOperand(i).getNode(); 6891 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6892 unsigned EltSize = VT.getScalarSizeInBits(); 6893 unsigned HalfSize = EltSize / 2; 6894 if (isSigned) { 6895 if (!isIntN(HalfSize, C->getSExtValue())) 6896 return false; 6897 } else { 6898 if (!isUIntN(HalfSize, C->getZExtValue())) 6899 return false; 6900 } 6901 continue; 6902 } 6903 return false; 6904 } 6905 6906 return true; 6907 } 6908 6909 /// isSignExtended - Check if a node is a vector value that is sign-extended 6910 /// or a constant BUILD_VECTOR with sign-extended elements. 6911 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6912 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6913 return true; 6914 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6915 return true; 6916 return false; 6917 } 6918 6919 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6920 /// or a constant BUILD_VECTOR with zero-extended elements. 6921 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6922 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6923 return true; 6924 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6925 return true; 6926 return false; 6927 } 6928 6929 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6930 if (OrigVT.getSizeInBits() >= 64) 6931 return OrigVT; 6932 6933 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6934 6935 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6936 switch (OrigSimpleTy) { 6937 default: llvm_unreachable("Unexpected Vector Type"); 6938 case MVT::v2i8: 6939 case MVT::v2i16: 6940 return MVT::v2i32; 6941 case MVT::v4i8: 6942 return MVT::v4i16; 6943 } 6944 } 6945 6946 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6947 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6948 /// We insert the required extension here to get the vector to fill a D register. 6949 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6950 const EVT &OrigTy, 6951 const EVT &ExtTy, 6952 unsigned ExtOpcode) { 6953 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6954 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6955 // 64-bits we need to insert a new extension so that it will be 64-bits. 6956 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6957 if (OrigTy.getSizeInBits() >= 64) 6958 return N; 6959 6960 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6961 EVT NewVT = getExtensionTo64Bits(OrigTy); 6962 6963 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6964 } 6965 6966 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6967 /// does not do any sign/zero extension. If the original vector is less 6968 /// than 64 bits, an appropriate extension will be added after the load to 6969 /// reach a total size of 64 bits. We have to add the extension separately 6970 /// because ARM does not have a sign/zero extending load for vectors. 6971 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6972 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6973 6974 // The load already has the right type. 6975 if (ExtendedTy == LD->getMemoryVT()) 6976 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6977 LD->getBasePtr(), LD->getPointerInfo(), 6978 LD->getAlignment(), LD->getMemOperand()->getFlags()); 6979 6980 // We need to create a zextload/sextload. We cannot just create a load 6981 // followed by a zext/zext node because LowerMUL is also run during normal 6982 // operation legalization where we can't create illegal types. 6983 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6984 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6985 LD->getMemoryVT(), LD->getAlignment(), 6986 LD->getMemOperand()->getFlags()); 6987 } 6988 6989 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6990 /// extending load, or BUILD_VECTOR with extended elements, return the 6991 /// unextended value. The unextended vector should be 64 bits so that it can 6992 /// be used as an operand to a VMULL instruction. If the original vector size 6993 /// before extension is less than 64 bits we add a an extension to resize 6994 /// the vector to 64 bits. 6995 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6996 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6997 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6998 N->getOperand(0)->getValueType(0), 6999 N->getValueType(0), 7000 N->getOpcode()); 7001 7002 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7003 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7004 "Expected extending load"); 7005 7006 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7007 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7008 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7009 SDValue extLoad = 7010 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7011 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7012 7013 return newLoad; 7014 } 7015 7016 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7017 // have been legalized as a BITCAST from v4i32. 7018 if (N->getOpcode() == ISD::BITCAST) { 7019 SDNode *BVN = N->getOperand(0).getNode(); 7020 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7021 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7022 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7023 return DAG.getBuildVector( 7024 MVT::v2i32, SDLoc(N), 7025 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7026 } 7027 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7028 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7029 EVT VT = N->getValueType(0); 7030 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7031 unsigned NumElts = VT.getVectorNumElements(); 7032 MVT TruncVT = MVT::getIntegerVT(EltSize); 7033 SmallVector<SDValue, 8> Ops; 7034 SDLoc dl(N); 7035 for (unsigned i = 0; i != NumElts; ++i) { 7036 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7037 const APInt &CInt = C->getAPIntValue(); 7038 // Element types smaller than 32 bits are not legal, so use i32 elements. 7039 // The values are implicitly truncated so sext vs. zext doesn't matter. 7040 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7041 } 7042 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7043 } 7044 7045 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7046 unsigned Opcode = N->getOpcode(); 7047 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7048 SDNode *N0 = N->getOperand(0).getNode(); 7049 SDNode *N1 = N->getOperand(1).getNode(); 7050 return N0->hasOneUse() && N1->hasOneUse() && 7051 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7052 } 7053 return false; 7054 } 7055 7056 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7057 unsigned Opcode = N->getOpcode(); 7058 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7059 SDNode *N0 = N->getOperand(0).getNode(); 7060 SDNode *N1 = N->getOperand(1).getNode(); 7061 return N0->hasOneUse() && N1->hasOneUse() && 7062 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7063 } 7064 return false; 7065 } 7066 7067 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7068 // Multiplications are only custom-lowered for 128-bit vectors so that 7069 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7070 EVT VT = Op.getValueType(); 7071 assert(VT.is128BitVector() && VT.isInteger() && 7072 "unexpected type for custom-lowering ISD::MUL"); 7073 SDNode *N0 = Op.getOperand(0).getNode(); 7074 SDNode *N1 = Op.getOperand(1).getNode(); 7075 unsigned NewOpc = 0; 7076 bool isMLA = false; 7077 bool isN0SExt = isSignExtended(N0, DAG); 7078 bool isN1SExt = isSignExtended(N1, DAG); 7079 if (isN0SExt && isN1SExt) 7080 NewOpc = ARMISD::VMULLs; 7081 else { 7082 bool isN0ZExt = isZeroExtended(N0, DAG); 7083 bool isN1ZExt = isZeroExtended(N1, DAG); 7084 if (isN0ZExt && isN1ZExt) 7085 NewOpc = ARMISD::VMULLu; 7086 else if (isN1SExt || isN1ZExt) { 7087 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7088 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7089 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7090 NewOpc = ARMISD::VMULLs; 7091 isMLA = true; 7092 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7093 NewOpc = ARMISD::VMULLu; 7094 isMLA = true; 7095 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7096 std::swap(N0, N1); 7097 NewOpc = ARMISD::VMULLu; 7098 isMLA = true; 7099 } 7100 } 7101 7102 if (!NewOpc) { 7103 if (VT == MVT::v2i64) 7104 // Fall through to expand this. It is not legal. 7105 return SDValue(); 7106 else 7107 // Other vector multiplications are legal. 7108 return Op; 7109 } 7110 } 7111 7112 // Legalize to a VMULL instruction. 7113 SDLoc DL(Op); 7114 SDValue Op0; 7115 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7116 if (!isMLA) { 7117 Op0 = SkipExtensionForVMULL(N0, DAG); 7118 assert(Op0.getValueType().is64BitVector() && 7119 Op1.getValueType().is64BitVector() && 7120 "unexpected types for extended operands to VMULL"); 7121 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7122 } 7123 7124 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7125 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7126 // vmull q0, d4, d6 7127 // vmlal q0, d5, d6 7128 // is faster than 7129 // vaddl q0, d4, d5 7130 // vmovl q1, d6 7131 // vmul q0, q0, q1 7132 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7133 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7134 EVT Op1VT = Op1.getValueType(); 7135 return DAG.getNode(N0->getOpcode(), DL, VT, 7136 DAG.getNode(NewOpc, DL, VT, 7137 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7138 DAG.getNode(NewOpc, DL, VT, 7139 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7140 } 7141 7142 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7143 SelectionDAG &DAG) { 7144 // TODO: Should this propagate fast-math-flags? 7145 7146 // Convert to float 7147 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7148 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7149 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7150 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7151 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7152 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7153 // Get reciprocal estimate. 7154 // float4 recip = vrecpeq_f32(yf); 7155 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7156 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7157 Y); 7158 // Because char has a smaller range than uchar, we can actually get away 7159 // without any newton steps. This requires that we use a weird bias 7160 // of 0xb000, however (again, this has been exhaustively tested). 7161 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7162 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7163 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7164 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7165 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7166 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7167 // Convert back to short. 7168 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7169 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7170 return X; 7171 } 7172 7173 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7174 SelectionDAG &DAG) { 7175 // TODO: Should this propagate fast-math-flags? 7176 7177 SDValue N2; 7178 // Convert to float. 7179 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7180 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7181 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7182 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7183 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7184 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7185 7186 // Use reciprocal estimate and one refinement step. 7187 // float4 recip = vrecpeq_f32(yf); 7188 // recip *= vrecpsq_f32(yf, recip); 7189 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7190 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7191 N1); 7192 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7193 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7194 N1, N2); 7195 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7196 // Because short has a smaller range than ushort, we can actually get away 7197 // with only a single newton step. This requires that we use a weird bias 7198 // of 89, however (again, this has been exhaustively tested). 7199 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7200 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7201 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7202 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7203 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7204 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7205 // Convert back to integer and return. 7206 // return vmovn_s32(vcvt_s32_f32(result)); 7207 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7208 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7209 return N0; 7210 } 7211 7212 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7213 EVT VT = Op.getValueType(); 7214 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7215 "unexpected type for custom-lowering ISD::SDIV"); 7216 7217 SDLoc dl(Op); 7218 SDValue N0 = Op.getOperand(0); 7219 SDValue N1 = Op.getOperand(1); 7220 SDValue N2, N3; 7221 7222 if (VT == MVT::v8i8) { 7223 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7224 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7225 7226 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7227 DAG.getIntPtrConstant(4, dl)); 7228 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7229 DAG.getIntPtrConstant(4, dl)); 7230 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7231 DAG.getIntPtrConstant(0, dl)); 7232 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7233 DAG.getIntPtrConstant(0, dl)); 7234 7235 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7236 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7237 7238 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7239 N0 = LowerCONCAT_VECTORS(N0, DAG); 7240 7241 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7242 return N0; 7243 } 7244 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7245 } 7246 7247 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7248 // TODO: Should this propagate fast-math-flags? 7249 EVT VT = Op.getValueType(); 7250 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7251 "unexpected type for custom-lowering ISD::UDIV"); 7252 7253 SDLoc dl(Op); 7254 SDValue N0 = Op.getOperand(0); 7255 SDValue N1 = Op.getOperand(1); 7256 SDValue N2, N3; 7257 7258 if (VT == MVT::v8i8) { 7259 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7260 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7261 7262 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7263 DAG.getIntPtrConstant(4, dl)); 7264 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7265 DAG.getIntPtrConstant(4, dl)); 7266 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7267 DAG.getIntPtrConstant(0, dl)); 7268 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7269 DAG.getIntPtrConstant(0, dl)); 7270 7271 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7272 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7273 7274 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7275 N0 = LowerCONCAT_VECTORS(N0, DAG); 7276 7277 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7278 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7279 MVT::i32), 7280 N0); 7281 return N0; 7282 } 7283 7284 // v4i16 sdiv ... Convert to float. 7285 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7286 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7287 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7288 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7289 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7290 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7291 7292 // Use reciprocal estimate and two refinement steps. 7293 // float4 recip = vrecpeq_f32(yf); 7294 // recip *= vrecpsq_f32(yf, recip); 7295 // recip *= vrecpsq_f32(yf, recip); 7296 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7297 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7298 BN1); 7299 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7300 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7301 BN1, N2); 7302 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7303 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7304 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7305 BN1, N2); 7306 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7307 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7308 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7309 // and that it will never cause us to return an answer too large). 7310 // float4 result = as_float4(as_int4(xf*recip) + 2); 7311 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7312 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7313 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7314 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7315 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7316 // Convert back to integer and return. 7317 // return vmovn_u32(vcvt_s32_f32(result)); 7318 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7319 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7320 return N0; 7321 } 7322 7323 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7324 EVT VT = Op.getNode()->getValueType(0); 7325 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7326 7327 unsigned Opc; 7328 bool ExtraOp = false; 7329 switch (Op.getOpcode()) { 7330 default: llvm_unreachable("Invalid code"); 7331 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7332 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7333 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7334 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7335 } 7336 7337 if (!ExtraOp) 7338 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7339 Op.getOperand(1)); 7340 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7341 Op.getOperand(1), Op.getOperand(2)); 7342 } 7343 7344 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7345 assert(Subtarget->isTargetDarwin()); 7346 7347 // For iOS, we want to call an alternative entry point: __sincos_stret, 7348 // return values are passed via sret. 7349 SDLoc dl(Op); 7350 SDValue Arg = Op.getOperand(0); 7351 EVT ArgVT = Arg.getValueType(); 7352 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7353 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7354 7355 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7356 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7357 7358 // Pair of floats / doubles used to pass the result. 7359 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 7360 auto &DL = DAG.getDataLayout(); 7361 7362 ArgListTy Args; 7363 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7364 SDValue SRet; 7365 if (ShouldUseSRet) { 7366 // Create stack object for sret. 7367 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7368 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7369 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7370 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7371 7372 ArgListEntry Entry; 7373 Entry.Node = SRet; 7374 Entry.Ty = RetTy->getPointerTo(); 7375 Entry.IsSExt = false; 7376 Entry.IsZExt = false; 7377 Entry.IsSRet = true; 7378 Args.push_back(Entry); 7379 RetTy = Type::getVoidTy(*DAG.getContext()); 7380 } 7381 7382 ArgListEntry Entry; 7383 Entry.Node = Arg; 7384 Entry.Ty = ArgTy; 7385 Entry.IsSExt = false; 7386 Entry.IsZExt = false; 7387 Args.push_back(Entry); 7388 7389 const char *LibcallName = 7390 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 7391 RTLIB::Libcall LC = 7392 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 7393 CallingConv::ID CC = getLibcallCallingConv(LC); 7394 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7395 7396 TargetLowering::CallLoweringInfo CLI(DAG); 7397 CLI.setDebugLoc(dl) 7398 .setChain(DAG.getEntryNode()) 7399 .setCallee(CC, RetTy, Callee, std::move(Args)) 7400 .setDiscardResult(ShouldUseSRet); 7401 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7402 7403 if (!ShouldUseSRet) 7404 return CallResult.first; 7405 7406 SDValue LoadSin = 7407 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7408 7409 // Address of cos field. 7410 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7411 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7412 SDValue LoadCos = 7413 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7414 7415 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7416 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7417 LoadSin.getValue(0), LoadCos.getValue(0)); 7418 } 7419 7420 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7421 bool Signed, 7422 SDValue &Chain) const { 7423 EVT VT = Op.getValueType(); 7424 assert((VT == MVT::i32 || VT == MVT::i64) && 7425 "unexpected type for custom lowering DIV"); 7426 SDLoc dl(Op); 7427 7428 const auto &DL = DAG.getDataLayout(); 7429 const auto &TLI = DAG.getTargetLoweringInfo(); 7430 7431 const char *Name = nullptr; 7432 if (Signed) 7433 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7434 else 7435 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7436 7437 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7438 7439 ARMTargetLowering::ArgListTy Args; 7440 7441 for (auto AI : {1, 0}) { 7442 ArgListEntry Arg; 7443 Arg.Node = Op.getOperand(AI); 7444 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7445 Args.push_back(Arg); 7446 } 7447 7448 CallLoweringInfo CLI(DAG); 7449 CLI.setDebugLoc(dl) 7450 .setChain(Chain) 7451 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7452 ES, std::move(Args)); 7453 7454 return LowerCallTo(CLI).first; 7455 } 7456 7457 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7458 bool Signed) const { 7459 assert(Op.getValueType() == MVT::i32 && 7460 "unexpected type for custom lowering DIV"); 7461 SDLoc dl(Op); 7462 7463 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7464 DAG.getEntryNode(), Op.getOperand(1)); 7465 7466 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7467 } 7468 7469 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7470 SDLoc DL(N); 7471 SDValue Op = N->getOperand(1); 7472 if (N->getValueType(0) == MVT::i32) 7473 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7474 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7475 DAG.getConstant(0, DL, MVT::i32)); 7476 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7477 DAG.getConstant(1, DL, MVT::i32)); 7478 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7479 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7480 } 7481 7482 void ARMTargetLowering::ExpandDIV_Windows( 7483 SDValue Op, SelectionDAG &DAG, bool Signed, 7484 SmallVectorImpl<SDValue> &Results) const { 7485 const auto &DL = DAG.getDataLayout(); 7486 const auto &TLI = DAG.getTargetLoweringInfo(); 7487 7488 assert(Op.getValueType() == MVT::i64 && 7489 "unexpected type for custom lowering DIV"); 7490 SDLoc dl(Op); 7491 7492 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7493 7494 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7495 7496 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7497 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7498 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7499 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7500 7501 Results.push_back(Lower); 7502 Results.push_back(Upper); 7503 } 7504 7505 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7506 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7507 // Acquire/Release load/store is not legal for targets without a dmb or 7508 // equivalent available. 7509 return SDValue(); 7510 7511 // Monotonic load/store is legal for all targets. 7512 return Op; 7513 } 7514 7515 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7516 SmallVectorImpl<SDValue> &Results, 7517 SelectionDAG &DAG, 7518 const ARMSubtarget *Subtarget) { 7519 SDLoc DL(N); 7520 // Under Power Management extensions, the cycle-count is: 7521 // mrc p15, #0, <Rt>, c9, c13, #0 7522 SDValue Ops[] = { N->getOperand(0), // Chain 7523 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7524 DAG.getConstant(15, DL, MVT::i32), 7525 DAG.getConstant(0, DL, MVT::i32), 7526 DAG.getConstant(9, DL, MVT::i32), 7527 DAG.getConstant(13, DL, MVT::i32), 7528 DAG.getConstant(0, DL, MVT::i32) 7529 }; 7530 7531 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7532 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7533 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7534 DAG.getConstant(0, DL, MVT::i32))); 7535 Results.push_back(Cycles32.getValue(1)); 7536 } 7537 7538 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7539 SDLoc dl(V.getNode()); 7540 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7541 SDValue VHi = DAG.getAnyExtOrTrunc( 7542 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7543 dl, MVT::i32); 7544 SDValue RegClass = 7545 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7546 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7547 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7548 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7549 return SDValue( 7550 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7551 } 7552 7553 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7554 SmallVectorImpl<SDValue> & Results, 7555 SelectionDAG &DAG) { 7556 assert(N->getValueType(0) == MVT::i64 && 7557 "AtomicCmpSwap on types less than 64 should be legal"); 7558 SDValue Ops[] = {N->getOperand(1), 7559 createGPRPairNode(DAG, N->getOperand(2)), 7560 createGPRPairNode(DAG, N->getOperand(3)), 7561 N->getOperand(0)}; 7562 SDNode *CmpSwap = DAG.getMachineNode( 7563 ARM::CMP_SWAP_64, SDLoc(N), 7564 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7565 7566 MachineFunction &MF = DAG.getMachineFunction(); 7567 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7568 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7569 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7570 7571 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7572 SDValue(CmpSwap, 0))); 7573 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7574 SDValue(CmpSwap, 0))); 7575 Results.push_back(SDValue(CmpSwap, 2)); 7576 } 7577 7578 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7579 SelectionDAG &DAG) { 7580 const auto &TLI = DAG.getTargetLoweringInfo(); 7581 7582 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7583 "Custom lowering is MSVCRT specific!"); 7584 7585 SDLoc dl(Op); 7586 SDValue Val = Op.getOperand(0); 7587 MVT Ty = Val->getSimpleValueType(0); 7588 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7589 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7590 TLI.getPointerTy(DAG.getDataLayout())); 7591 7592 TargetLowering::ArgListTy Args; 7593 TargetLowering::ArgListEntry Entry; 7594 7595 Entry.Node = Val; 7596 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7597 Entry.IsZExt = true; 7598 Args.push_back(Entry); 7599 7600 Entry.Node = Exponent; 7601 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7602 Entry.IsZExt = true; 7603 Args.push_back(Entry); 7604 7605 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7606 7607 // In the in-chain to the call is the entry node If we are emitting a 7608 // tailcall, the chain will be mutated if the node has a non-entry input 7609 // chain. 7610 SDValue InChain = DAG.getEntryNode(); 7611 SDValue TCChain = InChain; 7612 7613 const auto *F = DAG.getMachineFunction().getFunction(); 7614 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 7615 F->getReturnType() == LCRTy; 7616 if (IsTC) 7617 InChain = TCChain; 7618 7619 TargetLowering::CallLoweringInfo CLI(DAG); 7620 CLI.setDebugLoc(dl) 7621 .setChain(InChain) 7622 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 7623 .setTailCall(IsTC); 7624 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 7625 7626 // Return the chain (the DAG root) if it is a tail call 7627 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 7628 } 7629 7630 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7631 switch (Op.getOpcode()) { 7632 default: llvm_unreachable("Don't know how to custom lower this!"); 7633 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7634 case ISD::ConstantPool: 7635 if (Subtarget->genExecuteOnly()) 7636 llvm_unreachable("execute-only should not generate constant pools"); 7637 return LowerConstantPool(Op, DAG); 7638 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7639 case ISD::GlobalAddress: 7640 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7641 default: llvm_unreachable("unknown object format"); 7642 case Triple::COFF: 7643 return LowerGlobalAddressWindows(Op, DAG); 7644 case Triple::ELF: 7645 return LowerGlobalAddressELF(Op, DAG); 7646 case Triple::MachO: 7647 return LowerGlobalAddressDarwin(Op, DAG); 7648 } 7649 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7650 case ISD::SELECT: return LowerSELECT(Op, DAG); 7651 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7652 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7653 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7654 case ISD::VASTART: return LowerVASTART(Op, DAG); 7655 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7656 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7657 case ISD::SINT_TO_FP: 7658 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7659 case ISD::FP_TO_SINT: 7660 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7661 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7662 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7663 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7664 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7665 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7666 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7667 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7668 Subtarget); 7669 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7670 case ISD::SHL: 7671 case ISD::SRL: 7672 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7673 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7674 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7675 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7676 case ISD::SRL_PARTS: 7677 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7678 case ISD::CTTZ: 7679 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7680 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7681 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7682 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7683 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7684 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7685 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7686 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7687 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7688 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7689 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7690 case ISD::MUL: return LowerMUL(Op, DAG); 7691 case ISD::SDIV: 7692 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7693 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7694 return LowerSDIV(Op, DAG); 7695 case ISD::UDIV: 7696 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7697 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7698 return LowerUDIV(Op, DAG); 7699 case ISD::ADDC: 7700 case ISD::ADDE: 7701 case ISD::SUBC: 7702 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7703 case ISD::SADDO: 7704 case ISD::UADDO: 7705 case ISD::SSUBO: 7706 case ISD::USUBO: 7707 return LowerXALUO(Op, DAG); 7708 case ISD::ATOMIC_LOAD: 7709 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7710 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7711 case ISD::SDIVREM: 7712 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7713 case ISD::DYNAMIC_STACKALLOC: 7714 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7715 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7716 llvm_unreachable("Don't know how to custom lower this!"); 7717 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7718 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7719 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 7720 case ARMISD::WIN__DBZCHK: return SDValue(); 7721 } 7722 } 7723 7724 /// ReplaceNodeResults - Replace the results of node with an illegal result 7725 /// type with new values built out of custom code. 7726 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7727 SmallVectorImpl<SDValue> &Results, 7728 SelectionDAG &DAG) const { 7729 SDValue Res; 7730 switch (N->getOpcode()) { 7731 default: 7732 llvm_unreachable("Don't know how to custom expand this!"); 7733 case ISD::READ_REGISTER: 7734 ExpandREAD_REGISTER(N, Results, DAG); 7735 break; 7736 case ISD::BITCAST: 7737 Res = ExpandBITCAST(N, DAG); 7738 break; 7739 case ISD::SRL: 7740 case ISD::SRA: 7741 Res = Expand64BitShift(N, DAG, Subtarget); 7742 break; 7743 case ISD::SREM: 7744 case ISD::UREM: 7745 Res = LowerREM(N, DAG); 7746 break; 7747 case ISD::SDIVREM: 7748 case ISD::UDIVREM: 7749 Res = LowerDivRem(SDValue(N, 0), DAG); 7750 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7751 Results.push_back(Res.getValue(0)); 7752 Results.push_back(Res.getValue(1)); 7753 return; 7754 case ISD::READCYCLECOUNTER: 7755 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7756 return; 7757 case ISD::UDIV: 7758 case ISD::SDIV: 7759 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7760 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7761 Results); 7762 case ISD::ATOMIC_CMP_SWAP: 7763 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7764 return; 7765 } 7766 if (Res.getNode()) 7767 Results.push_back(Res); 7768 } 7769 7770 //===----------------------------------------------------------------------===// 7771 // ARM Scheduler Hooks 7772 //===----------------------------------------------------------------------===// 7773 7774 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7775 /// registers the function context. 7776 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7777 MachineBasicBlock *MBB, 7778 MachineBasicBlock *DispatchBB, 7779 int FI) const { 7780 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7781 "ROPI/RWPI not currently supported with SjLj"); 7782 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7783 DebugLoc dl = MI.getDebugLoc(); 7784 MachineFunction *MF = MBB->getParent(); 7785 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7786 MachineConstantPool *MCP = MF->getConstantPool(); 7787 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7788 const Function *F = MF->getFunction(); 7789 7790 bool isThumb = Subtarget->isThumb(); 7791 bool isThumb2 = Subtarget->isThumb2(); 7792 7793 unsigned PCLabelId = AFI->createPICLabelUId(); 7794 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7795 ARMConstantPoolValue *CPV = 7796 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7797 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7798 7799 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7800 : &ARM::GPRRegClass; 7801 7802 // Grab constant pool and fixed stack memory operands. 7803 MachineMemOperand *CPMMO = 7804 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7805 MachineMemOperand::MOLoad, 4, 4); 7806 7807 MachineMemOperand *FIMMOSt = 7808 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7809 MachineMemOperand::MOStore, 4, 4); 7810 7811 // Load the address of the dispatch MBB into the jump buffer. 7812 if (isThumb2) { 7813 // Incoming value: jbuf 7814 // ldr.n r5, LCPI1_1 7815 // orr r5, r5, #1 7816 // add r5, pc 7817 // str r5, [$jbuf, #+4] ; &jbuf[1] 7818 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7819 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7820 .addConstantPoolIndex(CPI) 7821 .addMemOperand(CPMMO) 7822 .add(predOps(ARMCC::AL)); 7823 // Set the low bit because of thumb mode. 7824 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7825 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7826 .addReg(NewVReg1, RegState::Kill) 7827 .addImm(0x01) 7828 .add(predOps(ARMCC::AL)) 7829 .add(condCodeOp()); 7830 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7831 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7832 .addReg(NewVReg2, RegState::Kill) 7833 .addImm(PCLabelId); 7834 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7835 .addReg(NewVReg3, RegState::Kill) 7836 .addFrameIndex(FI) 7837 .addImm(36) // &jbuf[1] :: pc 7838 .addMemOperand(FIMMOSt) 7839 .add(predOps(ARMCC::AL)); 7840 } else if (isThumb) { 7841 // Incoming value: jbuf 7842 // ldr.n r1, LCPI1_4 7843 // add r1, pc 7844 // mov r2, #1 7845 // orrs r1, r2 7846 // add r2, $jbuf, #+4 ; &jbuf[1] 7847 // str r1, [r2] 7848 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7849 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7850 .addConstantPoolIndex(CPI) 7851 .addMemOperand(CPMMO) 7852 .add(predOps(ARMCC::AL)); 7853 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7854 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7855 .addReg(NewVReg1, RegState::Kill) 7856 .addImm(PCLabelId); 7857 // Set the low bit because of thumb mode. 7858 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7859 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7860 .addReg(ARM::CPSR, RegState::Define) 7861 .addImm(1) 7862 .add(predOps(ARMCC::AL)); 7863 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7864 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7865 .addReg(ARM::CPSR, RegState::Define) 7866 .addReg(NewVReg2, RegState::Kill) 7867 .addReg(NewVReg3, RegState::Kill) 7868 .add(predOps(ARMCC::AL)); 7869 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7870 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7871 .addFrameIndex(FI) 7872 .addImm(36); // &jbuf[1] :: pc 7873 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7874 .addReg(NewVReg4, RegState::Kill) 7875 .addReg(NewVReg5, RegState::Kill) 7876 .addImm(0) 7877 .addMemOperand(FIMMOSt) 7878 .add(predOps(ARMCC::AL)); 7879 } else { 7880 // Incoming value: jbuf 7881 // ldr r1, LCPI1_1 7882 // add r1, pc, r1 7883 // str r1, [$jbuf, #+4] ; &jbuf[1] 7884 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7885 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7886 .addConstantPoolIndex(CPI) 7887 .addImm(0) 7888 .addMemOperand(CPMMO) 7889 .add(predOps(ARMCC::AL)); 7890 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7891 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7892 .addReg(NewVReg1, RegState::Kill) 7893 .addImm(PCLabelId) 7894 .add(predOps(ARMCC::AL)); 7895 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7896 .addReg(NewVReg2, RegState::Kill) 7897 .addFrameIndex(FI) 7898 .addImm(36) // &jbuf[1] :: pc 7899 .addMemOperand(FIMMOSt) 7900 .add(predOps(ARMCC::AL)); 7901 } 7902 } 7903 7904 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 7905 MachineBasicBlock *MBB) const { 7906 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7907 DebugLoc dl = MI.getDebugLoc(); 7908 MachineFunction *MF = MBB->getParent(); 7909 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7910 MachineFrameInfo &MFI = MF->getFrameInfo(); 7911 int FI = MFI.getFunctionContextIndex(); 7912 7913 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7914 : &ARM::GPRnopcRegClass; 7915 7916 // Get a mapping of the call site numbers to all of the landing pads they're 7917 // associated with. 7918 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 7919 unsigned MaxCSNum = 0; 7920 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7921 ++BB) { 7922 if (!BB->isEHPad()) continue; 7923 7924 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7925 // pad. 7926 for (MachineBasicBlock::iterator 7927 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7928 if (!II->isEHLabel()) continue; 7929 7930 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7931 if (!MF->hasCallSiteLandingPad(Sym)) continue; 7932 7933 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 7934 for (SmallVectorImpl<unsigned>::iterator 7935 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7936 CSI != CSE; ++CSI) { 7937 CallSiteNumToLPad[*CSI].push_back(&*BB); 7938 MaxCSNum = std::max(MaxCSNum, *CSI); 7939 } 7940 break; 7941 } 7942 } 7943 7944 // Get an ordered list of the machine basic blocks for the jump table. 7945 std::vector<MachineBasicBlock*> LPadList; 7946 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7947 LPadList.reserve(CallSiteNumToLPad.size()); 7948 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7949 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7950 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7951 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7952 LPadList.push_back(*II); 7953 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7954 } 7955 } 7956 7957 assert(!LPadList.empty() && 7958 "No landing pad destinations for the dispatch jump table!"); 7959 7960 // Create the jump table and associated information. 7961 MachineJumpTableInfo *JTI = 7962 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7963 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7964 7965 // Create the MBBs for the dispatch code. 7966 7967 // Shove the dispatch's address into the return slot in the function context. 7968 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7969 DispatchBB->setIsEHPad(); 7970 7971 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7972 unsigned trap_opcode; 7973 if (Subtarget->isThumb()) 7974 trap_opcode = ARM::tTRAP; 7975 else 7976 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7977 7978 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7979 DispatchBB->addSuccessor(TrapBB); 7980 7981 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7982 DispatchBB->addSuccessor(DispContBB); 7983 7984 // Insert and MBBs. 7985 MF->insert(MF->end(), DispatchBB); 7986 MF->insert(MF->end(), DispContBB); 7987 MF->insert(MF->end(), TrapBB); 7988 7989 // Insert code into the entry block that creates and registers the function 7990 // context. 7991 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7992 7993 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7994 MachinePointerInfo::getFixedStack(*MF, FI), 7995 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7996 7997 MachineInstrBuilder MIB; 7998 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7999 8000 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8001 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8002 8003 // Add a register mask with no preserved registers. This results in all 8004 // registers being marked as clobbered. This can't work if the dispatch block 8005 // is in a Thumb1 function and is linked with ARM code which uses the FP 8006 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8007 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8008 8009 bool IsPositionIndependent = isPositionIndependent(); 8010 unsigned NumLPads = LPadList.size(); 8011 if (Subtarget->isThumb2()) { 8012 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8013 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8014 .addFrameIndex(FI) 8015 .addImm(4) 8016 .addMemOperand(FIMMOLd) 8017 .add(predOps(ARMCC::AL)); 8018 8019 if (NumLPads < 256) { 8020 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8021 .addReg(NewVReg1) 8022 .addImm(LPadList.size()) 8023 .add(predOps(ARMCC::AL)); 8024 } else { 8025 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8026 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8027 .addImm(NumLPads & 0xFFFF) 8028 .add(predOps(ARMCC::AL)); 8029 8030 unsigned VReg2 = VReg1; 8031 if ((NumLPads & 0xFFFF0000) != 0) { 8032 VReg2 = MRI->createVirtualRegister(TRC); 8033 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8034 .addReg(VReg1) 8035 .addImm(NumLPads >> 16) 8036 .add(predOps(ARMCC::AL)); 8037 } 8038 8039 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8040 .addReg(NewVReg1) 8041 .addReg(VReg2) 8042 .add(predOps(ARMCC::AL)); 8043 } 8044 8045 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8046 .addMBB(TrapBB) 8047 .addImm(ARMCC::HI) 8048 .addReg(ARM::CPSR); 8049 8050 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8051 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8052 .addJumpTableIndex(MJTI) 8053 .add(predOps(ARMCC::AL)); 8054 8055 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8056 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8057 .addReg(NewVReg3, RegState::Kill) 8058 .addReg(NewVReg1) 8059 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8060 .add(predOps(ARMCC::AL)) 8061 .add(condCodeOp()); 8062 8063 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8064 .addReg(NewVReg4, RegState::Kill) 8065 .addReg(NewVReg1) 8066 .addJumpTableIndex(MJTI); 8067 } else if (Subtarget->isThumb()) { 8068 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8069 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8070 .addFrameIndex(FI) 8071 .addImm(1) 8072 .addMemOperand(FIMMOLd) 8073 .add(predOps(ARMCC::AL)); 8074 8075 if (NumLPads < 256) { 8076 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8077 .addReg(NewVReg1) 8078 .addImm(NumLPads) 8079 .add(predOps(ARMCC::AL)); 8080 } else { 8081 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8082 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8083 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8084 8085 // MachineConstantPool wants an explicit alignment. 8086 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8087 if (Align == 0) 8088 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8089 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8090 8091 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8092 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8093 .addReg(VReg1, RegState::Define) 8094 .addConstantPoolIndex(Idx) 8095 .add(predOps(ARMCC::AL)); 8096 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8097 .addReg(NewVReg1) 8098 .addReg(VReg1) 8099 .add(predOps(ARMCC::AL)); 8100 } 8101 8102 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8103 .addMBB(TrapBB) 8104 .addImm(ARMCC::HI) 8105 .addReg(ARM::CPSR); 8106 8107 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8108 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8109 .addReg(ARM::CPSR, RegState::Define) 8110 .addReg(NewVReg1) 8111 .addImm(2) 8112 .add(predOps(ARMCC::AL)); 8113 8114 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8115 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8116 .addJumpTableIndex(MJTI) 8117 .add(predOps(ARMCC::AL)); 8118 8119 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8120 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8121 .addReg(ARM::CPSR, RegState::Define) 8122 .addReg(NewVReg2, RegState::Kill) 8123 .addReg(NewVReg3) 8124 .add(predOps(ARMCC::AL)); 8125 8126 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8127 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8128 8129 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8130 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8131 .addReg(NewVReg4, RegState::Kill) 8132 .addImm(0) 8133 .addMemOperand(JTMMOLd) 8134 .add(predOps(ARMCC::AL)); 8135 8136 unsigned NewVReg6 = NewVReg5; 8137 if (IsPositionIndependent) { 8138 NewVReg6 = MRI->createVirtualRegister(TRC); 8139 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8140 .addReg(ARM::CPSR, RegState::Define) 8141 .addReg(NewVReg5, RegState::Kill) 8142 .addReg(NewVReg3) 8143 .add(predOps(ARMCC::AL)); 8144 } 8145 8146 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8147 .addReg(NewVReg6, RegState::Kill) 8148 .addJumpTableIndex(MJTI); 8149 } else { 8150 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8151 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8152 .addFrameIndex(FI) 8153 .addImm(4) 8154 .addMemOperand(FIMMOLd) 8155 .add(predOps(ARMCC::AL)); 8156 8157 if (NumLPads < 256) { 8158 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8159 .addReg(NewVReg1) 8160 .addImm(NumLPads) 8161 .add(predOps(ARMCC::AL)); 8162 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8163 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8164 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8165 .addImm(NumLPads & 0xFFFF) 8166 .add(predOps(ARMCC::AL)); 8167 8168 unsigned VReg2 = VReg1; 8169 if ((NumLPads & 0xFFFF0000) != 0) { 8170 VReg2 = MRI->createVirtualRegister(TRC); 8171 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8172 .addReg(VReg1) 8173 .addImm(NumLPads >> 16) 8174 .add(predOps(ARMCC::AL)); 8175 } 8176 8177 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8178 .addReg(NewVReg1) 8179 .addReg(VReg2) 8180 .add(predOps(ARMCC::AL)); 8181 } else { 8182 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8183 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8184 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8185 8186 // MachineConstantPool wants an explicit alignment. 8187 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8188 if (Align == 0) 8189 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8190 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8191 8192 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8193 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8194 .addReg(VReg1, RegState::Define) 8195 .addConstantPoolIndex(Idx) 8196 .addImm(0) 8197 .add(predOps(ARMCC::AL)); 8198 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8199 .addReg(NewVReg1) 8200 .addReg(VReg1, RegState::Kill) 8201 .add(predOps(ARMCC::AL)); 8202 } 8203 8204 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8205 .addMBB(TrapBB) 8206 .addImm(ARMCC::HI) 8207 .addReg(ARM::CPSR); 8208 8209 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8210 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8211 .addReg(NewVReg1) 8212 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8213 .add(predOps(ARMCC::AL)) 8214 .add(condCodeOp()); 8215 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8216 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8217 .addJumpTableIndex(MJTI) 8218 .add(predOps(ARMCC::AL)); 8219 8220 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8221 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8222 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8223 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8224 .addReg(NewVReg3, RegState::Kill) 8225 .addReg(NewVReg4) 8226 .addImm(0) 8227 .addMemOperand(JTMMOLd) 8228 .add(predOps(ARMCC::AL)); 8229 8230 if (IsPositionIndependent) { 8231 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8232 .addReg(NewVReg5, RegState::Kill) 8233 .addReg(NewVReg4) 8234 .addJumpTableIndex(MJTI); 8235 } else { 8236 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8237 .addReg(NewVReg5, RegState::Kill) 8238 .addJumpTableIndex(MJTI); 8239 } 8240 } 8241 8242 // Add the jump table entries as successors to the MBB. 8243 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8244 for (std::vector<MachineBasicBlock*>::iterator 8245 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8246 MachineBasicBlock *CurMBB = *I; 8247 if (SeenMBBs.insert(CurMBB).second) 8248 DispContBB->addSuccessor(CurMBB); 8249 } 8250 8251 // N.B. the order the invoke BBs are processed in doesn't matter here. 8252 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8253 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8254 for (MachineBasicBlock *BB : InvokeBBs) { 8255 8256 // Remove the landing pad successor from the invoke block and replace it 8257 // with the new dispatch block. 8258 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8259 BB->succ_end()); 8260 while (!Successors.empty()) { 8261 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8262 if (SMBB->isEHPad()) { 8263 BB->removeSuccessor(SMBB); 8264 MBBLPads.push_back(SMBB); 8265 } 8266 } 8267 8268 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8269 BB->normalizeSuccProbs(); 8270 8271 // Find the invoke call and mark all of the callee-saved registers as 8272 // 'implicit defined' so that they're spilled. This prevents code from 8273 // moving instructions to before the EH block, where they will never be 8274 // executed. 8275 for (MachineBasicBlock::reverse_iterator 8276 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8277 if (!II->isCall()) continue; 8278 8279 DenseMap<unsigned, bool> DefRegs; 8280 for (MachineInstr::mop_iterator 8281 OI = II->operands_begin(), OE = II->operands_end(); 8282 OI != OE; ++OI) { 8283 if (!OI->isReg()) continue; 8284 DefRegs[OI->getReg()] = true; 8285 } 8286 8287 MachineInstrBuilder MIB(*MF, &*II); 8288 8289 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8290 unsigned Reg = SavedRegs[i]; 8291 if (Subtarget->isThumb2() && 8292 !ARM::tGPRRegClass.contains(Reg) && 8293 !ARM::hGPRRegClass.contains(Reg)) 8294 continue; 8295 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8296 continue; 8297 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8298 continue; 8299 if (!DefRegs[Reg]) 8300 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8301 } 8302 8303 break; 8304 } 8305 } 8306 8307 // Mark all former landing pads as non-landing pads. The dispatch is the only 8308 // landing pad now. 8309 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8310 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8311 (*I)->setIsEHPad(false); 8312 8313 // The instruction is gone now. 8314 MI.eraseFromParent(); 8315 } 8316 8317 static 8318 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8319 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8320 E = MBB->succ_end(); I != E; ++I) 8321 if (*I != Succ) 8322 return *I; 8323 llvm_unreachable("Expecting a BB with two successors!"); 8324 } 8325 8326 /// Return the load opcode for a given load size. If load size >= 8, 8327 /// neon opcode will be returned. 8328 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8329 if (LdSize >= 8) 8330 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8331 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8332 if (IsThumb1) 8333 return LdSize == 4 ? ARM::tLDRi 8334 : LdSize == 2 ? ARM::tLDRHi 8335 : LdSize == 1 ? ARM::tLDRBi : 0; 8336 if (IsThumb2) 8337 return LdSize == 4 ? ARM::t2LDR_POST 8338 : LdSize == 2 ? ARM::t2LDRH_POST 8339 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8340 return LdSize == 4 ? ARM::LDR_POST_IMM 8341 : LdSize == 2 ? ARM::LDRH_POST 8342 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8343 } 8344 8345 /// Return the store opcode for a given store size. If store size >= 8, 8346 /// neon opcode will be returned. 8347 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8348 if (StSize >= 8) 8349 return StSize == 16 ? ARM::VST1q32wb_fixed 8350 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8351 if (IsThumb1) 8352 return StSize == 4 ? ARM::tSTRi 8353 : StSize == 2 ? ARM::tSTRHi 8354 : StSize == 1 ? ARM::tSTRBi : 0; 8355 if (IsThumb2) 8356 return StSize == 4 ? ARM::t2STR_POST 8357 : StSize == 2 ? ARM::t2STRH_POST 8358 : StSize == 1 ? ARM::t2STRB_POST : 0; 8359 return StSize == 4 ? ARM::STR_POST_IMM 8360 : StSize == 2 ? ARM::STRH_POST 8361 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8362 } 8363 8364 /// Emit a post-increment load operation with given size. The instructions 8365 /// will be added to BB at Pos. 8366 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8367 const TargetInstrInfo *TII, const DebugLoc &dl, 8368 unsigned LdSize, unsigned Data, unsigned AddrIn, 8369 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8370 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8371 assert(LdOpc != 0 && "Should have a load opcode"); 8372 if (LdSize >= 8) { 8373 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8374 .addReg(AddrOut, RegState::Define) 8375 .addReg(AddrIn) 8376 .addImm(0) 8377 .add(predOps(ARMCC::AL)); 8378 } else if (IsThumb1) { 8379 // load + update AddrIn 8380 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8381 .addReg(AddrIn) 8382 .addImm(0) 8383 .add(predOps(ARMCC::AL)); 8384 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8385 .add(t1CondCodeOp()) 8386 .addReg(AddrIn) 8387 .addImm(LdSize) 8388 .add(predOps(ARMCC::AL)); 8389 } else if (IsThumb2) { 8390 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8391 .addReg(AddrOut, RegState::Define) 8392 .addReg(AddrIn) 8393 .addImm(LdSize) 8394 .add(predOps(ARMCC::AL)); 8395 } else { // arm 8396 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8397 .addReg(AddrOut, RegState::Define) 8398 .addReg(AddrIn) 8399 .addReg(0) 8400 .addImm(LdSize) 8401 .add(predOps(ARMCC::AL)); 8402 } 8403 } 8404 8405 /// Emit a post-increment store operation with given size. The instructions 8406 /// will be added to BB at Pos. 8407 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8408 const TargetInstrInfo *TII, const DebugLoc &dl, 8409 unsigned StSize, unsigned Data, unsigned AddrIn, 8410 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8411 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8412 assert(StOpc != 0 && "Should have a store opcode"); 8413 if (StSize >= 8) { 8414 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8415 .addReg(AddrIn) 8416 .addImm(0) 8417 .addReg(Data) 8418 .add(predOps(ARMCC::AL)); 8419 } else if (IsThumb1) { 8420 // store + update AddrIn 8421 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8422 .addReg(Data) 8423 .addReg(AddrIn) 8424 .addImm(0) 8425 .add(predOps(ARMCC::AL)); 8426 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8427 .add(t1CondCodeOp()) 8428 .addReg(AddrIn) 8429 .addImm(StSize) 8430 .add(predOps(ARMCC::AL)); 8431 } else if (IsThumb2) { 8432 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8433 .addReg(Data) 8434 .addReg(AddrIn) 8435 .addImm(StSize) 8436 .add(predOps(ARMCC::AL)); 8437 } else { // arm 8438 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8439 .addReg(Data) 8440 .addReg(AddrIn) 8441 .addReg(0) 8442 .addImm(StSize) 8443 .add(predOps(ARMCC::AL)); 8444 } 8445 } 8446 8447 MachineBasicBlock * 8448 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8449 MachineBasicBlock *BB) const { 8450 // This pseudo instruction has 3 operands: dst, src, size 8451 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8452 // Otherwise, we will generate unrolled scalar copies. 8453 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8454 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8455 MachineFunction::iterator It = ++BB->getIterator(); 8456 8457 unsigned dest = MI.getOperand(0).getReg(); 8458 unsigned src = MI.getOperand(1).getReg(); 8459 unsigned SizeVal = MI.getOperand(2).getImm(); 8460 unsigned Align = MI.getOperand(3).getImm(); 8461 DebugLoc dl = MI.getDebugLoc(); 8462 8463 MachineFunction *MF = BB->getParent(); 8464 MachineRegisterInfo &MRI = MF->getRegInfo(); 8465 unsigned UnitSize = 0; 8466 const TargetRegisterClass *TRC = nullptr; 8467 const TargetRegisterClass *VecTRC = nullptr; 8468 8469 bool IsThumb1 = Subtarget->isThumb1Only(); 8470 bool IsThumb2 = Subtarget->isThumb2(); 8471 bool IsThumb = Subtarget->isThumb(); 8472 8473 if (Align & 1) { 8474 UnitSize = 1; 8475 } else if (Align & 2) { 8476 UnitSize = 2; 8477 } else { 8478 // Check whether we can use NEON instructions. 8479 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 8480 Subtarget->hasNEON()) { 8481 if ((Align % 16 == 0) && SizeVal >= 16) 8482 UnitSize = 16; 8483 else if ((Align % 8 == 0) && SizeVal >= 8) 8484 UnitSize = 8; 8485 } 8486 // Can't use NEON instructions. 8487 if (UnitSize == 0) 8488 UnitSize = 4; 8489 } 8490 8491 // Select the correct opcode and register class for unit size load/store 8492 bool IsNeon = UnitSize >= 8; 8493 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8494 if (IsNeon) 8495 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8496 : UnitSize == 8 ? &ARM::DPRRegClass 8497 : nullptr; 8498 8499 unsigned BytesLeft = SizeVal % UnitSize; 8500 unsigned LoopSize = SizeVal - BytesLeft; 8501 8502 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8503 // Use LDR and STR to copy. 8504 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8505 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8506 unsigned srcIn = src; 8507 unsigned destIn = dest; 8508 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8509 unsigned srcOut = MRI.createVirtualRegister(TRC); 8510 unsigned destOut = MRI.createVirtualRegister(TRC); 8511 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8512 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8513 IsThumb1, IsThumb2); 8514 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8515 IsThumb1, IsThumb2); 8516 srcIn = srcOut; 8517 destIn = destOut; 8518 } 8519 8520 // Handle the leftover bytes with LDRB and STRB. 8521 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8522 // [destOut] = STRB_POST(scratch, destIn, 1) 8523 for (unsigned i = 0; i < BytesLeft; i++) { 8524 unsigned srcOut = MRI.createVirtualRegister(TRC); 8525 unsigned destOut = MRI.createVirtualRegister(TRC); 8526 unsigned scratch = MRI.createVirtualRegister(TRC); 8527 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8528 IsThumb1, IsThumb2); 8529 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8530 IsThumb1, IsThumb2); 8531 srcIn = srcOut; 8532 destIn = destOut; 8533 } 8534 MI.eraseFromParent(); // The instruction is gone now. 8535 return BB; 8536 } 8537 8538 // Expand the pseudo op to a loop. 8539 // thisMBB: 8540 // ... 8541 // movw varEnd, # --> with thumb2 8542 // movt varEnd, # 8543 // ldrcp varEnd, idx --> without thumb2 8544 // fallthrough --> loopMBB 8545 // loopMBB: 8546 // PHI varPhi, varEnd, varLoop 8547 // PHI srcPhi, src, srcLoop 8548 // PHI destPhi, dst, destLoop 8549 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8550 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8551 // subs varLoop, varPhi, #UnitSize 8552 // bne loopMBB 8553 // fallthrough --> exitMBB 8554 // exitMBB: 8555 // epilogue to handle left-over bytes 8556 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8557 // [destOut] = STRB_POST(scratch, destLoop, 1) 8558 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8559 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8560 MF->insert(It, loopMBB); 8561 MF->insert(It, exitMBB); 8562 8563 // Transfer the remainder of BB and its successor edges to exitMBB. 8564 exitMBB->splice(exitMBB->begin(), BB, 8565 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8566 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8567 8568 // Load an immediate to varEnd. 8569 unsigned varEnd = MRI.createVirtualRegister(TRC); 8570 if (Subtarget->useMovt(*MF)) { 8571 unsigned Vtmp = varEnd; 8572 if ((LoopSize & 0xFFFF0000) != 0) 8573 Vtmp = MRI.createVirtualRegister(TRC); 8574 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8575 .addImm(LoopSize & 0xFFFF) 8576 .add(predOps(ARMCC::AL)); 8577 8578 if ((LoopSize & 0xFFFF0000) != 0) 8579 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8580 .addReg(Vtmp) 8581 .addImm(LoopSize >> 16) 8582 .add(predOps(ARMCC::AL)); 8583 } else { 8584 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8585 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8586 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8587 8588 // MachineConstantPool wants an explicit alignment. 8589 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8590 if (Align == 0) 8591 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8592 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8593 8594 if (IsThumb) 8595 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 8596 .addReg(varEnd, RegState::Define) 8597 .addConstantPoolIndex(Idx) 8598 .add(predOps(ARMCC::AL)); 8599 else 8600 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 8601 .addReg(varEnd, RegState::Define) 8602 .addConstantPoolIndex(Idx) 8603 .addImm(0) 8604 .add(predOps(ARMCC::AL)); 8605 } 8606 BB->addSuccessor(loopMBB); 8607 8608 // Generate the loop body: 8609 // varPhi = PHI(varLoop, varEnd) 8610 // srcPhi = PHI(srcLoop, src) 8611 // destPhi = PHI(destLoop, dst) 8612 MachineBasicBlock *entryBB = BB; 8613 BB = loopMBB; 8614 unsigned varLoop = MRI.createVirtualRegister(TRC); 8615 unsigned varPhi = MRI.createVirtualRegister(TRC); 8616 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8617 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8618 unsigned destLoop = MRI.createVirtualRegister(TRC); 8619 unsigned destPhi = MRI.createVirtualRegister(TRC); 8620 8621 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8622 .addReg(varLoop).addMBB(loopMBB) 8623 .addReg(varEnd).addMBB(entryBB); 8624 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8625 .addReg(srcLoop).addMBB(loopMBB) 8626 .addReg(src).addMBB(entryBB); 8627 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8628 .addReg(destLoop).addMBB(loopMBB) 8629 .addReg(dest).addMBB(entryBB); 8630 8631 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8632 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8633 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8634 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8635 IsThumb1, IsThumb2); 8636 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8637 IsThumb1, IsThumb2); 8638 8639 // Decrement loop variable by UnitSize. 8640 if (IsThumb1) { 8641 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 8642 .add(t1CondCodeOp()) 8643 .addReg(varPhi) 8644 .addImm(UnitSize) 8645 .add(predOps(ARMCC::AL)); 8646 } else { 8647 MachineInstrBuilder MIB = 8648 BuildMI(*BB, BB->end(), dl, 8649 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8650 MIB.addReg(varPhi) 8651 .addImm(UnitSize) 8652 .add(predOps(ARMCC::AL)) 8653 .add(condCodeOp()); 8654 MIB->getOperand(5).setReg(ARM::CPSR); 8655 MIB->getOperand(5).setIsDef(true); 8656 } 8657 BuildMI(*BB, BB->end(), dl, 8658 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8659 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8660 8661 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8662 BB->addSuccessor(loopMBB); 8663 BB->addSuccessor(exitMBB); 8664 8665 // Add epilogue to handle BytesLeft. 8666 BB = exitMBB; 8667 auto StartOfExit = exitMBB->begin(); 8668 8669 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8670 // [destOut] = STRB_POST(scratch, destLoop, 1) 8671 unsigned srcIn = srcLoop; 8672 unsigned destIn = destLoop; 8673 for (unsigned i = 0; i < BytesLeft; i++) { 8674 unsigned srcOut = MRI.createVirtualRegister(TRC); 8675 unsigned destOut = MRI.createVirtualRegister(TRC); 8676 unsigned scratch = MRI.createVirtualRegister(TRC); 8677 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8678 IsThumb1, IsThumb2); 8679 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8680 IsThumb1, IsThumb2); 8681 srcIn = srcOut; 8682 destIn = destOut; 8683 } 8684 8685 MI.eraseFromParent(); // The instruction is gone now. 8686 return BB; 8687 } 8688 8689 MachineBasicBlock * 8690 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8691 MachineBasicBlock *MBB) const { 8692 const TargetMachine &TM = getTargetMachine(); 8693 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8694 DebugLoc DL = MI.getDebugLoc(); 8695 8696 assert(Subtarget->isTargetWindows() && 8697 "__chkstk is only supported on Windows"); 8698 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8699 8700 // __chkstk takes the number of words to allocate on the stack in R4, and 8701 // returns the stack adjustment in number of bytes in R4. This will not 8702 // clober any other registers (other than the obvious lr). 8703 // 8704 // Although, technically, IP should be considered a register which may be 8705 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8706 // thumb-2 environment, so there is no interworking required. As a result, we 8707 // do not expect a veneer to be emitted by the linker, clobbering IP. 8708 // 8709 // Each module receives its own copy of __chkstk, so no import thunk is 8710 // required, again, ensuring that IP is not clobbered. 8711 // 8712 // Finally, although some linkers may theoretically provide a trampoline for 8713 // out of range calls (which is quite common due to a 32M range limitation of 8714 // branches for Thumb), we can generate the long-call version via 8715 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8716 // IP. 8717 8718 switch (TM.getCodeModel()) { 8719 case CodeModel::Small: 8720 case CodeModel::Medium: 8721 case CodeModel::Default: 8722 case CodeModel::Kernel: 8723 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8724 .add(predOps(ARMCC::AL)) 8725 .addExternalSymbol("__chkstk") 8726 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8727 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8728 .addReg(ARM::R12, 8729 RegState::Implicit | RegState::Define | RegState::Dead); 8730 break; 8731 case CodeModel::Large: 8732 case CodeModel::JITDefault: { 8733 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8734 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8735 8736 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8737 .addExternalSymbol("__chkstk"); 8738 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8739 .add(predOps(ARMCC::AL)) 8740 .addReg(Reg, RegState::Kill) 8741 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8742 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8743 .addReg(ARM::R12, 8744 RegState::Implicit | RegState::Define | RegState::Dead); 8745 break; 8746 } 8747 } 8748 8749 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 8750 .addReg(ARM::SP, RegState::Kill) 8751 .addReg(ARM::R4, RegState::Kill) 8752 .setMIFlags(MachineInstr::FrameSetup) 8753 .add(predOps(ARMCC::AL)) 8754 .add(condCodeOp()); 8755 8756 MI.eraseFromParent(); 8757 return MBB; 8758 } 8759 8760 MachineBasicBlock * 8761 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8762 MachineBasicBlock *MBB) const { 8763 DebugLoc DL = MI.getDebugLoc(); 8764 MachineFunction *MF = MBB->getParent(); 8765 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8766 8767 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8768 MF->insert(++MBB->getIterator(), ContBB); 8769 ContBB->splice(ContBB->begin(), MBB, 8770 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8771 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8772 MBB->addSuccessor(ContBB); 8773 8774 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8775 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 8776 MF->push_back(TrapBB); 8777 MBB->addSuccessor(TrapBB); 8778 8779 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 8780 .addReg(MI.getOperand(0).getReg()) 8781 .addImm(0) 8782 .add(predOps(ARMCC::AL)); 8783 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 8784 .addMBB(TrapBB) 8785 .addImm(ARMCC::EQ) 8786 .addReg(ARM::CPSR); 8787 8788 MI.eraseFromParent(); 8789 return ContBB; 8790 } 8791 8792 MachineBasicBlock * 8793 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8794 MachineBasicBlock *BB) const { 8795 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8796 DebugLoc dl = MI.getDebugLoc(); 8797 bool isThumb2 = Subtarget->isThumb2(); 8798 switch (MI.getOpcode()) { 8799 default: { 8800 MI.print(errs()); 8801 llvm_unreachable("Unexpected instr type to insert"); 8802 } 8803 8804 // Thumb1 post-indexed loads are really just single-register LDMs. 8805 case ARM::tLDR_postidx: { 8806 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8807 .add(MI.getOperand(1)) // Rn_wb 8808 .add(MI.getOperand(2)) // Rn 8809 .add(MI.getOperand(3)) // PredImm 8810 .add(MI.getOperand(4)) // PredReg 8811 .add(MI.getOperand(0)); // Rt 8812 MI.eraseFromParent(); 8813 return BB; 8814 } 8815 8816 // The Thumb2 pre-indexed stores have the same MI operands, they just 8817 // define them differently in the .td files from the isel patterns, so 8818 // they need pseudos. 8819 case ARM::t2STR_preidx: 8820 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8821 return BB; 8822 case ARM::t2STRB_preidx: 8823 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 8824 return BB; 8825 case ARM::t2STRH_preidx: 8826 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 8827 return BB; 8828 8829 case ARM::STRi_preidx: 8830 case ARM::STRBi_preidx: { 8831 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 8832 : ARM::STRB_PRE_IMM; 8833 // Decode the offset. 8834 unsigned Offset = MI.getOperand(4).getImm(); 8835 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8836 Offset = ARM_AM::getAM2Offset(Offset); 8837 if (isSub) 8838 Offset = -Offset; 8839 8840 MachineMemOperand *MMO = *MI.memoperands_begin(); 8841 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8842 .add(MI.getOperand(0)) // Rn_wb 8843 .add(MI.getOperand(1)) // Rt 8844 .add(MI.getOperand(2)) // Rn 8845 .addImm(Offset) // offset (skip GPR==zero_reg) 8846 .add(MI.getOperand(5)) // pred 8847 .add(MI.getOperand(6)) 8848 .addMemOperand(MMO); 8849 MI.eraseFromParent(); 8850 return BB; 8851 } 8852 case ARM::STRr_preidx: 8853 case ARM::STRBr_preidx: 8854 case ARM::STRH_preidx: { 8855 unsigned NewOpc; 8856 switch (MI.getOpcode()) { 8857 default: llvm_unreachable("unexpected opcode!"); 8858 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8859 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8860 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8861 } 8862 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8863 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 8864 MIB.add(MI.getOperand(i)); 8865 MI.eraseFromParent(); 8866 return BB; 8867 } 8868 8869 case ARM::tMOVCCr_pseudo: { 8870 // To "insert" a SELECT_CC instruction, we actually have to insert the 8871 // diamond control-flow pattern. The incoming instruction knows the 8872 // destination vreg to set, the condition code register to branch on, the 8873 // true/false values to select between, and a branch opcode to use. 8874 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8875 MachineFunction::iterator It = ++BB->getIterator(); 8876 8877 // thisMBB: 8878 // ... 8879 // TrueVal = ... 8880 // cmpTY ccX, r1, r2 8881 // bCC copy1MBB 8882 // fallthrough --> copy0MBB 8883 MachineBasicBlock *thisMBB = BB; 8884 MachineFunction *F = BB->getParent(); 8885 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8886 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8887 F->insert(It, copy0MBB); 8888 F->insert(It, sinkMBB); 8889 8890 // Transfer the remainder of BB and its successor edges to sinkMBB. 8891 sinkMBB->splice(sinkMBB->begin(), BB, 8892 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8893 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8894 8895 BB->addSuccessor(copy0MBB); 8896 BB->addSuccessor(sinkMBB); 8897 8898 BuildMI(BB, dl, TII->get(ARM::tBcc)) 8899 .addMBB(sinkMBB) 8900 .addImm(MI.getOperand(3).getImm()) 8901 .addReg(MI.getOperand(4).getReg()); 8902 8903 // copy0MBB: 8904 // %FalseValue = ... 8905 // # fallthrough to sinkMBB 8906 BB = copy0MBB; 8907 8908 // Update machine-CFG edges 8909 BB->addSuccessor(sinkMBB); 8910 8911 // sinkMBB: 8912 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8913 // ... 8914 BB = sinkMBB; 8915 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 8916 .addReg(MI.getOperand(1).getReg()) 8917 .addMBB(copy0MBB) 8918 .addReg(MI.getOperand(2).getReg()) 8919 .addMBB(thisMBB); 8920 8921 MI.eraseFromParent(); // The pseudo instruction is gone now. 8922 return BB; 8923 } 8924 8925 case ARM::BCCi64: 8926 case ARM::BCCZi64: { 8927 // If there is an unconditional branch to the other successor, remove it. 8928 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8929 8930 // Compare both parts that make up the double comparison separately for 8931 // equality. 8932 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 8933 8934 unsigned LHS1 = MI.getOperand(1).getReg(); 8935 unsigned LHS2 = MI.getOperand(2).getReg(); 8936 if (RHSisZero) { 8937 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8938 .addReg(LHS1) 8939 .addImm(0) 8940 .add(predOps(ARMCC::AL)); 8941 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8942 .addReg(LHS2).addImm(0) 8943 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8944 } else { 8945 unsigned RHS1 = MI.getOperand(3).getReg(); 8946 unsigned RHS2 = MI.getOperand(4).getReg(); 8947 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8948 .addReg(LHS1) 8949 .addReg(RHS1) 8950 .add(predOps(ARMCC::AL)); 8951 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8952 .addReg(LHS2).addReg(RHS2) 8953 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8954 } 8955 8956 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 8957 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8958 if (MI.getOperand(0).getImm() == ARMCC::NE) 8959 std::swap(destMBB, exitMBB); 8960 8961 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8962 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8963 if (isThumb2) 8964 BuildMI(BB, dl, TII->get(ARM::t2B)) 8965 .addMBB(exitMBB) 8966 .add(predOps(ARMCC::AL)); 8967 else 8968 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8969 8970 MI.eraseFromParent(); // The pseudo instruction is gone now. 8971 return BB; 8972 } 8973 8974 case ARM::Int_eh_sjlj_setjmp: 8975 case ARM::Int_eh_sjlj_setjmp_nofp: 8976 case ARM::tInt_eh_sjlj_setjmp: 8977 case ARM::t2Int_eh_sjlj_setjmp: 8978 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8979 return BB; 8980 8981 case ARM::Int_eh_sjlj_setup_dispatch: 8982 EmitSjLjDispatchBlock(MI, BB); 8983 return BB; 8984 8985 case ARM::ABS: 8986 case ARM::t2ABS: { 8987 // To insert an ABS instruction, we have to insert the 8988 // diamond control-flow pattern. The incoming instruction knows the 8989 // source vreg to test against 0, the destination vreg to set, 8990 // the condition code register to branch on, the 8991 // true/false values to select between, and a branch opcode to use. 8992 // It transforms 8993 // V1 = ABS V0 8994 // into 8995 // V2 = MOVS V0 8996 // BCC (branch to SinkBB if V0 >= 0) 8997 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8998 // SinkBB: V1 = PHI(V2, V3) 8999 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9000 MachineFunction::iterator BBI = ++BB->getIterator(); 9001 MachineFunction *Fn = BB->getParent(); 9002 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9003 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9004 Fn->insert(BBI, RSBBB); 9005 Fn->insert(BBI, SinkBB); 9006 9007 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9008 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9009 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9010 bool isThumb2 = Subtarget->isThumb2(); 9011 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9012 // In Thumb mode S must not be specified if source register is the SP or 9013 // PC and if destination register is the SP, so restrict register class 9014 unsigned NewRsbDstReg = 9015 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9016 9017 // Transfer the remainder of BB and its successor edges to sinkMBB. 9018 SinkBB->splice(SinkBB->begin(), BB, 9019 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9020 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9021 9022 BB->addSuccessor(RSBBB); 9023 BB->addSuccessor(SinkBB); 9024 9025 // fall through to SinkMBB 9026 RSBBB->addSuccessor(SinkBB); 9027 9028 // insert a cmp at the end of BB 9029 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9030 .addReg(ABSSrcReg) 9031 .addImm(0) 9032 .add(predOps(ARMCC::AL)); 9033 9034 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9035 BuildMI(BB, dl, 9036 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9037 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9038 9039 // insert rsbri in RSBBB 9040 // Note: BCC and rsbri will be converted into predicated rsbmi 9041 // by if-conversion pass 9042 BuildMI(*RSBBB, RSBBB->begin(), dl, 9043 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9044 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9045 .addImm(0) 9046 .add(predOps(ARMCC::AL)) 9047 .add(condCodeOp()); 9048 9049 // insert PHI in SinkBB, 9050 // reuse ABSDstReg to not change uses of ABS instruction 9051 BuildMI(*SinkBB, SinkBB->begin(), dl, 9052 TII->get(ARM::PHI), ABSDstReg) 9053 .addReg(NewRsbDstReg).addMBB(RSBBB) 9054 .addReg(ABSSrcReg).addMBB(BB); 9055 9056 // remove ABS instruction 9057 MI.eraseFromParent(); 9058 9059 // return last added BB 9060 return SinkBB; 9061 } 9062 case ARM::COPY_STRUCT_BYVAL_I32: 9063 ++NumLoopByVals; 9064 return EmitStructByval(MI, BB); 9065 case ARM::WIN__CHKSTK: 9066 return EmitLowered__chkstk(MI, BB); 9067 case ARM::WIN__DBZCHK: 9068 return EmitLowered__dbzchk(MI, BB); 9069 } 9070 } 9071 9072 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 9073 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9074 /// instead of as a custom inserter because we need the use list from the SDNode. 9075 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9076 MachineInstr &MI, const SDNode *Node) { 9077 bool isThumb1 = Subtarget->isThumb1Only(); 9078 9079 DebugLoc DL = MI.getDebugLoc(); 9080 MachineFunction *MF = MI.getParent()->getParent(); 9081 MachineRegisterInfo &MRI = MF->getRegInfo(); 9082 MachineInstrBuilder MIB(*MF, MI); 9083 9084 // If the new dst/src is unused mark it as dead. 9085 if (!Node->hasAnyUseOfValue(0)) { 9086 MI.getOperand(0).setIsDead(true); 9087 } 9088 if (!Node->hasAnyUseOfValue(1)) { 9089 MI.getOperand(1).setIsDead(true); 9090 } 9091 9092 // The MEMCPY both defines and kills the scratch registers. 9093 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9094 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9095 : &ARM::GPRRegClass); 9096 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9097 } 9098 } 9099 9100 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9101 SDNode *Node) const { 9102 if (MI.getOpcode() == ARM::MEMCPY) { 9103 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9104 return; 9105 } 9106 9107 const MCInstrDesc *MCID = &MI.getDesc(); 9108 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9109 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9110 // operand is still set to noreg. If needed, set the optional operand's 9111 // register to CPSR, and remove the redundant implicit def. 9112 // 9113 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 9114 9115 // Rename pseudo opcodes. 9116 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9117 unsigned ccOutIdx; 9118 if (NewOpc) { 9119 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9120 MCID = &TII->get(NewOpc); 9121 9122 assert(MCID->getNumOperands() == 9123 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9124 && "converted opcode should be the same except for cc_out" 9125 " (and, on Thumb1, pred)"); 9126 9127 MI.setDesc(*MCID); 9128 9129 // Add the optional cc_out operand 9130 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9131 9132 // On Thumb1, move all input operands to the end, then add the predicate 9133 if (Subtarget->isThumb1Only()) { 9134 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9135 MI.addOperand(MI.getOperand(1)); 9136 MI.RemoveOperand(1); 9137 } 9138 9139 // Restore the ties 9140 for (unsigned i = MI.getNumOperands(); i--;) { 9141 const MachineOperand& op = MI.getOperand(i); 9142 if (op.isReg() && op.isUse()) { 9143 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9144 if (DefIdx != -1) 9145 MI.tieOperands(DefIdx, i); 9146 } 9147 } 9148 9149 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9150 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9151 ccOutIdx = 1; 9152 } else 9153 ccOutIdx = MCID->getNumOperands() - 1; 9154 } else 9155 ccOutIdx = MCID->getNumOperands() - 1; 9156 9157 // Any ARM instruction that sets the 's' bit should specify an optional 9158 // "cc_out" operand in the last operand position. 9159 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9160 assert(!NewOpc && "Optional cc_out operand required"); 9161 return; 9162 } 9163 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9164 // since we already have an optional CPSR def. 9165 bool definesCPSR = false; 9166 bool deadCPSR = false; 9167 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9168 ++i) { 9169 const MachineOperand &MO = MI.getOperand(i); 9170 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9171 definesCPSR = true; 9172 if (MO.isDead()) 9173 deadCPSR = true; 9174 MI.RemoveOperand(i); 9175 break; 9176 } 9177 } 9178 if (!definesCPSR) { 9179 assert(!NewOpc && "Optional cc_out operand required"); 9180 return; 9181 } 9182 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9183 if (deadCPSR) { 9184 assert(!MI.getOperand(ccOutIdx).getReg() && 9185 "expect uninitialized optional cc_out operand"); 9186 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9187 if (!Subtarget->isThumb1Only()) 9188 return; 9189 } 9190 9191 // If this instruction was defined with an optional CPSR def and its dag node 9192 // had a live implicit CPSR def, then activate the optional CPSR def. 9193 MachineOperand &MO = MI.getOperand(ccOutIdx); 9194 MO.setReg(ARM::CPSR); 9195 MO.setIsDef(true); 9196 } 9197 9198 //===----------------------------------------------------------------------===// 9199 // ARM Optimization Hooks 9200 //===----------------------------------------------------------------------===// 9201 9202 // Helper function that checks if N is a null or all ones constant. 9203 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9204 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9205 } 9206 9207 // Return true if N is conditionally 0 or all ones. 9208 // Detects these expressions where cc is an i1 value: 9209 // 9210 // (select cc 0, y) [AllOnes=0] 9211 // (select cc y, 0) [AllOnes=0] 9212 // (zext cc) [AllOnes=0] 9213 // (sext cc) [AllOnes=0/1] 9214 // (select cc -1, y) [AllOnes=1] 9215 // (select cc y, -1) [AllOnes=1] 9216 // 9217 // Invert is set when N is the null/all ones constant when CC is false. 9218 // OtherOp is set to the alternative value of N. 9219 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9220 SDValue &CC, bool &Invert, 9221 SDValue &OtherOp, 9222 SelectionDAG &DAG) { 9223 switch (N->getOpcode()) { 9224 default: return false; 9225 case ISD::SELECT: { 9226 CC = N->getOperand(0); 9227 SDValue N1 = N->getOperand(1); 9228 SDValue N2 = N->getOperand(2); 9229 if (isZeroOrAllOnes(N1, AllOnes)) { 9230 Invert = false; 9231 OtherOp = N2; 9232 return true; 9233 } 9234 if (isZeroOrAllOnes(N2, AllOnes)) { 9235 Invert = true; 9236 OtherOp = N1; 9237 return true; 9238 } 9239 return false; 9240 } 9241 case ISD::ZERO_EXTEND: 9242 // (zext cc) can never be the all ones value. 9243 if (AllOnes) 9244 return false; 9245 LLVM_FALLTHROUGH; 9246 case ISD::SIGN_EXTEND: { 9247 SDLoc dl(N); 9248 EVT VT = N->getValueType(0); 9249 CC = N->getOperand(0); 9250 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9251 return false; 9252 Invert = !AllOnes; 9253 if (AllOnes) 9254 // When looking for an AllOnes constant, N is an sext, and the 'other' 9255 // value is 0. 9256 OtherOp = DAG.getConstant(0, dl, VT); 9257 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9258 // When looking for a 0 constant, N can be zext or sext. 9259 OtherOp = DAG.getConstant(1, dl, VT); 9260 else 9261 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9262 VT); 9263 return true; 9264 } 9265 } 9266 } 9267 9268 // Combine a constant select operand into its use: 9269 // 9270 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9271 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9272 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9273 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9274 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9275 // 9276 // The transform is rejected if the select doesn't have a constant operand that 9277 // is null, or all ones when AllOnes is set. 9278 // 9279 // Also recognize sext/zext from i1: 9280 // 9281 // (add (zext cc), x) -> (select cc (add x, 1), x) 9282 // (add (sext cc), x) -> (select cc (add x, -1), x) 9283 // 9284 // These transformations eventually create predicated instructions. 9285 // 9286 // @param N The node to transform. 9287 // @param Slct The N operand that is a select. 9288 // @param OtherOp The other N operand (x above). 9289 // @param DCI Context. 9290 // @param AllOnes Require the select constant to be all ones instead of null. 9291 // @returns The new node, or SDValue() on failure. 9292 static 9293 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9294 TargetLowering::DAGCombinerInfo &DCI, 9295 bool AllOnes = false) { 9296 SelectionDAG &DAG = DCI.DAG; 9297 EVT VT = N->getValueType(0); 9298 SDValue NonConstantVal; 9299 SDValue CCOp; 9300 bool SwapSelectOps; 9301 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9302 NonConstantVal, DAG)) 9303 return SDValue(); 9304 9305 // Slct is now know to be the desired identity constant when CC is true. 9306 SDValue TrueVal = OtherOp; 9307 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9308 OtherOp, NonConstantVal); 9309 // Unless SwapSelectOps says CC should be false. 9310 if (SwapSelectOps) 9311 std::swap(TrueVal, FalseVal); 9312 9313 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9314 CCOp, TrueVal, FalseVal); 9315 } 9316 9317 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9318 static 9319 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9320 TargetLowering::DAGCombinerInfo &DCI) { 9321 SDValue N0 = N->getOperand(0); 9322 SDValue N1 = N->getOperand(1); 9323 if (N0.getNode()->hasOneUse()) 9324 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9325 return Result; 9326 if (N1.getNode()->hasOneUse()) 9327 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9328 return Result; 9329 return SDValue(); 9330 } 9331 9332 static bool IsVUZPShuffleNode(SDNode *N) { 9333 // VUZP shuffle node. 9334 if (N->getOpcode() == ARMISD::VUZP) 9335 return true; 9336 9337 // "VUZP" on i32 is an alias for VTRN. 9338 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9339 return true; 9340 9341 return false; 9342 } 9343 9344 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9345 TargetLowering::DAGCombinerInfo &DCI, 9346 const ARMSubtarget *Subtarget) { 9347 // Look for ADD(VUZP.0, VUZP.1). 9348 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9349 N0 == N1) 9350 return SDValue(); 9351 9352 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9353 if (!N->getValueType(0).is64BitVector()) 9354 return SDValue(); 9355 9356 // Generate vpadd. 9357 SelectionDAG &DAG = DCI.DAG; 9358 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9359 SDLoc dl(N); 9360 SDNode *Unzip = N0.getNode(); 9361 EVT VT = N->getValueType(0); 9362 9363 SmallVector<SDValue, 8> Ops; 9364 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9365 TLI.getPointerTy(DAG.getDataLayout()))); 9366 Ops.push_back(Unzip->getOperand(0)); 9367 Ops.push_back(Unzip->getOperand(1)); 9368 9369 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9370 } 9371 9372 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9373 TargetLowering::DAGCombinerInfo &DCI, 9374 const ARMSubtarget *Subtarget) { 9375 // Check for two extended operands. 9376 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9377 N1.getOpcode() == ISD::SIGN_EXTEND) && 9378 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9379 N1.getOpcode() == ISD::ZERO_EXTEND)) 9380 return SDValue(); 9381 9382 SDValue N00 = N0.getOperand(0); 9383 SDValue N10 = N1.getOperand(0); 9384 9385 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9386 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9387 N00 == N10) 9388 return SDValue(); 9389 9390 // We only recognize Q register paddl here; this can't be reached until 9391 // after type legalization. 9392 if (!N00.getValueType().is64BitVector() || 9393 !N0.getValueType().is128BitVector()) 9394 return SDValue(); 9395 9396 // Generate vpaddl. 9397 SelectionDAG &DAG = DCI.DAG; 9398 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9399 SDLoc dl(N); 9400 EVT VT = N->getValueType(0); 9401 9402 SmallVector<SDValue, 8> Ops; 9403 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9404 unsigned Opcode; 9405 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9406 Opcode = Intrinsic::arm_neon_vpaddls; 9407 else 9408 Opcode = Intrinsic::arm_neon_vpaddlu; 9409 Ops.push_back(DAG.getConstant(Opcode, dl, 9410 TLI.getPointerTy(DAG.getDataLayout()))); 9411 EVT ElemTy = N00.getValueType().getVectorElementType(); 9412 unsigned NumElts = VT.getVectorNumElements(); 9413 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9414 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9415 N00.getOperand(0), N00.getOperand(1)); 9416 Ops.push_back(Concat); 9417 9418 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9419 } 9420 9421 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9422 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9423 // much easier to match. 9424 static SDValue 9425 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9426 TargetLowering::DAGCombinerInfo &DCI, 9427 const ARMSubtarget *Subtarget) { 9428 // Only perform optimization if after legalize, and if NEON is available. We 9429 // also expected both operands to be BUILD_VECTORs. 9430 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9431 || N0.getOpcode() != ISD::BUILD_VECTOR 9432 || N1.getOpcode() != ISD::BUILD_VECTOR) 9433 return SDValue(); 9434 9435 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9436 EVT VT = N->getValueType(0); 9437 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9438 return SDValue(); 9439 9440 // Check that the vector operands are of the right form. 9441 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9442 // operands, where N is the size of the formed vector. 9443 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9444 // index such that we have a pair wise add pattern. 9445 9446 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9447 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9448 return SDValue(); 9449 SDValue Vec = N0->getOperand(0)->getOperand(0); 9450 SDNode *V = Vec.getNode(); 9451 unsigned nextIndex = 0; 9452 9453 // For each operands to the ADD which are BUILD_VECTORs, 9454 // check to see if each of their operands are an EXTRACT_VECTOR with 9455 // the same vector and appropriate index. 9456 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9457 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9458 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9459 9460 SDValue ExtVec0 = N0->getOperand(i); 9461 SDValue ExtVec1 = N1->getOperand(i); 9462 9463 // First operand is the vector, verify its the same. 9464 if (V != ExtVec0->getOperand(0).getNode() || 9465 V != ExtVec1->getOperand(0).getNode()) 9466 return SDValue(); 9467 9468 // Second is the constant, verify its correct. 9469 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9470 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9471 9472 // For the constant, we want to see all the even or all the odd. 9473 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9474 || C1->getZExtValue() != nextIndex+1) 9475 return SDValue(); 9476 9477 // Increment index. 9478 nextIndex+=2; 9479 } else 9480 return SDValue(); 9481 } 9482 9483 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. 9484 if (Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9485 return SDValue(); 9486 9487 // Create VPADDL node. 9488 SelectionDAG &DAG = DCI.DAG; 9489 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9490 9491 SDLoc dl(N); 9492 9493 // Build operand list. 9494 SmallVector<SDValue, 8> Ops; 9495 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9496 TLI.getPointerTy(DAG.getDataLayout()))); 9497 9498 // Input is the vector. 9499 Ops.push_back(Vec); 9500 9501 // Get widened type and narrowed type. 9502 MVT widenType; 9503 unsigned numElem = VT.getVectorNumElements(); 9504 9505 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9506 switch (inputLaneType.getSimpleVT().SimpleTy) { 9507 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9508 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9509 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9510 default: 9511 llvm_unreachable("Invalid vector element type for padd optimization."); 9512 } 9513 9514 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9515 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9516 return DAG.getNode(ExtOp, dl, VT, tmp); 9517 } 9518 9519 static SDValue findMUL_LOHI(SDValue V) { 9520 if (V->getOpcode() == ISD::UMUL_LOHI || 9521 V->getOpcode() == ISD::SMUL_LOHI) 9522 return V; 9523 return SDValue(); 9524 } 9525 9526 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9527 TargetLowering::DAGCombinerInfo &DCI, 9528 const ARMSubtarget *Subtarget) { 9529 9530 if (Subtarget->isThumb()) { 9531 if (!Subtarget->hasDSP()) 9532 return SDValue(); 9533 } else if (!Subtarget->hasV5TEOps()) 9534 return SDValue(); 9535 9536 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9537 // accumulates the product into a 64-bit value. The 16-bit values will 9538 // be sign extended somehow or SRA'd into 32-bit values 9539 // (addc (adde (mul 16bit, 16bit), lo), hi) 9540 SDValue Mul = AddcNode->getOperand(0); 9541 SDValue Lo = AddcNode->getOperand(1); 9542 if (Mul.getOpcode() != ISD::MUL) { 9543 Lo = AddcNode->getOperand(0); 9544 Mul = AddcNode->getOperand(1); 9545 if (Mul.getOpcode() != ISD::MUL) 9546 return SDValue(); 9547 } 9548 9549 SDValue SRA = AddeNode->getOperand(0); 9550 SDValue Hi = AddeNode->getOperand(1); 9551 if (SRA.getOpcode() != ISD::SRA) { 9552 SRA = AddeNode->getOperand(1); 9553 Hi = AddeNode->getOperand(0); 9554 if (SRA.getOpcode() != ISD::SRA) 9555 return SDValue(); 9556 } 9557 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 9558 if (Const->getZExtValue() != 31) 9559 return SDValue(); 9560 } else 9561 return SDValue(); 9562 9563 if (SRA.getOperand(0) != Mul) 9564 return SDValue(); 9565 9566 SelectionDAG &DAG = DCI.DAG; 9567 SDLoc dl(AddcNode); 9568 unsigned Opcode = 0; 9569 SDValue Op0; 9570 SDValue Op1; 9571 9572 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 9573 Opcode = ARMISD::SMLALBB; 9574 Op0 = Mul.getOperand(0); 9575 Op1 = Mul.getOperand(1); 9576 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 9577 Opcode = ARMISD::SMLALBT; 9578 Op0 = Mul.getOperand(0); 9579 Op1 = Mul.getOperand(1).getOperand(0); 9580 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 9581 Opcode = ARMISD::SMLALTB; 9582 Op0 = Mul.getOperand(0).getOperand(0); 9583 Op1 = Mul.getOperand(1); 9584 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 9585 Opcode = ARMISD::SMLALTT; 9586 Op0 = Mul->getOperand(0).getOperand(0); 9587 Op1 = Mul->getOperand(1).getOperand(0); 9588 } 9589 9590 if (!Op0 || !Op1) 9591 return SDValue(); 9592 9593 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 9594 Op0, Op1, Lo, Hi); 9595 // Replace the ADDs' nodes uses by the MLA node's values. 9596 SDValue HiMLALResult(SMLAL.getNode(), 1); 9597 SDValue LoMLALResult(SMLAL.getNode(), 0); 9598 9599 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9600 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9601 9602 // Return original node to notify the driver to stop replacing. 9603 SDValue resNode(AddcNode, 0); 9604 return resNode; 9605 } 9606 9607 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode, 9608 TargetLowering::DAGCombinerInfo &DCI, 9609 const ARMSubtarget *Subtarget) { 9610 // Look for multiply add opportunities. 9611 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9612 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9613 // a glue link from the first add to the second add. 9614 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9615 // a S/UMLAL instruction. 9616 // UMUL_LOHI 9617 // / :lo \ :hi 9618 // / \ [no multiline comment] 9619 // loAdd -> ADDE | 9620 // \ :glue / 9621 // \ / 9622 // ADDC <- hiAdd 9623 // 9624 assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE"); 9625 9626 assert(AddeNode->getNumOperands() == 3 && 9627 AddeNode->getOperand(2).getValueType() == MVT::i32 && 9628 "ADDE node has the wrong inputs"); 9629 9630 // Check that we have a glued ADDC node. 9631 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9632 if (AddcNode->getOpcode() != ARMISD::ADDC) 9633 return SDValue(); 9634 9635 SDValue AddcOp0 = AddcNode->getOperand(0); 9636 SDValue AddcOp1 = AddcNode->getOperand(1); 9637 9638 // Check if the two operands are from the same mul_lohi node. 9639 if (AddcOp0.getNode() == AddcOp1.getNode()) 9640 return SDValue(); 9641 9642 assert(AddcNode->getNumValues() == 2 && 9643 AddcNode->getValueType(0) == MVT::i32 && 9644 "Expect ADDC with two result values. First: i32"); 9645 9646 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 9647 // maybe a SMLAL which multiplies two 16-bit values. 9648 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9649 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9650 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9651 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9652 return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget); 9653 9654 // Check for the triangle shape. 9655 SDValue AddeOp0 = AddeNode->getOperand(0); 9656 SDValue AddeOp1 = AddeNode->getOperand(1); 9657 9658 // Make sure that the ADDE operands are not coming from the same node. 9659 if (AddeOp0.getNode() == AddeOp1.getNode()) 9660 return SDValue(); 9661 9662 // Find the MUL_LOHI node walking up ADDE's operands. 9663 bool IsLeftOperandMUL = false; 9664 SDValue MULOp = findMUL_LOHI(AddeOp0); 9665 if (MULOp == SDValue()) 9666 MULOp = findMUL_LOHI(AddeOp1); 9667 else 9668 IsLeftOperandMUL = true; 9669 if (MULOp == SDValue()) 9670 return SDValue(); 9671 9672 // Figure out the right opcode. 9673 unsigned Opc = MULOp->getOpcode(); 9674 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9675 9676 // Figure out the high and low input values to the MLAL node. 9677 SDValue* HiAdd = nullptr; 9678 SDValue* LoMul = nullptr; 9679 SDValue* LowAdd = nullptr; 9680 9681 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 9682 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9683 return SDValue(); 9684 9685 if (IsLeftOperandMUL) 9686 HiAdd = &AddeOp1; 9687 else 9688 HiAdd = &AddeOp0; 9689 9690 9691 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9692 // whose low result is fed to the ADDC we are checking. 9693 9694 if (AddcOp0 == MULOp.getValue(0)) { 9695 LoMul = &AddcOp0; 9696 LowAdd = &AddcOp1; 9697 } 9698 if (AddcOp1 == MULOp.getValue(0)) { 9699 LoMul = &AddcOp1; 9700 LowAdd = &AddcOp0; 9701 } 9702 9703 if (!LoMul) 9704 return SDValue(); 9705 9706 // Create the merged node. 9707 SelectionDAG &DAG = DCI.DAG; 9708 9709 // Build operand list. 9710 SmallVector<SDValue, 8> Ops; 9711 Ops.push_back(LoMul->getOperand(0)); 9712 Ops.push_back(LoMul->getOperand(1)); 9713 Ops.push_back(*LowAdd); 9714 Ops.push_back(*HiAdd); 9715 9716 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9717 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9718 9719 // Replace the ADDs' nodes uses by the MLA node's values. 9720 SDValue HiMLALResult(MLALNode.getNode(), 1); 9721 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9722 9723 SDValue LoMLALResult(MLALNode.getNode(), 0); 9724 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9725 9726 // Return original node to notify the driver to stop replacing. 9727 return SDValue(AddeNode, 0); 9728 } 9729 9730 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 9731 TargetLowering::DAGCombinerInfo &DCI, 9732 const ARMSubtarget *Subtarget) { 9733 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9734 // While trying to combine for the other MLAL nodes, first search for the 9735 // chance to use UMAAL. Check if Addc uses a node which has already 9736 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 9737 // as the addend, and it's handled in PerformUMLALCombine. 9738 9739 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9740 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9741 9742 // Check that we have a glued ADDC node. 9743 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9744 if (AddcNode->getOpcode() != ARMISD::ADDC) 9745 return SDValue(); 9746 9747 // Find the converted UMAAL or quit if it doesn't exist. 9748 SDNode *UmlalNode = nullptr; 9749 SDValue AddHi; 9750 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9751 UmlalNode = AddcNode->getOperand(0).getNode(); 9752 AddHi = AddcNode->getOperand(1); 9753 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9754 UmlalNode = AddcNode->getOperand(1).getNode(); 9755 AddHi = AddcNode->getOperand(0); 9756 } else { 9757 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9758 } 9759 9760 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9761 // the ADDC as well as Zero. 9762 if (!isNullConstant(UmlalNode->getOperand(3))) 9763 return SDValue(); 9764 9765 if ((isNullConstant(AddeNode->getOperand(0)) && 9766 AddeNode->getOperand(1).getNode() == UmlalNode) || 9767 (AddeNode->getOperand(0).getNode() == UmlalNode && 9768 isNullConstant(AddeNode->getOperand(1)))) { 9769 9770 SelectionDAG &DAG = DCI.DAG; 9771 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9772 UmlalNode->getOperand(2), AddHi }; 9773 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9774 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9775 9776 // Replace the ADDs' nodes uses by the UMAAL node's values. 9777 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9778 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9779 9780 // Return original node to notify the driver to stop replacing. 9781 return SDValue(AddeNode, 0); 9782 } 9783 return SDValue(); 9784 } 9785 9786 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 9787 const ARMSubtarget *Subtarget) { 9788 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9789 return SDValue(); 9790 9791 // Check that we have a pair of ADDC and ADDE as operands. 9792 // Both addends of the ADDE must be zero. 9793 SDNode* AddcNode = N->getOperand(2).getNode(); 9794 SDNode* AddeNode = N->getOperand(3).getNode(); 9795 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 9796 (AddeNode->getOpcode() == ARMISD::ADDE) && 9797 isNullConstant(AddeNode->getOperand(0)) && 9798 isNullConstant(AddeNode->getOperand(1)) && 9799 (AddeNode->getOperand(2).getNode() == AddcNode)) 9800 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 9801 DAG.getVTList(MVT::i32, MVT::i32), 9802 {N->getOperand(0), N->getOperand(1), 9803 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 9804 else 9805 return SDValue(); 9806 } 9807 9808 static SDValue PerformAddcSubcCombine(SDNode *N, SelectionDAG &DAG, 9809 const ARMSubtarget *Subtarget) { 9810 if (Subtarget->isThumb1Only()) { 9811 SDValue RHS = N->getOperand(1); 9812 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 9813 int32_t imm = C->getSExtValue(); 9814 if (imm < 0 && imm > INT_MIN) { 9815 SDLoc DL(N); 9816 RHS = DAG.getConstant(-imm, DL, MVT::i32); 9817 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 9818 : ARMISD::ADDC; 9819 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 9820 } 9821 } 9822 } 9823 return SDValue(); 9824 } 9825 9826 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG, 9827 const ARMSubtarget *Subtarget) { 9828 if (Subtarget->isThumb1Only()) { 9829 SDValue RHS = N->getOperand(1); 9830 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 9831 int64_t imm = C->getSExtValue(); 9832 if (imm < 0) { 9833 SDLoc DL(N); 9834 9835 // The with-carry-in form matches bitwise not instead of the negation. 9836 // Effectively, the inverse interpretation of the carry flag already 9837 // accounts for part of the negation. 9838 RHS = DAG.getConstant(~imm, DL, MVT::i32); 9839 9840 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 9841 : ARMISD::ADDE; 9842 return DAG.getNode(Opcode, DL, N->getVTList(), 9843 N->getOperand(0), RHS, N->getOperand(2)); 9844 } 9845 } 9846 } 9847 return SDValue(); 9848 } 9849 9850 /// PerformADDECombine - Target-specific dag combine transform from 9851 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 9852 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 9853 static SDValue PerformADDECombine(SDNode *N, 9854 TargetLowering::DAGCombinerInfo &DCI, 9855 const ARMSubtarget *Subtarget) { 9856 // Only ARM and Thumb2 support UMLAL/SMLAL. 9857 if (Subtarget->isThumb1Only()) 9858 return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 9859 9860 // Only perform the checks after legalize when the pattern is available. 9861 if (DCI.isBeforeLegalize()) return SDValue(); 9862 9863 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 9864 } 9865 9866 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 9867 /// operands N0 and N1. This is a helper for PerformADDCombine that is 9868 /// called with the default operands, and if that fails, with commuted 9869 /// operands. 9870 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 9871 TargetLowering::DAGCombinerInfo &DCI, 9872 const ARMSubtarget *Subtarget){ 9873 // Attempt to create vpadd for this add. 9874 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 9875 return Result; 9876 9877 // Attempt to create vpaddl for this add. 9878 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 9879 return Result; 9880 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 9881 Subtarget)) 9882 return Result; 9883 9884 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9885 if (N0.getNode()->hasOneUse()) 9886 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 9887 return Result; 9888 return SDValue(); 9889 } 9890 9891 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 9892 /// 9893 static SDValue PerformADDCombine(SDNode *N, 9894 TargetLowering::DAGCombinerInfo &DCI, 9895 const ARMSubtarget *Subtarget) { 9896 SDValue N0 = N->getOperand(0); 9897 SDValue N1 = N->getOperand(1); 9898 9899 // First try with the default operand order. 9900 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 9901 return Result; 9902 9903 // If that didn't work, try again with the operands commuted. 9904 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 9905 } 9906 9907 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 9908 /// 9909 static SDValue PerformSUBCombine(SDNode *N, 9910 TargetLowering::DAGCombinerInfo &DCI) { 9911 SDValue N0 = N->getOperand(0); 9912 SDValue N1 = N->getOperand(1); 9913 9914 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9915 if (N1.getNode()->hasOneUse()) 9916 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 9917 return Result; 9918 9919 return SDValue(); 9920 } 9921 9922 /// PerformVMULCombine 9923 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 9924 /// special multiplier accumulator forwarding. 9925 /// vmul d3, d0, d2 9926 /// vmla d3, d1, d2 9927 /// is faster than 9928 /// vadd d3, d0, d1 9929 /// vmul d3, d3, d2 9930 // However, for (A + B) * (A + B), 9931 // vadd d2, d0, d1 9932 // vmul d3, d0, d2 9933 // vmla d3, d1, d2 9934 // is slower than 9935 // vadd d2, d0, d1 9936 // vmul d3, d2, d2 9937 static SDValue PerformVMULCombine(SDNode *N, 9938 TargetLowering::DAGCombinerInfo &DCI, 9939 const ARMSubtarget *Subtarget) { 9940 if (!Subtarget->hasVMLxForwarding()) 9941 return SDValue(); 9942 9943 SelectionDAG &DAG = DCI.DAG; 9944 SDValue N0 = N->getOperand(0); 9945 SDValue N1 = N->getOperand(1); 9946 unsigned Opcode = N0.getOpcode(); 9947 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9948 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 9949 Opcode = N1.getOpcode(); 9950 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9951 Opcode != ISD::FADD && Opcode != ISD::FSUB) 9952 return SDValue(); 9953 std::swap(N0, N1); 9954 } 9955 9956 if (N0 == N1) 9957 return SDValue(); 9958 9959 EVT VT = N->getValueType(0); 9960 SDLoc DL(N); 9961 SDValue N00 = N0->getOperand(0); 9962 SDValue N01 = N0->getOperand(1); 9963 return DAG.getNode(Opcode, DL, VT, 9964 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 9965 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 9966 } 9967 9968 static SDValue PerformMULCombine(SDNode *N, 9969 TargetLowering::DAGCombinerInfo &DCI, 9970 const ARMSubtarget *Subtarget) { 9971 SelectionDAG &DAG = DCI.DAG; 9972 9973 if (Subtarget->isThumb1Only()) 9974 return SDValue(); 9975 9976 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9977 return SDValue(); 9978 9979 EVT VT = N->getValueType(0); 9980 if (VT.is64BitVector() || VT.is128BitVector()) 9981 return PerformVMULCombine(N, DCI, Subtarget); 9982 if (VT != MVT::i32) 9983 return SDValue(); 9984 9985 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9986 if (!C) 9987 return SDValue(); 9988 9989 int64_t MulAmt = C->getSExtValue(); 9990 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 9991 9992 ShiftAmt = ShiftAmt & (32 - 1); 9993 SDValue V = N->getOperand(0); 9994 SDLoc DL(N); 9995 9996 SDValue Res; 9997 MulAmt >>= ShiftAmt; 9998 9999 if (MulAmt >= 0) { 10000 if (isPowerOf2_32(MulAmt - 1)) { 10001 // (mul x, 2^N + 1) => (add (shl x, N), x) 10002 Res = DAG.getNode(ISD::ADD, DL, VT, 10003 V, 10004 DAG.getNode(ISD::SHL, DL, VT, 10005 V, 10006 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10007 MVT::i32))); 10008 } else if (isPowerOf2_32(MulAmt + 1)) { 10009 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10010 Res = DAG.getNode(ISD::SUB, DL, VT, 10011 DAG.getNode(ISD::SHL, DL, VT, 10012 V, 10013 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10014 MVT::i32)), 10015 V); 10016 } else 10017 return SDValue(); 10018 } else { 10019 uint64_t MulAmtAbs = -MulAmt; 10020 if (isPowerOf2_32(MulAmtAbs + 1)) { 10021 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10022 Res = DAG.getNode(ISD::SUB, DL, VT, 10023 V, 10024 DAG.getNode(ISD::SHL, DL, VT, 10025 V, 10026 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10027 MVT::i32))); 10028 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10029 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10030 Res = DAG.getNode(ISD::ADD, DL, VT, 10031 V, 10032 DAG.getNode(ISD::SHL, DL, VT, 10033 V, 10034 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10035 MVT::i32))); 10036 Res = DAG.getNode(ISD::SUB, DL, VT, 10037 DAG.getConstant(0, DL, MVT::i32), Res); 10038 10039 } else 10040 return SDValue(); 10041 } 10042 10043 if (ShiftAmt != 0) 10044 Res = DAG.getNode(ISD::SHL, DL, VT, 10045 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10046 10047 // Do not add new nodes to DAG combiner worklist. 10048 DCI.CombineTo(N, Res, false); 10049 return SDValue(); 10050 } 10051 10052 static SDValue PerformANDCombine(SDNode *N, 10053 TargetLowering::DAGCombinerInfo &DCI, 10054 const ARMSubtarget *Subtarget) { 10055 // Attempt to use immediate-form VBIC 10056 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10057 SDLoc dl(N); 10058 EVT VT = N->getValueType(0); 10059 SelectionDAG &DAG = DCI.DAG; 10060 10061 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10062 return SDValue(); 10063 10064 APInt SplatBits, SplatUndef; 10065 unsigned SplatBitSize; 10066 bool HasAnyUndefs; 10067 if (BVN && 10068 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10069 if (SplatBitSize <= 64) { 10070 EVT VbicVT; 10071 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10072 SplatUndef.getZExtValue(), SplatBitSize, 10073 DAG, dl, VbicVT, VT.is128BitVector(), 10074 OtherModImm); 10075 if (Val.getNode()) { 10076 SDValue Input = 10077 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10078 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10079 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10080 } 10081 } 10082 } 10083 10084 if (!Subtarget->isThumb1Only()) { 10085 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10086 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10087 return Result; 10088 } 10089 10090 return SDValue(); 10091 } 10092 10093 // Try combining OR nodes to SMULWB, SMULWT. 10094 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10095 TargetLowering::DAGCombinerInfo &DCI, 10096 const ARMSubtarget *Subtarget) { 10097 if (!Subtarget->hasV6Ops() || 10098 (Subtarget->isThumb() && 10099 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10100 return SDValue(); 10101 10102 SDValue SRL = OR->getOperand(0); 10103 SDValue SHL = OR->getOperand(1); 10104 10105 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10106 SRL = OR->getOperand(1); 10107 SHL = OR->getOperand(0); 10108 } 10109 if (!isSRL16(SRL) || !isSHL16(SHL)) 10110 return SDValue(); 10111 10112 // The first operands to the shifts need to be the two results from the 10113 // same smul_lohi node. 10114 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10115 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10116 return SDValue(); 10117 10118 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10119 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10120 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10121 return SDValue(); 10122 10123 // Now we have: 10124 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10125 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10126 // For SMUWB the 16-bit value will signed extended somehow. 10127 // For SMULWT only the SRA is required. 10128 // Check both sides of SMUL_LOHI 10129 SDValue OpS16 = SMULLOHI->getOperand(0); 10130 SDValue OpS32 = SMULLOHI->getOperand(1); 10131 10132 SelectionDAG &DAG = DCI.DAG; 10133 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10134 OpS16 = OpS32; 10135 OpS32 = SMULLOHI->getOperand(0); 10136 } 10137 10138 SDLoc dl(OR); 10139 unsigned Opcode = 0; 10140 if (isS16(OpS16, DAG)) 10141 Opcode = ARMISD::SMULWB; 10142 else if (isSRA16(OpS16)) { 10143 Opcode = ARMISD::SMULWT; 10144 OpS16 = OpS16->getOperand(0); 10145 } 10146 else 10147 return SDValue(); 10148 10149 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10150 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10151 return SDValue(OR, 0); 10152 } 10153 10154 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10155 static SDValue PerformORCombine(SDNode *N, 10156 TargetLowering::DAGCombinerInfo &DCI, 10157 const ARMSubtarget *Subtarget) { 10158 // Attempt to use immediate-form VORR 10159 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10160 SDLoc dl(N); 10161 EVT VT = N->getValueType(0); 10162 SelectionDAG &DAG = DCI.DAG; 10163 10164 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10165 return SDValue(); 10166 10167 APInt SplatBits, SplatUndef; 10168 unsigned SplatBitSize; 10169 bool HasAnyUndefs; 10170 if (BVN && Subtarget->hasNEON() && 10171 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10172 if (SplatBitSize <= 64) { 10173 EVT VorrVT; 10174 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10175 SplatUndef.getZExtValue(), SplatBitSize, 10176 DAG, dl, VorrVT, VT.is128BitVector(), 10177 OtherModImm); 10178 if (Val.getNode()) { 10179 SDValue Input = 10180 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10181 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10182 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10183 } 10184 } 10185 } 10186 10187 if (!Subtarget->isThumb1Only()) { 10188 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10189 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10190 return Result; 10191 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10192 return Result; 10193 } 10194 10195 // The code below optimizes (or (and X, Y), Z). 10196 // The AND operand needs to have a single user to make these optimizations 10197 // profitable. 10198 SDValue N0 = N->getOperand(0); 10199 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10200 return SDValue(); 10201 SDValue N1 = N->getOperand(1); 10202 10203 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10204 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10205 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10206 APInt SplatUndef; 10207 unsigned SplatBitSize; 10208 bool HasAnyUndefs; 10209 10210 APInt SplatBits0, SplatBits1; 10211 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 10212 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 10213 // Ensure that the second operand of both ands are constants 10214 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 10215 HasAnyUndefs) && !HasAnyUndefs) { 10216 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 10217 HasAnyUndefs) && !HasAnyUndefs) { 10218 // Ensure that the bit width of the constants are the same and that 10219 // the splat arguments are logical inverses as per the pattern we 10220 // are trying to simplify. 10221 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 10222 SplatBits0 == ~SplatBits1) { 10223 // Canonicalize the vector type to make instruction selection 10224 // simpler. 10225 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 10226 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 10227 N0->getOperand(1), 10228 N0->getOperand(0), 10229 N1->getOperand(0)); 10230 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 10231 } 10232 } 10233 } 10234 } 10235 10236 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 10237 // reasonable. 10238 10239 // BFI is only available on V6T2+ 10240 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10241 return SDValue(); 10242 10243 SDLoc DL(N); 10244 // 1) or (and A, mask), val => ARMbfi A, val, mask 10245 // iff (val & mask) == val 10246 // 10247 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10248 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10249 // && mask == ~mask2 10250 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10251 // && ~mask == mask2 10252 // (i.e., copy a bitfield value into another bitfield of the same width) 10253 10254 if (VT != MVT::i32) 10255 return SDValue(); 10256 10257 SDValue N00 = N0.getOperand(0); 10258 10259 // The value and the mask need to be constants so we can verify this is 10260 // actually a bitfield set. If the mask is 0xffff, we can do better 10261 // via a movt instruction, so don't use BFI in that case. 10262 SDValue MaskOp = N0.getOperand(1); 10263 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10264 if (!MaskC) 10265 return SDValue(); 10266 unsigned Mask = MaskC->getZExtValue(); 10267 if (Mask == 0xffff) 10268 return SDValue(); 10269 SDValue Res; 10270 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10271 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10272 if (N1C) { 10273 unsigned Val = N1C->getZExtValue(); 10274 if ((Val & ~Mask) != Val) 10275 return SDValue(); 10276 10277 if (ARM::isBitFieldInvertedMask(Mask)) { 10278 Val >>= countTrailingZeros(~Mask); 10279 10280 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10281 DAG.getConstant(Val, DL, MVT::i32), 10282 DAG.getConstant(Mask, DL, MVT::i32)); 10283 10284 // Do not add new nodes to DAG combiner worklist. 10285 DCI.CombineTo(N, Res, false); 10286 return SDValue(); 10287 } 10288 } else if (N1.getOpcode() == ISD::AND) { 10289 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10290 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10291 if (!N11C) 10292 return SDValue(); 10293 unsigned Mask2 = N11C->getZExtValue(); 10294 10295 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10296 // as is to match. 10297 if (ARM::isBitFieldInvertedMask(Mask) && 10298 (Mask == ~Mask2)) { 10299 // The pack halfword instruction works better for masks that fit it, 10300 // so use that when it's available. 10301 if (Subtarget->hasDSP() && 10302 (Mask == 0xffff || Mask == 0xffff0000)) 10303 return SDValue(); 10304 // 2a 10305 unsigned amt = countTrailingZeros(Mask2); 10306 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10307 DAG.getConstant(amt, DL, MVT::i32)); 10308 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10309 DAG.getConstant(Mask, DL, MVT::i32)); 10310 // Do not add new nodes to DAG combiner worklist. 10311 DCI.CombineTo(N, Res, false); 10312 return SDValue(); 10313 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10314 (~Mask == Mask2)) { 10315 // The pack halfword instruction works better for masks that fit it, 10316 // so use that when it's available. 10317 if (Subtarget->hasDSP() && 10318 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10319 return SDValue(); 10320 // 2b 10321 unsigned lsb = countTrailingZeros(Mask); 10322 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10323 DAG.getConstant(lsb, DL, MVT::i32)); 10324 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10325 DAG.getConstant(Mask2, DL, MVT::i32)); 10326 // Do not add new nodes to DAG combiner worklist. 10327 DCI.CombineTo(N, Res, false); 10328 return SDValue(); 10329 } 10330 } 10331 10332 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10333 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10334 ARM::isBitFieldInvertedMask(~Mask)) { 10335 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10336 // where lsb(mask) == #shamt and masked bits of B are known zero. 10337 SDValue ShAmt = N00.getOperand(1); 10338 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10339 unsigned LSB = countTrailingZeros(Mask); 10340 if (ShAmtC != LSB) 10341 return SDValue(); 10342 10343 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10344 DAG.getConstant(~Mask, DL, MVT::i32)); 10345 10346 // Do not add new nodes to DAG combiner worklist. 10347 DCI.CombineTo(N, Res, false); 10348 } 10349 10350 return SDValue(); 10351 } 10352 10353 static SDValue PerformXORCombine(SDNode *N, 10354 TargetLowering::DAGCombinerInfo &DCI, 10355 const ARMSubtarget *Subtarget) { 10356 EVT VT = N->getValueType(0); 10357 SelectionDAG &DAG = DCI.DAG; 10358 10359 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10360 return SDValue(); 10361 10362 if (!Subtarget->isThumb1Only()) { 10363 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10364 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10365 return Result; 10366 } 10367 10368 return SDValue(); 10369 } 10370 10371 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 10372 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 10373 // their position in "to" (Rd). 10374 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 10375 assert(N->getOpcode() == ARMISD::BFI); 10376 10377 SDValue From = N->getOperand(1); 10378 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 10379 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 10380 10381 // If the Base came from a SHR #C, we can deduce that it is really testing bit 10382 // #C in the base of the SHR. 10383 if (From->getOpcode() == ISD::SRL && 10384 isa<ConstantSDNode>(From->getOperand(1))) { 10385 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 10386 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 10387 FromMask <<= Shift.getLimitedValue(31); 10388 From = From->getOperand(0); 10389 } 10390 10391 return From; 10392 } 10393 10394 // If A and B contain one contiguous set of bits, does A | B == A . B? 10395 // 10396 // Neither A nor B must be zero. 10397 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 10398 unsigned LastActiveBitInA = A.countTrailingZeros(); 10399 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 10400 return LastActiveBitInA - 1 == FirstActiveBitInB; 10401 } 10402 10403 static SDValue FindBFIToCombineWith(SDNode *N) { 10404 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 10405 // if one exists. 10406 APInt ToMask, FromMask; 10407 SDValue From = ParseBFI(N, ToMask, FromMask); 10408 SDValue To = N->getOperand(0); 10409 10410 // Now check for a compatible BFI to merge with. We can pass through BFIs that 10411 // aren't compatible, but not if they set the same bit in their destination as 10412 // we do (or that of any BFI we're going to combine with). 10413 SDValue V = To; 10414 APInt CombinedToMask = ToMask; 10415 while (V.getOpcode() == ARMISD::BFI) { 10416 APInt NewToMask, NewFromMask; 10417 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 10418 if (NewFrom != From) { 10419 // This BFI has a different base. Keep going. 10420 CombinedToMask |= NewToMask; 10421 V = V.getOperand(0); 10422 continue; 10423 } 10424 10425 // Do the written bits conflict with any we've seen so far? 10426 if ((NewToMask & CombinedToMask).getBoolValue()) 10427 // Conflicting bits - bail out because going further is unsafe. 10428 return SDValue(); 10429 10430 // Are the new bits contiguous when combined with the old bits? 10431 if (BitsProperlyConcatenate(ToMask, NewToMask) && 10432 BitsProperlyConcatenate(FromMask, NewFromMask)) 10433 return V; 10434 if (BitsProperlyConcatenate(NewToMask, ToMask) && 10435 BitsProperlyConcatenate(NewFromMask, FromMask)) 10436 return V; 10437 10438 // We've seen a write to some bits, so track it. 10439 CombinedToMask |= NewToMask; 10440 // Keep going... 10441 V = V.getOperand(0); 10442 } 10443 10444 return SDValue(); 10445 } 10446 10447 static SDValue PerformBFICombine(SDNode *N, 10448 TargetLowering::DAGCombinerInfo &DCI) { 10449 SDValue N1 = N->getOperand(1); 10450 if (N1.getOpcode() == ISD::AND) { 10451 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 10452 // the bits being cleared by the AND are not demanded by the BFI. 10453 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10454 if (!N11C) 10455 return SDValue(); 10456 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10457 unsigned LSB = countTrailingZeros(~InvMask); 10458 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 10459 assert(Width < 10460 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 10461 "undefined behavior"); 10462 unsigned Mask = (1u << Width) - 1; 10463 unsigned Mask2 = N11C->getZExtValue(); 10464 if ((Mask & (~Mask2)) == 0) 10465 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 10466 N->getOperand(0), N1.getOperand(0), 10467 N->getOperand(2)); 10468 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 10469 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 10470 // Keep track of any consecutive bits set that all come from the same base 10471 // value. We can combine these together into a single BFI. 10472 SDValue CombineBFI = FindBFIToCombineWith(N); 10473 if (CombineBFI == SDValue()) 10474 return SDValue(); 10475 10476 // We've found a BFI. 10477 APInt ToMask1, FromMask1; 10478 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 10479 10480 APInt ToMask2, FromMask2; 10481 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 10482 assert(From1 == From2); 10483 (void)From2; 10484 10485 // First, unlink CombineBFI. 10486 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 10487 // Then create a new BFI, combining the two together. 10488 APInt NewFromMask = FromMask1 | FromMask2; 10489 APInt NewToMask = ToMask1 | ToMask2; 10490 10491 EVT VT = N->getValueType(0); 10492 SDLoc dl(N); 10493 10494 if (NewFromMask[0] == 0) 10495 From1 = DCI.DAG.getNode( 10496 ISD::SRL, dl, VT, From1, 10497 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 10498 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 10499 DCI.DAG.getConstant(~NewToMask, dl, VT)); 10500 } 10501 return SDValue(); 10502 } 10503 10504 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 10505 /// ARMISD::VMOVRRD. 10506 static SDValue PerformVMOVRRDCombine(SDNode *N, 10507 TargetLowering::DAGCombinerInfo &DCI, 10508 const ARMSubtarget *Subtarget) { 10509 // vmovrrd(vmovdrr x, y) -> x,y 10510 SDValue InDouble = N->getOperand(0); 10511 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 10512 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 10513 10514 // vmovrrd(load f64) -> (load i32), (load i32) 10515 SDNode *InNode = InDouble.getNode(); 10516 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 10517 InNode->getValueType(0) == MVT::f64 && 10518 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 10519 !cast<LoadSDNode>(InNode)->isVolatile()) { 10520 // TODO: Should this be done for non-FrameIndex operands? 10521 LoadSDNode *LD = cast<LoadSDNode>(InNode); 10522 10523 SelectionDAG &DAG = DCI.DAG; 10524 SDLoc DL(LD); 10525 SDValue BasePtr = LD->getBasePtr(); 10526 SDValue NewLD1 = 10527 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 10528 LD->getAlignment(), LD->getMemOperand()->getFlags()); 10529 10530 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10531 DAG.getConstant(4, DL, MVT::i32)); 10532 SDValue NewLD2 = DAG.getLoad( 10533 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 10534 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 10535 10536 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 10537 if (DCI.DAG.getDataLayout().isBigEndian()) 10538 std::swap (NewLD1, NewLD2); 10539 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 10540 return Result; 10541 } 10542 10543 return SDValue(); 10544 } 10545 10546 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 10547 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 10548 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 10549 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 10550 SDValue Op0 = N->getOperand(0); 10551 SDValue Op1 = N->getOperand(1); 10552 if (Op0.getOpcode() == ISD::BITCAST) 10553 Op0 = Op0.getOperand(0); 10554 if (Op1.getOpcode() == ISD::BITCAST) 10555 Op1 = Op1.getOperand(0); 10556 if (Op0.getOpcode() == ARMISD::VMOVRRD && 10557 Op0.getNode() == Op1.getNode() && 10558 Op0.getResNo() == 0 && Op1.getResNo() == 1) 10559 return DAG.getNode(ISD::BITCAST, SDLoc(N), 10560 N->getValueType(0), Op0.getOperand(0)); 10561 return SDValue(); 10562 } 10563 10564 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 10565 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 10566 /// i64 vector to have f64 elements, since the value can then be loaded 10567 /// directly into a VFP register. 10568 static bool hasNormalLoadOperand(SDNode *N) { 10569 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 10570 for (unsigned i = 0; i < NumElts; ++i) { 10571 SDNode *Elt = N->getOperand(i).getNode(); 10572 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 10573 return true; 10574 } 10575 return false; 10576 } 10577 10578 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 10579 /// ISD::BUILD_VECTOR. 10580 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 10581 TargetLowering::DAGCombinerInfo &DCI, 10582 const ARMSubtarget *Subtarget) { 10583 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 10584 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 10585 // into a pair of GPRs, which is fine when the value is used as a scalar, 10586 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 10587 SelectionDAG &DAG = DCI.DAG; 10588 if (N->getNumOperands() == 2) 10589 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 10590 return RV; 10591 10592 // Load i64 elements as f64 values so that type legalization does not split 10593 // them up into i32 values. 10594 EVT VT = N->getValueType(0); 10595 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 10596 return SDValue(); 10597 SDLoc dl(N); 10598 SmallVector<SDValue, 8> Ops; 10599 unsigned NumElts = VT.getVectorNumElements(); 10600 for (unsigned i = 0; i < NumElts; ++i) { 10601 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 10602 Ops.push_back(V); 10603 // Make the DAGCombiner fold the bitcast. 10604 DCI.AddToWorklist(V.getNode()); 10605 } 10606 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 10607 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 10608 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10609 } 10610 10611 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 10612 static SDValue 10613 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10614 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 10615 // At that time, we may have inserted bitcasts from integer to float. 10616 // If these bitcasts have survived DAGCombine, change the lowering of this 10617 // BUILD_VECTOR in something more vector friendly, i.e., that does not 10618 // force to use floating point types. 10619 10620 // Make sure we can change the type of the vector. 10621 // This is possible iff: 10622 // 1. The vector is only used in a bitcast to a integer type. I.e., 10623 // 1.1. Vector is used only once. 10624 // 1.2. Use is a bit convert to an integer type. 10625 // 2. The size of its operands are 32-bits (64-bits are not legal). 10626 EVT VT = N->getValueType(0); 10627 EVT EltVT = VT.getVectorElementType(); 10628 10629 // Check 1.1. and 2. 10630 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 10631 return SDValue(); 10632 10633 // By construction, the input type must be float. 10634 assert(EltVT == MVT::f32 && "Unexpected type!"); 10635 10636 // Check 1.2. 10637 SDNode *Use = *N->use_begin(); 10638 if (Use->getOpcode() != ISD::BITCAST || 10639 Use->getValueType(0).isFloatingPoint()) 10640 return SDValue(); 10641 10642 // Check profitability. 10643 // Model is, if more than half of the relevant operands are bitcast from 10644 // i32, turn the build_vector into a sequence of insert_vector_elt. 10645 // Relevant operands are everything that is not statically 10646 // (i.e., at compile time) bitcasted. 10647 unsigned NumOfBitCastedElts = 0; 10648 unsigned NumElts = VT.getVectorNumElements(); 10649 unsigned NumOfRelevantElts = NumElts; 10650 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 10651 SDValue Elt = N->getOperand(Idx); 10652 if (Elt->getOpcode() == ISD::BITCAST) { 10653 // Assume only bit cast to i32 will go away. 10654 if (Elt->getOperand(0).getValueType() == MVT::i32) 10655 ++NumOfBitCastedElts; 10656 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 10657 // Constants are statically casted, thus do not count them as 10658 // relevant operands. 10659 --NumOfRelevantElts; 10660 } 10661 10662 // Check if more than half of the elements require a non-free bitcast. 10663 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 10664 return SDValue(); 10665 10666 SelectionDAG &DAG = DCI.DAG; 10667 // Create the new vector type. 10668 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 10669 // Check if the type is legal. 10670 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10671 if (!TLI.isTypeLegal(VecVT)) 10672 return SDValue(); 10673 10674 // Combine: 10675 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 10676 // => BITCAST INSERT_VECTOR_ELT 10677 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 10678 // (BITCAST EN), N. 10679 SDValue Vec = DAG.getUNDEF(VecVT); 10680 SDLoc dl(N); 10681 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 10682 SDValue V = N->getOperand(Idx); 10683 if (V.isUndef()) 10684 continue; 10685 if (V.getOpcode() == ISD::BITCAST && 10686 V->getOperand(0).getValueType() == MVT::i32) 10687 // Fold obvious case. 10688 V = V.getOperand(0); 10689 else { 10690 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 10691 // Make the DAGCombiner fold the bitcasts. 10692 DCI.AddToWorklist(V.getNode()); 10693 } 10694 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 10695 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 10696 } 10697 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 10698 // Make the DAGCombiner fold the bitcasts. 10699 DCI.AddToWorklist(Vec.getNode()); 10700 return Vec; 10701 } 10702 10703 /// PerformInsertEltCombine - Target-specific dag combine xforms for 10704 /// ISD::INSERT_VECTOR_ELT. 10705 static SDValue PerformInsertEltCombine(SDNode *N, 10706 TargetLowering::DAGCombinerInfo &DCI) { 10707 // Bitcast an i64 load inserted into a vector to f64. 10708 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10709 EVT VT = N->getValueType(0); 10710 SDNode *Elt = N->getOperand(1).getNode(); 10711 if (VT.getVectorElementType() != MVT::i64 || 10712 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 10713 return SDValue(); 10714 10715 SelectionDAG &DAG = DCI.DAG; 10716 SDLoc dl(N); 10717 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10718 VT.getVectorNumElements()); 10719 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 10720 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 10721 // Make the DAGCombiner fold the bitcasts. 10722 DCI.AddToWorklist(Vec.getNode()); 10723 DCI.AddToWorklist(V.getNode()); 10724 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 10725 Vec, V, N->getOperand(2)); 10726 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 10727 } 10728 10729 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 10730 /// ISD::VECTOR_SHUFFLE. 10731 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 10732 // The LLVM shufflevector instruction does not require the shuffle mask 10733 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 10734 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 10735 // operands do not match the mask length, they are extended by concatenating 10736 // them with undef vectors. That is probably the right thing for other 10737 // targets, but for NEON it is better to concatenate two double-register 10738 // size vector operands into a single quad-register size vector. Do that 10739 // transformation here: 10740 // shuffle(concat(v1, undef), concat(v2, undef)) -> 10741 // shuffle(concat(v1, v2), undef) 10742 SDValue Op0 = N->getOperand(0); 10743 SDValue Op1 = N->getOperand(1); 10744 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 10745 Op1.getOpcode() != ISD::CONCAT_VECTORS || 10746 Op0.getNumOperands() != 2 || 10747 Op1.getNumOperands() != 2) 10748 return SDValue(); 10749 SDValue Concat0Op1 = Op0.getOperand(1); 10750 SDValue Concat1Op1 = Op1.getOperand(1); 10751 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 10752 return SDValue(); 10753 // Skip the transformation if any of the types are illegal. 10754 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10755 EVT VT = N->getValueType(0); 10756 if (!TLI.isTypeLegal(VT) || 10757 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 10758 !TLI.isTypeLegal(Concat1Op1.getValueType())) 10759 return SDValue(); 10760 10761 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10762 Op0.getOperand(0), Op1.getOperand(0)); 10763 // Translate the shuffle mask. 10764 SmallVector<int, 16> NewMask; 10765 unsigned NumElts = VT.getVectorNumElements(); 10766 unsigned HalfElts = NumElts/2; 10767 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10768 for (unsigned n = 0; n < NumElts; ++n) { 10769 int MaskElt = SVN->getMaskElt(n); 10770 int NewElt = -1; 10771 if (MaskElt < (int)HalfElts) 10772 NewElt = MaskElt; 10773 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 10774 NewElt = HalfElts + MaskElt - NumElts; 10775 NewMask.push_back(NewElt); 10776 } 10777 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 10778 DAG.getUNDEF(VT), NewMask); 10779 } 10780 10781 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 10782 /// NEON load/store intrinsics, and generic vector load/stores, to merge 10783 /// base address updates. 10784 /// For generic load/stores, the memory type is assumed to be a vector. 10785 /// The caller is assumed to have checked legality. 10786 static SDValue CombineBaseUpdate(SDNode *N, 10787 TargetLowering::DAGCombinerInfo &DCI) { 10788 SelectionDAG &DAG = DCI.DAG; 10789 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 10790 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 10791 const bool isStore = N->getOpcode() == ISD::STORE; 10792 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 10793 SDValue Addr = N->getOperand(AddrOpIdx); 10794 MemSDNode *MemN = cast<MemSDNode>(N); 10795 SDLoc dl(N); 10796 10797 // Search for a use of the address operand that is an increment. 10798 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 10799 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 10800 SDNode *User = *UI; 10801 if (User->getOpcode() != ISD::ADD || 10802 UI.getUse().getResNo() != Addr.getResNo()) 10803 continue; 10804 10805 // Check that the add is independent of the load/store. Otherwise, folding 10806 // it would create a cycle. 10807 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 10808 continue; 10809 10810 // Find the new opcode for the updating load/store. 10811 bool isLoadOp = true; 10812 bool isLaneOp = false; 10813 unsigned NewOpc = 0; 10814 unsigned NumVecs = 0; 10815 if (isIntrinsic) { 10816 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10817 switch (IntNo) { 10818 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 10819 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 10820 NumVecs = 1; break; 10821 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 10822 NumVecs = 2; break; 10823 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 10824 NumVecs = 3; break; 10825 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 10826 NumVecs = 4; break; 10827 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 10828 NumVecs = 2; isLaneOp = true; break; 10829 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 10830 NumVecs = 3; isLaneOp = true; break; 10831 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 10832 NumVecs = 4; isLaneOp = true; break; 10833 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 10834 NumVecs = 1; isLoadOp = false; break; 10835 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 10836 NumVecs = 2; isLoadOp = false; break; 10837 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 10838 NumVecs = 3; isLoadOp = false; break; 10839 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 10840 NumVecs = 4; isLoadOp = false; break; 10841 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 10842 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 10843 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 10844 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 10845 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 10846 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 10847 } 10848 } else { 10849 isLaneOp = true; 10850 switch (N->getOpcode()) { 10851 default: llvm_unreachable("unexpected opcode for Neon base update"); 10852 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 10853 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 10854 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 10855 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 10856 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 10857 NumVecs = 1; isLaneOp = false; break; 10858 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 10859 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 10860 } 10861 } 10862 10863 // Find the size of memory referenced by the load/store. 10864 EVT VecTy; 10865 if (isLoadOp) { 10866 VecTy = N->getValueType(0); 10867 } else if (isIntrinsic) { 10868 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 10869 } else { 10870 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 10871 VecTy = N->getOperand(1).getValueType(); 10872 } 10873 10874 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 10875 if (isLaneOp) 10876 NumBytes /= VecTy.getVectorNumElements(); 10877 10878 // If the increment is a constant, it must match the memory ref size. 10879 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10880 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 10881 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 10882 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 10883 // separate instructions that make it harder to use a non-constant update. 10884 continue; 10885 } 10886 10887 // OK, we found an ADD we can fold into the base update. 10888 // Now, create a _UPD node, taking care of not breaking alignment. 10889 10890 EVT AlignedVecTy = VecTy; 10891 unsigned Alignment = MemN->getAlignment(); 10892 10893 // If this is a less-than-standard-aligned load/store, change the type to 10894 // match the standard alignment. 10895 // The alignment is overlooked when selecting _UPD variants; and it's 10896 // easier to introduce bitcasts here than fix that. 10897 // There are 3 ways to get to this base-update combine: 10898 // - intrinsics: they are assumed to be properly aligned (to the standard 10899 // alignment of the memory type), so we don't need to do anything. 10900 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 10901 // intrinsics, so, likewise, there's nothing to do. 10902 // - generic load/store instructions: the alignment is specified as an 10903 // explicit operand, rather than implicitly as the standard alignment 10904 // of the memory type (like the intrisics). We need to change the 10905 // memory type to match the explicit alignment. That way, we don't 10906 // generate non-standard-aligned ARMISD::VLDx nodes. 10907 if (isa<LSBaseSDNode>(N)) { 10908 if (Alignment == 0) 10909 Alignment = 1; 10910 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 10911 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 10912 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 10913 assert(!isLaneOp && "Unexpected generic load/store lane."); 10914 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 10915 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 10916 } 10917 // Don't set an explicit alignment on regular load/stores that we want 10918 // to transform to VLD/VST 1_UPD nodes. 10919 // This matches the behavior of regular load/stores, which only get an 10920 // explicit alignment if the MMO alignment is larger than the standard 10921 // alignment of the memory type. 10922 // Intrinsics, however, always get an explicit alignment, set to the 10923 // alignment of the MMO. 10924 Alignment = 1; 10925 } 10926 10927 // Create the new updating load/store node. 10928 // First, create an SDVTList for the new updating node's results. 10929 EVT Tys[6]; 10930 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 10931 unsigned n; 10932 for (n = 0; n < NumResultVecs; ++n) 10933 Tys[n] = AlignedVecTy; 10934 Tys[n++] = MVT::i32; 10935 Tys[n] = MVT::Other; 10936 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 10937 10938 // Then, gather the new node's operands. 10939 SmallVector<SDValue, 8> Ops; 10940 Ops.push_back(N->getOperand(0)); // incoming chain 10941 Ops.push_back(N->getOperand(AddrOpIdx)); 10942 Ops.push_back(Inc); 10943 10944 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 10945 // Try to match the intrinsic's signature 10946 Ops.push_back(StN->getValue()); 10947 } else { 10948 // Loads (and of course intrinsics) match the intrinsics' signature, 10949 // so just add all but the alignment operand. 10950 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 10951 Ops.push_back(N->getOperand(i)); 10952 } 10953 10954 // For all node types, the alignment operand is always the last one. 10955 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 10956 10957 // If this is a non-standard-aligned STORE, the penultimate operand is the 10958 // stored value. Bitcast it to the aligned type. 10959 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 10960 SDValue &StVal = Ops[Ops.size()-2]; 10961 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 10962 } 10963 10964 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 10965 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 10966 MemN->getMemOperand()); 10967 10968 // Update the uses. 10969 SmallVector<SDValue, 5> NewResults; 10970 for (unsigned i = 0; i < NumResultVecs; ++i) 10971 NewResults.push_back(SDValue(UpdN.getNode(), i)); 10972 10973 // If this is an non-standard-aligned LOAD, the first result is the loaded 10974 // value. Bitcast it to the expected result type. 10975 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 10976 SDValue &LdVal = NewResults[0]; 10977 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 10978 } 10979 10980 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 10981 DCI.CombineTo(N, NewResults); 10982 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 10983 10984 break; 10985 } 10986 return SDValue(); 10987 } 10988 10989 static SDValue PerformVLDCombine(SDNode *N, 10990 TargetLowering::DAGCombinerInfo &DCI) { 10991 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10992 return SDValue(); 10993 10994 return CombineBaseUpdate(N, DCI); 10995 } 10996 10997 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 10998 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 10999 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11000 /// return true. 11001 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11002 SelectionDAG &DAG = DCI.DAG; 11003 EVT VT = N->getValueType(0); 11004 // vldN-dup instructions only support 64-bit vectors for N > 1. 11005 if (!VT.is64BitVector()) 11006 return false; 11007 11008 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11009 SDNode *VLD = N->getOperand(0).getNode(); 11010 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11011 return false; 11012 unsigned NumVecs = 0; 11013 unsigned NewOpc = 0; 11014 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11015 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11016 NumVecs = 2; 11017 NewOpc = ARMISD::VLD2DUP; 11018 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11019 NumVecs = 3; 11020 NewOpc = ARMISD::VLD3DUP; 11021 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11022 NumVecs = 4; 11023 NewOpc = ARMISD::VLD4DUP; 11024 } else { 11025 return false; 11026 } 11027 11028 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11029 // numbers match the load. 11030 unsigned VLDLaneNo = 11031 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11032 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11033 UI != UE; ++UI) { 11034 // Ignore uses of the chain result. 11035 if (UI.getUse().getResNo() == NumVecs) 11036 continue; 11037 SDNode *User = *UI; 11038 if (User->getOpcode() != ARMISD::VDUPLANE || 11039 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11040 return false; 11041 } 11042 11043 // Create the vldN-dup node. 11044 EVT Tys[5]; 11045 unsigned n; 11046 for (n = 0; n < NumVecs; ++n) 11047 Tys[n] = VT; 11048 Tys[n] = MVT::Other; 11049 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11050 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11051 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11052 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11053 Ops, VLDMemInt->getMemoryVT(), 11054 VLDMemInt->getMemOperand()); 11055 11056 // Update the uses. 11057 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11058 UI != UE; ++UI) { 11059 unsigned ResNo = UI.getUse().getResNo(); 11060 // Ignore uses of the chain result. 11061 if (ResNo == NumVecs) 11062 continue; 11063 SDNode *User = *UI; 11064 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11065 } 11066 11067 // Now the vldN-lane intrinsic is dead except for its chain result. 11068 // Update uses of the chain. 11069 std::vector<SDValue> VLDDupResults; 11070 for (unsigned n = 0; n < NumVecs; ++n) 11071 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11072 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11073 DCI.CombineTo(VLD, VLDDupResults); 11074 11075 return true; 11076 } 11077 11078 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11079 /// ARMISD::VDUPLANE. 11080 static SDValue PerformVDUPLANECombine(SDNode *N, 11081 TargetLowering::DAGCombinerInfo &DCI) { 11082 SDValue Op = N->getOperand(0); 11083 11084 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11085 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11086 if (CombineVLDDUP(N, DCI)) 11087 return SDValue(N, 0); 11088 11089 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11090 // redundant. Ignore bit_converts for now; element sizes are checked below. 11091 while (Op.getOpcode() == ISD::BITCAST) 11092 Op = Op.getOperand(0); 11093 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11094 return SDValue(); 11095 11096 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11097 unsigned EltSize = Op.getScalarValueSizeInBits(); 11098 // The canonical VMOV for a zero vector uses a 32-bit element size. 11099 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11100 unsigned EltBits; 11101 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11102 EltSize = 8; 11103 EVT VT = N->getValueType(0); 11104 if (EltSize > VT.getScalarSizeInBits()) 11105 return SDValue(); 11106 11107 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11108 } 11109 11110 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11111 static SDValue PerformVDUPCombine(SDNode *N, 11112 TargetLowering::DAGCombinerInfo &DCI) { 11113 SelectionDAG &DAG = DCI.DAG; 11114 SDValue Op = N->getOperand(0); 11115 11116 // Match VDUP(LOAD) -> VLD1DUP. 11117 // We match this pattern here rather than waiting for isel because the 11118 // transform is only legal for unindexed loads. 11119 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11120 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11121 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11122 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11123 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11124 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11125 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11126 Ops, LD->getMemoryVT(), 11127 LD->getMemOperand()); 11128 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11129 return VLDDup; 11130 } 11131 11132 return SDValue(); 11133 } 11134 11135 static SDValue PerformLOADCombine(SDNode *N, 11136 TargetLowering::DAGCombinerInfo &DCI) { 11137 EVT VT = N->getValueType(0); 11138 11139 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11140 if (ISD::isNormalLoad(N) && VT.isVector() && 11141 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11142 return CombineBaseUpdate(N, DCI); 11143 11144 return SDValue(); 11145 } 11146 11147 /// PerformSTORECombine - Target-specific dag combine xforms for 11148 /// ISD::STORE. 11149 static SDValue PerformSTORECombine(SDNode *N, 11150 TargetLowering::DAGCombinerInfo &DCI) { 11151 StoreSDNode *St = cast<StoreSDNode>(N); 11152 if (St->isVolatile()) 11153 return SDValue(); 11154 11155 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11156 // pack all of the elements in one place. Next, store to memory in fewer 11157 // chunks. 11158 SDValue StVal = St->getValue(); 11159 EVT VT = StVal.getValueType(); 11160 if (St->isTruncatingStore() && VT.isVector()) { 11161 SelectionDAG &DAG = DCI.DAG; 11162 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11163 EVT StVT = St->getMemoryVT(); 11164 unsigned NumElems = VT.getVectorNumElements(); 11165 assert(StVT != VT && "Cannot truncate to the same type"); 11166 unsigned FromEltSz = VT.getScalarSizeInBits(); 11167 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11168 11169 // From, To sizes and ElemCount must be pow of two 11170 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11171 11172 // We are going to use the original vector elt for storing. 11173 // Accumulated smaller vector elements must be a multiple of the store size. 11174 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11175 11176 unsigned SizeRatio = FromEltSz / ToEltSz; 11177 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11178 11179 // Create a type on which we perform the shuffle. 11180 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11181 NumElems*SizeRatio); 11182 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11183 11184 SDLoc DL(St); 11185 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11186 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11187 for (unsigned i = 0; i < NumElems; ++i) 11188 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11189 ? (i + 1) * SizeRatio - 1 11190 : i * SizeRatio; 11191 11192 // Can't shuffle using an illegal type. 11193 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11194 11195 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11196 DAG.getUNDEF(WideVec.getValueType()), 11197 ShuffleVec); 11198 // At this point all of the data is stored at the bottom of the 11199 // register. We now need to save it to mem. 11200 11201 // Find the largest store unit 11202 MVT StoreType = MVT::i8; 11203 for (MVT Tp : MVT::integer_valuetypes()) { 11204 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11205 StoreType = Tp; 11206 } 11207 // Didn't find a legal store type. 11208 if (!TLI.isTypeLegal(StoreType)) 11209 return SDValue(); 11210 11211 // Bitcast the original vector into a vector of store-size units 11212 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11213 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11214 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11215 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11216 SmallVector<SDValue, 8> Chains; 11217 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11218 TLI.getPointerTy(DAG.getDataLayout())); 11219 SDValue BasePtr = St->getBasePtr(); 11220 11221 // Perform one or more big stores into memory. 11222 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11223 for (unsigned I = 0; I < E; I++) { 11224 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11225 StoreType, ShuffWide, 11226 DAG.getIntPtrConstant(I, DL)); 11227 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11228 St->getPointerInfo(), St->getAlignment(), 11229 St->getMemOperand()->getFlags()); 11230 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11231 Increment); 11232 Chains.push_back(Ch); 11233 } 11234 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11235 } 11236 11237 if (!ISD::isNormalStore(St)) 11238 return SDValue(); 11239 11240 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11241 // ARM stores of arguments in the same cache line. 11242 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11243 StVal.getNode()->hasOneUse()) { 11244 SelectionDAG &DAG = DCI.DAG; 11245 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11246 SDLoc DL(St); 11247 SDValue BasePtr = St->getBasePtr(); 11248 SDValue NewST1 = DAG.getStore( 11249 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11250 BasePtr, St->getPointerInfo(), St->getAlignment(), 11251 St->getMemOperand()->getFlags()); 11252 11253 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11254 DAG.getConstant(4, DL, MVT::i32)); 11255 return DAG.getStore(NewST1.getValue(0), DL, 11256 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11257 OffsetPtr, St->getPointerInfo(), 11258 std::min(4U, St->getAlignment() / 2), 11259 St->getMemOperand()->getFlags()); 11260 } 11261 11262 if (StVal.getValueType() == MVT::i64 && 11263 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11264 11265 // Bitcast an i64 store extracted from a vector to f64. 11266 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11267 SelectionDAG &DAG = DCI.DAG; 11268 SDLoc dl(StVal); 11269 SDValue IntVec = StVal.getOperand(0); 11270 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11271 IntVec.getValueType().getVectorNumElements()); 11272 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11273 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11274 Vec, StVal.getOperand(1)); 11275 dl = SDLoc(N); 11276 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11277 // Make the DAGCombiner fold the bitcasts. 11278 DCI.AddToWorklist(Vec.getNode()); 11279 DCI.AddToWorklist(ExtElt.getNode()); 11280 DCI.AddToWorklist(V.getNode()); 11281 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11282 St->getPointerInfo(), St->getAlignment(), 11283 St->getMemOperand()->getFlags(), St->getAAInfo()); 11284 } 11285 11286 // If this is a legal vector store, try to combine it into a VST1_UPD. 11287 if (ISD::isNormalStore(N) && VT.isVector() && 11288 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11289 return CombineBaseUpdate(N, DCI); 11290 11291 return SDValue(); 11292 } 11293 11294 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11295 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11296 /// when the VMUL has a constant operand that is a power of 2. 11297 /// 11298 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11299 /// vmul.f32 d16, d17, d16 11300 /// vcvt.s32.f32 d16, d16 11301 /// becomes: 11302 /// vcvt.s32.f32 d16, d16, #3 11303 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11304 const ARMSubtarget *Subtarget) { 11305 if (!Subtarget->hasNEON()) 11306 return SDValue(); 11307 11308 SDValue Op = N->getOperand(0); 11309 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11310 Op.getOpcode() != ISD::FMUL) 11311 return SDValue(); 11312 11313 SDValue ConstVec = Op->getOperand(1); 11314 if (!isa<BuildVectorSDNode>(ConstVec)) 11315 return SDValue(); 11316 11317 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11318 uint32_t FloatBits = FloatTy.getSizeInBits(); 11319 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11320 uint32_t IntBits = IntTy.getSizeInBits(); 11321 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11322 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11323 // These instructions only exist converting from f32 to i32. We can handle 11324 // smaller integers by generating an extra truncate, but larger ones would 11325 // be lossy. We also can't handle more then 4 lanes, since these intructions 11326 // only support v2i32/v4i32 types. 11327 return SDValue(); 11328 } 11329 11330 BitVector UndefElements; 11331 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11332 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11333 if (C == -1 || C == 0 || C > 32) 11334 return SDValue(); 11335 11336 SDLoc dl(N); 11337 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11338 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11339 Intrinsic::arm_neon_vcvtfp2fxu; 11340 SDValue FixConv = DAG.getNode( 11341 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11342 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11343 DAG.getConstant(C, dl, MVT::i32)); 11344 11345 if (IntBits < FloatBits) 11346 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11347 11348 return FixConv; 11349 } 11350 11351 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11352 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11353 /// when the VDIV has a constant operand that is a power of 2. 11354 /// 11355 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11356 /// vcvt.f32.s32 d16, d16 11357 /// vdiv.f32 d16, d17, d16 11358 /// becomes: 11359 /// vcvt.f32.s32 d16, d16, #3 11360 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 11361 const ARMSubtarget *Subtarget) { 11362 if (!Subtarget->hasNEON()) 11363 return SDValue(); 11364 11365 SDValue Op = N->getOperand(0); 11366 unsigned OpOpcode = Op.getNode()->getOpcode(); 11367 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 11368 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 11369 return SDValue(); 11370 11371 SDValue ConstVec = N->getOperand(1); 11372 if (!isa<BuildVectorSDNode>(ConstVec)) 11373 return SDValue(); 11374 11375 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 11376 uint32_t FloatBits = FloatTy.getSizeInBits(); 11377 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 11378 uint32_t IntBits = IntTy.getSizeInBits(); 11379 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11380 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11381 // These instructions only exist converting from i32 to f32. We can handle 11382 // smaller integers by generating an extra extend, but larger ones would 11383 // be lossy. We also can't handle more then 4 lanes, since these intructions 11384 // only support v2i32/v4i32 types. 11385 return SDValue(); 11386 } 11387 11388 BitVector UndefElements; 11389 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11390 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11391 if (C == -1 || C == 0 || C > 32) 11392 return SDValue(); 11393 11394 SDLoc dl(N); 11395 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 11396 SDValue ConvInput = Op.getOperand(0); 11397 if (IntBits < FloatBits) 11398 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 11399 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11400 ConvInput); 11401 11402 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 11403 Intrinsic::arm_neon_vcvtfxu2fp; 11404 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 11405 Op.getValueType(), 11406 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 11407 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 11408 } 11409 11410 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 11411 /// operand of a vector shift operation, where all the elements of the 11412 /// build_vector must have the same constant integer value. 11413 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 11414 // Ignore bit_converts. 11415 while (Op.getOpcode() == ISD::BITCAST) 11416 Op = Op.getOperand(0); 11417 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 11418 APInt SplatBits, SplatUndef; 11419 unsigned SplatBitSize; 11420 bool HasAnyUndefs; 11421 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 11422 HasAnyUndefs, ElementBits) || 11423 SplatBitSize > ElementBits) 11424 return false; 11425 Cnt = SplatBits.getSExtValue(); 11426 return true; 11427 } 11428 11429 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 11430 /// operand of a vector shift left operation. That value must be in the range: 11431 /// 0 <= Value < ElementBits for a left shift; or 11432 /// 0 <= Value <= ElementBits for a long left shift. 11433 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 11434 assert(VT.isVector() && "vector shift count is not a vector type"); 11435 int64_t ElementBits = VT.getScalarSizeInBits(); 11436 if (! getVShiftImm(Op, ElementBits, Cnt)) 11437 return false; 11438 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 11439 } 11440 11441 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 11442 /// operand of a vector shift right operation. For a shift opcode, the value 11443 /// is positive, but for an intrinsic the value count must be negative. The 11444 /// absolute value must be in the range: 11445 /// 1 <= |Value| <= ElementBits for a right shift; or 11446 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 11447 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 11448 int64_t &Cnt) { 11449 assert(VT.isVector() && "vector shift count is not a vector type"); 11450 int64_t ElementBits = VT.getScalarSizeInBits(); 11451 if (! getVShiftImm(Op, ElementBits, Cnt)) 11452 return false; 11453 if (!isIntrinsic) 11454 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 11455 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 11456 Cnt = -Cnt; 11457 return true; 11458 } 11459 return false; 11460 } 11461 11462 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 11463 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 11464 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11465 switch (IntNo) { 11466 default: 11467 // Don't do anything for most intrinsics. 11468 break; 11469 11470 // Vector shifts: check for immediate versions and lower them. 11471 // Note: This is done during DAG combining instead of DAG legalizing because 11472 // the build_vectors for 64-bit vector element shift counts are generally 11473 // not legal, and it is hard to see their values after they get legalized to 11474 // loads from a constant pool. 11475 case Intrinsic::arm_neon_vshifts: 11476 case Intrinsic::arm_neon_vshiftu: 11477 case Intrinsic::arm_neon_vrshifts: 11478 case Intrinsic::arm_neon_vrshiftu: 11479 case Intrinsic::arm_neon_vrshiftn: 11480 case Intrinsic::arm_neon_vqshifts: 11481 case Intrinsic::arm_neon_vqshiftu: 11482 case Intrinsic::arm_neon_vqshiftsu: 11483 case Intrinsic::arm_neon_vqshiftns: 11484 case Intrinsic::arm_neon_vqshiftnu: 11485 case Intrinsic::arm_neon_vqshiftnsu: 11486 case Intrinsic::arm_neon_vqrshiftns: 11487 case Intrinsic::arm_neon_vqrshiftnu: 11488 case Intrinsic::arm_neon_vqrshiftnsu: { 11489 EVT VT = N->getOperand(1).getValueType(); 11490 int64_t Cnt; 11491 unsigned VShiftOpc = 0; 11492 11493 switch (IntNo) { 11494 case Intrinsic::arm_neon_vshifts: 11495 case Intrinsic::arm_neon_vshiftu: 11496 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 11497 VShiftOpc = ARMISD::VSHL; 11498 break; 11499 } 11500 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 11501 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 11502 ARMISD::VSHRs : ARMISD::VSHRu); 11503 break; 11504 } 11505 return SDValue(); 11506 11507 case Intrinsic::arm_neon_vrshifts: 11508 case Intrinsic::arm_neon_vrshiftu: 11509 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 11510 break; 11511 return SDValue(); 11512 11513 case Intrinsic::arm_neon_vqshifts: 11514 case Intrinsic::arm_neon_vqshiftu: 11515 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11516 break; 11517 return SDValue(); 11518 11519 case Intrinsic::arm_neon_vqshiftsu: 11520 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11521 break; 11522 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 11523 11524 case Intrinsic::arm_neon_vrshiftn: 11525 case Intrinsic::arm_neon_vqshiftns: 11526 case Intrinsic::arm_neon_vqshiftnu: 11527 case Intrinsic::arm_neon_vqshiftnsu: 11528 case Intrinsic::arm_neon_vqrshiftns: 11529 case Intrinsic::arm_neon_vqrshiftnu: 11530 case Intrinsic::arm_neon_vqrshiftnsu: 11531 // Narrowing shifts require an immediate right shift. 11532 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 11533 break; 11534 llvm_unreachable("invalid shift count for narrowing vector shift " 11535 "intrinsic"); 11536 11537 default: 11538 llvm_unreachable("unhandled vector shift"); 11539 } 11540 11541 switch (IntNo) { 11542 case Intrinsic::arm_neon_vshifts: 11543 case Intrinsic::arm_neon_vshiftu: 11544 // Opcode already set above. 11545 break; 11546 case Intrinsic::arm_neon_vrshifts: 11547 VShiftOpc = ARMISD::VRSHRs; break; 11548 case Intrinsic::arm_neon_vrshiftu: 11549 VShiftOpc = ARMISD::VRSHRu; break; 11550 case Intrinsic::arm_neon_vrshiftn: 11551 VShiftOpc = ARMISD::VRSHRN; break; 11552 case Intrinsic::arm_neon_vqshifts: 11553 VShiftOpc = ARMISD::VQSHLs; break; 11554 case Intrinsic::arm_neon_vqshiftu: 11555 VShiftOpc = ARMISD::VQSHLu; break; 11556 case Intrinsic::arm_neon_vqshiftsu: 11557 VShiftOpc = ARMISD::VQSHLsu; break; 11558 case Intrinsic::arm_neon_vqshiftns: 11559 VShiftOpc = ARMISD::VQSHRNs; break; 11560 case Intrinsic::arm_neon_vqshiftnu: 11561 VShiftOpc = ARMISD::VQSHRNu; break; 11562 case Intrinsic::arm_neon_vqshiftnsu: 11563 VShiftOpc = ARMISD::VQSHRNsu; break; 11564 case Intrinsic::arm_neon_vqrshiftns: 11565 VShiftOpc = ARMISD::VQRSHRNs; break; 11566 case Intrinsic::arm_neon_vqrshiftnu: 11567 VShiftOpc = ARMISD::VQRSHRNu; break; 11568 case Intrinsic::arm_neon_vqrshiftnsu: 11569 VShiftOpc = ARMISD::VQRSHRNsu; break; 11570 } 11571 11572 SDLoc dl(N); 11573 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11574 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 11575 } 11576 11577 case Intrinsic::arm_neon_vshiftins: { 11578 EVT VT = N->getOperand(1).getValueType(); 11579 int64_t Cnt; 11580 unsigned VShiftOpc = 0; 11581 11582 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 11583 VShiftOpc = ARMISD::VSLI; 11584 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 11585 VShiftOpc = ARMISD::VSRI; 11586 else { 11587 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 11588 } 11589 11590 SDLoc dl(N); 11591 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11592 N->getOperand(1), N->getOperand(2), 11593 DAG.getConstant(Cnt, dl, MVT::i32)); 11594 } 11595 11596 case Intrinsic::arm_neon_vqrshifts: 11597 case Intrinsic::arm_neon_vqrshiftu: 11598 // No immediate versions of these to check for. 11599 break; 11600 } 11601 11602 return SDValue(); 11603 } 11604 11605 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 11606 /// lowers them. As with the vector shift intrinsics, this is done during DAG 11607 /// combining instead of DAG legalizing because the build_vectors for 64-bit 11608 /// vector element shift counts are generally not legal, and it is hard to see 11609 /// their values after they get legalized to loads from a constant pool. 11610 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 11611 const ARMSubtarget *ST) { 11612 EVT VT = N->getValueType(0); 11613 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 11614 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 11615 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 11616 SDValue N1 = N->getOperand(1); 11617 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 11618 SDValue N0 = N->getOperand(0); 11619 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 11620 DAG.MaskedValueIsZero(N0.getOperand(0), 11621 APInt::getHighBitsSet(32, 16))) 11622 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 11623 } 11624 } 11625 11626 // Nothing to be done for scalar shifts. 11627 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11628 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 11629 return SDValue(); 11630 11631 assert(ST->hasNEON() && "unexpected vector shift"); 11632 int64_t Cnt; 11633 11634 switch (N->getOpcode()) { 11635 default: llvm_unreachable("unexpected shift opcode"); 11636 11637 case ISD::SHL: 11638 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 11639 SDLoc dl(N); 11640 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 11641 DAG.getConstant(Cnt, dl, MVT::i32)); 11642 } 11643 break; 11644 11645 case ISD::SRA: 11646 case ISD::SRL: 11647 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 11648 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 11649 ARMISD::VSHRs : ARMISD::VSHRu); 11650 SDLoc dl(N); 11651 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 11652 DAG.getConstant(Cnt, dl, MVT::i32)); 11653 } 11654 } 11655 return SDValue(); 11656 } 11657 11658 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 11659 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 11660 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 11661 const ARMSubtarget *ST) { 11662 SDValue N0 = N->getOperand(0); 11663 11664 // Check for sign- and zero-extensions of vector extract operations of 8- 11665 // and 16-bit vector elements. NEON supports these directly. They are 11666 // handled during DAG combining because type legalization will promote them 11667 // to 32-bit types and it is messy to recognize the operations after that. 11668 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11669 SDValue Vec = N0.getOperand(0); 11670 SDValue Lane = N0.getOperand(1); 11671 EVT VT = N->getValueType(0); 11672 EVT EltVT = N0.getValueType(); 11673 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11674 11675 if (VT == MVT::i32 && 11676 (EltVT == MVT::i8 || EltVT == MVT::i16) && 11677 TLI.isTypeLegal(Vec.getValueType()) && 11678 isa<ConstantSDNode>(Lane)) { 11679 11680 unsigned Opc = 0; 11681 switch (N->getOpcode()) { 11682 default: llvm_unreachable("unexpected opcode"); 11683 case ISD::SIGN_EXTEND: 11684 Opc = ARMISD::VGETLANEs; 11685 break; 11686 case ISD::ZERO_EXTEND: 11687 case ISD::ANY_EXTEND: 11688 Opc = ARMISD::VGETLANEu; 11689 break; 11690 } 11691 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 11692 } 11693 } 11694 11695 return SDValue(); 11696 } 11697 11698 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 11699 // If we have a CMOV, OR and AND combination such as: 11700 // if (x & CN) 11701 // y |= CM; 11702 // 11703 // And: 11704 // * CN is a single bit; 11705 // * All bits covered by CM are known zero in y 11706 // 11707 // Then we can convert this into a sequence of BFI instructions. This will 11708 // always be a win if CM is a single bit, will always be no worse than the 11709 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 11710 // three bits (due to the extra IT instruction). 11711 11712 SDValue Op0 = CMOV->getOperand(0); 11713 SDValue Op1 = CMOV->getOperand(1); 11714 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 11715 auto CC = CCNode->getAPIntValue().getLimitedValue(); 11716 SDValue CmpZ = CMOV->getOperand(4); 11717 11718 // The compare must be against zero. 11719 if (!isNullConstant(CmpZ->getOperand(1))) 11720 return SDValue(); 11721 11722 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 11723 SDValue And = CmpZ->getOperand(0); 11724 if (And->getOpcode() != ISD::AND) 11725 return SDValue(); 11726 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 11727 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 11728 return SDValue(); 11729 SDValue X = And->getOperand(0); 11730 11731 if (CC == ARMCC::EQ) { 11732 // We're performing an "equal to zero" compare. Swap the operands so we 11733 // canonicalize on a "not equal to zero" compare. 11734 std::swap(Op0, Op1); 11735 } else { 11736 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 11737 } 11738 11739 if (Op1->getOpcode() != ISD::OR) 11740 return SDValue(); 11741 11742 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 11743 if (!OrC) 11744 return SDValue(); 11745 SDValue Y = Op1->getOperand(0); 11746 11747 if (Op0 != Y) 11748 return SDValue(); 11749 11750 // Now, is it profitable to continue? 11751 APInt OrCI = OrC->getAPIntValue(); 11752 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 11753 if (OrCI.countPopulation() > Heuristic) 11754 return SDValue(); 11755 11756 // Lastly, can we determine that the bits defined by OrCI 11757 // are zero in Y? 11758 APInt KnownZero, KnownOne; 11759 DAG.computeKnownBits(Y, KnownZero, KnownOne); 11760 if ((OrCI & KnownZero) != OrCI) 11761 return SDValue(); 11762 11763 // OK, we can do the combine. 11764 SDValue V = Y; 11765 SDLoc dl(X); 11766 EVT VT = X.getValueType(); 11767 unsigned BitInX = AndC->getAPIntValue().logBase2(); 11768 11769 if (BitInX != 0) { 11770 // We must shift X first. 11771 X = DAG.getNode(ISD::SRL, dl, VT, X, 11772 DAG.getConstant(BitInX, dl, VT)); 11773 } 11774 11775 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 11776 BitInY < NumActiveBits; ++BitInY) { 11777 if (OrCI[BitInY] == 0) 11778 continue; 11779 APInt Mask(VT.getSizeInBits(), 0); 11780 Mask.setBit(BitInY); 11781 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 11782 // Confusingly, the operand is an *inverted* mask. 11783 DAG.getConstant(~Mask, dl, VT)); 11784 } 11785 11786 return V; 11787 } 11788 11789 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 11790 SDValue 11791 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 11792 SDValue Cmp = N->getOperand(4); 11793 if (Cmp.getOpcode() != ARMISD::CMPZ) 11794 // Only looking at NE cases. 11795 return SDValue(); 11796 11797 EVT VT = N->getValueType(0); 11798 SDLoc dl(N); 11799 SDValue LHS = Cmp.getOperand(0); 11800 SDValue RHS = Cmp.getOperand(1); 11801 SDValue Chain = N->getOperand(0); 11802 SDValue BB = N->getOperand(1); 11803 SDValue ARMcc = N->getOperand(2); 11804 ARMCC::CondCodes CC = 11805 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11806 11807 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 11808 // -> (brcond Chain BB CC CPSR Cmp) 11809 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 11810 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 11811 LHS->getOperand(0)->hasOneUse()) { 11812 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 11813 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 11814 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11815 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11816 if ((LHS00C && LHS00C->getZExtValue() == 0) && 11817 (LHS01C && LHS01C->getZExtValue() == 1) && 11818 (LHS1C && LHS1C->getZExtValue() == 1) && 11819 (RHSC && RHSC->getZExtValue() == 0)) { 11820 return DAG.getNode( 11821 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 11822 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 11823 } 11824 } 11825 11826 return SDValue(); 11827 } 11828 11829 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 11830 SDValue 11831 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 11832 SDValue Cmp = N->getOperand(4); 11833 if (Cmp.getOpcode() != ARMISD::CMPZ) 11834 // Only looking at EQ and NE cases. 11835 return SDValue(); 11836 11837 EVT VT = N->getValueType(0); 11838 SDLoc dl(N); 11839 SDValue LHS = Cmp.getOperand(0); 11840 SDValue RHS = Cmp.getOperand(1); 11841 SDValue FalseVal = N->getOperand(0); 11842 SDValue TrueVal = N->getOperand(1); 11843 SDValue ARMcc = N->getOperand(2); 11844 ARMCC::CondCodes CC = 11845 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11846 11847 // BFI is only available on V6T2+. 11848 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 11849 SDValue R = PerformCMOVToBFICombine(N, DAG); 11850 if (R) 11851 return R; 11852 } 11853 11854 // Simplify 11855 // mov r1, r0 11856 // cmp r1, x 11857 // mov r0, y 11858 // moveq r0, x 11859 // to 11860 // cmp r0, x 11861 // movne r0, y 11862 // 11863 // mov r1, r0 11864 // cmp r1, x 11865 // mov r0, x 11866 // movne r0, y 11867 // to 11868 // cmp r0, x 11869 // movne r0, y 11870 /// FIXME: Turn this into a target neutral optimization? 11871 SDValue Res; 11872 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 11873 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 11874 N->getOperand(3), Cmp); 11875 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 11876 SDValue ARMcc; 11877 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 11878 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 11879 N->getOperand(3), NewCmp); 11880 } 11881 11882 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 11883 // -> (cmov F T CC CPSR Cmp) 11884 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 11885 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 11886 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11887 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11888 if ((LHS0C && LHS0C->getZExtValue() == 0) && 11889 (LHS1C && LHS1C->getZExtValue() == 1) && 11890 (RHSC && RHSC->getZExtValue() == 0)) { 11891 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 11892 LHS->getOperand(2), LHS->getOperand(3), 11893 LHS->getOperand(4)); 11894 } 11895 } 11896 11897 if (Res.getNode()) { 11898 APInt KnownZero, KnownOne; 11899 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 11900 // Capture demanded bits information that would be otherwise lost. 11901 if (KnownZero == 0xfffffffe) 11902 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11903 DAG.getValueType(MVT::i1)); 11904 else if (KnownZero == 0xffffff00) 11905 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11906 DAG.getValueType(MVT::i8)); 11907 else if (KnownZero == 0xffff0000) 11908 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11909 DAG.getValueType(MVT::i16)); 11910 } 11911 11912 return Res; 11913 } 11914 11915 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 11916 DAGCombinerInfo &DCI) const { 11917 switch (N->getOpcode()) { 11918 default: break; 11919 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 11920 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 11921 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 11922 case ISD::SUB: return PerformSUBCombine(N, DCI); 11923 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 11924 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 11925 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 11926 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 11927 case ARMISD::ADDC: 11928 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI.DAG, Subtarget); 11929 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 11930 case ARMISD::BFI: return PerformBFICombine(N, DCI); 11931 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 11932 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 11933 case ISD::STORE: return PerformSTORECombine(N, DCI); 11934 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 11935 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 11936 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 11937 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 11938 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 11939 case ISD::FP_TO_SINT: 11940 case ISD::FP_TO_UINT: 11941 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 11942 case ISD::FDIV: 11943 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 11944 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 11945 case ISD::SHL: 11946 case ISD::SRA: 11947 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 11948 case ISD::SIGN_EXTEND: 11949 case ISD::ZERO_EXTEND: 11950 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 11951 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 11952 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 11953 case ISD::LOAD: return PerformLOADCombine(N, DCI); 11954 case ARMISD::VLD1DUP: 11955 case ARMISD::VLD2DUP: 11956 case ARMISD::VLD3DUP: 11957 case ARMISD::VLD4DUP: 11958 return PerformVLDCombine(N, DCI); 11959 case ARMISD::BUILD_VECTOR: 11960 return PerformARMBUILD_VECTORCombine(N, DCI); 11961 case ARMISD::SMULWB: { 11962 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 11963 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 11964 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 11965 return SDValue(); 11966 break; 11967 } 11968 case ARMISD::SMULWT: { 11969 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 11970 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 11971 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 11972 return SDValue(); 11973 break; 11974 } 11975 case ARMISD::SMLALBB: { 11976 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 11977 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 11978 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 11979 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 11980 return SDValue(); 11981 break; 11982 } 11983 case ARMISD::SMLALBT: { 11984 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 11985 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 11986 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 11987 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 11988 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 11989 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 11990 return SDValue(); 11991 break; 11992 } 11993 case ARMISD::SMLALTB: { 11994 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 11995 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 11996 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 11997 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 11998 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 11999 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12000 return SDValue(); 12001 break; 12002 } 12003 case ARMISD::SMLALTT: { 12004 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12005 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12006 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12007 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12008 return SDValue(); 12009 break; 12010 } 12011 case ISD::INTRINSIC_VOID: 12012 case ISD::INTRINSIC_W_CHAIN: 12013 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12014 case Intrinsic::arm_neon_vld1: 12015 case Intrinsic::arm_neon_vld2: 12016 case Intrinsic::arm_neon_vld3: 12017 case Intrinsic::arm_neon_vld4: 12018 case Intrinsic::arm_neon_vld2lane: 12019 case Intrinsic::arm_neon_vld3lane: 12020 case Intrinsic::arm_neon_vld4lane: 12021 case Intrinsic::arm_neon_vst1: 12022 case Intrinsic::arm_neon_vst2: 12023 case Intrinsic::arm_neon_vst3: 12024 case Intrinsic::arm_neon_vst4: 12025 case Intrinsic::arm_neon_vst2lane: 12026 case Intrinsic::arm_neon_vst3lane: 12027 case Intrinsic::arm_neon_vst4lane: 12028 return PerformVLDCombine(N, DCI); 12029 default: break; 12030 } 12031 break; 12032 } 12033 return SDValue(); 12034 } 12035 12036 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12037 EVT VT) const { 12038 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12039 } 12040 12041 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12042 unsigned, 12043 unsigned, 12044 bool *Fast) const { 12045 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12046 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12047 12048 switch (VT.getSimpleVT().SimpleTy) { 12049 default: 12050 return false; 12051 case MVT::i8: 12052 case MVT::i16: 12053 case MVT::i32: { 12054 // Unaligned access can use (for example) LRDB, LRDH, LDR 12055 if (AllowsUnaligned) { 12056 if (Fast) 12057 *Fast = Subtarget->hasV7Ops(); 12058 return true; 12059 } 12060 return false; 12061 } 12062 case MVT::f64: 12063 case MVT::v2f64: { 12064 // For any little-endian targets with neon, we can support unaligned ld/st 12065 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12066 // A big-endian target may also explicitly support unaligned accesses 12067 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12068 if (Fast) 12069 *Fast = true; 12070 return true; 12071 } 12072 return false; 12073 } 12074 } 12075 } 12076 12077 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12078 unsigned AlignCheck) { 12079 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12080 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12081 } 12082 12083 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12084 unsigned DstAlign, unsigned SrcAlign, 12085 bool IsMemset, bool ZeroMemset, 12086 bool MemcpyStrSrc, 12087 MachineFunction &MF) const { 12088 const Function *F = MF.getFunction(); 12089 12090 // See if we can use NEON instructions for this... 12091 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12092 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 12093 bool Fast; 12094 if (Size >= 16 && 12095 (memOpAlign(SrcAlign, DstAlign, 16) || 12096 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12097 return MVT::v2f64; 12098 } else if (Size >= 8 && 12099 (memOpAlign(SrcAlign, DstAlign, 8) || 12100 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12101 Fast))) { 12102 return MVT::f64; 12103 } 12104 } 12105 12106 // Lowering to i32/i16 if the size permits. 12107 if (Size >= 4) 12108 return MVT::i32; 12109 else if (Size >= 2) 12110 return MVT::i16; 12111 12112 // Let the target-independent logic figure it out. 12113 return MVT::Other; 12114 } 12115 12116 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12117 if (Val.getOpcode() != ISD::LOAD) 12118 return false; 12119 12120 EVT VT1 = Val.getValueType(); 12121 if (!VT1.isSimple() || !VT1.isInteger() || 12122 !VT2.isSimple() || !VT2.isInteger()) 12123 return false; 12124 12125 switch (VT1.getSimpleVT().SimpleTy) { 12126 default: break; 12127 case MVT::i1: 12128 case MVT::i8: 12129 case MVT::i16: 12130 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12131 return true; 12132 } 12133 12134 return false; 12135 } 12136 12137 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12138 EVT VT = ExtVal.getValueType(); 12139 12140 if (!isTypeLegal(VT)) 12141 return false; 12142 12143 // Don't create a loadext if we can fold the extension into a wide/long 12144 // instruction. 12145 // If there's more than one user instruction, the loadext is desirable no 12146 // matter what. There can be two uses by the same instruction. 12147 if (ExtVal->use_empty() || 12148 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12149 return true; 12150 12151 SDNode *U = *ExtVal->use_begin(); 12152 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12153 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12154 return false; 12155 12156 return true; 12157 } 12158 12159 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12160 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12161 return false; 12162 12163 if (!isTypeLegal(EVT::getEVT(Ty1))) 12164 return false; 12165 12166 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12167 12168 // Assuming the caller doesn't have a zeroext or signext return parameter, 12169 // truncation all the way down to i1 is valid. 12170 return true; 12171 } 12172 12173 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12174 const AddrMode &AM, Type *Ty, 12175 unsigned AS) const { 12176 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12177 if (Subtarget->hasFPAO()) 12178 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12179 return 0; 12180 } 12181 return -1; 12182 } 12183 12184 12185 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 12186 if (V < 0) 12187 return false; 12188 12189 unsigned Scale = 1; 12190 switch (VT.getSimpleVT().SimpleTy) { 12191 default: return false; 12192 case MVT::i1: 12193 case MVT::i8: 12194 // Scale == 1; 12195 break; 12196 case MVT::i16: 12197 // Scale == 2; 12198 Scale = 2; 12199 break; 12200 case MVT::i32: 12201 // Scale == 4; 12202 Scale = 4; 12203 break; 12204 } 12205 12206 if ((V & (Scale - 1)) != 0) 12207 return false; 12208 V /= Scale; 12209 return V == (V & ((1LL << 5) - 1)); 12210 } 12211 12212 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 12213 const ARMSubtarget *Subtarget) { 12214 bool isNeg = false; 12215 if (V < 0) { 12216 isNeg = true; 12217 V = - V; 12218 } 12219 12220 switch (VT.getSimpleVT().SimpleTy) { 12221 default: return false; 12222 case MVT::i1: 12223 case MVT::i8: 12224 case MVT::i16: 12225 case MVT::i32: 12226 // + imm12 or - imm8 12227 if (isNeg) 12228 return V == (V & ((1LL << 8) - 1)); 12229 return V == (V & ((1LL << 12) - 1)); 12230 case MVT::f32: 12231 case MVT::f64: 12232 // Same as ARM mode. FIXME: NEON? 12233 if (!Subtarget->hasVFP2()) 12234 return false; 12235 if ((V & 3) != 0) 12236 return false; 12237 V >>= 2; 12238 return V == (V & ((1LL << 8) - 1)); 12239 } 12240 } 12241 12242 /// isLegalAddressImmediate - Return true if the integer value can be used 12243 /// as the offset of the target addressing mode for load / store of the 12244 /// given type. 12245 static bool isLegalAddressImmediate(int64_t V, EVT VT, 12246 const ARMSubtarget *Subtarget) { 12247 if (V == 0) 12248 return true; 12249 12250 if (!VT.isSimple()) 12251 return false; 12252 12253 if (Subtarget->isThumb1Only()) 12254 return isLegalT1AddressImmediate(V, VT); 12255 else if (Subtarget->isThumb2()) 12256 return isLegalT2AddressImmediate(V, VT, Subtarget); 12257 12258 // ARM mode. 12259 if (V < 0) 12260 V = - V; 12261 switch (VT.getSimpleVT().SimpleTy) { 12262 default: return false; 12263 case MVT::i1: 12264 case MVT::i8: 12265 case MVT::i32: 12266 // +- imm12 12267 return V == (V & ((1LL << 12) - 1)); 12268 case MVT::i16: 12269 // +- imm8 12270 return V == (V & ((1LL << 8) - 1)); 12271 case MVT::f32: 12272 case MVT::f64: 12273 if (!Subtarget->hasVFP2()) // FIXME: NEON? 12274 return false; 12275 if ((V & 3) != 0) 12276 return false; 12277 V >>= 2; 12278 return V == (V & ((1LL << 8) - 1)); 12279 } 12280 } 12281 12282 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 12283 EVT VT) const { 12284 int Scale = AM.Scale; 12285 if (Scale < 0) 12286 return false; 12287 12288 switch (VT.getSimpleVT().SimpleTy) { 12289 default: return false; 12290 case MVT::i1: 12291 case MVT::i8: 12292 case MVT::i16: 12293 case MVT::i32: 12294 if (Scale == 1) 12295 return true; 12296 // r + r << imm 12297 Scale = Scale & ~1; 12298 return Scale == 2 || Scale == 4 || Scale == 8; 12299 case MVT::i64: 12300 // r + r 12301 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 12302 return true; 12303 return false; 12304 case MVT::isVoid: 12305 // Note, we allow "void" uses (basically, uses that aren't loads or 12306 // stores), because arm allows folding a scale into many arithmetic 12307 // operations. This should be made more precise and revisited later. 12308 12309 // Allow r << imm, but the imm has to be a multiple of two. 12310 if (Scale & 1) return false; 12311 return isPowerOf2_32(Scale); 12312 } 12313 } 12314 12315 /// isLegalAddressingMode - Return true if the addressing mode represented 12316 /// by AM is legal for this target, for a load/store of the specified type. 12317 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12318 const AddrMode &AM, Type *Ty, 12319 unsigned AS) const { 12320 EVT VT = getValueType(DL, Ty, true); 12321 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 12322 return false; 12323 12324 // Can never fold addr of global into load/store. 12325 if (AM.BaseGV) 12326 return false; 12327 12328 switch (AM.Scale) { 12329 case 0: // no scale reg, must be "r+i" or "r", or "i". 12330 break; 12331 case 1: 12332 if (Subtarget->isThumb1Only()) 12333 return false; 12334 LLVM_FALLTHROUGH; 12335 default: 12336 // ARM doesn't support any R+R*scale+imm addr modes. 12337 if (AM.BaseOffs) 12338 return false; 12339 12340 if (!VT.isSimple()) 12341 return false; 12342 12343 if (Subtarget->isThumb2()) 12344 return isLegalT2ScaledAddressingMode(AM, VT); 12345 12346 int Scale = AM.Scale; 12347 switch (VT.getSimpleVT().SimpleTy) { 12348 default: return false; 12349 case MVT::i1: 12350 case MVT::i8: 12351 case MVT::i32: 12352 if (Scale < 0) Scale = -Scale; 12353 if (Scale == 1) 12354 return true; 12355 // r + r << imm 12356 return isPowerOf2_32(Scale & ~1); 12357 case MVT::i16: 12358 case MVT::i64: 12359 // r + r 12360 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 12361 return true; 12362 return false; 12363 12364 case MVT::isVoid: 12365 // Note, we allow "void" uses (basically, uses that aren't loads or 12366 // stores), because arm allows folding a scale into many arithmetic 12367 // operations. This should be made more precise and revisited later. 12368 12369 // Allow r << imm, but the imm has to be a multiple of two. 12370 if (Scale & 1) return false; 12371 return isPowerOf2_32(Scale); 12372 } 12373 } 12374 return true; 12375 } 12376 12377 /// isLegalICmpImmediate - Return true if the specified immediate is legal 12378 /// icmp immediate, that is the target has icmp instructions which can compare 12379 /// a register against the immediate without having to materialize the 12380 /// immediate into a register. 12381 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12382 // Thumb2 and ARM modes can use cmn for negative immediates. 12383 if (!Subtarget->isThumb()) 12384 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 12385 if (Subtarget->isThumb2()) 12386 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 12387 // Thumb1 doesn't have cmn, and only 8-bit immediates. 12388 return Imm >= 0 && Imm <= 255; 12389 } 12390 12391 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 12392 /// *or sub* immediate, that is the target has add or sub instructions which can 12393 /// add a register with the immediate without having to materialize the 12394 /// immediate into a register. 12395 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12396 // Same encoding for add/sub, just flip the sign. 12397 int64_t AbsImm = std::abs(Imm); 12398 if (!Subtarget->isThumb()) 12399 return ARM_AM::getSOImmVal(AbsImm) != -1; 12400 if (Subtarget->isThumb2()) 12401 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 12402 // Thumb1 only has 8-bit unsigned immediate. 12403 return AbsImm >= 0 && AbsImm <= 255; 12404 } 12405 12406 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 12407 bool isSEXTLoad, SDValue &Base, 12408 SDValue &Offset, bool &isInc, 12409 SelectionDAG &DAG) { 12410 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12411 return false; 12412 12413 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 12414 // AddressingMode 3 12415 Base = Ptr->getOperand(0); 12416 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12417 int RHSC = (int)RHS->getZExtValue(); 12418 if (RHSC < 0 && RHSC > -256) { 12419 assert(Ptr->getOpcode() == ISD::ADD); 12420 isInc = false; 12421 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12422 return true; 12423 } 12424 } 12425 isInc = (Ptr->getOpcode() == ISD::ADD); 12426 Offset = Ptr->getOperand(1); 12427 return true; 12428 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 12429 // AddressingMode 2 12430 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12431 int RHSC = (int)RHS->getZExtValue(); 12432 if (RHSC < 0 && RHSC > -0x1000) { 12433 assert(Ptr->getOpcode() == ISD::ADD); 12434 isInc = false; 12435 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12436 Base = Ptr->getOperand(0); 12437 return true; 12438 } 12439 } 12440 12441 if (Ptr->getOpcode() == ISD::ADD) { 12442 isInc = true; 12443 ARM_AM::ShiftOpc ShOpcVal= 12444 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 12445 if (ShOpcVal != ARM_AM::no_shift) { 12446 Base = Ptr->getOperand(1); 12447 Offset = Ptr->getOperand(0); 12448 } else { 12449 Base = Ptr->getOperand(0); 12450 Offset = Ptr->getOperand(1); 12451 } 12452 return true; 12453 } 12454 12455 isInc = (Ptr->getOpcode() == ISD::ADD); 12456 Base = Ptr->getOperand(0); 12457 Offset = Ptr->getOperand(1); 12458 return true; 12459 } 12460 12461 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 12462 return false; 12463 } 12464 12465 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 12466 bool isSEXTLoad, SDValue &Base, 12467 SDValue &Offset, bool &isInc, 12468 SelectionDAG &DAG) { 12469 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12470 return false; 12471 12472 Base = Ptr->getOperand(0); 12473 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12474 int RHSC = (int)RHS->getZExtValue(); 12475 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 12476 assert(Ptr->getOpcode() == ISD::ADD); 12477 isInc = false; 12478 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12479 return true; 12480 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 12481 isInc = Ptr->getOpcode() == ISD::ADD; 12482 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12483 return true; 12484 } 12485 } 12486 12487 return false; 12488 } 12489 12490 /// getPreIndexedAddressParts - returns true by value, base pointer and 12491 /// offset pointer and addressing mode by reference if the node's address 12492 /// can be legally represented as pre-indexed load / store address. 12493 bool 12494 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 12495 SDValue &Offset, 12496 ISD::MemIndexedMode &AM, 12497 SelectionDAG &DAG) const { 12498 if (Subtarget->isThumb1Only()) 12499 return false; 12500 12501 EVT VT; 12502 SDValue Ptr; 12503 bool isSEXTLoad = false; 12504 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12505 Ptr = LD->getBasePtr(); 12506 VT = LD->getMemoryVT(); 12507 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12508 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12509 Ptr = ST->getBasePtr(); 12510 VT = ST->getMemoryVT(); 12511 } else 12512 return false; 12513 12514 bool isInc; 12515 bool isLegal = false; 12516 if (Subtarget->isThumb2()) 12517 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12518 Offset, isInc, DAG); 12519 else 12520 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12521 Offset, isInc, DAG); 12522 if (!isLegal) 12523 return false; 12524 12525 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 12526 return true; 12527 } 12528 12529 /// getPostIndexedAddressParts - returns true by value, base pointer and 12530 /// offset pointer and addressing mode by reference if this node can be 12531 /// combined with a load / store to form a post-indexed load / store. 12532 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 12533 SDValue &Base, 12534 SDValue &Offset, 12535 ISD::MemIndexedMode &AM, 12536 SelectionDAG &DAG) const { 12537 EVT VT; 12538 SDValue Ptr; 12539 bool isSEXTLoad = false, isNonExt; 12540 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12541 VT = LD->getMemoryVT(); 12542 Ptr = LD->getBasePtr(); 12543 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12544 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 12545 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12546 VT = ST->getMemoryVT(); 12547 Ptr = ST->getBasePtr(); 12548 isNonExt = !ST->isTruncatingStore(); 12549 } else 12550 return false; 12551 12552 if (Subtarget->isThumb1Only()) { 12553 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 12554 // must be non-extending/truncating, i32, with an offset of 4. 12555 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 12556 if (Op->getOpcode() != ISD::ADD || !isNonExt) 12557 return false; 12558 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12559 if (!RHS || RHS->getZExtValue() != 4) 12560 return false; 12561 12562 Offset = Op->getOperand(1); 12563 Base = Op->getOperand(0); 12564 AM = ISD::POST_INC; 12565 return true; 12566 } 12567 12568 bool isInc; 12569 bool isLegal = false; 12570 if (Subtarget->isThumb2()) 12571 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12572 isInc, DAG); 12573 else 12574 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12575 isInc, DAG); 12576 if (!isLegal) 12577 return false; 12578 12579 if (Ptr != Base) { 12580 // Swap base ptr and offset to catch more post-index load / store when 12581 // it's legal. In Thumb2 mode, offset must be an immediate. 12582 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 12583 !Subtarget->isThumb2()) 12584 std::swap(Base, Offset); 12585 12586 // Post-indexed load / store update the base pointer. 12587 if (Ptr != Base) 12588 return false; 12589 } 12590 12591 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 12592 return true; 12593 } 12594 12595 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12596 APInt &KnownZero, 12597 APInt &KnownOne, 12598 const APInt &DemandedElts, 12599 const SelectionDAG &DAG, 12600 unsigned Depth) const { 12601 unsigned BitWidth = KnownOne.getBitWidth(); 12602 KnownZero = KnownOne = APInt(BitWidth, 0); 12603 switch (Op.getOpcode()) { 12604 default: break; 12605 case ARMISD::ADDC: 12606 case ARMISD::ADDE: 12607 case ARMISD::SUBC: 12608 case ARMISD::SUBE: 12609 // These nodes' second result is a boolean 12610 if (Op.getResNo() == 0) 12611 break; 12612 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 12613 break; 12614 case ARMISD::CMOV: { 12615 // Bits are known zero/one if known on the LHS and RHS. 12616 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 12617 if (KnownZero == 0 && KnownOne == 0) return; 12618 12619 APInt KnownZeroRHS, KnownOneRHS; 12620 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 12621 KnownZero &= KnownZeroRHS; 12622 KnownOne &= KnownOneRHS; 12623 return; 12624 } 12625 case ISD::INTRINSIC_W_CHAIN: { 12626 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 12627 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 12628 switch (IntID) { 12629 default: return; 12630 case Intrinsic::arm_ldaex: 12631 case Intrinsic::arm_ldrex: { 12632 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 12633 unsigned MemBits = VT.getScalarSizeInBits(); 12634 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 12635 return; 12636 } 12637 } 12638 } 12639 case ARMISD::BFI: { 12640 // Conservatively, we can recurse down the first operand 12641 // and just mask out all affected bits. 12642 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth + 1); 12643 12644 // The operand to BFI is already a mask suitable for removing the bits it 12645 // sets. 12646 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 12647 const APInt &Mask = CI->getAPIntValue(); 12648 KnownZero &= Mask; 12649 KnownOne &= Mask; 12650 return; 12651 } 12652 } 12653 } 12654 12655 //===----------------------------------------------------------------------===// 12656 // ARM Inline Assembly Support 12657 //===----------------------------------------------------------------------===// 12658 12659 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 12660 // Looking for "rev" which is V6+. 12661 if (!Subtarget->hasV6Ops()) 12662 return false; 12663 12664 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 12665 std::string AsmStr = IA->getAsmString(); 12666 SmallVector<StringRef, 4> AsmPieces; 12667 SplitString(AsmStr, AsmPieces, ";\n"); 12668 12669 switch (AsmPieces.size()) { 12670 default: return false; 12671 case 1: 12672 AsmStr = AsmPieces[0]; 12673 AsmPieces.clear(); 12674 SplitString(AsmStr, AsmPieces, " \t,"); 12675 12676 // rev $0, $1 12677 if (AsmPieces.size() == 3 && 12678 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 12679 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 12680 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12681 if (Ty && Ty->getBitWidth() == 32) 12682 return IntrinsicLowering::LowerToByteSwap(CI); 12683 } 12684 break; 12685 } 12686 12687 return false; 12688 } 12689 12690 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 12691 // At this point, we have to lower this constraint to something else, so we 12692 // lower it to an "r" or "w". However, by doing this we will force the result 12693 // to be in register, while the X constraint is much more permissive. 12694 // 12695 // Although we are correct (we are free to emit anything, without 12696 // constraints), we might break use cases that would expect us to be more 12697 // efficient and emit something else. 12698 if (!Subtarget->hasVFP2()) 12699 return "r"; 12700 if (ConstraintVT.isFloatingPoint()) 12701 return "w"; 12702 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 12703 (ConstraintVT.getSizeInBits() == 64 || 12704 ConstraintVT.getSizeInBits() == 128)) 12705 return "w"; 12706 12707 return "r"; 12708 } 12709 12710 /// getConstraintType - Given a constraint letter, return the type of 12711 /// constraint it is for this target. 12712 ARMTargetLowering::ConstraintType 12713 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 12714 if (Constraint.size() == 1) { 12715 switch (Constraint[0]) { 12716 default: break; 12717 case 'l': return C_RegisterClass; 12718 case 'w': return C_RegisterClass; 12719 case 'h': return C_RegisterClass; 12720 case 'x': return C_RegisterClass; 12721 case 't': return C_RegisterClass; 12722 case 'j': return C_Other; // Constant for movw. 12723 // An address with a single base register. Due to the way we 12724 // currently handle addresses it is the same as an 'r' memory constraint. 12725 case 'Q': return C_Memory; 12726 } 12727 } else if (Constraint.size() == 2) { 12728 switch (Constraint[0]) { 12729 default: break; 12730 // All 'U+' constraints are addresses. 12731 case 'U': return C_Memory; 12732 } 12733 } 12734 return TargetLowering::getConstraintType(Constraint); 12735 } 12736 12737 /// Examine constraint type and operand type and determine a weight value. 12738 /// This object must already have been set up with the operand type 12739 /// and the current alternative constraint selected. 12740 TargetLowering::ConstraintWeight 12741 ARMTargetLowering::getSingleConstraintMatchWeight( 12742 AsmOperandInfo &info, const char *constraint) const { 12743 ConstraintWeight weight = CW_Invalid; 12744 Value *CallOperandVal = info.CallOperandVal; 12745 // If we don't have a value, we can't do a match, 12746 // but allow it at the lowest weight. 12747 if (!CallOperandVal) 12748 return CW_Default; 12749 Type *type = CallOperandVal->getType(); 12750 // Look at the constraint type. 12751 switch (*constraint) { 12752 default: 12753 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12754 break; 12755 case 'l': 12756 if (type->isIntegerTy()) { 12757 if (Subtarget->isThumb()) 12758 weight = CW_SpecificReg; 12759 else 12760 weight = CW_Register; 12761 } 12762 break; 12763 case 'w': 12764 if (type->isFloatingPointTy()) 12765 weight = CW_Register; 12766 break; 12767 } 12768 return weight; 12769 } 12770 12771 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 12772 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 12773 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 12774 if (Constraint.size() == 1) { 12775 // GCC ARM Constraint Letters 12776 switch (Constraint[0]) { 12777 case 'l': // Low regs or general regs. 12778 if (Subtarget->isThumb()) 12779 return RCPair(0U, &ARM::tGPRRegClass); 12780 return RCPair(0U, &ARM::GPRRegClass); 12781 case 'h': // High regs or no regs. 12782 if (Subtarget->isThumb()) 12783 return RCPair(0U, &ARM::hGPRRegClass); 12784 break; 12785 case 'r': 12786 if (Subtarget->isThumb1Only()) 12787 return RCPair(0U, &ARM::tGPRRegClass); 12788 return RCPair(0U, &ARM::GPRRegClass); 12789 case 'w': 12790 if (VT == MVT::Other) 12791 break; 12792 if (VT == MVT::f32) 12793 return RCPair(0U, &ARM::SPRRegClass); 12794 if (VT.getSizeInBits() == 64) 12795 return RCPair(0U, &ARM::DPRRegClass); 12796 if (VT.getSizeInBits() == 128) 12797 return RCPair(0U, &ARM::QPRRegClass); 12798 break; 12799 case 'x': 12800 if (VT == MVT::Other) 12801 break; 12802 if (VT == MVT::f32) 12803 return RCPair(0U, &ARM::SPR_8RegClass); 12804 if (VT.getSizeInBits() == 64) 12805 return RCPair(0U, &ARM::DPR_8RegClass); 12806 if (VT.getSizeInBits() == 128) 12807 return RCPair(0U, &ARM::QPR_8RegClass); 12808 break; 12809 case 't': 12810 if (VT == MVT::f32) 12811 return RCPair(0U, &ARM::SPRRegClass); 12812 break; 12813 } 12814 } 12815 if (StringRef("{cc}").equals_lower(Constraint)) 12816 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 12817 12818 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12819 } 12820 12821 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12822 /// vector. If it is invalid, don't add anything to Ops. 12823 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12824 std::string &Constraint, 12825 std::vector<SDValue>&Ops, 12826 SelectionDAG &DAG) const { 12827 SDValue Result; 12828 12829 // Currently only support length 1 constraints. 12830 if (Constraint.length() != 1) return; 12831 12832 char ConstraintLetter = Constraint[0]; 12833 switch (ConstraintLetter) { 12834 default: break; 12835 case 'j': 12836 case 'I': case 'J': case 'K': case 'L': 12837 case 'M': case 'N': case 'O': 12838 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 12839 if (!C) 12840 return; 12841 12842 int64_t CVal64 = C->getSExtValue(); 12843 int CVal = (int) CVal64; 12844 // None of these constraints allow values larger than 32 bits. Check 12845 // that the value fits in an int. 12846 if (CVal != CVal64) 12847 return; 12848 12849 switch (ConstraintLetter) { 12850 case 'j': 12851 // Constant suitable for movw, must be between 0 and 12852 // 65535. 12853 if (Subtarget->hasV6T2Ops()) 12854 if (CVal >= 0 && CVal <= 65535) 12855 break; 12856 return; 12857 case 'I': 12858 if (Subtarget->isThumb1Only()) { 12859 // This must be a constant between 0 and 255, for ADD 12860 // immediates. 12861 if (CVal >= 0 && CVal <= 255) 12862 break; 12863 } else if (Subtarget->isThumb2()) { 12864 // A constant that can be used as an immediate value in a 12865 // data-processing instruction. 12866 if (ARM_AM::getT2SOImmVal(CVal) != -1) 12867 break; 12868 } else { 12869 // A constant that can be used as an immediate value in a 12870 // data-processing instruction. 12871 if (ARM_AM::getSOImmVal(CVal) != -1) 12872 break; 12873 } 12874 return; 12875 12876 case 'J': 12877 if (Subtarget->isThumb1Only()) { 12878 // This must be a constant between -255 and -1, for negated ADD 12879 // immediates. This can be used in GCC with an "n" modifier that 12880 // prints the negated value, for use with SUB instructions. It is 12881 // not useful otherwise but is implemented for compatibility. 12882 if (CVal >= -255 && CVal <= -1) 12883 break; 12884 } else { 12885 // This must be a constant between -4095 and 4095. It is not clear 12886 // what this constraint is intended for. Implemented for 12887 // compatibility with GCC. 12888 if (CVal >= -4095 && CVal <= 4095) 12889 break; 12890 } 12891 return; 12892 12893 case 'K': 12894 if (Subtarget->isThumb1Only()) { 12895 // A 32-bit value where only one byte has a nonzero value. Exclude 12896 // zero to match GCC. This constraint is used by GCC internally for 12897 // constants that can be loaded with a move/shift combination. 12898 // It is not useful otherwise but is implemented for compatibility. 12899 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 12900 break; 12901 } else if (Subtarget->isThumb2()) { 12902 // A constant whose bitwise inverse can be used as an immediate 12903 // value in a data-processing instruction. This can be used in GCC 12904 // with a "B" modifier that prints the inverted value, for use with 12905 // BIC and MVN instructions. It is not useful otherwise but is 12906 // implemented for compatibility. 12907 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 12908 break; 12909 } else { 12910 // A constant whose bitwise inverse can be used as an immediate 12911 // value in a data-processing instruction. This can be used in GCC 12912 // with a "B" modifier that prints the inverted value, for use with 12913 // BIC and MVN instructions. It is not useful otherwise but is 12914 // implemented for compatibility. 12915 if (ARM_AM::getSOImmVal(~CVal) != -1) 12916 break; 12917 } 12918 return; 12919 12920 case 'L': 12921 if (Subtarget->isThumb1Only()) { 12922 // This must be a constant between -7 and 7, 12923 // for 3-operand ADD/SUB immediate instructions. 12924 if (CVal >= -7 && CVal < 7) 12925 break; 12926 } else if (Subtarget->isThumb2()) { 12927 // A constant whose negation can be used as an immediate value in a 12928 // data-processing instruction. This can be used in GCC with an "n" 12929 // modifier that prints the negated value, for use with SUB 12930 // instructions. It is not useful otherwise but is implemented for 12931 // compatibility. 12932 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 12933 break; 12934 } else { 12935 // A constant whose negation can be used as an immediate value in a 12936 // data-processing instruction. This can be used in GCC with an "n" 12937 // modifier that prints the negated value, for use with SUB 12938 // instructions. It is not useful otherwise but is implemented for 12939 // compatibility. 12940 if (ARM_AM::getSOImmVal(-CVal) != -1) 12941 break; 12942 } 12943 return; 12944 12945 case 'M': 12946 if (Subtarget->isThumb1Only()) { 12947 // This must be a multiple of 4 between 0 and 1020, for 12948 // ADD sp + immediate. 12949 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 12950 break; 12951 } else { 12952 // A power of two or a constant between 0 and 32. This is used in 12953 // GCC for the shift amount on shifted register operands, but it is 12954 // useful in general for any shift amounts. 12955 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 12956 break; 12957 } 12958 return; 12959 12960 case 'N': 12961 if (Subtarget->isThumb()) { // FIXME thumb2 12962 // This must be a constant between 0 and 31, for shift amounts. 12963 if (CVal >= 0 && CVal <= 31) 12964 break; 12965 } 12966 return; 12967 12968 case 'O': 12969 if (Subtarget->isThumb()) { // FIXME thumb2 12970 // This must be a multiple of 4 between -508 and 508, for 12971 // ADD/SUB sp = sp + immediate. 12972 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 12973 break; 12974 } 12975 return; 12976 } 12977 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 12978 break; 12979 } 12980 12981 if (Result.getNode()) { 12982 Ops.push_back(Result); 12983 return; 12984 } 12985 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12986 } 12987 12988 static RTLIB::Libcall getDivRemLibcall( 12989 const SDNode *N, MVT::SimpleValueType SVT) { 12990 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12991 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12992 "Unhandled Opcode in getDivRemLibcall"); 12993 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12994 N->getOpcode() == ISD::SREM; 12995 RTLIB::Libcall LC; 12996 switch (SVT) { 12997 default: llvm_unreachable("Unexpected request for libcall!"); 12998 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 12999 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13000 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13001 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13002 } 13003 return LC; 13004 } 13005 13006 static TargetLowering::ArgListTy getDivRemArgList( 13007 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13008 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13009 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13010 "Unhandled Opcode in getDivRemArgList"); 13011 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13012 N->getOpcode() == ISD::SREM; 13013 TargetLowering::ArgListTy Args; 13014 TargetLowering::ArgListEntry Entry; 13015 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13016 EVT ArgVT = N->getOperand(i).getValueType(); 13017 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13018 Entry.Node = N->getOperand(i); 13019 Entry.Ty = ArgTy; 13020 Entry.IsSExt = isSigned; 13021 Entry.IsZExt = !isSigned; 13022 Args.push_back(Entry); 13023 } 13024 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13025 std::swap(Args[0], Args[1]); 13026 return Args; 13027 } 13028 13029 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13030 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13031 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13032 Subtarget->isTargetWindows()) && 13033 "Register-based DivRem lowering only"); 13034 unsigned Opcode = Op->getOpcode(); 13035 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13036 "Invalid opcode for Div/Rem lowering"); 13037 bool isSigned = (Opcode == ISD::SDIVREM); 13038 EVT VT = Op->getValueType(0); 13039 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13040 SDLoc dl(Op); 13041 13042 // If the target has hardware divide, use divide + multiply + subtract: 13043 // div = a / b 13044 // rem = a - b * div 13045 // return {div, rem} 13046 // This should be lowered into UDIV/SDIV + MLS later on. 13047 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13048 : Subtarget->hasDivideInARMMode(); 13049 if (hasDivide && Op->getValueType(0).isSimple() && 13050 Op->getSimpleValueType(0) == MVT::i32) { 13051 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13052 const SDValue Dividend = Op->getOperand(0); 13053 const SDValue Divisor = Op->getOperand(1); 13054 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13055 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13056 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13057 13058 SDValue Values[2] = {Div, Rem}; 13059 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13060 } 13061 13062 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13063 VT.getSimpleVT().SimpleTy); 13064 SDValue InChain = DAG.getEntryNode(); 13065 13066 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13067 DAG.getContext(), 13068 Subtarget); 13069 13070 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13071 getPointerTy(DAG.getDataLayout())); 13072 13073 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 13074 13075 if (Subtarget->isTargetWindows()) 13076 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13077 13078 TargetLowering::CallLoweringInfo CLI(DAG); 13079 CLI.setDebugLoc(dl).setChain(InChain) 13080 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13081 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13082 13083 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13084 return CallInfo.first; 13085 } 13086 13087 // Lowers REM using divmod helpers 13088 // see RTABI section 4.2/4.3 13089 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13090 // Build return types (div and rem) 13091 std::vector<Type*> RetTyParams; 13092 Type *RetTyElement; 13093 13094 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13095 default: llvm_unreachable("Unexpected request for libcall!"); 13096 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13097 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13098 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13099 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13100 } 13101 13102 RetTyParams.push_back(RetTyElement); 13103 RetTyParams.push_back(RetTyElement); 13104 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13105 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13106 13107 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13108 SimpleTy); 13109 SDValue InChain = DAG.getEntryNode(); 13110 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13111 Subtarget); 13112 bool isSigned = N->getOpcode() == ISD::SREM; 13113 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13114 getPointerTy(DAG.getDataLayout())); 13115 13116 if (Subtarget->isTargetWindows()) 13117 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13118 13119 // Lower call 13120 CallLoweringInfo CLI(DAG); 13121 CLI.setChain(InChain) 13122 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13123 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13124 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13125 13126 // Return second (rem) result operand (first contains div) 13127 SDNode *ResNode = CallResult.first.getNode(); 13128 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13129 return ResNode->getOperand(1); 13130 } 13131 13132 SDValue 13133 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13134 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13135 SDLoc DL(Op); 13136 13137 // Get the inputs. 13138 SDValue Chain = Op.getOperand(0); 13139 SDValue Size = Op.getOperand(1); 13140 13141 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 13142 DAG.getConstant(2, DL, MVT::i32)); 13143 13144 SDValue Flag; 13145 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 13146 Flag = Chain.getValue(1); 13147 13148 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13149 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 13150 13151 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13152 Chain = NewSP.getValue(1); 13153 13154 SDValue Ops[2] = { NewSP, Chain }; 13155 return DAG.getMergeValues(Ops, DL); 13156 } 13157 13158 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 13159 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 13160 "Unexpected type for custom-lowering FP_EXTEND"); 13161 13162 RTLIB::Libcall LC; 13163 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 13164 13165 SDValue SrcVal = Op.getOperand(0); 13166 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13167 SDLoc(Op)).first; 13168 } 13169 13170 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 13171 assert(Op.getOperand(0).getValueType() == MVT::f64 && 13172 Subtarget->isFPOnlySP() && 13173 "Unexpected type for custom-lowering FP_ROUND"); 13174 13175 RTLIB::Libcall LC; 13176 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 13177 13178 SDValue SrcVal = Op.getOperand(0); 13179 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13180 SDLoc(Op)).first; 13181 } 13182 13183 bool 13184 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13185 // The ARM target isn't yet aware of offsets. 13186 return false; 13187 } 13188 13189 bool ARM::isBitFieldInvertedMask(unsigned v) { 13190 if (v == 0xffffffff) 13191 return false; 13192 13193 // there can be 1's on either or both "outsides", all the "inside" 13194 // bits must be 0's 13195 return isShiftedMask_32(~v); 13196 } 13197 13198 /// isFPImmLegal - Returns true if the target can instruction select the 13199 /// specified FP immediate natively. If false, the legalizer will 13200 /// materialize the FP immediate as a load from a constant pool. 13201 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13202 if (!Subtarget->hasVFP3()) 13203 return false; 13204 if (VT == MVT::f32) 13205 return ARM_AM::getFP32Imm(Imm) != -1; 13206 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 13207 return ARM_AM::getFP64Imm(Imm) != -1; 13208 return false; 13209 } 13210 13211 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 13212 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 13213 /// specified in the intrinsic calls. 13214 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13215 const CallInst &I, 13216 unsigned Intrinsic) const { 13217 switch (Intrinsic) { 13218 case Intrinsic::arm_neon_vld1: 13219 case Intrinsic::arm_neon_vld2: 13220 case Intrinsic::arm_neon_vld3: 13221 case Intrinsic::arm_neon_vld4: 13222 case Intrinsic::arm_neon_vld2lane: 13223 case Intrinsic::arm_neon_vld3lane: 13224 case Intrinsic::arm_neon_vld4lane: { 13225 Info.opc = ISD::INTRINSIC_W_CHAIN; 13226 // Conservatively set memVT to the entire set of vectors loaded. 13227 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13228 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 13229 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13230 Info.ptrVal = I.getArgOperand(0); 13231 Info.offset = 0; 13232 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13233 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13234 Info.vol = false; // volatile loads with NEON intrinsics not supported 13235 Info.readMem = true; 13236 Info.writeMem = false; 13237 return true; 13238 } 13239 case Intrinsic::arm_neon_vst1: 13240 case Intrinsic::arm_neon_vst2: 13241 case Intrinsic::arm_neon_vst3: 13242 case Intrinsic::arm_neon_vst4: 13243 case Intrinsic::arm_neon_vst2lane: 13244 case Intrinsic::arm_neon_vst3lane: 13245 case Intrinsic::arm_neon_vst4lane: { 13246 Info.opc = ISD::INTRINSIC_VOID; 13247 // Conservatively set memVT to the entire set of vectors stored. 13248 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13249 unsigned NumElts = 0; 13250 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 13251 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 13252 if (!ArgTy->isVectorTy()) 13253 break; 13254 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 13255 } 13256 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13257 Info.ptrVal = I.getArgOperand(0); 13258 Info.offset = 0; 13259 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13260 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13261 Info.vol = false; // volatile stores with NEON intrinsics not supported 13262 Info.readMem = false; 13263 Info.writeMem = true; 13264 return true; 13265 } 13266 case Intrinsic::arm_ldaex: 13267 case Intrinsic::arm_ldrex: { 13268 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13269 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 13270 Info.opc = ISD::INTRINSIC_W_CHAIN; 13271 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13272 Info.ptrVal = I.getArgOperand(0); 13273 Info.offset = 0; 13274 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13275 Info.vol = true; 13276 Info.readMem = true; 13277 Info.writeMem = false; 13278 return true; 13279 } 13280 case Intrinsic::arm_stlex: 13281 case Intrinsic::arm_strex: { 13282 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13283 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 13284 Info.opc = ISD::INTRINSIC_W_CHAIN; 13285 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13286 Info.ptrVal = I.getArgOperand(1); 13287 Info.offset = 0; 13288 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13289 Info.vol = true; 13290 Info.readMem = false; 13291 Info.writeMem = true; 13292 return true; 13293 } 13294 case Intrinsic::arm_stlexd: 13295 case Intrinsic::arm_strexd: 13296 Info.opc = ISD::INTRINSIC_W_CHAIN; 13297 Info.memVT = MVT::i64; 13298 Info.ptrVal = I.getArgOperand(2); 13299 Info.offset = 0; 13300 Info.align = 8; 13301 Info.vol = true; 13302 Info.readMem = false; 13303 Info.writeMem = true; 13304 return true; 13305 13306 case Intrinsic::arm_ldaexd: 13307 case Intrinsic::arm_ldrexd: 13308 Info.opc = ISD::INTRINSIC_W_CHAIN; 13309 Info.memVT = MVT::i64; 13310 Info.ptrVal = I.getArgOperand(0); 13311 Info.offset = 0; 13312 Info.align = 8; 13313 Info.vol = true; 13314 Info.readMem = true; 13315 Info.writeMem = false; 13316 return true; 13317 13318 default: 13319 break; 13320 } 13321 13322 return false; 13323 } 13324 13325 /// \brief Returns true if it is beneficial to convert a load of a constant 13326 /// to just the constant itself. 13327 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13328 Type *Ty) const { 13329 assert(Ty->isIntegerTy()); 13330 13331 unsigned Bits = Ty->getPrimitiveSizeInBits(); 13332 if (Bits == 0 || Bits > 32) 13333 return false; 13334 return true; 13335 } 13336 13337 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, 13338 unsigned Index) const { 13339 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 13340 return false; 13341 13342 return (Index == 0 || Index == ResVT.getVectorNumElements()); 13343 } 13344 13345 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 13346 ARM_MB::MemBOpt Domain) const { 13347 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13348 13349 // First, if the target has no DMB, see what fallback we can use. 13350 if (!Subtarget->hasDataBarrier()) { 13351 // Some ARMv6 cpus can support data barriers with an mcr instruction. 13352 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 13353 // here. 13354 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 13355 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 13356 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 13357 Builder.getInt32(0), Builder.getInt32(7), 13358 Builder.getInt32(10), Builder.getInt32(5)}; 13359 return Builder.CreateCall(MCR, args); 13360 } else { 13361 // Instead of using barriers, atomic accesses on these subtargets use 13362 // libcalls. 13363 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 13364 } 13365 } else { 13366 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 13367 // Only a full system barrier exists in the M-class architectures. 13368 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 13369 Constant *CDomain = Builder.getInt32(Domain); 13370 return Builder.CreateCall(DMB, CDomain); 13371 } 13372 } 13373 13374 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 13375 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 13376 AtomicOrdering Ord, bool IsStore, 13377 bool IsLoad) const { 13378 switch (Ord) { 13379 case AtomicOrdering::NotAtomic: 13380 case AtomicOrdering::Unordered: 13381 llvm_unreachable("Invalid fence: unordered/non-atomic"); 13382 case AtomicOrdering::Monotonic: 13383 case AtomicOrdering::Acquire: 13384 return nullptr; // Nothing to do 13385 case AtomicOrdering::SequentiallyConsistent: 13386 if (!IsStore) 13387 return nullptr; // Nothing to do 13388 /*FALLTHROUGH*/ 13389 case AtomicOrdering::Release: 13390 case AtomicOrdering::AcquireRelease: 13391 if (Subtarget->preferISHSTBarriers()) 13392 return makeDMB(Builder, ARM_MB::ISHST); 13393 // FIXME: add a comment with a link to documentation justifying this. 13394 else 13395 return makeDMB(Builder, ARM_MB::ISH); 13396 } 13397 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 13398 } 13399 13400 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 13401 AtomicOrdering Ord, bool IsStore, 13402 bool IsLoad) const { 13403 switch (Ord) { 13404 case AtomicOrdering::NotAtomic: 13405 case AtomicOrdering::Unordered: 13406 llvm_unreachable("Invalid fence: unordered/not-atomic"); 13407 case AtomicOrdering::Monotonic: 13408 case AtomicOrdering::Release: 13409 return nullptr; // Nothing to do 13410 case AtomicOrdering::Acquire: 13411 case AtomicOrdering::AcquireRelease: 13412 case AtomicOrdering::SequentiallyConsistent: 13413 return makeDMB(Builder, ARM_MB::ISH); 13414 } 13415 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 13416 } 13417 13418 // Loads and stores less than 64-bits are already atomic; ones above that 13419 // are doomed anyway, so defer to the default libcall and blame the OS when 13420 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13421 // anything for those. 13422 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13423 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13424 return (Size == 64) && !Subtarget->isMClass(); 13425 } 13426 13427 // Loads and stores less than 64-bits are already atomic; ones above that 13428 // are doomed anyway, so defer to the default libcall and blame the OS when 13429 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13430 // anything for those. 13431 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 13432 // guarantee, see DDI0406C ARM architecture reference manual, 13433 // sections A8.8.72-74 LDRD) 13434 TargetLowering::AtomicExpansionKind 13435 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13436 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13437 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 13438 : AtomicExpansionKind::None; 13439 } 13440 13441 // For the real atomic operations, we have ldrex/strex up to 32 bits, 13442 // and up to 64 bits on the non-M profiles 13443 TargetLowering::AtomicExpansionKind 13444 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13445 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13446 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13447 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 13448 ? AtomicExpansionKind::LLSC 13449 : AtomicExpansionKind::None; 13450 } 13451 13452 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 13453 AtomicCmpXchgInst *AI) const { 13454 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13455 // implement cmpxchg without spilling. If the address being exchanged is also 13456 // on the stack and close enough to the spill slot, this can lead to a 13457 // situation where the monitor always gets cleared and the atomic operation 13458 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13459 bool hasAtomicCmpXchg = 13460 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13461 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 13462 } 13463 13464 bool ARMTargetLowering::shouldInsertFencesForAtomic( 13465 const Instruction *I) const { 13466 return InsertFencesForAtomic; 13467 } 13468 13469 // This has so far only been implemented for MachO. 13470 bool ARMTargetLowering::useLoadStackGuardNode() const { 13471 return Subtarget->isTargetMachO(); 13472 } 13473 13474 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 13475 unsigned &Cost) const { 13476 // If we do not have NEON, vector types are not natively supported. 13477 if (!Subtarget->hasNEON()) 13478 return false; 13479 13480 // Floating point values and vector values map to the same register file. 13481 // Therefore, although we could do a store extract of a vector type, this is 13482 // better to leave at float as we have more freedom in the addressing mode for 13483 // those. 13484 if (VectorTy->isFPOrFPVectorTy()) 13485 return false; 13486 13487 // If the index is unknown at compile time, this is very expensive to lower 13488 // and it is not possible to combine the store with the extract. 13489 if (!isa<ConstantInt>(Idx)) 13490 return false; 13491 13492 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 13493 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 13494 // We can do a store + vector extract on any vector that fits perfectly in a D 13495 // or Q register. 13496 if (BitWidth == 64 || BitWidth == 128) { 13497 Cost = 0; 13498 return true; 13499 } 13500 return false; 13501 } 13502 13503 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 13504 return Subtarget->hasV6T2Ops(); 13505 } 13506 13507 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 13508 return Subtarget->hasV6T2Ops(); 13509 } 13510 13511 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13512 AtomicOrdering Ord) const { 13513 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13514 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13515 bool IsAcquire = isAcquireOrStronger(Ord); 13516 13517 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 13518 // intrinsic must return {i32, i32} and we have to recombine them into a 13519 // single i64 here. 13520 if (ValTy->getPrimitiveSizeInBits() == 64) { 13521 Intrinsic::ID Int = 13522 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 13523 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 13524 13525 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13526 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 13527 13528 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13529 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13530 if (!Subtarget->isLittle()) 13531 std::swap (Lo, Hi); 13532 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13533 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13534 return Builder.CreateOr( 13535 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 13536 } 13537 13538 Type *Tys[] = { Addr->getType() }; 13539 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 13540 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 13541 13542 return Builder.CreateTruncOrBitCast( 13543 Builder.CreateCall(Ldrex, Addr), 13544 cast<PointerType>(Addr->getType())->getElementType()); 13545 } 13546 13547 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13548 IRBuilder<> &Builder) const { 13549 if (!Subtarget->hasV7Ops()) 13550 return; 13551 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13552 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 13553 } 13554 13555 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 13556 Value *Addr, 13557 AtomicOrdering Ord) const { 13558 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13559 bool IsRelease = isReleaseOrStronger(Ord); 13560 13561 // Since the intrinsics must have legal type, the i64 intrinsics take two 13562 // parameters: "i32, i32". We must marshal Val into the appropriate form 13563 // before the call. 13564 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 13565 Intrinsic::ID Int = 13566 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 13567 Function *Strex = Intrinsic::getDeclaration(M, Int); 13568 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 13569 13570 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 13571 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 13572 if (!Subtarget->isLittle()) 13573 std::swap (Lo, Hi); 13574 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13575 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 13576 } 13577 13578 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 13579 Type *Tys[] = { Addr->getType() }; 13580 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 13581 13582 return Builder.CreateCall( 13583 Strex, {Builder.CreateZExtOrBitCast( 13584 Val, Strex->getFunctionType()->getParamType(0)), 13585 Addr}); 13586 } 13587 13588 /// A helper function for determining the number of interleaved accesses we 13589 /// will generate when lowering accesses of the given type. 13590 unsigned 13591 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 13592 const DataLayout &DL) const { 13593 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 13594 } 13595 13596 bool ARMTargetLowering::isLegalInterleavedAccessType( 13597 VectorType *VecTy, const DataLayout &DL) const { 13598 13599 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 13600 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 13601 13602 // Ensure the vector doesn't have f16 elements. Even though we could do an 13603 // i16 vldN, we can't hold the f16 vectors and will end up converting via 13604 // f32. 13605 if (VecTy->getElementType()->isHalfTy()) 13606 return false; 13607 13608 // Ensure the number of vector elements is greater than 1. 13609 if (VecTy->getNumElements() < 2) 13610 return false; 13611 13612 // Ensure the element type is legal. 13613 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 13614 return false; 13615 13616 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 13617 // 128 will be split into multiple interleaved accesses. 13618 return VecSize == 64 || VecSize % 128 == 0; 13619 } 13620 13621 /// \brief Lower an interleaved load into a vldN intrinsic. 13622 /// 13623 /// E.g. Lower an interleaved load (Factor = 2): 13624 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 13625 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 13626 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 13627 /// 13628 /// Into: 13629 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 13630 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 13631 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 13632 bool ARMTargetLowering::lowerInterleavedLoad( 13633 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 13634 ArrayRef<unsigned> Indices, unsigned Factor) const { 13635 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13636 "Invalid interleave factor"); 13637 assert(!Shuffles.empty() && "Empty shufflevector input"); 13638 assert(Shuffles.size() == Indices.size() && 13639 "Unmatched number of shufflevectors and indices"); 13640 13641 VectorType *VecTy = Shuffles[0]->getType(); 13642 Type *EltTy = VecTy->getVectorElementType(); 13643 13644 const DataLayout &DL = LI->getModule()->getDataLayout(); 13645 13646 // Skip if we do not have NEON and skip illegal vector types. We can 13647 // "legalize" wide vector types into multiple interleaved accesses as long as 13648 // the vector types are divisible by 128. 13649 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 13650 return false; 13651 13652 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 13653 13654 // A pointer vector can not be the return type of the ldN intrinsics. Need to 13655 // load integer vectors first and then convert to pointer vectors. 13656 if (EltTy->isPointerTy()) 13657 VecTy = 13658 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 13659 13660 IRBuilder<> Builder(LI); 13661 13662 // The base address of the load. 13663 Value *BaseAddr = LI->getPointerOperand(); 13664 13665 if (NumLoads > 1) { 13666 // If we're going to generate more than one load, reset the sub-vector type 13667 // to something legal. 13668 VecTy = VectorType::get(VecTy->getVectorElementType(), 13669 VecTy->getVectorNumElements() / NumLoads); 13670 13671 // We will compute the pointer operand of each load from the original base 13672 // address using GEPs. Cast the base address to a pointer to the scalar 13673 // element type. 13674 BaseAddr = Builder.CreateBitCast( 13675 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 13676 LI->getPointerAddressSpace())); 13677 } 13678 13679 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 13680 13681 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 13682 Type *Tys[] = {VecTy, Int8Ptr}; 13683 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 13684 Intrinsic::arm_neon_vld3, 13685 Intrinsic::arm_neon_vld4}; 13686 Function *VldnFunc = 13687 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 13688 13689 // Holds sub-vectors extracted from the load intrinsic return values. The 13690 // sub-vectors are associated with the shufflevector instructions they will 13691 // replace. 13692 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 13693 13694 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 13695 13696 // If we're generating more than one load, compute the base address of 13697 // subsequent loads as an offset from the previous. 13698 if (LoadCount > 0) 13699 BaseAddr = Builder.CreateConstGEP1_32( 13700 BaseAddr, VecTy->getVectorNumElements() * Factor); 13701 13702 SmallVector<Value *, 2> Ops; 13703 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 13704 Ops.push_back(Builder.getInt32(LI->getAlignment())); 13705 13706 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 13707 13708 // Replace uses of each shufflevector with the corresponding vector loaded 13709 // by ldN. 13710 for (unsigned i = 0; i < Shuffles.size(); i++) { 13711 ShuffleVectorInst *SV = Shuffles[i]; 13712 unsigned Index = Indices[i]; 13713 13714 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 13715 13716 // Convert the integer vector to pointer vector if the element is pointer. 13717 if (EltTy->isPointerTy()) 13718 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 13719 13720 SubVecs[SV].push_back(SubVec); 13721 } 13722 } 13723 13724 // Replace uses of the shufflevector instructions with the sub-vectors 13725 // returned by the load intrinsic. If a shufflevector instruction is 13726 // associated with more than one sub-vector, those sub-vectors will be 13727 // concatenated into a single wide vector. 13728 for (ShuffleVectorInst *SVI : Shuffles) { 13729 auto &SubVec = SubVecs[SVI]; 13730 auto *WideVec = 13731 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 13732 SVI->replaceAllUsesWith(WideVec); 13733 } 13734 13735 return true; 13736 } 13737 13738 /// \brief Lower an interleaved store into a vstN intrinsic. 13739 /// 13740 /// E.g. Lower an interleaved store (Factor = 3): 13741 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 13742 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 13743 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 13744 /// 13745 /// Into: 13746 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 13747 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 13748 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 13749 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13750 /// 13751 /// Note that the new shufflevectors will be removed and we'll only generate one 13752 /// vst3 instruction in CodeGen. 13753 /// 13754 /// Example for a more general valid mask (Factor 3). Lower: 13755 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 13756 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 13757 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 13758 /// 13759 /// Into: 13760 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 13761 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 13762 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 13763 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13764 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 13765 ShuffleVectorInst *SVI, 13766 unsigned Factor) const { 13767 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13768 "Invalid interleave factor"); 13769 13770 VectorType *VecTy = SVI->getType(); 13771 assert(VecTy->getVectorNumElements() % Factor == 0 && 13772 "Invalid interleaved store"); 13773 13774 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 13775 Type *EltTy = VecTy->getVectorElementType(); 13776 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 13777 13778 const DataLayout &DL = SI->getModule()->getDataLayout(); 13779 13780 // Skip if we do not have NEON and skip illegal vector types. We can 13781 // "legalize" wide vector types into multiple interleaved accesses as long as 13782 // the vector types are divisible by 128. 13783 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 13784 return false; 13785 13786 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 13787 13788 Value *Op0 = SVI->getOperand(0); 13789 Value *Op1 = SVI->getOperand(1); 13790 IRBuilder<> Builder(SI); 13791 13792 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 13793 // vectors to integer vectors. 13794 if (EltTy->isPointerTy()) { 13795 Type *IntTy = DL.getIntPtrType(EltTy); 13796 13797 // Convert to the corresponding integer vector. 13798 Type *IntVecTy = 13799 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 13800 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 13801 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 13802 13803 SubVecTy = VectorType::get(IntTy, LaneLen); 13804 } 13805 13806 // The base address of the store. 13807 Value *BaseAddr = SI->getPointerOperand(); 13808 13809 if (NumStores > 1) { 13810 // If we're going to generate more than one store, reset the lane length 13811 // and sub-vector type to something legal. 13812 LaneLen /= NumStores; 13813 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 13814 13815 // We will compute the pointer operand of each store from the original base 13816 // address using GEPs. Cast the base address to a pointer to the scalar 13817 // element type. 13818 BaseAddr = Builder.CreateBitCast( 13819 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 13820 SI->getPointerAddressSpace())); 13821 } 13822 13823 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 13824 13825 auto Mask = SVI->getShuffleMask(); 13826 13827 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 13828 Type *Tys[] = {Int8Ptr, SubVecTy}; 13829 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 13830 Intrinsic::arm_neon_vst3, 13831 Intrinsic::arm_neon_vst4}; 13832 13833 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 13834 13835 // If we generating more than one store, we compute the base address of 13836 // subsequent stores as an offset from the previous. 13837 if (StoreCount > 0) 13838 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 13839 13840 SmallVector<Value *, 6> Ops; 13841 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 13842 13843 Function *VstNFunc = 13844 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 13845 13846 // Split the shufflevector operands into sub vectors for the new vstN call. 13847 for (unsigned i = 0; i < Factor; i++) { 13848 unsigned IdxI = StoreCount * LaneLen * Factor + i; 13849 if (Mask[IdxI] >= 0) { 13850 Ops.push_back(Builder.CreateShuffleVector( 13851 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 13852 } else { 13853 unsigned StartMask = 0; 13854 for (unsigned j = 1; j < LaneLen; j++) { 13855 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 13856 if (Mask[IdxJ * Factor + IdxI] >= 0) { 13857 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 13858 break; 13859 } 13860 } 13861 // Note: If all elements in a chunk are undefs, StartMask=0! 13862 // Note: Filling undef gaps with random elements is ok, since 13863 // those elements were being written anyway (with undefs). 13864 // In the case of all undefs we're defaulting to using elems from 0 13865 // Note: StartMask cannot be negative, it's checked in 13866 // isReInterleaveMask 13867 Ops.push_back(Builder.CreateShuffleVector( 13868 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 13869 } 13870 } 13871 13872 Ops.push_back(Builder.getInt32(SI->getAlignment())); 13873 Builder.CreateCall(VstNFunc, Ops); 13874 } 13875 return true; 13876 } 13877 13878 enum HABaseType { 13879 HA_UNKNOWN = 0, 13880 HA_FLOAT, 13881 HA_DOUBLE, 13882 HA_VECT64, 13883 HA_VECT128 13884 }; 13885 13886 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 13887 uint64_t &Members) { 13888 if (auto *ST = dyn_cast<StructType>(Ty)) { 13889 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 13890 uint64_t SubMembers = 0; 13891 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 13892 return false; 13893 Members += SubMembers; 13894 } 13895 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 13896 uint64_t SubMembers = 0; 13897 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 13898 return false; 13899 Members += SubMembers * AT->getNumElements(); 13900 } else if (Ty->isFloatTy()) { 13901 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 13902 return false; 13903 Members = 1; 13904 Base = HA_FLOAT; 13905 } else if (Ty->isDoubleTy()) { 13906 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 13907 return false; 13908 Members = 1; 13909 Base = HA_DOUBLE; 13910 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 13911 Members = 1; 13912 switch (Base) { 13913 case HA_FLOAT: 13914 case HA_DOUBLE: 13915 return false; 13916 case HA_VECT64: 13917 return VT->getBitWidth() == 64; 13918 case HA_VECT128: 13919 return VT->getBitWidth() == 128; 13920 case HA_UNKNOWN: 13921 switch (VT->getBitWidth()) { 13922 case 64: 13923 Base = HA_VECT64; 13924 return true; 13925 case 128: 13926 Base = HA_VECT128; 13927 return true; 13928 default: 13929 return false; 13930 } 13931 } 13932 } 13933 13934 return (Members > 0 && Members <= 4); 13935 } 13936 13937 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 13938 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 13939 /// passing according to AAPCS rules. 13940 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 13941 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 13942 if (getEffectiveCallingConv(CallConv, isVarArg) != 13943 CallingConv::ARM_AAPCS_VFP) 13944 return false; 13945 13946 HABaseType Base = HA_UNKNOWN; 13947 uint64_t Members = 0; 13948 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 13949 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 13950 13951 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 13952 return IsHA || IsIntArray; 13953 } 13954 13955 unsigned ARMTargetLowering::getExceptionPointerRegister( 13956 const Constant *PersonalityFn) const { 13957 // Platforms which do not use SjLj EH may return values in these registers 13958 // via the personality function. 13959 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 13960 } 13961 13962 unsigned ARMTargetLowering::getExceptionSelectorRegister( 13963 const Constant *PersonalityFn) const { 13964 // Platforms which do not use SjLj EH may return values in these registers 13965 // via the personality function. 13966 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 13967 } 13968 13969 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13970 // Update IsSplitCSR in ARMFunctionInfo. 13971 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 13972 AFI->setIsSplitCSR(true); 13973 } 13974 13975 void ARMTargetLowering::insertCopiesSplitCSR( 13976 MachineBasicBlock *Entry, 13977 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13978 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 13979 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13980 if (!IStart) 13981 return; 13982 13983 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 13984 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13985 MachineBasicBlock::iterator MBBI = Entry->begin(); 13986 for (const MCPhysReg *I = IStart; *I; ++I) { 13987 const TargetRegisterClass *RC = nullptr; 13988 if (ARM::GPRRegClass.contains(*I)) 13989 RC = &ARM::GPRRegClass; 13990 else if (ARM::DPRRegClass.contains(*I)) 13991 RC = &ARM::DPRRegClass; 13992 else 13993 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13994 13995 unsigned NewVR = MRI->createVirtualRegister(RC); 13996 // Create copy from CSR to a virtual register. 13997 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13998 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13999 // nounwind. If we want to generalize this later, we may need to emit 14000 // CFI pseudo-instructions. 14001 assert(Entry->getParent()->getFunction()->hasFnAttribute( 14002 Attribute::NoUnwind) && 14003 "Function should be nounwind in insertCopiesSplitCSR!"); 14004 Entry->addLiveIn(*I); 14005 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14006 .addReg(*I); 14007 14008 // Insert the copy-back instructions right before the terminator. 14009 for (auto *Exit : Exits) 14010 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14011 TII->get(TargetOpcode::COPY), *I) 14012 .addReg(NewVR); 14013 } 14014 } 14015