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 "ARMISelLowering.h" 16 #include "ARMCallingConv.h" 17 #include "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMPerfectShuffle.h" 20 #include "ARMSubtarget.h" 21 #include "ARMTargetMachine.h" 22 #include "ARMTargetObjectFile.h" 23 #include "MCTargetDesc/ARMAddressingModes.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringSwitch.h" 27 #include "llvm/CodeGen/CallingConvLower.h" 28 #include "llvm/CodeGen/IntrinsicLowering.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineJumpTableInfo.h" 34 #include "llvm/CodeGen/MachineModuleInfo.h" 35 #include "llvm/CodeGen/MachineRegisterInfo.h" 36 #include "llvm/CodeGen/SelectionDAG.h" 37 #include "llvm/IR/CallingConv.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/IRBuilder.h" 42 #include "llvm/IR/Instruction.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/MC/MCSectionMachO.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/MathExtras.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include <utility> 55 using namespace llvm; 56 57 #define DEBUG_TYPE "arm-isel" 58 59 STATISTIC(NumTailCalls, "Number of tail calls"); 60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 62 63 static cl::opt<bool> 64 ARMInterworking("arm-interworking", cl::Hidden, 65 cl::desc("Enable / disable ARM interworking (for debugging only)"), 66 cl::init(true)); 67 68 namespace { 69 class ARMCCState : public CCState { 70 public: 71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 73 ParmContext PC) 74 : CCState(CC, isVarArg, MF, locs, C) { 75 assert(((PC == Call) || (PC == Prologue)) && 76 "ARMCCState users must specify whether their context is call" 77 "or prologue generation."); 78 CallOrPrologue = PC; 79 } 80 }; 81 } 82 83 // The APCS parameter registers. 84 static const MCPhysReg GPRArgRegs[] = { 85 ARM::R0, ARM::R1, ARM::R2, ARM::R3 86 }; 87 88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 89 MVT PromotedBitwiseVT) { 90 if (VT != PromotedLdStVT) { 91 setOperationAction(ISD::LOAD, VT, Promote); 92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 93 94 setOperationAction(ISD::STORE, VT, Promote); 95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 96 } 97 98 MVT ElemTy = VT.getVectorElementType(); 99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 100 setOperationAction(ISD::SETCC, VT, Custom); 101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 103 if (ElemTy == MVT::i32) { 104 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 105 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 106 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 107 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 108 } else { 109 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 110 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 111 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 112 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 113 } 114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 118 setOperationAction(ISD::SELECT, VT, Expand); 119 setOperationAction(ISD::SELECT_CC, VT, Expand); 120 setOperationAction(ISD::VSELECT, VT, Expand); 121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 122 if (VT.isInteger()) { 123 setOperationAction(ISD::SHL, VT, Custom); 124 setOperationAction(ISD::SRA, VT, Custom); 125 setOperationAction(ISD::SRL, VT, Custom); 126 } 127 128 // Promote all bit-wise operations. 129 if (VT.isInteger() && VT != PromotedBitwiseVT) { 130 setOperationAction(ISD::AND, VT, Promote); 131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 132 setOperationAction(ISD::OR, VT, Promote); 133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 134 setOperationAction(ISD::XOR, VT, Promote); 135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 136 } 137 138 // Neon does not support vector divide/remainder operations. 139 setOperationAction(ISD::SDIV, VT, Expand); 140 setOperationAction(ISD::UDIV, VT, Expand); 141 setOperationAction(ISD::FDIV, VT, Expand); 142 setOperationAction(ISD::SREM, VT, Expand); 143 setOperationAction(ISD::UREM, VT, Expand); 144 setOperationAction(ISD::FREM, VT, Expand); 145 146 if (VT.isInteger()) { 147 setOperationAction(ISD::SABSDIFF, VT, Legal); 148 setOperationAction(ISD::UABSDIFF, VT, Legal); 149 } 150 } 151 152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 153 addRegisterClass(VT, &ARM::DPRRegClass); 154 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 155 } 156 157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 158 addRegisterClass(VT, &ARM::DPairRegClass); 159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 160 } 161 162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 163 const ARMSubtarget &STI) 164 : TargetLowering(TM), Subtarget(&STI) { 165 RegInfo = Subtarget->getRegisterInfo(); 166 Itins = Subtarget->getInstrItineraryData(); 167 168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 169 170 if (Subtarget->isTargetMachO()) { 171 // Uses VFP for Thumb libfuncs if available. 172 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 174 // Single-precision floating-point arithmetic. 175 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp"); 176 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp"); 177 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp"); 178 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp"); 179 180 // Double-precision floating-point arithmetic. 181 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp"); 182 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp"); 183 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp"); 184 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp"); 185 186 // Single-precision comparisons. 187 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp"); 188 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp"); 189 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp"); 190 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp"); 191 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp"); 192 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp"); 193 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp"); 194 setLibcallName(RTLIB::O_F32, "__unordsf2vfp"); 195 196 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE); 197 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE); 198 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE); 199 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE); 200 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE); 201 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE); 202 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE); 203 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ); 204 205 // Double-precision comparisons. 206 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp"); 207 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp"); 208 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp"); 209 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp"); 210 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp"); 211 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp"); 212 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp"); 213 setLibcallName(RTLIB::O_F64, "__unorddf2vfp"); 214 215 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE); 216 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE); 217 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE); 218 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE); 219 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE); 220 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE); 221 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE); 222 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ); 223 224 // Floating-point to integer conversions. 225 // i64 conversions are done via library routines even when generating VFP 226 // instructions, so use the same ones. 227 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp"); 228 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp"); 229 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp"); 230 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp"); 231 232 // Conversions between floating types. 233 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp"); 234 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp"); 235 236 // Integer to floating-point conversions. 237 // i64 conversions are done via library routines even when generating VFP 238 // instructions, so use the same ones. 239 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 240 // e.g., __floatunsidf vs. __floatunssidfvfp. 241 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp"); 242 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp"); 243 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp"); 244 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp"); 245 } 246 } 247 248 // These libcalls are not available in 32-bit. 249 setLibcallName(RTLIB::SHL_I128, nullptr); 250 setLibcallName(RTLIB::SRL_I128, nullptr); 251 setLibcallName(RTLIB::SRA_I128, nullptr); 252 253 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() && 254 !Subtarget->isTargetWindows()) { 255 static const struct { 256 const RTLIB::Libcall Op; 257 const char * const Name; 258 const CallingConv::ID CC; 259 const ISD::CondCode Cond; 260 } LibraryCalls[] = { 261 // Double-precision floating-point arithmetic helper functions 262 // RTABI chapter 4.1.2, Table 2 263 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 264 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 265 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 266 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 267 268 // Double-precision floating-point comparison helper functions 269 // RTABI chapter 4.1.2, Table 3 270 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 271 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 272 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 273 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 274 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 275 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 276 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 277 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 278 279 // Single-precision floating-point arithmetic helper functions 280 // RTABI chapter 4.1.2, Table 4 281 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 282 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 283 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 284 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 285 286 // Single-precision floating-point comparison helper functions 287 // RTABI chapter 4.1.2, Table 5 288 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 289 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 290 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 291 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 292 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 293 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 294 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 295 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 296 297 // Floating-point to integer conversions. 298 // RTABI chapter 4.1.2, Table 6 299 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 300 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 301 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 302 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 303 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 304 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 305 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 306 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 307 308 // Conversions between floating types. 309 // RTABI chapter 4.1.2, Table 7 310 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 311 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 312 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 313 314 // Integer to floating-point conversions. 315 // RTABI chapter 4.1.2, Table 8 316 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 317 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 318 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 319 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 320 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 322 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 323 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 324 325 // Long long helper functions 326 // RTABI chapter 4.2, Table 9 327 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 328 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 329 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 330 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 331 332 // Integer division functions 333 // RTABI chapter 4.3.1 334 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 335 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 336 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 337 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 343 // Memory operations 344 // RTABI chapter 4.3.4 345 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 346 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 347 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 348 }; 349 350 for (const auto &LC : LibraryCalls) { 351 setLibcallName(LC.Op, LC.Name); 352 setLibcallCallingConv(LC.Op, LC.CC); 353 if (LC.Cond != ISD::SETCC_INVALID) 354 setCmpLibcallCC(LC.Op, LC.Cond); 355 } 356 } 357 358 if (Subtarget->isTargetWindows()) { 359 static const struct { 360 const RTLIB::Libcall Op; 361 const char * const Name; 362 const CallingConv::ID CC; 363 } LibraryCalls[] = { 364 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 365 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 366 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 367 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 368 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 369 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 370 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 371 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 372 }; 373 374 for (const auto &LC : LibraryCalls) { 375 setLibcallName(LC.Op, LC.Name); 376 setLibcallCallingConv(LC.Op, LC.CC); 377 } 378 } 379 380 // Use divmod compiler-rt calls for iOS 5.0 and later. 381 if (Subtarget->getTargetTriple().isiOS() && 382 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) { 383 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 384 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 385 } 386 387 // The half <-> float conversion functions are always soft-float, but are 388 // needed for some targets which use a hard-float calling convention by 389 // default. 390 if (Subtarget->isAAPCS_ABI()) { 391 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 392 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 393 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 394 } else { 395 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 396 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 397 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 398 } 399 400 if (Subtarget->isThumb1Only()) 401 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 402 else 403 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 404 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 405 !Subtarget->isThumb1Only()) { 406 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 407 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 408 } 409 410 for (MVT VT : MVT::vector_valuetypes()) { 411 for (MVT InnerVT : MVT::vector_valuetypes()) { 412 setTruncStoreAction(VT, InnerVT, Expand); 413 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 414 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 415 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 416 } 417 418 setOperationAction(ISD::MULHS, VT, Expand); 419 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 420 setOperationAction(ISD::MULHU, VT, Expand); 421 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 422 423 setOperationAction(ISD::BSWAP, VT, Expand); 424 } 425 426 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 427 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 428 429 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 430 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 431 432 if (Subtarget->hasNEON()) { 433 addDRTypeForNEON(MVT::v2f32); 434 addDRTypeForNEON(MVT::v8i8); 435 addDRTypeForNEON(MVT::v4i16); 436 addDRTypeForNEON(MVT::v2i32); 437 addDRTypeForNEON(MVT::v1i64); 438 439 addQRTypeForNEON(MVT::v4f32); 440 addQRTypeForNEON(MVT::v2f64); 441 addQRTypeForNEON(MVT::v16i8); 442 addQRTypeForNEON(MVT::v8i16); 443 addQRTypeForNEON(MVT::v4i32); 444 addQRTypeForNEON(MVT::v2i64); 445 446 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 447 // neither Neon nor VFP support any arithmetic operations on it. 448 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 449 // supported for v4f32. 450 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 451 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 452 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 453 // FIXME: Code duplication: FDIV and FREM are expanded always, see 454 // ARMTargetLowering::addTypeForNEON method for details. 455 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 456 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 457 // FIXME: Create unittest. 458 // In another words, find a way when "copysign" appears in DAG with vector 459 // operands. 460 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 461 // FIXME: Code duplication: SETCC has custom operation action, see 462 // ARMTargetLowering::addTypeForNEON method for details. 463 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 464 // FIXME: Create unittest for FNEG and for FABS. 465 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 466 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 467 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 468 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 469 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 470 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 471 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 472 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 473 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 474 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 475 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 476 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 477 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 478 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 479 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 480 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 481 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 482 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 483 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 484 485 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 486 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 487 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 488 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 489 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 490 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 491 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 492 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 493 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 494 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 495 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 496 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 497 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 498 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 499 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 500 501 // Mark v2f32 intrinsics. 502 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 503 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 504 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 505 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 506 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 507 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 508 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 509 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 510 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 511 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 512 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 513 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 514 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 515 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 516 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 517 518 // Neon does not support some operations on v1i64 and v2i64 types. 519 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 520 // Custom handling for some quad-vector types to detect VMULL. 521 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 522 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 523 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 524 // Custom handling for some vector types to avoid expensive expansions 525 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 526 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 527 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 528 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 529 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 530 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 531 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 532 // a destination type that is wider than the source, and nor does 533 // it have a FP_TO_[SU]INT instruction with a narrower destination than 534 // source. 535 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 536 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 537 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 538 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 539 540 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 541 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 542 543 // NEON does not have single instruction CTPOP for vectors with element 544 // types wider than 8-bits. However, custom lowering can leverage the 545 // v8i8/v16i8 vcnt instruction. 546 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 547 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 548 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 549 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 550 551 // NEON does not have single instruction CTTZ for vectors. 552 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 553 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 554 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 555 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 556 557 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 558 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 559 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 560 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 561 562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 563 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 565 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 566 567 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 568 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 569 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 570 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 571 572 // NEON only has FMA instructions as of VFP4. 573 if (!Subtarget->hasVFP4()) { 574 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 575 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 576 } 577 578 setTargetDAGCombine(ISD::INTRINSIC_VOID); 579 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 580 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 581 setTargetDAGCombine(ISD::SHL); 582 setTargetDAGCombine(ISD::SRL); 583 setTargetDAGCombine(ISD::SRA); 584 setTargetDAGCombine(ISD::SIGN_EXTEND); 585 setTargetDAGCombine(ISD::ZERO_EXTEND); 586 setTargetDAGCombine(ISD::ANY_EXTEND); 587 setTargetDAGCombine(ISD::SELECT_CC); 588 setTargetDAGCombine(ISD::BUILD_VECTOR); 589 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 590 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 591 setTargetDAGCombine(ISD::STORE); 592 setTargetDAGCombine(ISD::FP_TO_SINT); 593 setTargetDAGCombine(ISD::FP_TO_UINT); 594 setTargetDAGCombine(ISD::FDIV); 595 setTargetDAGCombine(ISD::LOAD); 596 597 // It is legal to extload from v4i8 to v4i16 or v4i32. 598 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 599 MVT::v2i32}) { 600 for (MVT VT : MVT::integer_vector_valuetypes()) { 601 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 602 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 603 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 604 } 605 } 606 } 607 608 // ARM and Thumb2 support UMLAL/SMLAL. 609 if (!Subtarget->isThumb1Only()) 610 setTargetDAGCombine(ISD::ADDC); 611 612 if (Subtarget->isFPOnlySP()) { 613 // When targetting a floating-point unit with only single-precision 614 // operations, f64 is legal for the few double-precision instructions which 615 // are present However, no double-precision operations other than moves, 616 // loads and stores are provided by the hardware. 617 setOperationAction(ISD::FADD, MVT::f64, Expand); 618 setOperationAction(ISD::FSUB, MVT::f64, Expand); 619 setOperationAction(ISD::FMUL, MVT::f64, Expand); 620 setOperationAction(ISD::FMA, MVT::f64, Expand); 621 setOperationAction(ISD::FDIV, MVT::f64, Expand); 622 setOperationAction(ISD::FREM, MVT::f64, Expand); 623 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 624 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 625 setOperationAction(ISD::FNEG, MVT::f64, Expand); 626 setOperationAction(ISD::FABS, MVT::f64, Expand); 627 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 628 setOperationAction(ISD::FSIN, MVT::f64, Expand); 629 setOperationAction(ISD::FCOS, MVT::f64, Expand); 630 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 631 setOperationAction(ISD::FPOW, MVT::f64, Expand); 632 setOperationAction(ISD::FLOG, MVT::f64, Expand); 633 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 634 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 635 setOperationAction(ISD::FEXP, MVT::f64, Expand); 636 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 637 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 638 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 639 setOperationAction(ISD::FRINT, MVT::f64, Expand); 640 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 641 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 642 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 643 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 644 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 645 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 646 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 647 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 648 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 649 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 650 } 651 652 computeRegisterProperties(Subtarget->getRegisterInfo()); 653 654 // ARM does not have floating-point extending loads. 655 for (MVT VT : MVT::fp_valuetypes()) { 656 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 657 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 658 } 659 660 // ... or truncating stores 661 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 662 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 663 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 664 665 // ARM does not have i1 sign extending load. 666 for (MVT VT : MVT::integer_valuetypes()) 667 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 668 669 // ARM supports all 4 flavors of integer indexed load / store. 670 if (!Subtarget->isThumb1Only()) { 671 for (unsigned im = (unsigned)ISD::PRE_INC; 672 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 673 setIndexedLoadAction(im, MVT::i1, Legal); 674 setIndexedLoadAction(im, MVT::i8, Legal); 675 setIndexedLoadAction(im, MVT::i16, Legal); 676 setIndexedLoadAction(im, MVT::i32, Legal); 677 setIndexedStoreAction(im, MVT::i1, Legal); 678 setIndexedStoreAction(im, MVT::i8, Legal); 679 setIndexedStoreAction(im, MVT::i16, Legal); 680 setIndexedStoreAction(im, MVT::i32, Legal); 681 } 682 } 683 684 setOperationAction(ISD::SADDO, MVT::i32, Custom); 685 setOperationAction(ISD::UADDO, MVT::i32, Custom); 686 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 687 setOperationAction(ISD::USUBO, MVT::i32, Custom); 688 689 // i64 operation support. 690 setOperationAction(ISD::MUL, MVT::i64, Expand); 691 setOperationAction(ISD::MULHU, MVT::i32, Expand); 692 if (Subtarget->isThumb1Only()) { 693 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 694 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 695 } 696 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 697 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP())) 698 setOperationAction(ISD::MULHS, MVT::i32, Expand); 699 700 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 701 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 702 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 703 setOperationAction(ISD::SRL, MVT::i64, Custom); 704 setOperationAction(ISD::SRA, MVT::i64, Custom); 705 706 if (!Subtarget->isThumb1Only()) { 707 // FIXME: We should do this for Thumb1 as well. 708 setOperationAction(ISD::ADDC, MVT::i32, Custom); 709 setOperationAction(ISD::ADDE, MVT::i32, Custom); 710 setOperationAction(ISD::SUBC, MVT::i32, Custom); 711 setOperationAction(ISD::SUBE, MVT::i32, Custom); 712 } 713 714 // ARM does not have ROTL. 715 setOperationAction(ISD::ROTL, MVT::i32, Expand); 716 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 717 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 718 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 719 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 720 721 // These just redirect to CTTZ and CTLZ on ARM. 722 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand); 723 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand); 724 725 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 726 727 // Only ARMv6 has BSWAP. 728 if (!Subtarget->hasV6Ops()) 729 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 730 731 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) && 732 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) { 733 // These are expanded into libcalls if the cpu doesn't have HW divider. 734 setOperationAction(ISD::SDIV, MVT::i32, Expand); 735 setOperationAction(ISD::UDIV, MVT::i32, Expand); 736 } 737 738 // FIXME: Also set divmod for SREM on EABI 739 setOperationAction(ISD::SREM, MVT::i32, Expand); 740 setOperationAction(ISD::UREM, MVT::i32, Expand); 741 // Register based DivRem for AEABI (RTABI 4.2) 742 if (Subtarget->isTargetAEABI()) { 743 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 744 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 745 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 746 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 747 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 748 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 749 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 750 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 751 752 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 753 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 754 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 755 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 756 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 757 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 758 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 759 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 760 761 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 762 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 763 } else { 764 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 765 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 766 } 767 768 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 769 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 770 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom); 771 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 772 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 773 774 setOperationAction(ISD::TRAP, MVT::Other, Legal); 775 776 // Use the default implementation. 777 setOperationAction(ISD::VASTART, MVT::Other, Custom); 778 setOperationAction(ISD::VAARG, MVT::Other, Expand); 779 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 780 setOperationAction(ISD::VAEND, MVT::Other, Expand); 781 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 782 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 783 784 if (!Subtarget->isTargetMachO()) { 785 // Non-MachO platforms may return values in these registers via the 786 // personality function. 787 setExceptionPointerRegister(ARM::R0); 788 setExceptionSelectorRegister(ARM::R1); 789 } 790 791 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 792 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 793 else 794 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 795 796 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 797 // the default expansion. If we are targeting a single threaded system, 798 // then set them all for expand so we can lower them later into their 799 // non-atomic form. 800 if (TM.Options.ThreadModel == ThreadModel::Single) 801 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand); 802 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) { 803 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 804 // to ldrex/strex loops already. 805 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 806 807 // On v8, we have particularly efficient implementations of atomic fences 808 // if they can be combined with nearby atomic loads and stores. 809 if (!Subtarget->hasV8Ops()) { 810 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 811 setInsertFencesForAtomic(true); 812 } 813 } else { 814 // If there's anything we can use as a barrier, go through custom lowering 815 // for ATOMIC_FENCE. 816 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 817 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 818 819 // Set them all for expansion, which will force libcalls. 820 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 821 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 822 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 823 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 824 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 825 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 826 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 827 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 828 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 829 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 830 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 831 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 832 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 833 // Unordered/Monotonic case. 834 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 835 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 836 } 837 838 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 839 840 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 841 if (!Subtarget->hasV6Ops()) { 842 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 843 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 844 } 845 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 846 847 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 848 !Subtarget->isThumb1Only()) { 849 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 850 // iff target supports vfp2. 851 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 852 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 853 } 854 855 // We want to custom lower some of our intrinsics. 856 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 857 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 858 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 859 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 860 if (Subtarget->isTargetDarwin()) 861 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 862 863 setOperationAction(ISD::SETCC, MVT::i32, Expand); 864 setOperationAction(ISD::SETCC, MVT::f32, Expand); 865 setOperationAction(ISD::SETCC, MVT::f64, Expand); 866 setOperationAction(ISD::SELECT, MVT::i32, Custom); 867 setOperationAction(ISD::SELECT, MVT::f32, Custom); 868 setOperationAction(ISD::SELECT, MVT::f64, Custom); 869 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 870 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 871 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 872 873 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 874 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 875 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 876 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 877 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 878 879 // We don't support sin/cos/fmod/copysign/pow 880 setOperationAction(ISD::FSIN, MVT::f64, Expand); 881 setOperationAction(ISD::FSIN, MVT::f32, Expand); 882 setOperationAction(ISD::FCOS, MVT::f32, Expand); 883 setOperationAction(ISD::FCOS, MVT::f64, Expand); 884 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 885 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 886 setOperationAction(ISD::FREM, MVT::f64, Expand); 887 setOperationAction(ISD::FREM, MVT::f32, Expand); 888 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 889 !Subtarget->isThumb1Only()) { 890 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 891 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 892 } 893 setOperationAction(ISD::FPOW, MVT::f64, Expand); 894 setOperationAction(ISD::FPOW, MVT::f32, Expand); 895 896 if (!Subtarget->hasVFP4()) { 897 setOperationAction(ISD::FMA, MVT::f64, Expand); 898 setOperationAction(ISD::FMA, MVT::f32, Expand); 899 } 900 901 // Various VFP goodness 902 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 903 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 904 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 905 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 906 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 907 } 908 909 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 910 if (!Subtarget->hasFP16()) { 911 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 912 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 913 } 914 } 915 916 // Combine sin / cos into one node or libcall if possible. 917 if (Subtarget->hasSinCos()) { 918 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 919 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 920 if (Subtarget->getTargetTriple().isiOS()) { 921 // For iOS, we don't want to the normal expansion of a libcall to 922 // sincos. We want to issue a libcall to __sincos_stret. 923 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 924 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 925 } 926 } 927 928 // FP-ARMv8 implements a lot of rounding-like FP operations. 929 if (Subtarget->hasFPARMv8()) { 930 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 931 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 932 setOperationAction(ISD::FROUND, MVT::f32, Legal); 933 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 934 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 935 setOperationAction(ISD::FRINT, MVT::f32, Legal); 936 if (!Subtarget->isFPOnlySP()) { 937 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 938 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 939 setOperationAction(ISD::FROUND, MVT::f64, Legal); 940 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 941 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 942 setOperationAction(ISD::FRINT, MVT::f64, Legal); 943 } 944 } 945 // We have target-specific dag combine patterns for the following nodes: 946 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 947 setTargetDAGCombine(ISD::ADD); 948 setTargetDAGCombine(ISD::SUB); 949 setTargetDAGCombine(ISD::MUL); 950 setTargetDAGCombine(ISD::AND); 951 setTargetDAGCombine(ISD::OR); 952 setTargetDAGCombine(ISD::XOR); 953 954 if (Subtarget->hasV6Ops()) 955 setTargetDAGCombine(ISD::SRL); 956 957 setStackPointerRegisterToSaveRestore(ARM::SP); 958 959 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 960 !Subtarget->hasVFP2()) 961 setSchedulingPreference(Sched::RegPressure); 962 else 963 setSchedulingPreference(Sched::Hybrid); 964 965 //// temporary - rewrite interface to use type 966 MaxStoresPerMemset = 8; 967 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 968 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 969 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2; 970 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 971 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2; 972 973 // On ARM arguments smaller than 4 bytes are extended, so all arguments 974 // are at least 4 bytes aligned. 975 setMinStackArgumentAlignment(4); 976 977 // Prefer likely predicted branches to selects on out-of-order cores. 978 PredictableSelectIsExpensive = Subtarget->isLikeA9(); 979 980 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 981 } 982 983 bool ARMTargetLowering::useSoftFloat() const { 984 return Subtarget->useSoftFloat(); 985 } 986 987 // FIXME: It might make sense to define the representative register class as the 988 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 989 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 990 // SPR's representative would be DPR_VFP2. This should work well if register 991 // pressure tracking were modified such that a register use would increment the 992 // pressure of the register class's representative and all of it's super 993 // classes' representatives transitively. We have not implemented this because 994 // of the difficulty prior to coalescing of modeling operand register classes 995 // due to the common occurrence of cross class copies and subregister insertions 996 // and extractions. 997 std::pair<const TargetRegisterClass *, uint8_t> 998 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 999 MVT VT) const { 1000 const TargetRegisterClass *RRC = nullptr; 1001 uint8_t Cost = 1; 1002 switch (VT.SimpleTy) { 1003 default: 1004 return TargetLowering::findRepresentativeClass(TRI, VT); 1005 // Use DPR as representative register class for all floating point 1006 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1007 // the cost is 1 for both f32 and f64. 1008 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1009 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1010 RRC = &ARM::DPRRegClass; 1011 // When NEON is used for SP, only half of the register file is available 1012 // because operations that define both SP and DP results will be constrained 1013 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1014 // coalescing by double-counting the SP regs. See the FIXME above. 1015 if (Subtarget->useNEONForSinglePrecisionFP()) 1016 Cost = 2; 1017 break; 1018 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1019 case MVT::v4f32: case MVT::v2f64: 1020 RRC = &ARM::DPRRegClass; 1021 Cost = 2; 1022 break; 1023 case MVT::v4i64: 1024 RRC = &ARM::DPRRegClass; 1025 Cost = 4; 1026 break; 1027 case MVT::v8i64: 1028 RRC = &ARM::DPRRegClass; 1029 Cost = 8; 1030 break; 1031 } 1032 return std::make_pair(RRC, Cost); 1033 } 1034 1035 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1036 switch ((ARMISD::NodeType)Opcode) { 1037 case ARMISD::FIRST_NUMBER: break; 1038 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1039 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1040 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1041 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1042 case ARMISD::CALL: return "ARMISD::CALL"; 1043 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1044 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1045 case ARMISD::tCALL: return "ARMISD::tCALL"; 1046 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1047 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1048 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1049 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1050 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1051 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1052 case ARMISD::CMP: return "ARMISD::CMP"; 1053 case ARMISD::CMN: return "ARMISD::CMN"; 1054 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1055 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1056 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1057 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1058 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1059 1060 case ARMISD::CMOV: return "ARMISD::CMOV"; 1061 1062 case ARMISD::RBIT: return "ARMISD::RBIT"; 1063 1064 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1065 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1066 case ARMISD::RRX: return "ARMISD::RRX"; 1067 1068 case ARMISD::ADDC: return "ARMISD::ADDC"; 1069 case ARMISD::ADDE: return "ARMISD::ADDE"; 1070 case ARMISD::SUBC: return "ARMISD::SUBC"; 1071 case ARMISD::SUBE: return "ARMISD::SUBE"; 1072 1073 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1074 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1075 1076 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1077 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1078 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1079 1080 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1081 1082 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1083 1084 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1085 1086 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1087 1088 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1089 1090 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1091 1092 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1093 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1094 case ARMISD::VCGE: return "ARMISD::VCGE"; 1095 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1096 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1097 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1098 case ARMISD::VCGT: return "ARMISD::VCGT"; 1099 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1100 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1101 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1102 case ARMISD::VTST: return "ARMISD::VTST"; 1103 1104 case ARMISD::VSHL: return "ARMISD::VSHL"; 1105 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1106 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1107 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1108 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1109 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1110 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1111 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1112 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1113 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1114 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1115 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1116 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1117 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1118 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1119 case ARMISD::VSLI: return "ARMISD::VSLI"; 1120 case ARMISD::VSRI: return "ARMISD::VSRI"; 1121 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1122 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1123 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1124 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1125 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1126 case ARMISD::VDUP: return "ARMISD::VDUP"; 1127 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1128 case ARMISD::VEXT: return "ARMISD::VEXT"; 1129 case ARMISD::VREV64: return "ARMISD::VREV64"; 1130 case ARMISD::VREV32: return "ARMISD::VREV32"; 1131 case ARMISD::VREV16: return "ARMISD::VREV16"; 1132 case ARMISD::VZIP: return "ARMISD::VZIP"; 1133 case ARMISD::VUZP: return "ARMISD::VUZP"; 1134 case ARMISD::VTRN: return "ARMISD::VTRN"; 1135 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1136 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1137 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1138 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1139 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1140 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1141 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1142 case ARMISD::FMAX: return "ARMISD::FMAX"; 1143 case ARMISD::FMIN: return "ARMISD::FMIN"; 1144 case ARMISD::VMAXNM: return "ARMISD::VMAX"; 1145 case ARMISD::VMINNM: return "ARMISD::VMIN"; 1146 case ARMISD::BFI: return "ARMISD::BFI"; 1147 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1148 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1149 case ARMISD::VBSL: return "ARMISD::VBSL"; 1150 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1151 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1152 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1153 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1154 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1155 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1156 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1157 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1158 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1159 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1160 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1161 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1162 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1163 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1164 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1165 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1166 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1167 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1168 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1169 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1170 } 1171 return nullptr; 1172 } 1173 1174 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1175 EVT VT) const { 1176 if (!VT.isVector()) 1177 return getPointerTy(DL); 1178 return VT.changeVectorElementTypeToInteger(); 1179 } 1180 1181 /// getRegClassFor - Return the register class that should be used for the 1182 /// specified value type. 1183 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1184 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1185 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1186 // load / store 4 to 8 consecutive D registers. 1187 if (Subtarget->hasNEON()) { 1188 if (VT == MVT::v4i64) 1189 return &ARM::QQPRRegClass; 1190 if (VT == MVT::v8i64) 1191 return &ARM::QQQQPRRegClass; 1192 } 1193 return TargetLowering::getRegClassFor(VT); 1194 } 1195 1196 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1197 // source/dest is aligned and the copy size is large enough. We therefore want 1198 // to align such objects passed to memory intrinsics. 1199 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1200 unsigned &PrefAlign) const { 1201 if (!isa<MemIntrinsic>(CI)) 1202 return false; 1203 MinSize = 8; 1204 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1205 // cycle faster than 4-byte aligned LDM. 1206 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1207 return true; 1208 } 1209 1210 // Create a fast isel object. 1211 FastISel * 1212 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1213 const TargetLibraryInfo *libInfo) const { 1214 return ARM::createFastISel(funcInfo, libInfo); 1215 } 1216 1217 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1218 unsigned NumVals = N->getNumValues(); 1219 if (!NumVals) 1220 return Sched::RegPressure; 1221 1222 for (unsigned i = 0; i != NumVals; ++i) { 1223 EVT VT = N->getValueType(i); 1224 if (VT == MVT::Glue || VT == MVT::Other) 1225 continue; 1226 if (VT.isFloatingPoint() || VT.isVector()) 1227 return Sched::ILP; 1228 } 1229 1230 if (!N->isMachineOpcode()) 1231 return Sched::RegPressure; 1232 1233 // Load are scheduled for latency even if there instruction itinerary 1234 // is not available. 1235 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1236 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1237 1238 if (MCID.getNumDefs() == 0) 1239 return Sched::RegPressure; 1240 if (!Itins->isEmpty() && 1241 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1242 return Sched::ILP; 1243 1244 return Sched::RegPressure; 1245 } 1246 1247 //===----------------------------------------------------------------------===// 1248 // Lowering Code 1249 //===----------------------------------------------------------------------===// 1250 1251 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1252 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1253 switch (CC) { 1254 default: llvm_unreachable("Unknown condition code!"); 1255 case ISD::SETNE: return ARMCC::NE; 1256 case ISD::SETEQ: return ARMCC::EQ; 1257 case ISD::SETGT: return ARMCC::GT; 1258 case ISD::SETGE: return ARMCC::GE; 1259 case ISD::SETLT: return ARMCC::LT; 1260 case ISD::SETLE: return ARMCC::LE; 1261 case ISD::SETUGT: return ARMCC::HI; 1262 case ISD::SETUGE: return ARMCC::HS; 1263 case ISD::SETULT: return ARMCC::LO; 1264 case ISD::SETULE: return ARMCC::LS; 1265 } 1266 } 1267 1268 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1269 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1270 ARMCC::CondCodes &CondCode2) { 1271 CondCode2 = ARMCC::AL; 1272 switch (CC) { 1273 default: llvm_unreachable("Unknown FP condition!"); 1274 case ISD::SETEQ: 1275 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1276 case ISD::SETGT: 1277 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1278 case ISD::SETGE: 1279 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1280 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1281 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1282 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1283 case ISD::SETO: CondCode = ARMCC::VC; break; 1284 case ISD::SETUO: CondCode = ARMCC::VS; break; 1285 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1286 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1287 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1288 case ISD::SETLT: 1289 case ISD::SETULT: CondCode = ARMCC::LT; break; 1290 case ISD::SETLE: 1291 case ISD::SETULE: CondCode = ARMCC::LE; break; 1292 case ISD::SETNE: 1293 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1294 } 1295 } 1296 1297 //===----------------------------------------------------------------------===// 1298 // Calling Convention Implementation 1299 //===----------------------------------------------------------------------===// 1300 1301 #include "ARMGenCallingConv.inc" 1302 1303 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1304 /// account presence of floating point hardware and calling convention 1305 /// limitations, such as support for variadic functions. 1306 CallingConv::ID 1307 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1308 bool isVarArg) const { 1309 switch (CC) { 1310 default: 1311 llvm_unreachable("Unsupported calling convention"); 1312 case CallingConv::ARM_AAPCS: 1313 case CallingConv::ARM_APCS: 1314 case CallingConv::GHC: 1315 return CC; 1316 case CallingConv::ARM_AAPCS_VFP: 1317 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1318 case CallingConv::C: 1319 if (!Subtarget->isAAPCS_ABI()) 1320 return CallingConv::ARM_APCS; 1321 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1322 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1323 !isVarArg) 1324 return CallingConv::ARM_AAPCS_VFP; 1325 else 1326 return CallingConv::ARM_AAPCS; 1327 case CallingConv::Fast: 1328 if (!Subtarget->isAAPCS_ABI()) { 1329 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1330 return CallingConv::Fast; 1331 return CallingConv::ARM_APCS; 1332 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1333 return CallingConv::ARM_AAPCS_VFP; 1334 else 1335 return CallingConv::ARM_AAPCS; 1336 } 1337 } 1338 1339 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1340 /// CallingConvention. 1341 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1342 bool Return, 1343 bool isVarArg) const { 1344 switch (getEffectiveCallingConv(CC, isVarArg)) { 1345 default: 1346 llvm_unreachable("Unsupported calling convention"); 1347 case CallingConv::ARM_APCS: 1348 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1349 case CallingConv::ARM_AAPCS: 1350 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1351 case CallingConv::ARM_AAPCS_VFP: 1352 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1353 case CallingConv::Fast: 1354 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1355 case CallingConv::GHC: 1356 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1357 } 1358 } 1359 1360 /// LowerCallResult - Lower the result values of a call into the 1361 /// appropriate copies out of appropriate physical registers. 1362 SDValue 1363 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1364 CallingConv::ID CallConv, bool isVarArg, 1365 const SmallVectorImpl<ISD::InputArg> &Ins, 1366 SDLoc dl, SelectionDAG &DAG, 1367 SmallVectorImpl<SDValue> &InVals, 1368 bool isThisReturn, SDValue ThisVal) const { 1369 1370 // Assign locations to each value returned by this call. 1371 SmallVector<CCValAssign, 16> RVLocs; 1372 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1373 *DAG.getContext(), Call); 1374 CCInfo.AnalyzeCallResult(Ins, 1375 CCAssignFnForNode(CallConv, /* Return*/ true, 1376 isVarArg)); 1377 1378 // Copy all of the result registers out of their specified physreg. 1379 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1380 CCValAssign VA = RVLocs[i]; 1381 1382 // Pass 'this' value directly from the argument to return value, to avoid 1383 // reg unit interference 1384 if (i == 0 && isThisReturn) { 1385 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1386 "unexpected return calling convention register assignment"); 1387 InVals.push_back(ThisVal); 1388 continue; 1389 } 1390 1391 SDValue Val; 1392 if (VA.needsCustom()) { 1393 // Handle f64 or half of a v2f64. 1394 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1395 InFlag); 1396 Chain = Lo.getValue(1); 1397 InFlag = Lo.getValue(2); 1398 VA = RVLocs[++i]; // skip ahead to next loc 1399 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1400 InFlag); 1401 Chain = Hi.getValue(1); 1402 InFlag = Hi.getValue(2); 1403 if (!Subtarget->isLittle()) 1404 std::swap (Lo, Hi); 1405 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1406 1407 if (VA.getLocVT() == MVT::v2f64) { 1408 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1409 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1410 DAG.getConstant(0, dl, MVT::i32)); 1411 1412 VA = RVLocs[++i]; // skip ahead to next loc 1413 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1414 Chain = Lo.getValue(1); 1415 InFlag = Lo.getValue(2); 1416 VA = RVLocs[++i]; // skip ahead to next loc 1417 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1418 Chain = Hi.getValue(1); 1419 InFlag = Hi.getValue(2); 1420 if (!Subtarget->isLittle()) 1421 std::swap (Lo, Hi); 1422 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1423 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1424 DAG.getConstant(1, dl, MVT::i32)); 1425 } 1426 } else { 1427 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1428 InFlag); 1429 Chain = Val.getValue(1); 1430 InFlag = Val.getValue(2); 1431 } 1432 1433 switch (VA.getLocInfo()) { 1434 default: llvm_unreachable("Unknown loc info!"); 1435 case CCValAssign::Full: break; 1436 case CCValAssign::BCvt: 1437 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1438 break; 1439 } 1440 1441 InVals.push_back(Val); 1442 } 1443 1444 return Chain; 1445 } 1446 1447 /// LowerMemOpCallTo - Store the argument to the stack. 1448 SDValue 1449 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1450 SDValue StackPtr, SDValue Arg, 1451 SDLoc dl, SelectionDAG &DAG, 1452 const CCValAssign &VA, 1453 ISD::ArgFlagsTy Flags) const { 1454 unsigned LocMemOffset = VA.getLocMemOffset(); 1455 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1456 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1457 StackPtr, PtrOff); 1458 return DAG.getStore(Chain, dl, Arg, PtrOff, 1459 MachinePointerInfo::getStack(LocMemOffset), 1460 false, false, 0); 1461 } 1462 1463 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1464 SDValue Chain, SDValue &Arg, 1465 RegsToPassVector &RegsToPass, 1466 CCValAssign &VA, CCValAssign &NextVA, 1467 SDValue &StackPtr, 1468 SmallVectorImpl<SDValue> &MemOpChains, 1469 ISD::ArgFlagsTy Flags) const { 1470 1471 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1472 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1473 unsigned id = Subtarget->isLittle() ? 0 : 1; 1474 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1475 1476 if (NextVA.isRegLoc()) 1477 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1478 else { 1479 assert(NextVA.isMemLoc()); 1480 if (!StackPtr.getNode()) 1481 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1482 getPointerTy(DAG.getDataLayout())); 1483 1484 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1485 dl, DAG, NextVA, 1486 Flags)); 1487 } 1488 } 1489 1490 /// LowerCall - Lowering a call into a callseq_start <- 1491 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1492 /// nodes. 1493 SDValue 1494 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1495 SmallVectorImpl<SDValue> &InVals) const { 1496 SelectionDAG &DAG = CLI.DAG; 1497 SDLoc &dl = CLI.DL; 1498 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1499 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1500 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1501 SDValue Chain = CLI.Chain; 1502 SDValue Callee = CLI.Callee; 1503 bool &isTailCall = CLI.IsTailCall; 1504 CallingConv::ID CallConv = CLI.CallConv; 1505 bool doesNotRet = CLI.DoesNotReturn; 1506 bool isVarArg = CLI.IsVarArg; 1507 1508 MachineFunction &MF = DAG.getMachineFunction(); 1509 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1510 bool isThisReturn = false; 1511 bool isSibCall = false; 1512 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1513 1514 // Disable tail calls if they're not supported. 1515 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1516 isTailCall = false; 1517 1518 if (isTailCall) { 1519 // Check if it's really possible to do a tail call. 1520 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1521 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1522 Outs, OutVals, Ins, DAG); 1523 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1524 report_fatal_error("failed to perform tail call elimination on a call " 1525 "site marked musttail"); 1526 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1527 // detected sibcalls. 1528 if (isTailCall) { 1529 ++NumTailCalls; 1530 isSibCall = true; 1531 } 1532 } 1533 1534 // Analyze operands of the call, assigning locations to each operand. 1535 SmallVector<CCValAssign, 16> ArgLocs; 1536 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1537 *DAG.getContext(), Call); 1538 CCInfo.AnalyzeCallOperands(Outs, 1539 CCAssignFnForNode(CallConv, /* Return*/ false, 1540 isVarArg)); 1541 1542 // Get a count of how many bytes are to be pushed on the stack. 1543 unsigned NumBytes = CCInfo.getNextStackOffset(); 1544 1545 // For tail calls, memory operands are available in our caller's stack. 1546 if (isSibCall) 1547 NumBytes = 0; 1548 1549 // Adjust the stack pointer for the new arguments... 1550 // These operations are automatically eliminated by the prolog/epilog pass 1551 if (!isSibCall) 1552 Chain = DAG.getCALLSEQ_START(Chain, 1553 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1554 1555 SDValue StackPtr = 1556 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1557 1558 RegsToPassVector RegsToPass; 1559 SmallVector<SDValue, 8> MemOpChains; 1560 1561 // Walk the register/memloc assignments, inserting copies/loads. In the case 1562 // of tail call optimization, arguments are handled later. 1563 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1564 i != e; 1565 ++i, ++realArgIdx) { 1566 CCValAssign &VA = ArgLocs[i]; 1567 SDValue Arg = OutVals[realArgIdx]; 1568 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1569 bool isByVal = Flags.isByVal(); 1570 1571 // Promote the value if needed. 1572 switch (VA.getLocInfo()) { 1573 default: llvm_unreachable("Unknown loc info!"); 1574 case CCValAssign::Full: break; 1575 case CCValAssign::SExt: 1576 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1577 break; 1578 case CCValAssign::ZExt: 1579 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1580 break; 1581 case CCValAssign::AExt: 1582 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1583 break; 1584 case CCValAssign::BCvt: 1585 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1586 break; 1587 } 1588 1589 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1590 if (VA.needsCustom()) { 1591 if (VA.getLocVT() == MVT::v2f64) { 1592 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1593 DAG.getConstant(0, dl, MVT::i32)); 1594 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1595 DAG.getConstant(1, dl, MVT::i32)); 1596 1597 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1598 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1599 1600 VA = ArgLocs[++i]; // skip ahead to next loc 1601 if (VA.isRegLoc()) { 1602 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1603 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1604 } else { 1605 assert(VA.isMemLoc()); 1606 1607 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1608 dl, DAG, VA, Flags)); 1609 } 1610 } else { 1611 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1612 StackPtr, MemOpChains, Flags); 1613 } 1614 } else if (VA.isRegLoc()) { 1615 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1616 assert(VA.getLocVT() == MVT::i32 && 1617 "unexpected calling convention register assignment"); 1618 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1619 "unexpected use of 'returned'"); 1620 isThisReturn = true; 1621 } 1622 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1623 } else if (isByVal) { 1624 assert(VA.isMemLoc()); 1625 unsigned offset = 0; 1626 1627 // True if this byval aggregate will be split between registers 1628 // and memory. 1629 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1630 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1631 1632 if (CurByValIdx < ByValArgsCount) { 1633 1634 unsigned RegBegin, RegEnd; 1635 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1636 1637 EVT PtrVT = 1638 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1639 unsigned int i, j; 1640 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1641 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1642 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1643 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1644 MachinePointerInfo(), 1645 false, false, false, 1646 DAG.InferPtrAlignment(AddArg)); 1647 MemOpChains.push_back(Load.getValue(1)); 1648 RegsToPass.push_back(std::make_pair(j, Load)); 1649 } 1650 1651 // If parameter size outsides register area, "offset" value 1652 // helps us to calculate stack slot for remained part properly. 1653 offset = RegEnd - RegBegin; 1654 1655 CCInfo.nextInRegsParam(); 1656 } 1657 1658 if (Flags.getByValSize() > 4*offset) { 1659 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1660 unsigned LocMemOffset = VA.getLocMemOffset(); 1661 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1662 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1663 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1664 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1665 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1666 MVT::i32); 1667 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1668 MVT::i32); 1669 1670 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1671 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1672 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1673 Ops)); 1674 } 1675 } else if (!isSibCall) { 1676 assert(VA.isMemLoc()); 1677 1678 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1679 dl, DAG, VA, Flags)); 1680 } 1681 } 1682 1683 if (!MemOpChains.empty()) 1684 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1685 1686 // Build a sequence of copy-to-reg nodes chained together with token chain 1687 // and flag operands which copy the outgoing args into the appropriate regs. 1688 SDValue InFlag; 1689 // Tail call byval lowering might overwrite argument registers so in case of 1690 // tail call optimization the copies to registers are lowered later. 1691 if (!isTailCall) 1692 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1693 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1694 RegsToPass[i].second, InFlag); 1695 InFlag = Chain.getValue(1); 1696 } 1697 1698 // For tail calls lower the arguments to the 'real' stack slot. 1699 if (isTailCall) { 1700 // Force all the incoming stack arguments to be loaded from the stack 1701 // before any new outgoing arguments are stored to the stack, because the 1702 // outgoing stack slots may alias the incoming argument stack slots, and 1703 // the alias isn't otherwise explicit. This is slightly more conservative 1704 // than necessary, because it means that each store effectively depends 1705 // on every argument instead of just those arguments it would clobber. 1706 1707 // Do not flag preceding copytoreg stuff together with the following stuff. 1708 InFlag = SDValue(); 1709 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1710 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1711 RegsToPass[i].second, InFlag); 1712 InFlag = Chain.getValue(1); 1713 } 1714 InFlag = SDValue(); 1715 } 1716 1717 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1718 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1719 // node so that legalize doesn't hack it. 1720 bool isDirect = false; 1721 bool isARMFunc = false; 1722 bool isLocalARMFunc = false; 1723 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1724 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1725 1726 if (Subtarget->genLongCalls()) { 1727 assert((Subtarget->isTargetWindows() || 1728 getTargetMachine().getRelocationModel() == Reloc::Static) && 1729 "long-calls with non-static relocation model!"); 1730 // Handle a global address or an external symbol. If it's not one of 1731 // those, the target's already in a register, so we don't need to do 1732 // anything extra. 1733 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1734 const GlobalValue *GV = G->getGlobal(); 1735 // Create a constant pool entry for the callee address 1736 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1737 ARMConstantPoolValue *CPV = 1738 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1739 1740 // Get the address of the callee into a register 1741 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1742 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1743 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr, 1744 MachinePointerInfo::getConstantPool(), false, false, 1745 false, 0); 1746 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1747 const char *Sym = S->getSymbol(); 1748 1749 // Create a constant pool entry for the callee address 1750 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1751 ARMConstantPoolValue *CPV = 1752 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1753 ARMPCLabelIndex, 0); 1754 // Get the address of the callee into a register 1755 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1756 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1757 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr, 1758 MachinePointerInfo::getConstantPool(), false, false, 1759 false, 0); 1760 } 1761 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1762 const GlobalValue *GV = G->getGlobal(); 1763 isDirect = true; 1764 bool isDef = GV->isStrongDefinitionForLinker(); 1765 bool isStub = (!isDef && Subtarget->isTargetMachO()) && 1766 getTargetMachine().getRelocationModel() != Reloc::Static; 1767 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1768 // ARM call to a local ARM function is predicable. 1769 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1770 // tBX takes a register source operand. 1771 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1772 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1773 Callee = DAG.getNode( 1774 ARMISD::WrapperPIC, dl, PtrVt, 1775 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1776 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1777 MachinePointerInfo::getGOT(), false, false, true, 0); 1778 } else if (Subtarget->isTargetCOFF()) { 1779 assert(Subtarget->isTargetWindows() && 1780 "Windows is the only supported COFF target"); 1781 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1782 ? ARMII::MO_DLLIMPORT 1783 : ARMII::MO_NO_FLAG; 1784 Callee = 1785 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags); 1786 if (GV->hasDLLImportStorageClass()) 1787 Callee = 1788 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1789 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1790 MachinePointerInfo::getGOT(), false, false, false, 0); 1791 } else { 1792 // On ELF targets for PIC code, direct calls should go through the PLT 1793 unsigned OpFlags = 0; 1794 if (Subtarget->isTargetELF() && 1795 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1796 OpFlags = ARMII::MO_PLT; 1797 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags); 1798 } 1799 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1800 isDirect = true; 1801 bool isStub = Subtarget->isTargetMachO() && 1802 getTargetMachine().getRelocationModel() != Reloc::Static; 1803 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1804 // tBX takes a register source operand. 1805 const char *Sym = S->getSymbol(); 1806 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1807 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1808 ARMConstantPoolValue *CPV = 1809 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1810 ARMPCLabelIndex, 4); 1811 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1812 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1813 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr, 1814 MachinePointerInfo::getConstantPool(), false, false, 1815 false, 0); 1816 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1817 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1818 } else { 1819 unsigned OpFlags = 0; 1820 // On ELF targets for PIC code, direct calls should go through the PLT 1821 if (Subtarget->isTargetELF() && 1822 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1823 OpFlags = ARMII::MO_PLT; 1824 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags); 1825 } 1826 } 1827 1828 // FIXME: handle tail calls differently. 1829 unsigned CallOpc; 1830 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize); 1831 if (Subtarget->isThumb()) { 1832 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1833 CallOpc = ARMISD::CALL_NOLINK; 1834 else 1835 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL; 1836 } else { 1837 if (!isDirect && !Subtarget->hasV5TOps()) 1838 CallOpc = ARMISD::CALL_NOLINK; 1839 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1840 // Emit regular call when code size is the priority 1841 !HasMinSizeAttr) 1842 // "mov lr, pc; b _foo" to avoid confusing the RSP 1843 CallOpc = ARMISD::CALL_NOLINK; 1844 else 1845 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1846 } 1847 1848 std::vector<SDValue> Ops; 1849 Ops.push_back(Chain); 1850 Ops.push_back(Callee); 1851 1852 // Add argument registers to the end of the list so that they are known live 1853 // into the call. 1854 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1855 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1856 RegsToPass[i].second.getValueType())); 1857 1858 // Add a register mask operand representing the call-preserved registers. 1859 if (!isTailCall) { 1860 const uint32_t *Mask; 1861 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1862 if (isThisReturn) { 1863 // For 'this' returns, use the R0-preserving mask if applicable 1864 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1865 if (!Mask) { 1866 // Set isThisReturn to false if the calling convention is not one that 1867 // allows 'returned' to be modeled in this way, so LowerCallResult does 1868 // not try to pass 'this' straight through 1869 isThisReturn = false; 1870 Mask = ARI->getCallPreservedMask(MF, CallConv); 1871 } 1872 } else 1873 Mask = ARI->getCallPreservedMask(MF, CallConv); 1874 1875 assert(Mask && "Missing call preserved mask for calling convention"); 1876 Ops.push_back(DAG.getRegisterMask(Mask)); 1877 } 1878 1879 if (InFlag.getNode()) 1880 Ops.push_back(InFlag); 1881 1882 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1883 if (isTailCall) { 1884 MF.getFrameInfo()->setHasTailCall(); 1885 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1886 } 1887 1888 // Returns a chain and a flag for retval copy to use. 1889 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1890 InFlag = Chain.getValue(1); 1891 1892 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1893 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1894 if (!Ins.empty()) 1895 InFlag = Chain.getValue(1); 1896 1897 // Handle result values, copying them out of physregs into vregs that we 1898 // return. 1899 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1900 InVals, isThisReturn, 1901 isThisReturn ? OutVals[0] : SDValue()); 1902 } 1903 1904 /// HandleByVal - Every parameter *after* a byval parameter is passed 1905 /// on the stack. Remember the next parameter register to allocate, 1906 /// and then confiscate the rest of the parameter registers to insure 1907 /// this. 1908 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1909 unsigned Align) const { 1910 assert((State->getCallOrPrologue() == Prologue || 1911 State->getCallOrPrologue() == Call) && 1912 "unhandled ParmContext"); 1913 1914 // Byval (as with any stack) slots are always at least 4 byte aligned. 1915 Align = std::max(Align, 4U); 1916 1917 unsigned Reg = State->AllocateReg(GPRArgRegs); 1918 if (!Reg) 1919 return; 1920 1921 unsigned AlignInRegs = Align / 4; 1922 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 1923 for (unsigned i = 0; i < Waste; ++i) 1924 Reg = State->AllocateReg(GPRArgRegs); 1925 1926 if (!Reg) 1927 return; 1928 1929 unsigned Excess = 4 * (ARM::R4 - Reg); 1930 1931 // Special case when NSAA != SP and parameter size greater than size of 1932 // all remained GPR regs. In that case we can't split parameter, we must 1933 // send it to stack. We also must set NCRN to R4, so waste all 1934 // remained registers. 1935 const unsigned NSAAOffset = State->getNextStackOffset(); 1936 if (NSAAOffset != 0 && Size > Excess) { 1937 while (State->AllocateReg(GPRArgRegs)) 1938 ; 1939 return; 1940 } 1941 1942 // First register for byval parameter is the first register that wasn't 1943 // allocated before this method call, so it would be "reg". 1944 // If parameter is small enough to be saved in range [reg, r4), then 1945 // the end (first after last) register would be reg + param-size-in-regs, 1946 // else parameter would be splitted between registers and stack, 1947 // end register would be r4 in this case. 1948 unsigned ByValRegBegin = Reg; 1949 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 1950 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 1951 // Note, first register is allocated in the beginning of function already, 1952 // allocate remained amount of registers we need. 1953 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 1954 State->AllocateReg(GPRArgRegs); 1955 // A byval parameter that is split between registers and memory needs its 1956 // size truncated here. 1957 // In the case where the entire structure fits in registers, we set the 1958 // size in memory to zero. 1959 Size = std::max<int>(Size - Excess, 0); 1960 } 1961 1962 /// MatchingStackOffset - Return true if the given stack call argument is 1963 /// already available in the same position (relatively) of the caller's 1964 /// incoming argument stack. 1965 static 1966 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 1967 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 1968 const TargetInstrInfo *TII) { 1969 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 1970 int FI = INT_MAX; 1971 if (Arg.getOpcode() == ISD::CopyFromReg) { 1972 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 1973 if (!TargetRegisterInfo::isVirtualRegister(VR)) 1974 return false; 1975 MachineInstr *Def = MRI->getVRegDef(VR); 1976 if (!Def) 1977 return false; 1978 if (!Flags.isByVal()) { 1979 if (!TII->isLoadFromStackSlot(Def, FI)) 1980 return false; 1981 } else { 1982 return false; 1983 } 1984 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 1985 if (Flags.isByVal()) 1986 // ByVal argument is passed in as a pointer but it's now being 1987 // dereferenced. e.g. 1988 // define @foo(%struct.X* %A) { 1989 // tail call @bar(%struct.X* byval %A) 1990 // } 1991 return false; 1992 SDValue Ptr = Ld->getBasePtr(); 1993 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 1994 if (!FINode) 1995 return false; 1996 FI = FINode->getIndex(); 1997 } else 1998 return false; 1999 2000 assert(FI != INT_MAX); 2001 if (!MFI->isFixedObjectIndex(FI)) 2002 return false; 2003 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2004 } 2005 2006 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2007 /// for tail call optimization. Targets which want to do tail call 2008 /// optimization should implement this function. 2009 bool 2010 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2011 CallingConv::ID CalleeCC, 2012 bool isVarArg, 2013 bool isCalleeStructRet, 2014 bool isCallerStructRet, 2015 const SmallVectorImpl<ISD::OutputArg> &Outs, 2016 const SmallVectorImpl<SDValue> &OutVals, 2017 const SmallVectorImpl<ISD::InputArg> &Ins, 2018 SelectionDAG& DAG) const { 2019 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2020 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2021 bool CCMatch = CallerCC == CalleeCC; 2022 2023 // Look for obvious safe cases to perform tail call optimization that do not 2024 // require ABI changes. This is what gcc calls sibcall. 2025 2026 // Do not sibcall optimize vararg calls unless the call site is not passing 2027 // any arguments. 2028 if (isVarArg && !Outs.empty()) 2029 return false; 2030 2031 // Exception-handling functions need a special set of instructions to indicate 2032 // a return to the hardware. Tail-calling another function would probably 2033 // break this. 2034 if (CallerF->hasFnAttribute("interrupt")) 2035 return false; 2036 2037 // Also avoid sibcall optimization if either caller or callee uses struct 2038 // return semantics. 2039 if (isCalleeStructRet || isCallerStructRet) 2040 return false; 2041 2042 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo:: 2043 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as 2044 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation 2045 // support in the assembler and linker to be used. This would need to be 2046 // fixed to fully support tail calls in Thumb1. 2047 // 2048 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take 2049 // LR. This means if we need to reload LR, it takes an extra instructions, 2050 // which outweighs the value of the tail call; but here we don't know yet 2051 // whether LR is going to be used. Probably the right approach is to 2052 // generate the tail call here and turn it back into CALL/RET in 2053 // emitEpilogue if LR is used. 2054 2055 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls, 2056 // but we need to make sure there are enough registers; the only valid 2057 // registers are the 4 used for parameters. We don't currently do this 2058 // case. 2059 if (Subtarget->isThumb1Only()) 2060 return false; 2061 2062 // Externally-defined functions with weak linkage should not be 2063 // tail-called on ARM when the OS does not support dynamic 2064 // pre-emption of symbols, as the AAELF spec requires normal calls 2065 // to undefined weak functions to be replaced with a NOP or jump to the 2066 // next instruction. The behaviour of branch instructions in this 2067 // situation (as used for tail calls) is implementation-defined, so we 2068 // cannot rely on the linker replacing the tail call with a return. 2069 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2070 const GlobalValue *GV = G->getGlobal(); 2071 const Triple &TT = getTargetMachine().getTargetTriple(); 2072 if (GV->hasExternalWeakLinkage() && 2073 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2074 return false; 2075 } 2076 2077 // If the calling conventions do not match, then we'd better make sure the 2078 // results are returned in the same way as what the caller expects. 2079 if (!CCMatch) { 2080 SmallVector<CCValAssign, 16> RVLocs1; 2081 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1, 2082 *DAG.getContext(), Call); 2083 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg)); 2084 2085 SmallVector<CCValAssign, 16> RVLocs2; 2086 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2, 2087 *DAG.getContext(), Call); 2088 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg)); 2089 2090 if (RVLocs1.size() != RVLocs2.size()) 2091 return false; 2092 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2093 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2094 return false; 2095 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2096 return false; 2097 if (RVLocs1[i].isRegLoc()) { 2098 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2099 return false; 2100 } else { 2101 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2102 return false; 2103 } 2104 } 2105 } 2106 2107 // If Caller's vararg or byval argument has been split between registers and 2108 // stack, do not perform tail call, since part of the argument is in caller's 2109 // local frame. 2110 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction(). 2111 getInfo<ARMFunctionInfo>(); 2112 if (AFI_Caller->getArgRegsSaveSize()) 2113 return false; 2114 2115 // If the callee takes no arguments then go on to check the results of the 2116 // call. 2117 if (!Outs.empty()) { 2118 // Check if stack adjustment is needed. For now, do not do this if any 2119 // argument is passed on the stack. 2120 SmallVector<CCValAssign, 16> ArgLocs; 2121 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs, 2122 *DAG.getContext(), Call); 2123 CCInfo.AnalyzeCallOperands(Outs, 2124 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2125 if (CCInfo.getNextStackOffset()) { 2126 MachineFunction &MF = DAG.getMachineFunction(); 2127 2128 // Check if the arguments are already laid out in the right way as 2129 // the caller's fixed stack objects. 2130 MachineFrameInfo *MFI = MF.getFrameInfo(); 2131 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2132 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2133 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2134 i != e; 2135 ++i, ++realArgIdx) { 2136 CCValAssign &VA = ArgLocs[i]; 2137 EVT RegVT = VA.getLocVT(); 2138 SDValue Arg = OutVals[realArgIdx]; 2139 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2140 if (VA.getLocInfo() == CCValAssign::Indirect) 2141 return false; 2142 if (VA.needsCustom()) { 2143 // f64 and vector types are split into multiple registers or 2144 // register/stack-slot combinations. The types will not match 2145 // the registers; give up on memory f64 refs until we figure 2146 // out what to do about this. 2147 if (!VA.isRegLoc()) 2148 return false; 2149 if (!ArgLocs[++i].isRegLoc()) 2150 return false; 2151 if (RegVT == MVT::v2f64) { 2152 if (!ArgLocs[++i].isRegLoc()) 2153 return false; 2154 if (!ArgLocs[++i].isRegLoc()) 2155 return false; 2156 } 2157 } else if (!VA.isRegLoc()) { 2158 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2159 MFI, MRI, TII)) 2160 return false; 2161 } 2162 } 2163 } 2164 } 2165 2166 return true; 2167 } 2168 2169 bool 2170 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2171 MachineFunction &MF, bool isVarArg, 2172 const SmallVectorImpl<ISD::OutputArg> &Outs, 2173 LLVMContext &Context) const { 2174 SmallVector<CCValAssign, 16> RVLocs; 2175 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2176 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2177 isVarArg)); 2178 } 2179 2180 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2181 SDLoc DL, SelectionDAG &DAG) { 2182 const MachineFunction &MF = DAG.getMachineFunction(); 2183 const Function *F = MF.getFunction(); 2184 2185 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2186 2187 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2188 // version of the "preferred return address". These offsets affect the return 2189 // instruction if this is a return from PL1 without hypervisor extensions. 2190 // IRQ/FIQ: +4 "subs pc, lr, #4" 2191 // SWI: 0 "subs pc, lr, #0" 2192 // ABORT: +4 "subs pc, lr, #4" 2193 // UNDEF: +4/+2 "subs pc, lr, #0" 2194 // UNDEF varies depending on where the exception came from ARM or Thumb 2195 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2196 2197 int64_t LROffset; 2198 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2199 IntKind == "ABORT") 2200 LROffset = 4; 2201 else if (IntKind == "SWI" || IntKind == "UNDEF") 2202 LROffset = 0; 2203 else 2204 report_fatal_error("Unsupported interrupt attribute. If present, value " 2205 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2206 2207 RetOps.insert(RetOps.begin() + 1, 2208 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2209 2210 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2211 } 2212 2213 SDValue 2214 ARMTargetLowering::LowerReturn(SDValue Chain, 2215 CallingConv::ID CallConv, bool isVarArg, 2216 const SmallVectorImpl<ISD::OutputArg> &Outs, 2217 const SmallVectorImpl<SDValue> &OutVals, 2218 SDLoc dl, SelectionDAG &DAG) const { 2219 2220 // CCValAssign - represent the assignment of the return value to a location. 2221 SmallVector<CCValAssign, 16> RVLocs; 2222 2223 // CCState - Info about the registers and stack slots. 2224 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2225 *DAG.getContext(), Call); 2226 2227 // Analyze outgoing return values. 2228 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2229 isVarArg)); 2230 2231 SDValue Flag; 2232 SmallVector<SDValue, 4> RetOps; 2233 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2234 bool isLittleEndian = Subtarget->isLittle(); 2235 2236 MachineFunction &MF = DAG.getMachineFunction(); 2237 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2238 AFI->setReturnRegsCount(RVLocs.size()); 2239 2240 // Copy the result values into the output registers. 2241 for (unsigned i = 0, realRVLocIdx = 0; 2242 i != RVLocs.size(); 2243 ++i, ++realRVLocIdx) { 2244 CCValAssign &VA = RVLocs[i]; 2245 assert(VA.isRegLoc() && "Can only return in registers!"); 2246 2247 SDValue Arg = OutVals[realRVLocIdx]; 2248 2249 switch (VA.getLocInfo()) { 2250 default: llvm_unreachable("Unknown loc info!"); 2251 case CCValAssign::Full: break; 2252 case CCValAssign::BCvt: 2253 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2254 break; 2255 } 2256 2257 if (VA.needsCustom()) { 2258 if (VA.getLocVT() == MVT::v2f64) { 2259 // Extract the first half and return it in two registers. 2260 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2261 DAG.getConstant(0, dl, MVT::i32)); 2262 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2263 DAG.getVTList(MVT::i32, MVT::i32), Half); 2264 2265 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2266 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2267 Flag); 2268 Flag = Chain.getValue(1); 2269 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2270 VA = RVLocs[++i]; // skip ahead to next loc 2271 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2272 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2273 Flag); 2274 Flag = Chain.getValue(1); 2275 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2276 VA = RVLocs[++i]; // skip ahead to next loc 2277 2278 // Extract the 2nd half and fall through to handle it as an f64 value. 2279 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2280 DAG.getConstant(1, dl, MVT::i32)); 2281 } 2282 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2283 // available. 2284 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2285 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2286 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2287 fmrrd.getValue(isLittleEndian ? 0 : 1), 2288 Flag); 2289 Flag = Chain.getValue(1); 2290 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2291 VA = RVLocs[++i]; // skip ahead to next loc 2292 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2293 fmrrd.getValue(isLittleEndian ? 1 : 0), 2294 Flag); 2295 } else 2296 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2297 2298 // Guarantee that all emitted copies are 2299 // stuck together, avoiding something bad. 2300 Flag = Chain.getValue(1); 2301 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2302 } 2303 2304 // Update chain and glue. 2305 RetOps[0] = Chain; 2306 if (Flag.getNode()) 2307 RetOps.push_back(Flag); 2308 2309 // CPUs which aren't M-class use a special sequence to return from 2310 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2311 // though we use "subs pc, lr, #N"). 2312 // 2313 // M-class CPUs actually use a normal return sequence with a special 2314 // (hardware-provided) value in LR, so the normal code path works. 2315 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2316 !Subtarget->isMClass()) { 2317 if (Subtarget->isThumb1Only()) 2318 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2319 return LowerInterruptReturn(RetOps, dl, DAG); 2320 } 2321 2322 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2323 } 2324 2325 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2326 if (N->getNumValues() != 1) 2327 return false; 2328 if (!N->hasNUsesOfValue(1, 0)) 2329 return false; 2330 2331 SDValue TCChain = Chain; 2332 SDNode *Copy = *N->use_begin(); 2333 if (Copy->getOpcode() == ISD::CopyToReg) { 2334 // If the copy has a glue operand, we conservatively assume it isn't safe to 2335 // perform a tail call. 2336 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2337 return false; 2338 TCChain = Copy->getOperand(0); 2339 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2340 SDNode *VMov = Copy; 2341 // f64 returned in a pair of GPRs. 2342 SmallPtrSet<SDNode*, 2> Copies; 2343 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2344 UI != UE; ++UI) { 2345 if (UI->getOpcode() != ISD::CopyToReg) 2346 return false; 2347 Copies.insert(*UI); 2348 } 2349 if (Copies.size() > 2) 2350 return false; 2351 2352 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2353 UI != UE; ++UI) { 2354 SDValue UseChain = UI->getOperand(0); 2355 if (Copies.count(UseChain.getNode())) 2356 // Second CopyToReg 2357 Copy = *UI; 2358 else { 2359 // We are at the top of this chain. 2360 // If the copy has a glue operand, we conservatively assume it 2361 // isn't safe to perform a tail call. 2362 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2363 return false; 2364 // First CopyToReg 2365 TCChain = UseChain; 2366 } 2367 } 2368 } else if (Copy->getOpcode() == ISD::BITCAST) { 2369 // f32 returned in a single GPR. 2370 if (!Copy->hasOneUse()) 2371 return false; 2372 Copy = *Copy->use_begin(); 2373 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2374 return false; 2375 // If the copy has a glue operand, we conservatively assume it isn't safe to 2376 // perform a tail call. 2377 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2378 return false; 2379 TCChain = Copy->getOperand(0); 2380 } else { 2381 return false; 2382 } 2383 2384 bool HasRet = false; 2385 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2386 UI != UE; ++UI) { 2387 if (UI->getOpcode() != ARMISD::RET_FLAG && 2388 UI->getOpcode() != ARMISD::INTRET_FLAG) 2389 return false; 2390 HasRet = true; 2391 } 2392 2393 if (!HasRet) 2394 return false; 2395 2396 Chain = TCChain; 2397 return true; 2398 } 2399 2400 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2401 if (!Subtarget->supportsTailCall()) 2402 return false; 2403 2404 auto Attr = 2405 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2406 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2407 return false; 2408 2409 return !Subtarget->isThumb1Only(); 2410 } 2411 2412 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2413 // and pass the lower and high parts through. 2414 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2415 SDLoc DL(Op); 2416 SDValue WriteValue = Op->getOperand(2); 2417 2418 // This function is only supposed to be called for i64 type argument. 2419 assert(WriteValue.getValueType() == MVT::i64 2420 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2421 2422 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2423 DAG.getConstant(0, DL, MVT::i32)); 2424 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2425 DAG.getConstant(1, DL, MVT::i32)); 2426 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2427 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2428 } 2429 2430 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2431 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2432 // one of the above mentioned nodes. It has to be wrapped because otherwise 2433 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2434 // be used to form addressing mode. These wrapped nodes will be selected 2435 // into MOVi. 2436 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2437 EVT PtrVT = Op.getValueType(); 2438 // FIXME there is no actual debug info here 2439 SDLoc dl(Op); 2440 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2441 SDValue Res; 2442 if (CP->isMachineConstantPoolEntry()) 2443 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2444 CP->getAlignment()); 2445 else 2446 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2447 CP->getAlignment()); 2448 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2449 } 2450 2451 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2452 return MachineJumpTableInfo::EK_Inline; 2453 } 2454 2455 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2456 SelectionDAG &DAG) const { 2457 MachineFunction &MF = DAG.getMachineFunction(); 2458 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2459 unsigned ARMPCLabelIndex = 0; 2460 SDLoc DL(Op); 2461 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2462 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2463 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2464 SDValue CPAddr; 2465 if (RelocM == Reloc::Static) { 2466 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2467 } else { 2468 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2469 ARMPCLabelIndex = AFI->createPICLabelUId(); 2470 ARMConstantPoolValue *CPV = 2471 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2472 ARMCP::CPBlockAddress, PCAdj); 2473 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2474 } 2475 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2476 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2477 MachinePointerInfo::getConstantPool(), 2478 false, false, false, 0); 2479 if (RelocM == Reloc::Static) 2480 return Result; 2481 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2482 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2483 } 2484 2485 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2486 SDValue 2487 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2488 SelectionDAG &DAG) const { 2489 SDLoc dl(GA); 2490 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2491 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2492 MachineFunction &MF = DAG.getMachineFunction(); 2493 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2494 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2495 ARMConstantPoolValue *CPV = 2496 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2497 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2498 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2499 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2500 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2501 MachinePointerInfo::getConstantPool(), 2502 false, false, false, 0); 2503 SDValue Chain = Argument.getValue(1); 2504 2505 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2506 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2507 2508 // call __tls_get_addr. 2509 ArgListTy Args; 2510 ArgListEntry Entry; 2511 Entry.Node = Argument; 2512 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2513 Args.push_back(Entry); 2514 2515 // FIXME: is there useful debug info available here? 2516 TargetLowering::CallLoweringInfo CLI(DAG); 2517 CLI.setDebugLoc(dl).setChain(Chain) 2518 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2519 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args), 2520 0); 2521 2522 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2523 return CallResult.first; 2524 } 2525 2526 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2527 // "local exec" model. 2528 SDValue 2529 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2530 SelectionDAG &DAG, 2531 TLSModel::Model model) const { 2532 const GlobalValue *GV = GA->getGlobal(); 2533 SDLoc dl(GA); 2534 SDValue Offset; 2535 SDValue Chain = DAG.getEntryNode(); 2536 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2537 // Get the Thread Pointer 2538 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2539 2540 if (model == TLSModel::InitialExec) { 2541 MachineFunction &MF = DAG.getMachineFunction(); 2542 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2543 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2544 // Initial exec model. 2545 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2546 ARMConstantPoolValue *CPV = 2547 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2548 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2549 true); 2550 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2551 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2552 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, 2553 MachinePointerInfo::getConstantPool(), 2554 false, false, false, 0); 2555 Chain = Offset.getValue(1); 2556 2557 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2558 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2559 2560 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, 2561 MachinePointerInfo::getConstantPool(), 2562 false, false, false, 0); 2563 } else { 2564 // local exec model 2565 assert(model == TLSModel::LocalExec); 2566 ARMConstantPoolValue *CPV = 2567 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2568 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2569 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2570 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, 2571 MachinePointerInfo::getConstantPool(), 2572 false, false, false, 0); 2573 } 2574 2575 // The address of the thread local variable is the add of the thread 2576 // pointer with the offset of the variable. 2577 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2578 } 2579 2580 SDValue 2581 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2582 // TODO: implement the "local dynamic" model 2583 assert(Subtarget->isTargetELF() && 2584 "TLS not implemented for non-ELF targets"); 2585 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2586 2587 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2588 2589 switch (model) { 2590 case TLSModel::GeneralDynamic: 2591 case TLSModel::LocalDynamic: 2592 return LowerToTLSGeneralDynamicModel(GA, DAG); 2593 case TLSModel::InitialExec: 2594 case TLSModel::LocalExec: 2595 return LowerToTLSExecModels(GA, DAG, model); 2596 } 2597 llvm_unreachable("bogus TLS model"); 2598 } 2599 2600 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2601 SelectionDAG &DAG) const { 2602 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2603 SDLoc dl(Op); 2604 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2605 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2606 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility(); 2607 ARMConstantPoolValue *CPV = 2608 ARMConstantPoolConstant::Create(GV, 2609 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT); 2610 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2611 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2612 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 2613 CPAddr, 2614 MachinePointerInfo::getConstantPool(), 2615 false, false, false, 0); 2616 SDValue Chain = Result.getValue(1); 2617 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT); 2618 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT); 2619 if (!UseGOTOFF) 2620 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2621 MachinePointerInfo::getGOT(), 2622 false, false, false, 0); 2623 return Result; 2624 } 2625 2626 // If we have T2 ops, we can materialize the address directly via movt/movw 2627 // pair. This is always cheaper. 2628 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2629 ++NumMovwMovt; 2630 // FIXME: Once remat is capable of dealing with instructions with register 2631 // operands, expand this into two nodes. 2632 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2633 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2634 } else { 2635 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2636 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2637 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, 2638 MachinePointerInfo::getConstantPool(), 2639 false, false, false, 0); 2640 } 2641 } 2642 2643 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2644 SelectionDAG &DAG) const { 2645 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2646 SDLoc dl(Op); 2647 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2648 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2649 2650 if (Subtarget->useMovt(DAG.getMachineFunction())) 2651 ++NumMovwMovt; 2652 2653 // FIXME: Once remat is capable of dealing with instructions with register 2654 // operands, expand this into multiple nodes 2655 unsigned Wrapper = 2656 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2657 2658 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2659 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2660 2661 if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) 2662 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2663 MachinePointerInfo::getGOT(), false, false, false, 0); 2664 return Result; 2665 } 2666 2667 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2668 SelectionDAG &DAG) const { 2669 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2670 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2671 "Windows on ARM expects to use movw/movt"); 2672 2673 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2674 const ARMII::TOF TargetFlags = 2675 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2676 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2677 SDValue Result; 2678 SDLoc DL(Op); 2679 2680 ++NumMovwMovt; 2681 2682 // FIXME: Once remat is capable of dealing with instructions with register 2683 // operands, expand this into two nodes. 2684 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2685 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2686 TargetFlags)); 2687 if (GV->hasDLLImportStorageClass()) 2688 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2689 MachinePointerInfo::getGOT(), false, false, false, 0); 2690 return Result; 2691 } 2692 2693 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op, 2694 SelectionDAG &DAG) const { 2695 assert(Subtarget->isTargetELF() && 2696 "GLOBAL OFFSET TABLE not implemented for non-ELF targets"); 2697 MachineFunction &MF = DAG.getMachineFunction(); 2698 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2699 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2700 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2701 SDLoc dl(Op); 2702 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2703 ARMConstantPoolValue *CPV = 2704 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_", 2705 ARMPCLabelIndex, PCAdj); 2706 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2707 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2708 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, 2709 MachinePointerInfo::getConstantPool(), 2710 false, false, false, 0); 2711 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2712 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2713 } 2714 2715 SDValue 2716 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2717 SDLoc dl(Op); 2718 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 2719 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2720 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2721 Op.getOperand(1), Val); 2722 } 2723 2724 SDValue 2725 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2726 SDLoc dl(Op); 2727 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2728 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 2729 } 2730 2731 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 2732 SelectionDAG &DAG) const { 2733 SDLoc dl(Op); 2734 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 2735 Op.getOperand(0)); 2736 } 2737 2738 SDValue 2739 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2740 const ARMSubtarget *Subtarget) const { 2741 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2742 SDLoc dl(Op); 2743 switch (IntNo) { 2744 default: return SDValue(); // Don't custom lower most intrinsics. 2745 case Intrinsic::arm_rbit: { 2746 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2747 "RBIT intrinsic must have i32 type!"); 2748 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1)); 2749 } 2750 case Intrinsic::arm_thread_pointer: { 2751 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2752 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2753 } 2754 case Intrinsic::eh_sjlj_lsda: { 2755 MachineFunction &MF = DAG.getMachineFunction(); 2756 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2757 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2758 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2759 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2760 SDValue CPAddr; 2761 unsigned PCAdj = (RelocM != Reloc::PIC_) 2762 ? 0 : (Subtarget->isThumb() ? 4 : 8); 2763 ARMConstantPoolValue *CPV = 2764 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2765 ARMCP::CPLSDA, PCAdj); 2766 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2767 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2768 SDValue Result = 2769 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, 2770 MachinePointerInfo::getConstantPool(), 2771 false, false, false, 0); 2772 2773 if (RelocM == Reloc::PIC_) { 2774 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2775 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2776 } 2777 return Result; 2778 } 2779 case Intrinsic::arm_neon_vmulls: 2780 case Intrinsic::arm_neon_vmullu: { 2781 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2782 ? ARMISD::VMULLs : ARMISD::VMULLu; 2783 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2784 Op.getOperand(1), Op.getOperand(2)); 2785 } 2786 } 2787 } 2788 2789 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 2790 const ARMSubtarget *Subtarget) { 2791 // FIXME: handle "fence singlethread" more efficiently. 2792 SDLoc dl(Op); 2793 if (!Subtarget->hasDataBarrier()) { 2794 // Some ARMv6 cpus can support data barriers with an mcr instruction. 2795 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 2796 // here. 2797 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 2798 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 2799 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 2800 DAG.getConstant(0, dl, MVT::i32)); 2801 } 2802 2803 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 2804 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 2805 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 2806 if (Subtarget->isMClass()) { 2807 // Only a full system barrier exists in the M-class architectures. 2808 Domain = ARM_MB::SY; 2809 } else if (Subtarget->isSwift() && Ord == Release) { 2810 // Swift happens to implement ISHST barriers in a way that's compatible with 2811 // Release semantics but weaker than ISH so we'd be fools not to use 2812 // it. Beware: other processors probably don't! 2813 Domain = ARM_MB::ISHST; 2814 } 2815 2816 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 2817 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 2818 DAG.getConstant(Domain, dl, MVT::i32)); 2819 } 2820 2821 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 2822 const ARMSubtarget *Subtarget) { 2823 // ARM pre v5TE and Thumb1 does not have preload instructions. 2824 if (!(Subtarget->isThumb2() || 2825 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 2826 // Just preserve the chain. 2827 return Op.getOperand(0); 2828 2829 SDLoc dl(Op); 2830 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 2831 if (!isRead && 2832 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 2833 // ARMv7 with MP extension has PLDW. 2834 return Op.getOperand(0); 2835 2836 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2837 if (Subtarget->isThumb()) { 2838 // Invert the bits. 2839 isRead = ~isRead & 1; 2840 isData = ~isData & 1; 2841 } 2842 2843 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 2844 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 2845 DAG.getConstant(isData, dl, MVT::i32)); 2846 } 2847 2848 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 2849 MachineFunction &MF = DAG.getMachineFunction(); 2850 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 2851 2852 // vastart just stores the address of the VarArgsFrameIndex slot into the 2853 // memory location argument. 2854 SDLoc dl(Op); 2855 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2856 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2857 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2858 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2859 MachinePointerInfo(SV), false, false, 0); 2860 } 2861 2862 SDValue 2863 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA, 2864 SDValue &Root, SelectionDAG &DAG, 2865 SDLoc dl) const { 2866 MachineFunction &MF = DAG.getMachineFunction(); 2867 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2868 2869 const TargetRegisterClass *RC; 2870 if (AFI->isThumb1OnlyFunction()) 2871 RC = &ARM::tGPRRegClass; 2872 else 2873 RC = &ARM::GPRRegClass; 2874 2875 // Transform the arguments stored in physical registers into virtual ones. 2876 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2877 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 2878 2879 SDValue ArgValue2; 2880 if (NextVA.isMemLoc()) { 2881 MachineFrameInfo *MFI = MF.getFrameInfo(); 2882 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 2883 2884 // Create load node to retrieve arguments from the stack. 2885 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2886 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, 2887 MachinePointerInfo::getFixedStack(FI), 2888 false, false, false, 0); 2889 } else { 2890 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 2891 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 2892 } 2893 if (!Subtarget->isLittle()) 2894 std::swap (ArgValue, ArgValue2); 2895 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 2896 } 2897 2898 // The remaining GPRs hold either the beginning of variable-argument 2899 // data, or the beginning of an aggregate passed by value (usually 2900 // byval). Either way, we allocate stack slots adjacent to the data 2901 // provided by our caller, and store the unallocated registers there. 2902 // If this is a variadic function, the va_list pointer will begin with 2903 // these values; otherwise, this reassembles a (byval) structure that 2904 // was split between registers and memory. 2905 // Return: The frame index registers were stored into. 2906 int 2907 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 2908 SDLoc dl, SDValue &Chain, 2909 const Value *OrigArg, 2910 unsigned InRegsParamRecordIdx, 2911 int ArgOffset, 2912 unsigned ArgSize) const { 2913 // Currently, two use-cases possible: 2914 // Case #1. Non-var-args function, and we meet first byval parameter. 2915 // Setup first unallocated register as first byval register; 2916 // eat all remained registers 2917 // (these two actions are performed by HandleByVal method). 2918 // Then, here, we initialize stack frame with 2919 // "store-reg" instructions. 2920 // Case #2. Var-args function, that doesn't contain byval parameters. 2921 // The same: eat all remained unallocated registers, 2922 // initialize stack frame. 2923 2924 MachineFunction &MF = DAG.getMachineFunction(); 2925 MachineFrameInfo *MFI = MF.getFrameInfo(); 2926 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2927 unsigned RBegin, REnd; 2928 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 2929 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 2930 } else { 2931 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 2932 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 2933 REnd = ARM::R4; 2934 } 2935 2936 if (REnd != RBegin) 2937 ArgOffset = -4 * (ARM::R4 - RBegin); 2938 2939 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2940 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false); 2941 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 2942 2943 SmallVector<SDValue, 4> MemOps; 2944 const TargetRegisterClass *RC = 2945 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 2946 2947 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 2948 unsigned VReg = MF.addLiveIn(Reg, RC); 2949 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 2950 SDValue Store = 2951 DAG.getStore(Val.getValue(1), dl, Val, FIN, 2952 MachinePointerInfo(OrigArg, 4 * i), false, false, 0); 2953 MemOps.push_back(Store); 2954 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 2955 } 2956 2957 if (!MemOps.empty()) 2958 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 2959 return FrameIndex; 2960 } 2961 2962 // Setup stack frame, the va_list pointer will start from. 2963 void 2964 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 2965 SDLoc dl, SDValue &Chain, 2966 unsigned ArgOffset, 2967 unsigned TotalArgRegsSaveSize, 2968 bool ForceMutable) const { 2969 MachineFunction &MF = DAG.getMachineFunction(); 2970 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2971 2972 // Try to store any remaining integer argument regs 2973 // to their spots on the stack so that they may be loaded by deferencing 2974 // the result of va_next. 2975 // If there is no regs to be stored, just point address after last 2976 // argument passed via stack. 2977 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 2978 CCInfo.getInRegsParamsCount(), 2979 CCInfo.getNextStackOffset(), 4); 2980 AFI->setVarArgsFrameIndex(FrameIndex); 2981 } 2982 2983 SDValue 2984 ARMTargetLowering::LowerFormalArguments(SDValue Chain, 2985 CallingConv::ID CallConv, bool isVarArg, 2986 const SmallVectorImpl<ISD::InputArg> 2987 &Ins, 2988 SDLoc dl, SelectionDAG &DAG, 2989 SmallVectorImpl<SDValue> &InVals) 2990 const { 2991 MachineFunction &MF = DAG.getMachineFunction(); 2992 MachineFrameInfo *MFI = MF.getFrameInfo(); 2993 2994 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2995 2996 // Assign locations to all of the incoming arguments. 2997 SmallVector<CCValAssign, 16> ArgLocs; 2998 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2999 *DAG.getContext(), Prologue); 3000 CCInfo.AnalyzeFormalArguments(Ins, 3001 CCAssignFnForNode(CallConv, /* Return*/ false, 3002 isVarArg)); 3003 3004 SmallVector<SDValue, 16> ArgValues; 3005 SDValue ArgValue; 3006 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3007 unsigned CurArgIdx = 0; 3008 3009 // Initially ArgRegsSaveSize is zero. 3010 // Then we increase this value each time we meet byval parameter. 3011 // We also increase this value in case of varargs function. 3012 AFI->setArgRegsSaveSize(0); 3013 3014 // Calculate the amount of stack space that we need to allocate to store 3015 // byval and variadic arguments that are passed in registers. 3016 // We need to know this before we allocate the first byval or variadic 3017 // argument, as they will be allocated a stack slot below the CFA (Canonical 3018 // Frame Address, the stack pointer at entry to the function). 3019 unsigned ArgRegBegin = ARM::R4; 3020 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3021 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3022 break; 3023 3024 CCValAssign &VA = ArgLocs[i]; 3025 unsigned Index = VA.getValNo(); 3026 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3027 if (!Flags.isByVal()) 3028 continue; 3029 3030 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3031 unsigned RBegin, REnd; 3032 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3033 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3034 3035 CCInfo.nextInRegsParam(); 3036 } 3037 CCInfo.rewindByValRegsInfo(); 3038 3039 int lastInsIndex = -1; 3040 if (isVarArg && MFI->hasVAStart()) { 3041 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3042 if (RegIdx != array_lengthof(GPRArgRegs)) 3043 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3044 } 3045 3046 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3047 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3048 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3049 3050 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3051 CCValAssign &VA = ArgLocs[i]; 3052 if (Ins[VA.getValNo()].isOrigArg()) { 3053 std::advance(CurOrigArg, 3054 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3055 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3056 } 3057 // Arguments stored in registers. 3058 if (VA.isRegLoc()) { 3059 EVT RegVT = VA.getLocVT(); 3060 3061 if (VA.needsCustom()) { 3062 // f64 and vector types are split up into multiple registers or 3063 // combinations of registers and stack slots. 3064 if (VA.getLocVT() == MVT::v2f64) { 3065 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3066 Chain, DAG, dl); 3067 VA = ArgLocs[++i]; // skip ahead to next loc 3068 SDValue ArgValue2; 3069 if (VA.isMemLoc()) { 3070 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 3071 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3072 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3073 MachinePointerInfo::getFixedStack(FI), 3074 false, false, false, 0); 3075 } else { 3076 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3077 Chain, DAG, dl); 3078 } 3079 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3080 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3081 ArgValue, ArgValue1, 3082 DAG.getIntPtrConstant(0, dl)); 3083 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3084 ArgValue, ArgValue2, 3085 DAG.getIntPtrConstant(1, dl)); 3086 } else 3087 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3088 3089 } else { 3090 const TargetRegisterClass *RC; 3091 3092 if (RegVT == MVT::f32) 3093 RC = &ARM::SPRRegClass; 3094 else if (RegVT == MVT::f64) 3095 RC = &ARM::DPRRegClass; 3096 else if (RegVT == MVT::v2f64) 3097 RC = &ARM::QPRRegClass; 3098 else if (RegVT == MVT::i32) 3099 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3100 : &ARM::GPRRegClass; 3101 else 3102 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3103 3104 // Transform the arguments in physical registers into virtual ones. 3105 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3106 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3107 } 3108 3109 // If this is an 8 or 16-bit value, it is really passed promoted 3110 // to 32 bits. Insert an assert[sz]ext to capture this, then 3111 // truncate to the right size. 3112 switch (VA.getLocInfo()) { 3113 default: llvm_unreachable("Unknown loc info!"); 3114 case CCValAssign::Full: break; 3115 case CCValAssign::BCvt: 3116 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3117 break; 3118 case CCValAssign::SExt: 3119 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3120 DAG.getValueType(VA.getValVT())); 3121 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3122 break; 3123 case CCValAssign::ZExt: 3124 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3125 DAG.getValueType(VA.getValVT())); 3126 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3127 break; 3128 } 3129 3130 InVals.push_back(ArgValue); 3131 3132 } else { // VA.isRegLoc() 3133 3134 // sanity check 3135 assert(VA.isMemLoc()); 3136 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3137 3138 int index = VA.getValNo(); 3139 3140 // Some Ins[] entries become multiple ArgLoc[] entries. 3141 // Process them only once. 3142 if (index != lastInsIndex) 3143 { 3144 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3145 // FIXME: For now, all byval parameter objects are marked mutable. 3146 // This can be changed with more analysis. 3147 // In case of tail call optimization mark all arguments mutable. 3148 // Since they could be overwritten by lowering of arguments in case of 3149 // a tail call. 3150 if (Flags.isByVal()) { 3151 assert(Ins[index].isOrigArg() && 3152 "Byval arguments cannot be implicit"); 3153 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3154 3155 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg, 3156 CurByValIndex, VA.getLocMemOffset(), 3157 Flags.getByValSize()); 3158 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3159 CCInfo.nextInRegsParam(); 3160 } else { 3161 unsigned FIOffset = VA.getLocMemOffset(); 3162 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3163 FIOffset, true); 3164 3165 // Create load nodes to retrieve arguments from the stack. 3166 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3167 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3168 MachinePointerInfo::getFixedStack(FI), 3169 false, false, false, 0)); 3170 } 3171 lastInsIndex = index; 3172 } 3173 } 3174 } 3175 3176 // varargs 3177 if (isVarArg && MFI->hasVAStart()) 3178 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3179 CCInfo.getNextStackOffset(), 3180 TotalArgRegsSaveSize); 3181 3182 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3183 3184 return Chain; 3185 } 3186 3187 /// isFloatingPointZero - Return true if this is +0.0. 3188 static bool isFloatingPointZero(SDValue Op) { 3189 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3190 return CFP->getValueAPF().isPosZero(); 3191 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3192 // Maybe this has already been legalized into the constant pool? 3193 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3194 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3195 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3196 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3197 return CFP->getValueAPF().isPosZero(); 3198 } 3199 } else if (Op->getOpcode() == ISD::BITCAST && 3200 Op->getValueType(0) == MVT::f64) { 3201 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3202 // created by LowerConstantFP(). 3203 SDValue BitcastOp = Op->getOperand(0); 3204 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) { 3205 SDValue MoveOp = BitcastOp->getOperand(0); 3206 if (MoveOp->getOpcode() == ISD::TargetConstant && 3207 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) { 3208 return true; 3209 } 3210 } 3211 } 3212 return false; 3213 } 3214 3215 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3216 /// the given operands. 3217 SDValue 3218 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3219 SDValue &ARMcc, SelectionDAG &DAG, 3220 SDLoc dl) const { 3221 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3222 unsigned C = RHSC->getZExtValue(); 3223 if (!isLegalICmpImmediate(C)) { 3224 // Constant does not fit, try adjusting it by one? 3225 switch (CC) { 3226 default: break; 3227 case ISD::SETLT: 3228 case ISD::SETGE: 3229 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3230 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3231 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3232 } 3233 break; 3234 case ISD::SETULT: 3235 case ISD::SETUGE: 3236 if (C != 0 && isLegalICmpImmediate(C-1)) { 3237 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3238 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3239 } 3240 break; 3241 case ISD::SETLE: 3242 case ISD::SETGT: 3243 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3244 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3245 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3246 } 3247 break; 3248 case ISD::SETULE: 3249 case ISD::SETUGT: 3250 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3251 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3252 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3253 } 3254 break; 3255 } 3256 } 3257 } 3258 3259 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3260 ARMISD::NodeType CompareType; 3261 switch (CondCode) { 3262 default: 3263 CompareType = ARMISD::CMP; 3264 break; 3265 case ARMCC::EQ: 3266 case ARMCC::NE: 3267 // Uses only Z Flag 3268 CompareType = ARMISD::CMPZ; 3269 break; 3270 } 3271 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3272 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3273 } 3274 3275 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3276 SDValue 3277 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG, 3278 SDLoc dl) const { 3279 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3280 SDValue Cmp; 3281 if (!isFloatingPointZero(RHS)) 3282 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3283 else 3284 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3285 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3286 } 3287 3288 /// duplicateCmp - Glue values can have only one use, so this function 3289 /// duplicates a comparison node. 3290 SDValue 3291 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3292 unsigned Opc = Cmp.getOpcode(); 3293 SDLoc DL(Cmp); 3294 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3295 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3296 3297 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3298 Cmp = Cmp.getOperand(0); 3299 Opc = Cmp.getOpcode(); 3300 if (Opc == ARMISD::CMPFP) 3301 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3302 else { 3303 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3304 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3305 } 3306 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3307 } 3308 3309 std::pair<SDValue, SDValue> 3310 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3311 SDValue &ARMcc) const { 3312 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3313 3314 SDValue Value, OverflowCmp; 3315 SDValue LHS = Op.getOperand(0); 3316 SDValue RHS = Op.getOperand(1); 3317 SDLoc dl(Op); 3318 3319 // FIXME: We are currently always generating CMPs because we don't support 3320 // generating CMN through the backend. This is not as good as the natural 3321 // CMP case because it causes a register dependency and cannot be folded 3322 // later. 3323 3324 switch (Op.getOpcode()) { 3325 default: 3326 llvm_unreachable("Unknown overflow instruction!"); 3327 case ISD::SADDO: 3328 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3329 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3330 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3331 break; 3332 case ISD::UADDO: 3333 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3334 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3335 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3336 break; 3337 case ISD::SSUBO: 3338 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3339 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3340 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3341 break; 3342 case ISD::USUBO: 3343 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3344 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3345 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3346 break; 3347 } // switch (...) 3348 3349 return std::make_pair(Value, OverflowCmp); 3350 } 3351 3352 3353 SDValue 3354 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3355 // Let legalize expand this if it isn't a legal type yet. 3356 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3357 return SDValue(); 3358 3359 SDValue Value, OverflowCmp; 3360 SDValue ARMcc; 3361 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3362 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3363 SDLoc dl(Op); 3364 // We use 0 and 1 as false and true values. 3365 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3366 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3367 EVT VT = Op.getValueType(); 3368 3369 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3370 ARMcc, CCR, OverflowCmp); 3371 3372 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3373 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3374 } 3375 3376 3377 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3378 SDValue Cond = Op.getOperand(0); 3379 SDValue SelectTrue = Op.getOperand(1); 3380 SDValue SelectFalse = Op.getOperand(2); 3381 SDLoc dl(Op); 3382 unsigned Opc = Cond.getOpcode(); 3383 3384 if (Cond.getResNo() == 1 && 3385 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3386 Opc == ISD::USUBO)) { 3387 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3388 return SDValue(); 3389 3390 SDValue Value, OverflowCmp; 3391 SDValue ARMcc; 3392 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3393 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3394 EVT VT = Op.getValueType(); 3395 3396 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3397 OverflowCmp, DAG); 3398 } 3399 3400 // Convert: 3401 // 3402 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3403 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3404 // 3405 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3406 const ConstantSDNode *CMOVTrue = 3407 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3408 const ConstantSDNode *CMOVFalse = 3409 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3410 3411 if (CMOVTrue && CMOVFalse) { 3412 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3413 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3414 3415 SDValue True; 3416 SDValue False; 3417 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3418 True = SelectTrue; 3419 False = SelectFalse; 3420 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3421 True = SelectFalse; 3422 False = SelectTrue; 3423 } 3424 3425 if (True.getNode() && False.getNode()) { 3426 EVT VT = Op.getValueType(); 3427 SDValue ARMcc = Cond.getOperand(2); 3428 SDValue CCR = Cond.getOperand(3); 3429 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3430 assert(True.getValueType() == VT); 3431 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3432 } 3433 } 3434 } 3435 3436 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3437 // undefined bits before doing a full-word comparison with zero. 3438 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3439 DAG.getConstant(1, dl, Cond.getValueType())); 3440 3441 return DAG.getSelectCC(dl, Cond, 3442 DAG.getConstant(0, dl, Cond.getValueType()), 3443 SelectTrue, SelectFalse, ISD::SETNE); 3444 } 3445 3446 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3447 bool &swpCmpOps, bool &swpVselOps) { 3448 // Start by selecting the GE condition code for opcodes that return true for 3449 // 'equality' 3450 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3451 CC == ISD::SETULE) 3452 CondCode = ARMCC::GE; 3453 3454 // and GT for opcodes that return false for 'equality'. 3455 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3456 CC == ISD::SETULT) 3457 CondCode = ARMCC::GT; 3458 3459 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3460 // to swap the compare operands. 3461 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3462 CC == ISD::SETULT) 3463 swpCmpOps = true; 3464 3465 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3466 // If we have an unordered opcode, we need to swap the operands to the VSEL 3467 // instruction (effectively negating the condition). 3468 // 3469 // This also has the effect of swapping which one of 'less' or 'greater' 3470 // returns true, so we also swap the compare operands. It also switches 3471 // whether we return true for 'equality', so we compensate by picking the 3472 // opposite condition code to our original choice. 3473 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3474 CC == ISD::SETUGT) { 3475 swpCmpOps = !swpCmpOps; 3476 swpVselOps = !swpVselOps; 3477 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3478 } 3479 3480 // 'ordered' is 'anything but unordered', so use the VS condition code and 3481 // swap the VSEL operands. 3482 if (CC == ISD::SETO) { 3483 CondCode = ARMCC::VS; 3484 swpVselOps = true; 3485 } 3486 3487 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3488 // code and swap the VSEL operands. 3489 if (CC == ISD::SETUNE) { 3490 CondCode = ARMCC::EQ; 3491 swpVselOps = true; 3492 } 3493 } 3494 3495 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal, 3496 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3497 SDValue Cmp, SelectionDAG &DAG) const { 3498 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3499 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3500 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3501 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3502 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3503 3504 SDValue TrueLow = TrueVal.getValue(0); 3505 SDValue TrueHigh = TrueVal.getValue(1); 3506 SDValue FalseLow = FalseVal.getValue(0); 3507 SDValue FalseHigh = FalseVal.getValue(1); 3508 3509 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3510 ARMcc, CCR, Cmp); 3511 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3512 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3513 3514 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3515 } else { 3516 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3517 Cmp); 3518 } 3519 } 3520 3521 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3522 EVT VT = Op.getValueType(); 3523 SDValue LHS = Op.getOperand(0); 3524 SDValue RHS = Op.getOperand(1); 3525 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3526 SDValue TrueVal = Op.getOperand(2); 3527 SDValue FalseVal = Op.getOperand(3); 3528 SDLoc dl(Op); 3529 3530 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3531 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3532 dl); 3533 3534 // If softenSetCCOperands only returned one value, we should compare it to 3535 // zero. 3536 if (!RHS.getNode()) { 3537 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3538 CC = ISD::SETNE; 3539 } 3540 } 3541 3542 if (LHS.getValueType() == MVT::i32) { 3543 // Try to generate VSEL on ARMv8. 3544 // The VSEL instruction can't use all the usual ARM condition 3545 // codes: it only has two bits to select the condition code, so it's 3546 // constrained to use only GE, GT, VS and EQ. 3547 // 3548 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3549 // swap the operands of the previous compare instruction (effectively 3550 // inverting the compare condition, swapping 'less' and 'greater') and 3551 // sometimes need to swap the operands to the VSEL (which inverts the 3552 // condition in the sense of firing whenever the previous condition didn't) 3553 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3554 TrueVal.getValueType() == MVT::f64)) { 3555 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3556 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3557 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3558 CC = ISD::getSetCCInverse(CC, true); 3559 std::swap(TrueVal, FalseVal); 3560 } 3561 } 3562 3563 SDValue ARMcc; 3564 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3565 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3566 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3567 } 3568 3569 ARMCC::CondCodes CondCode, CondCode2; 3570 FPCCToARMCC(CC, CondCode, CondCode2); 3571 3572 // Try to generate VMAXNM/VMINNM on ARMv8. 3573 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3574 TrueVal.getValueType() == MVT::f64)) { 3575 // We can use VMAXNM/VMINNM for a compare followed by a select with the 3576 // same operands, as follows: 3577 // c = fcmp [?gt, ?ge, ?lt, ?le] a, b 3578 // select c, a, b 3579 // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'. 3580 bool swapSides = false; 3581 if (!getTargetMachine().Options.NoNaNsFPMath) { 3582 // transformability may depend on which way around we compare 3583 switch (CC) { 3584 default: 3585 break; 3586 case ISD::SETOGT: 3587 case ISD::SETOGE: 3588 case ISD::SETOLT: 3589 case ISD::SETOLE: 3590 // the non-NaN should be RHS 3591 swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS); 3592 break; 3593 case ISD::SETUGT: 3594 case ISD::SETUGE: 3595 case ISD::SETULT: 3596 case ISD::SETULE: 3597 // the non-NaN should be LHS 3598 swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS); 3599 break; 3600 } 3601 } 3602 swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal); 3603 if (swapSides) { 3604 CC = ISD::getSetCCSwappedOperands(CC); 3605 std::swap(LHS, RHS); 3606 } 3607 if (LHS == TrueVal && RHS == FalseVal) { 3608 bool canTransform = true; 3609 // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here 3610 if (!getTargetMachine().Options.UnsafeFPMath && 3611 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 3612 const ConstantFPSDNode *Zero; 3613 switch (CC) { 3614 default: 3615 break; 3616 case ISD::SETOGT: 3617 case ISD::SETUGT: 3618 case ISD::SETGT: 3619 // RHS must not be -0 3620 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) && 3621 !Zero->isNegative(); 3622 break; 3623 case ISD::SETOGE: 3624 case ISD::SETUGE: 3625 case ISD::SETGE: 3626 // LHS must not be -0 3627 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) && 3628 !Zero->isNegative(); 3629 break; 3630 case ISD::SETOLT: 3631 case ISD::SETULT: 3632 case ISD::SETLT: 3633 // RHS must not be +0 3634 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) && 3635 Zero->isNegative(); 3636 break; 3637 case ISD::SETOLE: 3638 case ISD::SETULE: 3639 case ISD::SETLE: 3640 // LHS must not be +0 3641 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) && 3642 Zero->isNegative(); 3643 break; 3644 } 3645 } 3646 if (canTransform) { 3647 // Note: If one of the elements in a pair is a number and the other 3648 // element is NaN, the corresponding result element is the number. 3649 // This is consistent with the IEEE 754-2008 standard. 3650 // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN 3651 switch (CC) { 3652 default: 3653 break; 3654 case ISD::SETOGT: 3655 case ISD::SETOGE: 3656 if (!DAG.isKnownNeverNaN(RHS)) 3657 break; 3658 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS); 3659 case ISD::SETUGT: 3660 case ISD::SETUGE: 3661 if (!DAG.isKnownNeverNaN(LHS)) 3662 break; 3663 case ISD::SETGT: 3664 case ISD::SETGE: 3665 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS); 3666 case ISD::SETOLT: 3667 case ISD::SETOLE: 3668 if (!DAG.isKnownNeverNaN(RHS)) 3669 break; 3670 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS); 3671 case ISD::SETULT: 3672 case ISD::SETULE: 3673 if (!DAG.isKnownNeverNaN(LHS)) 3674 break; 3675 case ISD::SETLT: 3676 case ISD::SETLE: 3677 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS); 3678 } 3679 } 3680 } 3681 3682 bool swpCmpOps = false; 3683 bool swpVselOps = false; 3684 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3685 3686 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3687 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3688 if (swpCmpOps) 3689 std::swap(LHS, RHS); 3690 if (swpVselOps) 3691 std::swap(TrueVal, FalseVal); 3692 } 3693 } 3694 3695 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3696 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3697 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3698 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3699 if (CondCode2 != ARMCC::AL) { 3700 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 3701 // FIXME: Needs another CMP because flag can have but one use. 3702 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3703 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3704 } 3705 return Result; 3706 } 3707 3708 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3709 /// to morph to an integer compare sequence. 3710 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3711 const ARMSubtarget *Subtarget) { 3712 SDNode *N = Op.getNode(); 3713 if (!N->hasOneUse()) 3714 // Otherwise it requires moving the value from fp to integer registers. 3715 return false; 3716 if (!N->getNumValues()) 3717 return false; 3718 EVT VT = Op.getValueType(); 3719 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3720 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3721 // vmrs are very slow, e.g. cortex-a8. 3722 return false; 3723 3724 if (isFloatingPointZero(Op)) { 3725 SeenZero = true; 3726 return true; 3727 } 3728 return ISD::isNormalLoad(N); 3729 } 3730 3731 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3732 if (isFloatingPointZero(Op)) 3733 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 3734 3735 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3736 return DAG.getLoad(MVT::i32, SDLoc(Op), 3737 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3738 Ld->isVolatile(), Ld->isNonTemporal(), 3739 Ld->isInvariant(), Ld->getAlignment()); 3740 3741 llvm_unreachable("Unknown VFP cmp argument!"); 3742 } 3743 3744 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3745 SDValue &RetVal1, SDValue &RetVal2) { 3746 SDLoc dl(Op); 3747 3748 if (isFloatingPointZero(Op)) { 3749 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 3750 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 3751 return; 3752 } 3753 3754 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3755 SDValue Ptr = Ld->getBasePtr(); 3756 RetVal1 = DAG.getLoad(MVT::i32, dl, 3757 Ld->getChain(), Ptr, 3758 Ld->getPointerInfo(), 3759 Ld->isVolatile(), Ld->isNonTemporal(), 3760 Ld->isInvariant(), Ld->getAlignment()); 3761 3762 EVT PtrType = Ptr.getValueType(); 3763 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3764 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 3765 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 3766 RetVal2 = DAG.getLoad(MVT::i32, dl, 3767 Ld->getChain(), NewPtr, 3768 Ld->getPointerInfo().getWithOffset(4), 3769 Ld->isVolatile(), Ld->isNonTemporal(), 3770 Ld->isInvariant(), NewAlign); 3771 return; 3772 } 3773 3774 llvm_unreachable("Unknown VFP cmp argument!"); 3775 } 3776 3777 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 3778 /// f32 and even f64 comparisons to integer ones. 3779 SDValue 3780 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 3781 SDValue Chain = Op.getOperand(0); 3782 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3783 SDValue LHS = Op.getOperand(2); 3784 SDValue RHS = Op.getOperand(3); 3785 SDValue Dest = Op.getOperand(4); 3786 SDLoc dl(Op); 3787 3788 bool LHSSeenZero = false; 3789 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 3790 bool RHSSeenZero = false; 3791 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 3792 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 3793 // If unsafe fp math optimization is enabled and there are no other uses of 3794 // the CMP operands, and the condition code is EQ or NE, we can optimize it 3795 // to an integer comparison. 3796 if (CC == ISD::SETOEQ) 3797 CC = ISD::SETEQ; 3798 else if (CC == ISD::SETUNE) 3799 CC = ISD::SETNE; 3800 3801 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 3802 SDValue ARMcc; 3803 if (LHS.getValueType() == MVT::f32) { 3804 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3805 bitcastf32Toi32(LHS, DAG), Mask); 3806 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3807 bitcastf32Toi32(RHS, DAG), Mask); 3808 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3809 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3810 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3811 Chain, Dest, ARMcc, CCR, Cmp); 3812 } 3813 3814 SDValue LHS1, LHS2; 3815 SDValue RHS1, RHS2; 3816 expandf64Toi32(LHS, DAG, LHS1, LHS2); 3817 expandf64Toi32(RHS, DAG, RHS1, RHS2); 3818 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 3819 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 3820 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3821 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3822 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3823 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 3824 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 3825 } 3826 3827 return SDValue(); 3828 } 3829 3830 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3831 SDValue Chain = Op.getOperand(0); 3832 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3833 SDValue LHS = Op.getOperand(2); 3834 SDValue RHS = Op.getOperand(3); 3835 SDValue Dest = Op.getOperand(4); 3836 SDLoc dl(Op); 3837 3838 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3839 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3840 dl); 3841 3842 // If softenSetCCOperands only returned one value, we should compare it to 3843 // zero. 3844 if (!RHS.getNode()) { 3845 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3846 CC = ISD::SETNE; 3847 } 3848 } 3849 3850 if (LHS.getValueType() == MVT::i32) { 3851 SDValue ARMcc; 3852 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3853 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3854 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3855 Chain, Dest, ARMcc, CCR, Cmp); 3856 } 3857 3858 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3859 3860 if (getTargetMachine().Options.UnsafeFPMath && 3861 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 3862 CC == ISD::SETNE || CC == ISD::SETUNE)) { 3863 SDValue Result = OptimizeVFPBrcond(Op, DAG); 3864 if (Result.getNode()) 3865 return Result; 3866 } 3867 3868 ARMCC::CondCodes CondCode, CondCode2; 3869 FPCCToARMCC(CC, CondCode, CondCode2); 3870 3871 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3872 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3873 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3874 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3875 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 3876 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3877 if (CondCode2 != ARMCC::AL) { 3878 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 3879 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 3880 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3881 } 3882 return Res; 3883 } 3884 3885 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 3886 SDValue Chain = Op.getOperand(0); 3887 SDValue Table = Op.getOperand(1); 3888 SDValue Index = Op.getOperand(2); 3889 SDLoc dl(Op); 3890 3891 EVT PTy = getPointerTy(DAG.getDataLayout()); 3892 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 3893 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 3894 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 3895 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 3896 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 3897 if (Subtarget->isThumb2()) { 3898 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 3899 // which does another jump to the destination. This also makes it easier 3900 // to translate it to TBB / TBH later. 3901 // FIXME: This might not work if the function is extremely large. 3902 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 3903 Addr, Op.getOperand(2), JTI); 3904 } 3905 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 3906 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 3907 MachinePointerInfo::getJumpTable(), 3908 false, false, false, 0); 3909 Chain = Addr.getValue(1); 3910 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 3911 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 3912 } else { 3913 Addr = DAG.getLoad(PTy, dl, Chain, Addr, 3914 MachinePointerInfo::getJumpTable(), 3915 false, false, false, 0); 3916 Chain = Addr.getValue(1); 3917 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 3918 } 3919 } 3920 3921 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 3922 EVT VT = Op.getValueType(); 3923 SDLoc dl(Op); 3924 3925 if (Op.getValueType().getVectorElementType() == MVT::i32) { 3926 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 3927 return Op; 3928 return DAG.UnrollVectorOp(Op.getNode()); 3929 } 3930 3931 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 3932 "Invalid type for custom lowering!"); 3933 if (VT != MVT::v4i16) 3934 return DAG.UnrollVectorOp(Op.getNode()); 3935 3936 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 3937 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 3938 } 3939 3940 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 3941 EVT VT = Op.getValueType(); 3942 if (VT.isVector()) 3943 return LowerVectorFP_TO_INT(Op, DAG); 3944 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 3945 RTLIB::Libcall LC; 3946 if (Op.getOpcode() == ISD::FP_TO_SINT) 3947 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 3948 Op.getValueType()); 3949 else 3950 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 3951 Op.getValueType()); 3952 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1, 3953 /*isSigned*/ false, SDLoc(Op)).first; 3954 } 3955 3956 return Op; 3957 } 3958 3959 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 3960 EVT VT = Op.getValueType(); 3961 SDLoc dl(Op); 3962 3963 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 3964 if (VT.getVectorElementType() == MVT::f32) 3965 return Op; 3966 return DAG.UnrollVectorOp(Op.getNode()); 3967 } 3968 3969 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 3970 "Invalid type for custom lowering!"); 3971 if (VT != MVT::v4f32) 3972 return DAG.UnrollVectorOp(Op.getNode()); 3973 3974 unsigned CastOpc; 3975 unsigned Opc; 3976 switch (Op.getOpcode()) { 3977 default: llvm_unreachable("Invalid opcode!"); 3978 case ISD::SINT_TO_FP: 3979 CastOpc = ISD::SIGN_EXTEND; 3980 Opc = ISD::SINT_TO_FP; 3981 break; 3982 case ISD::UINT_TO_FP: 3983 CastOpc = ISD::ZERO_EXTEND; 3984 Opc = ISD::UINT_TO_FP; 3985 break; 3986 } 3987 3988 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 3989 return DAG.getNode(Opc, dl, VT, Op); 3990 } 3991 3992 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 3993 EVT VT = Op.getValueType(); 3994 if (VT.isVector()) 3995 return LowerVectorINT_TO_FP(Op, DAG); 3996 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 3997 RTLIB::Libcall LC; 3998 if (Op.getOpcode() == ISD::SINT_TO_FP) 3999 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4000 Op.getValueType()); 4001 else 4002 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4003 Op.getValueType()); 4004 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1, 4005 /*isSigned*/ false, SDLoc(Op)).first; 4006 } 4007 4008 return Op; 4009 } 4010 4011 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4012 // Implement fcopysign with a fabs and a conditional fneg. 4013 SDValue Tmp0 = Op.getOperand(0); 4014 SDValue Tmp1 = Op.getOperand(1); 4015 SDLoc dl(Op); 4016 EVT VT = Op.getValueType(); 4017 EVT SrcVT = Tmp1.getValueType(); 4018 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4019 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4020 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4021 4022 if (UseNEON) { 4023 // Use VBSL to copy the sign bit. 4024 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4025 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4026 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4027 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4028 if (VT == MVT::f64) 4029 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4030 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4031 DAG.getConstant(32, dl, MVT::i32)); 4032 else /*if (VT == MVT::f32)*/ 4033 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4034 if (SrcVT == MVT::f32) { 4035 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4036 if (VT == MVT::f64) 4037 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4038 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4039 DAG.getConstant(32, dl, MVT::i32)); 4040 } else if (VT == MVT::f32) 4041 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4042 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4043 DAG.getConstant(32, dl, MVT::i32)); 4044 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4045 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4046 4047 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4048 dl, MVT::i32); 4049 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4050 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4051 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4052 4053 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4054 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4055 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4056 if (VT == MVT::f32) { 4057 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4058 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4059 DAG.getConstant(0, dl, MVT::i32)); 4060 } else { 4061 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4062 } 4063 4064 return Res; 4065 } 4066 4067 // Bitcast operand 1 to i32. 4068 if (SrcVT == MVT::f64) 4069 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4070 Tmp1).getValue(1); 4071 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4072 4073 // Or in the signbit with integer operations. 4074 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4075 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4076 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4077 if (VT == MVT::f32) { 4078 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4079 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4080 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4081 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4082 } 4083 4084 // f64: Or the high part with signbit and then combine two parts. 4085 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4086 Tmp0); 4087 SDValue Lo = Tmp0.getValue(0); 4088 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4089 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4090 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4091 } 4092 4093 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4094 MachineFunction &MF = DAG.getMachineFunction(); 4095 MachineFrameInfo *MFI = MF.getFrameInfo(); 4096 MFI->setReturnAddressIsTaken(true); 4097 4098 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4099 return SDValue(); 4100 4101 EVT VT = Op.getValueType(); 4102 SDLoc dl(Op); 4103 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4104 if (Depth) { 4105 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4106 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4107 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4108 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4109 MachinePointerInfo(), false, false, false, 0); 4110 } 4111 4112 // Return LR, which contains the return address. Mark it an implicit live-in. 4113 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4114 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4115 } 4116 4117 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4118 const ARMBaseRegisterInfo &ARI = 4119 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4120 MachineFunction &MF = DAG.getMachineFunction(); 4121 MachineFrameInfo *MFI = MF.getFrameInfo(); 4122 MFI->setFrameAddressIsTaken(true); 4123 4124 EVT VT = Op.getValueType(); 4125 SDLoc dl(Op); // FIXME probably not meaningful 4126 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4127 unsigned FrameReg = ARI.getFrameRegister(MF); 4128 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4129 while (Depth--) 4130 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4131 MachinePointerInfo(), 4132 false, false, false, 0); 4133 return FrameAddr; 4134 } 4135 4136 // FIXME? Maybe this could be a TableGen attribute on some registers and 4137 // this table could be generated automatically from RegInfo. 4138 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4139 SelectionDAG &DAG) const { 4140 unsigned Reg = StringSwitch<unsigned>(RegName) 4141 .Case("sp", ARM::SP) 4142 .Default(0); 4143 if (Reg) 4144 return Reg; 4145 report_fatal_error(Twine("Invalid register name \"" 4146 + StringRef(RegName) + "\".")); 4147 } 4148 4149 // Result is 64 bit value so split into two 32 bit values and return as a 4150 // pair of values. 4151 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4152 SelectionDAG &DAG) { 4153 SDLoc DL(N); 4154 4155 // This function is only supposed to be called for i64 type destination. 4156 assert(N->getValueType(0) == MVT::i64 4157 && "ExpandREAD_REGISTER called for non-i64 type result."); 4158 4159 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4160 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4161 N->getOperand(0), 4162 N->getOperand(1)); 4163 4164 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4165 Read.getValue(1))); 4166 Results.push_back(Read.getOperand(0)); 4167 } 4168 4169 /// ExpandBITCAST - If the target supports VFP, this function is called to 4170 /// expand a bit convert where either the source or destination type is i64 to 4171 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4172 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4173 /// vectors), since the legalizer won't know what to do with that. 4174 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4175 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4176 SDLoc dl(N); 4177 SDValue Op = N->getOperand(0); 4178 4179 // This function is only supposed to be called for i64 types, either as the 4180 // source or destination of the bit convert. 4181 EVT SrcVT = Op.getValueType(); 4182 EVT DstVT = N->getValueType(0); 4183 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4184 "ExpandBITCAST called for non-i64 type"); 4185 4186 // Turn i64->f64 into VMOVDRR. 4187 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4188 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4189 DAG.getConstant(0, dl, MVT::i32)); 4190 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4191 DAG.getConstant(1, dl, MVT::i32)); 4192 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4193 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4194 } 4195 4196 // Turn f64->i64 into VMOVRRD. 4197 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4198 SDValue Cvt; 4199 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4200 SrcVT.getVectorNumElements() > 1) 4201 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4202 DAG.getVTList(MVT::i32, MVT::i32), 4203 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4204 else 4205 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4206 DAG.getVTList(MVT::i32, MVT::i32), Op); 4207 // Merge the pieces into a single i64 value. 4208 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4209 } 4210 4211 return SDValue(); 4212 } 4213 4214 /// getZeroVector - Returns a vector of specified type with all zero elements. 4215 /// Zero vectors are used to represent vector negation and in those cases 4216 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4217 /// not support i64 elements, so sometimes the zero vectors will need to be 4218 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4219 /// zero vector. 4220 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) { 4221 assert(VT.isVector() && "Expected a vector type"); 4222 // The canonical modified immediate encoding of a zero vector is....0! 4223 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4224 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4225 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4226 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4227 } 4228 4229 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4230 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4231 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4232 SelectionDAG &DAG) const { 4233 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4234 EVT VT = Op.getValueType(); 4235 unsigned VTBits = VT.getSizeInBits(); 4236 SDLoc dl(Op); 4237 SDValue ShOpLo = Op.getOperand(0); 4238 SDValue ShOpHi = Op.getOperand(1); 4239 SDValue ShAmt = Op.getOperand(2); 4240 SDValue ARMcc; 4241 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4242 4243 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4244 4245 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4246 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4247 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4248 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4249 DAG.getConstant(VTBits, dl, MVT::i32)); 4250 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4251 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4252 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4253 4254 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4255 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4256 ISD::SETGE, ARMcc, DAG, dl); 4257 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4258 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4259 CCR, Cmp); 4260 4261 SDValue Ops[2] = { Lo, Hi }; 4262 return DAG.getMergeValues(Ops, dl); 4263 } 4264 4265 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4266 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4267 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4268 SelectionDAG &DAG) const { 4269 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4270 EVT VT = Op.getValueType(); 4271 unsigned VTBits = VT.getSizeInBits(); 4272 SDLoc dl(Op); 4273 SDValue ShOpLo = Op.getOperand(0); 4274 SDValue ShOpHi = Op.getOperand(1); 4275 SDValue ShAmt = Op.getOperand(2); 4276 SDValue ARMcc; 4277 4278 assert(Op.getOpcode() == ISD::SHL_PARTS); 4279 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4280 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4281 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4282 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4283 DAG.getConstant(VTBits, dl, MVT::i32)); 4284 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4285 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4286 4287 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4288 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4289 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4290 ISD::SETGE, ARMcc, DAG, dl); 4291 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4292 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4293 CCR, Cmp); 4294 4295 SDValue Ops[2] = { Lo, Hi }; 4296 return DAG.getMergeValues(Ops, dl); 4297 } 4298 4299 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4300 SelectionDAG &DAG) const { 4301 // The rounding mode is in bits 23:22 of the FPSCR. 4302 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4303 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4304 // so that the shift + and get folded into a bitfield extract. 4305 SDLoc dl(Op); 4306 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4307 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4308 MVT::i32)); 4309 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4310 DAG.getConstant(1U << 22, dl, MVT::i32)); 4311 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4312 DAG.getConstant(22, dl, MVT::i32)); 4313 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4314 DAG.getConstant(3, dl, MVT::i32)); 4315 } 4316 4317 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4318 const ARMSubtarget *ST) { 4319 SDLoc dl(N); 4320 EVT VT = N->getValueType(0); 4321 if (VT.isVector()) { 4322 assert(ST->hasNEON()); 4323 4324 // Compute the least significant set bit: LSB = X & -X 4325 SDValue X = N->getOperand(0); 4326 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4327 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4328 4329 EVT ElemTy = VT.getVectorElementType(); 4330 4331 if (ElemTy == MVT::i8) { 4332 // Compute with: cttz(x) = ctpop(lsb - 1) 4333 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4334 DAG.getTargetConstant(1, dl, ElemTy)); 4335 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4336 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4337 } 4338 4339 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4340 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4341 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4342 unsigned NumBits = ElemTy.getSizeInBits(); 4343 SDValue WidthMinus1 = 4344 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4345 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4346 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4347 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4348 } 4349 4350 // Compute with: cttz(x) = ctpop(lsb - 1) 4351 4352 // Since we can only compute the number of bits in a byte with vcnt.8, we 4353 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4354 // and i64. 4355 4356 // Compute LSB - 1. 4357 SDValue Bits; 4358 if (ElemTy == MVT::i64) { 4359 // Load constant 0xffff'ffff'ffff'ffff to register. 4360 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4361 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4362 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4363 } else { 4364 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4365 DAG.getTargetConstant(1, dl, ElemTy)); 4366 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4367 } 4368 4369 // Count #bits with vcnt.8. 4370 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4371 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4372 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4373 4374 // Gather the #bits with vpaddl (pairwise add.) 4375 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4376 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4377 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4378 Cnt8); 4379 if (ElemTy == MVT::i16) 4380 return Cnt16; 4381 4382 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4383 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4384 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4385 Cnt16); 4386 if (ElemTy == MVT::i32) 4387 return Cnt32; 4388 4389 assert(ElemTy == MVT::i64); 4390 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4391 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4392 Cnt32); 4393 return Cnt64; 4394 } 4395 4396 if (!ST->hasV6T2Ops()) 4397 return SDValue(); 4398 4399 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0)); 4400 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4401 } 4402 4403 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4404 /// for each 16-bit element from operand, repeated. The basic idea is to 4405 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4406 /// 4407 /// Trace for v4i16: 4408 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4409 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4410 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4411 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4412 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4413 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4414 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4415 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4416 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4417 EVT VT = N->getValueType(0); 4418 SDLoc DL(N); 4419 4420 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4421 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4422 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4423 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4424 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4425 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4426 } 4427 4428 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4429 /// bit-count for each 16-bit element from the operand. We need slightly 4430 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4431 /// 64/128-bit registers. 4432 /// 4433 /// Trace for v4i16: 4434 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4435 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4436 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4437 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4438 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4439 EVT VT = N->getValueType(0); 4440 SDLoc DL(N); 4441 4442 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4443 if (VT.is64BitVector()) { 4444 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4445 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4446 DAG.getIntPtrConstant(0, DL)); 4447 } else { 4448 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4449 BitCounts, DAG.getIntPtrConstant(0, DL)); 4450 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4451 } 4452 } 4453 4454 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4455 /// bit-count for each 32-bit element from the operand. The idea here is 4456 /// to split the vector into 16-bit elements, leverage the 16-bit count 4457 /// routine, and then combine the results. 4458 /// 4459 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4460 /// input = [v0 v1 ] (vi: 32-bit elements) 4461 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4462 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4463 /// vrev: N0 = [k1 k0 k3 k2 ] 4464 /// [k0 k1 k2 k3 ] 4465 /// N1 =+[k1 k0 k3 k2 ] 4466 /// [k0 k2 k1 k3 ] 4467 /// N2 =+[k1 k3 k0 k2 ] 4468 /// [k0 k2 k1 k3 ] 4469 /// Extended =+[k1 k3 k0 k2 ] 4470 /// [k0 k2 ] 4471 /// Extracted=+[k1 k3 ] 4472 /// 4473 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4474 EVT VT = N->getValueType(0); 4475 SDLoc DL(N); 4476 4477 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4478 4479 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4480 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4481 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4482 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4483 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4484 4485 if (VT.is64BitVector()) { 4486 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4487 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4488 DAG.getIntPtrConstant(0, DL)); 4489 } else { 4490 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4491 DAG.getIntPtrConstant(0, DL)); 4492 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4493 } 4494 } 4495 4496 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4497 const ARMSubtarget *ST) { 4498 EVT VT = N->getValueType(0); 4499 4500 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4501 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4502 VT == MVT::v4i16 || VT == MVT::v8i16) && 4503 "Unexpected type for custom ctpop lowering"); 4504 4505 if (VT.getVectorElementType() == MVT::i32) 4506 return lowerCTPOP32BitElements(N, DAG); 4507 else 4508 return lowerCTPOP16BitElements(N, DAG); 4509 } 4510 4511 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4512 const ARMSubtarget *ST) { 4513 EVT VT = N->getValueType(0); 4514 SDLoc dl(N); 4515 4516 if (!VT.isVector()) 4517 return SDValue(); 4518 4519 // Lower vector shifts on NEON to use VSHL. 4520 assert(ST->hasNEON() && "unexpected vector shift"); 4521 4522 // Left shifts translate directly to the vshiftu intrinsic. 4523 if (N->getOpcode() == ISD::SHL) 4524 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4525 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4526 MVT::i32), 4527 N->getOperand(0), N->getOperand(1)); 4528 4529 assert((N->getOpcode() == ISD::SRA || 4530 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4531 4532 // NEON uses the same intrinsics for both left and right shifts. For 4533 // right shifts, the shift amounts are negative, so negate the vector of 4534 // shift amounts. 4535 EVT ShiftVT = N->getOperand(1).getValueType(); 4536 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4537 getZeroVector(ShiftVT, DAG, dl), 4538 N->getOperand(1)); 4539 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4540 Intrinsic::arm_neon_vshifts : 4541 Intrinsic::arm_neon_vshiftu); 4542 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4543 DAG.getConstant(vshiftInt, dl, MVT::i32), 4544 N->getOperand(0), NegatedCount); 4545 } 4546 4547 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4548 const ARMSubtarget *ST) { 4549 EVT VT = N->getValueType(0); 4550 SDLoc dl(N); 4551 4552 // We can get here for a node like i32 = ISD::SHL i32, i64 4553 if (VT != MVT::i64) 4554 return SDValue(); 4555 4556 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4557 "Unknown shift to lower!"); 4558 4559 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4560 if (!isa<ConstantSDNode>(N->getOperand(1)) || 4561 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1) 4562 return SDValue(); 4563 4564 // If we are in thumb mode, we don't have RRX. 4565 if (ST->isThumb1Only()) return SDValue(); 4566 4567 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4568 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4569 DAG.getConstant(0, dl, MVT::i32)); 4570 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4571 DAG.getConstant(1, dl, MVT::i32)); 4572 4573 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4574 // captures the result into a carry flag. 4575 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4576 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4577 4578 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4579 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4580 4581 // Merge the pieces into a single i64 value. 4582 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4583 } 4584 4585 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4586 SDValue TmpOp0, TmpOp1; 4587 bool Invert = false; 4588 bool Swap = false; 4589 unsigned Opc = 0; 4590 4591 SDValue Op0 = Op.getOperand(0); 4592 SDValue Op1 = Op.getOperand(1); 4593 SDValue CC = Op.getOperand(2); 4594 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 4595 EVT VT = Op.getValueType(); 4596 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4597 SDLoc dl(Op); 4598 4599 if (Op1.getValueType().isFloatingPoint()) { 4600 switch (SetCCOpcode) { 4601 default: llvm_unreachable("Illegal FP comparison"); 4602 case ISD::SETUNE: 4603 case ISD::SETNE: Invert = true; // Fallthrough 4604 case ISD::SETOEQ: 4605 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4606 case ISD::SETOLT: 4607 case ISD::SETLT: Swap = true; // Fallthrough 4608 case ISD::SETOGT: 4609 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4610 case ISD::SETOLE: 4611 case ISD::SETLE: Swap = true; // Fallthrough 4612 case ISD::SETOGE: 4613 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4614 case ISD::SETUGE: Swap = true; // Fallthrough 4615 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4616 case ISD::SETUGT: Swap = true; // Fallthrough 4617 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4618 case ISD::SETUEQ: Invert = true; // Fallthrough 4619 case ISD::SETONE: 4620 // Expand this to (OLT | OGT). 4621 TmpOp0 = Op0; 4622 TmpOp1 = Op1; 4623 Opc = ISD::OR; 4624 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4625 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 4626 break; 4627 case ISD::SETUO: Invert = true; // Fallthrough 4628 case ISD::SETO: 4629 // Expand this to (OLT | OGE). 4630 TmpOp0 = Op0; 4631 TmpOp1 = Op1; 4632 Opc = ISD::OR; 4633 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4634 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 4635 break; 4636 } 4637 } else { 4638 // Integer comparisons. 4639 switch (SetCCOpcode) { 4640 default: llvm_unreachable("Illegal integer comparison"); 4641 case ISD::SETNE: Invert = true; 4642 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4643 case ISD::SETLT: Swap = true; 4644 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4645 case ISD::SETLE: Swap = true; 4646 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4647 case ISD::SETULT: Swap = true; 4648 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4649 case ISD::SETULE: Swap = true; 4650 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4651 } 4652 4653 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4654 if (Opc == ARMISD::VCEQ) { 4655 4656 SDValue AndOp; 4657 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4658 AndOp = Op0; 4659 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4660 AndOp = Op1; 4661 4662 // Ignore bitconvert. 4663 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4664 AndOp = AndOp.getOperand(0); 4665 4666 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4667 Opc = ARMISD::VTST; 4668 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 4669 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 4670 Invert = !Invert; 4671 } 4672 } 4673 } 4674 4675 if (Swap) 4676 std::swap(Op0, Op1); 4677 4678 // If one of the operands is a constant vector zero, attempt to fold the 4679 // comparison to a specialized compare-against-zero form. 4680 SDValue SingleOp; 4681 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4682 SingleOp = Op0; 4683 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4684 if (Opc == ARMISD::VCGE) 4685 Opc = ARMISD::VCLEZ; 4686 else if (Opc == ARMISD::VCGT) 4687 Opc = ARMISD::VCLTZ; 4688 SingleOp = Op1; 4689 } 4690 4691 SDValue Result; 4692 if (SingleOp.getNode()) { 4693 switch (Opc) { 4694 case ARMISD::VCEQ: 4695 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 4696 case ARMISD::VCGE: 4697 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 4698 case ARMISD::VCLEZ: 4699 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 4700 case ARMISD::VCGT: 4701 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 4702 case ARMISD::VCLTZ: 4703 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 4704 default: 4705 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4706 } 4707 } else { 4708 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4709 } 4710 4711 Result = DAG.getSExtOrTrunc(Result, dl, VT); 4712 4713 if (Invert) 4714 Result = DAG.getNOT(dl, Result, VT); 4715 4716 return Result; 4717 } 4718 4719 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4720 /// valid vector constant for a NEON instruction with a "modified immediate" 4721 /// operand (e.g., VMOV). If so, return the encoded value. 4722 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4723 unsigned SplatBitSize, SelectionDAG &DAG, 4724 SDLoc dl, EVT &VT, bool is128Bits, 4725 NEONModImmType type) { 4726 unsigned OpCmode, Imm; 4727 4728 // SplatBitSize is set to the smallest size that splats the vector, so a 4729 // zero vector will always have SplatBitSize == 8. However, NEON modified 4730 // immediate instructions others than VMOV do not support the 8-bit encoding 4731 // of a zero vector, and the default encoding of zero is supposed to be the 4732 // 32-bit version. 4733 if (SplatBits == 0) 4734 SplatBitSize = 32; 4735 4736 switch (SplatBitSize) { 4737 case 8: 4738 if (type != VMOVModImm) 4739 return SDValue(); 4740 // Any 1-byte value is OK. Op=0, Cmode=1110. 4741 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4742 OpCmode = 0xe; 4743 Imm = SplatBits; 4744 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4745 break; 4746 4747 case 16: 4748 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4749 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4750 if ((SplatBits & ~0xff) == 0) { 4751 // Value = 0x00nn: Op=x, Cmode=100x. 4752 OpCmode = 0x8; 4753 Imm = SplatBits; 4754 break; 4755 } 4756 if ((SplatBits & ~0xff00) == 0) { 4757 // Value = 0xnn00: Op=x, Cmode=101x. 4758 OpCmode = 0xa; 4759 Imm = SplatBits >> 8; 4760 break; 4761 } 4762 return SDValue(); 4763 4764 case 32: 4765 // NEON's 32-bit VMOV supports splat values where: 4766 // * only one byte is nonzero, or 4767 // * the least significant byte is 0xff and the second byte is nonzero, or 4768 // * the least significant 2 bytes are 0xff and the third is nonzero. 4769 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4770 if ((SplatBits & ~0xff) == 0) { 4771 // Value = 0x000000nn: Op=x, Cmode=000x. 4772 OpCmode = 0; 4773 Imm = SplatBits; 4774 break; 4775 } 4776 if ((SplatBits & ~0xff00) == 0) { 4777 // Value = 0x0000nn00: Op=x, Cmode=001x. 4778 OpCmode = 0x2; 4779 Imm = SplatBits >> 8; 4780 break; 4781 } 4782 if ((SplatBits & ~0xff0000) == 0) { 4783 // Value = 0x00nn0000: Op=x, Cmode=010x. 4784 OpCmode = 0x4; 4785 Imm = SplatBits >> 16; 4786 break; 4787 } 4788 if ((SplatBits & ~0xff000000) == 0) { 4789 // Value = 0xnn000000: Op=x, Cmode=011x. 4790 OpCmode = 0x6; 4791 Imm = SplatBits >> 24; 4792 break; 4793 } 4794 4795 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 4796 if (type == OtherModImm) return SDValue(); 4797 4798 if ((SplatBits & ~0xffff) == 0 && 4799 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 4800 // Value = 0x0000nnff: Op=x, Cmode=1100. 4801 OpCmode = 0xc; 4802 Imm = SplatBits >> 8; 4803 break; 4804 } 4805 4806 if ((SplatBits & ~0xffffff) == 0 && 4807 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 4808 // Value = 0x00nnffff: Op=x, Cmode=1101. 4809 OpCmode = 0xd; 4810 Imm = SplatBits >> 16; 4811 break; 4812 } 4813 4814 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 4815 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 4816 // VMOV.I32. A (very) minor optimization would be to replicate the value 4817 // and fall through here to test for a valid 64-bit splat. But, then the 4818 // caller would also need to check and handle the change in size. 4819 return SDValue(); 4820 4821 case 64: { 4822 if (type != VMOVModImm) 4823 return SDValue(); 4824 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 4825 uint64_t BitMask = 0xff; 4826 uint64_t Val = 0; 4827 unsigned ImmMask = 1; 4828 Imm = 0; 4829 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 4830 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 4831 Val |= BitMask; 4832 Imm |= ImmMask; 4833 } else if ((SplatBits & BitMask) != 0) { 4834 return SDValue(); 4835 } 4836 BitMask <<= 8; 4837 ImmMask <<= 1; 4838 } 4839 4840 if (DAG.getDataLayout().isBigEndian()) 4841 // swap higher and lower 32 bit word 4842 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 4843 4844 // Op=1, Cmode=1110. 4845 OpCmode = 0x1e; 4846 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 4847 break; 4848 } 4849 4850 default: 4851 llvm_unreachable("unexpected size for isNEONModifiedImm"); 4852 } 4853 4854 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 4855 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 4856 } 4857 4858 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 4859 const ARMSubtarget *ST) const { 4860 if (!ST->hasVFP3()) 4861 return SDValue(); 4862 4863 bool IsDouble = Op.getValueType() == MVT::f64; 4864 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 4865 4866 // Use the default (constant pool) lowering for double constants when we have 4867 // an SP-only FPU 4868 if (IsDouble && Subtarget->isFPOnlySP()) 4869 return SDValue(); 4870 4871 // Try splatting with a VMOV.f32... 4872 APFloat FPVal = CFP->getValueAPF(); 4873 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 4874 4875 if (ImmVal != -1) { 4876 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 4877 // We have code in place to select a valid ConstantFP already, no need to 4878 // do any mangling. 4879 return Op; 4880 } 4881 4882 // It's a float and we are trying to use NEON operations where 4883 // possible. Lower it to a splat followed by an extract. 4884 SDLoc DL(Op); 4885 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 4886 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 4887 NewVal); 4888 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 4889 DAG.getConstant(0, DL, MVT::i32)); 4890 } 4891 4892 // The rest of our options are NEON only, make sure that's allowed before 4893 // proceeding.. 4894 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 4895 return SDValue(); 4896 4897 EVT VMovVT; 4898 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 4899 4900 // It wouldn't really be worth bothering for doubles except for one very 4901 // important value, which does happen to match: 0.0. So make sure we don't do 4902 // anything stupid. 4903 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 4904 return SDValue(); 4905 4906 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 4907 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 4908 VMovVT, false, VMOVModImm); 4909 if (NewVal != SDValue()) { 4910 SDLoc DL(Op); 4911 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 4912 NewVal); 4913 if (IsDouble) 4914 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 4915 4916 // It's a float: cast and extract a vector element. 4917 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 4918 VecConstant); 4919 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 4920 DAG.getConstant(0, DL, MVT::i32)); 4921 } 4922 4923 // Finally, try a VMVN.i32 4924 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 4925 false, VMVNModImm); 4926 if (NewVal != SDValue()) { 4927 SDLoc DL(Op); 4928 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 4929 4930 if (IsDouble) 4931 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 4932 4933 // It's a float: cast and extract a vector element. 4934 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 4935 VecConstant); 4936 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 4937 DAG.getConstant(0, DL, MVT::i32)); 4938 } 4939 4940 return SDValue(); 4941 } 4942 4943 // check if an VEXT instruction can handle the shuffle mask when the 4944 // vector sources of the shuffle are the same. 4945 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 4946 unsigned NumElts = VT.getVectorNumElements(); 4947 4948 // Assume that the first shuffle index is not UNDEF. Fail if it is. 4949 if (M[0] < 0) 4950 return false; 4951 4952 Imm = M[0]; 4953 4954 // If this is a VEXT shuffle, the immediate value is the index of the first 4955 // element. The other shuffle indices must be the successive elements after 4956 // the first one. 4957 unsigned ExpectedElt = Imm; 4958 for (unsigned i = 1; i < NumElts; ++i) { 4959 // Increment the expected index. If it wraps around, just follow it 4960 // back to index zero and keep going. 4961 ++ExpectedElt; 4962 if (ExpectedElt == NumElts) 4963 ExpectedElt = 0; 4964 4965 if (M[i] < 0) continue; // ignore UNDEF indices 4966 if (ExpectedElt != static_cast<unsigned>(M[i])) 4967 return false; 4968 } 4969 4970 return true; 4971 } 4972 4973 4974 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 4975 bool &ReverseVEXT, unsigned &Imm) { 4976 unsigned NumElts = VT.getVectorNumElements(); 4977 ReverseVEXT = false; 4978 4979 // Assume that the first shuffle index is not UNDEF. Fail if it is. 4980 if (M[0] < 0) 4981 return false; 4982 4983 Imm = M[0]; 4984 4985 // If this is a VEXT shuffle, the immediate value is the index of the first 4986 // element. The other shuffle indices must be the successive elements after 4987 // the first one. 4988 unsigned ExpectedElt = Imm; 4989 for (unsigned i = 1; i < NumElts; ++i) { 4990 // Increment the expected index. If it wraps around, it may still be 4991 // a VEXT but the source vectors must be swapped. 4992 ExpectedElt += 1; 4993 if (ExpectedElt == NumElts * 2) { 4994 ExpectedElt = 0; 4995 ReverseVEXT = true; 4996 } 4997 4998 if (M[i] < 0) continue; // ignore UNDEF indices 4999 if (ExpectedElt != static_cast<unsigned>(M[i])) 5000 return false; 5001 } 5002 5003 // Adjust the index value if the source operands will be swapped. 5004 if (ReverseVEXT) 5005 Imm -= NumElts; 5006 5007 return true; 5008 } 5009 5010 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5011 /// instruction with the specified blocksize. (The order of the elements 5012 /// within each block of the vector is reversed.) 5013 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5014 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5015 "Only possible block sizes for VREV are: 16, 32, 64"); 5016 5017 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5018 if (EltSz == 64) 5019 return false; 5020 5021 unsigned NumElts = VT.getVectorNumElements(); 5022 unsigned BlockElts = M[0] + 1; 5023 // If the first shuffle index is UNDEF, be optimistic. 5024 if (M[0] < 0) 5025 BlockElts = BlockSize / EltSz; 5026 5027 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5028 return false; 5029 5030 for (unsigned i = 0; i < NumElts; ++i) { 5031 if (M[i] < 0) continue; // ignore UNDEF indices 5032 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5033 return false; 5034 } 5035 5036 return true; 5037 } 5038 5039 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5040 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5041 // range, then 0 is placed into the resulting vector. So pretty much any mask 5042 // of 8 elements can work here. 5043 return VT == MVT::v8i8 && M.size() == 8; 5044 } 5045 5046 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5047 // checking that pairs of elements in the shuffle mask represent the same index 5048 // in each vector, incrementing the expected index by 2 at each step. 5049 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5050 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5051 // v2={e,f,g,h} 5052 // WhichResult gives the offset for each element in the mask based on which 5053 // of the two results it belongs to. 5054 // 5055 // The transpose can be represented either as: 5056 // result1 = shufflevector v1, v2, result1_shuffle_mask 5057 // result2 = shufflevector v1, v2, result2_shuffle_mask 5058 // where v1/v2 and the shuffle masks have the same number of elements 5059 // (here WhichResult (see below) indicates which result is being checked) 5060 // 5061 // or as: 5062 // results = shufflevector v1, v2, shuffle_mask 5063 // where both results are returned in one vector and the shuffle mask has twice 5064 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5065 // want to check the low half and high half of the shuffle mask as if it were 5066 // the other case 5067 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5068 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5069 if (EltSz == 64) 5070 return false; 5071 5072 unsigned NumElts = VT.getVectorNumElements(); 5073 if (M.size() != NumElts && M.size() != NumElts*2) 5074 return false; 5075 5076 // If the mask is twice as long as the result then we need to check the upper 5077 // and lower parts of the mask 5078 for (unsigned i = 0; i < M.size(); i += NumElts) { 5079 WhichResult = M[i] == 0 ? 0 : 1; 5080 for (unsigned j = 0; j < NumElts; j += 2) { 5081 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5082 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5083 return false; 5084 } 5085 } 5086 5087 if (M.size() == NumElts*2) 5088 WhichResult = 0; 5089 5090 return true; 5091 } 5092 5093 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5094 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5095 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5096 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5097 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5098 if (EltSz == 64) 5099 return false; 5100 5101 unsigned NumElts = VT.getVectorNumElements(); 5102 if (M.size() != NumElts && M.size() != NumElts*2) 5103 return false; 5104 5105 for (unsigned i = 0; i < M.size(); i += NumElts) { 5106 WhichResult = M[i] == 0 ? 0 : 1; 5107 for (unsigned j = 0; j < NumElts; j += 2) { 5108 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5109 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5110 return false; 5111 } 5112 } 5113 5114 if (M.size() == NumElts*2) 5115 WhichResult = 0; 5116 5117 return true; 5118 } 5119 5120 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5121 // that the mask elements are either all even and in steps of size 2 or all odd 5122 // and in steps of size 2. 5123 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5124 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5125 // v2={e,f,g,h} 5126 // Requires similar checks to that of isVTRNMask with 5127 // respect the how results are returned. 5128 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5129 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5130 if (EltSz == 64) 5131 return false; 5132 5133 unsigned NumElts = VT.getVectorNumElements(); 5134 if (M.size() != NumElts && M.size() != NumElts*2) 5135 return false; 5136 5137 for (unsigned i = 0; i < M.size(); i += NumElts) { 5138 WhichResult = M[i] == 0 ? 0 : 1; 5139 for (unsigned j = 0; j < NumElts; ++j) { 5140 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5141 return false; 5142 } 5143 } 5144 5145 if (M.size() == NumElts*2) 5146 WhichResult = 0; 5147 5148 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5149 if (VT.is64BitVector() && EltSz == 32) 5150 return false; 5151 5152 return true; 5153 } 5154 5155 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5156 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5157 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5158 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5159 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5160 if (EltSz == 64) 5161 return false; 5162 5163 unsigned NumElts = VT.getVectorNumElements(); 5164 if (M.size() != NumElts && M.size() != NumElts*2) 5165 return false; 5166 5167 unsigned Half = NumElts / 2; 5168 for (unsigned i = 0; i < M.size(); i += NumElts) { 5169 WhichResult = M[i] == 0 ? 0 : 1; 5170 for (unsigned j = 0; j < NumElts; j += Half) { 5171 unsigned Idx = WhichResult; 5172 for (unsigned k = 0; k < Half; ++k) { 5173 int MIdx = M[i + j + k]; 5174 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5175 return false; 5176 Idx += 2; 5177 } 5178 } 5179 } 5180 5181 if (M.size() == NumElts*2) 5182 WhichResult = 0; 5183 5184 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5185 if (VT.is64BitVector() && EltSz == 32) 5186 return false; 5187 5188 return true; 5189 } 5190 5191 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5192 // that pairs of elements of the shufflemask represent the same index in each 5193 // vector incrementing sequentially through the vectors. 5194 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5195 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5196 // v2={e,f,g,h} 5197 // Requires similar checks to that of isVTRNMask with respect the how results 5198 // are returned. 5199 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5200 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5201 if (EltSz == 64) 5202 return false; 5203 5204 unsigned NumElts = VT.getVectorNumElements(); 5205 if (M.size() != NumElts && M.size() != NumElts*2) 5206 return false; 5207 5208 for (unsigned i = 0; i < M.size(); i += NumElts) { 5209 WhichResult = M[i] == 0 ? 0 : 1; 5210 unsigned Idx = WhichResult * NumElts / 2; 5211 for (unsigned j = 0; j < NumElts; j += 2) { 5212 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5213 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5214 return false; 5215 Idx += 1; 5216 } 5217 } 5218 5219 if (M.size() == NumElts*2) 5220 WhichResult = 0; 5221 5222 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5223 if (VT.is64BitVector() && EltSz == 32) 5224 return false; 5225 5226 return true; 5227 } 5228 5229 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5230 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5231 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5232 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5233 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5234 if (EltSz == 64) 5235 return false; 5236 5237 unsigned NumElts = VT.getVectorNumElements(); 5238 if (M.size() != NumElts && M.size() != NumElts*2) 5239 return false; 5240 5241 for (unsigned i = 0; i < M.size(); i += NumElts) { 5242 WhichResult = M[i] == 0 ? 0 : 1; 5243 unsigned Idx = WhichResult * NumElts / 2; 5244 for (unsigned j = 0; j < NumElts; j += 2) { 5245 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5246 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5247 return false; 5248 Idx += 1; 5249 } 5250 } 5251 5252 if (M.size() == NumElts*2) 5253 WhichResult = 0; 5254 5255 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5256 if (VT.is64BitVector() && EltSz == 32) 5257 return false; 5258 5259 return true; 5260 } 5261 5262 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5263 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5264 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5265 unsigned &WhichResult, 5266 bool &isV_UNDEF) { 5267 isV_UNDEF = false; 5268 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5269 return ARMISD::VTRN; 5270 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5271 return ARMISD::VUZP; 5272 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5273 return ARMISD::VZIP; 5274 5275 isV_UNDEF = true; 5276 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5277 return ARMISD::VTRN; 5278 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5279 return ARMISD::VUZP; 5280 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5281 return ARMISD::VZIP; 5282 5283 return 0; 5284 } 5285 5286 /// \return true if this is a reverse operation on an vector. 5287 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5288 unsigned NumElts = VT.getVectorNumElements(); 5289 // Make sure the mask has the right size. 5290 if (NumElts != M.size()) 5291 return false; 5292 5293 // Look for <15, ..., 3, -1, 1, 0>. 5294 for (unsigned i = 0; i != NumElts; ++i) 5295 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5296 return false; 5297 5298 return true; 5299 } 5300 5301 // If N is an integer constant that can be moved into a register in one 5302 // instruction, return an SDValue of such a constant (will become a MOV 5303 // instruction). Otherwise return null. 5304 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5305 const ARMSubtarget *ST, SDLoc dl) { 5306 uint64_t Val; 5307 if (!isa<ConstantSDNode>(N)) 5308 return SDValue(); 5309 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5310 5311 if (ST->isThumb1Only()) { 5312 if (Val <= 255 || ~Val <= 255) 5313 return DAG.getConstant(Val, dl, MVT::i32); 5314 } else { 5315 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5316 return DAG.getConstant(Val, dl, MVT::i32); 5317 } 5318 return SDValue(); 5319 } 5320 5321 // If this is a case we can't handle, return null and let the default 5322 // expansion code take care of it. 5323 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5324 const ARMSubtarget *ST) const { 5325 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5326 SDLoc dl(Op); 5327 EVT VT = Op.getValueType(); 5328 5329 APInt SplatBits, SplatUndef; 5330 unsigned SplatBitSize; 5331 bool HasAnyUndefs; 5332 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5333 if (SplatBitSize <= 64) { 5334 // Check if an immediate VMOV works. 5335 EVT VmovVT; 5336 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5337 SplatUndef.getZExtValue(), SplatBitSize, 5338 DAG, dl, VmovVT, VT.is128BitVector(), 5339 VMOVModImm); 5340 if (Val.getNode()) { 5341 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5342 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5343 } 5344 5345 // Try an immediate VMVN. 5346 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5347 Val = isNEONModifiedImm(NegatedImm, 5348 SplatUndef.getZExtValue(), SplatBitSize, 5349 DAG, dl, VmovVT, VT.is128BitVector(), 5350 VMVNModImm); 5351 if (Val.getNode()) { 5352 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5353 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5354 } 5355 5356 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5357 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5358 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5359 if (ImmVal != -1) { 5360 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5361 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5362 } 5363 } 5364 } 5365 } 5366 5367 // Scan through the operands to see if only one value is used. 5368 // 5369 // As an optimisation, even if more than one value is used it may be more 5370 // profitable to splat with one value then change some lanes. 5371 // 5372 // Heuristically we decide to do this if the vector has a "dominant" value, 5373 // defined as splatted to more than half of the lanes. 5374 unsigned NumElts = VT.getVectorNumElements(); 5375 bool isOnlyLowElement = true; 5376 bool usesOnlyOneValue = true; 5377 bool hasDominantValue = false; 5378 bool isConstant = true; 5379 5380 // Map of the number of times a particular SDValue appears in the 5381 // element list. 5382 DenseMap<SDValue, unsigned> ValueCounts; 5383 SDValue Value; 5384 for (unsigned i = 0; i < NumElts; ++i) { 5385 SDValue V = Op.getOperand(i); 5386 if (V.getOpcode() == ISD::UNDEF) 5387 continue; 5388 if (i > 0) 5389 isOnlyLowElement = false; 5390 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5391 isConstant = false; 5392 5393 ValueCounts.insert(std::make_pair(V, 0)); 5394 unsigned &Count = ValueCounts[V]; 5395 5396 // Is this value dominant? (takes up more than half of the lanes) 5397 if (++Count > (NumElts / 2)) { 5398 hasDominantValue = true; 5399 Value = V; 5400 } 5401 } 5402 if (ValueCounts.size() != 1) 5403 usesOnlyOneValue = false; 5404 if (!Value.getNode() && ValueCounts.size() > 0) 5405 Value = ValueCounts.begin()->first; 5406 5407 if (ValueCounts.size() == 0) 5408 return DAG.getUNDEF(VT); 5409 5410 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5411 // Keep going if we are hitting this case. 5412 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5413 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5414 5415 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5416 5417 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5418 // i32 and try again. 5419 if (hasDominantValue && EltSize <= 32) { 5420 if (!isConstant) { 5421 SDValue N; 5422 5423 // If we are VDUPing a value that comes directly from a vector, that will 5424 // cause an unnecessary move to and from a GPR, where instead we could 5425 // just use VDUPLANE. We can only do this if the lane being extracted 5426 // is at a constant index, as the VDUP from lane instructions only have 5427 // constant-index forms. 5428 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5429 isa<ConstantSDNode>(Value->getOperand(1))) { 5430 // We need to create a new undef vector to use for the VDUPLANE if the 5431 // size of the vector from which we get the value is different than the 5432 // size of the vector that we need to create. We will insert the element 5433 // such that the register coalescer will remove unnecessary copies. 5434 if (VT != Value->getOperand(0).getValueType()) { 5435 ConstantSDNode *constIndex; 5436 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)); 5437 assert(constIndex && "The index is not a constant!"); 5438 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5439 VT.getVectorNumElements(); 5440 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5441 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5442 Value, DAG.getConstant(index, dl, MVT::i32)), 5443 DAG.getConstant(index, dl, MVT::i32)); 5444 } else 5445 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5446 Value->getOperand(0), Value->getOperand(1)); 5447 } else 5448 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5449 5450 if (!usesOnlyOneValue) { 5451 // The dominant value was splatted as 'N', but we now have to insert 5452 // all differing elements. 5453 for (unsigned I = 0; I < NumElts; ++I) { 5454 if (Op.getOperand(I) == Value) 5455 continue; 5456 SmallVector<SDValue, 3> Ops; 5457 Ops.push_back(N); 5458 Ops.push_back(Op.getOperand(I)); 5459 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5460 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5461 } 5462 } 5463 return N; 5464 } 5465 if (VT.getVectorElementType().isFloatingPoint()) { 5466 SmallVector<SDValue, 8> Ops; 5467 for (unsigned i = 0; i < NumElts; ++i) 5468 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5469 Op.getOperand(i))); 5470 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5471 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 5472 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5473 if (Val.getNode()) 5474 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5475 } 5476 if (usesOnlyOneValue) { 5477 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5478 if (isConstant && Val.getNode()) 5479 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5480 } 5481 } 5482 5483 // If all elements are constants and the case above didn't get hit, fall back 5484 // to the default expansion, which will generate a load from the constant 5485 // pool. 5486 if (isConstant) 5487 return SDValue(); 5488 5489 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5490 if (NumElts >= 4) { 5491 SDValue shuffle = ReconstructShuffle(Op, DAG); 5492 if (shuffle != SDValue()) 5493 return shuffle; 5494 } 5495 5496 // Vectors with 32- or 64-bit elements can be built by directly assigning 5497 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5498 // will be legalized. 5499 if (EltSize >= 32) { 5500 // Do the expansion with floating-point types, since that is what the VFP 5501 // registers are defined to use, and since i64 is not legal. 5502 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5503 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5504 SmallVector<SDValue, 8> Ops; 5505 for (unsigned i = 0; i < NumElts; ++i) 5506 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5507 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5508 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5509 } 5510 5511 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5512 // know the default expansion would otherwise fall back on something even 5513 // worse. For a vector with one or two non-undef values, that's 5514 // scalar_to_vector for the elements followed by a shuffle (provided the 5515 // shuffle is valid for the target) and materialization element by element 5516 // on the stack followed by a load for everything else. 5517 if (!isConstant && !usesOnlyOneValue) { 5518 SDValue Vec = DAG.getUNDEF(VT); 5519 for (unsigned i = 0 ; i < NumElts; ++i) { 5520 SDValue V = Op.getOperand(i); 5521 if (V.getOpcode() == ISD::UNDEF) 5522 continue; 5523 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5524 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5525 } 5526 return Vec; 5527 } 5528 5529 return SDValue(); 5530 } 5531 5532 // Gather data to see if the operation can be modelled as a 5533 // shuffle in combination with VEXTs. 5534 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5535 SelectionDAG &DAG) const { 5536 SDLoc dl(Op); 5537 EVT VT = Op.getValueType(); 5538 unsigned NumElts = VT.getVectorNumElements(); 5539 5540 SmallVector<SDValue, 2> SourceVecs; 5541 SmallVector<unsigned, 2> MinElts; 5542 SmallVector<unsigned, 2> MaxElts; 5543 5544 for (unsigned i = 0; i < NumElts; ++i) { 5545 SDValue V = Op.getOperand(i); 5546 if (V.getOpcode() == ISD::UNDEF) 5547 continue; 5548 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5549 // A shuffle can only come from building a vector from various 5550 // elements of other vectors. 5551 return SDValue(); 5552 } else if (V.getOperand(0).getValueType().getVectorElementType() != 5553 VT.getVectorElementType()) { 5554 // This code doesn't know how to handle shuffles where the vector 5555 // element types do not match (this happens because type legalization 5556 // promotes the return type of EXTRACT_VECTOR_ELT). 5557 // FIXME: It might be appropriate to extend this code to handle 5558 // mismatched types. 5559 return SDValue(); 5560 } 5561 5562 // Record this extraction against the appropriate vector if possible... 5563 SDValue SourceVec = V.getOperand(0); 5564 // If the element number isn't a constant, we can't effectively 5565 // analyze what's going on. 5566 if (!isa<ConstantSDNode>(V.getOperand(1))) 5567 return SDValue(); 5568 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5569 bool FoundSource = false; 5570 for (unsigned j = 0; j < SourceVecs.size(); ++j) { 5571 if (SourceVecs[j] == SourceVec) { 5572 if (MinElts[j] > EltNo) 5573 MinElts[j] = EltNo; 5574 if (MaxElts[j] < EltNo) 5575 MaxElts[j] = EltNo; 5576 FoundSource = true; 5577 break; 5578 } 5579 } 5580 5581 // Or record a new source if not... 5582 if (!FoundSource) { 5583 SourceVecs.push_back(SourceVec); 5584 MinElts.push_back(EltNo); 5585 MaxElts.push_back(EltNo); 5586 } 5587 } 5588 5589 // Currently only do something sane when at most two source vectors 5590 // involved. 5591 if (SourceVecs.size() > 2) 5592 return SDValue(); 5593 5594 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) }; 5595 int VEXTOffsets[2] = {0, 0}; 5596 5597 // This loop extracts the usage patterns of the source vectors 5598 // and prepares appropriate SDValues for a shuffle if possible. 5599 for (unsigned i = 0; i < SourceVecs.size(); ++i) { 5600 if (SourceVecs[i].getValueType() == VT) { 5601 // No VEXT necessary 5602 ShuffleSrcs[i] = SourceVecs[i]; 5603 VEXTOffsets[i] = 0; 5604 continue; 5605 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) { 5606 // It probably isn't worth padding out a smaller vector just to 5607 // break it down again in a shuffle. 5608 return SDValue(); 5609 } 5610 5611 // Since only 64-bit and 128-bit vectors are legal on ARM and 5612 // we've eliminated the other cases... 5613 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts && 5614 "unexpected vector sizes in ReconstructShuffle"); 5615 5616 if (MaxElts[i] - MinElts[i] >= NumElts) { 5617 // Span too large for a VEXT to cope 5618 return SDValue(); 5619 } 5620 5621 if (MinElts[i] >= NumElts) { 5622 // The extraction can just take the second half 5623 VEXTOffsets[i] = NumElts; 5624 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5625 SourceVecs[i], 5626 DAG.getIntPtrConstant(NumElts, dl)); 5627 } else if (MaxElts[i] < NumElts) { 5628 // The extraction can just take the first half 5629 VEXTOffsets[i] = 0; 5630 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5631 SourceVecs[i], 5632 DAG.getIntPtrConstant(0, dl)); 5633 } else { 5634 // An actual VEXT is needed 5635 VEXTOffsets[i] = MinElts[i]; 5636 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5637 SourceVecs[i], 5638 DAG.getIntPtrConstant(0, dl)); 5639 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5640 SourceVecs[i], 5641 DAG.getIntPtrConstant(NumElts, dl)); 5642 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2, 5643 DAG.getConstant(VEXTOffsets[i], dl, 5644 MVT::i32)); 5645 } 5646 } 5647 5648 SmallVector<int, 8> Mask; 5649 5650 for (unsigned i = 0; i < NumElts; ++i) { 5651 SDValue Entry = Op.getOperand(i); 5652 if (Entry.getOpcode() == ISD::UNDEF) { 5653 Mask.push_back(-1); 5654 continue; 5655 } 5656 5657 SDValue ExtractVec = Entry.getOperand(0); 5658 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i) 5659 .getOperand(1))->getSExtValue(); 5660 if (ExtractVec == SourceVecs[0]) { 5661 Mask.push_back(ExtractElt - VEXTOffsets[0]); 5662 } else { 5663 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]); 5664 } 5665 } 5666 5667 // Final check before we try to produce nonsense... 5668 if (isShuffleMaskLegal(Mask, VT)) 5669 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1], 5670 &Mask[0]); 5671 5672 return SDValue(); 5673 } 5674 5675 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5676 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5677 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5678 /// are assumed to be legal. 5679 bool 5680 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5681 EVT VT) const { 5682 if (VT.getVectorNumElements() == 4 && 5683 (VT.is128BitVector() || VT.is64BitVector())) { 5684 unsigned PFIndexes[4]; 5685 for (unsigned i = 0; i != 4; ++i) { 5686 if (M[i] < 0) 5687 PFIndexes[i] = 8; 5688 else 5689 PFIndexes[i] = M[i]; 5690 } 5691 5692 // Compute the index in the perfect shuffle table. 5693 unsigned PFTableIndex = 5694 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5695 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5696 unsigned Cost = (PFEntry >> 30); 5697 5698 if (Cost <= 4) 5699 return true; 5700 } 5701 5702 bool ReverseVEXT, isV_UNDEF; 5703 unsigned Imm, WhichResult; 5704 5705 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5706 return (EltSize >= 32 || 5707 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5708 isVREVMask(M, VT, 64) || 5709 isVREVMask(M, VT, 32) || 5710 isVREVMask(M, VT, 16) || 5711 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5712 isVTBLMask(M, VT) || 5713 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 5714 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5715 } 5716 5717 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5718 /// the specified operations to build the shuffle. 5719 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5720 SDValue RHS, SelectionDAG &DAG, 5721 SDLoc dl) { 5722 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5723 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5724 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5725 5726 enum { 5727 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5728 OP_VREV, 5729 OP_VDUP0, 5730 OP_VDUP1, 5731 OP_VDUP2, 5732 OP_VDUP3, 5733 OP_VEXT1, 5734 OP_VEXT2, 5735 OP_VEXT3, 5736 OP_VUZPL, // VUZP, left result 5737 OP_VUZPR, // VUZP, right result 5738 OP_VZIPL, // VZIP, left result 5739 OP_VZIPR, // VZIP, right result 5740 OP_VTRNL, // VTRN, left result 5741 OP_VTRNR // VTRN, right result 5742 }; 5743 5744 if (OpNum == OP_COPY) { 5745 if (LHSID == (1*9+2)*9+3) return LHS; 5746 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 5747 return RHS; 5748 } 5749 5750 SDValue OpLHS, OpRHS; 5751 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5752 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5753 EVT VT = OpLHS.getValueType(); 5754 5755 switch (OpNum) { 5756 default: llvm_unreachable("Unknown shuffle opcode!"); 5757 case OP_VREV: 5758 // VREV divides the vector in half and swaps within the half. 5759 if (VT.getVectorElementType() == MVT::i32 || 5760 VT.getVectorElementType() == MVT::f32) 5761 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 5762 // vrev <4 x i16> -> VREV32 5763 if (VT.getVectorElementType() == MVT::i16) 5764 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 5765 // vrev <4 x i8> -> VREV16 5766 assert(VT.getVectorElementType() == MVT::i8); 5767 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 5768 case OP_VDUP0: 5769 case OP_VDUP1: 5770 case OP_VDUP2: 5771 case OP_VDUP3: 5772 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5773 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 5774 case OP_VEXT1: 5775 case OP_VEXT2: 5776 case OP_VEXT3: 5777 return DAG.getNode(ARMISD::VEXT, dl, VT, 5778 OpLHS, OpRHS, 5779 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 5780 case OP_VUZPL: 5781 case OP_VUZPR: 5782 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 5783 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 5784 case OP_VZIPL: 5785 case OP_VZIPR: 5786 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 5787 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 5788 case OP_VTRNL: 5789 case OP_VTRNR: 5790 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 5791 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 5792 } 5793 } 5794 5795 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 5796 ArrayRef<int> ShuffleMask, 5797 SelectionDAG &DAG) { 5798 // Check to see if we can use the VTBL instruction. 5799 SDValue V1 = Op.getOperand(0); 5800 SDValue V2 = Op.getOperand(1); 5801 SDLoc DL(Op); 5802 5803 SmallVector<SDValue, 8> VTBLMask; 5804 for (ArrayRef<int>::iterator 5805 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 5806 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 5807 5808 if (V2.getNode()->getOpcode() == ISD::UNDEF) 5809 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 5810 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 5811 5812 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 5813 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 5814 } 5815 5816 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 5817 SelectionDAG &DAG) { 5818 SDLoc DL(Op); 5819 SDValue OpLHS = Op.getOperand(0); 5820 EVT VT = OpLHS.getValueType(); 5821 5822 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 5823 "Expect an v8i16/v16i8 type"); 5824 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 5825 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 5826 // extract the first 8 bytes into the top double word and the last 8 bytes 5827 // into the bottom double word. The v8i16 case is similar. 5828 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 5829 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 5830 DAG.getConstant(ExtractNum, DL, MVT::i32)); 5831 } 5832 5833 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 5834 SDValue V1 = Op.getOperand(0); 5835 SDValue V2 = Op.getOperand(1); 5836 SDLoc dl(Op); 5837 EVT VT = Op.getValueType(); 5838 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 5839 5840 // Convert shuffles that are directly supported on NEON to target-specific 5841 // DAG nodes, instead of keeping them as shuffles and matching them again 5842 // during code selection. This is more efficient and avoids the possibility 5843 // of inconsistencies between legalization and selection. 5844 // FIXME: floating-point vectors should be canonicalized to integer vectors 5845 // of the same time so that they get CSEd properly. 5846 ArrayRef<int> ShuffleMask = SVN->getMask(); 5847 5848 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5849 if (EltSize <= 32) { 5850 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 5851 int Lane = SVN->getSplatIndex(); 5852 // If this is undef splat, generate it via "just" vdup, if possible. 5853 if (Lane == -1) Lane = 0; 5854 5855 // Test if V1 is a SCALAR_TO_VECTOR. 5856 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5857 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 5858 } 5859 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 5860 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 5861 // reaches it). 5862 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 5863 !isa<ConstantSDNode>(V1.getOperand(0))) { 5864 bool IsScalarToVector = true; 5865 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 5866 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) { 5867 IsScalarToVector = false; 5868 break; 5869 } 5870 if (IsScalarToVector) 5871 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 5872 } 5873 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 5874 DAG.getConstant(Lane, dl, MVT::i32)); 5875 } 5876 5877 bool ReverseVEXT; 5878 unsigned Imm; 5879 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 5880 if (ReverseVEXT) 5881 std::swap(V1, V2); 5882 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 5883 DAG.getConstant(Imm, dl, MVT::i32)); 5884 } 5885 5886 if (isVREVMask(ShuffleMask, VT, 64)) 5887 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 5888 if (isVREVMask(ShuffleMask, VT, 32)) 5889 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 5890 if (isVREVMask(ShuffleMask, VT, 16)) 5891 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 5892 5893 if (V2->getOpcode() == ISD::UNDEF && 5894 isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 5895 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 5896 DAG.getConstant(Imm, dl, MVT::i32)); 5897 } 5898 5899 // Check for Neon shuffles that modify both input vectors in place. 5900 // If both results are used, i.e., if there are two shuffles with the same 5901 // source operands and with masks corresponding to both results of one of 5902 // these operations, DAG memoization will ensure that a single node is 5903 // used for both shuffles. 5904 unsigned WhichResult; 5905 bool isV_UNDEF; 5906 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 5907 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 5908 if (isV_UNDEF) 5909 V2 = V1; 5910 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 5911 .getValue(WhichResult); 5912 } 5913 5914 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 5915 // shuffles that produce a result larger than their operands with: 5916 // shuffle(concat(v1, undef), concat(v2, undef)) 5917 // -> 5918 // shuffle(concat(v1, v2), undef) 5919 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 5920 // 5921 // This is useful in the general case, but there are special cases where 5922 // native shuffles produce larger results: the two-result ops. 5923 // 5924 // Look through the concat when lowering them: 5925 // shuffle(concat(v1, v2), undef) 5926 // -> 5927 // concat(VZIP(v1, v2):0, :1) 5928 // 5929 if (V1->getOpcode() == ISD::CONCAT_VECTORS && 5930 V2->getOpcode() == ISD::UNDEF) { 5931 SDValue SubV1 = V1->getOperand(0); 5932 SDValue SubV2 = V1->getOperand(1); 5933 EVT SubVT = SubV1.getValueType(); 5934 5935 // We expect these to have been canonicalized to -1. 5936 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) { 5937 return i < (int)VT.getVectorNumElements(); 5938 }) && "Unexpected shuffle index into UNDEF operand!"); 5939 5940 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 5941 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 5942 if (isV_UNDEF) 5943 SubV2 = SubV1; 5944 assert((WhichResult == 0) && 5945 "In-place shuffle of concat can only have one result!"); 5946 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 5947 SubV1, SubV2); 5948 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 5949 Res.getValue(1)); 5950 } 5951 } 5952 } 5953 5954 // If the shuffle is not directly supported and it has 4 elements, use 5955 // the PerfectShuffle-generated table to synthesize it from other shuffles. 5956 unsigned NumElts = VT.getVectorNumElements(); 5957 if (NumElts == 4) { 5958 unsigned PFIndexes[4]; 5959 for (unsigned i = 0; i != 4; ++i) { 5960 if (ShuffleMask[i] < 0) 5961 PFIndexes[i] = 8; 5962 else 5963 PFIndexes[i] = ShuffleMask[i]; 5964 } 5965 5966 // Compute the index in the perfect shuffle table. 5967 unsigned PFTableIndex = 5968 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5969 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5970 unsigned Cost = (PFEntry >> 30); 5971 5972 if (Cost <= 4) 5973 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 5974 } 5975 5976 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 5977 if (EltSize >= 32) { 5978 // Do the expansion with floating-point types, since that is what the VFP 5979 // registers are defined to use, and since i64 is not legal. 5980 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5981 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5982 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 5983 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 5984 SmallVector<SDValue, 8> Ops; 5985 for (unsigned i = 0; i < NumElts; ++i) { 5986 if (ShuffleMask[i] < 0) 5987 Ops.push_back(DAG.getUNDEF(EltVT)); 5988 else 5989 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 5990 ShuffleMask[i] < (int)NumElts ? V1 : V2, 5991 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 5992 dl, MVT::i32))); 5993 } 5994 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5995 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5996 } 5997 5998 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 5999 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6000 6001 if (VT == MVT::v8i8) { 6002 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG); 6003 if (NewOp.getNode()) 6004 return NewOp; 6005 } 6006 6007 return SDValue(); 6008 } 6009 6010 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6011 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6012 SDValue Lane = Op.getOperand(2); 6013 if (!isa<ConstantSDNode>(Lane)) 6014 return SDValue(); 6015 6016 return Op; 6017 } 6018 6019 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6020 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6021 SDValue Lane = Op.getOperand(1); 6022 if (!isa<ConstantSDNode>(Lane)) 6023 return SDValue(); 6024 6025 SDValue Vec = Op.getOperand(0); 6026 if (Op.getValueType() == MVT::i32 && 6027 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6028 SDLoc dl(Op); 6029 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6030 } 6031 6032 return Op; 6033 } 6034 6035 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6036 // The only time a CONCAT_VECTORS operation can have legal types is when 6037 // two 64-bit vectors are concatenated to a 128-bit vector. 6038 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6039 "unexpected CONCAT_VECTORS"); 6040 SDLoc dl(Op); 6041 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6042 SDValue Op0 = Op.getOperand(0); 6043 SDValue Op1 = Op.getOperand(1); 6044 if (Op0.getOpcode() != ISD::UNDEF) 6045 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6046 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6047 DAG.getIntPtrConstant(0, dl)); 6048 if (Op1.getOpcode() != ISD::UNDEF) 6049 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6050 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6051 DAG.getIntPtrConstant(1, dl)); 6052 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6053 } 6054 6055 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6056 /// element has been zero/sign-extended, depending on the isSigned parameter, 6057 /// from an integer type half its size. 6058 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6059 bool isSigned) { 6060 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6061 EVT VT = N->getValueType(0); 6062 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6063 SDNode *BVN = N->getOperand(0).getNode(); 6064 if (BVN->getValueType(0) != MVT::v4i32 || 6065 BVN->getOpcode() != ISD::BUILD_VECTOR) 6066 return false; 6067 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6068 unsigned HiElt = 1 - LoElt; 6069 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6070 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6071 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6072 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6073 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6074 return false; 6075 if (isSigned) { 6076 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6077 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6078 return true; 6079 } else { 6080 if (Hi0->isNullValue() && Hi1->isNullValue()) 6081 return true; 6082 } 6083 return false; 6084 } 6085 6086 if (N->getOpcode() != ISD::BUILD_VECTOR) 6087 return false; 6088 6089 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6090 SDNode *Elt = N->getOperand(i).getNode(); 6091 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6092 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6093 unsigned HalfSize = EltSize / 2; 6094 if (isSigned) { 6095 if (!isIntN(HalfSize, C->getSExtValue())) 6096 return false; 6097 } else { 6098 if (!isUIntN(HalfSize, C->getZExtValue())) 6099 return false; 6100 } 6101 continue; 6102 } 6103 return false; 6104 } 6105 6106 return true; 6107 } 6108 6109 /// isSignExtended - Check if a node is a vector value that is sign-extended 6110 /// or a constant BUILD_VECTOR with sign-extended elements. 6111 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6112 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6113 return true; 6114 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6115 return true; 6116 return false; 6117 } 6118 6119 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6120 /// or a constant BUILD_VECTOR with zero-extended elements. 6121 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6122 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6123 return true; 6124 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6125 return true; 6126 return false; 6127 } 6128 6129 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6130 if (OrigVT.getSizeInBits() >= 64) 6131 return OrigVT; 6132 6133 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6134 6135 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6136 switch (OrigSimpleTy) { 6137 default: llvm_unreachable("Unexpected Vector Type"); 6138 case MVT::v2i8: 6139 case MVT::v2i16: 6140 return MVT::v2i32; 6141 case MVT::v4i8: 6142 return MVT::v4i16; 6143 } 6144 } 6145 6146 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6147 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6148 /// We insert the required extension here to get the vector to fill a D register. 6149 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6150 const EVT &OrigTy, 6151 const EVT &ExtTy, 6152 unsigned ExtOpcode) { 6153 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6154 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6155 // 64-bits we need to insert a new extension so that it will be 64-bits. 6156 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6157 if (OrigTy.getSizeInBits() >= 64) 6158 return N; 6159 6160 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6161 EVT NewVT = getExtensionTo64Bits(OrigTy); 6162 6163 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6164 } 6165 6166 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6167 /// does not do any sign/zero extension. If the original vector is less 6168 /// than 64 bits, an appropriate extension will be added after the load to 6169 /// reach a total size of 64 bits. We have to add the extension separately 6170 /// because ARM does not have a sign/zero extending load for vectors. 6171 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6172 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6173 6174 // The load already has the right type. 6175 if (ExtendedTy == LD->getMemoryVT()) 6176 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6177 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 6178 LD->isNonTemporal(), LD->isInvariant(), 6179 LD->getAlignment()); 6180 6181 // We need to create a zextload/sextload. We cannot just create a load 6182 // followed by a zext/zext node because LowerMUL is also run during normal 6183 // operation legalization where we can't create illegal types. 6184 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6185 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6186 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 6187 LD->isNonTemporal(), LD->getAlignment()); 6188 } 6189 6190 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6191 /// extending load, or BUILD_VECTOR with extended elements, return the 6192 /// unextended value. The unextended vector should be 64 bits so that it can 6193 /// be used as an operand to a VMULL instruction. If the original vector size 6194 /// before extension is less than 64 bits we add a an extension to resize 6195 /// the vector to 64 bits. 6196 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6197 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6198 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6199 N->getOperand(0)->getValueType(0), 6200 N->getValueType(0), 6201 N->getOpcode()); 6202 6203 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6204 return SkipLoadExtensionForVMULL(LD, DAG); 6205 6206 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6207 // have been legalized as a BITCAST from v4i32. 6208 if (N->getOpcode() == ISD::BITCAST) { 6209 SDNode *BVN = N->getOperand(0).getNode(); 6210 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6211 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6212 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6213 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32, 6214 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2)); 6215 } 6216 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6217 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6218 EVT VT = N->getValueType(0); 6219 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6220 unsigned NumElts = VT.getVectorNumElements(); 6221 MVT TruncVT = MVT::getIntegerVT(EltSize); 6222 SmallVector<SDValue, 8> Ops; 6223 SDLoc dl(N); 6224 for (unsigned i = 0; i != NumElts; ++i) { 6225 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6226 const APInt &CInt = C->getAPIntValue(); 6227 // Element types smaller than 32 bits are not legal, so use i32 elements. 6228 // The values are implicitly truncated so sext vs. zext doesn't matter. 6229 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6230 } 6231 return DAG.getNode(ISD::BUILD_VECTOR, dl, 6232 MVT::getVectorVT(TruncVT, NumElts), Ops); 6233 } 6234 6235 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6236 unsigned Opcode = N->getOpcode(); 6237 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6238 SDNode *N0 = N->getOperand(0).getNode(); 6239 SDNode *N1 = N->getOperand(1).getNode(); 6240 return N0->hasOneUse() && N1->hasOneUse() && 6241 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6242 } 6243 return false; 6244 } 6245 6246 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6247 unsigned Opcode = N->getOpcode(); 6248 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6249 SDNode *N0 = N->getOperand(0).getNode(); 6250 SDNode *N1 = N->getOperand(1).getNode(); 6251 return N0->hasOneUse() && N1->hasOneUse() && 6252 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6253 } 6254 return false; 6255 } 6256 6257 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6258 // Multiplications are only custom-lowered for 128-bit vectors so that 6259 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6260 EVT VT = Op.getValueType(); 6261 assert(VT.is128BitVector() && VT.isInteger() && 6262 "unexpected type for custom-lowering ISD::MUL"); 6263 SDNode *N0 = Op.getOperand(0).getNode(); 6264 SDNode *N1 = Op.getOperand(1).getNode(); 6265 unsigned NewOpc = 0; 6266 bool isMLA = false; 6267 bool isN0SExt = isSignExtended(N0, DAG); 6268 bool isN1SExt = isSignExtended(N1, DAG); 6269 if (isN0SExt && isN1SExt) 6270 NewOpc = ARMISD::VMULLs; 6271 else { 6272 bool isN0ZExt = isZeroExtended(N0, DAG); 6273 bool isN1ZExt = isZeroExtended(N1, DAG); 6274 if (isN0ZExt && isN1ZExt) 6275 NewOpc = ARMISD::VMULLu; 6276 else if (isN1SExt || isN1ZExt) { 6277 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6278 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6279 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6280 NewOpc = ARMISD::VMULLs; 6281 isMLA = true; 6282 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6283 NewOpc = ARMISD::VMULLu; 6284 isMLA = true; 6285 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6286 std::swap(N0, N1); 6287 NewOpc = ARMISD::VMULLu; 6288 isMLA = true; 6289 } 6290 } 6291 6292 if (!NewOpc) { 6293 if (VT == MVT::v2i64) 6294 // Fall through to expand this. It is not legal. 6295 return SDValue(); 6296 else 6297 // Other vector multiplications are legal. 6298 return Op; 6299 } 6300 } 6301 6302 // Legalize to a VMULL instruction. 6303 SDLoc DL(Op); 6304 SDValue Op0; 6305 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6306 if (!isMLA) { 6307 Op0 = SkipExtensionForVMULL(N0, DAG); 6308 assert(Op0.getValueType().is64BitVector() && 6309 Op1.getValueType().is64BitVector() && 6310 "unexpected types for extended operands to VMULL"); 6311 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6312 } 6313 6314 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6315 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6316 // vmull q0, d4, d6 6317 // vmlal q0, d5, d6 6318 // is faster than 6319 // vaddl q0, d4, d5 6320 // vmovl q1, d6 6321 // vmul q0, q0, q1 6322 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6323 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6324 EVT Op1VT = Op1.getValueType(); 6325 return DAG.getNode(N0->getOpcode(), DL, VT, 6326 DAG.getNode(NewOpc, DL, VT, 6327 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6328 DAG.getNode(NewOpc, DL, VT, 6329 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6330 } 6331 6332 static SDValue 6333 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 6334 // Convert to float 6335 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6336 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6337 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6338 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6339 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6340 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6341 // Get reciprocal estimate. 6342 // float4 recip = vrecpeq_f32(yf); 6343 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6344 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6345 Y); 6346 // Because char has a smaller range than uchar, we can actually get away 6347 // without any newton steps. This requires that we use a weird bias 6348 // of 0xb000, however (again, this has been exhaustively tested). 6349 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6350 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6351 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6352 Y = DAG.getConstant(0xb000, dl, MVT::i32); 6353 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y); 6354 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6355 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6356 // Convert back to short. 6357 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6358 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6359 return X; 6360 } 6361 6362 static SDValue 6363 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 6364 SDValue N2; 6365 // Convert to float. 6366 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6367 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6368 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6369 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6370 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6371 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6372 6373 // Use reciprocal estimate and one refinement step. 6374 // float4 recip = vrecpeq_f32(yf); 6375 // recip *= vrecpsq_f32(yf, recip); 6376 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6377 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6378 N1); 6379 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6380 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6381 N1, N2); 6382 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6383 // Because short has a smaller range than ushort, we can actually get away 6384 // with only a single newton step. This requires that we use a weird bias 6385 // of 89, however (again, this has been exhaustively tested). 6386 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6387 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6388 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6389 N1 = DAG.getConstant(0x89, dl, MVT::i32); 6390 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 6391 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6392 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6393 // Convert back to integer and return. 6394 // return vmovn_s32(vcvt_s32_f32(result)); 6395 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6396 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6397 return N0; 6398 } 6399 6400 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6401 EVT VT = Op.getValueType(); 6402 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6403 "unexpected type for custom-lowering ISD::SDIV"); 6404 6405 SDLoc dl(Op); 6406 SDValue N0 = Op.getOperand(0); 6407 SDValue N1 = Op.getOperand(1); 6408 SDValue N2, N3; 6409 6410 if (VT == MVT::v8i8) { 6411 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6412 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6413 6414 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6415 DAG.getIntPtrConstant(4, dl)); 6416 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6417 DAG.getIntPtrConstant(4, dl)); 6418 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6419 DAG.getIntPtrConstant(0, dl)); 6420 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6421 DAG.getIntPtrConstant(0, dl)); 6422 6423 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6424 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6425 6426 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6427 N0 = LowerCONCAT_VECTORS(N0, DAG); 6428 6429 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6430 return N0; 6431 } 6432 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6433 } 6434 6435 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6436 EVT VT = Op.getValueType(); 6437 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6438 "unexpected type for custom-lowering ISD::UDIV"); 6439 6440 SDLoc dl(Op); 6441 SDValue N0 = Op.getOperand(0); 6442 SDValue N1 = Op.getOperand(1); 6443 SDValue N2, N3; 6444 6445 if (VT == MVT::v8i8) { 6446 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6447 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6448 6449 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6450 DAG.getIntPtrConstant(4, dl)); 6451 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6452 DAG.getIntPtrConstant(4, dl)); 6453 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6454 DAG.getIntPtrConstant(0, dl)); 6455 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6456 DAG.getIntPtrConstant(0, dl)); 6457 6458 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6459 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6460 6461 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6462 N0 = LowerCONCAT_VECTORS(N0, DAG); 6463 6464 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6465 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6466 MVT::i32), 6467 N0); 6468 return N0; 6469 } 6470 6471 // v4i16 sdiv ... Convert to float. 6472 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6473 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6474 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6475 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6476 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6477 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6478 6479 // Use reciprocal estimate and two refinement steps. 6480 // float4 recip = vrecpeq_f32(yf); 6481 // recip *= vrecpsq_f32(yf, recip); 6482 // recip *= vrecpsq_f32(yf, recip); 6483 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6484 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6485 BN1); 6486 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6487 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6488 BN1, N2); 6489 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6490 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6491 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6492 BN1, N2); 6493 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6494 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6495 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6496 // and that it will never cause us to return an answer too large). 6497 // float4 result = as_float4(as_int4(xf*recip) + 2); 6498 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6499 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6500 N1 = DAG.getConstant(2, dl, MVT::i32); 6501 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 6502 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6503 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6504 // Convert back to integer and return. 6505 // return vmovn_u32(vcvt_s32_f32(result)); 6506 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6507 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6508 return N0; 6509 } 6510 6511 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6512 EVT VT = Op.getNode()->getValueType(0); 6513 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6514 6515 unsigned Opc; 6516 bool ExtraOp = false; 6517 switch (Op.getOpcode()) { 6518 default: llvm_unreachable("Invalid code"); 6519 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6520 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6521 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6522 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6523 } 6524 6525 if (!ExtraOp) 6526 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6527 Op.getOperand(1)); 6528 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6529 Op.getOperand(1), Op.getOperand(2)); 6530 } 6531 6532 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6533 assert(Subtarget->isTargetDarwin()); 6534 6535 // For iOS, we want to call an alternative entry point: __sincos_stret, 6536 // return values are passed via sret. 6537 SDLoc dl(Op); 6538 SDValue Arg = Op.getOperand(0); 6539 EVT ArgVT = Arg.getValueType(); 6540 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6541 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6542 6543 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6544 6545 // Pair of floats / doubles used to pass the result. 6546 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6547 6548 // Create stack object for sret. 6549 auto &DL = DAG.getDataLayout(); 6550 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6551 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6552 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6553 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL)); 6554 6555 ArgListTy Args; 6556 ArgListEntry Entry; 6557 6558 Entry.Node = SRet; 6559 Entry.Ty = RetTy->getPointerTo(); 6560 Entry.isSExt = false; 6561 Entry.isZExt = false; 6562 Entry.isSRet = true; 6563 Args.push_back(Entry); 6564 6565 Entry.Node = Arg; 6566 Entry.Ty = ArgTy; 6567 Entry.isSExt = false; 6568 Entry.isZExt = false; 6569 Args.push_back(Entry); 6570 6571 const char *LibcallName = (ArgVT == MVT::f64) 6572 ? "__sincos_stret" : "__sincosf_stret"; 6573 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6574 6575 TargetLowering::CallLoweringInfo CLI(DAG); 6576 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 6577 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee, 6578 std::move(Args), 0) 6579 .setDiscardResult(); 6580 6581 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6582 6583 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6584 MachinePointerInfo(), false, false, false, 0); 6585 6586 // Address of cos field. 6587 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6588 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6589 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6590 MachinePointerInfo(), false, false, false, 0); 6591 6592 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6593 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6594 LoadSin.getValue(0), LoadCos.getValue(0)); 6595 } 6596 6597 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 6598 // Monotonic load/store is legal for all targets 6599 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic) 6600 return Op; 6601 6602 // Acquire/Release load/store is not legal for targets without a 6603 // dmb or equivalent available. 6604 return SDValue(); 6605 } 6606 6607 static void ReplaceREADCYCLECOUNTER(SDNode *N, 6608 SmallVectorImpl<SDValue> &Results, 6609 SelectionDAG &DAG, 6610 const ARMSubtarget *Subtarget) { 6611 SDLoc DL(N); 6612 SDValue Cycles32, OutChain; 6613 6614 if (Subtarget->hasPerfMon()) { 6615 // Under Power Management extensions, the cycle-count is: 6616 // mrc p15, #0, <Rt>, c9, c13, #0 6617 SDValue Ops[] = { N->getOperand(0), // Chain 6618 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 6619 DAG.getConstant(15, DL, MVT::i32), 6620 DAG.getConstant(0, DL, MVT::i32), 6621 DAG.getConstant(9, DL, MVT::i32), 6622 DAG.getConstant(13, DL, MVT::i32), 6623 DAG.getConstant(0, DL, MVT::i32) 6624 }; 6625 6626 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6627 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6628 OutChain = Cycles32.getValue(1); 6629 } else { 6630 // Intrinsic is defined to return 0 on unsupported platforms. Technically 6631 // there are older ARM CPUs that have implementation-specific ways of 6632 // obtaining this information (FIXME!). 6633 Cycles32 = DAG.getConstant(0, DL, MVT::i32); 6634 OutChain = DAG.getEntryNode(); 6635 } 6636 6637 6638 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, 6639 Cycles32, DAG.getConstant(0, DL, MVT::i32)); 6640 Results.push_back(Cycles64); 6641 Results.push_back(OutChain); 6642 } 6643 6644 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6645 switch (Op.getOpcode()) { 6646 default: llvm_unreachable("Don't know how to custom lower this!"); 6647 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 6648 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 6649 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 6650 case ISD::GlobalAddress: 6651 switch (Subtarget->getTargetTriple().getObjectFormat()) { 6652 default: llvm_unreachable("unknown object format"); 6653 case Triple::COFF: 6654 return LowerGlobalAddressWindows(Op, DAG); 6655 case Triple::ELF: 6656 return LowerGlobalAddressELF(Op, DAG); 6657 case Triple::MachO: 6658 return LowerGlobalAddressDarwin(Op, DAG); 6659 } 6660 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 6661 case ISD::SELECT: return LowerSELECT(Op, DAG); 6662 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 6663 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 6664 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 6665 case ISD::VASTART: return LowerVASTART(Op, DAG); 6666 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 6667 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 6668 case ISD::SINT_TO_FP: 6669 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 6670 case ISD::FP_TO_SINT: 6671 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 6672 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 6673 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 6674 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 6675 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG); 6676 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 6677 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 6678 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 6679 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 6680 Subtarget); 6681 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 6682 case ISD::SHL: 6683 case ISD::SRL: 6684 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 6685 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 6686 case ISD::SRL_PARTS: 6687 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 6688 case ISD::CTTZ: 6689 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 6690 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 6691 case ISD::SETCC: return LowerVSETCC(Op, DAG); 6692 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 6693 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 6694 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 6695 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 6696 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 6697 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 6698 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 6699 case ISD::MUL: return LowerMUL(Op, DAG); 6700 case ISD::SDIV: return LowerSDIV(Op, DAG); 6701 case ISD::UDIV: return LowerUDIV(Op, DAG); 6702 case ISD::ADDC: 6703 case ISD::ADDE: 6704 case ISD::SUBC: 6705 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 6706 case ISD::SADDO: 6707 case ISD::UADDO: 6708 case ISD::SSUBO: 6709 case ISD::USUBO: 6710 return LowerXALUO(Op, DAG); 6711 case ISD::ATOMIC_LOAD: 6712 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 6713 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 6714 case ISD::SDIVREM: 6715 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 6716 case ISD::DYNAMIC_STACKALLOC: 6717 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 6718 return LowerDYNAMIC_STACKALLOC(Op, DAG); 6719 llvm_unreachable("Don't know how to custom lower this!"); 6720 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 6721 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 6722 } 6723 } 6724 6725 /// ReplaceNodeResults - Replace the results of node with an illegal result 6726 /// type with new values built out of custom code. 6727 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 6728 SmallVectorImpl<SDValue>&Results, 6729 SelectionDAG &DAG) const { 6730 SDValue Res; 6731 switch (N->getOpcode()) { 6732 default: 6733 llvm_unreachable("Don't know how to custom expand this!"); 6734 case ISD::READ_REGISTER: 6735 ExpandREAD_REGISTER(N, Results, DAG); 6736 break; 6737 case ISD::BITCAST: 6738 Res = ExpandBITCAST(N, DAG); 6739 break; 6740 case ISD::SRL: 6741 case ISD::SRA: 6742 Res = Expand64BitShift(N, DAG, Subtarget); 6743 break; 6744 case ISD::READCYCLECOUNTER: 6745 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 6746 return; 6747 } 6748 if (Res.getNode()) 6749 Results.push_back(Res); 6750 } 6751 6752 //===----------------------------------------------------------------------===// 6753 // ARM Scheduler Hooks 6754 //===----------------------------------------------------------------------===// 6755 6756 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 6757 /// registers the function context. 6758 void ARMTargetLowering:: 6759 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 6760 MachineBasicBlock *DispatchBB, int FI) const { 6761 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 6762 DebugLoc dl = MI->getDebugLoc(); 6763 MachineFunction *MF = MBB->getParent(); 6764 MachineRegisterInfo *MRI = &MF->getRegInfo(); 6765 MachineConstantPool *MCP = MF->getConstantPool(); 6766 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 6767 const Function *F = MF->getFunction(); 6768 6769 bool isThumb = Subtarget->isThumb(); 6770 bool isThumb2 = Subtarget->isThumb2(); 6771 6772 unsigned PCLabelId = AFI->createPICLabelUId(); 6773 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 6774 ARMConstantPoolValue *CPV = 6775 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 6776 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 6777 6778 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 6779 : &ARM::GPRRegClass; 6780 6781 // Grab constant pool and fixed stack memory operands. 6782 MachineMemOperand *CPMMO = 6783 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(), 6784 MachineMemOperand::MOLoad, 4, 4); 6785 6786 MachineMemOperand *FIMMOSt = 6787 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), 6788 MachineMemOperand::MOStore, 4, 4); 6789 6790 // Load the address of the dispatch MBB into the jump buffer. 6791 if (isThumb2) { 6792 // Incoming value: jbuf 6793 // ldr.n r5, LCPI1_1 6794 // orr r5, r5, #1 6795 // add r5, pc 6796 // str r5, [$jbuf, #+4] ; &jbuf[1] 6797 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6798 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 6799 .addConstantPoolIndex(CPI) 6800 .addMemOperand(CPMMO)); 6801 // Set the low bit because of thumb mode. 6802 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6803 AddDefaultCC( 6804 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 6805 .addReg(NewVReg1, RegState::Kill) 6806 .addImm(0x01))); 6807 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6808 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 6809 .addReg(NewVReg2, RegState::Kill) 6810 .addImm(PCLabelId); 6811 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 6812 .addReg(NewVReg3, RegState::Kill) 6813 .addFrameIndex(FI) 6814 .addImm(36) // &jbuf[1] :: pc 6815 .addMemOperand(FIMMOSt)); 6816 } else if (isThumb) { 6817 // Incoming value: jbuf 6818 // ldr.n r1, LCPI1_4 6819 // add r1, pc 6820 // mov r2, #1 6821 // orrs r1, r2 6822 // add r2, $jbuf, #+4 ; &jbuf[1] 6823 // str r1, [r2] 6824 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6825 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 6826 .addConstantPoolIndex(CPI) 6827 .addMemOperand(CPMMO)); 6828 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6829 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 6830 .addReg(NewVReg1, RegState::Kill) 6831 .addImm(PCLabelId); 6832 // Set the low bit because of thumb mode. 6833 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6834 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 6835 .addReg(ARM::CPSR, RegState::Define) 6836 .addImm(1)); 6837 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 6838 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 6839 .addReg(ARM::CPSR, RegState::Define) 6840 .addReg(NewVReg2, RegState::Kill) 6841 .addReg(NewVReg3, RegState::Kill)); 6842 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 6843 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 6844 .addFrameIndex(FI) 6845 .addImm(36); // &jbuf[1] :: pc 6846 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 6847 .addReg(NewVReg4, RegState::Kill) 6848 .addReg(NewVReg5, RegState::Kill) 6849 .addImm(0) 6850 .addMemOperand(FIMMOSt)); 6851 } else { 6852 // Incoming value: jbuf 6853 // ldr r1, LCPI1_1 6854 // add r1, pc, r1 6855 // str r1, [$jbuf, #+4] ; &jbuf[1] 6856 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6857 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 6858 .addConstantPoolIndex(CPI) 6859 .addImm(0) 6860 .addMemOperand(CPMMO)); 6861 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6862 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 6863 .addReg(NewVReg1, RegState::Kill) 6864 .addImm(PCLabelId)); 6865 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 6866 .addReg(NewVReg2, RegState::Kill) 6867 .addFrameIndex(FI) 6868 .addImm(36) // &jbuf[1] :: pc 6869 .addMemOperand(FIMMOSt)); 6870 } 6871 } 6872 6873 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI, 6874 MachineBasicBlock *MBB) const { 6875 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 6876 DebugLoc dl = MI->getDebugLoc(); 6877 MachineFunction *MF = MBB->getParent(); 6878 MachineRegisterInfo *MRI = &MF->getRegInfo(); 6879 MachineFrameInfo *MFI = MF->getFrameInfo(); 6880 int FI = MFI->getFunctionContextIndex(); 6881 6882 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 6883 : &ARM::GPRnopcRegClass; 6884 6885 // Get a mapping of the call site numbers to all of the landing pads they're 6886 // associated with. 6887 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 6888 unsigned MaxCSNum = 0; 6889 MachineModuleInfo &MMI = MF->getMMI(); 6890 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 6891 ++BB) { 6892 if (!BB->isLandingPad()) continue; 6893 6894 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 6895 // pad. 6896 for (MachineBasicBlock::iterator 6897 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 6898 if (!II->isEHLabel()) continue; 6899 6900 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 6901 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 6902 6903 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 6904 for (SmallVectorImpl<unsigned>::iterator 6905 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 6906 CSI != CSE; ++CSI) { 6907 CallSiteNumToLPad[*CSI].push_back(BB); 6908 MaxCSNum = std::max(MaxCSNum, *CSI); 6909 } 6910 break; 6911 } 6912 } 6913 6914 // Get an ordered list of the machine basic blocks for the jump table. 6915 std::vector<MachineBasicBlock*> LPadList; 6916 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs; 6917 LPadList.reserve(CallSiteNumToLPad.size()); 6918 for (unsigned I = 1; I <= MaxCSNum; ++I) { 6919 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 6920 for (SmallVectorImpl<MachineBasicBlock*>::iterator 6921 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 6922 LPadList.push_back(*II); 6923 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 6924 } 6925 } 6926 6927 assert(!LPadList.empty() && 6928 "No landing pad destinations for the dispatch jump table!"); 6929 6930 // Create the jump table and associated information. 6931 MachineJumpTableInfo *JTI = 6932 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 6933 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 6934 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 6935 6936 // Create the MBBs for the dispatch code. 6937 6938 // Shove the dispatch's address into the return slot in the function context. 6939 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 6940 DispatchBB->setIsLandingPad(); 6941 6942 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 6943 unsigned trap_opcode; 6944 if (Subtarget->isThumb()) 6945 trap_opcode = ARM::tTRAP; 6946 else 6947 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 6948 6949 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 6950 DispatchBB->addSuccessor(TrapBB); 6951 6952 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 6953 DispatchBB->addSuccessor(DispContBB); 6954 6955 // Insert and MBBs. 6956 MF->insert(MF->end(), DispatchBB); 6957 MF->insert(MF->end(), DispContBB); 6958 MF->insert(MF->end(), TrapBB); 6959 6960 // Insert code into the entry block that creates and registers the function 6961 // context. 6962 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 6963 6964 MachineMemOperand *FIMMOLd = 6965 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), 6966 MachineMemOperand::MOLoad | 6967 MachineMemOperand::MOVolatile, 4, 4); 6968 6969 MachineInstrBuilder MIB; 6970 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 6971 6972 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 6973 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 6974 6975 // Add a register mask with no preserved registers. This results in all 6976 // registers being marked as clobbered. 6977 MIB.addRegMask(RI.getNoPreservedMask()); 6978 6979 unsigned NumLPads = LPadList.size(); 6980 if (Subtarget->isThumb2()) { 6981 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6982 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 6983 .addFrameIndex(FI) 6984 .addImm(4) 6985 .addMemOperand(FIMMOLd)); 6986 6987 if (NumLPads < 256) { 6988 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 6989 .addReg(NewVReg1) 6990 .addImm(LPadList.size())); 6991 } else { 6992 unsigned VReg1 = MRI->createVirtualRegister(TRC); 6993 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 6994 .addImm(NumLPads & 0xFFFF)); 6995 6996 unsigned VReg2 = VReg1; 6997 if ((NumLPads & 0xFFFF0000) != 0) { 6998 VReg2 = MRI->createVirtualRegister(TRC); 6999 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7000 .addReg(VReg1) 7001 .addImm(NumLPads >> 16)); 7002 } 7003 7004 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7005 .addReg(NewVReg1) 7006 .addReg(VReg2)); 7007 } 7008 7009 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7010 .addMBB(TrapBB) 7011 .addImm(ARMCC::HI) 7012 .addReg(ARM::CPSR); 7013 7014 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7015 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7016 .addJumpTableIndex(MJTI)); 7017 7018 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7019 AddDefaultCC( 7020 AddDefaultPred( 7021 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7022 .addReg(NewVReg3, RegState::Kill) 7023 .addReg(NewVReg1) 7024 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7025 7026 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7027 .addReg(NewVReg4, RegState::Kill) 7028 .addReg(NewVReg1) 7029 .addJumpTableIndex(MJTI); 7030 } else if (Subtarget->isThumb()) { 7031 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7032 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7033 .addFrameIndex(FI) 7034 .addImm(1) 7035 .addMemOperand(FIMMOLd)); 7036 7037 if (NumLPads < 256) { 7038 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7039 .addReg(NewVReg1) 7040 .addImm(NumLPads)); 7041 } else { 7042 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7043 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7044 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7045 7046 // MachineConstantPool wants an explicit alignment. 7047 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7048 if (Align == 0) 7049 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7050 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7051 7052 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7053 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7054 .addReg(VReg1, RegState::Define) 7055 .addConstantPoolIndex(Idx)); 7056 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7057 .addReg(NewVReg1) 7058 .addReg(VReg1)); 7059 } 7060 7061 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7062 .addMBB(TrapBB) 7063 .addImm(ARMCC::HI) 7064 .addReg(ARM::CPSR); 7065 7066 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7067 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7068 .addReg(ARM::CPSR, RegState::Define) 7069 .addReg(NewVReg1) 7070 .addImm(2)); 7071 7072 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7073 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7074 .addJumpTableIndex(MJTI)); 7075 7076 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7077 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7078 .addReg(ARM::CPSR, RegState::Define) 7079 .addReg(NewVReg2, RegState::Kill) 7080 .addReg(NewVReg3)); 7081 7082 MachineMemOperand *JTMMOLd = 7083 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(), 7084 MachineMemOperand::MOLoad, 4, 4); 7085 7086 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7087 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7088 .addReg(NewVReg4, RegState::Kill) 7089 .addImm(0) 7090 .addMemOperand(JTMMOLd)); 7091 7092 unsigned NewVReg6 = NewVReg5; 7093 if (RelocM == Reloc::PIC_) { 7094 NewVReg6 = MRI->createVirtualRegister(TRC); 7095 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7096 .addReg(ARM::CPSR, RegState::Define) 7097 .addReg(NewVReg5, RegState::Kill) 7098 .addReg(NewVReg3)); 7099 } 7100 7101 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7102 .addReg(NewVReg6, RegState::Kill) 7103 .addJumpTableIndex(MJTI); 7104 } else { 7105 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7106 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7107 .addFrameIndex(FI) 7108 .addImm(4) 7109 .addMemOperand(FIMMOLd)); 7110 7111 if (NumLPads < 256) { 7112 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7113 .addReg(NewVReg1) 7114 .addImm(NumLPads)); 7115 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7116 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7117 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7118 .addImm(NumLPads & 0xFFFF)); 7119 7120 unsigned VReg2 = VReg1; 7121 if ((NumLPads & 0xFFFF0000) != 0) { 7122 VReg2 = MRI->createVirtualRegister(TRC); 7123 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7124 .addReg(VReg1) 7125 .addImm(NumLPads >> 16)); 7126 } 7127 7128 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7129 .addReg(NewVReg1) 7130 .addReg(VReg2)); 7131 } else { 7132 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7133 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7134 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7135 7136 // MachineConstantPool wants an explicit alignment. 7137 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7138 if (Align == 0) 7139 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7140 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7141 7142 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7143 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7144 .addReg(VReg1, RegState::Define) 7145 .addConstantPoolIndex(Idx) 7146 .addImm(0)); 7147 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7148 .addReg(NewVReg1) 7149 .addReg(VReg1, RegState::Kill)); 7150 } 7151 7152 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7153 .addMBB(TrapBB) 7154 .addImm(ARMCC::HI) 7155 .addReg(ARM::CPSR); 7156 7157 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7158 AddDefaultCC( 7159 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7160 .addReg(NewVReg1) 7161 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7162 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7163 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7164 .addJumpTableIndex(MJTI)); 7165 7166 MachineMemOperand *JTMMOLd = 7167 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(), 7168 MachineMemOperand::MOLoad, 4, 4); 7169 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7170 AddDefaultPred( 7171 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7172 .addReg(NewVReg3, RegState::Kill) 7173 .addReg(NewVReg4) 7174 .addImm(0) 7175 .addMemOperand(JTMMOLd)); 7176 7177 if (RelocM == Reloc::PIC_) { 7178 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7179 .addReg(NewVReg5, RegState::Kill) 7180 .addReg(NewVReg4) 7181 .addJumpTableIndex(MJTI); 7182 } else { 7183 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7184 .addReg(NewVReg5, RegState::Kill) 7185 .addJumpTableIndex(MJTI); 7186 } 7187 } 7188 7189 // Add the jump table entries as successors to the MBB. 7190 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7191 for (std::vector<MachineBasicBlock*>::iterator 7192 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7193 MachineBasicBlock *CurMBB = *I; 7194 if (SeenMBBs.insert(CurMBB).second) 7195 DispContBB->addSuccessor(CurMBB); 7196 } 7197 7198 // N.B. the order the invoke BBs are processed in doesn't matter here. 7199 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7200 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7201 for (MachineBasicBlock *BB : InvokeBBs) { 7202 7203 // Remove the landing pad successor from the invoke block and replace it 7204 // with the new dispatch block. 7205 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7206 BB->succ_end()); 7207 while (!Successors.empty()) { 7208 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7209 if (SMBB->isLandingPad()) { 7210 BB->removeSuccessor(SMBB); 7211 MBBLPads.push_back(SMBB); 7212 } 7213 } 7214 7215 BB->addSuccessor(DispatchBB); 7216 7217 // Find the invoke call and mark all of the callee-saved registers as 7218 // 'implicit defined' so that they're spilled. This prevents code from 7219 // moving instructions to before the EH block, where they will never be 7220 // executed. 7221 for (MachineBasicBlock::reverse_iterator 7222 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7223 if (!II->isCall()) continue; 7224 7225 DenseMap<unsigned, bool> DefRegs; 7226 for (MachineInstr::mop_iterator 7227 OI = II->operands_begin(), OE = II->operands_end(); 7228 OI != OE; ++OI) { 7229 if (!OI->isReg()) continue; 7230 DefRegs[OI->getReg()] = true; 7231 } 7232 7233 MachineInstrBuilder MIB(*MF, &*II); 7234 7235 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7236 unsigned Reg = SavedRegs[i]; 7237 if (Subtarget->isThumb2() && 7238 !ARM::tGPRRegClass.contains(Reg) && 7239 !ARM::hGPRRegClass.contains(Reg)) 7240 continue; 7241 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7242 continue; 7243 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7244 continue; 7245 if (!DefRegs[Reg]) 7246 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7247 } 7248 7249 break; 7250 } 7251 } 7252 7253 // Mark all former landing pads as non-landing pads. The dispatch is the only 7254 // landing pad now. 7255 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7256 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7257 (*I)->setIsLandingPad(false); 7258 7259 // The instruction is gone now. 7260 MI->eraseFromParent(); 7261 } 7262 7263 static 7264 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7265 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7266 E = MBB->succ_end(); I != E; ++I) 7267 if (*I != Succ) 7268 return *I; 7269 llvm_unreachable("Expecting a BB with two successors!"); 7270 } 7271 7272 /// Return the load opcode for a given load size. If load size >= 8, 7273 /// neon opcode will be returned. 7274 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7275 if (LdSize >= 8) 7276 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7277 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7278 if (IsThumb1) 7279 return LdSize == 4 ? ARM::tLDRi 7280 : LdSize == 2 ? ARM::tLDRHi 7281 : LdSize == 1 ? ARM::tLDRBi : 0; 7282 if (IsThumb2) 7283 return LdSize == 4 ? ARM::t2LDR_POST 7284 : LdSize == 2 ? ARM::t2LDRH_POST 7285 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7286 return LdSize == 4 ? ARM::LDR_POST_IMM 7287 : LdSize == 2 ? ARM::LDRH_POST 7288 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7289 } 7290 7291 /// Return the store opcode for a given store size. If store size >= 8, 7292 /// neon opcode will be returned. 7293 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7294 if (StSize >= 8) 7295 return StSize == 16 ? ARM::VST1q32wb_fixed 7296 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7297 if (IsThumb1) 7298 return StSize == 4 ? ARM::tSTRi 7299 : StSize == 2 ? ARM::tSTRHi 7300 : StSize == 1 ? ARM::tSTRBi : 0; 7301 if (IsThumb2) 7302 return StSize == 4 ? ARM::t2STR_POST 7303 : StSize == 2 ? ARM::t2STRH_POST 7304 : StSize == 1 ? ARM::t2STRB_POST : 0; 7305 return StSize == 4 ? ARM::STR_POST_IMM 7306 : StSize == 2 ? ARM::STRH_POST 7307 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7308 } 7309 7310 /// Emit a post-increment load operation with given size. The instructions 7311 /// will be added to BB at Pos. 7312 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7313 const TargetInstrInfo *TII, DebugLoc dl, 7314 unsigned LdSize, unsigned Data, unsigned AddrIn, 7315 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7316 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7317 assert(LdOpc != 0 && "Should have a load opcode"); 7318 if (LdSize >= 8) { 7319 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7320 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7321 .addImm(0)); 7322 } else if (IsThumb1) { 7323 // load + update AddrIn 7324 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7325 .addReg(AddrIn).addImm(0)); 7326 MachineInstrBuilder MIB = 7327 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7328 MIB = AddDefaultT1CC(MIB); 7329 MIB.addReg(AddrIn).addImm(LdSize); 7330 AddDefaultPred(MIB); 7331 } else if (IsThumb2) { 7332 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7333 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7334 .addImm(LdSize)); 7335 } else { // arm 7336 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7337 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7338 .addReg(0).addImm(LdSize)); 7339 } 7340 } 7341 7342 /// Emit a post-increment store operation with given size. The instructions 7343 /// will be added to BB at Pos. 7344 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7345 const TargetInstrInfo *TII, DebugLoc dl, 7346 unsigned StSize, unsigned Data, unsigned AddrIn, 7347 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7348 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7349 assert(StOpc != 0 && "Should have a store opcode"); 7350 if (StSize >= 8) { 7351 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7352 .addReg(AddrIn).addImm(0).addReg(Data)); 7353 } else if (IsThumb1) { 7354 // store + update AddrIn 7355 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7356 .addReg(AddrIn).addImm(0)); 7357 MachineInstrBuilder MIB = 7358 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7359 MIB = AddDefaultT1CC(MIB); 7360 MIB.addReg(AddrIn).addImm(StSize); 7361 AddDefaultPred(MIB); 7362 } else if (IsThumb2) { 7363 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7364 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7365 } else { // arm 7366 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7367 .addReg(Data).addReg(AddrIn).addReg(0) 7368 .addImm(StSize)); 7369 } 7370 } 7371 7372 MachineBasicBlock * 7373 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7374 MachineBasicBlock *BB) const { 7375 // This pseudo instruction has 3 operands: dst, src, size 7376 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7377 // Otherwise, we will generate unrolled scalar copies. 7378 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7379 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7380 MachineFunction::iterator It = BB; 7381 ++It; 7382 7383 unsigned dest = MI->getOperand(0).getReg(); 7384 unsigned src = MI->getOperand(1).getReg(); 7385 unsigned SizeVal = MI->getOperand(2).getImm(); 7386 unsigned Align = MI->getOperand(3).getImm(); 7387 DebugLoc dl = MI->getDebugLoc(); 7388 7389 MachineFunction *MF = BB->getParent(); 7390 MachineRegisterInfo &MRI = MF->getRegInfo(); 7391 unsigned UnitSize = 0; 7392 const TargetRegisterClass *TRC = nullptr; 7393 const TargetRegisterClass *VecTRC = nullptr; 7394 7395 bool IsThumb1 = Subtarget->isThumb1Only(); 7396 bool IsThumb2 = Subtarget->isThumb2(); 7397 7398 if (Align & 1) { 7399 UnitSize = 1; 7400 } else if (Align & 2) { 7401 UnitSize = 2; 7402 } else { 7403 // Check whether we can use NEON instructions. 7404 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7405 Subtarget->hasNEON()) { 7406 if ((Align % 16 == 0) && SizeVal >= 16) 7407 UnitSize = 16; 7408 else if ((Align % 8 == 0) && SizeVal >= 8) 7409 UnitSize = 8; 7410 } 7411 // Can't use NEON instructions. 7412 if (UnitSize == 0) 7413 UnitSize = 4; 7414 } 7415 7416 // Select the correct opcode and register class for unit size load/store 7417 bool IsNeon = UnitSize >= 8; 7418 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7419 if (IsNeon) 7420 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7421 : UnitSize == 8 ? &ARM::DPRRegClass 7422 : nullptr; 7423 7424 unsigned BytesLeft = SizeVal % UnitSize; 7425 unsigned LoopSize = SizeVal - BytesLeft; 7426 7427 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7428 // Use LDR and STR to copy. 7429 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7430 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7431 unsigned srcIn = src; 7432 unsigned destIn = dest; 7433 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7434 unsigned srcOut = MRI.createVirtualRegister(TRC); 7435 unsigned destOut = MRI.createVirtualRegister(TRC); 7436 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7437 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7438 IsThumb1, IsThumb2); 7439 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7440 IsThumb1, IsThumb2); 7441 srcIn = srcOut; 7442 destIn = destOut; 7443 } 7444 7445 // Handle the leftover bytes with LDRB and STRB. 7446 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7447 // [destOut] = STRB_POST(scratch, destIn, 1) 7448 for (unsigned i = 0; i < BytesLeft; i++) { 7449 unsigned srcOut = MRI.createVirtualRegister(TRC); 7450 unsigned destOut = MRI.createVirtualRegister(TRC); 7451 unsigned scratch = MRI.createVirtualRegister(TRC); 7452 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7453 IsThumb1, IsThumb2); 7454 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7455 IsThumb1, IsThumb2); 7456 srcIn = srcOut; 7457 destIn = destOut; 7458 } 7459 MI->eraseFromParent(); // The instruction is gone now. 7460 return BB; 7461 } 7462 7463 // Expand the pseudo op to a loop. 7464 // thisMBB: 7465 // ... 7466 // movw varEnd, # --> with thumb2 7467 // movt varEnd, # 7468 // ldrcp varEnd, idx --> without thumb2 7469 // fallthrough --> loopMBB 7470 // loopMBB: 7471 // PHI varPhi, varEnd, varLoop 7472 // PHI srcPhi, src, srcLoop 7473 // PHI destPhi, dst, destLoop 7474 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7475 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7476 // subs varLoop, varPhi, #UnitSize 7477 // bne loopMBB 7478 // fallthrough --> exitMBB 7479 // exitMBB: 7480 // epilogue to handle left-over bytes 7481 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7482 // [destOut] = STRB_POST(scratch, destLoop, 1) 7483 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7484 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7485 MF->insert(It, loopMBB); 7486 MF->insert(It, exitMBB); 7487 7488 // Transfer the remainder of BB and its successor edges to exitMBB. 7489 exitMBB->splice(exitMBB->begin(), BB, 7490 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7491 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7492 7493 // Load an immediate to varEnd. 7494 unsigned varEnd = MRI.createVirtualRegister(TRC); 7495 if (Subtarget->useMovt(*MF)) { 7496 unsigned Vtmp = varEnd; 7497 if ((LoopSize & 0xFFFF0000) != 0) 7498 Vtmp = MRI.createVirtualRegister(TRC); 7499 AddDefaultPred(BuildMI(BB, dl, 7500 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16), 7501 Vtmp).addImm(LoopSize & 0xFFFF)); 7502 7503 if ((LoopSize & 0xFFFF0000) != 0) 7504 AddDefaultPred(BuildMI(BB, dl, 7505 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16), 7506 varEnd) 7507 .addReg(Vtmp) 7508 .addImm(LoopSize >> 16)); 7509 } else { 7510 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7511 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7512 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 7513 7514 // MachineConstantPool wants an explicit alignment. 7515 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7516 if (Align == 0) 7517 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7518 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7519 7520 if (IsThumb1) 7521 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 7522 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 7523 else 7524 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 7525 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 7526 } 7527 BB->addSuccessor(loopMBB); 7528 7529 // Generate the loop body: 7530 // varPhi = PHI(varLoop, varEnd) 7531 // srcPhi = PHI(srcLoop, src) 7532 // destPhi = PHI(destLoop, dst) 7533 MachineBasicBlock *entryBB = BB; 7534 BB = loopMBB; 7535 unsigned varLoop = MRI.createVirtualRegister(TRC); 7536 unsigned varPhi = MRI.createVirtualRegister(TRC); 7537 unsigned srcLoop = MRI.createVirtualRegister(TRC); 7538 unsigned srcPhi = MRI.createVirtualRegister(TRC); 7539 unsigned destLoop = MRI.createVirtualRegister(TRC); 7540 unsigned destPhi = MRI.createVirtualRegister(TRC); 7541 7542 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 7543 .addReg(varLoop).addMBB(loopMBB) 7544 .addReg(varEnd).addMBB(entryBB); 7545 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 7546 .addReg(srcLoop).addMBB(loopMBB) 7547 .addReg(src).addMBB(entryBB); 7548 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 7549 .addReg(destLoop).addMBB(loopMBB) 7550 .addReg(dest).addMBB(entryBB); 7551 7552 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7553 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 7554 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7555 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 7556 IsThumb1, IsThumb2); 7557 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 7558 IsThumb1, IsThumb2); 7559 7560 // Decrement loop variable by UnitSize. 7561 if (IsThumb1) { 7562 MachineInstrBuilder MIB = 7563 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 7564 MIB = AddDefaultT1CC(MIB); 7565 MIB.addReg(varPhi).addImm(UnitSize); 7566 AddDefaultPred(MIB); 7567 } else { 7568 MachineInstrBuilder MIB = 7569 BuildMI(*BB, BB->end(), dl, 7570 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 7571 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 7572 MIB->getOperand(5).setReg(ARM::CPSR); 7573 MIB->getOperand(5).setIsDef(true); 7574 } 7575 BuildMI(*BB, BB->end(), dl, 7576 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7577 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 7578 7579 // loopMBB can loop back to loopMBB or fall through to exitMBB. 7580 BB->addSuccessor(loopMBB); 7581 BB->addSuccessor(exitMBB); 7582 7583 // Add epilogue to handle BytesLeft. 7584 BB = exitMBB; 7585 MachineInstr *StartOfExit = exitMBB->begin(); 7586 7587 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7588 // [destOut] = STRB_POST(scratch, destLoop, 1) 7589 unsigned srcIn = srcLoop; 7590 unsigned destIn = destLoop; 7591 for (unsigned i = 0; i < BytesLeft; i++) { 7592 unsigned srcOut = MRI.createVirtualRegister(TRC); 7593 unsigned destOut = MRI.createVirtualRegister(TRC); 7594 unsigned scratch = MRI.createVirtualRegister(TRC); 7595 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 7596 IsThumb1, IsThumb2); 7597 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 7598 IsThumb1, IsThumb2); 7599 srcIn = srcOut; 7600 destIn = destOut; 7601 } 7602 7603 MI->eraseFromParent(); // The instruction is gone now. 7604 return BB; 7605 } 7606 7607 MachineBasicBlock * 7608 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 7609 MachineBasicBlock *MBB) const { 7610 const TargetMachine &TM = getTargetMachine(); 7611 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 7612 DebugLoc DL = MI->getDebugLoc(); 7613 7614 assert(Subtarget->isTargetWindows() && 7615 "__chkstk is only supported on Windows"); 7616 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 7617 7618 // __chkstk takes the number of words to allocate on the stack in R4, and 7619 // returns the stack adjustment in number of bytes in R4. This will not 7620 // clober any other registers (other than the obvious lr). 7621 // 7622 // Although, technically, IP should be considered a register which may be 7623 // clobbered, the call itself will not touch it. Windows on ARM is a pure 7624 // thumb-2 environment, so there is no interworking required. As a result, we 7625 // do not expect a veneer to be emitted by the linker, clobbering IP. 7626 // 7627 // Each module receives its own copy of __chkstk, so no import thunk is 7628 // required, again, ensuring that IP is not clobbered. 7629 // 7630 // Finally, although some linkers may theoretically provide a trampoline for 7631 // out of range calls (which is quite common due to a 32M range limitation of 7632 // branches for Thumb), we can generate the long-call version via 7633 // -mcmodel=large, alleviating the need for the trampoline which may clobber 7634 // IP. 7635 7636 switch (TM.getCodeModel()) { 7637 case CodeModel::Small: 7638 case CodeModel::Medium: 7639 case CodeModel::Default: 7640 case CodeModel::Kernel: 7641 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 7642 .addImm((unsigned)ARMCC::AL).addReg(0) 7643 .addExternalSymbol("__chkstk") 7644 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7645 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7646 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7647 break; 7648 case CodeModel::Large: 7649 case CodeModel::JITDefault: { 7650 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 7651 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 7652 7653 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 7654 .addExternalSymbol("__chkstk"); 7655 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 7656 .addImm((unsigned)ARMCC::AL).addReg(0) 7657 .addReg(Reg, RegState::Kill) 7658 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7659 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7660 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7661 break; 7662 } 7663 } 7664 7665 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 7666 ARM::SP) 7667 .addReg(ARM::SP).addReg(ARM::R4))); 7668 7669 MI->eraseFromParent(); 7670 return MBB; 7671 } 7672 7673 MachineBasicBlock * 7674 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 7675 MachineBasicBlock *BB) const { 7676 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7677 DebugLoc dl = MI->getDebugLoc(); 7678 bool isThumb2 = Subtarget->isThumb2(); 7679 switch (MI->getOpcode()) { 7680 default: { 7681 MI->dump(); 7682 llvm_unreachable("Unexpected instr type to insert"); 7683 } 7684 // The Thumb2 pre-indexed stores have the same MI operands, they just 7685 // define them differently in the .td files from the isel patterns, so 7686 // they need pseudos. 7687 case ARM::t2STR_preidx: 7688 MI->setDesc(TII->get(ARM::t2STR_PRE)); 7689 return BB; 7690 case ARM::t2STRB_preidx: 7691 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 7692 return BB; 7693 case ARM::t2STRH_preidx: 7694 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 7695 return BB; 7696 7697 case ARM::STRi_preidx: 7698 case ARM::STRBi_preidx: { 7699 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 7700 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 7701 // Decode the offset. 7702 unsigned Offset = MI->getOperand(4).getImm(); 7703 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 7704 Offset = ARM_AM::getAM2Offset(Offset); 7705 if (isSub) 7706 Offset = -Offset; 7707 7708 MachineMemOperand *MMO = *MI->memoperands_begin(); 7709 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 7710 .addOperand(MI->getOperand(0)) // Rn_wb 7711 .addOperand(MI->getOperand(1)) // Rt 7712 .addOperand(MI->getOperand(2)) // Rn 7713 .addImm(Offset) // offset (skip GPR==zero_reg) 7714 .addOperand(MI->getOperand(5)) // pred 7715 .addOperand(MI->getOperand(6)) 7716 .addMemOperand(MMO); 7717 MI->eraseFromParent(); 7718 return BB; 7719 } 7720 case ARM::STRr_preidx: 7721 case ARM::STRBr_preidx: 7722 case ARM::STRH_preidx: { 7723 unsigned NewOpc; 7724 switch (MI->getOpcode()) { 7725 default: llvm_unreachable("unexpected opcode!"); 7726 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 7727 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 7728 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 7729 } 7730 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 7731 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 7732 MIB.addOperand(MI->getOperand(i)); 7733 MI->eraseFromParent(); 7734 return BB; 7735 } 7736 7737 case ARM::tMOVCCr_pseudo: { 7738 // To "insert" a SELECT_CC instruction, we actually have to insert the 7739 // diamond control-flow pattern. The incoming instruction knows the 7740 // destination vreg to set, the condition code register to branch on, the 7741 // true/false values to select between, and a branch opcode to use. 7742 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7743 MachineFunction::iterator It = BB; 7744 ++It; 7745 7746 // thisMBB: 7747 // ... 7748 // TrueVal = ... 7749 // cmpTY ccX, r1, r2 7750 // bCC copy1MBB 7751 // fallthrough --> copy0MBB 7752 MachineBasicBlock *thisMBB = BB; 7753 MachineFunction *F = BB->getParent(); 7754 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 7755 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 7756 F->insert(It, copy0MBB); 7757 F->insert(It, sinkMBB); 7758 7759 // Transfer the remainder of BB and its successor edges to sinkMBB. 7760 sinkMBB->splice(sinkMBB->begin(), BB, 7761 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7762 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 7763 7764 BB->addSuccessor(copy0MBB); 7765 BB->addSuccessor(sinkMBB); 7766 7767 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 7768 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 7769 7770 // copy0MBB: 7771 // %FalseValue = ... 7772 // # fallthrough to sinkMBB 7773 BB = copy0MBB; 7774 7775 // Update machine-CFG edges 7776 BB->addSuccessor(sinkMBB); 7777 7778 // sinkMBB: 7779 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 7780 // ... 7781 BB = sinkMBB; 7782 BuildMI(*BB, BB->begin(), dl, 7783 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 7784 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 7785 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 7786 7787 MI->eraseFromParent(); // The pseudo instruction is gone now. 7788 return BB; 7789 } 7790 7791 case ARM::BCCi64: 7792 case ARM::BCCZi64: { 7793 // If there is an unconditional branch to the other successor, remove it. 7794 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7795 7796 // Compare both parts that make up the double comparison separately for 7797 // equality. 7798 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 7799 7800 unsigned LHS1 = MI->getOperand(1).getReg(); 7801 unsigned LHS2 = MI->getOperand(2).getReg(); 7802 if (RHSisZero) { 7803 AddDefaultPred(BuildMI(BB, dl, 7804 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 7805 .addReg(LHS1).addImm(0)); 7806 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 7807 .addReg(LHS2).addImm(0) 7808 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 7809 } else { 7810 unsigned RHS1 = MI->getOperand(3).getReg(); 7811 unsigned RHS2 = MI->getOperand(4).getReg(); 7812 AddDefaultPred(BuildMI(BB, dl, 7813 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 7814 .addReg(LHS1).addReg(RHS1)); 7815 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 7816 .addReg(LHS2).addReg(RHS2) 7817 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 7818 } 7819 7820 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 7821 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 7822 if (MI->getOperand(0).getImm() == ARMCC::NE) 7823 std::swap(destMBB, exitMBB); 7824 7825 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7826 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 7827 if (isThumb2) 7828 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 7829 else 7830 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 7831 7832 MI->eraseFromParent(); // The pseudo instruction is gone now. 7833 return BB; 7834 } 7835 7836 case ARM::Int_eh_sjlj_setjmp: 7837 case ARM::Int_eh_sjlj_setjmp_nofp: 7838 case ARM::tInt_eh_sjlj_setjmp: 7839 case ARM::t2Int_eh_sjlj_setjmp: 7840 case ARM::t2Int_eh_sjlj_setjmp_nofp: 7841 return BB; 7842 7843 case ARM::Int_eh_sjlj_setup_dispatch: 7844 EmitSjLjDispatchBlock(MI, BB); 7845 return BB; 7846 7847 case ARM::ABS: 7848 case ARM::t2ABS: { 7849 // To insert an ABS instruction, we have to insert the 7850 // diamond control-flow pattern. The incoming instruction knows the 7851 // source vreg to test against 0, the destination vreg to set, 7852 // the condition code register to branch on, the 7853 // true/false values to select between, and a branch opcode to use. 7854 // It transforms 7855 // V1 = ABS V0 7856 // into 7857 // V2 = MOVS V0 7858 // BCC (branch to SinkBB if V0 >= 0) 7859 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 7860 // SinkBB: V1 = PHI(V2, V3) 7861 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7862 MachineFunction::iterator BBI = BB; 7863 ++BBI; 7864 MachineFunction *Fn = BB->getParent(); 7865 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 7866 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 7867 Fn->insert(BBI, RSBBB); 7868 Fn->insert(BBI, SinkBB); 7869 7870 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 7871 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 7872 bool ABSSrcKIll = MI->getOperand(1).isKill(); 7873 bool isThumb2 = Subtarget->isThumb2(); 7874 MachineRegisterInfo &MRI = Fn->getRegInfo(); 7875 // In Thumb mode S must not be specified if source register is the SP or 7876 // PC and if destination register is the SP, so restrict register class 7877 unsigned NewRsbDstReg = 7878 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 7879 7880 // Transfer the remainder of BB and its successor edges to sinkMBB. 7881 SinkBB->splice(SinkBB->begin(), BB, 7882 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7883 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 7884 7885 BB->addSuccessor(RSBBB); 7886 BB->addSuccessor(SinkBB); 7887 7888 // fall through to SinkMBB 7889 RSBBB->addSuccessor(SinkBB); 7890 7891 // insert a cmp at the end of BB 7892 AddDefaultPred(BuildMI(BB, dl, 7893 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 7894 .addReg(ABSSrcReg).addImm(0)); 7895 7896 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 7897 BuildMI(BB, dl, 7898 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 7899 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 7900 7901 // insert rsbri in RSBBB 7902 // Note: BCC and rsbri will be converted into predicated rsbmi 7903 // by if-conversion pass 7904 BuildMI(*RSBBB, RSBBB->begin(), dl, 7905 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 7906 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 7907 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 7908 7909 // insert PHI in SinkBB, 7910 // reuse ABSDstReg to not change uses of ABS instruction 7911 BuildMI(*SinkBB, SinkBB->begin(), dl, 7912 TII->get(ARM::PHI), ABSDstReg) 7913 .addReg(NewRsbDstReg).addMBB(RSBBB) 7914 .addReg(ABSSrcReg).addMBB(BB); 7915 7916 // remove ABS instruction 7917 MI->eraseFromParent(); 7918 7919 // return last added BB 7920 return SinkBB; 7921 } 7922 case ARM::COPY_STRUCT_BYVAL_I32: 7923 ++NumLoopByVals; 7924 return EmitStructByval(MI, BB); 7925 case ARM::WIN__CHKSTK: 7926 return EmitLowered__chkstk(MI, BB); 7927 } 7928 } 7929 7930 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 7931 SDNode *Node) const { 7932 const MCInstrDesc *MCID = &MI->getDesc(); 7933 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 7934 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 7935 // operand is still set to noreg. If needed, set the optional operand's 7936 // register to CPSR, and remove the redundant implicit def. 7937 // 7938 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 7939 7940 // Rename pseudo opcodes. 7941 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 7942 if (NewOpc) { 7943 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 7944 MCID = &TII->get(NewOpc); 7945 7946 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 7947 "converted opcode should be the same except for cc_out"); 7948 7949 MI->setDesc(*MCID); 7950 7951 // Add the optional cc_out operand 7952 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 7953 } 7954 unsigned ccOutIdx = MCID->getNumOperands() - 1; 7955 7956 // Any ARM instruction that sets the 's' bit should specify an optional 7957 // "cc_out" operand in the last operand position. 7958 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 7959 assert(!NewOpc && "Optional cc_out operand required"); 7960 return; 7961 } 7962 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 7963 // since we already have an optional CPSR def. 7964 bool definesCPSR = false; 7965 bool deadCPSR = false; 7966 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 7967 i != e; ++i) { 7968 const MachineOperand &MO = MI->getOperand(i); 7969 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 7970 definesCPSR = true; 7971 if (MO.isDead()) 7972 deadCPSR = true; 7973 MI->RemoveOperand(i); 7974 break; 7975 } 7976 } 7977 if (!definesCPSR) { 7978 assert(!NewOpc && "Optional cc_out operand required"); 7979 return; 7980 } 7981 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 7982 if (deadCPSR) { 7983 assert(!MI->getOperand(ccOutIdx).getReg() && 7984 "expect uninitialized optional cc_out operand"); 7985 return; 7986 } 7987 7988 // If this instruction was defined with an optional CPSR def and its dag node 7989 // had a live implicit CPSR def, then activate the optional CPSR def. 7990 MachineOperand &MO = MI->getOperand(ccOutIdx); 7991 MO.setReg(ARM::CPSR); 7992 MO.setIsDef(true); 7993 } 7994 7995 //===----------------------------------------------------------------------===// 7996 // ARM Optimization Hooks 7997 //===----------------------------------------------------------------------===// 7998 7999 // Helper function that checks if N is a null or all ones constant. 8000 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8001 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N); 8002 if (!C) 8003 return false; 8004 return AllOnes ? C->isAllOnesValue() : C->isNullValue(); 8005 } 8006 8007 // Return true if N is conditionally 0 or all ones. 8008 // Detects these expressions where cc is an i1 value: 8009 // 8010 // (select cc 0, y) [AllOnes=0] 8011 // (select cc y, 0) [AllOnes=0] 8012 // (zext cc) [AllOnes=0] 8013 // (sext cc) [AllOnes=0/1] 8014 // (select cc -1, y) [AllOnes=1] 8015 // (select cc y, -1) [AllOnes=1] 8016 // 8017 // Invert is set when N is the null/all ones constant when CC is false. 8018 // OtherOp is set to the alternative value of N. 8019 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8020 SDValue &CC, bool &Invert, 8021 SDValue &OtherOp, 8022 SelectionDAG &DAG) { 8023 switch (N->getOpcode()) { 8024 default: return false; 8025 case ISD::SELECT: { 8026 CC = N->getOperand(0); 8027 SDValue N1 = N->getOperand(1); 8028 SDValue N2 = N->getOperand(2); 8029 if (isZeroOrAllOnes(N1, AllOnes)) { 8030 Invert = false; 8031 OtherOp = N2; 8032 return true; 8033 } 8034 if (isZeroOrAllOnes(N2, AllOnes)) { 8035 Invert = true; 8036 OtherOp = N1; 8037 return true; 8038 } 8039 return false; 8040 } 8041 case ISD::ZERO_EXTEND: 8042 // (zext cc) can never be the all ones value. 8043 if (AllOnes) 8044 return false; 8045 // Fall through. 8046 case ISD::SIGN_EXTEND: { 8047 SDLoc dl(N); 8048 EVT VT = N->getValueType(0); 8049 CC = N->getOperand(0); 8050 if (CC.getValueType() != MVT::i1) 8051 return false; 8052 Invert = !AllOnes; 8053 if (AllOnes) 8054 // When looking for an AllOnes constant, N is an sext, and the 'other' 8055 // value is 0. 8056 OtherOp = DAG.getConstant(0, dl, VT); 8057 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8058 // When looking for a 0 constant, N can be zext or sext. 8059 OtherOp = DAG.getConstant(1, dl, VT); 8060 else 8061 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8062 VT); 8063 return true; 8064 } 8065 } 8066 } 8067 8068 // Combine a constant select operand into its use: 8069 // 8070 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8071 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8072 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8073 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8074 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8075 // 8076 // The transform is rejected if the select doesn't have a constant operand that 8077 // is null, or all ones when AllOnes is set. 8078 // 8079 // Also recognize sext/zext from i1: 8080 // 8081 // (add (zext cc), x) -> (select cc (add x, 1), x) 8082 // (add (sext cc), x) -> (select cc (add x, -1), x) 8083 // 8084 // These transformations eventually create predicated instructions. 8085 // 8086 // @param N The node to transform. 8087 // @param Slct The N operand that is a select. 8088 // @param OtherOp The other N operand (x above). 8089 // @param DCI Context. 8090 // @param AllOnes Require the select constant to be all ones instead of null. 8091 // @returns The new node, or SDValue() on failure. 8092 static 8093 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8094 TargetLowering::DAGCombinerInfo &DCI, 8095 bool AllOnes = false) { 8096 SelectionDAG &DAG = DCI.DAG; 8097 EVT VT = N->getValueType(0); 8098 SDValue NonConstantVal; 8099 SDValue CCOp; 8100 bool SwapSelectOps; 8101 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8102 NonConstantVal, DAG)) 8103 return SDValue(); 8104 8105 // Slct is now know to be the desired identity constant when CC is true. 8106 SDValue TrueVal = OtherOp; 8107 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8108 OtherOp, NonConstantVal); 8109 // Unless SwapSelectOps says CC should be false. 8110 if (SwapSelectOps) 8111 std::swap(TrueVal, FalseVal); 8112 8113 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8114 CCOp, TrueVal, FalseVal); 8115 } 8116 8117 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8118 static 8119 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8120 TargetLowering::DAGCombinerInfo &DCI) { 8121 SDValue N0 = N->getOperand(0); 8122 SDValue N1 = N->getOperand(1); 8123 if (N0.getNode()->hasOneUse()) { 8124 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes); 8125 if (Result.getNode()) 8126 return Result; 8127 } 8128 if (N1.getNode()->hasOneUse()) { 8129 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes); 8130 if (Result.getNode()) 8131 return Result; 8132 } 8133 return SDValue(); 8134 } 8135 8136 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8137 // (only after legalization). 8138 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8139 TargetLowering::DAGCombinerInfo &DCI, 8140 const ARMSubtarget *Subtarget) { 8141 8142 // Only perform optimization if after legalize, and if NEON is available. We 8143 // also expected both operands to be BUILD_VECTORs. 8144 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8145 || N0.getOpcode() != ISD::BUILD_VECTOR 8146 || N1.getOpcode() != ISD::BUILD_VECTOR) 8147 return SDValue(); 8148 8149 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8150 EVT VT = N->getValueType(0); 8151 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8152 return SDValue(); 8153 8154 // Check that the vector operands are of the right form. 8155 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8156 // operands, where N is the size of the formed vector. 8157 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8158 // index such that we have a pair wise add pattern. 8159 8160 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8161 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8162 return SDValue(); 8163 SDValue Vec = N0->getOperand(0)->getOperand(0); 8164 SDNode *V = Vec.getNode(); 8165 unsigned nextIndex = 0; 8166 8167 // For each operands to the ADD which are BUILD_VECTORs, 8168 // check to see if each of their operands are an EXTRACT_VECTOR with 8169 // the same vector and appropriate index. 8170 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8171 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8172 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8173 8174 SDValue ExtVec0 = N0->getOperand(i); 8175 SDValue ExtVec1 = N1->getOperand(i); 8176 8177 // First operand is the vector, verify its the same. 8178 if (V != ExtVec0->getOperand(0).getNode() || 8179 V != ExtVec1->getOperand(0).getNode()) 8180 return SDValue(); 8181 8182 // Second is the constant, verify its correct. 8183 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8184 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8185 8186 // For the constant, we want to see all the even or all the odd. 8187 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8188 || C1->getZExtValue() != nextIndex+1) 8189 return SDValue(); 8190 8191 // Increment index. 8192 nextIndex+=2; 8193 } else 8194 return SDValue(); 8195 } 8196 8197 // Create VPADDL node. 8198 SelectionDAG &DAG = DCI.DAG; 8199 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8200 8201 SDLoc dl(N); 8202 8203 // Build operand list. 8204 SmallVector<SDValue, 8> Ops; 8205 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8206 TLI.getPointerTy(DAG.getDataLayout()))); 8207 8208 // Input is the vector. 8209 Ops.push_back(Vec); 8210 8211 // Get widened type and narrowed type. 8212 MVT widenType; 8213 unsigned numElem = VT.getVectorNumElements(); 8214 8215 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8216 switch (inputLaneType.getSimpleVT().SimpleTy) { 8217 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8218 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8219 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8220 default: 8221 llvm_unreachable("Invalid vector element type for padd optimization."); 8222 } 8223 8224 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8225 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8226 return DAG.getNode(ExtOp, dl, VT, tmp); 8227 } 8228 8229 static SDValue findMUL_LOHI(SDValue V) { 8230 if (V->getOpcode() == ISD::UMUL_LOHI || 8231 V->getOpcode() == ISD::SMUL_LOHI) 8232 return V; 8233 return SDValue(); 8234 } 8235 8236 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8237 TargetLowering::DAGCombinerInfo &DCI, 8238 const ARMSubtarget *Subtarget) { 8239 8240 if (Subtarget->isThumb1Only()) return SDValue(); 8241 8242 // Only perform the checks after legalize when the pattern is available. 8243 if (DCI.isBeforeLegalize()) return SDValue(); 8244 8245 // Look for multiply add opportunities. 8246 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8247 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8248 // a glue link from the first add to the second add. 8249 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8250 // a S/UMLAL instruction. 8251 // UMUL_LOHI 8252 // / :lo \ :hi 8253 // / \ [no multiline comment] 8254 // loAdd -> ADDE | 8255 // \ :glue / 8256 // \ / 8257 // ADDC <- hiAdd 8258 // 8259 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8260 SDValue AddcOp0 = AddcNode->getOperand(0); 8261 SDValue AddcOp1 = AddcNode->getOperand(1); 8262 8263 // Check if the two operands are from the same mul_lohi node. 8264 if (AddcOp0.getNode() == AddcOp1.getNode()) 8265 return SDValue(); 8266 8267 assert(AddcNode->getNumValues() == 2 && 8268 AddcNode->getValueType(0) == MVT::i32 && 8269 "Expect ADDC with two result values. First: i32"); 8270 8271 // Check that we have a glued ADDC node. 8272 if (AddcNode->getValueType(1) != MVT::Glue) 8273 return SDValue(); 8274 8275 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8276 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8277 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8278 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8279 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8280 return SDValue(); 8281 8282 // Look for the glued ADDE. 8283 SDNode* AddeNode = AddcNode->getGluedUser(); 8284 if (!AddeNode) 8285 return SDValue(); 8286 8287 // Make sure it is really an ADDE. 8288 if (AddeNode->getOpcode() != ISD::ADDE) 8289 return SDValue(); 8290 8291 assert(AddeNode->getNumOperands() == 3 && 8292 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8293 "ADDE node has the wrong inputs"); 8294 8295 // Check for the triangle shape. 8296 SDValue AddeOp0 = AddeNode->getOperand(0); 8297 SDValue AddeOp1 = AddeNode->getOperand(1); 8298 8299 // Make sure that the ADDE operands are not coming from the same node. 8300 if (AddeOp0.getNode() == AddeOp1.getNode()) 8301 return SDValue(); 8302 8303 // Find the MUL_LOHI node walking up ADDE's operands. 8304 bool IsLeftOperandMUL = false; 8305 SDValue MULOp = findMUL_LOHI(AddeOp0); 8306 if (MULOp == SDValue()) 8307 MULOp = findMUL_LOHI(AddeOp1); 8308 else 8309 IsLeftOperandMUL = true; 8310 if (MULOp == SDValue()) 8311 return SDValue(); 8312 8313 // Figure out the right opcode. 8314 unsigned Opc = MULOp->getOpcode(); 8315 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8316 8317 // Figure out the high and low input values to the MLAL node. 8318 SDValue* HiAdd = nullptr; 8319 SDValue* LoMul = nullptr; 8320 SDValue* LowAdd = nullptr; 8321 8322 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8323 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8324 return SDValue(); 8325 8326 if (IsLeftOperandMUL) 8327 HiAdd = &AddeOp1; 8328 else 8329 HiAdd = &AddeOp0; 8330 8331 8332 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8333 // whose low result is fed to the ADDC we are checking. 8334 8335 if (AddcOp0 == MULOp.getValue(0)) { 8336 LoMul = &AddcOp0; 8337 LowAdd = &AddcOp1; 8338 } 8339 if (AddcOp1 == MULOp.getValue(0)) { 8340 LoMul = &AddcOp1; 8341 LowAdd = &AddcOp0; 8342 } 8343 8344 if (!LoMul) 8345 return SDValue(); 8346 8347 // Create the merged node. 8348 SelectionDAG &DAG = DCI.DAG; 8349 8350 // Build operand list. 8351 SmallVector<SDValue, 8> Ops; 8352 Ops.push_back(LoMul->getOperand(0)); 8353 Ops.push_back(LoMul->getOperand(1)); 8354 Ops.push_back(*LowAdd); 8355 Ops.push_back(*HiAdd); 8356 8357 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8358 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8359 8360 // Replace the ADDs' nodes uses by the MLA node's values. 8361 SDValue HiMLALResult(MLALNode.getNode(), 1); 8362 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8363 8364 SDValue LoMLALResult(MLALNode.getNode(), 0); 8365 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8366 8367 // Return original node to notify the driver to stop replacing. 8368 SDValue resNode(AddcNode, 0); 8369 return resNode; 8370 } 8371 8372 /// PerformADDCCombine - Target-specific dag combine transform from 8373 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 8374 static SDValue PerformADDCCombine(SDNode *N, 8375 TargetLowering::DAGCombinerInfo &DCI, 8376 const ARMSubtarget *Subtarget) { 8377 8378 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 8379 8380 } 8381 8382 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 8383 /// operands N0 and N1. This is a helper for PerformADDCombine that is 8384 /// called with the default operands, and if that fails, with commuted 8385 /// operands. 8386 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 8387 TargetLowering::DAGCombinerInfo &DCI, 8388 const ARMSubtarget *Subtarget){ 8389 8390 // Attempt to create vpaddl for this add. 8391 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget); 8392 if (Result.getNode()) 8393 return Result; 8394 8395 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8396 if (N0.getNode()->hasOneUse()) { 8397 SDValue Result = combineSelectAndUse(N, N0, N1, DCI); 8398 if (Result.getNode()) return Result; 8399 } 8400 return SDValue(); 8401 } 8402 8403 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 8404 /// 8405 static SDValue PerformADDCombine(SDNode *N, 8406 TargetLowering::DAGCombinerInfo &DCI, 8407 const ARMSubtarget *Subtarget) { 8408 SDValue N0 = N->getOperand(0); 8409 SDValue N1 = N->getOperand(1); 8410 8411 // First try with the default operand order. 8412 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget); 8413 if (Result.getNode()) 8414 return Result; 8415 8416 // If that didn't work, try again with the operands commuted. 8417 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 8418 } 8419 8420 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 8421 /// 8422 static SDValue PerformSUBCombine(SDNode *N, 8423 TargetLowering::DAGCombinerInfo &DCI) { 8424 SDValue N0 = N->getOperand(0); 8425 SDValue N1 = N->getOperand(1); 8426 8427 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8428 if (N1.getNode()->hasOneUse()) { 8429 SDValue Result = combineSelectAndUse(N, N1, N0, DCI); 8430 if (Result.getNode()) return Result; 8431 } 8432 8433 return SDValue(); 8434 } 8435 8436 /// PerformVMULCombine 8437 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 8438 /// special multiplier accumulator forwarding. 8439 /// vmul d3, d0, d2 8440 /// vmla d3, d1, d2 8441 /// is faster than 8442 /// vadd d3, d0, d1 8443 /// vmul d3, d3, d2 8444 // However, for (A + B) * (A + B), 8445 // vadd d2, d0, d1 8446 // vmul d3, d0, d2 8447 // vmla d3, d1, d2 8448 // is slower than 8449 // vadd d2, d0, d1 8450 // vmul d3, d2, d2 8451 static SDValue PerformVMULCombine(SDNode *N, 8452 TargetLowering::DAGCombinerInfo &DCI, 8453 const ARMSubtarget *Subtarget) { 8454 if (!Subtarget->hasVMLxForwarding()) 8455 return SDValue(); 8456 8457 SelectionDAG &DAG = DCI.DAG; 8458 SDValue N0 = N->getOperand(0); 8459 SDValue N1 = N->getOperand(1); 8460 unsigned Opcode = N0.getOpcode(); 8461 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8462 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 8463 Opcode = N1.getOpcode(); 8464 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8465 Opcode != ISD::FADD && Opcode != ISD::FSUB) 8466 return SDValue(); 8467 std::swap(N0, N1); 8468 } 8469 8470 if (N0 == N1) 8471 return SDValue(); 8472 8473 EVT VT = N->getValueType(0); 8474 SDLoc DL(N); 8475 SDValue N00 = N0->getOperand(0); 8476 SDValue N01 = N0->getOperand(1); 8477 return DAG.getNode(Opcode, DL, VT, 8478 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 8479 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 8480 } 8481 8482 static SDValue PerformMULCombine(SDNode *N, 8483 TargetLowering::DAGCombinerInfo &DCI, 8484 const ARMSubtarget *Subtarget) { 8485 SelectionDAG &DAG = DCI.DAG; 8486 8487 if (Subtarget->isThumb1Only()) 8488 return SDValue(); 8489 8490 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8491 return SDValue(); 8492 8493 EVT VT = N->getValueType(0); 8494 if (VT.is64BitVector() || VT.is128BitVector()) 8495 return PerformVMULCombine(N, DCI, Subtarget); 8496 if (VT != MVT::i32) 8497 return SDValue(); 8498 8499 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8500 if (!C) 8501 return SDValue(); 8502 8503 int64_t MulAmt = C->getSExtValue(); 8504 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 8505 8506 ShiftAmt = ShiftAmt & (32 - 1); 8507 SDValue V = N->getOperand(0); 8508 SDLoc DL(N); 8509 8510 SDValue Res; 8511 MulAmt >>= ShiftAmt; 8512 8513 if (MulAmt >= 0) { 8514 if (isPowerOf2_32(MulAmt - 1)) { 8515 // (mul x, 2^N + 1) => (add (shl x, N), x) 8516 Res = DAG.getNode(ISD::ADD, DL, VT, 8517 V, 8518 DAG.getNode(ISD::SHL, DL, VT, 8519 V, 8520 DAG.getConstant(Log2_32(MulAmt - 1), DL, 8521 MVT::i32))); 8522 } else if (isPowerOf2_32(MulAmt + 1)) { 8523 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8524 Res = DAG.getNode(ISD::SUB, DL, VT, 8525 DAG.getNode(ISD::SHL, DL, VT, 8526 V, 8527 DAG.getConstant(Log2_32(MulAmt + 1), DL, 8528 MVT::i32)), 8529 V); 8530 } else 8531 return SDValue(); 8532 } else { 8533 uint64_t MulAmtAbs = -MulAmt; 8534 if (isPowerOf2_32(MulAmtAbs + 1)) { 8535 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8536 Res = DAG.getNode(ISD::SUB, DL, VT, 8537 V, 8538 DAG.getNode(ISD::SHL, DL, VT, 8539 V, 8540 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 8541 MVT::i32))); 8542 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 8543 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8544 Res = DAG.getNode(ISD::ADD, DL, VT, 8545 V, 8546 DAG.getNode(ISD::SHL, DL, VT, 8547 V, 8548 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 8549 MVT::i32))); 8550 Res = DAG.getNode(ISD::SUB, DL, VT, 8551 DAG.getConstant(0, DL, MVT::i32), Res); 8552 8553 } else 8554 return SDValue(); 8555 } 8556 8557 if (ShiftAmt != 0) 8558 Res = DAG.getNode(ISD::SHL, DL, VT, 8559 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 8560 8561 // Do not add new nodes to DAG combiner worklist. 8562 DCI.CombineTo(N, Res, false); 8563 return SDValue(); 8564 } 8565 8566 static SDValue PerformANDCombine(SDNode *N, 8567 TargetLowering::DAGCombinerInfo &DCI, 8568 const ARMSubtarget *Subtarget) { 8569 8570 // Attempt to use immediate-form VBIC 8571 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8572 SDLoc dl(N); 8573 EVT VT = N->getValueType(0); 8574 SelectionDAG &DAG = DCI.DAG; 8575 8576 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8577 return SDValue(); 8578 8579 APInt SplatBits, SplatUndef; 8580 unsigned SplatBitSize; 8581 bool HasAnyUndefs; 8582 if (BVN && 8583 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8584 if (SplatBitSize <= 64) { 8585 EVT VbicVT; 8586 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 8587 SplatUndef.getZExtValue(), SplatBitSize, 8588 DAG, dl, VbicVT, VT.is128BitVector(), 8589 OtherModImm); 8590 if (Val.getNode()) { 8591 SDValue Input = 8592 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 8593 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 8594 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 8595 } 8596 } 8597 } 8598 8599 if (!Subtarget->isThumb1Only()) { 8600 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 8601 SDValue Result = combineSelectAndUseCommutative(N, true, DCI); 8602 if (Result.getNode()) 8603 return Result; 8604 } 8605 8606 return SDValue(); 8607 } 8608 8609 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 8610 static SDValue PerformORCombine(SDNode *N, 8611 TargetLowering::DAGCombinerInfo &DCI, 8612 const ARMSubtarget *Subtarget) { 8613 // Attempt to use immediate-form VORR 8614 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8615 SDLoc dl(N); 8616 EVT VT = N->getValueType(0); 8617 SelectionDAG &DAG = DCI.DAG; 8618 8619 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8620 return SDValue(); 8621 8622 APInt SplatBits, SplatUndef; 8623 unsigned SplatBitSize; 8624 bool HasAnyUndefs; 8625 if (BVN && Subtarget->hasNEON() && 8626 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8627 if (SplatBitSize <= 64) { 8628 EVT VorrVT; 8629 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 8630 SplatUndef.getZExtValue(), SplatBitSize, 8631 DAG, dl, VorrVT, VT.is128BitVector(), 8632 OtherModImm); 8633 if (Val.getNode()) { 8634 SDValue Input = 8635 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 8636 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 8637 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 8638 } 8639 } 8640 } 8641 8642 if (!Subtarget->isThumb1Only()) { 8643 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8644 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 8645 if (Result.getNode()) 8646 return Result; 8647 } 8648 8649 // The code below optimizes (or (and X, Y), Z). 8650 // The AND operand needs to have a single user to make these optimizations 8651 // profitable. 8652 SDValue N0 = N->getOperand(0); 8653 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 8654 return SDValue(); 8655 SDValue N1 = N->getOperand(1); 8656 8657 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 8658 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 8659 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 8660 APInt SplatUndef; 8661 unsigned SplatBitSize; 8662 bool HasAnyUndefs; 8663 8664 APInt SplatBits0, SplatBits1; 8665 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 8666 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 8667 // Ensure that the second operand of both ands are constants 8668 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 8669 HasAnyUndefs) && !HasAnyUndefs) { 8670 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 8671 HasAnyUndefs) && !HasAnyUndefs) { 8672 // Ensure that the bit width of the constants are the same and that 8673 // the splat arguments are logical inverses as per the pattern we 8674 // are trying to simplify. 8675 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 8676 SplatBits0 == ~SplatBits1) { 8677 // Canonicalize the vector type to make instruction selection 8678 // simpler. 8679 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 8680 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 8681 N0->getOperand(1), 8682 N0->getOperand(0), 8683 N1->getOperand(0)); 8684 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 8685 } 8686 } 8687 } 8688 } 8689 8690 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 8691 // reasonable. 8692 8693 // BFI is only available on V6T2+ 8694 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 8695 return SDValue(); 8696 8697 SDLoc DL(N); 8698 // 1) or (and A, mask), val => ARMbfi A, val, mask 8699 // iff (val & mask) == val 8700 // 8701 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 8702 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 8703 // && mask == ~mask2 8704 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 8705 // && ~mask == mask2 8706 // (i.e., copy a bitfield value into another bitfield of the same width) 8707 8708 if (VT != MVT::i32) 8709 return SDValue(); 8710 8711 SDValue N00 = N0.getOperand(0); 8712 8713 // The value and the mask need to be constants so we can verify this is 8714 // actually a bitfield set. If the mask is 0xffff, we can do better 8715 // via a movt instruction, so don't use BFI in that case. 8716 SDValue MaskOp = N0.getOperand(1); 8717 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 8718 if (!MaskC) 8719 return SDValue(); 8720 unsigned Mask = MaskC->getZExtValue(); 8721 if (Mask == 0xffff) 8722 return SDValue(); 8723 SDValue Res; 8724 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 8725 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 8726 if (N1C) { 8727 unsigned Val = N1C->getZExtValue(); 8728 if ((Val & ~Mask) != Val) 8729 return SDValue(); 8730 8731 if (ARM::isBitFieldInvertedMask(Mask)) { 8732 Val >>= countTrailingZeros(~Mask); 8733 8734 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 8735 DAG.getConstant(Val, DL, MVT::i32), 8736 DAG.getConstant(Mask, DL, MVT::i32)); 8737 8738 // Do not add new nodes to DAG combiner worklist. 8739 DCI.CombineTo(N, Res, false); 8740 return SDValue(); 8741 } 8742 } else if (N1.getOpcode() == ISD::AND) { 8743 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 8744 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 8745 if (!N11C) 8746 return SDValue(); 8747 unsigned Mask2 = N11C->getZExtValue(); 8748 8749 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 8750 // as is to match. 8751 if (ARM::isBitFieldInvertedMask(Mask) && 8752 (Mask == ~Mask2)) { 8753 // The pack halfword instruction works better for masks that fit it, 8754 // so use that when it's available. 8755 if (Subtarget->hasT2ExtractPack() && 8756 (Mask == 0xffff || Mask == 0xffff0000)) 8757 return SDValue(); 8758 // 2a 8759 unsigned amt = countTrailingZeros(Mask2); 8760 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 8761 DAG.getConstant(amt, DL, MVT::i32)); 8762 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 8763 DAG.getConstant(Mask, DL, MVT::i32)); 8764 // Do not add new nodes to DAG combiner worklist. 8765 DCI.CombineTo(N, Res, false); 8766 return SDValue(); 8767 } else if (ARM::isBitFieldInvertedMask(~Mask) && 8768 (~Mask == Mask2)) { 8769 // The pack halfword instruction works better for masks that fit it, 8770 // so use that when it's available. 8771 if (Subtarget->hasT2ExtractPack() && 8772 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 8773 return SDValue(); 8774 // 2b 8775 unsigned lsb = countTrailingZeros(Mask); 8776 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 8777 DAG.getConstant(lsb, DL, MVT::i32)); 8778 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 8779 DAG.getConstant(Mask2, DL, MVT::i32)); 8780 // Do not add new nodes to DAG combiner worklist. 8781 DCI.CombineTo(N, Res, false); 8782 return SDValue(); 8783 } 8784 } 8785 8786 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 8787 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 8788 ARM::isBitFieldInvertedMask(~Mask)) { 8789 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 8790 // where lsb(mask) == #shamt and masked bits of B are known zero. 8791 SDValue ShAmt = N00.getOperand(1); 8792 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 8793 unsigned LSB = countTrailingZeros(Mask); 8794 if (ShAmtC != LSB) 8795 return SDValue(); 8796 8797 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 8798 DAG.getConstant(~Mask, DL, MVT::i32)); 8799 8800 // Do not add new nodes to DAG combiner worklist. 8801 DCI.CombineTo(N, Res, false); 8802 } 8803 8804 return SDValue(); 8805 } 8806 8807 static SDValue PerformXORCombine(SDNode *N, 8808 TargetLowering::DAGCombinerInfo &DCI, 8809 const ARMSubtarget *Subtarget) { 8810 EVT VT = N->getValueType(0); 8811 SelectionDAG &DAG = DCI.DAG; 8812 8813 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8814 return SDValue(); 8815 8816 if (!Subtarget->isThumb1Only()) { 8817 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8818 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 8819 if (Result.getNode()) 8820 return Result; 8821 } 8822 8823 return SDValue(); 8824 } 8825 8826 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 8827 /// the bits being cleared by the AND are not demanded by the BFI. 8828 static SDValue PerformBFICombine(SDNode *N, 8829 TargetLowering::DAGCombinerInfo &DCI) { 8830 SDValue N1 = N->getOperand(1); 8831 if (N1.getOpcode() == ISD::AND) { 8832 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 8833 if (!N11C) 8834 return SDValue(); 8835 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 8836 unsigned LSB = countTrailingZeros(~InvMask); 8837 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 8838 assert(Width < 8839 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 8840 "undefined behavior"); 8841 unsigned Mask = (1u << Width) - 1; 8842 unsigned Mask2 = N11C->getZExtValue(); 8843 if ((Mask & (~Mask2)) == 0) 8844 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 8845 N->getOperand(0), N1.getOperand(0), 8846 N->getOperand(2)); 8847 } 8848 return SDValue(); 8849 } 8850 8851 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 8852 /// ARMISD::VMOVRRD. 8853 static SDValue PerformVMOVRRDCombine(SDNode *N, 8854 TargetLowering::DAGCombinerInfo &DCI, 8855 const ARMSubtarget *Subtarget) { 8856 // vmovrrd(vmovdrr x, y) -> x,y 8857 SDValue InDouble = N->getOperand(0); 8858 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 8859 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 8860 8861 // vmovrrd(load f64) -> (load i32), (load i32) 8862 SDNode *InNode = InDouble.getNode(); 8863 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 8864 InNode->getValueType(0) == MVT::f64 && 8865 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 8866 !cast<LoadSDNode>(InNode)->isVolatile()) { 8867 // TODO: Should this be done for non-FrameIndex operands? 8868 LoadSDNode *LD = cast<LoadSDNode>(InNode); 8869 8870 SelectionDAG &DAG = DCI.DAG; 8871 SDLoc DL(LD); 8872 SDValue BasePtr = LD->getBasePtr(); 8873 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 8874 LD->getPointerInfo(), LD->isVolatile(), 8875 LD->isNonTemporal(), LD->isInvariant(), 8876 LD->getAlignment()); 8877 8878 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 8879 DAG.getConstant(4, DL, MVT::i32)); 8880 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 8881 LD->getPointerInfo(), LD->isVolatile(), 8882 LD->isNonTemporal(), LD->isInvariant(), 8883 std::min(4U, LD->getAlignment() / 2)); 8884 8885 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 8886 if (DCI.DAG.getDataLayout().isBigEndian()) 8887 std::swap (NewLD1, NewLD2); 8888 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 8889 return Result; 8890 } 8891 8892 return SDValue(); 8893 } 8894 8895 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 8896 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 8897 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 8898 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 8899 SDValue Op0 = N->getOperand(0); 8900 SDValue Op1 = N->getOperand(1); 8901 if (Op0.getOpcode() == ISD::BITCAST) 8902 Op0 = Op0.getOperand(0); 8903 if (Op1.getOpcode() == ISD::BITCAST) 8904 Op1 = Op1.getOperand(0); 8905 if (Op0.getOpcode() == ARMISD::VMOVRRD && 8906 Op0.getNode() == Op1.getNode() && 8907 Op0.getResNo() == 0 && Op1.getResNo() == 1) 8908 return DAG.getNode(ISD::BITCAST, SDLoc(N), 8909 N->getValueType(0), Op0.getOperand(0)); 8910 return SDValue(); 8911 } 8912 8913 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 8914 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 8915 /// i64 vector to have f64 elements, since the value can then be loaded 8916 /// directly into a VFP register. 8917 static bool hasNormalLoadOperand(SDNode *N) { 8918 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 8919 for (unsigned i = 0; i < NumElts; ++i) { 8920 SDNode *Elt = N->getOperand(i).getNode(); 8921 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 8922 return true; 8923 } 8924 return false; 8925 } 8926 8927 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 8928 /// ISD::BUILD_VECTOR. 8929 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 8930 TargetLowering::DAGCombinerInfo &DCI, 8931 const ARMSubtarget *Subtarget) { 8932 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 8933 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 8934 // into a pair of GPRs, which is fine when the value is used as a scalar, 8935 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 8936 SelectionDAG &DAG = DCI.DAG; 8937 if (N->getNumOperands() == 2) { 8938 SDValue RV = PerformVMOVDRRCombine(N, DAG); 8939 if (RV.getNode()) 8940 return RV; 8941 } 8942 8943 // Load i64 elements as f64 values so that type legalization does not split 8944 // them up into i32 values. 8945 EVT VT = N->getValueType(0); 8946 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 8947 return SDValue(); 8948 SDLoc dl(N); 8949 SmallVector<SDValue, 8> Ops; 8950 unsigned NumElts = VT.getVectorNumElements(); 8951 for (unsigned i = 0; i < NumElts; ++i) { 8952 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 8953 Ops.push_back(V); 8954 // Make the DAGCombiner fold the bitcast. 8955 DCI.AddToWorklist(V.getNode()); 8956 } 8957 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 8958 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops); 8959 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 8960 } 8961 8962 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 8963 static SDValue 8964 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 8965 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 8966 // At that time, we may have inserted bitcasts from integer to float. 8967 // If these bitcasts have survived DAGCombine, change the lowering of this 8968 // BUILD_VECTOR in something more vector friendly, i.e., that does not 8969 // force to use floating point types. 8970 8971 // Make sure we can change the type of the vector. 8972 // This is possible iff: 8973 // 1. The vector is only used in a bitcast to a integer type. I.e., 8974 // 1.1. Vector is used only once. 8975 // 1.2. Use is a bit convert to an integer type. 8976 // 2. The size of its operands are 32-bits (64-bits are not legal). 8977 EVT VT = N->getValueType(0); 8978 EVT EltVT = VT.getVectorElementType(); 8979 8980 // Check 1.1. and 2. 8981 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 8982 return SDValue(); 8983 8984 // By construction, the input type must be float. 8985 assert(EltVT == MVT::f32 && "Unexpected type!"); 8986 8987 // Check 1.2. 8988 SDNode *Use = *N->use_begin(); 8989 if (Use->getOpcode() != ISD::BITCAST || 8990 Use->getValueType(0).isFloatingPoint()) 8991 return SDValue(); 8992 8993 // Check profitability. 8994 // Model is, if more than half of the relevant operands are bitcast from 8995 // i32, turn the build_vector into a sequence of insert_vector_elt. 8996 // Relevant operands are everything that is not statically 8997 // (i.e., at compile time) bitcasted. 8998 unsigned NumOfBitCastedElts = 0; 8999 unsigned NumElts = VT.getVectorNumElements(); 9000 unsigned NumOfRelevantElts = NumElts; 9001 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9002 SDValue Elt = N->getOperand(Idx); 9003 if (Elt->getOpcode() == ISD::BITCAST) { 9004 // Assume only bit cast to i32 will go away. 9005 if (Elt->getOperand(0).getValueType() == MVT::i32) 9006 ++NumOfBitCastedElts; 9007 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt)) 9008 // Constants are statically casted, thus do not count them as 9009 // relevant operands. 9010 --NumOfRelevantElts; 9011 } 9012 9013 // Check if more than half of the elements require a non-free bitcast. 9014 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9015 return SDValue(); 9016 9017 SelectionDAG &DAG = DCI.DAG; 9018 // Create the new vector type. 9019 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9020 // Check if the type is legal. 9021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9022 if (!TLI.isTypeLegal(VecVT)) 9023 return SDValue(); 9024 9025 // Combine: 9026 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9027 // => BITCAST INSERT_VECTOR_ELT 9028 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9029 // (BITCAST EN), N. 9030 SDValue Vec = DAG.getUNDEF(VecVT); 9031 SDLoc dl(N); 9032 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9033 SDValue V = N->getOperand(Idx); 9034 if (V.getOpcode() == ISD::UNDEF) 9035 continue; 9036 if (V.getOpcode() == ISD::BITCAST && 9037 V->getOperand(0).getValueType() == MVT::i32) 9038 // Fold obvious case. 9039 V = V.getOperand(0); 9040 else { 9041 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9042 // Make the DAGCombiner fold the bitcasts. 9043 DCI.AddToWorklist(V.getNode()); 9044 } 9045 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9046 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9047 } 9048 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9049 // Make the DAGCombiner fold the bitcasts. 9050 DCI.AddToWorklist(Vec.getNode()); 9051 return Vec; 9052 } 9053 9054 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9055 /// ISD::INSERT_VECTOR_ELT. 9056 static SDValue PerformInsertEltCombine(SDNode *N, 9057 TargetLowering::DAGCombinerInfo &DCI) { 9058 // Bitcast an i64 load inserted into a vector to f64. 9059 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9060 EVT VT = N->getValueType(0); 9061 SDNode *Elt = N->getOperand(1).getNode(); 9062 if (VT.getVectorElementType() != MVT::i64 || 9063 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9064 return SDValue(); 9065 9066 SelectionDAG &DAG = DCI.DAG; 9067 SDLoc dl(N); 9068 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9069 VT.getVectorNumElements()); 9070 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9071 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9072 // Make the DAGCombiner fold the bitcasts. 9073 DCI.AddToWorklist(Vec.getNode()); 9074 DCI.AddToWorklist(V.getNode()); 9075 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9076 Vec, V, N->getOperand(2)); 9077 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9078 } 9079 9080 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9081 /// ISD::VECTOR_SHUFFLE. 9082 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9083 // The LLVM shufflevector instruction does not require the shuffle mask 9084 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9085 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9086 // operands do not match the mask length, they are extended by concatenating 9087 // them with undef vectors. That is probably the right thing for other 9088 // targets, but for NEON it is better to concatenate two double-register 9089 // size vector operands into a single quad-register size vector. Do that 9090 // transformation here: 9091 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9092 // shuffle(concat(v1, v2), undef) 9093 SDValue Op0 = N->getOperand(0); 9094 SDValue Op1 = N->getOperand(1); 9095 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9096 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9097 Op0.getNumOperands() != 2 || 9098 Op1.getNumOperands() != 2) 9099 return SDValue(); 9100 SDValue Concat0Op1 = Op0.getOperand(1); 9101 SDValue Concat1Op1 = Op1.getOperand(1); 9102 if (Concat0Op1.getOpcode() != ISD::UNDEF || 9103 Concat1Op1.getOpcode() != ISD::UNDEF) 9104 return SDValue(); 9105 // Skip the transformation if any of the types are illegal. 9106 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9107 EVT VT = N->getValueType(0); 9108 if (!TLI.isTypeLegal(VT) || 9109 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9110 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9111 return SDValue(); 9112 9113 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9114 Op0.getOperand(0), Op1.getOperand(0)); 9115 // Translate the shuffle mask. 9116 SmallVector<int, 16> NewMask; 9117 unsigned NumElts = VT.getVectorNumElements(); 9118 unsigned HalfElts = NumElts/2; 9119 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9120 for (unsigned n = 0; n < NumElts; ++n) { 9121 int MaskElt = SVN->getMaskElt(n); 9122 int NewElt = -1; 9123 if (MaskElt < (int)HalfElts) 9124 NewElt = MaskElt; 9125 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9126 NewElt = HalfElts + MaskElt - NumElts; 9127 NewMask.push_back(NewElt); 9128 } 9129 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9130 DAG.getUNDEF(VT), NewMask.data()); 9131 } 9132 9133 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9134 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9135 /// base address updates. 9136 /// For generic load/stores, the memory type is assumed to be a vector. 9137 /// The caller is assumed to have checked legality. 9138 static SDValue CombineBaseUpdate(SDNode *N, 9139 TargetLowering::DAGCombinerInfo &DCI) { 9140 SelectionDAG &DAG = DCI.DAG; 9141 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9142 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9143 const bool isStore = N->getOpcode() == ISD::STORE; 9144 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9145 SDValue Addr = N->getOperand(AddrOpIdx); 9146 MemSDNode *MemN = cast<MemSDNode>(N); 9147 SDLoc dl(N); 9148 9149 // Search for a use of the address operand that is an increment. 9150 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9151 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9152 SDNode *User = *UI; 9153 if (User->getOpcode() != ISD::ADD || 9154 UI.getUse().getResNo() != Addr.getResNo()) 9155 continue; 9156 9157 // Check that the add is independent of the load/store. Otherwise, folding 9158 // it would create a cycle. 9159 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9160 continue; 9161 9162 // Find the new opcode for the updating load/store. 9163 bool isLoadOp = true; 9164 bool isLaneOp = false; 9165 unsigned NewOpc = 0; 9166 unsigned NumVecs = 0; 9167 if (isIntrinsic) { 9168 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9169 switch (IntNo) { 9170 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9171 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9172 NumVecs = 1; break; 9173 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9174 NumVecs = 2; break; 9175 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9176 NumVecs = 3; break; 9177 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9178 NumVecs = 4; break; 9179 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9180 NumVecs = 2; isLaneOp = true; break; 9181 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9182 NumVecs = 3; isLaneOp = true; break; 9183 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9184 NumVecs = 4; isLaneOp = true; break; 9185 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9186 NumVecs = 1; isLoadOp = false; break; 9187 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9188 NumVecs = 2; isLoadOp = false; break; 9189 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9190 NumVecs = 3; isLoadOp = false; break; 9191 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9192 NumVecs = 4; isLoadOp = false; break; 9193 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9194 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9195 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9196 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9197 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9198 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9199 } 9200 } else { 9201 isLaneOp = true; 9202 switch (N->getOpcode()) { 9203 default: llvm_unreachable("unexpected opcode for Neon base update"); 9204 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9205 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9206 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9207 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9208 NumVecs = 1; isLaneOp = false; break; 9209 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9210 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9211 } 9212 } 9213 9214 // Find the size of memory referenced by the load/store. 9215 EVT VecTy; 9216 if (isLoadOp) { 9217 VecTy = N->getValueType(0); 9218 } else if (isIntrinsic) { 9219 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 9220 } else { 9221 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 9222 VecTy = N->getOperand(1).getValueType(); 9223 } 9224 9225 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9226 if (isLaneOp) 9227 NumBytes /= VecTy.getVectorNumElements(); 9228 9229 // If the increment is a constant, it must match the memory ref size. 9230 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9231 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9232 uint64_t IncVal = CInc->getZExtValue(); 9233 if (IncVal != NumBytes) 9234 continue; 9235 } else if (NumBytes >= 3 * 16) { 9236 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 9237 // separate instructions that make it harder to use a non-constant update. 9238 continue; 9239 } 9240 9241 // OK, we found an ADD we can fold into the base update. 9242 // Now, create a _UPD node, taking care of not breaking alignment. 9243 9244 EVT AlignedVecTy = VecTy; 9245 unsigned Alignment = MemN->getAlignment(); 9246 9247 // If this is a less-than-standard-aligned load/store, change the type to 9248 // match the standard alignment. 9249 // The alignment is overlooked when selecting _UPD variants; and it's 9250 // easier to introduce bitcasts here than fix that. 9251 // There are 3 ways to get to this base-update combine: 9252 // - intrinsics: they are assumed to be properly aligned (to the standard 9253 // alignment of the memory type), so we don't need to do anything. 9254 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 9255 // intrinsics, so, likewise, there's nothing to do. 9256 // - generic load/store instructions: the alignment is specified as an 9257 // explicit operand, rather than implicitly as the standard alignment 9258 // of the memory type (like the intrisics). We need to change the 9259 // memory type to match the explicit alignment. That way, we don't 9260 // generate non-standard-aligned ARMISD::VLDx nodes. 9261 if (isa<LSBaseSDNode>(N)) { 9262 if (Alignment == 0) 9263 Alignment = 1; 9264 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 9265 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 9266 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 9267 assert(!isLaneOp && "Unexpected generic load/store lane."); 9268 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 9269 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 9270 } 9271 // Don't set an explicit alignment on regular load/stores that we want 9272 // to transform to VLD/VST 1_UPD nodes. 9273 // This matches the behavior of regular load/stores, which only get an 9274 // explicit alignment if the MMO alignment is larger than the standard 9275 // alignment of the memory type. 9276 // Intrinsics, however, always get an explicit alignment, set to the 9277 // alignment of the MMO. 9278 Alignment = 1; 9279 } 9280 9281 // Create the new updating load/store node. 9282 // First, create an SDVTList for the new updating node's results. 9283 EVT Tys[6]; 9284 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 9285 unsigned n; 9286 for (n = 0; n < NumResultVecs; ++n) 9287 Tys[n] = AlignedVecTy; 9288 Tys[n++] = MVT::i32; 9289 Tys[n] = MVT::Other; 9290 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 9291 9292 // Then, gather the new node's operands. 9293 SmallVector<SDValue, 8> Ops; 9294 Ops.push_back(N->getOperand(0)); // incoming chain 9295 Ops.push_back(N->getOperand(AddrOpIdx)); 9296 Ops.push_back(Inc); 9297 9298 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 9299 // Try to match the intrinsic's signature 9300 Ops.push_back(StN->getValue()); 9301 } else { 9302 // Loads (and of course intrinsics) match the intrinsics' signature, 9303 // so just add all but the alignment operand. 9304 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 9305 Ops.push_back(N->getOperand(i)); 9306 } 9307 9308 // For all node types, the alignment operand is always the last one. 9309 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 9310 9311 // If this is a non-standard-aligned STORE, the penultimate operand is the 9312 // stored value. Bitcast it to the aligned type. 9313 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 9314 SDValue &StVal = Ops[Ops.size()-2]; 9315 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 9316 } 9317 9318 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 9319 Ops, AlignedVecTy, 9320 MemN->getMemOperand()); 9321 9322 // Update the uses. 9323 SmallVector<SDValue, 5> NewResults; 9324 for (unsigned i = 0; i < NumResultVecs; ++i) 9325 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9326 9327 // If this is an non-standard-aligned LOAD, the first result is the loaded 9328 // value. Bitcast it to the expected result type. 9329 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 9330 SDValue &LdVal = NewResults[0]; 9331 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 9332 } 9333 9334 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 9335 DCI.CombineTo(N, NewResults); 9336 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9337 9338 break; 9339 } 9340 return SDValue(); 9341 } 9342 9343 static SDValue PerformVLDCombine(SDNode *N, 9344 TargetLowering::DAGCombinerInfo &DCI) { 9345 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9346 return SDValue(); 9347 9348 return CombineBaseUpdate(N, DCI); 9349 } 9350 9351 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 9352 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 9353 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 9354 /// return true. 9355 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9356 SelectionDAG &DAG = DCI.DAG; 9357 EVT VT = N->getValueType(0); 9358 // vldN-dup instructions only support 64-bit vectors for N > 1. 9359 if (!VT.is64BitVector()) 9360 return false; 9361 9362 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 9363 SDNode *VLD = N->getOperand(0).getNode(); 9364 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 9365 return false; 9366 unsigned NumVecs = 0; 9367 unsigned NewOpc = 0; 9368 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 9369 if (IntNo == Intrinsic::arm_neon_vld2lane) { 9370 NumVecs = 2; 9371 NewOpc = ARMISD::VLD2DUP; 9372 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 9373 NumVecs = 3; 9374 NewOpc = ARMISD::VLD3DUP; 9375 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 9376 NumVecs = 4; 9377 NewOpc = ARMISD::VLD4DUP; 9378 } else { 9379 return false; 9380 } 9381 9382 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 9383 // numbers match the load. 9384 unsigned VLDLaneNo = 9385 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 9386 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9387 UI != UE; ++UI) { 9388 // Ignore uses of the chain result. 9389 if (UI.getUse().getResNo() == NumVecs) 9390 continue; 9391 SDNode *User = *UI; 9392 if (User->getOpcode() != ARMISD::VDUPLANE || 9393 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 9394 return false; 9395 } 9396 9397 // Create the vldN-dup node. 9398 EVT Tys[5]; 9399 unsigned n; 9400 for (n = 0; n < NumVecs; ++n) 9401 Tys[n] = VT; 9402 Tys[n] = MVT::Other; 9403 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 9404 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 9405 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 9406 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 9407 Ops, VLDMemInt->getMemoryVT(), 9408 VLDMemInt->getMemOperand()); 9409 9410 // Update the uses. 9411 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9412 UI != UE; ++UI) { 9413 unsigned ResNo = UI.getUse().getResNo(); 9414 // Ignore uses of the chain result. 9415 if (ResNo == NumVecs) 9416 continue; 9417 SDNode *User = *UI; 9418 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 9419 } 9420 9421 // Now the vldN-lane intrinsic is dead except for its chain result. 9422 // Update uses of the chain. 9423 std::vector<SDValue> VLDDupResults; 9424 for (unsigned n = 0; n < NumVecs; ++n) 9425 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 9426 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 9427 DCI.CombineTo(VLD, VLDDupResults); 9428 9429 return true; 9430 } 9431 9432 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 9433 /// ARMISD::VDUPLANE. 9434 static SDValue PerformVDUPLANECombine(SDNode *N, 9435 TargetLowering::DAGCombinerInfo &DCI) { 9436 SDValue Op = N->getOperand(0); 9437 9438 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 9439 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 9440 if (CombineVLDDUP(N, DCI)) 9441 return SDValue(N, 0); 9442 9443 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 9444 // redundant. Ignore bit_converts for now; element sizes are checked below. 9445 while (Op.getOpcode() == ISD::BITCAST) 9446 Op = Op.getOperand(0); 9447 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 9448 return SDValue(); 9449 9450 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 9451 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 9452 // The canonical VMOV for a zero vector uses a 32-bit element size. 9453 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9454 unsigned EltBits; 9455 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 9456 EltSize = 8; 9457 EVT VT = N->getValueType(0); 9458 if (EltSize > VT.getVectorElementType().getSizeInBits()) 9459 return SDValue(); 9460 9461 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 9462 } 9463 9464 static SDValue PerformLOADCombine(SDNode *N, 9465 TargetLowering::DAGCombinerInfo &DCI) { 9466 EVT VT = N->getValueType(0); 9467 9468 // If this is a legal vector load, try to combine it into a VLD1_UPD. 9469 if (ISD::isNormalLoad(N) && VT.isVector() && 9470 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9471 return CombineBaseUpdate(N, DCI); 9472 9473 return SDValue(); 9474 } 9475 9476 /// PerformSTORECombine - Target-specific dag combine xforms for 9477 /// ISD::STORE. 9478 static SDValue PerformSTORECombine(SDNode *N, 9479 TargetLowering::DAGCombinerInfo &DCI) { 9480 StoreSDNode *St = cast<StoreSDNode>(N); 9481 if (St->isVolatile()) 9482 return SDValue(); 9483 9484 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 9485 // pack all of the elements in one place. Next, store to memory in fewer 9486 // chunks. 9487 SDValue StVal = St->getValue(); 9488 EVT VT = StVal.getValueType(); 9489 if (St->isTruncatingStore() && VT.isVector()) { 9490 SelectionDAG &DAG = DCI.DAG; 9491 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9492 EVT StVT = St->getMemoryVT(); 9493 unsigned NumElems = VT.getVectorNumElements(); 9494 assert(StVT != VT && "Cannot truncate to the same type"); 9495 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 9496 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 9497 9498 // From, To sizes and ElemCount must be pow of two 9499 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 9500 9501 // We are going to use the original vector elt for storing. 9502 // Accumulated smaller vector elements must be a multiple of the store size. 9503 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 9504 9505 unsigned SizeRatio = FromEltSz / ToEltSz; 9506 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 9507 9508 // Create a type on which we perform the shuffle. 9509 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 9510 NumElems*SizeRatio); 9511 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 9512 9513 SDLoc DL(St); 9514 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 9515 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 9516 for (unsigned i = 0; i < NumElems; ++i) 9517 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 9518 ? (i + 1) * SizeRatio - 1 9519 : i * SizeRatio; 9520 9521 // Can't shuffle using an illegal type. 9522 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 9523 9524 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 9525 DAG.getUNDEF(WideVec.getValueType()), 9526 ShuffleVec.data()); 9527 // At this point all of the data is stored at the bottom of the 9528 // register. We now need to save it to mem. 9529 9530 // Find the largest store unit 9531 MVT StoreType = MVT::i8; 9532 for (MVT Tp : MVT::integer_valuetypes()) { 9533 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 9534 StoreType = Tp; 9535 } 9536 // Didn't find a legal store type. 9537 if (!TLI.isTypeLegal(StoreType)) 9538 return SDValue(); 9539 9540 // Bitcast the original vector into a vector of store-size units 9541 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 9542 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 9543 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 9544 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 9545 SmallVector<SDValue, 8> Chains; 9546 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 9547 TLI.getPointerTy(DAG.getDataLayout())); 9548 SDValue BasePtr = St->getBasePtr(); 9549 9550 // Perform one or more big stores into memory. 9551 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 9552 for (unsigned I = 0; I < E; I++) { 9553 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 9554 StoreType, ShuffWide, 9555 DAG.getIntPtrConstant(I, DL)); 9556 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 9557 St->getPointerInfo(), St->isVolatile(), 9558 St->isNonTemporal(), St->getAlignment()); 9559 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 9560 Increment); 9561 Chains.push_back(Ch); 9562 } 9563 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 9564 } 9565 9566 if (!ISD::isNormalStore(St)) 9567 return SDValue(); 9568 9569 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 9570 // ARM stores of arguments in the same cache line. 9571 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 9572 StVal.getNode()->hasOneUse()) { 9573 SelectionDAG &DAG = DCI.DAG; 9574 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9575 SDLoc DL(St); 9576 SDValue BasePtr = St->getBasePtr(); 9577 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 9578 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 9579 BasePtr, St->getPointerInfo(), St->isVolatile(), 9580 St->isNonTemporal(), St->getAlignment()); 9581 9582 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9583 DAG.getConstant(4, DL, MVT::i32)); 9584 return DAG.getStore(NewST1.getValue(0), DL, 9585 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 9586 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 9587 St->isNonTemporal(), 9588 std::min(4U, St->getAlignment() / 2)); 9589 } 9590 9591 if (StVal.getValueType() == MVT::i64 && 9592 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9593 9594 // Bitcast an i64 store extracted from a vector to f64. 9595 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9596 SelectionDAG &DAG = DCI.DAG; 9597 SDLoc dl(StVal); 9598 SDValue IntVec = StVal.getOperand(0); 9599 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9600 IntVec.getValueType().getVectorNumElements()); 9601 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 9602 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 9603 Vec, StVal.getOperand(1)); 9604 dl = SDLoc(N); 9605 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 9606 // Make the DAGCombiner fold the bitcasts. 9607 DCI.AddToWorklist(Vec.getNode()); 9608 DCI.AddToWorklist(ExtElt.getNode()); 9609 DCI.AddToWorklist(V.getNode()); 9610 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 9611 St->getPointerInfo(), St->isVolatile(), 9612 St->isNonTemporal(), St->getAlignment(), 9613 St->getAAInfo()); 9614 } 9615 9616 // If this is a legal vector store, try to combine it into a VST1_UPD. 9617 if (ISD::isNormalStore(N) && VT.isVector() && 9618 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9619 return CombineBaseUpdate(N, DCI); 9620 9621 return SDValue(); 9622 } 9623 9624 // isConstVecPow2 - Return true if each vector element is a power of 2, all 9625 // elements are the same constant, C, and Log2(C) ranges from 1 to 32. 9626 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C) 9627 { 9628 integerPart cN; 9629 integerPart c0 = 0; 9630 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements(); 9631 I != E; I++) { 9632 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I)); 9633 if (!C) 9634 return false; 9635 9636 bool isExact; 9637 APFloat APF = C->getValueAPF(); 9638 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact) 9639 != APFloat::opOK || !isExact) 9640 return false; 9641 9642 c0 = (I == 0) ? cN : c0; 9643 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32) 9644 return false; 9645 } 9646 C = c0; 9647 return true; 9648 } 9649 9650 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 9651 /// can replace combinations of VMUL and VCVT (floating-point to integer) 9652 /// when the VMUL has a constant operand that is a power of 2. 9653 /// 9654 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 9655 /// vmul.f32 d16, d17, d16 9656 /// vcvt.s32.f32 d16, d16 9657 /// becomes: 9658 /// vcvt.s32.f32 d16, d16, #3 9659 static SDValue PerformVCVTCombine(SDNode *N, 9660 TargetLowering::DAGCombinerInfo &DCI, 9661 const ARMSubtarget *Subtarget) { 9662 SelectionDAG &DAG = DCI.DAG; 9663 SDValue Op = N->getOperand(0); 9664 9665 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() || 9666 Op.getOpcode() != ISD::FMUL) 9667 return SDValue(); 9668 9669 uint64_t C; 9670 SDValue N0 = Op->getOperand(0); 9671 SDValue ConstVec = Op->getOperand(1); 9672 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 9673 9674 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR || 9675 !isConstVecPow2(ConstVec, isSigned, C)) 9676 return SDValue(); 9677 9678 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 9679 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 9680 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 9681 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 || 9682 NumLanes > 4) { 9683 // These instructions only exist converting from f32 to i32. We can handle 9684 // smaller integers by generating an extra truncate, but larger ones would 9685 // be lossy. We also can't handle more then 4 lanes, since these intructions 9686 // only support v2i32/v4i32 types. 9687 return SDValue(); 9688 } 9689 9690 SDLoc dl(N); 9691 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 9692 Intrinsic::arm_neon_vcvtfp2fxu; 9693 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 9694 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 9695 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 9696 N0, 9697 DAG.getConstant(Log2_64(C), dl, MVT::i32)); 9698 9699 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits()) 9700 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 9701 9702 return FixConv; 9703 } 9704 9705 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 9706 /// can replace combinations of VCVT (integer to floating-point) and VDIV 9707 /// when the VDIV has a constant operand that is a power of 2. 9708 /// 9709 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 9710 /// vcvt.f32.s32 d16, d16 9711 /// vdiv.f32 d16, d17, d16 9712 /// becomes: 9713 /// vcvt.f32.s32 d16, d16, #3 9714 static SDValue PerformVDIVCombine(SDNode *N, 9715 TargetLowering::DAGCombinerInfo &DCI, 9716 const ARMSubtarget *Subtarget) { 9717 SelectionDAG &DAG = DCI.DAG; 9718 SDValue Op = N->getOperand(0); 9719 unsigned OpOpcode = Op.getNode()->getOpcode(); 9720 9721 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() || 9722 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 9723 return SDValue(); 9724 9725 uint64_t C; 9726 SDValue ConstVec = N->getOperand(1); 9727 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 9728 9729 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR || 9730 !isConstVecPow2(ConstVec, isSigned, C)) 9731 return SDValue(); 9732 9733 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 9734 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 9735 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) { 9736 // These instructions only exist converting from i32 to f32. We can handle 9737 // smaller integers by generating an extra extend, but larger ones would 9738 // be lossy. 9739 return SDValue(); 9740 } 9741 9742 SDLoc dl(N); 9743 SDValue ConvInput = Op.getOperand(0); 9744 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 9745 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits()) 9746 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9747 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 9748 ConvInput); 9749 9750 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 9751 Intrinsic::arm_neon_vcvtfxu2fp; 9752 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 9753 Op.getValueType(), 9754 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 9755 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32)); 9756 } 9757 9758 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 9759 /// operand of a vector shift operation, where all the elements of the 9760 /// build_vector must have the same constant integer value. 9761 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 9762 // Ignore bit_converts. 9763 while (Op.getOpcode() == ISD::BITCAST) 9764 Op = Op.getOperand(0); 9765 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9766 APInt SplatBits, SplatUndef; 9767 unsigned SplatBitSize; 9768 bool HasAnyUndefs; 9769 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 9770 HasAnyUndefs, ElementBits) || 9771 SplatBitSize > ElementBits) 9772 return false; 9773 Cnt = SplatBits.getSExtValue(); 9774 return true; 9775 } 9776 9777 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 9778 /// operand of a vector shift left operation. That value must be in the range: 9779 /// 0 <= Value < ElementBits for a left shift; or 9780 /// 0 <= Value <= ElementBits for a long left shift. 9781 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 9782 assert(VT.isVector() && "vector shift count is not a vector type"); 9783 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 9784 if (! getVShiftImm(Op, ElementBits, Cnt)) 9785 return false; 9786 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 9787 } 9788 9789 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 9790 /// operand of a vector shift right operation. For a shift opcode, the value 9791 /// is positive, but for an intrinsic the value count must be negative. The 9792 /// absolute value must be in the range: 9793 /// 1 <= |Value| <= ElementBits for a right shift; or 9794 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 9795 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 9796 int64_t &Cnt) { 9797 assert(VT.isVector() && "vector shift count is not a vector type"); 9798 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 9799 if (! getVShiftImm(Op, ElementBits, Cnt)) 9800 return false; 9801 if (!isIntrinsic) 9802 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 9803 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 9804 Cnt = -Cnt; 9805 return true; 9806 } 9807 return false; 9808 } 9809 9810 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 9811 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 9812 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9813 switch (IntNo) { 9814 default: 9815 // Don't do anything for most intrinsics. 9816 break; 9817 9818 case Intrinsic::arm_neon_vabds: 9819 if (!N->getValueType(0).isInteger()) 9820 return SDValue(); 9821 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0), 9822 N->getOperand(1), N->getOperand(2)); 9823 case Intrinsic::arm_neon_vabdu: 9824 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0), 9825 N->getOperand(1), N->getOperand(2)); 9826 9827 // Vector shifts: check for immediate versions and lower them. 9828 // Note: This is done during DAG combining instead of DAG legalizing because 9829 // the build_vectors for 64-bit vector element shift counts are generally 9830 // not legal, and it is hard to see their values after they get legalized to 9831 // loads from a constant pool. 9832 case Intrinsic::arm_neon_vshifts: 9833 case Intrinsic::arm_neon_vshiftu: 9834 case Intrinsic::arm_neon_vrshifts: 9835 case Intrinsic::arm_neon_vrshiftu: 9836 case Intrinsic::arm_neon_vrshiftn: 9837 case Intrinsic::arm_neon_vqshifts: 9838 case Intrinsic::arm_neon_vqshiftu: 9839 case Intrinsic::arm_neon_vqshiftsu: 9840 case Intrinsic::arm_neon_vqshiftns: 9841 case Intrinsic::arm_neon_vqshiftnu: 9842 case Intrinsic::arm_neon_vqshiftnsu: 9843 case Intrinsic::arm_neon_vqrshiftns: 9844 case Intrinsic::arm_neon_vqrshiftnu: 9845 case Intrinsic::arm_neon_vqrshiftnsu: { 9846 EVT VT = N->getOperand(1).getValueType(); 9847 int64_t Cnt; 9848 unsigned VShiftOpc = 0; 9849 9850 switch (IntNo) { 9851 case Intrinsic::arm_neon_vshifts: 9852 case Intrinsic::arm_neon_vshiftu: 9853 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 9854 VShiftOpc = ARMISD::VSHL; 9855 break; 9856 } 9857 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 9858 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 9859 ARMISD::VSHRs : ARMISD::VSHRu); 9860 break; 9861 } 9862 return SDValue(); 9863 9864 case Intrinsic::arm_neon_vrshifts: 9865 case Intrinsic::arm_neon_vrshiftu: 9866 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 9867 break; 9868 return SDValue(); 9869 9870 case Intrinsic::arm_neon_vqshifts: 9871 case Intrinsic::arm_neon_vqshiftu: 9872 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 9873 break; 9874 return SDValue(); 9875 9876 case Intrinsic::arm_neon_vqshiftsu: 9877 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 9878 break; 9879 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 9880 9881 case Intrinsic::arm_neon_vrshiftn: 9882 case Intrinsic::arm_neon_vqshiftns: 9883 case Intrinsic::arm_neon_vqshiftnu: 9884 case Intrinsic::arm_neon_vqshiftnsu: 9885 case Intrinsic::arm_neon_vqrshiftns: 9886 case Intrinsic::arm_neon_vqrshiftnu: 9887 case Intrinsic::arm_neon_vqrshiftnsu: 9888 // Narrowing shifts require an immediate right shift. 9889 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 9890 break; 9891 llvm_unreachable("invalid shift count for narrowing vector shift " 9892 "intrinsic"); 9893 9894 default: 9895 llvm_unreachable("unhandled vector shift"); 9896 } 9897 9898 switch (IntNo) { 9899 case Intrinsic::arm_neon_vshifts: 9900 case Intrinsic::arm_neon_vshiftu: 9901 // Opcode already set above. 9902 break; 9903 case Intrinsic::arm_neon_vrshifts: 9904 VShiftOpc = ARMISD::VRSHRs; break; 9905 case Intrinsic::arm_neon_vrshiftu: 9906 VShiftOpc = ARMISD::VRSHRu; break; 9907 case Intrinsic::arm_neon_vrshiftn: 9908 VShiftOpc = ARMISD::VRSHRN; break; 9909 case Intrinsic::arm_neon_vqshifts: 9910 VShiftOpc = ARMISD::VQSHLs; break; 9911 case Intrinsic::arm_neon_vqshiftu: 9912 VShiftOpc = ARMISD::VQSHLu; break; 9913 case Intrinsic::arm_neon_vqshiftsu: 9914 VShiftOpc = ARMISD::VQSHLsu; break; 9915 case Intrinsic::arm_neon_vqshiftns: 9916 VShiftOpc = ARMISD::VQSHRNs; break; 9917 case Intrinsic::arm_neon_vqshiftnu: 9918 VShiftOpc = ARMISD::VQSHRNu; break; 9919 case Intrinsic::arm_neon_vqshiftnsu: 9920 VShiftOpc = ARMISD::VQSHRNsu; break; 9921 case Intrinsic::arm_neon_vqrshiftns: 9922 VShiftOpc = ARMISD::VQRSHRNs; break; 9923 case Intrinsic::arm_neon_vqrshiftnu: 9924 VShiftOpc = ARMISD::VQRSHRNu; break; 9925 case Intrinsic::arm_neon_vqrshiftnsu: 9926 VShiftOpc = ARMISD::VQRSHRNsu; break; 9927 } 9928 9929 SDLoc dl(N); 9930 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 9931 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 9932 } 9933 9934 case Intrinsic::arm_neon_vshiftins: { 9935 EVT VT = N->getOperand(1).getValueType(); 9936 int64_t Cnt; 9937 unsigned VShiftOpc = 0; 9938 9939 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 9940 VShiftOpc = ARMISD::VSLI; 9941 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 9942 VShiftOpc = ARMISD::VSRI; 9943 else { 9944 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 9945 } 9946 9947 SDLoc dl(N); 9948 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 9949 N->getOperand(1), N->getOperand(2), 9950 DAG.getConstant(Cnt, dl, MVT::i32)); 9951 } 9952 9953 case Intrinsic::arm_neon_vqrshifts: 9954 case Intrinsic::arm_neon_vqrshiftu: 9955 // No immediate versions of these to check for. 9956 break; 9957 } 9958 9959 return SDValue(); 9960 } 9961 9962 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 9963 /// lowers them. As with the vector shift intrinsics, this is done during DAG 9964 /// combining instead of DAG legalizing because the build_vectors for 64-bit 9965 /// vector element shift counts are generally not legal, and it is hard to see 9966 /// their values after they get legalized to loads from a constant pool. 9967 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 9968 const ARMSubtarget *ST) { 9969 EVT VT = N->getValueType(0); 9970 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 9971 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 9972 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 9973 SDValue N1 = N->getOperand(1); 9974 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 9975 SDValue N0 = N->getOperand(0); 9976 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 9977 DAG.MaskedValueIsZero(N0.getOperand(0), 9978 APInt::getHighBitsSet(32, 16))) 9979 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 9980 } 9981 } 9982 9983 // Nothing to be done for scalar shifts. 9984 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9985 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 9986 return SDValue(); 9987 9988 assert(ST->hasNEON() && "unexpected vector shift"); 9989 int64_t Cnt; 9990 9991 switch (N->getOpcode()) { 9992 default: llvm_unreachable("unexpected shift opcode"); 9993 9994 case ISD::SHL: 9995 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 9996 SDLoc dl(N); 9997 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 9998 DAG.getConstant(Cnt, dl, MVT::i32)); 9999 } 10000 break; 10001 10002 case ISD::SRA: 10003 case ISD::SRL: 10004 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10005 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10006 ARMISD::VSHRs : ARMISD::VSHRu); 10007 SDLoc dl(N); 10008 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10009 DAG.getConstant(Cnt, dl, MVT::i32)); 10010 } 10011 } 10012 return SDValue(); 10013 } 10014 10015 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10016 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10017 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10018 const ARMSubtarget *ST) { 10019 SDValue N0 = N->getOperand(0); 10020 10021 // Check for sign- and zero-extensions of vector extract operations of 8- 10022 // and 16-bit vector elements. NEON supports these directly. They are 10023 // handled during DAG combining because type legalization will promote them 10024 // to 32-bit types and it is messy to recognize the operations after that. 10025 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10026 SDValue Vec = N0.getOperand(0); 10027 SDValue Lane = N0.getOperand(1); 10028 EVT VT = N->getValueType(0); 10029 EVT EltVT = N0.getValueType(); 10030 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10031 10032 if (VT == MVT::i32 && 10033 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10034 TLI.isTypeLegal(Vec.getValueType()) && 10035 isa<ConstantSDNode>(Lane)) { 10036 10037 unsigned Opc = 0; 10038 switch (N->getOpcode()) { 10039 default: llvm_unreachable("unexpected opcode"); 10040 case ISD::SIGN_EXTEND: 10041 Opc = ARMISD::VGETLANEs; 10042 break; 10043 case ISD::ZERO_EXTEND: 10044 case ISD::ANY_EXTEND: 10045 Opc = ARMISD::VGETLANEu; 10046 break; 10047 } 10048 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10049 } 10050 } 10051 10052 return SDValue(); 10053 } 10054 10055 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC 10056 /// to match f32 max/min patterns to use NEON vmax/vmin instructions. 10057 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG, 10058 const ARMSubtarget *ST) { 10059 // If the target supports NEON, try to use vmax/vmin instructions for f32 10060 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set, 10061 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is 10062 // a NaN; only do the transformation when it matches that behavior. 10063 10064 // For now only do this when using NEON for FP operations; if using VFP, it 10065 // is not obvious that the benefit outweighs the cost of switching to the 10066 // NEON pipeline. 10067 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() || 10068 N->getValueType(0) != MVT::f32) 10069 return SDValue(); 10070 10071 SDValue CondLHS = N->getOperand(0); 10072 SDValue CondRHS = N->getOperand(1); 10073 SDValue LHS = N->getOperand(2); 10074 SDValue RHS = N->getOperand(3); 10075 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 10076 10077 unsigned Opcode = 0; 10078 bool IsReversed; 10079 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) { 10080 IsReversed = false; // x CC y ? x : y 10081 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) { 10082 IsReversed = true ; // x CC y ? y : x 10083 } else { 10084 return SDValue(); 10085 } 10086 10087 bool IsUnordered; 10088 switch (CC) { 10089 default: break; 10090 case ISD::SETOLT: 10091 case ISD::SETOLE: 10092 case ISD::SETLT: 10093 case ISD::SETLE: 10094 case ISD::SETULT: 10095 case ISD::SETULE: 10096 // If LHS is NaN, an ordered comparison will be false and the result will 10097 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS 10098 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN. 10099 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE); 10100 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS)) 10101 break; 10102 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin 10103 // will return -0, so vmin can only be used for unsafe math or if one of 10104 // the operands is known to be nonzero. 10105 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) && 10106 !DAG.getTarget().Options.UnsafeFPMath && 10107 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 10108 break; 10109 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN; 10110 break; 10111 10112 case ISD::SETOGT: 10113 case ISD::SETOGE: 10114 case ISD::SETGT: 10115 case ISD::SETGE: 10116 case ISD::SETUGT: 10117 case ISD::SETUGE: 10118 // If LHS is NaN, an ordered comparison will be false and the result will 10119 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS 10120 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN. 10121 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE); 10122 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS)) 10123 break; 10124 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax 10125 // will return +0, so vmax can only be used for unsafe math or if one of 10126 // the operands is known to be nonzero. 10127 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) && 10128 !DAG.getTarget().Options.UnsafeFPMath && 10129 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 10130 break; 10131 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX; 10132 break; 10133 } 10134 10135 if (!Opcode) 10136 return SDValue(); 10137 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS); 10138 } 10139 10140 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10141 SDValue 10142 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10143 SDValue Cmp = N->getOperand(4); 10144 if (Cmp.getOpcode() != ARMISD::CMPZ) 10145 // Only looking at EQ and NE cases. 10146 return SDValue(); 10147 10148 EVT VT = N->getValueType(0); 10149 SDLoc dl(N); 10150 SDValue LHS = Cmp.getOperand(0); 10151 SDValue RHS = Cmp.getOperand(1); 10152 SDValue FalseVal = N->getOperand(0); 10153 SDValue TrueVal = N->getOperand(1); 10154 SDValue ARMcc = N->getOperand(2); 10155 ARMCC::CondCodes CC = 10156 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10157 10158 // Simplify 10159 // mov r1, r0 10160 // cmp r1, x 10161 // mov r0, y 10162 // moveq r0, x 10163 // to 10164 // cmp r0, x 10165 // movne r0, y 10166 // 10167 // mov r1, r0 10168 // cmp r1, x 10169 // mov r0, x 10170 // movne r0, y 10171 // to 10172 // cmp r0, x 10173 // movne r0, y 10174 /// FIXME: Turn this into a target neutral optimization? 10175 SDValue Res; 10176 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 10177 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 10178 N->getOperand(3), Cmp); 10179 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 10180 SDValue ARMcc; 10181 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 10182 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 10183 N->getOperand(3), NewCmp); 10184 } 10185 10186 if (Res.getNode()) { 10187 APInt KnownZero, KnownOne; 10188 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 10189 // Capture demanded bits information that would be otherwise lost. 10190 if (KnownZero == 0xfffffffe) 10191 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10192 DAG.getValueType(MVT::i1)); 10193 else if (KnownZero == 0xffffff00) 10194 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10195 DAG.getValueType(MVT::i8)); 10196 else if (KnownZero == 0xffff0000) 10197 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10198 DAG.getValueType(MVT::i16)); 10199 } 10200 10201 return Res; 10202 } 10203 10204 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 10205 DAGCombinerInfo &DCI) const { 10206 switch (N->getOpcode()) { 10207 default: break; 10208 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 10209 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 10210 case ISD::SUB: return PerformSUBCombine(N, DCI); 10211 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 10212 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 10213 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 10214 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 10215 case ARMISD::BFI: return PerformBFICombine(N, DCI); 10216 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 10217 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 10218 case ISD::STORE: return PerformSTORECombine(N, DCI); 10219 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 10220 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 10221 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 10222 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 10223 case ISD::FP_TO_SINT: 10224 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget); 10225 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget); 10226 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 10227 case ISD::SHL: 10228 case ISD::SRA: 10229 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 10230 case ISD::SIGN_EXTEND: 10231 case ISD::ZERO_EXTEND: 10232 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 10233 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget); 10234 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 10235 case ISD::LOAD: return PerformLOADCombine(N, DCI); 10236 case ARMISD::VLD2DUP: 10237 case ARMISD::VLD3DUP: 10238 case ARMISD::VLD4DUP: 10239 return PerformVLDCombine(N, DCI); 10240 case ARMISD::BUILD_VECTOR: 10241 return PerformARMBUILD_VECTORCombine(N, DCI); 10242 case ISD::INTRINSIC_VOID: 10243 case ISD::INTRINSIC_W_CHAIN: 10244 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10245 case Intrinsic::arm_neon_vld1: 10246 case Intrinsic::arm_neon_vld2: 10247 case Intrinsic::arm_neon_vld3: 10248 case Intrinsic::arm_neon_vld4: 10249 case Intrinsic::arm_neon_vld2lane: 10250 case Intrinsic::arm_neon_vld3lane: 10251 case Intrinsic::arm_neon_vld4lane: 10252 case Intrinsic::arm_neon_vst1: 10253 case Intrinsic::arm_neon_vst2: 10254 case Intrinsic::arm_neon_vst3: 10255 case Intrinsic::arm_neon_vst4: 10256 case Intrinsic::arm_neon_vst2lane: 10257 case Intrinsic::arm_neon_vst3lane: 10258 case Intrinsic::arm_neon_vst4lane: 10259 return PerformVLDCombine(N, DCI); 10260 default: break; 10261 } 10262 break; 10263 } 10264 return SDValue(); 10265 } 10266 10267 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 10268 EVT VT) const { 10269 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 10270 } 10271 10272 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 10273 unsigned, 10274 unsigned, 10275 bool *Fast) const { 10276 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 10277 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 10278 10279 switch (VT.getSimpleVT().SimpleTy) { 10280 default: 10281 return false; 10282 case MVT::i8: 10283 case MVT::i16: 10284 case MVT::i32: { 10285 // Unaligned access can use (for example) LRDB, LRDH, LDR 10286 if (AllowsUnaligned) { 10287 if (Fast) 10288 *Fast = Subtarget->hasV7Ops(); 10289 return true; 10290 } 10291 return false; 10292 } 10293 case MVT::f64: 10294 case MVT::v2f64: { 10295 // For any little-endian targets with neon, we can support unaligned ld/st 10296 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 10297 // A big-endian target may also explicitly support unaligned accesses 10298 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 10299 if (Fast) 10300 *Fast = true; 10301 return true; 10302 } 10303 return false; 10304 } 10305 } 10306 } 10307 10308 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 10309 unsigned AlignCheck) { 10310 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 10311 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 10312 } 10313 10314 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 10315 unsigned DstAlign, unsigned SrcAlign, 10316 bool IsMemset, bool ZeroMemset, 10317 bool MemcpyStrSrc, 10318 MachineFunction &MF) const { 10319 const Function *F = MF.getFunction(); 10320 10321 // See if we can use NEON instructions for this... 10322 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 10323 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 10324 bool Fast; 10325 if (Size >= 16 && 10326 (memOpAlign(SrcAlign, DstAlign, 16) || 10327 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 10328 return MVT::v2f64; 10329 } else if (Size >= 8 && 10330 (memOpAlign(SrcAlign, DstAlign, 8) || 10331 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 10332 Fast))) { 10333 return MVT::f64; 10334 } 10335 } 10336 10337 // Lowering to i32/i16 if the size permits. 10338 if (Size >= 4) 10339 return MVT::i32; 10340 else if (Size >= 2) 10341 return MVT::i16; 10342 10343 // Let the target-independent logic figure it out. 10344 return MVT::Other; 10345 } 10346 10347 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10348 if (Val.getOpcode() != ISD::LOAD) 10349 return false; 10350 10351 EVT VT1 = Val.getValueType(); 10352 if (!VT1.isSimple() || !VT1.isInteger() || 10353 !VT2.isSimple() || !VT2.isInteger()) 10354 return false; 10355 10356 switch (VT1.getSimpleVT().SimpleTy) { 10357 default: break; 10358 case MVT::i1: 10359 case MVT::i8: 10360 case MVT::i16: 10361 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 10362 return true; 10363 } 10364 10365 return false; 10366 } 10367 10368 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 10369 EVT VT = ExtVal.getValueType(); 10370 10371 if (!isTypeLegal(VT)) 10372 return false; 10373 10374 // Don't create a loadext if we can fold the extension into a wide/long 10375 // instruction. 10376 // If there's more than one user instruction, the loadext is desirable no 10377 // matter what. There can be two uses by the same instruction. 10378 if (ExtVal->use_empty() || 10379 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 10380 return true; 10381 10382 SDNode *U = *ExtVal->use_begin(); 10383 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 10384 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 10385 return false; 10386 10387 return true; 10388 } 10389 10390 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 10391 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10392 return false; 10393 10394 if (!isTypeLegal(EVT::getEVT(Ty1))) 10395 return false; 10396 10397 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 10398 10399 // Assuming the caller doesn't have a zeroext or signext return parameter, 10400 // truncation all the way down to i1 is valid. 10401 return true; 10402 } 10403 10404 10405 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 10406 if (V < 0) 10407 return false; 10408 10409 unsigned Scale = 1; 10410 switch (VT.getSimpleVT().SimpleTy) { 10411 default: return false; 10412 case MVT::i1: 10413 case MVT::i8: 10414 // Scale == 1; 10415 break; 10416 case MVT::i16: 10417 // Scale == 2; 10418 Scale = 2; 10419 break; 10420 case MVT::i32: 10421 // Scale == 4; 10422 Scale = 4; 10423 break; 10424 } 10425 10426 if ((V & (Scale - 1)) != 0) 10427 return false; 10428 V /= Scale; 10429 return V == (V & ((1LL << 5) - 1)); 10430 } 10431 10432 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 10433 const ARMSubtarget *Subtarget) { 10434 bool isNeg = false; 10435 if (V < 0) { 10436 isNeg = true; 10437 V = - V; 10438 } 10439 10440 switch (VT.getSimpleVT().SimpleTy) { 10441 default: return false; 10442 case MVT::i1: 10443 case MVT::i8: 10444 case MVT::i16: 10445 case MVT::i32: 10446 // + imm12 or - imm8 10447 if (isNeg) 10448 return V == (V & ((1LL << 8) - 1)); 10449 return V == (V & ((1LL << 12) - 1)); 10450 case MVT::f32: 10451 case MVT::f64: 10452 // Same as ARM mode. FIXME: NEON? 10453 if (!Subtarget->hasVFP2()) 10454 return false; 10455 if ((V & 3) != 0) 10456 return false; 10457 V >>= 2; 10458 return V == (V & ((1LL << 8) - 1)); 10459 } 10460 } 10461 10462 /// isLegalAddressImmediate - Return true if the integer value can be used 10463 /// as the offset of the target addressing mode for load / store of the 10464 /// given type. 10465 static bool isLegalAddressImmediate(int64_t V, EVT VT, 10466 const ARMSubtarget *Subtarget) { 10467 if (V == 0) 10468 return true; 10469 10470 if (!VT.isSimple()) 10471 return false; 10472 10473 if (Subtarget->isThumb1Only()) 10474 return isLegalT1AddressImmediate(V, VT); 10475 else if (Subtarget->isThumb2()) 10476 return isLegalT2AddressImmediate(V, VT, Subtarget); 10477 10478 // ARM mode. 10479 if (V < 0) 10480 V = - V; 10481 switch (VT.getSimpleVT().SimpleTy) { 10482 default: return false; 10483 case MVT::i1: 10484 case MVT::i8: 10485 case MVT::i32: 10486 // +- imm12 10487 return V == (V & ((1LL << 12) - 1)); 10488 case MVT::i16: 10489 // +- imm8 10490 return V == (V & ((1LL << 8) - 1)); 10491 case MVT::f32: 10492 case MVT::f64: 10493 if (!Subtarget->hasVFP2()) // FIXME: NEON? 10494 return false; 10495 if ((V & 3) != 0) 10496 return false; 10497 V >>= 2; 10498 return V == (V & ((1LL << 8) - 1)); 10499 } 10500 } 10501 10502 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 10503 EVT VT) const { 10504 int Scale = AM.Scale; 10505 if (Scale < 0) 10506 return false; 10507 10508 switch (VT.getSimpleVT().SimpleTy) { 10509 default: return false; 10510 case MVT::i1: 10511 case MVT::i8: 10512 case MVT::i16: 10513 case MVT::i32: 10514 if (Scale == 1) 10515 return true; 10516 // r + r << imm 10517 Scale = Scale & ~1; 10518 return Scale == 2 || Scale == 4 || Scale == 8; 10519 case MVT::i64: 10520 // r + r 10521 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 10522 return true; 10523 return false; 10524 case MVT::isVoid: 10525 // Note, we allow "void" uses (basically, uses that aren't loads or 10526 // stores), because arm allows folding a scale into many arithmetic 10527 // operations. This should be made more precise and revisited later. 10528 10529 // Allow r << imm, but the imm has to be a multiple of two. 10530 if (Scale & 1) return false; 10531 return isPowerOf2_32(Scale); 10532 } 10533 } 10534 10535 /// isLegalAddressingMode - Return true if the addressing mode represented 10536 /// by AM is legal for this target, for a load/store of the specified type. 10537 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 10538 const AddrMode &AM, Type *Ty, 10539 unsigned AS) const { 10540 EVT VT = getValueType(DL, Ty, true); 10541 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 10542 return false; 10543 10544 // Can never fold addr of global into load/store. 10545 if (AM.BaseGV) 10546 return false; 10547 10548 switch (AM.Scale) { 10549 case 0: // no scale reg, must be "r+i" or "r", or "i". 10550 break; 10551 case 1: 10552 if (Subtarget->isThumb1Only()) 10553 return false; 10554 // FALL THROUGH. 10555 default: 10556 // ARM doesn't support any R+R*scale+imm addr modes. 10557 if (AM.BaseOffs) 10558 return false; 10559 10560 if (!VT.isSimple()) 10561 return false; 10562 10563 if (Subtarget->isThumb2()) 10564 return isLegalT2ScaledAddressingMode(AM, VT); 10565 10566 int Scale = AM.Scale; 10567 switch (VT.getSimpleVT().SimpleTy) { 10568 default: return false; 10569 case MVT::i1: 10570 case MVT::i8: 10571 case MVT::i32: 10572 if (Scale < 0) Scale = -Scale; 10573 if (Scale == 1) 10574 return true; 10575 // r + r << imm 10576 return isPowerOf2_32(Scale & ~1); 10577 case MVT::i16: 10578 case MVT::i64: 10579 // r + r 10580 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 10581 return true; 10582 return false; 10583 10584 case MVT::isVoid: 10585 // Note, we allow "void" uses (basically, uses that aren't loads or 10586 // stores), because arm allows folding a scale into many arithmetic 10587 // operations. This should be made more precise and revisited later. 10588 10589 // Allow r << imm, but the imm has to be a multiple of two. 10590 if (Scale & 1) return false; 10591 return isPowerOf2_32(Scale); 10592 } 10593 } 10594 return true; 10595 } 10596 10597 /// isLegalICmpImmediate - Return true if the specified immediate is legal 10598 /// icmp immediate, that is the target has icmp instructions which can compare 10599 /// a register against the immediate without having to materialize the 10600 /// immediate into a register. 10601 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 10602 // Thumb2 and ARM modes can use cmn for negative immediates. 10603 if (!Subtarget->isThumb()) 10604 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 10605 if (Subtarget->isThumb2()) 10606 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 10607 // Thumb1 doesn't have cmn, and only 8-bit immediates. 10608 return Imm >= 0 && Imm <= 255; 10609 } 10610 10611 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 10612 /// *or sub* immediate, that is the target has add or sub instructions which can 10613 /// add a register with the immediate without having to materialize the 10614 /// immediate into a register. 10615 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 10616 // Same encoding for add/sub, just flip the sign. 10617 int64_t AbsImm = std::abs(Imm); 10618 if (!Subtarget->isThumb()) 10619 return ARM_AM::getSOImmVal(AbsImm) != -1; 10620 if (Subtarget->isThumb2()) 10621 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 10622 // Thumb1 only has 8-bit unsigned immediate. 10623 return AbsImm >= 0 && AbsImm <= 255; 10624 } 10625 10626 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 10627 bool isSEXTLoad, SDValue &Base, 10628 SDValue &Offset, bool &isInc, 10629 SelectionDAG &DAG) { 10630 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 10631 return false; 10632 10633 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 10634 // AddressingMode 3 10635 Base = Ptr->getOperand(0); 10636 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 10637 int RHSC = (int)RHS->getZExtValue(); 10638 if (RHSC < 0 && RHSC > -256) { 10639 assert(Ptr->getOpcode() == ISD::ADD); 10640 isInc = false; 10641 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 10642 return true; 10643 } 10644 } 10645 isInc = (Ptr->getOpcode() == ISD::ADD); 10646 Offset = Ptr->getOperand(1); 10647 return true; 10648 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 10649 // AddressingMode 2 10650 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 10651 int RHSC = (int)RHS->getZExtValue(); 10652 if (RHSC < 0 && RHSC > -0x1000) { 10653 assert(Ptr->getOpcode() == ISD::ADD); 10654 isInc = false; 10655 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 10656 Base = Ptr->getOperand(0); 10657 return true; 10658 } 10659 } 10660 10661 if (Ptr->getOpcode() == ISD::ADD) { 10662 isInc = true; 10663 ARM_AM::ShiftOpc ShOpcVal= 10664 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 10665 if (ShOpcVal != ARM_AM::no_shift) { 10666 Base = Ptr->getOperand(1); 10667 Offset = Ptr->getOperand(0); 10668 } else { 10669 Base = Ptr->getOperand(0); 10670 Offset = Ptr->getOperand(1); 10671 } 10672 return true; 10673 } 10674 10675 isInc = (Ptr->getOpcode() == ISD::ADD); 10676 Base = Ptr->getOperand(0); 10677 Offset = Ptr->getOperand(1); 10678 return true; 10679 } 10680 10681 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 10682 return false; 10683 } 10684 10685 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 10686 bool isSEXTLoad, SDValue &Base, 10687 SDValue &Offset, bool &isInc, 10688 SelectionDAG &DAG) { 10689 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 10690 return false; 10691 10692 Base = Ptr->getOperand(0); 10693 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 10694 int RHSC = (int)RHS->getZExtValue(); 10695 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 10696 assert(Ptr->getOpcode() == ISD::ADD); 10697 isInc = false; 10698 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 10699 return true; 10700 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 10701 isInc = Ptr->getOpcode() == ISD::ADD; 10702 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 10703 return true; 10704 } 10705 } 10706 10707 return false; 10708 } 10709 10710 /// getPreIndexedAddressParts - returns true by value, base pointer and 10711 /// offset pointer and addressing mode by reference if the node's address 10712 /// can be legally represented as pre-indexed load / store address. 10713 bool 10714 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 10715 SDValue &Offset, 10716 ISD::MemIndexedMode &AM, 10717 SelectionDAG &DAG) const { 10718 if (Subtarget->isThumb1Only()) 10719 return false; 10720 10721 EVT VT; 10722 SDValue Ptr; 10723 bool isSEXTLoad = false; 10724 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10725 Ptr = LD->getBasePtr(); 10726 VT = LD->getMemoryVT(); 10727 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 10728 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10729 Ptr = ST->getBasePtr(); 10730 VT = ST->getMemoryVT(); 10731 } else 10732 return false; 10733 10734 bool isInc; 10735 bool isLegal = false; 10736 if (Subtarget->isThumb2()) 10737 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 10738 Offset, isInc, DAG); 10739 else 10740 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 10741 Offset, isInc, DAG); 10742 if (!isLegal) 10743 return false; 10744 10745 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 10746 return true; 10747 } 10748 10749 /// getPostIndexedAddressParts - returns true by value, base pointer and 10750 /// offset pointer and addressing mode by reference if this node can be 10751 /// combined with a load / store to form a post-indexed load / store. 10752 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 10753 SDValue &Base, 10754 SDValue &Offset, 10755 ISD::MemIndexedMode &AM, 10756 SelectionDAG &DAG) const { 10757 if (Subtarget->isThumb1Only()) 10758 return false; 10759 10760 EVT VT; 10761 SDValue Ptr; 10762 bool isSEXTLoad = false; 10763 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10764 VT = LD->getMemoryVT(); 10765 Ptr = LD->getBasePtr(); 10766 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 10767 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10768 VT = ST->getMemoryVT(); 10769 Ptr = ST->getBasePtr(); 10770 } else 10771 return false; 10772 10773 bool isInc; 10774 bool isLegal = false; 10775 if (Subtarget->isThumb2()) 10776 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 10777 isInc, DAG); 10778 else 10779 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 10780 isInc, DAG); 10781 if (!isLegal) 10782 return false; 10783 10784 if (Ptr != Base) { 10785 // Swap base ptr and offset to catch more post-index load / store when 10786 // it's legal. In Thumb2 mode, offset must be an immediate. 10787 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 10788 !Subtarget->isThumb2()) 10789 std::swap(Base, Offset); 10790 10791 // Post-indexed load / store update the base pointer. 10792 if (Ptr != Base) 10793 return false; 10794 } 10795 10796 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 10797 return true; 10798 } 10799 10800 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 10801 APInt &KnownZero, 10802 APInt &KnownOne, 10803 const SelectionDAG &DAG, 10804 unsigned Depth) const { 10805 unsigned BitWidth = KnownOne.getBitWidth(); 10806 KnownZero = KnownOne = APInt(BitWidth, 0); 10807 switch (Op.getOpcode()) { 10808 default: break; 10809 case ARMISD::ADDC: 10810 case ARMISD::ADDE: 10811 case ARMISD::SUBC: 10812 case ARMISD::SUBE: 10813 // These nodes' second result is a boolean 10814 if (Op.getResNo() == 0) 10815 break; 10816 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 10817 break; 10818 case ARMISD::CMOV: { 10819 // Bits are known zero/one if known on the LHS and RHS. 10820 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 10821 if (KnownZero == 0 && KnownOne == 0) return; 10822 10823 APInt KnownZeroRHS, KnownOneRHS; 10824 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 10825 KnownZero &= KnownZeroRHS; 10826 KnownOne &= KnownOneRHS; 10827 return; 10828 } 10829 case ISD::INTRINSIC_W_CHAIN: { 10830 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 10831 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 10832 switch (IntID) { 10833 default: return; 10834 case Intrinsic::arm_ldaex: 10835 case Intrinsic::arm_ldrex: { 10836 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 10837 unsigned MemBits = VT.getScalarType().getSizeInBits(); 10838 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 10839 return; 10840 } 10841 } 10842 } 10843 } 10844 } 10845 10846 //===----------------------------------------------------------------------===// 10847 // ARM Inline Assembly Support 10848 //===----------------------------------------------------------------------===// 10849 10850 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 10851 // Looking for "rev" which is V6+. 10852 if (!Subtarget->hasV6Ops()) 10853 return false; 10854 10855 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 10856 std::string AsmStr = IA->getAsmString(); 10857 SmallVector<StringRef, 4> AsmPieces; 10858 SplitString(AsmStr, AsmPieces, ";\n"); 10859 10860 switch (AsmPieces.size()) { 10861 default: return false; 10862 case 1: 10863 AsmStr = AsmPieces[0]; 10864 AsmPieces.clear(); 10865 SplitString(AsmStr, AsmPieces, " \t,"); 10866 10867 // rev $0, $1 10868 if (AsmPieces.size() == 3 && 10869 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 10870 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 10871 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 10872 if (Ty && Ty->getBitWidth() == 32) 10873 return IntrinsicLowering::LowerToByteSwap(CI); 10874 } 10875 break; 10876 } 10877 10878 return false; 10879 } 10880 10881 /// getConstraintType - Given a constraint letter, return the type of 10882 /// constraint it is for this target. 10883 ARMTargetLowering::ConstraintType 10884 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 10885 if (Constraint.size() == 1) { 10886 switch (Constraint[0]) { 10887 default: break; 10888 case 'l': return C_RegisterClass; 10889 case 'w': return C_RegisterClass; 10890 case 'h': return C_RegisterClass; 10891 case 'x': return C_RegisterClass; 10892 case 't': return C_RegisterClass; 10893 case 'j': return C_Other; // Constant for movw. 10894 // An address with a single base register. Due to the way we 10895 // currently handle addresses it is the same as an 'r' memory constraint. 10896 case 'Q': return C_Memory; 10897 } 10898 } else if (Constraint.size() == 2) { 10899 switch (Constraint[0]) { 10900 default: break; 10901 // All 'U+' constraints are addresses. 10902 case 'U': return C_Memory; 10903 } 10904 } 10905 return TargetLowering::getConstraintType(Constraint); 10906 } 10907 10908 /// Examine constraint type and operand type and determine a weight value. 10909 /// This object must already have been set up with the operand type 10910 /// and the current alternative constraint selected. 10911 TargetLowering::ConstraintWeight 10912 ARMTargetLowering::getSingleConstraintMatchWeight( 10913 AsmOperandInfo &info, const char *constraint) const { 10914 ConstraintWeight weight = CW_Invalid; 10915 Value *CallOperandVal = info.CallOperandVal; 10916 // If we don't have a value, we can't do a match, 10917 // but allow it at the lowest weight. 10918 if (!CallOperandVal) 10919 return CW_Default; 10920 Type *type = CallOperandVal->getType(); 10921 // Look at the constraint type. 10922 switch (*constraint) { 10923 default: 10924 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 10925 break; 10926 case 'l': 10927 if (type->isIntegerTy()) { 10928 if (Subtarget->isThumb()) 10929 weight = CW_SpecificReg; 10930 else 10931 weight = CW_Register; 10932 } 10933 break; 10934 case 'w': 10935 if (type->isFloatingPointTy()) 10936 weight = CW_Register; 10937 break; 10938 } 10939 return weight; 10940 } 10941 10942 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 10943 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 10944 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 10945 if (Constraint.size() == 1) { 10946 // GCC ARM Constraint Letters 10947 switch (Constraint[0]) { 10948 case 'l': // Low regs or general regs. 10949 if (Subtarget->isThumb()) 10950 return RCPair(0U, &ARM::tGPRRegClass); 10951 return RCPair(0U, &ARM::GPRRegClass); 10952 case 'h': // High regs or no regs. 10953 if (Subtarget->isThumb()) 10954 return RCPair(0U, &ARM::hGPRRegClass); 10955 break; 10956 case 'r': 10957 if (Subtarget->isThumb1Only()) 10958 return RCPair(0U, &ARM::tGPRRegClass); 10959 return RCPair(0U, &ARM::GPRRegClass); 10960 case 'w': 10961 if (VT == MVT::Other) 10962 break; 10963 if (VT == MVT::f32) 10964 return RCPair(0U, &ARM::SPRRegClass); 10965 if (VT.getSizeInBits() == 64) 10966 return RCPair(0U, &ARM::DPRRegClass); 10967 if (VT.getSizeInBits() == 128) 10968 return RCPair(0U, &ARM::QPRRegClass); 10969 break; 10970 case 'x': 10971 if (VT == MVT::Other) 10972 break; 10973 if (VT == MVT::f32) 10974 return RCPair(0U, &ARM::SPR_8RegClass); 10975 if (VT.getSizeInBits() == 64) 10976 return RCPair(0U, &ARM::DPR_8RegClass); 10977 if (VT.getSizeInBits() == 128) 10978 return RCPair(0U, &ARM::QPR_8RegClass); 10979 break; 10980 case 't': 10981 if (VT == MVT::f32) 10982 return RCPair(0U, &ARM::SPRRegClass); 10983 break; 10984 } 10985 } 10986 if (StringRef("{cc}").equals_lower(Constraint)) 10987 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 10988 10989 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10990 } 10991 10992 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 10993 /// vector. If it is invalid, don't add anything to Ops. 10994 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 10995 std::string &Constraint, 10996 std::vector<SDValue>&Ops, 10997 SelectionDAG &DAG) const { 10998 SDValue Result; 10999 11000 // Currently only support length 1 constraints. 11001 if (Constraint.length() != 1) return; 11002 11003 char ConstraintLetter = Constraint[0]; 11004 switch (ConstraintLetter) { 11005 default: break; 11006 case 'j': 11007 case 'I': case 'J': case 'K': case 'L': 11008 case 'M': case 'N': case 'O': 11009 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11010 if (!C) 11011 return; 11012 11013 int64_t CVal64 = C->getSExtValue(); 11014 int CVal = (int) CVal64; 11015 // None of these constraints allow values larger than 32 bits. Check 11016 // that the value fits in an int. 11017 if (CVal != CVal64) 11018 return; 11019 11020 switch (ConstraintLetter) { 11021 case 'j': 11022 // Constant suitable for movw, must be between 0 and 11023 // 65535. 11024 if (Subtarget->hasV6T2Ops()) 11025 if (CVal >= 0 && CVal <= 65535) 11026 break; 11027 return; 11028 case 'I': 11029 if (Subtarget->isThumb1Only()) { 11030 // This must be a constant between 0 and 255, for ADD 11031 // immediates. 11032 if (CVal >= 0 && CVal <= 255) 11033 break; 11034 } else if (Subtarget->isThumb2()) { 11035 // A constant that can be used as an immediate value in a 11036 // data-processing instruction. 11037 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11038 break; 11039 } else { 11040 // A constant that can be used as an immediate value in a 11041 // data-processing instruction. 11042 if (ARM_AM::getSOImmVal(CVal) != -1) 11043 break; 11044 } 11045 return; 11046 11047 case 'J': 11048 if (Subtarget->isThumb()) { // FIXME thumb2 11049 // This must be a constant between -255 and -1, for negated ADD 11050 // immediates. This can be used in GCC with an "n" modifier that 11051 // prints the negated value, for use with SUB instructions. It is 11052 // not useful otherwise but is implemented for compatibility. 11053 if (CVal >= -255 && CVal <= -1) 11054 break; 11055 } else { 11056 // This must be a constant between -4095 and 4095. It is not clear 11057 // what this constraint is intended for. Implemented for 11058 // compatibility with GCC. 11059 if (CVal >= -4095 && CVal <= 4095) 11060 break; 11061 } 11062 return; 11063 11064 case 'K': 11065 if (Subtarget->isThumb1Only()) { 11066 // A 32-bit value where only one byte has a nonzero value. Exclude 11067 // zero to match GCC. This constraint is used by GCC internally for 11068 // constants that can be loaded with a move/shift combination. 11069 // It is not useful otherwise but is implemented for compatibility. 11070 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11071 break; 11072 } else if (Subtarget->isThumb2()) { 11073 // A constant whose bitwise inverse can be used as an immediate 11074 // value in a data-processing instruction. This can be used in GCC 11075 // with a "B" modifier that prints the inverted value, for use with 11076 // BIC and MVN instructions. It is not useful otherwise but is 11077 // implemented for compatibility. 11078 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11079 break; 11080 } else { 11081 // A constant whose bitwise inverse can be used as an immediate 11082 // value in a data-processing instruction. This can be used in GCC 11083 // with a "B" modifier that prints the inverted value, for use with 11084 // BIC and MVN instructions. It is not useful otherwise but is 11085 // implemented for compatibility. 11086 if (ARM_AM::getSOImmVal(~CVal) != -1) 11087 break; 11088 } 11089 return; 11090 11091 case 'L': 11092 if (Subtarget->isThumb1Only()) { 11093 // This must be a constant between -7 and 7, 11094 // for 3-operand ADD/SUB immediate instructions. 11095 if (CVal >= -7 && CVal < 7) 11096 break; 11097 } else if (Subtarget->isThumb2()) { 11098 // A constant whose negation can be used as an immediate value in a 11099 // data-processing instruction. This can be used in GCC with an "n" 11100 // modifier that prints the negated value, for use with SUB 11101 // instructions. It is not useful otherwise but is implemented for 11102 // compatibility. 11103 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11104 break; 11105 } else { 11106 // A constant whose negation can be used as an immediate value in a 11107 // data-processing instruction. This can be used in GCC with an "n" 11108 // modifier that prints the negated value, for use with SUB 11109 // instructions. It is not useful otherwise but is implemented for 11110 // compatibility. 11111 if (ARM_AM::getSOImmVal(-CVal) != -1) 11112 break; 11113 } 11114 return; 11115 11116 case 'M': 11117 if (Subtarget->isThumb()) { // FIXME thumb2 11118 // This must be a multiple of 4 between 0 and 1020, for 11119 // ADD sp + immediate. 11120 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 11121 break; 11122 } else { 11123 // A power of two or a constant between 0 and 32. This is used in 11124 // GCC for the shift amount on shifted register operands, but it is 11125 // useful in general for any shift amounts. 11126 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 11127 break; 11128 } 11129 return; 11130 11131 case 'N': 11132 if (Subtarget->isThumb()) { // FIXME thumb2 11133 // This must be a constant between 0 and 31, for shift amounts. 11134 if (CVal >= 0 && CVal <= 31) 11135 break; 11136 } 11137 return; 11138 11139 case 'O': 11140 if (Subtarget->isThumb()) { // FIXME thumb2 11141 // This must be a multiple of 4 between -508 and 508, for 11142 // ADD/SUB sp = sp + immediate. 11143 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 11144 break; 11145 } 11146 return; 11147 } 11148 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 11149 break; 11150 } 11151 11152 if (Result.getNode()) { 11153 Ops.push_back(Result); 11154 return; 11155 } 11156 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11157 } 11158 11159 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 11160 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only"); 11161 unsigned Opcode = Op->getOpcode(); 11162 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 11163 "Invalid opcode for Div/Rem lowering"); 11164 bool isSigned = (Opcode == ISD::SDIVREM); 11165 EVT VT = Op->getValueType(0); 11166 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 11167 11168 RTLIB::Libcall LC; 11169 switch (VT.getSimpleVT().SimpleTy) { 11170 default: llvm_unreachable("Unexpected request for libcall!"); 11171 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 11172 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 11173 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 11174 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 11175 } 11176 11177 SDValue InChain = DAG.getEntryNode(); 11178 11179 TargetLowering::ArgListTy Args; 11180 TargetLowering::ArgListEntry Entry; 11181 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) { 11182 EVT ArgVT = Op->getOperand(i).getValueType(); 11183 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 11184 Entry.Node = Op->getOperand(i); 11185 Entry.Ty = ArgTy; 11186 Entry.isSExt = isSigned; 11187 Entry.isZExt = !isSigned; 11188 Args.push_back(Entry); 11189 } 11190 11191 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11192 getPointerTy(DAG.getDataLayout())); 11193 11194 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 11195 11196 SDLoc dl(Op); 11197 TargetLowering::CallLoweringInfo CLI(DAG); 11198 CLI.setDebugLoc(dl).setChain(InChain) 11199 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 11200 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 11201 11202 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 11203 return CallInfo.first; 11204 } 11205 11206 SDValue 11207 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 11208 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 11209 SDLoc DL(Op); 11210 11211 // Get the inputs. 11212 SDValue Chain = Op.getOperand(0); 11213 SDValue Size = Op.getOperand(1); 11214 11215 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 11216 DAG.getConstant(2, DL, MVT::i32)); 11217 11218 SDValue Flag; 11219 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 11220 Flag = Chain.getValue(1); 11221 11222 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11223 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 11224 11225 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 11226 Chain = NewSP.getValue(1); 11227 11228 SDValue Ops[2] = { NewSP, Chain }; 11229 return DAG.getMergeValues(Ops, DL); 11230 } 11231 11232 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11233 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 11234 "Unexpected type for custom-lowering FP_EXTEND"); 11235 11236 RTLIB::Libcall LC; 11237 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 11238 11239 SDValue SrcVal = Op.getOperand(0); 11240 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1, 11241 /*isSigned*/ false, SDLoc(Op)).first; 11242 } 11243 11244 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11245 assert(Op.getOperand(0).getValueType() == MVT::f64 && 11246 Subtarget->isFPOnlySP() && 11247 "Unexpected type for custom-lowering FP_ROUND"); 11248 11249 RTLIB::Libcall LC; 11250 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 11251 11252 SDValue SrcVal = Op.getOperand(0); 11253 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1, 11254 /*isSigned*/ false, SDLoc(Op)).first; 11255 } 11256 11257 bool 11258 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 11259 // The ARM target isn't yet aware of offsets. 11260 return false; 11261 } 11262 11263 bool ARM::isBitFieldInvertedMask(unsigned v) { 11264 if (v == 0xffffffff) 11265 return false; 11266 11267 // there can be 1's on either or both "outsides", all the "inside" 11268 // bits must be 0's 11269 return isShiftedMask_32(~v); 11270 } 11271 11272 /// isFPImmLegal - Returns true if the target can instruction select the 11273 /// specified FP immediate natively. If false, the legalizer will 11274 /// materialize the FP immediate as a load from a constant pool. 11275 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 11276 if (!Subtarget->hasVFP3()) 11277 return false; 11278 if (VT == MVT::f32) 11279 return ARM_AM::getFP32Imm(Imm) != -1; 11280 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 11281 return ARM_AM::getFP64Imm(Imm) != -1; 11282 return false; 11283 } 11284 11285 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 11286 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 11287 /// specified in the intrinsic calls. 11288 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 11289 const CallInst &I, 11290 unsigned Intrinsic) const { 11291 switch (Intrinsic) { 11292 case Intrinsic::arm_neon_vld1: 11293 case Intrinsic::arm_neon_vld2: 11294 case Intrinsic::arm_neon_vld3: 11295 case Intrinsic::arm_neon_vld4: 11296 case Intrinsic::arm_neon_vld2lane: 11297 case Intrinsic::arm_neon_vld3lane: 11298 case Intrinsic::arm_neon_vld4lane: { 11299 Info.opc = ISD::INTRINSIC_W_CHAIN; 11300 // Conservatively set memVT to the entire set of vectors loaded. 11301 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11302 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8; 11303 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11304 Info.ptrVal = I.getArgOperand(0); 11305 Info.offset = 0; 11306 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11307 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11308 Info.vol = false; // volatile loads with NEON intrinsics not supported 11309 Info.readMem = true; 11310 Info.writeMem = false; 11311 return true; 11312 } 11313 case Intrinsic::arm_neon_vst1: 11314 case Intrinsic::arm_neon_vst2: 11315 case Intrinsic::arm_neon_vst3: 11316 case Intrinsic::arm_neon_vst4: 11317 case Intrinsic::arm_neon_vst2lane: 11318 case Intrinsic::arm_neon_vst3lane: 11319 case Intrinsic::arm_neon_vst4lane: { 11320 Info.opc = ISD::INTRINSIC_VOID; 11321 // Conservatively set memVT to the entire set of vectors stored. 11322 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11323 unsigned NumElts = 0; 11324 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 11325 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 11326 if (!ArgTy->isVectorTy()) 11327 break; 11328 NumElts += DL.getTypeAllocSize(ArgTy) / 8; 11329 } 11330 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11331 Info.ptrVal = I.getArgOperand(0); 11332 Info.offset = 0; 11333 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11334 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11335 Info.vol = false; // volatile stores with NEON intrinsics not supported 11336 Info.readMem = false; 11337 Info.writeMem = true; 11338 return true; 11339 } 11340 case Intrinsic::arm_ldaex: 11341 case Intrinsic::arm_ldrex: { 11342 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11343 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 11344 Info.opc = ISD::INTRINSIC_W_CHAIN; 11345 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11346 Info.ptrVal = I.getArgOperand(0); 11347 Info.offset = 0; 11348 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 11349 Info.vol = true; 11350 Info.readMem = true; 11351 Info.writeMem = false; 11352 return true; 11353 } 11354 case Intrinsic::arm_stlex: 11355 case Intrinsic::arm_strex: { 11356 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11357 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 11358 Info.opc = ISD::INTRINSIC_W_CHAIN; 11359 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11360 Info.ptrVal = I.getArgOperand(1); 11361 Info.offset = 0; 11362 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 11363 Info.vol = true; 11364 Info.readMem = false; 11365 Info.writeMem = true; 11366 return true; 11367 } 11368 case Intrinsic::arm_stlexd: 11369 case Intrinsic::arm_strexd: { 11370 Info.opc = ISD::INTRINSIC_W_CHAIN; 11371 Info.memVT = MVT::i64; 11372 Info.ptrVal = I.getArgOperand(2); 11373 Info.offset = 0; 11374 Info.align = 8; 11375 Info.vol = true; 11376 Info.readMem = false; 11377 Info.writeMem = true; 11378 return true; 11379 } 11380 case Intrinsic::arm_ldaexd: 11381 case Intrinsic::arm_ldrexd: { 11382 Info.opc = ISD::INTRINSIC_W_CHAIN; 11383 Info.memVT = MVT::i64; 11384 Info.ptrVal = I.getArgOperand(0); 11385 Info.offset = 0; 11386 Info.align = 8; 11387 Info.vol = true; 11388 Info.readMem = true; 11389 Info.writeMem = false; 11390 return true; 11391 } 11392 default: 11393 break; 11394 } 11395 11396 return false; 11397 } 11398 11399 /// \brief Returns true if it is beneficial to convert a load of a constant 11400 /// to just the constant itself. 11401 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 11402 Type *Ty) const { 11403 assert(Ty->isIntegerTy()); 11404 11405 unsigned Bits = Ty->getPrimitiveSizeInBits(); 11406 if (Bits == 0 || Bits > 32) 11407 return false; 11408 return true; 11409 } 11410 11411 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; } 11412 11413 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 11414 ARM_MB::MemBOpt Domain) const { 11415 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11416 11417 // First, if the target has no DMB, see what fallback we can use. 11418 if (!Subtarget->hasDataBarrier()) { 11419 // Some ARMv6 cpus can support data barriers with an mcr instruction. 11420 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 11421 // here. 11422 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 11423 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 11424 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 11425 Builder.getInt32(0), Builder.getInt32(7), 11426 Builder.getInt32(10), Builder.getInt32(5)}; 11427 return Builder.CreateCall(MCR, args); 11428 } else { 11429 // Instead of using barriers, atomic accesses on these subtargets use 11430 // libcalls. 11431 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 11432 } 11433 } else { 11434 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 11435 // Only a full system barrier exists in the M-class architectures. 11436 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 11437 Constant *CDomain = Builder.getInt32(Domain); 11438 return Builder.CreateCall(DMB, CDomain); 11439 } 11440 } 11441 11442 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11443 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11444 AtomicOrdering Ord, bool IsStore, 11445 bool IsLoad) const { 11446 if (!getInsertFencesForAtomic()) 11447 return nullptr; 11448 11449 switch (Ord) { 11450 case NotAtomic: 11451 case Unordered: 11452 llvm_unreachable("Invalid fence: unordered/non-atomic"); 11453 case Monotonic: 11454 case Acquire: 11455 return nullptr; // Nothing to do 11456 case SequentiallyConsistent: 11457 if (!IsStore) 11458 return nullptr; // Nothing to do 11459 /*FALLTHROUGH*/ 11460 case Release: 11461 case AcquireRelease: 11462 if (Subtarget->isSwift()) 11463 return makeDMB(Builder, ARM_MB::ISHST); 11464 // FIXME: add a comment with a link to documentation justifying this. 11465 else 11466 return makeDMB(Builder, ARM_MB::ISH); 11467 } 11468 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 11469 } 11470 11471 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11472 AtomicOrdering Ord, bool IsStore, 11473 bool IsLoad) const { 11474 if (!getInsertFencesForAtomic()) 11475 return nullptr; 11476 11477 switch (Ord) { 11478 case NotAtomic: 11479 case Unordered: 11480 llvm_unreachable("Invalid fence: unordered/not-atomic"); 11481 case Monotonic: 11482 case Release: 11483 return nullptr; // Nothing to do 11484 case Acquire: 11485 case AcquireRelease: 11486 case SequentiallyConsistent: 11487 return makeDMB(Builder, ARM_MB::ISH); 11488 } 11489 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 11490 } 11491 11492 // Loads and stores less than 64-bits are already atomic; ones above that 11493 // are doomed anyway, so defer to the default libcall and blame the OS when 11494 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 11495 // anything for those. 11496 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 11497 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 11498 return (Size == 64) && !Subtarget->isMClass(); 11499 } 11500 11501 // Loads and stores less than 64-bits are already atomic; ones above that 11502 // are doomed anyway, so defer to the default libcall and blame the OS when 11503 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 11504 // anything for those. 11505 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 11506 // guarantee, see DDI0406C ARM architecture reference manual, 11507 // sections A8.8.72-74 LDRD) 11508 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 11509 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 11510 return (Size == 64) && !Subtarget->isMClass(); 11511 } 11512 11513 // For the real atomic operations, we have ldrex/strex up to 32 bits, 11514 // and up to 64 bits on the non-M profiles 11515 TargetLoweringBase::AtomicRMWExpansionKind 11516 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11517 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11518 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 11519 ? AtomicRMWExpansionKind::LLSC 11520 : AtomicRMWExpansionKind::None; 11521 } 11522 11523 // This has so far only been implemented for MachO. 11524 bool ARMTargetLowering::useLoadStackGuardNode() const { 11525 return Subtarget->isTargetMachO(); 11526 } 11527 11528 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 11529 unsigned &Cost) const { 11530 // If we do not have NEON, vector types are not natively supported. 11531 if (!Subtarget->hasNEON()) 11532 return false; 11533 11534 // Floating point values and vector values map to the same register file. 11535 // Therefore, althought we could do a store extract of a vector type, this is 11536 // better to leave at float as we have more freedom in the addressing mode for 11537 // those. 11538 if (VectorTy->isFPOrFPVectorTy()) 11539 return false; 11540 11541 // If the index is unknown at compile time, this is very expensive to lower 11542 // and it is not possible to combine the store with the extract. 11543 if (!isa<ConstantInt>(Idx)) 11544 return false; 11545 11546 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 11547 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 11548 // We can do a store + vector extract on any vector that fits perfectly in a D 11549 // or Q register. 11550 if (BitWidth == 64 || BitWidth == 128) { 11551 Cost = 0; 11552 return true; 11553 } 11554 return false; 11555 } 11556 11557 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 11558 AtomicOrdering Ord) const { 11559 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11560 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 11561 bool IsAcquire = isAtLeastAcquire(Ord); 11562 11563 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 11564 // intrinsic must return {i32, i32} and we have to recombine them into a 11565 // single i64 here. 11566 if (ValTy->getPrimitiveSizeInBits() == 64) { 11567 Intrinsic::ID Int = 11568 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 11569 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 11570 11571 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 11572 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 11573 11574 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 11575 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 11576 if (!Subtarget->isLittle()) 11577 std::swap (Lo, Hi); 11578 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 11579 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 11580 return Builder.CreateOr( 11581 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 11582 } 11583 11584 Type *Tys[] = { Addr->getType() }; 11585 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 11586 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 11587 11588 return Builder.CreateTruncOrBitCast( 11589 Builder.CreateCall(Ldrex, Addr), 11590 cast<PointerType>(Addr->getType())->getElementType()); 11591 } 11592 11593 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 11594 Value *Addr, 11595 AtomicOrdering Ord) const { 11596 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11597 bool IsRelease = isAtLeastRelease(Ord); 11598 11599 // Since the intrinsics must have legal type, the i64 intrinsics take two 11600 // parameters: "i32, i32". We must marshal Val into the appropriate form 11601 // before the call. 11602 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 11603 Intrinsic::ID Int = 11604 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 11605 Function *Strex = Intrinsic::getDeclaration(M, Int); 11606 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 11607 11608 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 11609 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 11610 if (!Subtarget->isLittle()) 11611 std::swap (Lo, Hi); 11612 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 11613 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 11614 } 11615 11616 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 11617 Type *Tys[] = { Addr->getType() }; 11618 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 11619 11620 return Builder.CreateCall( 11621 Strex, {Builder.CreateZExtOrBitCast( 11622 Val, Strex->getFunctionType()->getParamType(0)), 11623 Addr}); 11624 } 11625 11626 /// \brief Lower an interleaved load into a vldN intrinsic. 11627 /// 11628 /// E.g. Lower an interleaved load (Factor = 2): 11629 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 11630 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 11631 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 11632 /// 11633 /// Into: 11634 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 11635 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 11636 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 11637 bool ARMTargetLowering::lowerInterleavedLoad( 11638 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 11639 ArrayRef<unsigned> Indices, unsigned Factor) const { 11640 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 11641 "Invalid interleave factor"); 11642 assert(!Shuffles.empty() && "Empty shufflevector input"); 11643 assert(Shuffles.size() == Indices.size() && 11644 "Unmatched number of shufflevectors and indices"); 11645 11646 VectorType *VecTy = Shuffles[0]->getType(); 11647 Type *EltTy = VecTy->getVectorElementType(); 11648 11649 const DataLayout &DL = LI->getModule()->getDataLayout(); 11650 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy); 11651 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64; 11652 11653 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't 11654 // support i64/f64 element). 11655 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits) 11656 return false; 11657 11658 // A pointer vector can not be the return type of the ldN intrinsics. Need to 11659 // load integer vectors first and then convert to pointer vectors. 11660 if (EltTy->isPointerTy()) 11661 VecTy = 11662 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 11663 11664 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 11665 Intrinsic::arm_neon_vld3, 11666 Intrinsic::arm_neon_vld4}; 11667 11668 Function *VldnFunc = 11669 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy); 11670 11671 IRBuilder<> Builder(LI); 11672 SmallVector<Value *, 2> Ops; 11673 11674 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 11675 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 11676 Ops.push_back(Builder.getInt32(LI->getAlignment())); 11677 11678 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 11679 11680 // Replace uses of each shufflevector with the corresponding vector loaded 11681 // by ldN. 11682 for (unsigned i = 0; i < Shuffles.size(); i++) { 11683 ShuffleVectorInst *SV = Shuffles[i]; 11684 unsigned Index = Indices[i]; 11685 11686 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 11687 11688 // Convert the integer vector to pointer vector if the element is pointer. 11689 if (EltTy->isPointerTy()) 11690 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 11691 11692 SV->replaceAllUsesWith(SubVec); 11693 } 11694 11695 return true; 11696 } 11697 11698 /// \brief Get a mask consisting of sequential integers starting from \p Start. 11699 /// 11700 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 11701 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 11702 unsigned NumElts) { 11703 SmallVector<Constant *, 16> Mask; 11704 for (unsigned i = 0; i < NumElts; i++) 11705 Mask.push_back(Builder.getInt32(Start + i)); 11706 11707 return ConstantVector::get(Mask); 11708 } 11709 11710 /// \brief Lower an interleaved store into a vstN intrinsic. 11711 /// 11712 /// E.g. Lower an interleaved store (Factor = 3): 11713 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 11714 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 11715 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 11716 /// 11717 /// Into: 11718 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 11719 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 11720 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 11721 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 11722 /// 11723 /// Note that the new shufflevectors will be removed and we'll only generate one 11724 /// vst3 instruction in CodeGen. 11725 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 11726 ShuffleVectorInst *SVI, 11727 unsigned Factor) const { 11728 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 11729 "Invalid interleave factor"); 11730 11731 VectorType *VecTy = SVI->getType(); 11732 assert(VecTy->getVectorNumElements() % Factor == 0 && 11733 "Invalid interleaved store"); 11734 11735 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 11736 Type *EltTy = VecTy->getVectorElementType(); 11737 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 11738 11739 const DataLayout &DL = SI->getModule()->getDataLayout(); 11740 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy); 11741 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64; 11742 11743 // Skip illegal sub vector types and vector types of i64/f64 element (vstN 11744 // doesn't support i64/f64 element). 11745 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits) 11746 return false; 11747 11748 Value *Op0 = SVI->getOperand(0); 11749 Value *Op1 = SVI->getOperand(1); 11750 IRBuilder<> Builder(SI); 11751 11752 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 11753 // vectors to integer vectors. 11754 if (EltTy->isPointerTy()) { 11755 Type *IntTy = DL.getIntPtrType(EltTy); 11756 11757 // Convert to the corresponding integer vector. 11758 Type *IntVecTy = 11759 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 11760 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 11761 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 11762 11763 SubVecTy = VectorType::get(IntTy, NumSubElts); 11764 } 11765 11766 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 11767 Intrinsic::arm_neon_vst3, 11768 Intrinsic::arm_neon_vst4}; 11769 Function *VstNFunc = Intrinsic::getDeclaration( 11770 SI->getModule(), StoreInts[Factor - 2], SubVecTy); 11771 11772 SmallVector<Value *, 6> Ops; 11773 11774 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 11775 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 11776 11777 // Split the shufflevector operands into sub vectors for the new vstN call. 11778 for (unsigned i = 0; i < Factor; i++) 11779 Ops.push_back(Builder.CreateShuffleVector( 11780 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 11781 11782 Ops.push_back(Builder.getInt32(SI->getAlignment())); 11783 Builder.CreateCall(VstNFunc, Ops); 11784 return true; 11785 } 11786 11787 enum HABaseType { 11788 HA_UNKNOWN = 0, 11789 HA_FLOAT, 11790 HA_DOUBLE, 11791 HA_VECT64, 11792 HA_VECT128 11793 }; 11794 11795 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 11796 uint64_t &Members) { 11797 if (const StructType *ST = dyn_cast<StructType>(Ty)) { 11798 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 11799 uint64_t SubMembers = 0; 11800 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 11801 return false; 11802 Members += SubMembers; 11803 } 11804 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 11805 uint64_t SubMembers = 0; 11806 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 11807 return false; 11808 Members += SubMembers * AT->getNumElements(); 11809 } else if (Ty->isFloatTy()) { 11810 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 11811 return false; 11812 Members = 1; 11813 Base = HA_FLOAT; 11814 } else if (Ty->isDoubleTy()) { 11815 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 11816 return false; 11817 Members = 1; 11818 Base = HA_DOUBLE; 11819 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) { 11820 Members = 1; 11821 switch (Base) { 11822 case HA_FLOAT: 11823 case HA_DOUBLE: 11824 return false; 11825 case HA_VECT64: 11826 return VT->getBitWidth() == 64; 11827 case HA_VECT128: 11828 return VT->getBitWidth() == 128; 11829 case HA_UNKNOWN: 11830 switch (VT->getBitWidth()) { 11831 case 64: 11832 Base = HA_VECT64; 11833 return true; 11834 case 128: 11835 Base = HA_VECT128; 11836 return true; 11837 default: 11838 return false; 11839 } 11840 } 11841 } 11842 11843 return (Members > 0 && Members <= 4); 11844 } 11845 11846 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 11847 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 11848 /// passing according to AAPCS rules. 11849 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 11850 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 11851 if (getEffectiveCallingConv(CallConv, isVarArg) != 11852 CallingConv::ARM_AAPCS_VFP) 11853 return false; 11854 11855 HABaseType Base = HA_UNKNOWN; 11856 uint64_t Members = 0; 11857 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 11858 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 11859 11860 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 11861 return IsHA || IsIntArray; 11862 } 11863