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.isFloatingPoint() && 147 VT != MVT::v2i64 && VT != MVT::v1i64) 148 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 149 setOperationAction(Opcode, VT, Legal); 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 static const struct { 175 const RTLIB::Libcall Op; 176 const char * const Name; 177 const ISD::CondCode Cond; 178 } LibraryCalls[] = { 179 // Single-precision floating-point arithmetic. 180 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 181 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 182 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 183 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 184 185 // Double-precision floating-point arithmetic. 186 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 187 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 188 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 189 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 190 191 // Single-precision comparisons. 192 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 193 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 194 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 195 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 196 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 197 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 198 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 199 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 200 201 // Double-precision comparisons. 202 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 203 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 204 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 205 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 206 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 207 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 208 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 209 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 210 211 // Floating-point to integer conversions. 212 // i64 conversions are done via library routines even when generating VFP 213 // instructions, so use the same ones. 214 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 215 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 216 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 217 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 218 219 // Conversions between floating types. 220 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 221 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 222 223 // Integer to floating-point conversions. 224 // i64 conversions are done via library routines even when generating VFP 225 // instructions, so use the same ones. 226 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 227 // e.g., __floatunsidf vs. __floatunssidfvfp. 228 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 229 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 230 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 231 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 232 }; 233 234 for (const auto &LC : LibraryCalls) { 235 setLibcallName(LC.Op, LC.Name); 236 if (LC.Cond != ISD::SETCC_INVALID) 237 setCmpLibcallCC(LC.Op, LC.Cond); 238 } 239 } 240 241 // Set the correct calling convention for ARMv7k WatchOS. It's just 242 // AAPCS_VFP for functions as simple as libcalls. 243 if (Subtarget->isTargetWatchABI()) { 244 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 245 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 246 } 247 } 248 249 // These libcalls are not available in 32-bit. 250 setLibcallName(RTLIB::SHL_I128, nullptr); 251 setLibcallName(RTLIB::SRL_I128, nullptr); 252 setLibcallName(RTLIB::SRA_I128, nullptr); 253 254 // RTLIB 255 if (Subtarget->isAAPCS_ABI() && 256 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 257 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 258 static const struct { 259 const RTLIB::Libcall Op; 260 const char * const Name; 261 const CallingConv::ID CC; 262 const ISD::CondCode Cond; 263 } LibraryCalls[] = { 264 // Double-precision floating-point arithmetic helper functions 265 // RTABI chapter 4.1.2, Table 2 266 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 267 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 268 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 269 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 270 271 // Double-precision floating-point comparison helper functions 272 // RTABI chapter 4.1.2, Table 3 273 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 274 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 275 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 276 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 277 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 278 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 279 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 280 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 281 282 // Single-precision floating-point arithmetic helper functions 283 // RTABI chapter 4.1.2, Table 4 284 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 285 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 286 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 287 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 288 289 // Single-precision floating-point comparison helper functions 290 // RTABI chapter 4.1.2, Table 5 291 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 292 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 293 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 294 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 295 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 296 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 297 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 298 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 299 300 // Floating-point to integer conversions. 301 // RTABI chapter 4.1.2, Table 6 302 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 303 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 304 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 305 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 306 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 307 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 308 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 309 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 310 311 // Conversions between floating types. 312 // RTABI chapter 4.1.2, Table 7 313 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 314 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 315 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 316 317 // Integer to floating-point conversions. 318 // RTABI chapter 4.1.2, Table 8 319 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 320 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 322 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 323 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 324 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 325 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 326 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 327 328 // Long long helper functions 329 // RTABI chapter 4.2, Table 9 330 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 331 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 335 // Integer division functions 336 // RTABI chapter 4.3.1 337 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 345 }; 346 347 for (const auto &LC : LibraryCalls) { 348 setLibcallName(LC.Op, LC.Name); 349 setLibcallCallingConv(LC.Op, LC.CC); 350 if (LC.Cond != ISD::SETCC_INVALID) 351 setCmpLibcallCC(LC.Op, LC.Cond); 352 } 353 354 // EABI dependent RTLIB 355 if (TM.Options.EABIVersion == EABI::EABI4 || 356 TM.Options.EABIVersion == EABI::EABI5) { 357 static const struct { 358 const RTLIB::Libcall Op; 359 const char *const Name; 360 const CallingConv::ID CC; 361 const ISD::CondCode Cond; 362 } MemOpsLibraryCalls[] = { 363 // Memory operations 364 // RTABI chapter 4.3.4 365 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 366 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 367 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 }; 369 370 for (const auto &LC : MemOpsLibraryCalls) { 371 setLibcallName(LC.Op, LC.Name); 372 setLibcallCallingConv(LC.Op, LC.CC); 373 if (LC.Cond != ISD::SETCC_INVALID) 374 setCmpLibcallCC(LC.Op, LC.Cond); 375 } 376 } 377 } 378 379 if (Subtarget->isTargetWindows()) { 380 static const struct { 381 const RTLIB::Libcall Op; 382 const char * const Name; 383 const CallingConv::ID CC; 384 } LibraryCalls[] = { 385 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 386 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 387 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 388 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 389 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 390 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 391 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 392 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 393 }; 394 395 for (const auto &LC : LibraryCalls) { 396 setLibcallName(LC.Op, LC.Name); 397 setLibcallCallingConv(LC.Op, LC.CC); 398 } 399 } 400 401 // Use divmod compiler-rt calls for iOS 5.0 and later. 402 if (Subtarget->isTargetWatchOS() || 403 (Subtarget->isTargetIOS() && 404 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 405 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 406 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 407 } 408 409 // The half <-> float conversion functions are always soft-float on 410 // non-watchos platforms, but are needed for some targets which use a 411 // hard-float calling convention by default. 412 if (!Subtarget->isTargetWatchABI()) { 413 if (Subtarget->isAAPCS_ABI()) { 414 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 415 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 416 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 417 } else { 418 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 419 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 420 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 421 } 422 } 423 424 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 425 // a __gnu_ prefix (which is the default). 426 if (Subtarget->isTargetAEABI()) { 427 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 428 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 429 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 430 } 431 432 if (Subtarget->isThumb1Only()) 433 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 434 else 435 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 436 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 437 !Subtarget->isThumb1Only()) { 438 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 439 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 440 } 441 442 for (MVT VT : MVT::vector_valuetypes()) { 443 for (MVT InnerVT : MVT::vector_valuetypes()) { 444 setTruncStoreAction(VT, InnerVT, Expand); 445 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 446 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 447 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 448 } 449 450 setOperationAction(ISD::MULHS, VT, Expand); 451 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 452 setOperationAction(ISD::MULHU, VT, Expand); 453 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 454 455 setOperationAction(ISD::BSWAP, VT, Expand); 456 } 457 458 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 459 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 460 461 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 462 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 463 464 if (Subtarget->hasNEON()) { 465 addDRTypeForNEON(MVT::v2f32); 466 addDRTypeForNEON(MVT::v8i8); 467 addDRTypeForNEON(MVT::v4i16); 468 addDRTypeForNEON(MVT::v2i32); 469 addDRTypeForNEON(MVT::v1i64); 470 471 addQRTypeForNEON(MVT::v4f32); 472 addQRTypeForNEON(MVT::v2f64); 473 addQRTypeForNEON(MVT::v16i8); 474 addQRTypeForNEON(MVT::v8i16); 475 addQRTypeForNEON(MVT::v4i32); 476 addQRTypeForNEON(MVT::v2i64); 477 478 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 479 // neither Neon nor VFP support any arithmetic operations on it. 480 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 481 // supported for v4f32. 482 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 483 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 484 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 485 // FIXME: Code duplication: FDIV and FREM are expanded always, see 486 // ARMTargetLowering::addTypeForNEON method for details. 487 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 488 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 489 // FIXME: Create unittest. 490 // In another words, find a way when "copysign" appears in DAG with vector 491 // operands. 492 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 493 // FIXME: Code duplication: SETCC has custom operation action, see 494 // ARMTargetLowering::addTypeForNEON method for details. 495 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 496 // FIXME: Create unittest for FNEG and for FABS. 497 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 498 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 499 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 500 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 501 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 502 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 503 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 504 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 505 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 506 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 507 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 508 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 509 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 510 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 511 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 512 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 513 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 514 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 515 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 516 517 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 518 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 519 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 520 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 521 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 522 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 523 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 524 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 525 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 526 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 527 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 528 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 529 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 530 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 531 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 532 533 // Mark v2f32 intrinsics. 534 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 535 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 536 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 537 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 538 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 539 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 540 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 541 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 542 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 543 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 544 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 545 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 546 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 547 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 548 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 549 550 // Neon does not support some operations on v1i64 and v2i64 types. 551 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 552 // Custom handling for some quad-vector types to detect VMULL. 553 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 554 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 555 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 556 // Custom handling for some vector types to avoid expensive expansions 557 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 558 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 559 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 560 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 561 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 562 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 563 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 564 // a destination type that is wider than the source, and nor does 565 // it have a FP_TO_[SU]INT instruction with a narrower destination than 566 // source. 567 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 568 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 569 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 570 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 571 572 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 573 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 574 575 // NEON does not have single instruction CTPOP for vectors with element 576 // types wider than 8-bits. However, custom lowering can leverage the 577 // v8i8/v16i8 vcnt instruction. 578 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 579 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 580 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 581 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 582 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 583 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 584 585 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 586 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 587 588 // NEON does not have single instruction CTTZ for vectors. 589 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 590 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 591 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 592 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 593 594 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 595 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 596 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 597 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 598 599 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 600 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 603 604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 605 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 606 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 607 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 608 609 // NEON only has FMA instructions as of VFP4. 610 if (!Subtarget->hasVFP4()) { 611 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 612 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 613 } 614 615 setTargetDAGCombine(ISD::INTRINSIC_VOID); 616 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 617 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 618 setTargetDAGCombine(ISD::SHL); 619 setTargetDAGCombine(ISD::SRL); 620 setTargetDAGCombine(ISD::SRA); 621 setTargetDAGCombine(ISD::SIGN_EXTEND); 622 setTargetDAGCombine(ISD::ZERO_EXTEND); 623 setTargetDAGCombine(ISD::ANY_EXTEND); 624 setTargetDAGCombine(ISD::BUILD_VECTOR); 625 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 626 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 627 setTargetDAGCombine(ISD::STORE); 628 setTargetDAGCombine(ISD::FP_TO_SINT); 629 setTargetDAGCombine(ISD::FP_TO_UINT); 630 setTargetDAGCombine(ISD::FDIV); 631 setTargetDAGCombine(ISD::LOAD); 632 633 // It is legal to extload from v4i8 to v4i16 or v4i32. 634 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 635 MVT::v2i32}) { 636 for (MVT VT : MVT::integer_vector_valuetypes()) { 637 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 638 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 639 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 640 } 641 } 642 } 643 644 // ARM and Thumb2 support UMLAL/SMLAL. 645 if (!Subtarget->isThumb1Only()) 646 setTargetDAGCombine(ISD::ADDC); 647 648 if (Subtarget->isFPOnlySP()) { 649 // When targeting a floating-point unit with only single-precision 650 // operations, f64 is legal for the few double-precision instructions which 651 // are present However, no double-precision operations other than moves, 652 // loads and stores are provided by the hardware. 653 setOperationAction(ISD::FADD, MVT::f64, Expand); 654 setOperationAction(ISD::FSUB, MVT::f64, Expand); 655 setOperationAction(ISD::FMUL, MVT::f64, Expand); 656 setOperationAction(ISD::FMA, MVT::f64, Expand); 657 setOperationAction(ISD::FDIV, MVT::f64, Expand); 658 setOperationAction(ISD::FREM, MVT::f64, Expand); 659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 660 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 661 setOperationAction(ISD::FNEG, MVT::f64, Expand); 662 setOperationAction(ISD::FABS, MVT::f64, Expand); 663 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 664 setOperationAction(ISD::FSIN, MVT::f64, Expand); 665 setOperationAction(ISD::FCOS, MVT::f64, Expand); 666 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 667 setOperationAction(ISD::FPOW, MVT::f64, Expand); 668 setOperationAction(ISD::FLOG, MVT::f64, Expand); 669 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 670 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 671 setOperationAction(ISD::FEXP, MVT::f64, Expand); 672 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 673 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 674 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 675 setOperationAction(ISD::FRINT, MVT::f64, Expand); 676 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 677 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 678 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 679 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 680 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 681 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 682 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 683 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 684 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 685 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 686 } 687 688 computeRegisterProperties(Subtarget->getRegisterInfo()); 689 690 // ARM does not have floating-point extending loads. 691 for (MVT VT : MVT::fp_valuetypes()) { 692 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 693 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 694 } 695 696 // ... or truncating stores 697 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 698 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 699 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 700 701 // ARM does not have i1 sign extending load. 702 for (MVT VT : MVT::integer_valuetypes()) 703 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 704 705 // ARM supports all 4 flavors of integer indexed load / store. 706 if (!Subtarget->isThumb1Only()) { 707 for (unsigned im = (unsigned)ISD::PRE_INC; 708 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 709 setIndexedLoadAction(im, MVT::i1, Legal); 710 setIndexedLoadAction(im, MVT::i8, Legal); 711 setIndexedLoadAction(im, MVT::i16, Legal); 712 setIndexedLoadAction(im, MVT::i32, Legal); 713 setIndexedStoreAction(im, MVT::i1, Legal); 714 setIndexedStoreAction(im, MVT::i8, Legal); 715 setIndexedStoreAction(im, MVT::i16, Legal); 716 setIndexedStoreAction(im, MVT::i32, Legal); 717 } 718 } else { 719 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 720 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 721 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 722 } 723 724 setOperationAction(ISD::SADDO, MVT::i32, Custom); 725 setOperationAction(ISD::UADDO, MVT::i32, Custom); 726 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 727 setOperationAction(ISD::USUBO, MVT::i32, Custom); 728 729 // i64 operation support. 730 setOperationAction(ISD::MUL, MVT::i64, Expand); 731 setOperationAction(ISD::MULHU, MVT::i32, Expand); 732 if (Subtarget->isThumb1Only()) { 733 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 734 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 735 } 736 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 737 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 738 setOperationAction(ISD::MULHS, MVT::i32, Expand); 739 740 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 741 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 742 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 743 setOperationAction(ISD::SRL, MVT::i64, Custom); 744 setOperationAction(ISD::SRA, MVT::i64, Custom); 745 746 if (!Subtarget->isThumb1Only()) { 747 // FIXME: We should do this for Thumb1 as well. 748 setOperationAction(ISD::ADDC, MVT::i32, Custom); 749 setOperationAction(ISD::ADDE, MVT::i32, Custom); 750 setOperationAction(ISD::SUBC, MVT::i32, Custom); 751 setOperationAction(ISD::SUBE, MVT::i32, Custom); 752 } 753 754 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 755 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 756 757 // ARM does not have ROTL. 758 setOperationAction(ISD::ROTL, MVT::i32, Expand); 759 for (MVT VT : MVT::vector_valuetypes()) { 760 setOperationAction(ISD::ROTL, VT, Expand); 761 setOperationAction(ISD::ROTR, VT, Expand); 762 } 763 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 764 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 765 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 766 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 767 768 // @llvm.readcyclecounter requires the Performance Monitors extension. 769 // Default to the 0 expansion on unsupported platforms. 770 // FIXME: Technically there are older ARM CPUs that have 771 // implementation-specific ways of obtaining this information. 772 if (Subtarget->hasPerfMon()) 773 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 774 775 // Only ARMv6 has BSWAP. 776 if (!Subtarget->hasV6Ops()) 777 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 778 779 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 780 : Subtarget->hasDivideInARMMode(); 781 if (!hasDivide) { 782 // These are expanded into libcalls if the cpu doesn't have HW divider. 783 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 784 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 785 } 786 787 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 788 setOperationAction(ISD::SDIV, MVT::i32, Custom); 789 setOperationAction(ISD::UDIV, MVT::i32, Custom); 790 791 setOperationAction(ISD::SDIV, MVT::i64, Custom); 792 setOperationAction(ISD::UDIV, MVT::i64, Custom); 793 } 794 795 setOperationAction(ISD::SREM, MVT::i32, Expand); 796 setOperationAction(ISD::UREM, MVT::i32, Expand); 797 // Register based DivRem for AEABI (RTABI 4.2) 798 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 799 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) { 800 setOperationAction(ISD::SREM, MVT::i64, Custom); 801 setOperationAction(ISD::UREM, MVT::i64, Custom); 802 HasStandaloneRem = false; 803 804 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 805 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 806 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 807 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 808 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 809 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 810 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 811 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 812 813 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 814 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 815 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 816 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 817 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 818 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 819 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 820 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 821 822 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 823 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 824 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 825 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 826 } else { 827 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 828 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 829 } 830 831 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 832 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 833 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 834 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 835 836 setOperationAction(ISD::TRAP, MVT::Other, Legal); 837 838 // Use the default implementation. 839 setOperationAction(ISD::VASTART, MVT::Other, Custom); 840 setOperationAction(ISD::VAARG, MVT::Other, Expand); 841 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 842 setOperationAction(ISD::VAEND, MVT::Other, Expand); 843 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 844 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 845 846 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 847 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 848 else 849 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 850 851 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 852 // the default expansion. 853 InsertFencesForAtomic = false; 854 if (Subtarget->hasAnyDataBarrier() && 855 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 856 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 857 // to ldrex/strex loops already. 858 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 859 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 860 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 861 862 // On v8, we have particularly efficient implementations of atomic fences 863 // if they can be combined with nearby atomic loads and stores. 864 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 865 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 866 InsertFencesForAtomic = true; 867 } 868 } else { 869 // If there's anything we can use as a barrier, go through custom lowering 870 // for ATOMIC_FENCE. 871 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 872 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 873 874 // Set them all for expansion, which will force libcalls. 875 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 876 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 877 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 878 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 879 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 880 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 881 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 882 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 883 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 884 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 885 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 886 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 887 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 888 // Unordered/Monotonic case. 889 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 890 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 891 } 892 893 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 894 895 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 896 if (!Subtarget->hasV6Ops()) { 897 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 898 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 899 } 900 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 901 902 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 903 !Subtarget->isThumb1Only()) { 904 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 905 // iff target supports vfp2. 906 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 907 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 908 } 909 910 // We want to custom lower some of our intrinsics. 911 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 912 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 913 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 914 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 915 if (Subtarget->useSjLjEH()) 916 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 917 918 setOperationAction(ISD::SETCC, MVT::i32, Expand); 919 setOperationAction(ISD::SETCC, MVT::f32, Expand); 920 setOperationAction(ISD::SETCC, MVT::f64, Expand); 921 setOperationAction(ISD::SELECT, MVT::i32, Custom); 922 setOperationAction(ISD::SELECT, MVT::f32, Custom); 923 setOperationAction(ISD::SELECT, MVT::f64, Custom); 924 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 925 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 926 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 927 928 // Thumb-1 cannot currently select ARMISD::SUBE. 929 if (!Subtarget->isThumb1Only()) 930 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 931 932 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 933 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 934 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 935 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 936 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 937 938 // We don't support sin/cos/fmod/copysign/pow 939 setOperationAction(ISD::FSIN, MVT::f64, Expand); 940 setOperationAction(ISD::FSIN, MVT::f32, Expand); 941 setOperationAction(ISD::FCOS, MVT::f32, Expand); 942 setOperationAction(ISD::FCOS, MVT::f64, Expand); 943 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 944 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 945 setOperationAction(ISD::FREM, MVT::f64, Expand); 946 setOperationAction(ISD::FREM, MVT::f32, Expand); 947 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 948 !Subtarget->isThumb1Only()) { 949 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 950 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 951 } 952 setOperationAction(ISD::FPOW, MVT::f64, Expand); 953 setOperationAction(ISD::FPOW, MVT::f32, Expand); 954 955 if (!Subtarget->hasVFP4()) { 956 setOperationAction(ISD::FMA, MVT::f64, Expand); 957 setOperationAction(ISD::FMA, MVT::f32, Expand); 958 } 959 960 // Various VFP goodness 961 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 962 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 963 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 964 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 965 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 966 } 967 968 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 969 if (!Subtarget->hasFP16()) { 970 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 971 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 972 } 973 } 974 975 // Combine sin / cos into one node or libcall if possible. 976 if (Subtarget->hasSinCos()) { 977 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 978 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 979 if (Subtarget->isTargetWatchABI()) { 980 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 981 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 982 } 983 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 984 // For iOS, we don't want to the normal expansion of a libcall to 985 // sincos. We want to issue a libcall to __sincos_stret. 986 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 987 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 988 } 989 } 990 991 // FP-ARMv8 implements a lot of rounding-like FP operations. 992 if (Subtarget->hasFPARMv8()) { 993 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 994 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 995 setOperationAction(ISD::FROUND, MVT::f32, Legal); 996 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 997 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 998 setOperationAction(ISD::FRINT, MVT::f32, Legal); 999 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1000 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1001 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1002 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1003 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1004 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1005 1006 if (!Subtarget->isFPOnlySP()) { 1007 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1008 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1009 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1010 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1011 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1012 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1013 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1014 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1015 } 1016 } 1017 1018 if (Subtarget->hasNEON()) { 1019 // vmin and vmax aren't available in a scalar form, so we use 1020 // a NEON instruction with an undef lane instead. 1021 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1022 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1023 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1024 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1025 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1026 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1027 } 1028 1029 // We have target-specific dag combine patterns for the following nodes: 1030 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1031 setTargetDAGCombine(ISD::ADD); 1032 setTargetDAGCombine(ISD::SUB); 1033 setTargetDAGCombine(ISD::MUL); 1034 setTargetDAGCombine(ISD::AND); 1035 setTargetDAGCombine(ISD::OR); 1036 setTargetDAGCombine(ISD::XOR); 1037 1038 if (Subtarget->hasV6Ops()) 1039 setTargetDAGCombine(ISD::SRL); 1040 1041 setStackPointerRegisterToSaveRestore(ARM::SP); 1042 1043 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1044 !Subtarget->hasVFP2()) 1045 setSchedulingPreference(Sched::RegPressure); 1046 else 1047 setSchedulingPreference(Sched::Hybrid); 1048 1049 //// temporary - rewrite interface to use type 1050 MaxStoresPerMemset = 8; 1051 MaxStoresPerMemsetOptSize = 4; 1052 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1053 MaxStoresPerMemcpyOptSize = 2; 1054 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1055 MaxStoresPerMemmoveOptSize = 2; 1056 1057 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1058 // are at least 4 bytes aligned. 1059 setMinStackArgumentAlignment(4); 1060 1061 // Prefer likely predicted branches to selects on out-of-order cores. 1062 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1063 1064 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1065 } 1066 1067 bool ARMTargetLowering::useSoftFloat() const { 1068 return Subtarget->useSoftFloat(); 1069 } 1070 1071 // FIXME: It might make sense to define the representative register class as the 1072 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1073 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1074 // SPR's representative would be DPR_VFP2. This should work well if register 1075 // pressure tracking were modified such that a register use would increment the 1076 // pressure of the register class's representative and all of it's super 1077 // classes' representatives transitively. We have not implemented this because 1078 // of the difficulty prior to coalescing of modeling operand register classes 1079 // due to the common occurrence of cross class copies and subregister insertions 1080 // and extractions. 1081 std::pair<const TargetRegisterClass *, uint8_t> 1082 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1083 MVT VT) const { 1084 const TargetRegisterClass *RRC = nullptr; 1085 uint8_t Cost = 1; 1086 switch (VT.SimpleTy) { 1087 default: 1088 return TargetLowering::findRepresentativeClass(TRI, VT); 1089 // Use DPR as representative register class for all floating point 1090 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1091 // the cost is 1 for both f32 and f64. 1092 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1093 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1094 RRC = &ARM::DPRRegClass; 1095 // When NEON is used for SP, only half of the register file is available 1096 // because operations that define both SP and DP results will be constrained 1097 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1098 // coalescing by double-counting the SP regs. See the FIXME above. 1099 if (Subtarget->useNEONForSinglePrecisionFP()) 1100 Cost = 2; 1101 break; 1102 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1103 case MVT::v4f32: case MVT::v2f64: 1104 RRC = &ARM::DPRRegClass; 1105 Cost = 2; 1106 break; 1107 case MVT::v4i64: 1108 RRC = &ARM::DPRRegClass; 1109 Cost = 4; 1110 break; 1111 case MVT::v8i64: 1112 RRC = &ARM::DPRRegClass; 1113 Cost = 8; 1114 break; 1115 } 1116 return std::make_pair(RRC, Cost); 1117 } 1118 1119 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1120 switch ((ARMISD::NodeType)Opcode) { 1121 case ARMISD::FIRST_NUMBER: break; 1122 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1123 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1124 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1125 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1126 case ARMISD::CALL: return "ARMISD::CALL"; 1127 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1128 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1129 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1130 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1131 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1132 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1133 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1134 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1135 case ARMISD::CMP: return "ARMISD::CMP"; 1136 case ARMISD::CMN: return "ARMISD::CMN"; 1137 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1138 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1139 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1140 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1141 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1142 1143 case ARMISD::CMOV: return "ARMISD::CMOV"; 1144 1145 case ARMISD::SSAT: return "ARMISD::SSAT"; 1146 1147 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1148 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1149 case ARMISD::RRX: return "ARMISD::RRX"; 1150 1151 case ARMISD::ADDC: return "ARMISD::ADDC"; 1152 case ARMISD::ADDE: return "ARMISD::ADDE"; 1153 case ARMISD::SUBC: return "ARMISD::SUBC"; 1154 case ARMISD::SUBE: return "ARMISD::SUBE"; 1155 1156 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1157 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1158 1159 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1160 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1161 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1162 1163 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1164 1165 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1166 1167 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1168 1169 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1170 1171 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1172 1173 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1174 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1175 1176 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1177 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1178 case ARMISD::VCGE: return "ARMISD::VCGE"; 1179 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1180 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1181 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1182 case ARMISD::VCGT: return "ARMISD::VCGT"; 1183 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1184 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1185 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1186 case ARMISD::VTST: return "ARMISD::VTST"; 1187 1188 case ARMISD::VSHL: return "ARMISD::VSHL"; 1189 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1190 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1191 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1192 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1193 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1194 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1195 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1196 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1197 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1198 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1199 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1200 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1201 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1202 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1203 case ARMISD::VSLI: return "ARMISD::VSLI"; 1204 case ARMISD::VSRI: return "ARMISD::VSRI"; 1205 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1206 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1207 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1208 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1209 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1210 case ARMISD::VDUP: return "ARMISD::VDUP"; 1211 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1212 case ARMISD::VEXT: return "ARMISD::VEXT"; 1213 case ARMISD::VREV64: return "ARMISD::VREV64"; 1214 case ARMISD::VREV32: return "ARMISD::VREV32"; 1215 case ARMISD::VREV16: return "ARMISD::VREV16"; 1216 case ARMISD::VZIP: return "ARMISD::VZIP"; 1217 case ARMISD::VUZP: return "ARMISD::VUZP"; 1218 case ARMISD::VTRN: return "ARMISD::VTRN"; 1219 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1220 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1221 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1222 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1223 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1224 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1225 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1226 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1227 case ARMISD::BFI: return "ARMISD::BFI"; 1228 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1229 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1230 case ARMISD::VBSL: return "ARMISD::VBSL"; 1231 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1232 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1233 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1234 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1235 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1236 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1237 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1238 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1239 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1240 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1241 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1242 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1243 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1244 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1245 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1246 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1247 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1248 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1249 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1250 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1251 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1252 } 1253 return nullptr; 1254 } 1255 1256 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1257 EVT VT) const { 1258 if (!VT.isVector()) 1259 return getPointerTy(DL); 1260 return VT.changeVectorElementTypeToInteger(); 1261 } 1262 1263 /// getRegClassFor - Return the register class that should be used for the 1264 /// specified value type. 1265 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1266 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1267 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1268 // load / store 4 to 8 consecutive D registers. 1269 if (Subtarget->hasNEON()) { 1270 if (VT == MVT::v4i64) 1271 return &ARM::QQPRRegClass; 1272 if (VT == MVT::v8i64) 1273 return &ARM::QQQQPRRegClass; 1274 } 1275 return TargetLowering::getRegClassFor(VT); 1276 } 1277 1278 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1279 // source/dest is aligned and the copy size is large enough. We therefore want 1280 // to align such objects passed to memory intrinsics. 1281 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1282 unsigned &PrefAlign) const { 1283 if (!isa<MemIntrinsic>(CI)) 1284 return false; 1285 MinSize = 8; 1286 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1287 // cycle faster than 4-byte aligned LDM. 1288 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1289 return true; 1290 } 1291 1292 // Create a fast isel object. 1293 FastISel * 1294 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1295 const TargetLibraryInfo *libInfo) const { 1296 return ARM::createFastISel(funcInfo, libInfo); 1297 } 1298 1299 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1300 unsigned NumVals = N->getNumValues(); 1301 if (!NumVals) 1302 return Sched::RegPressure; 1303 1304 for (unsigned i = 0; i != NumVals; ++i) { 1305 EVT VT = N->getValueType(i); 1306 if (VT == MVT::Glue || VT == MVT::Other) 1307 continue; 1308 if (VT.isFloatingPoint() || VT.isVector()) 1309 return Sched::ILP; 1310 } 1311 1312 if (!N->isMachineOpcode()) 1313 return Sched::RegPressure; 1314 1315 // Load are scheduled for latency even if there instruction itinerary 1316 // is not available. 1317 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1318 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1319 1320 if (MCID.getNumDefs() == 0) 1321 return Sched::RegPressure; 1322 if (!Itins->isEmpty() && 1323 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1324 return Sched::ILP; 1325 1326 return Sched::RegPressure; 1327 } 1328 1329 //===----------------------------------------------------------------------===// 1330 // Lowering Code 1331 //===----------------------------------------------------------------------===// 1332 1333 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1334 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1335 switch (CC) { 1336 default: llvm_unreachable("Unknown condition code!"); 1337 case ISD::SETNE: return ARMCC::NE; 1338 case ISD::SETEQ: return ARMCC::EQ; 1339 case ISD::SETGT: return ARMCC::GT; 1340 case ISD::SETGE: return ARMCC::GE; 1341 case ISD::SETLT: return ARMCC::LT; 1342 case ISD::SETLE: return ARMCC::LE; 1343 case ISD::SETUGT: return ARMCC::HI; 1344 case ISD::SETUGE: return ARMCC::HS; 1345 case ISD::SETULT: return ARMCC::LO; 1346 case ISD::SETULE: return ARMCC::LS; 1347 } 1348 } 1349 1350 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1351 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1352 ARMCC::CondCodes &CondCode2) { 1353 CondCode2 = ARMCC::AL; 1354 switch (CC) { 1355 default: llvm_unreachable("Unknown FP condition!"); 1356 case ISD::SETEQ: 1357 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1358 case ISD::SETGT: 1359 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1360 case ISD::SETGE: 1361 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1362 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1363 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1364 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1365 case ISD::SETO: CondCode = ARMCC::VC; break; 1366 case ISD::SETUO: CondCode = ARMCC::VS; break; 1367 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1368 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1369 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1370 case ISD::SETLT: 1371 case ISD::SETULT: CondCode = ARMCC::LT; break; 1372 case ISD::SETLE: 1373 case ISD::SETULE: CondCode = ARMCC::LE; break; 1374 case ISD::SETNE: 1375 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1376 } 1377 } 1378 1379 //===----------------------------------------------------------------------===// 1380 // Calling Convention Implementation 1381 //===----------------------------------------------------------------------===// 1382 1383 #include "ARMGenCallingConv.inc" 1384 1385 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1386 /// account presence of floating point hardware and calling convention 1387 /// limitations, such as support for variadic functions. 1388 CallingConv::ID 1389 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1390 bool isVarArg) const { 1391 switch (CC) { 1392 default: 1393 llvm_unreachable("Unsupported calling convention"); 1394 case CallingConv::ARM_AAPCS: 1395 case CallingConv::ARM_APCS: 1396 case CallingConv::GHC: 1397 return CC; 1398 case CallingConv::PreserveMost: 1399 return CallingConv::PreserveMost; 1400 case CallingConv::ARM_AAPCS_VFP: 1401 case CallingConv::Swift: 1402 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1403 case CallingConv::C: 1404 if (!Subtarget->isAAPCS_ABI()) 1405 return CallingConv::ARM_APCS; 1406 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1407 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1408 !isVarArg) 1409 return CallingConv::ARM_AAPCS_VFP; 1410 else 1411 return CallingConv::ARM_AAPCS; 1412 case CallingConv::Fast: 1413 case CallingConv::CXX_FAST_TLS: 1414 if (!Subtarget->isAAPCS_ABI()) { 1415 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1416 return CallingConv::Fast; 1417 return CallingConv::ARM_APCS; 1418 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1419 return CallingConv::ARM_AAPCS_VFP; 1420 else 1421 return CallingConv::ARM_AAPCS; 1422 } 1423 } 1424 1425 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1426 /// CallingConvention. 1427 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1428 bool Return, 1429 bool isVarArg) const { 1430 switch (getEffectiveCallingConv(CC, isVarArg)) { 1431 default: 1432 llvm_unreachable("Unsupported calling convention"); 1433 case CallingConv::ARM_APCS: 1434 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1435 case CallingConv::ARM_AAPCS: 1436 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1437 case CallingConv::ARM_AAPCS_VFP: 1438 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1439 case CallingConv::Fast: 1440 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1441 case CallingConv::GHC: 1442 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1443 case CallingConv::PreserveMost: 1444 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1445 } 1446 } 1447 1448 /// LowerCallResult - Lower the result values of a call into the 1449 /// appropriate copies out of appropriate physical registers. 1450 SDValue ARMTargetLowering::LowerCallResult( 1451 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1452 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1453 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1454 SDValue ThisVal) const { 1455 1456 // Assign locations to each value returned by this call. 1457 SmallVector<CCValAssign, 16> RVLocs; 1458 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1459 *DAG.getContext(), Call); 1460 CCInfo.AnalyzeCallResult(Ins, 1461 CCAssignFnForNode(CallConv, /* Return*/ true, 1462 isVarArg)); 1463 1464 // Copy all of the result registers out of their specified physreg. 1465 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1466 CCValAssign VA = RVLocs[i]; 1467 1468 // Pass 'this' value directly from the argument to return value, to avoid 1469 // reg unit interference 1470 if (i == 0 && isThisReturn) { 1471 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1472 "unexpected return calling convention register assignment"); 1473 InVals.push_back(ThisVal); 1474 continue; 1475 } 1476 1477 SDValue Val; 1478 if (VA.needsCustom()) { 1479 // Handle f64 or half of a v2f64. 1480 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1481 InFlag); 1482 Chain = Lo.getValue(1); 1483 InFlag = Lo.getValue(2); 1484 VA = RVLocs[++i]; // skip ahead to next loc 1485 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1486 InFlag); 1487 Chain = Hi.getValue(1); 1488 InFlag = Hi.getValue(2); 1489 if (!Subtarget->isLittle()) 1490 std::swap (Lo, Hi); 1491 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1492 1493 if (VA.getLocVT() == MVT::v2f64) { 1494 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1495 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1496 DAG.getConstant(0, dl, MVT::i32)); 1497 1498 VA = RVLocs[++i]; // skip ahead to next loc 1499 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1500 Chain = Lo.getValue(1); 1501 InFlag = Lo.getValue(2); 1502 VA = RVLocs[++i]; // skip ahead to next loc 1503 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1504 Chain = Hi.getValue(1); 1505 InFlag = Hi.getValue(2); 1506 if (!Subtarget->isLittle()) 1507 std::swap (Lo, Hi); 1508 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1509 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1510 DAG.getConstant(1, dl, MVT::i32)); 1511 } 1512 } else { 1513 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1514 InFlag); 1515 Chain = Val.getValue(1); 1516 InFlag = Val.getValue(2); 1517 } 1518 1519 switch (VA.getLocInfo()) { 1520 default: llvm_unreachable("Unknown loc info!"); 1521 case CCValAssign::Full: break; 1522 case CCValAssign::BCvt: 1523 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1524 break; 1525 } 1526 1527 InVals.push_back(Val); 1528 } 1529 1530 return Chain; 1531 } 1532 1533 /// LowerMemOpCallTo - Store the argument to the stack. 1534 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1535 SDValue Arg, const SDLoc &dl, 1536 SelectionDAG &DAG, 1537 const CCValAssign &VA, 1538 ISD::ArgFlagsTy Flags) const { 1539 unsigned LocMemOffset = VA.getLocMemOffset(); 1540 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1541 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1542 StackPtr, PtrOff); 1543 return DAG.getStore( 1544 Chain, dl, Arg, PtrOff, 1545 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1546 } 1547 1548 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1549 SDValue Chain, SDValue &Arg, 1550 RegsToPassVector &RegsToPass, 1551 CCValAssign &VA, CCValAssign &NextVA, 1552 SDValue &StackPtr, 1553 SmallVectorImpl<SDValue> &MemOpChains, 1554 ISD::ArgFlagsTy Flags) const { 1555 1556 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1557 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1558 unsigned id = Subtarget->isLittle() ? 0 : 1; 1559 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1560 1561 if (NextVA.isRegLoc()) 1562 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1563 else { 1564 assert(NextVA.isMemLoc()); 1565 if (!StackPtr.getNode()) 1566 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1567 getPointerTy(DAG.getDataLayout())); 1568 1569 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1570 dl, DAG, NextVA, 1571 Flags)); 1572 } 1573 } 1574 1575 /// LowerCall - Lowering a call into a callseq_start <- 1576 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1577 /// nodes. 1578 SDValue 1579 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1580 SmallVectorImpl<SDValue> &InVals) const { 1581 SelectionDAG &DAG = CLI.DAG; 1582 SDLoc &dl = CLI.DL; 1583 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1584 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1585 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1586 SDValue Chain = CLI.Chain; 1587 SDValue Callee = CLI.Callee; 1588 bool &isTailCall = CLI.IsTailCall; 1589 CallingConv::ID CallConv = CLI.CallConv; 1590 bool doesNotRet = CLI.DoesNotReturn; 1591 bool isVarArg = CLI.IsVarArg; 1592 1593 MachineFunction &MF = DAG.getMachineFunction(); 1594 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1595 bool isThisReturn = false; 1596 bool isSibCall = false; 1597 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1598 1599 // Disable tail calls if they're not supported. 1600 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1601 isTailCall = false; 1602 1603 if (isTailCall) { 1604 // Check if it's really possible to do a tail call. 1605 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1606 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1607 Outs, OutVals, Ins, DAG); 1608 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1609 report_fatal_error("failed to perform tail call elimination on a call " 1610 "site marked musttail"); 1611 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1612 // detected sibcalls. 1613 if (isTailCall) { 1614 ++NumTailCalls; 1615 isSibCall = true; 1616 } 1617 } 1618 1619 // Analyze operands of the call, assigning locations to each operand. 1620 SmallVector<CCValAssign, 16> ArgLocs; 1621 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1622 *DAG.getContext(), Call); 1623 CCInfo.AnalyzeCallOperands(Outs, 1624 CCAssignFnForNode(CallConv, /* Return*/ false, 1625 isVarArg)); 1626 1627 // Get a count of how many bytes are to be pushed on the stack. 1628 unsigned NumBytes = CCInfo.getNextStackOffset(); 1629 1630 // For tail calls, memory operands are available in our caller's stack. 1631 if (isSibCall) 1632 NumBytes = 0; 1633 1634 // Adjust the stack pointer for the new arguments... 1635 // These operations are automatically eliminated by the prolog/epilog pass 1636 if (!isSibCall) 1637 Chain = DAG.getCALLSEQ_START(Chain, 1638 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1639 1640 SDValue StackPtr = 1641 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1642 1643 RegsToPassVector RegsToPass; 1644 SmallVector<SDValue, 8> MemOpChains; 1645 1646 // Walk the register/memloc assignments, inserting copies/loads. In the case 1647 // of tail call optimization, arguments are handled later. 1648 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1649 i != e; 1650 ++i, ++realArgIdx) { 1651 CCValAssign &VA = ArgLocs[i]; 1652 SDValue Arg = OutVals[realArgIdx]; 1653 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1654 bool isByVal = Flags.isByVal(); 1655 1656 // Promote the value if needed. 1657 switch (VA.getLocInfo()) { 1658 default: llvm_unreachable("Unknown loc info!"); 1659 case CCValAssign::Full: break; 1660 case CCValAssign::SExt: 1661 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1662 break; 1663 case CCValAssign::ZExt: 1664 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1665 break; 1666 case CCValAssign::AExt: 1667 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1668 break; 1669 case CCValAssign::BCvt: 1670 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1671 break; 1672 } 1673 1674 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1675 if (VA.needsCustom()) { 1676 if (VA.getLocVT() == MVT::v2f64) { 1677 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1678 DAG.getConstant(0, dl, MVT::i32)); 1679 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1680 DAG.getConstant(1, dl, MVT::i32)); 1681 1682 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1683 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1684 1685 VA = ArgLocs[++i]; // skip ahead to next loc 1686 if (VA.isRegLoc()) { 1687 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1688 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1689 } else { 1690 assert(VA.isMemLoc()); 1691 1692 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1693 dl, DAG, VA, Flags)); 1694 } 1695 } else { 1696 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1697 StackPtr, MemOpChains, Flags); 1698 } 1699 } else if (VA.isRegLoc()) { 1700 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1701 assert(VA.getLocVT() == MVT::i32 && 1702 "unexpected calling convention register assignment"); 1703 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1704 "unexpected use of 'returned'"); 1705 isThisReturn = true; 1706 } 1707 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1708 } else if (isByVal) { 1709 assert(VA.isMemLoc()); 1710 unsigned offset = 0; 1711 1712 // True if this byval aggregate will be split between registers 1713 // and memory. 1714 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1715 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1716 1717 if (CurByValIdx < ByValArgsCount) { 1718 1719 unsigned RegBegin, RegEnd; 1720 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1721 1722 EVT PtrVT = 1723 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1724 unsigned int i, j; 1725 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1726 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1727 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1728 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1729 MachinePointerInfo(), 1730 DAG.InferPtrAlignment(AddArg)); 1731 MemOpChains.push_back(Load.getValue(1)); 1732 RegsToPass.push_back(std::make_pair(j, Load)); 1733 } 1734 1735 // If parameter size outsides register area, "offset" value 1736 // helps us to calculate stack slot for remained part properly. 1737 offset = RegEnd - RegBegin; 1738 1739 CCInfo.nextInRegsParam(); 1740 } 1741 1742 if (Flags.getByValSize() > 4*offset) { 1743 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1744 unsigned LocMemOffset = VA.getLocMemOffset(); 1745 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1746 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1747 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1748 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1749 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1750 MVT::i32); 1751 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1752 MVT::i32); 1753 1754 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1755 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1756 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1757 Ops)); 1758 } 1759 } else if (!isSibCall) { 1760 assert(VA.isMemLoc()); 1761 1762 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1763 dl, DAG, VA, Flags)); 1764 } 1765 } 1766 1767 if (!MemOpChains.empty()) 1768 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1769 1770 // Build a sequence of copy-to-reg nodes chained together with token chain 1771 // and flag operands which copy the outgoing args into the appropriate regs. 1772 SDValue InFlag; 1773 // Tail call byval lowering might overwrite argument registers so in case of 1774 // tail call optimization the copies to registers are lowered later. 1775 if (!isTailCall) 1776 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1777 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1778 RegsToPass[i].second, InFlag); 1779 InFlag = Chain.getValue(1); 1780 } 1781 1782 // For tail calls lower the arguments to the 'real' stack slot. 1783 if (isTailCall) { 1784 // Force all the incoming stack arguments to be loaded from the stack 1785 // before any new outgoing arguments are stored to the stack, because the 1786 // outgoing stack slots may alias the incoming argument stack slots, and 1787 // the alias isn't otherwise explicit. This is slightly more conservative 1788 // than necessary, because it means that each store effectively depends 1789 // on every argument instead of just those arguments it would clobber. 1790 1791 // Do not flag preceding copytoreg stuff together with the following stuff. 1792 InFlag = SDValue(); 1793 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1794 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1795 RegsToPass[i].second, InFlag); 1796 InFlag = Chain.getValue(1); 1797 } 1798 InFlag = SDValue(); 1799 } 1800 1801 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1802 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1803 // node so that legalize doesn't hack it. 1804 bool isDirect = false; 1805 1806 const TargetMachine &TM = getTargetMachine(); 1807 const Module *Mod = MF.getFunction()->getParent(); 1808 const GlobalValue *GV = nullptr; 1809 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1810 GV = G->getGlobal(); 1811 bool isStub = 1812 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1813 1814 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1815 bool isLocalARMFunc = false; 1816 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1817 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1818 1819 if (Subtarget->genLongCalls()) { 1820 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1821 "long-calls codegen is not position independent!"); 1822 // Handle a global address or an external symbol. If it's not one of 1823 // those, the target's already in a register, so we don't need to do 1824 // anything extra. 1825 if (isa<GlobalAddressSDNode>(Callee)) { 1826 // Create a constant pool entry for the callee address 1827 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1828 ARMConstantPoolValue *CPV = 1829 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1830 1831 // Get the address of the callee into a register 1832 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1833 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1834 Callee = DAG.getLoad( 1835 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1836 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 1837 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1838 const char *Sym = S->getSymbol(); 1839 1840 // Create a constant pool entry for the callee address 1841 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1842 ARMConstantPoolValue *CPV = 1843 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1844 ARMPCLabelIndex, 0); 1845 // Get the address of the callee into a register 1846 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1847 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1848 Callee = DAG.getLoad( 1849 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1850 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 1851 } 1852 } else if (isa<GlobalAddressSDNode>(Callee)) { 1853 // If we're optimizing for minimum size and the function is called three or 1854 // more times in this block, we can improve codesize by calling indirectly 1855 // as BLXr has a 16-bit encoding. 1856 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 1857 auto *BB = CLI.CS->getParent(); 1858 bool PreferIndirect = 1859 Subtarget->isThumb() && MF.getFunction()->optForMinSize() && 1860 count_if(GV->users(), [&BB](const User *U) { 1861 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 1862 }) > 2; 1863 1864 if (!PreferIndirect) { 1865 isDirect = true; 1866 bool isDef = GV->isStrongDefinitionForLinker(); 1867 1868 // ARM call to a local ARM function is predicable. 1869 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1870 // tBX takes a register source operand. 1871 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1872 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1873 Callee = DAG.getNode( 1874 ARMISD::WrapperPIC, dl, PtrVt, 1875 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1876 Callee = 1877 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1878 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1879 /* Alignment = */ 0, MachineMemOperand::MOInvariant); 1880 } else if (Subtarget->isTargetCOFF()) { 1881 assert(Subtarget->isTargetWindows() && 1882 "Windows is the only supported COFF target"); 1883 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1884 ? ARMII::MO_DLLIMPORT 1885 : ARMII::MO_NO_FLAG; 1886 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 1887 TargetFlags); 1888 if (GV->hasDLLImportStorageClass()) 1889 Callee = 1890 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1891 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1892 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 1893 } else { 1894 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 1895 } 1896 } 1897 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1898 isDirect = true; 1899 // tBX takes a register source operand. 1900 const char *Sym = S->getSymbol(); 1901 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1902 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1903 ARMConstantPoolValue *CPV = 1904 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1905 ARMPCLabelIndex, 4); 1906 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1907 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1908 Callee = DAG.getLoad( 1909 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1910 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 1911 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1912 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1913 } else { 1914 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 1915 } 1916 } 1917 1918 // FIXME: handle tail calls differently. 1919 unsigned CallOpc; 1920 if (Subtarget->isThumb()) { 1921 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1922 CallOpc = ARMISD::CALL_NOLINK; 1923 else 1924 CallOpc = ARMISD::CALL; 1925 } else { 1926 if (!isDirect && !Subtarget->hasV5TOps()) 1927 CallOpc = ARMISD::CALL_NOLINK; 1928 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 1929 // Emit regular call when code size is the priority 1930 !MF.getFunction()->optForMinSize()) 1931 // "mov lr, pc; b _foo" to avoid confusing the RSP 1932 CallOpc = ARMISD::CALL_NOLINK; 1933 else 1934 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1935 } 1936 1937 std::vector<SDValue> Ops; 1938 Ops.push_back(Chain); 1939 Ops.push_back(Callee); 1940 1941 // Add argument registers to the end of the list so that they are known live 1942 // into the call. 1943 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1944 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1945 RegsToPass[i].second.getValueType())); 1946 1947 // Add a register mask operand representing the call-preserved registers. 1948 if (!isTailCall) { 1949 const uint32_t *Mask; 1950 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1951 if (isThisReturn) { 1952 // For 'this' returns, use the R0-preserving mask if applicable 1953 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1954 if (!Mask) { 1955 // Set isThisReturn to false if the calling convention is not one that 1956 // allows 'returned' to be modeled in this way, so LowerCallResult does 1957 // not try to pass 'this' straight through 1958 isThisReturn = false; 1959 Mask = ARI->getCallPreservedMask(MF, CallConv); 1960 } 1961 } else 1962 Mask = ARI->getCallPreservedMask(MF, CallConv); 1963 1964 assert(Mask && "Missing call preserved mask for calling convention"); 1965 Ops.push_back(DAG.getRegisterMask(Mask)); 1966 } 1967 1968 if (InFlag.getNode()) 1969 Ops.push_back(InFlag); 1970 1971 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1972 if (isTailCall) { 1973 MF.getFrameInfo().setHasTailCall(); 1974 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1975 } 1976 1977 // Returns a chain and a flag for retval copy to use. 1978 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1979 InFlag = Chain.getValue(1); 1980 1981 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1982 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1983 if (!Ins.empty()) 1984 InFlag = Chain.getValue(1); 1985 1986 // Handle result values, copying them out of physregs into vregs that we 1987 // return. 1988 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1989 InVals, isThisReturn, 1990 isThisReturn ? OutVals[0] : SDValue()); 1991 } 1992 1993 /// HandleByVal - Every parameter *after* a byval parameter is passed 1994 /// on the stack. Remember the next parameter register to allocate, 1995 /// and then confiscate the rest of the parameter registers to insure 1996 /// this. 1997 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1998 unsigned Align) const { 1999 assert((State->getCallOrPrologue() == Prologue || 2000 State->getCallOrPrologue() == Call) && 2001 "unhandled ParmContext"); 2002 2003 // Byval (as with any stack) slots are always at least 4 byte aligned. 2004 Align = std::max(Align, 4U); 2005 2006 unsigned Reg = State->AllocateReg(GPRArgRegs); 2007 if (!Reg) 2008 return; 2009 2010 unsigned AlignInRegs = Align / 4; 2011 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2012 for (unsigned i = 0; i < Waste; ++i) 2013 Reg = State->AllocateReg(GPRArgRegs); 2014 2015 if (!Reg) 2016 return; 2017 2018 unsigned Excess = 4 * (ARM::R4 - Reg); 2019 2020 // Special case when NSAA != SP and parameter size greater than size of 2021 // all remained GPR regs. In that case we can't split parameter, we must 2022 // send it to stack. We also must set NCRN to R4, so waste all 2023 // remained registers. 2024 const unsigned NSAAOffset = State->getNextStackOffset(); 2025 if (NSAAOffset != 0 && Size > Excess) { 2026 while (State->AllocateReg(GPRArgRegs)) 2027 ; 2028 return; 2029 } 2030 2031 // First register for byval parameter is the first register that wasn't 2032 // allocated before this method call, so it would be "reg". 2033 // If parameter is small enough to be saved in range [reg, r4), then 2034 // the end (first after last) register would be reg + param-size-in-regs, 2035 // else parameter would be splitted between registers and stack, 2036 // end register would be r4 in this case. 2037 unsigned ByValRegBegin = Reg; 2038 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2039 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2040 // Note, first register is allocated in the beginning of function already, 2041 // allocate remained amount of registers we need. 2042 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2043 State->AllocateReg(GPRArgRegs); 2044 // A byval parameter that is split between registers and memory needs its 2045 // size truncated here. 2046 // In the case where the entire structure fits in registers, we set the 2047 // size in memory to zero. 2048 Size = std::max<int>(Size - Excess, 0); 2049 } 2050 2051 /// MatchingStackOffset - Return true if the given stack call argument is 2052 /// already available in the same position (relatively) of the caller's 2053 /// incoming argument stack. 2054 static 2055 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2056 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2057 const TargetInstrInfo *TII) { 2058 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2059 int FI = INT_MAX; 2060 if (Arg.getOpcode() == ISD::CopyFromReg) { 2061 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2062 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2063 return false; 2064 MachineInstr *Def = MRI->getVRegDef(VR); 2065 if (!Def) 2066 return false; 2067 if (!Flags.isByVal()) { 2068 if (!TII->isLoadFromStackSlot(*Def, FI)) 2069 return false; 2070 } else { 2071 return false; 2072 } 2073 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2074 if (Flags.isByVal()) 2075 // ByVal argument is passed in as a pointer but it's now being 2076 // dereferenced. e.g. 2077 // define @foo(%struct.X* %A) { 2078 // tail call @bar(%struct.X* byval %A) 2079 // } 2080 return false; 2081 SDValue Ptr = Ld->getBasePtr(); 2082 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2083 if (!FINode) 2084 return false; 2085 FI = FINode->getIndex(); 2086 } else 2087 return false; 2088 2089 assert(FI != INT_MAX); 2090 if (!MFI.isFixedObjectIndex(FI)) 2091 return false; 2092 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2093 } 2094 2095 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2096 /// for tail call optimization. Targets which want to do tail call 2097 /// optimization should implement this function. 2098 bool 2099 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2100 CallingConv::ID CalleeCC, 2101 bool isVarArg, 2102 bool isCalleeStructRet, 2103 bool isCallerStructRet, 2104 const SmallVectorImpl<ISD::OutputArg> &Outs, 2105 const SmallVectorImpl<SDValue> &OutVals, 2106 const SmallVectorImpl<ISD::InputArg> &Ins, 2107 SelectionDAG& DAG) const { 2108 MachineFunction &MF = DAG.getMachineFunction(); 2109 const Function *CallerF = MF.getFunction(); 2110 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2111 2112 assert(Subtarget->supportsTailCall()); 2113 2114 // Look for obvious safe cases to perform tail call optimization that do not 2115 // require ABI changes. This is what gcc calls sibcall. 2116 2117 // Do not sibcall optimize vararg calls unless the call site is not passing 2118 // any arguments. 2119 if (isVarArg && !Outs.empty()) 2120 return false; 2121 2122 // Exception-handling functions need a special set of instructions to indicate 2123 // a return to the hardware. Tail-calling another function would probably 2124 // break this. 2125 if (CallerF->hasFnAttribute("interrupt")) 2126 return false; 2127 2128 // Also avoid sibcall optimization if either caller or callee uses struct 2129 // return semantics. 2130 if (isCalleeStructRet || isCallerStructRet) 2131 return false; 2132 2133 // Externally-defined functions with weak linkage should not be 2134 // tail-called on ARM when the OS does not support dynamic 2135 // pre-emption of symbols, as the AAELF spec requires normal calls 2136 // to undefined weak functions to be replaced with a NOP or jump to the 2137 // next instruction. The behaviour of branch instructions in this 2138 // situation (as used for tail calls) is implementation-defined, so we 2139 // cannot rely on the linker replacing the tail call with a return. 2140 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2141 const GlobalValue *GV = G->getGlobal(); 2142 const Triple &TT = getTargetMachine().getTargetTriple(); 2143 if (GV->hasExternalWeakLinkage() && 2144 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2145 return false; 2146 } 2147 2148 // Check that the call results are passed in the same way. 2149 LLVMContext &C = *DAG.getContext(); 2150 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2151 CCAssignFnForNode(CalleeCC, true, isVarArg), 2152 CCAssignFnForNode(CallerCC, true, isVarArg))) 2153 return false; 2154 // The callee has to preserve all registers the caller needs to preserve. 2155 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2156 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2157 if (CalleeCC != CallerCC) { 2158 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2159 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2160 return false; 2161 } 2162 2163 // If Caller's vararg or byval argument has been split between registers and 2164 // stack, do not perform tail call, since part of the argument is in caller's 2165 // local frame. 2166 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2167 if (AFI_Caller->getArgRegsSaveSize()) 2168 return false; 2169 2170 // If the callee takes no arguments then go on to check the results of the 2171 // call. 2172 if (!Outs.empty()) { 2173 // Check if stack adjustment is needed. For now, do not do this if any 2174 // argument is passed on the stack. 2175 SmallVector<CCValAssign, 16> ArgLocs; 2176 ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call); 2177 CCInfo.AnalyzeCallOperands(Outs, 2178 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2179 if (CCInfo.getNextStackOffset()) { 2180 // Check if the arguments are already laid out in the right way as 2181 // the caller's fixed stack objects. 2182 MachineFrameInfo &MFI = MF.getFrameInfo(); 2183 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2184 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2185 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2186 i != e; 2187 ++i, ++realArgIdx) { 2188 CCValAssign &VA = ArgLocs[i]; 2189 EVT RegVT = VA.getLocVT(); 2190 SDValue Arg = OutVals[realArgIdx]; 2191 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2192 if (VA.getLocInfo() == CCValAssign::Indirect) 2193 return false; 2194 if (VA.needsCustom()) { 2195 // f64 and vector types are split into multiple registers or 2196 // register/stack-slot combinations. The types will not match 2197 // the registers; give up on memory f64 refs until we figure 2198 // out what to do about this. 2199 if (!VA.isRegLoc()) 2200 return false; 2201 if (!ArgLocs[++i].isRegLoc()) 2202 return false; 2203 if (RegVT == MVT::v2f64) { 2204 if (!ArgLocs[++i].isRegLoc()) 2205 return false; 2206 if (!ArgLocs[++i].isRegLoc()) 2207 return false; 2208 } 2209 } else if (!VA.isRegLoc()) { 2210 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2211 MFI, MRI, TII)) 2212 return false; 2213 } 2214 } 2215 } 2216 2217 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2218 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2219 return false; 2220 } 2221 2222 return true; 2223 } 2224 2225 bool 2226 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2227 MachineFunction &MF, bool isVarArg, 2228 const SmallVectorImpl<ISD::OutputArg> &Outs, 2229 LLVMContext &Context) const { 2230 SmallVector<CCValAssign, 16> RVLocs; 2231 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2232 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2233 isVarArg)); 2234 } 2235 2236 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2237 const SDLoc &DL, SelectionDAG &DAG) { 2238 const MachineFunction &MF = DAG.getMachineFunction(); 2239 const Function *F = MF.getFunction(); 2240 2241 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2242 2243 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2244 // version of the "preferred return address". These offsets affect the return 2245 // instruction if this is a return from PL1 without hypervisor extensions. 2246 // IRQ/FIQ: +4 "subs pc, lr, #4" 2247 // SWI: 0 "subs pc, lr, #0" 2248 // ABORT: +4 "subs pc, lr, #4" 2249 // UNDEF: +4/+2 "subs pc, lr, #0" 2250 // UNDEF varies depending on where the exception came from ARM or Thumb 2251 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2252 2253 int64_t LROffset; 2254 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2255 IntKind == "ABORT") 2256 LROffset = 4; 2257 else if (IntKind == "SWI" || IntKind == "UNDEF") 2258 LROffset = 0; 2259 else 2260 report_fatal_error("Unsupported interrupt attribute. If present, value " 2261 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2262 2263 RetOps.insert(RetOps.begin() + 1, 2264 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2265 2266 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2267 } 2268 2269 SDValue 2270 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2271 bool isVarArg, 2272 const SmallVectorImpl<ISD::OutputArg> &Outs, 2273 const SmallVectorImpl<SDValue> &OutVals, 2274 const SDLoc &dl, SelectionDAG &DAG) const { 2275 2276 // CCValAssign - represent the assignment of the return value to a location. 2277 SmallVector<CCValAssign, 16> RVLocs; 2278 2279 // CCState - Info about the registers and stack slots. 2280 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2281 *DAG.getContext(), Call); 2282 2283 // Analyze outgoing return values. 2284 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2285 isVarArg)); 2286 2287 SDValue Flag; 2288 SmallVector<SDValue, 4> RetOps; 2289 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2290 bool isLittleEndian = Subtarget->isLittle(); 2291 2292 MachineFunction &MF = DAG.getMachineFunction(); 2293 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2294 AFI->setReturnRegsCount(RVLocs.size()); 2295 2296 // Copy the result values into the output registers. 2297 for (unsigned i = 0, realRVLocIdx = 0; 2298 i != RVLocs.size(); 2299 ++i, ++realRVLocIdx) { 2300 CCValAssign &VA = RVLocs[i]; 2301 assert(VA.isRegLoc() && "Can only return in registers!"); 2302 2303 SDValue Arg = OutVals[realRVLocIdx]; 2304 2305 switch (VA.getLocInfo()) { 2306 default: llvm_unreachable("Unknown loc info!"); 2307 case CCValAssign::Full: break; 2308 case CCValAssign::BCvt: 2309 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2310 break; 2311 } 2312 2313 if (VA.needsCustom()) { 2314 if (VA.getLocVT() == MVT::v2f64) { 2315 // Extract the first half and return it in two registers. 2316 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2317 DAG.getConstant(0, dl, MVT::i32)); 2318 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2319 DAG.getVTList(MVT::i32, MVT::i32), Half); 2320 2321 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2322 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2323 Flag); 2324 Flag = Chain.getValue(1); 2325 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2326 VA = RVLocs[++i]; // skip ahead to next loc 2327 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2328 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2329 Flag); 2330 Flag = Chain.getValue(1); 2331 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2332 VA = RVLocs[++i]; // skip ahead to next loc 2333 2334 // Extract the 2nd half and fall through to handle it as an f64 value. 2335 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2336 DAG.getConstant(1, dl, MVT::i32)); 2337 } 2338 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2339 // available. 2340 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2341 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2342 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2343 fmrrd.getValue(isLittleEndian ? 0 : 1), 2344 Flag); 2345 Flag = Chain.getValue(1); 2346 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2347 VA = RVLocs[++i]; // skip ahead to next loc 2348 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2349 fmrrd.getValue(isLittleEndian ? 1 : 0), 2350 Flag); 2351 } else 2352 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2353 2354 // Guarantee that all emitted copies are 2355 // stuck together, avoiding something bad. 2356 Flag = Chain.getValue(1); 2357 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2358 } 2359 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2360 const MCPhysReg *I = 2361 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2362 if (I) { 2363 for (; *I; ++I) { 2364 if (ARM::GPRRegClass.contains(*I)) 2365 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2366 else if (ARM::DPRRegClass.contains(*I)) 2367 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2368 else 2369 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2370 } 2371 } 2372 2373 // Update chain and glue. 2374 RetOps[0] = Chain; 2375 if (Flag.getNode()) 2376 RetOps.push_back(Flag); 2377 2378 // CPUs which aren't M-class use a special sequence to return from 2379 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2380 // though we use "subs pc, lr, #N"). 2381 // 2382 // M-class CPUs actually use a normal return sequence with a special 2383 // (hardware-provided) value in LR, so the normal code path works. 2384 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2385 !Subtarget->isMClass()) { 2386 if (Subtarget->isThumb1Only()) 2387 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2388 return LowerInterruptReturn(RetOps, dl, DAG); 2389 } 2390 2391 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2392 } 2393 2394 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2395 if (N->getNumValues() != 1) 2396 return false; 2397 if (!N->hasNUsesOfValue(1, 0)) 2398 return false; 2399 2400 SDValue TCChain = Chain; 2401 SDNode *Copy = *N->use_begin(); 2402 if (Copy->getOpcode() == ISD::CopyToReg) { 2403 // If the copy has a glue operand, we conservatively assume it isn't safe to 2404 // perform a tail call. 2405 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2406 return false; 2407 TCChain = Copy->getOperand(0); 2408 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2409 SDNode *VMov = Copy; 2410 // f64 returned in a pair of GPRs. 2411 SmallPtrSet<SDNode*, 2> Copies; 2412 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2413 UI != UE; ++UI) { 2414 if (UI->getOpcode() != ISD::CopyToReg) 2415 return false; 2416 Copies.insert(*UI); 2417 } 2418 if (Copies.size() > 2) 2419 return false; 2420 2421 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2422 UI != UE; ++UI) { 2423 SDValue UseChain = UI->getOperand(0); 2424 if (Copies.count(UseChain.getNode())) 2425 // Second CopyToReg 2426 Copy = *UI; 2427 else { 2428 // We are at the top of this chain. 2429 // If the copy has a glue operand, we conservatively assume it 2430 // isn't safe to perform a tail call. 2431 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2432 return false; 2433 // First CopyToReg 2434 TCChain = UseChain; 2435 } 2436 } 2437 } else if (Copy->getOpcode() == ISD::BITCAST) { 2438 // f32 returned in a single GPR. 2439 if (!Copy->hasOneUse()) 2440 return false; 2441 Copy = *Copy->use_begin(); 2442 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2443 return false; 2444 // If the copy has a glue operand, we conservatively assume it isn't safe to 2445 // perform a tail call. 2446 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2447 return false; 2448 TCChain = Copy->getOperand(0); 2449 } else { 2450 return false; 2451 } 2452 2453 bool HasRet = false; 2454 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2455 UI != UE; ++UI) { 2456 if (UI->getOpcode() != ARMISD::RET_FLAG && 2457 UI->getOpcode() != ARMISD::INTRET_FLAG) 2458 return false; 2459 HasRet = true; 2460 } 2461 2462 if (!HasRet) 2463 return false; 2464 2465 Chain = TCChain; 2466 return true; 2467 } 2468 2469 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2470 if (!Subtarget->supportsTailCall()) 2471 return false; 2472 2473 auto Attr = 2474 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2475 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2476 return false; 2477 2478 return true; 2479 } 2480 2481 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2482 // and pass the lower and high parts through. 2483 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2484 SDLoc DL(Op); 2485 SDValue WriteValue = Op->getOperand(2); 2486 2487 // This function is only supposed to be called for i64 type argument. 2488 assert(WriteValue.getValueType() == MVT::i64 2489 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2490 2491 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2492 DAG.getConstant(0, DL, MVT::i32)); 2493 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2494 DAG.getConstant(1, DL, MVT::i32)); 2495 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2496 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2497 } 2498 2499 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2500 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2501 // one of the above mentioned nodes. It has to be wrapped because otherwise 2502 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2503 // be used to form addressing mode. These wrapped nodes will be selected 2504 // into MOVi. 2505 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2506 EVT PtrVT = Op.getValueType(); 2507 // FIXME there is no actual debug info here 2508 SDLoc dl(Op); 2509 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2510 SDValue Res; 2511 if (CP->isMachineConstantPoolEntry()) 2512 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2513 CP->getAlignment()); 2514 else 2515 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2516 CP->getAlignment()); 2517 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2518 } 2519 2520 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2521 return MachineJumpTableInfo::EK_Inline; 2522 } 2523 2524 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2525 SelectionDAG &DAG) const { 2526 MachineFunction &MF = DAG.getMachineFunction(); 2527 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2528 unsigned ARMPCLabelIndex = 0; 2529 SDLoc DL(Op); 2530 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2531 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2532 SDValue CPAddr; 2533 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2534 if (!IsPositionIndependent) { 2535 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2536 } else { 2537 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2538 ARMPCLabelIndex = AFI->createPICLabelUId(); 2539 ARMConstantPoolValue *CPV = 2540 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2541 ARMCP::CPBlockAddress, PCAdj); 2542 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2543 } 2544 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2545 SDValue Result = DAG.getLoad( 2546 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2547 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2548 if (!IsPositionIndependent) 2549 return Result; 2550 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2551 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2552 } 2553 2554 /// \brief Convert a TLS address reference into the correct sequence of loads 2555 /// and calls to compute the variable's address for Darwin, and return an 2556 /// SDValue containing the final node. 2557 2558 /// Darwin only has one TLS scheme which must be capable of dealing with the 2559 /// fully general situation, in the worst case. This means: 2560 /// + "extern __thread" declaration. 2561 /// + Defined in a possibly unknown dynamic library. 2562 /// 2563 /// The general system is that each __thread variable has a [3 x i32] descriptor 2564 /// which contains information used by the runtime to calculate the address. The 2565 /// only part of this the compiler needs to know about is the first word, which 2566 /// contains a function pointer that must be called with the address of the 2567 /// entire descriptor in "r0". 2568 /// 2569 /// Since this descriptor may be in a different unit, in general access must 2570 /// proceed along the usual ARM rules. A common sequence to produce is: 2571 /// 2572 /// movw rT1, :lower16:_var$non_lazy_ptr 2573 /// movt rT1, :upper16:_var$non_lazy_ptr 2574 /// ldr r0, [rT1] 2575 /// ldr rT2, [r0] 2576 /// blx rT2 2577 /// [...address now in r0...] 2578 SDValue 2579 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2580 SelectionDAG &DAG) const { 2581 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2582 SDLoc DL(Op); 2583 2584 // First step is to get the address of the actua global symbol. This is where 2585 // the TLS descriptor lives. 2586 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2587 2588 // The first entry in the descriptor is a function pointer that we must call 2589 // to obtain the address of the variable. 2590 SDValue Chain = DAG.getEntryNode(); 2591 SDValue FuncTLVGet = 2592 DAG.getLoad(MVT::i32, DL, Chain, DescAddr, 2593 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2594 /* Alignment = */ 4, MachineMemOperand::MONonTemporal | 2595 MachineMemOperand::MOInvariant); 2596 Chain = FuncTLVGet.getValue(1); 2597 2598 MachineFunction &F = DAG.getMachineFunction(); 2599 MachineFrameInfo &MFI = F.getFrameInfo(); 2600 MFI.setAdjustsStack(true); 2601 2602 // TLS calls preserve all registers except those that absolutely must be 2603 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2604 // silly). 2605 auto TRI = 2606 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2607 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2608 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2609 2610 // Finally, we can make the call. This is just a degenerate version of a 2611 // normal AArch64 call node: r0 takes the address of the descriptor, and 2612 // returns the address of the variable in this thread. 2613 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2614 Chain = 2615 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2616 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2617 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2618 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2619 } 2620 2621 SDValue 2622 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2623 SelectionDAG &DAG) const { 2624 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2625 2626 SDValue Chain = DAG.getEntryNode(); 2627 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2628 SDLoc DL(Op); 2629 2630 // Load the current TEB (thread environment block) 2631 SDValue Ops[] = {Chain, 2632 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2633 DAG.getConstant(15, DL, MVT::i32), 2634 DAG.getConstant(0, DL, MVT::i32), 2635 DAG.getConstant(13, DL, MVT::i32), 2636 DAG.getConstant(0, DL, MVT::i32), 2637 DAG.getConstant(2, DL, MVT::i32)}; 2638 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2639 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2640 2641 SDValue TEB = CurrentTEB.getValue(0); 2642 Chain = CurrentTEB.getValue(1); 2643 2644 // Load the ThreadLocalStoragePointer from the TEB 2645 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2646 SDValue TLSArray = 2647 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2648 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2649 2650 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2651 // offset into the TLSArray. 2652 2653 // Load the TLS index from the C runtime 2654 SDValue TLSIndex = 2655 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2656 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2657 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2658 2659 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2660 DAG.getConstant(2, DL, MVT::i32)); 2661 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2662 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2663 MachinePointerInfo()); 2664 2665 // Get the offset of the start of the .tls section (section base) 2666 const auto *GA = cast<GlobalAddressSDNode>(Op); 2667 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2668 SDValue Offset = DAG.getLoad( 2669 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2670 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2671 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2672 2673 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2674 } 2675 2676 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2677 SDValue 2678 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2679 SelectionDAG &DAG) const { 2680 SDLoc dl(GA); 2681 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2682 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2683 MachineFunction &MF = DAG.getMachineFunction(); 2684 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2685 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2686 ARMConstantPoolValue *CPV = 2687 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2688 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2689 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2690 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2691 Argument = DAG.getLoad( 2692 PtrVT, dl, DAG.getEntryNode(), Argument, 2693 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2694 SDValue Chain = Argument.getValue(1); 2695 2696 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2697 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2698 2699 // call __tls_get_addr. 2700 ArgListTy Args; 2701 ArgListEntry Entry; 2702 Entry.Node = Argument; 2703 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2704 Args.push_back(Entry); 2705 2706 // FIXME: is there useful debug info available here? 2707 TargetLowering::CallLoweringInfo CLI(DAG); 2708 CLI.setDebugLoc(dl).setChain(Chain) 2709 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2710 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2711 2712 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2713 return CallResult.first; 2714 } 2715 2716 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2717 // "local exec" model. 2718 SDValue 2719 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2720 SelectionDAG &DAG, 2721 TLSModel::Model model) const { 2722 const GlobalValue *GV = GA->getGlobal(); 2723 SDLoc dl(GA); 2724 SDValue Offset; 2725 SDValue Chain = DAG.getEntryNode(); 2726 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2727 // Get the Thread Pointer 2728 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2729 2730 if (model == TLSModel::InitialExec) { 2731 MachineFunction &MF = DAG.getMachineFunction(); 2732 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2733 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2734 // Initial exec model. 2735 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2736 ARMConstantPoolValue *CPV = 2737 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2738 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2739 true); 2740 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2741 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2742 Offset = DAG.getLoad( 2743 PtrVT, dl, Chain, Offset, 2744 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2745 Chain = Offset.getValue(1); 2746 2747 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2748 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2749 2750 Offset = DAG.getLoad( 2751 PtrVT, dl, Chain, Offset, 2752 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2753 } else { 2754 // local exec model 2755 assert(model == TLSModel::LocalExec); 2756 ARMConstantPoolValue *CPV = 2757 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2758 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2759 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2760 Offset = DAG.getLoad( 2761 PtrVT, dl, Chain, Offset, 2762 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2763 } 2764 2765 // The address of the thread local variable is the add of the thread 2766 // pointer with the offset of the variable. 2767 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2768 } 2769 2770 SDValue 2771 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2772 if (Subtarget->isTargetDarwin()) 2773 return LowerGlobalTLSAddressDarwin(Op, DAG); 2774 2775 if (Subtarget->isTargetWindows()) 2776 return LowerGlobalTLSAddressWindows(Op, DAG); 2777 2778 // TODO: implement the "local dynamic" model 2779 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2780 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2781 if (DAG.getTarget().Options.EmulatedTLS) 2782 return LowerToTLSEmulatedModel(GA, DAG); 2783 2784 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2785 2786 switch (model) { 2787 case TLSModel::GeneralDynamic: 2788 case TLSModel::LocalDynamic: 2789 return LowerToTLSGeneralDynamicModel(GA, DAG); 2790 case TLSModel::InitialExec: 2791 case TLSModel::LocalExec: 2792 return LowerToTLSExecModels(GA, DAG, model); 2793 } 2794 llvm_unreachable("bogus TLS model"); 2795 } 2796 2797 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2798 SelectionDAG &DAG) const { 2799 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2800 SDLoc dl(Op); 2801 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2802 const TargetMachine &TM = getTargetMachine(); 2803 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 2804 GV = GA->getBaseObject(); 2805 bool IsRO = 2806 (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 2807 isa<Function>(GV); 2808 if (isPositionIndependent()) { 2809 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 2810 2811 MachineFunction &MF = DAG.getMachineFunction(); 2812 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2813 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2814 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2815 SDLoc dl(Op); 2816 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2817 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2818 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2819 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2820 /*AddCurrentAddress=*/UseGOT_PREL); 2821 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2822 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2823 SDValue Result = DAG.getLoad( 2824 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2825 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2826 SDValue Chain = Result.getValue(1); 2827 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2828 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2829 if (UseGOT_PREL) 2830 Result = 2831 DAG.getLoad(PtrVT, dl, Chain, Result, 2832 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2833 return Result; 2834 } else if (Subtarget->isROPI() && IsRO) { 2835 // PC-relative. 2836 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 2837 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 2838 return Result; 2839 } else if (Subtarget->isRWPI() && !IsRO) { 2840 // SB-relative. 2841 ARMConstantPoolValue *CPV = 2842 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 2843 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2844 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2845 SDValue G = DAG.getLoad( 2846 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2847 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2848 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 2849 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, G); 2850 return Result; 2851 } 2852 2853 // If we have T2 ops, we can materialize the address directly via movt/movw 2854 // pair. This is always cheaper. 2855 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2856 ++NumMovwMovt; 2857 // FIXME: Once remat is capable of dealing with instructions with register 2858 // operands, expand this into two nodes. 2859 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2860 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2861 } else { 2862 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2863 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2864 return DAG.getLoad( 2865 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2866 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2867 } 2868 } 2869 2870 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2871 SelectionDAG &DAG) const { 2872 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 2873 "ROPI/RWPI not currently supported for Darwin"); 2874 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2875 SDLoc dl(Op); 2876 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2877 2878 if (Subtarget->useMovt(DAG.getMachineFunction())) 2879 ++NumMovwMovt; 2880 2881 // FIXME: Once remat is capable of dealing with instructions with register 2882 // operands, expand this into multiple nodes 2883 unsigned Wrapper = 2884 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2885 2886 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2887 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2888 2889 if (Subtarget->isGVIndirectSymbol(GV)) 2890 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2891 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2892 return Result; 2893 } 2894 2895 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2896 SelectionDAG &DAG) const { 2897 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2898 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2899 "Windows on ARM expects to use movw/movt"); 2900 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 2901 "ROPI/RWPI not currently supported for Windows"); 2902 2903 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2904 const ARMII::TOF TargetFlags = 2905 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2906 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2907 SDValue Result; 2908 SDLoc DL(Op); 2909 2910 ++NumMovwMovt; 2911 2912 // FIXME: Once remat is capable of dealing with instructions with register 2913 // operands, expand this into two nodes. 2914 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2915 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2916 TargetFlags)); 2917 if (GV->hasDLLImportStorageClass()) 2918 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2919 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2920 return Result; 2921 } 2922 2923 SDValue 2924 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2925 SDLoc dl(Op); 2926 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 2927 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2928 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2929 Op.getOperand(1), Val); 2930 } 2931 2932 SDValue 2933 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2934 SDLoc dl(Op); 2935 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2936 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 2937 } 2938 2939 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 2940 SelectionDAG &DAG) const { 2941 SDLoc dl(Op); 2942 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 2943 Op.getOperand(0)); 2944 } 2945 2946 SDValue 2947 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2948 const ARMSubtarget *Subtarget) const { 2949 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2950 SDLoc dl(Op); 2951 switch (IntNo) { 2952 default: return SDValue(); // Don't custom lower most intrinsics. 2953 case Intrinsic::arm_rbit: { 2954 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2955 "RBIT intrinsic must have i32 type!"); 2956 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 2957 } 2958 case Intrinsic::thread_pointer: { 2959 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2960 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2961 } 2962 case Intrinsic::eh_sjlj_lsda: { 2963 MachineFunction &MF = DAG.getMachineFunction(); 2964 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2965 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2966 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2967 SDValue CPAddr; 2968 bool IsPositionIndependent = isPositionIndependent(); 2969 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 2970 ARMConstantPoolValue *CPV = 2971 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2972 ARMCP::CPLSDA, PCAdj); 2973 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2974 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2975 SDValue Result = DAG.getLoad( 2976 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2977 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2978 2979 if (IsPositionIndependent) { 2980 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2981 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2982 } 2983 return Result; 2984 } 2985 case Intrinsic::arm_neon_vmulls: 2986 case Intrinsic::arm_neon_vmullu: { 2987 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2988 ? ARMISD::VMULLs : ARMISD::VMULLu; 2989 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2990 Op.getOperand(1), Op.getOperand(2)); 2991 } 2992 case Intrinsic::arm_neon_vminnm: 2993 case Intrinsic::arm_neon_vmaxnm: { 2994 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 2995 ? ISD::FMINNUM : ISD::FMAXNUM; 2996 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2997 Op.getOperand(1), Op.getOperand(2)); 2998 } 2999 case Intrinsic::arm_neon_vminu: 3000 case Intrinsic::arm_neon_vmaxu: { 3001 if (Op.getValueType().isFloatingPoint()) 3002 return SDValue(); 3003 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3004 ? ISD::UMIN : ISD::UMAX; 3005 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3006 Op.getOperand(1), Op.getOperand(2)); 3007 } 3008 case Intrinsic::arm_neon_vmins: 3009 case Intrinsic::arm_neon_vmaxs: { 3010 // v{min,max}s is overloaded between signed integers and floats. 3011 if (!Op.getValueType().isFloatingPoint()) { 3012 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3013 ? ISD::SMIN : ISD::SMAX; 3014 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3015 Op.getOperand(1), Op.getOperand(2)); 3016 } 3017 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3018 ? ISD::FMINNAN : ISD::FMAXNAN; 3019 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3020 Op.getOperand(1), Op.getOperand(2)); 3021 } 3022 } 3023 } 3024 3025 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3026 const ARMSubtarget *Subtarget) { 3027 // FIXME: handle "fence singlethread" more efficiently. 3028 SDLoc dl(Op); 3029 if (!Subtarget->hasDataBarrier()) { 3030 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3031 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3032 // here. 3033 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3034 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3035 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3036 DAG.getConstant(0, dl, MVT::i32)); 3037 } 3038 3039 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3040 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3041 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3042 if (Subtarget->isMClass()) { 3043 // Only a full system barrier exists in the M-class architectures. 3044 Domain = ARM_MB::SY; 3045 } else if (Subtarget->preferISHSTBarriers() && 3046 Ord == AtomicOrdering::Release) { 3047 // Swift happens to implement ISHST barriers in a way that's compatible with 3048 // Release semantics but weaker than ISH so we'd be fools not to use 3049 // it. Beware: other processors probably don't! 3050 Domain = ARM_MB::ISHST; 3051 } 3052 3053 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3054 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3055 DAG.getConstant(Domain, dl, MVT::i32)); 3056 } 3057 3058 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3059 const ARMSubtarget *Subtarget) { 3060 // ARM pre v5TE and Thumb1 does not have preload instructions. 3061 if (!(Subtarget->isThumb2() || 3062 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3063 // Just preserve the chain. 3064 return Op.getOperand(0); 3065 3066 SDLoc dl(Op); 3067 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3068 if (!isRead && 3069 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3070 // ARMv7 with MP extension has PLDW. 3071 return Op.getOperand(0); 3072 3073 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3074 if (Subtarget->isThumb()) { 3075 // Invert the bits. 3076 isRead = ~isRead & 1; 3077 isData = ~isData & 1; 3078 } 3079 3080 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3081 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3082 DAG.getConstant(isData, dl, MVT::i32)); 3083 } 3084 3085 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3086 MachineFunction &MF = DAG.getMachineFunction(); 3087 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3088 3089 // vastart just stores the address of the VarArgsFrameIndex slot into the 3090 // memory location argument. 3091 SDLoc dl(Op); 3092 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3093 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3094 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3095 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3096 MachinePointerInfo(SV)); 3097 } 3098 3099 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3100 CCValAssign &NextVA, 3101 SDValue &Root, 3102 SelectionDAG &DAG, 3103 const SDLoc &dl) const { 3104 MachineFunction &MF = DAG.getMachineFunction(); 3105 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3106 3107 const TargetRegisterClass *RC; 3108 if (AFI->isThumb1OnlyFunction()) 3109 RC = &ARM::tGPRRegClass; 3110 else 3111 RC = &ARM::GPRRegClass; 3112 3113 // Transform the arguments stored in physical registers into virtual ones. 3114 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3115 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3116 3117 SDValue ArgValue2; 3118 if (NextVA.isMemLoc()) { 3119 MachineFrameInfo &MFI = MF.getFrameInfo(); 3120 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3121 3122 // Create load node to retrieve arguments from the stack. 3123 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3124 ArgValue2 = DAG.getLoad( 3125 MVT::i32, dl, Root, FIN, 3126 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3127 } else { 3128 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3129 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3130 } 3131 if (!Subtarget->isLittle()) 3132 std::swap (ArgValue, ArgValue2); 3133 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3134 } 3135 3136 // The remaining GPRs hold either the beginning of variable-argument 3137 // data, or the beginning of an aggregate passed by value (usually 3138 // byval). Either way, we allocate stack slots adjacent to the data 3139 // provided by our caller, and store the unallocated registers there. 3140 // If this is a variadic function, the va_list pointer will begin with 3141 // these values; otherwise, this reassembles a (byval) structure that 3142 // was split between registers and memory. 3143 // Return: The frame index registers were stored into. 3144 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3145 const SDLoc &dl, SDValue &Chain, 3146 const Value *OrigArg, 3147 unsigned InRegsParamRecordIdx, 3148 int ArgOffset, unsigned ArgSize) const { 3149 // Currently, two use-cases possible: 3150 // Case #1. Non-var-args function, and we meet first byval parameter. 3151 // Setup first unallocated register as first byval register; 3152 // eat all remained registers 3153 // (these two actions are performed by HandleByVal method). 3154 // Then, here, we initialize stack frame with 3155 // "store-reg" instructions. 3156 // Case #2. Var-args function, that doesn't contain byval parameters. 3157 // The same: eat all remained unallocated registers, 3158 // initialize stack frame. 3159 3160 MachineFunction &MF = DAG.getMachineFunction(); 3161 MachineFrameInfo &MFI = MF.getFrameInfo(); 3162 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3163 unsigned RBegin, REnd; 3164 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3165 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3166 } else { 3167 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3168 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3169 REnd = ARM::R4; 3170 } 3171 3172 if (REnd != RBegin) 3173 ArgOffset = -4 * (ARM::R4 - RBegin); 3174 3175 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3176 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3177 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3178 3179 SmallVector<SDValue, 4> MemOps; 3180 const TargetRegisterClass *RC = 3181 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3182 3183 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3184 unsigned VReg = MF.addLiveIn(Reg, RC); 3185 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3186 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3187 MachinePointerInfo(OrigArg, 4 * i)); 3188 MemOps.push_back(Store); 3189 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3190 } 3191 3192 if (!MemOps.empty()) 3193 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3194 return FrameIndex; 3195 } 3196 3197 // Setup stack frame, the va_list pointer will start from. 3198 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3199 const SDLoc &dl, SDValue &Chain, 3200 unsigned ArgOffset, 3201 unsigned TotalArgRegsSaveSize, 3202 bool ForceMutable) const { 3203 MachineFunction &MF = DAG.getMachineFunction(); 3204 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3205 3206 // Try to store any remaining integer argument regs 3207 // to their spots on the stack so that they may be loaded by dereferencing 3208 // the result of va_next. 3209 // If there is no regs to be stored, just point address after last 3210 // argument passed via stack. 3211 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3212 CCInfo.getInRegsParamsCount(), 3213 CCInfo.getNextStackOffset(), 4); 3214 AFI->setVarArgsFrameIndex(FrameIndex); 3215 } 3216 3217 SDValue ARMTargetLowering::LowerFormalArguments( 3218 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3219 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3220 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3221 MachineFunction &MF = DAG.getMachineFunction(); 3222 MachineFrameInfo &MFI = MF.getFrameInfo(); 3223 3224 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3225 3226 // Assign locations to all of the incoming arguments. 3227 SmallVector<CCValAssign, 16> ArgLocs; 3228 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3229 *DAG.getContext(), Prologue); 3230 CCInfo.AnalyzeFormalArguments(Ins, 3231 CCAssignFnForNode(CallConv, /* Return*/ false, 3232 isVarArg)); 3233 3234 SmallVector<SDValue, 16> ArgValues; 3235 SDValue ArgValue; 3236 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3237 unsigned CurArgIdx = 0; 3238 3239 // Initially ArgRegsSaveSize is zero. 3240 // Then we increase this value each time we meet byval parameter. 3241 // We also increase this value in case of varargs function. 3242 AFI->setArgRegsSaveSize(0); 3243 3244 // Calculate the amount of stack space that we need to allocate to store 3245 // byval and variadic arguments that are passed in registers. 3246 // We need to know this before we allocate the first byval or variadic 3247 // argument, as they will be allocated a stack slot below the CFA (Canonical 3248 // Frame Address, the stack pointer at entry to the function). 3249 unsigned ArgRegBegin = ARM::R4; 3250 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3251 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3252 break; 3253 3254 CCValAssign &VA = ArgLocs[i]; 3255 unsigned Index = VA.getValNo(); 3256 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3257 if (!Flags.isByVal()) 3258 continue; 3259 3260 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3261 unsigned RBegin, REnd; 3262 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3263 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3264 3265 CCInfo.nextInRegsParam(); 3266 } 3267 CCInfo.rewindByValRegsInfo(); 3268 3269 int lastInsIndex = -1; 3270 if (isVarArg && MFI.hasVAStart()) { 3271 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3272 if (RegIdx != array_lengthof(GPRArgRegs)) 3273 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3274 } 3275 3276 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3277 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3278 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3279 3280 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3281 CCValAssign &VA = ArgLocs[i]; 3282 if (Ins[VA.getValNo()].isOrigArg()) { 3283 std::advance(CurOrigArg, 3284 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3285 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3286 } 3287 // Arguments stored in registers. 3288 if (VA.isRegLoc()) { 3289 EVT RegVT = VA.getLocVT(); 3290 3291 if (VA.needsCustom()) { 3292 // f64 and vector types are split up into multiple registers or 3293 // combinations of registers and stack slots. 3294 if (VA.getLocVT() == MVT::v2f64) { 3295 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3296 Chain, DAG, dl); 3297 VA = ArgLocs[++i]; // skip ahead to next loc 3298 SDValue ArgValue2; 3299 if (VA.isMemLoc()) { 3300 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3301 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3302 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3303 MachinePointerInfo::getFixedStack( 3304 DAG.getMachineFunction(), FI)); 3305 } else { 3306 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3307 Chain, DAG, dl); 3308 } 3309 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3310 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3311 ArgValue, ArgValue1, 3312 DAG.getIntPtrConstant(0, dl)); 3313 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3314 ArgValue, ArgValue2, 3315 DAG.getIntPtrConstant(1, dl)); 3316 } else 3317 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3318 3319 } else { 3320 const TargetRegisterClass *RC; 3321 3322 if (RegVT == MVT::f32) 3323 RC = &ARM::SPRRegClass; 3324 else if (RegVT == MVT::f64) 3325 RC = &ARM::DPRRegClass; 3326 else if (RegVT == MVT::v2f64) 3327 RC = &ARM::QPRRegClass; 3328 else if (RegVT == MVT::i32) 3329 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3330 : &ARM::GPRRegClass; 3331 else 3332 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3333 3334 // Transform the arguments in physical registers into virtual ones. 3335 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3336 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3337 } 3338 3339 // If this is an 8 or 16-bit value, it is really passed promoted 3340 // to 32 bits. Insert an assert[sz]ext to capture this, then 3341 // truncate to the right size. 3342 switch (VA.getLocInfo()) { 3343 default: llvm_unreachable("Unknown loc info!"); 3344 case CCValAssign::Full: break; 3345 case CCValAssign::BCvt: 3346 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3347 break; 3348 case CCValAssign::SExt: 3349 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3350 DAG.getValueType(VA.getValVT())); 3351 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3352 break; 3353 case CCValAssign::ZExt: 3354 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3355 DAG.getValueType(VA.getValVT())); 3356 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3357 break; 3358 } 3359 3360 InVals.push_back(ArgValue); 3361 3362 } else { // VA.isRegLoc() 3363 3364 // sanity check 3365 assert(VA.isMemLoc()); 3366 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3367 3368 int index = VA.getValNo(); 3369 3370 // Some Ins[] entries become multiple ArgLoc[] entries. 3371 // Process them only once. 3372 if (index != lastInsIndex) 3373 { 3374 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3375 // FIXME: For now, all byval parameter objects are marked mutable. 3376 // This can be changed with more analysis. 3377 // In case of tail call optimization mark all arguments mutable. 3378 // Since they could be overwritten by lowering of arguments in case of 3379 // a tail call. 3380 if (Flags.isByVal()) { 3381 assert(Ins[index].isOrigArg() && 3382 "Byval arguments cannot be implicit"); 3383 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3384 3385 int FrameIndex = StoreByValRegs( 3386 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3387 VA.getLocMemOffset(), Flags.getByValSize()); 3388 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3389 CCInfo.nextInRegsParam(); 3390 } else { 3391 unsigned FIOffset = VA.getLocMemOffset(); 3392 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3393 FIOffset, true); 3394 3395 // Create load nodes to retrieve arguments from the stack. 3396 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3397 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3398 MachinePointerInfo::getFixedStack( 3399 DAG.getMachineFunction(), FI))); 3400 } 3401 lastInsIndex = index; 3402 } 3403 } 3404 } 3405 3406 // varargs 3407 if (isVarArg && MFI.hasVAStart()) 3408 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3409 CCInfo.getNextStackOffset(), 3410 TotalArgRegsSaveSize); 3411 3412 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3413 3414 return Chain; 3415 } 3416 3417 /// isFloatingPointZero - Return true if this is +0.0. 3418 static bool isFloatingPointZero(SDValue Op) { 3419 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3420 return CFP->getValueAPF().isPosZero(); 3421 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3422 // Maybe this has already been legalized into the constant pool? 3423 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3424 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3425 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3426 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3427 return CFP->getValueAPF().isPosZero(); 3428 } 3429 } else if (Op->getOpcode() == ISD::BITCAST && 3430 Op->getValueType(0) == MVT::f64) { 3431 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3432 // created by LowerConstantFP(). 3433 SDValue BitcastOp = Op->getOperand(0); 3434 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3435 isNullConstant(BitcastOp->getOperand(0))) 3436 return true; 3437 } 3438 return false; 3439 } 3440 3441 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3442 /// the given operands. 3443 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3444 SDValue &ARMcc, SelectionDAG &DAG, 3445 const SDLoc &dl) const { 3446 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3447 unsigned C = RHSC->getZExtValue(); 3448 if (!isLegalICmpImmediate(C)) { 3449 // Constant does not fit, try adjusting it by one? 3450 switch (CC) { 3451 default: break; 3452 case ISD::SETLT: 3453 case ISD::SETGE: 3454 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3455 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3456 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3457 } 3458 break; 3459 case ISD::SETULT: 3460 case ISD::SETUGE: 3461 if (C != 0 && isLegalICmpImmediate(C-1)) { 3462 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3463 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3464 } 3465 break; 3466 case ISD::SETLE: 3467 case ISD::SETGT: 3468 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3469 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3470 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3471 } 3472 break; 3473 case ISD::SETULE: 3474 case ISD::SETUGT: 3475 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3476 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3477 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3478 } 3479 break; 3480 } 3481 } 3482 } 3483 3484 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3485 ARMISD::NodeType CompareType; 3486 switch (CondCode) { 3487 default: 3488 CompareType = ARMISD::CMP; 3489 break; 3490 case ARMCC::EQ: 3491 case ARMCC::NE: 3492 // Uses only Z Flag 3493 CompareType = ARMISD::CMPZ; 3494 break; 3495 } 3496 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3497 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3498 } 3499 3500 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3501 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3502 SelectionDAG &DAG, const SDLoc &dl) const { 3503 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3504 SDValue Cmp; 3505 if (!isFloatingPointZero(RHS)) 3506 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3507 else 3508 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3509 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3510 } 3511 3512 /// duplicateCmp - Glue values can have only one use, so this function 3513 /// duplicates a comparison node. 3514 SDValue 3515 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3516 unsigned Opc = Cmp.getOpcode(); 3517 SDLoc DL(Cmp); 3518 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3519 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3520 3521 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3522 Cmp = Cmp.getOperand(0); 3523 Opc = Cmp.getOpcode(); 3524 if (Opc == ARMISD::CMPFP) 3525 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3526 else { 3527 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3528 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3529 } 3530 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3531 } 3532 3533 std::pair<SDValue, SDValue> 3534 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3535 SDValue &ARMcc) const { 3536 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3537 3538 SDValue Value, OverflowCmp; 3539 SDValue LHS = Op.getOperand(0); 3540 SDValue RHS = Op.getOperand(1); 3541 SDLoc dl(Op); 3542 3543 // FIXME: We are currently always generating CMPs because we don't support 3544 // generating CMN through the backend. This is not as good as the natural 3545 // CMP case because it causes a register dependency and cannot be folded 3546 // later. 3547 3548 switch (Op.getOpcode()) { 3549 default: 3550 llvm_unreachable("Unknown overflow instruction!"); 3551 case ISD::SADDO: 3552 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3553 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3554 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3555 break; 3556 case ISD::UADDO: 3557 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3558 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3559 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3560 break; 3561 case ISD::SSUBO: 3562 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3563 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3564 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3565 break; 3566 case ISD::USUBO: 3567 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3568 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3569 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3570 break; 3571 } // switch (...) 3572 3573 return std::make_pair(Value, OverflowCmp); 3574 } 3575 3576 3577 SDValue 3578 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3579 // Let legalize expand this if it isn't a legal type yet. 3580 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3581 return SDValue(); 3582 3583 SDValue Value, OverflowCmp; 3584 SDValue ARMcc; 3585 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3586 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3587 SDLoc dl(Op); 3588 // We use 0 and 1 as false and true values. 3589 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3590 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3591 EVT VT = Op.getValueType(); 3592 3593 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3594 ARMcc, CCR, OverflowCmp); 3595 3596 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3597 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3598 } 3599 3600 3601 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3602 SDValue Cond = Op.getOperand(0); 3603 SDValue SelectTrue = Op.getOperand(1); 3604 SDValue SelectFalse = Op.getOperand(2); 3605 SDLoc dl(Op); 3606 unsigned Opc = Cond.getOpcode(); 3607 3608 if (Cond.getResNo() == 1 && 3609 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3610 Opc == ISD::USUBO)) { 3611 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3612 return SDValue(); 3613 3614 SDValue Value, OverflowCmp; 3615 SDValue ARMcc; 3616 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3617 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3618 EVT VT = Op.getValueType(); 3619 3620 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3621 OverflowCmp, DAG); 3622 } 3623 3624 // Convert: 3625 // 3626 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3627 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3628 // 3629 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3630 const ConstantSDNode *CMOVTrue = 3631 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3632 const ConstantSDNode *CMOVFalse = 3633 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3634 3635 if (CMOVTrue && CMOVFalse) { 3636 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3637 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3638 3639 SDValue True; 3640 SDValue False; 3641 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3642 True = SelectTrue; 3643 False = SelectFalse; 3644 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3645 True = SelectFalse; 3646 False = SelectTrue; 3647 } 3648 3649 if (True.getNode() && False.getNode()) { 3650 EVT VT = Op.getValueType(); 3651 SDValue ARMcc = Cond.getOperand(2); 3652 SDValue CCR = Cond.getOperand(3); 3653 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3654 assert(True.getValueType() == VT); 3655 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3656 } 3657 } 3658 } 3659 3660 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3661 // undefined bits before doing a full-word comparison with zero. 3662 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3663 DAG.getConstant(1, dl, Cond.getValueType())); 3664 3665 return DAG.getSelectCC(dl, Cond, 3666 DAG.getConstant(0, dl, Cond.getValueType()), 3667 SelectTrue, SelectFalse, ISD::SETNE); 3668 } 3669 3670 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3671 bool &swpCmpOps, bool &swpVselOps) { 3672 // Start by selecting the GE condition code for opcodes that return true for 3673 // 'equality' 3674 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3675 CC == ISD::SETULE) 3676 CondCode = ARMCC::GE; 3677 3678 // and GT for opcodes that return false for 'equality'. 3679 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3680 CC == ISD::SETULT) 3681 CondCode = ARMCC::GT; 3682 3683 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3684 // to swap the compare operands. 3685 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3686 CC == ISD::SETULT) 3687 swpCmpOps = true; 3688 3689 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3690 // If we have an unordered opcode, we need to swap the operands to the VSEL 3691 // instruction (effectively negating the condition). 3692 // 3693 // This also has the effect of swapping which one of 'less' or 'greater' 3694 // returns true, so we also swap the compare operands. It also switches 3695 // whether we return true for 'equality', so we compensate by picking the 3696 // opposite condition code to our original choice. 3697 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3698 CC == ISD::SETUGT) { 3699 swpCmpOps = !swpCmpOps; 3700 swpVselOps = !swpVselOps; 3701 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3702 } 3703 3704 // 'ordered' is 'anything but unordered', so use the VS condition code and 3705 // swap the VSEL operands. 3706 if (CC == ISD::SETO) { 3707 CondCode = ARMCC::VS; 3708 swpVselOps = true; 3709 } 3710 3711 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3712 // code and swap the VSEL operands. 3713 if (CC == ISD::SETUNE) { 3714 CondCode = ARMCC::EQ; 3715 swpVselOps = true; 3716 } 3717 } 3718 3719 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 3720 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3721 SDValue Cmp, SelectionDAG &DAG) const { 3722 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3723 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3724 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3725 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3726 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3727 3728 SDValue TrueLow = TrueVal.getValue(0); 3729 SDValue TrueHigh = TrueVal.getValue(1); 3730 SDValue FalseLow = FalseVal.getValue(0); 3731 SDValue FalseHigh = FalseVal.getValue(1); 3732 3733 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3734 ARMcc, CCR, Cmp); 3735 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3736 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3737 3738 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3739 } else { 3740 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3741 Cmp); 3742 } 3743 } 3744 3745 static bool isGTorGE(ISD::CondCode CC) { 3746 return CC == ISD::SETGT || CC == ISD::SETGE; 3747 } 3748 3749 static bool isLTorLE(ISD::CondCode CC) { 3750 return CC == ISD::SETLT || CC == ISD::SETLE; 3751 } 3752 3753 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 3754 // All of these conditions (and their <= and >= counterparts) will do: 3755 // x < k ? k : x 3756 // x > k ? x : k 3757 // k < x ? x : k 3758 // k > x ? k : x 3759 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 3760 const SDValue TrueVal, const SDValue FalseVal, 3761 const ISD::CondCode CC, const SDValue K) { 3762 return (isGTorGE(CC) && 3763 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 3764 (isLTorLE(CC) && 3765 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 3766 } 3767 3768 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 3769 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 3770 const SDValue TrueVal, const SDValue FalseVal, 3771 const ISD::CondCode CC, const SDValue K) { 3772 return (isGTorGE(CC) && 3773 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 3774 (isLTorLE(CC) && 3775 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 3776 } 3777 3778 // Check if two chained conditionals could be converted into SSAT. 3779 // 3780 // SSAT can replace a set of two conditional selectors that bound a number to an 3781 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 3782 // 3783 // x < -k ? -k : (x > k ? k : x) 3784 // x < -k ? -k : (x < k ? x : k) 3785 // x > -k ? (x > k ? k : x) : -k 3786 // x < k ? (x < -k ? -k : x) : k 3787 // etc. 3788 // 3789 // It returns true if the conversion can be done, false otherwise. 3790 // Additionally, the variable is returned in parameter V and the constant in K. 3791 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 3792 uint64_t &K) { 3793 3794 SDValue LHS1 = Op.getOperand(0); 3795 SDValue RHS1 = Op.getOperand(1); 3796 SDValue TrueVal1 = Op.getOperand(2); 3797 SDValue FalseVal1 = Op.getOperand(3); 3798 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3799 3800 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 3801 if (Op2.getOpcode() != ISD::SELECT_CC) 3802 return false; 3803 3804 SDValue LHS2 = Op2.getOperand(0); 3805 SDValue RHS2 = Op2.getOperand(1); 3806 SDValue TrueVal2 = Op2.getOperand(2); 3807 SDValue FalseVal2 = Op2.getOperand(3); 3808 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 3809 3810 // Find out which are the constants and which are the variables 3811 // in each conditional 3812 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 3813 ? &RHS1 3814 : NULL; 3815 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 3816 ? &RHS2 3817 : NULL; 3818 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 3819 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 3820 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 3821 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 3822 3823 // We must detect cases where the original operations worked with 16- or 3824 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 3825 // must work with sign-extended values but the select operations return 3826 // the original non-extended value. 3827 SDValue V2TmpReg = V2Tmp; 3828 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 3829 V2TmpReg = V2Tmp->getOperand(0); 3830 3831 // Check that the registers and the constants have the correct values 3832 // in both conditionals 3833 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 3834 V2TmpReg != V2) 3835 return false; 3836 3837 // Figure out which conditional is saturating the lower/upper bound. 3838 const SDValue *LowerCheckOp = 3839 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 3840 ? &Op 3841 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2 3842 : NULL; 3843 const SDValue *UpperCheckOp = 3844 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 3845 ? &Op 3846 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2 3847 : NULL; 3848 3849 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 3850 return false; 3851 3852 // Check that the constant in the lower-bound check is 3853 // the opposite of the constant in the upper-bound check 3854 // in 1's complement. 3855 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 3856 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 3857 int64_t PosVal = std::max(Val1, Val2); 3858 3859 if (((Val1 > Val2 && UpperCheckOp == &Op) || 3860 (Val1 < Val2 && UpperCheckOp == &Op2)) && 3861 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 3862 3863 V = V2; 3864 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 3865 return true; 3866 } 3867 3868 return false; 3869 } 3870 3871 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3872 3873 EVT VT = Op.getValueType(); 3874 SDLoc dl(Op); 3875 3876 // Try to convert two saturating conditional selects into a single SSAT 3877 SDValue SatValue; 3878 uint64_t SatConstant; 3879 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 3880 isSaturatingConditional(Op, SatValue, SatConstant)) 3881 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 3882 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 3883 3884 SDValue LHS = Op.getOperand(0); 3885 SDValue RHS = Op.getOperand(1); 3886 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3887 SDValue TrueVal = Op.getOperand(2); 3888 SDValue FalseVal = Op.getOperand(3); 3889 3890 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3891 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3892 dl); 3893 3894 // If softenSetCCOperands only returned one value, we should compare it to 3895 // zero. 3896 if (!RHS.getNode()) { 3897 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3898 CC = ISD::SETNE; 3899 } 3900 } 3901 3902 if (LHS.getValueType() == MVT::i32) { 3903 // Try to generate VSEL on ARMv8. 3904 // The VSEL instruction can't use all the usual ARM condition 3905 // codes: it only has two bits to select the condition code, so it's 3906 // constrained to use only GE, GT, VS and EQ. 3907 // 3908 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3909 // swap the operands of the previous compare instruction (effectively 3910 // inverting the compare condition, swapping 'less' and 'greater') and 3911 // sometimes need to swap the operands to the VSEL (which inverts the 3912 // condition in the sense of firing whenever the previous condition didn't) 3913 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3914 TrueVal.getValueType() == MVT::f64)) { 3915 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3916 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3917 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3918 CC = ISD::getSetCCInverse(CC, true); 3919 std::swap(TrueVal, FalseVal); 3920 } 3921 } 3922 3923 SDValue ARMcc; 3924 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3925 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3926 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3927 } 3928 3929 ARMCC::CondCodes CondCode, CondCode2; 3930 FPCCToARMCC(CC, CondCode, CondCode2); 3931 3932 // Try to generate VMAXNM/VMINNM on ARMv8. 3933 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3934 TrueVal.getValueType() == MVT::f64)) { 3935 bool swpCmpOps = false; 3936 bool swpVselOps = false; 3937 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3938 3939 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3940 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3941 if (swpCmpOps) 3942 std::swap(LHS, RHS); 3943 if (swpVselOps) 3944 std::swap(TrueVal, FalseVal); 3945 } 3946 } 3947 3948 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3949 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3950 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3951 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3952 if (CondCode2 != ARMCC::AL) { 3953 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 3954 // FIXME: Needs another CMP because flag can have but one use. 3955 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3956 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3957 } 3958 return Result; 3959 } 3960 3961 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3962 /// to morph to an integer compare sequence. 3963 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3964 const ARMSubtarget *Subtarget) { 3965 SDNode *N = Op.getNode(); 3966 if (!N->hasOneUse()) 3967 // Otherwise it requires moving the value from fp to integer registers. 3968 return false; 3969 if (!N->getNumValues()) 3970 return false; 3971 EVT VT = Op.getValueType(); 3972 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3973 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3974 // vmrs are very slow, e.g. cortex-a8. 3975 return false; 3976 3977 if (isFloatingPointZero(Op)) { 3978 SeenZero = true; 3979 return true; 3980 } 3981 return ISD::isNormalLoad(N); 3982 } 3983 3984 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3985 if (isFloatingPointZero(Op)) 3986 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 3987 3988 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3989 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 3990 Ld->getPointerInfo(), Ld->getAlignment(), 3991 Ld->getMemOperand()->getFlags()); 3992 3993 llvm_unreachable("Unknown VFP cmp argument!"); 3994 } 3995 3996 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3997 SDValue &RetVal1, SDValue &RetVal2) { 3998 SDLoc dl(Op); 3999 4000 if (isFloatingPointZero(Op)) { 4001 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4002 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4003 return; 4004 } 4005 4006 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4007 SDValue Ptr = Ld->getBasePtr(); 4008 RetVal1 = 4009 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4010 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4011 4012 EVT PtrType = Ptr.getValueType(); 4013 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4014 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4015 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4016 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4017 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4018 Ld->getMemOperand()->getFlags()); 4019 return; 4020 } 4021 4022 llvm_unreachable("Unknown VFP cmp argument!"); 4023 } 4024 4025 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4026 /// f32 and even f64 comparisons to integer ones. 4027 SDValue 4028 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4029 SDValue Chain = Op.getOperand(0); 4030 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4031 SDValue LHS = Op.getOperand(2); 4032 SDValue RHS = Op.getOperand(3); 4033 SDValue Dest = Op.getOperand(4); 4034 SDLoc dl(Op); 4035 4036 bool LHSSeenZero = false; 4037 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4038 bool RHSSeenZero = false; 4039 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4040 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4041 // If unsafe fp math optimization is enabled and there are no other uses of 4042 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4043 // to an integer comparison. 4044 if (CC == ISD::SETOEQ) 4045 CC = ISD::SETEQ; 4046 else if (CC == ISD::SETUNE) 4047 CC = ISD::SETNE; 4048 4049 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4050 SDValue ARMcc; 4051 if (LHS.getValueType() == MVT::f32) { 4052 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4053 bitcastf32Toi32(LHS, DAG), Mask); 4054 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4055 bitcastf32Toi32(RHS, DAG), Mask); 4056 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4057 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4058 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4059 Chain, Dest, ARMcc, CCR, Cmp); 4060 } 4061 4062 SDValue LHS1, LHS2; 4063 SDValue RHS1, RHS2; 4064 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4065 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4066 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4067 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4068 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4069 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4070 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4071 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4072 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4073 } 4074 4075 return SDValue(); 4076 } 4077 4078 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4079 SDValue Chain = Op.getOperand(0); 4080 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4081 SDValue LHS = Op.getOperand(2); 4082 SDValue RHS = Op.getOperand(3); 4083 SDValue Dest = Op.getOperand(4); 4084 SDLoc dl(Op); 4085 4086 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4087 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4088 dl); 4089 4090 // If softenSetCCOperands only returned one value, we should compare it to 4091 // zero. 4092 if (!RHS.getNode()) { 4093 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4094 CC = ISD::SETNE; 4095 } 4096 } 4097 4098 if (LHS.getValueType() == MVT::i32) { 4099 SDValue ARMcc; 4100 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4101 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4102 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4103 Chain, Dest, ARMcc, CCR, Cmp); 4104 } 4105 4106 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4107 4108 if (getTargetMachine().Options.UnsafeFPMath && 4109 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4110 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4111 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4112 return Result; 4113 } 4114 4115 ARMCC::CondCodes CondCode, CondCode2; 4116 FPCCToARMCC(CC, CondCode, CondCode2); 4117 4118 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4119 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 4120 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4121 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4122 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4123 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4124 if (CondCode2 != ARMCC::AL) { 4125 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4126 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4127 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4128 } 4129 return Res; 4130 } 4131 4132 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4133 SDValue Chain = Op.getOperand(0); 4134 SDValue Table = Op.getOperand(1); 4135 SDValue Index = Op.getOperand(2); 4136 SDLoc dl(Op); 4137 4138 EVT PTy = getPointerTy(DAG.getDataLayout()); 4139 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4140 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4141 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4142 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4143 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4144 if (Subtarget->isThumb2()) { 4145 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 4146 // which does another jump to the destination. This also makes it easier 4147 // to translate it to TBB / TBH later. 4148 // FIXME: This might not work if the function is extremely large. 4149 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4150 Addr, Op.getOperand(2), JTI); 4151 } 4152 if (isPositionIndependent() || Subtarget->isROPI()) { 4153 Addr = 4154 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4155 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4156 Chain = Addr.getValue(1); 4157 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4158 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4159 } else { 4160 Addr = 4161 DAG.getLoad(PTy, dl, Chain, Addr, 4162 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4163 Chain = Addr.getValue(1); 4164 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4165 } 4166 } 4167 4168 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4169 EVT VT = Op.getValueType(); 4170 SDLoc dl(Op); 4171 4172 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4173 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4174 return Op; 4175 return DAG.UnrollVectorOp(Op.getNode()); 4176 } 4177 4178 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4179 "Invalid type for custom lowering!"); 4180 if (VT != MVT::v4i16) 4181 return DAG.UnrollVectorOp(Op.getNode()); 4182 4183 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4184 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4185 } 4186 4187 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4188 EVT VT = Op.getValueType(); 4189 if (VT.isVector()) 4190 return LowerVectorFP_TO_INT(Op, DAG); 4191 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4192 RTLIB::Libcall LC; 4193 if (Op.getOpcode() == ISD::FP_TO_SINT) 4194 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4195 Op.getValueType()); 4196 else 4197 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4198 Op.getValueType()); 4199 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4200 /*isSigned*/ false, SDLoc(Op)).first; 4201 } 4202 4203 return Op; 4204 } 4205 4206 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4207 EVT VT = Op.getValueType(); 4208 SDLoc dl(Op); 4209 4210 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4211 if (VT.getVectorElementType() == MVT::f32) 4212 return Op; 4213 return DAG.UnrollVectorOp(Op.getNode()); 4214 } 4215 4216 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4217 "Invalid type for custom lowering!"); 4218 if (VT != MVT::v4f32) 4219 return DAG.UnrollVectorOp(Op.getNode()); 4220 4221 unsigned CastOpc; 4222 unsigned Opc; 4223 switch (Op.getOpcode()) { 4224 default: llvm_unreachable("Invalid opcode!"); 4225 case ISD::SINT_TO_FP: 4226 CastOpc = ISD::SIGN_EXTEND; 4227 Opc = ISD::SINT_TO_FP; 4228 break; 4229 case ISD::UINT_TO_FP: 4230 CastOpc = ISD::ZERO_EXTEND; 4231 Opc = ISD::UINT_TO_FP; 4232 break; 4233 } 4234 4235 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4236 return DAG.getNode(Opc, dl, VT, Op); 4237 } 4238 4239 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4240 EVT VT = Op.getValueType(); 4241 if (VT.isVector()) 4242 return LowerVectorINT_TO_FP(Op, DAG); 4243 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4244 RTLIB::Libcall LC; 4245 if (Op.getOpcode() == ISD::SINT_TO_FP) 4246 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4247 Op.getValueType()); 4248 else 4249 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4250 Op.getValueType()); 4251 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4252 /*isSigned*/ false, SDLoc(Op)).first; 4253 } 4254 4255 return Op; 4256 } 4257 4258 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4259 // Implement fcopysign with a fabs and a conditional fneg. 4260 SDValue Tmp0 = Op.getOperand(0); 4261 SDValue Tmp1 = Op.getOperand(1); 4262 SDLoc dl(Op); 4263 EVT VT = Op.getValueType(); 4264 EVT SrcVT = Tmp1.getValueType(); 4265 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4266 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4267 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4268 4269 if (UseNEON) { 4270 // Use VBSL to copy the sign bit. 4271 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4272 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4273 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4274 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4275 if (VT == MVT::f64) 4276 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4277 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4278 DAG.getConstant(32, dl, MVT::i32)); 4279 else /*if (VT == MVT::f32)*/ 4280 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4281 if (SrcVT == MVT::f32) { 4282 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4283 if (VT == MVT::f64) 4284 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4285 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4286 DAG.getConstant(32, dl, MVT::i32)); 4287 } else if (VT == MVT::f32) 4288 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4289 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4290 DAG.getConstant(32, dl, MVT::i32)); 4291 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4292 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4293 4294 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4295 dl, MVT::i32); 4296 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4297 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4298 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4299 4300 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4301 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4302 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4303 if (VT == MVT::f32) { 4304 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4305 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4306 DAG.getConstant(0, dl, MVT::i32)); 4307 } else { 4308 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4309 } 4310 4311 return Res; 4312 } 4313 4314 // Bitcast operand 1 to i32. 4315 if (SrcVT == MVT::f64) 4316 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4317 Tmp1).getValue(1); 4318 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4319 4320 // Or in the signbit with integer operations. 4321 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4322 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4323 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4324 if (VT == MVT::f32) { 4325 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4326 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4327 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4328 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4329 } 4330 4331 // f64: Or the high part with signbit and then combine two parts. 4332 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4333 Tmp0); 4334 SDValue Lo = Tmp0.getValue(0); 4335 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4336 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4337 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4338 } 4339 4340 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4341 MachineFunction &MF = DAG.getMachineFunction(); 4342 MachineFrameInfo &MFI = MF.getFrameInfo(); 4343 MFI.setReturnAddressIsTaken(true); 4344 4345 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4346 return SDValue(); 4347 4348 EVT VT = Op.getValueType(); 4349 SDLoc dl(Op); 4350 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4351 if (Depth) { 4352 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4353 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4354 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4355 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4356 MachinePointerInfo()); 4357 } 4358 4359 // Return LR, which contains the return address. Mark it an implicit live-in. 4360 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4361 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4362 } 4363 4364 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4365 const ARMBaseRegisterInfo &ARI = 4366 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4367 MachineFunction &MF = DAG.getMachineFunction(); 4368 MachineFrameInfo &MFI = MF.getFrameInfo(); 4369 MFI.setFrameAddressIsTaken(true); 4370 4371 EVT VT = Op.getValueType(); 4372 SDLoc dl(Op); // FIXME probably not meaningful 4373 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4374 unsigned FrameReg = ARI.getFrameRegister(MF); 4375 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4376 while (Depth--) 4377 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4378 MachinePointerInfo()); 4379 return FrameAddr; 4380 } 4381 4382 // FIXME? Maybe this could be a TableGen attribute on some registers and 4383 // this table could be generated automatically from RegInfo. 4384 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4385 SelectionDAG &DAG) const { 4386 unsigned Reg = StringSwitch<unsigned>(RegName) 4387 .Case("sp", ARM::SP) 4388 .Default(0); 4389 if (Reg) 4390 return Reg; 4391 report_fatal_error(Twine("Invalid register name \"" 4392 + StringRef(RegName) + "\".")); 4393 } 4394 4395 // Result is 64 bit value so split into two 32 bit values and return as a 4396 // pair of values. 4397 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4398 SelectionDAG &DAG) { 4399 SDLoc DL(N); 4400 4401 // This function is only supposed to be called for i64 type destination. 4402 assert(N->getValueType(0) == MVT::i64 4403 && "ExpandREAD_REGISTER called for non-i64 type result."); 4404 4405 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4406 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4407 N->getOperand(0), 4408 N->getOperand(1)); 4409 4410 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4411 Read.getValue(1))); 4412 Results.push_back(Read.getOperand(0)); 4413 } 4414 4415 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4416 /// When \p DstVT, the destination type of \p BC, is on the vector 4417 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4418 /// it might be possible to combine them, such that everything stays on the 4419 /// vector register bank. 4420 /// \p return The node that would replace \p BT, if the combine 4421 /// is possible. 4422 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4423 SelectionDAG &DAG) { 4424 SDValue Op = BC->getOperand(0); 4425 EVT DstVT = BC->getValueType(0); 4426 4427 // The only vector instruction that can produce a scalar (remember, 4428 // since the bitcast was about to be turned into VMOVDRR, the source 4429 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4430 // Moreover, we can do this combine only if there is one use. 4431 // Finally, if the destination type is not a vector, there is not 4432 // much point on forcing everything on the vector bank. 4433 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4434 !Op.hasOneUse()) 4435 return SDValue(); 4436 4437 // If the index is not constant, we will introduce an additional 4438 // multiply that will stick. 4439 // Give up in that case. 4440 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4441 if (!Index) 4442 return SDValue(); 4443 unsigned DstNumElt = DstVT.getVectorNumElements(); 4444 4445 // Compute the new index. 4446 const APInt &APIntIndex = Index->getAPIntValue(); 4447 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4448 NewIndex *= APIntIndex; 4449 // Check if the new constant index fits into i32. 4450 if (NewIndex.getBitWidth() > 32) 4451 return SDValue(); 4452 4453 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4454 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4455 SDLoc dl(Op); 4456 SDValue ExtractSrc = Op.getOperand(0); 4457 EVT VecVT = EVT::getVectorVT( 4458 *DAG.getContext(), DstVT.getScalarType(), 4459 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4460 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4461 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4462 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4463 } 4464 4465 /// ExpandBITCAST - If the target supports VFP, this function is called to 4466 /// expand a bit convert where either the source or destination type is i64 to 4467 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4468 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4469 /// vectors), since the legalizer won't know what to do with that. 4470 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4471 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4472 SDLoc dl(N); 4473 SDValue Op = N->getOperand(0); 4474 4475 // This function is only supposed to be called for i64 types, either as the 4476 // source or destination of the bit convert. 4477 EVT SrcVT = Op.getValueType(); 4478 EVT DstVT = N->getValueType(0); 4479 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4480 "ExpandBITCAST called for non-i64 type"); 4481 4482 // Turn i64->f64 into VMOVDRR. 4483 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4484 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4485 // if we can combine the bitcast with its source. 4486 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4487 return Val; 4488 4489 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4490 DAG.getConstant(0, dl, MVT::i32)); 4491 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4492 DAG.getConstant(1, dl, MVT::i32)); 4493 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4494 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4495 } 4496 4497 // Turn f64->i64 into VMOVRRD. 4498 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4499 SDValue Cvt; 4500 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4501 SrcVT.getVectorNumElements() > 1) 4502 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4503 DAG.getVTList(MVT::i32, MVT::i32), 4504 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4505 else 4506 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4507 DAG.getVTList(MVT::i32, MVT::i32), Op); 4508 // Merge the pieces into a single i64 value. 4509 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4510 } 4511 4512 return SDValue(); 4513 } 4514 4515 /// getZeroVector - Returns a vector of specified type with all zero elements. 4516 /// Zero vectors are used to represent vector negation and in those cases 4517 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4518 /// not support i64 elements, so sometimes the zero vectors will need to be 4519 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4520 /// zero vector. 4521 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4522 assert(VT.isVector() && "Expected a vector type"); 4523 // The canonical modified immediate encoding of a zero vector is....0! 4524 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4525 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4526 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4527 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4528 } 4529 4530 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4531 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4532 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4533 SelectionDAG &DAG) const { 4534 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4535 EVT VT = Op.getValueType(); 4536 unsigned VTBits = VT.getSizeInBits(); 4537 SDLoc dl(Op); 4538 SDValue ShOpLo = Op.getOperand(0); 4539 SDValue ShOpHi = Op.getOperand(1); 4540 SDValue ShAmt = Op.getOperand(2); 4541 SDValue ARMcc; 4542 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4543 4544 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4545 4546 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4547 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4548 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4549 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4550 DAG.getConstant(VTBits, dl, MVT::i32)); 4551 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4552 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4553 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4554 4555 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4556 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4557 ISD::SETGE, ARMcc, DAG, dl); 4558 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4559 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4560 CCR, Cmp); 4561 4562 SDValue Ops[2] = { Lo, Hi }; 4563 return DAG.getMergeValues(Ops, dl); 4564 } 4565 4566 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4567 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4568 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4569 SelectionDAG &DAG) const { 4570 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4571 EVT VT = Op.getValueType(); 4572 unsigned VTBits = VT.getSizeInBits(); 4573 SDLoc dl(Op); 4574 SDValue ShOpLo = Op.getOperand(0); 4575 SDValue ShOpHi = Op.getOperand(1); 4576 SDValue ShAmt = Op.getOperand(2); 4577 SDValue ARMcc; 4578 4579 assert(Op.getOpcode() == ISD::SHL_PARTS); 4580 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4581 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4582 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4583 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4584 DAG.getConstant(VTBits, dl, MVT::i32)); 4585 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4586 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4587 4588 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4589 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4590 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4591 ISD::SETGE, ARMcc, DAG, dl); 4592 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4593 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4594 CCR, Cmp); 4595 4596 SDValue Ops[2] = { Lo, Hi }; 4597 return DAG.getMergeValues(Ops, dl); 4598 } 4599 4600 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4601 SelectionDAG &DAG) const { 4602 // The rounding mode is in bits 23:22 of the FPSCR. 4603 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4604 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4605 // so that the shift + and get folded into a bitfield extract. 4606 SDLoc dl(Op); 4607 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4608 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4609 MVT::i32)); 4610 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4611 DAG.getConstant(1U << 22, dl, MVT::i32)); 4612 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4613 DAG.getConstant(22, dl, MVT::i32)); 4614 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4615 DAG.getConstant(3, dl, MVT::i32)); 4616 } 4617 4618 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4619 const ARMSubtarget *ST) { 4620 SDLoc dl(N); 4621 EVT VT = N->getValueType(0); 4622 if (VT.isVector()) { 4623 assert(ST->hasNEON()); 4624 4625 // Compute the least significant set bit: LSB = X & -X 4626 SDValue X = N->getOperand(0); 4627 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4628 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4629 4630 EVT ElemTy = VT.getVectorElementType(); 4631 4632 if (ElemTy == MVT::i8) { 4633 // Compute with: cttz(x) = ctpop(lsb - 1) 4634 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4635 DAG.getTargetConstant(1, dl, ElemTy)); 4636 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4637 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4638 } 4639 4640 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4641 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4642 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4643 unsigned NumBits = ElemTy.getSizeInBits(); 4644 SDValue WidthMinus1 = 4645 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4646 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4647 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4648 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4649 } 4650 4651 // Compute with: cttz(x) = ctpop(lsb - 1) 4652 4653 // Since we can only compute the number of bits in a byte with vcnt.8, we 4654 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4655 // and i64. 4656 4657 // Compute LSB - 1. 4658 SDValue Bits; 4659 if (ElemTy == MVT::i64) { 4660 // Load constant 0xffff'ffff'ffff'ffff to register. 4661 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4662 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4663 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4664 } else { 4665 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4666 DAG.getTargetConstant(1, dl, ElemTy)); 4667 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4668 } 4669 4670 // Count #bits with vcnt.8. 4671 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4672 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4673 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4674 4675 // Gather the #bits with vpaddl (pairwise add.) 4676 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4677 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4678 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4679 Cnt8); 4680 if (ElemTy == MVT::i16) 4681 return Cnt16; 4682 4683 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4684 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4685 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4686 Cnt16); 4687 if (ElemTy == MVT::i32) 4688 return Cnt32; 4689 4690 assert(ElemTy == MVT::i64); 4691 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4692 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4693 Cnt32); 4694 return Cnt64; 4695 } 4696 4697 if (!ST->hasV6T2Ops()) 4698 return SDValue(); 4699 4700 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4701 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4702 } 4703 4704 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4705 /// for each 16-bit element from operand, repeated. The basic idea is to 4706 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4707 /// 4708 /// Trace for v4i16: 4709 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4710 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4711 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4712 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4713 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4714 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4715 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4716 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4717 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4718 EVT VT = N->getValueType(0); 4719 SDLoc DL(N); 4720 4721 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4722 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4723 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4724 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4725 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4726 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4727 } 4728 4729 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4730 /// bit-count for each 16-bit element from the operand. We need slightly 4731 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4732 /// 64/128-bit registers. 4733 /// 4734 /// Trace for v4i16: 4735 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4736 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4737 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4738 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4739 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4740 EVT VT = N->getValueType(0); 4741 SDLoc DL(N); 4742 4743 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4744 if (VT.is64BitVector()) { 4745 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4746 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4747 DAG.getIntPtrConstant(0, DL)); 4748 } else { 4749 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4750 BitCounts, DAG.getIntPtrConstant(0, DL)); 4751 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4752 } 4753 } 4754 4755 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4756 /// bit-count for each 32-bit element from the operand. The idea here is 4757 /// to split the vector into 16-bit elements, leverage the 16-bit count 4758 /// routine, and then combine the results. 4759 /// 4760 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4761 /// input = [v0 v1 ] (vi: 32-bit elements) 4762 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4763 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4764 /// vrev: N0 = [k1 k0 k3 k2 ] 4765 /// [k0 k1 k2 k3 ] 4766 /// N1 =+[k1 k0 k3 k2 ] 4767 /// [k0 k2 k1 k3 ] 4768 /// N2 =+[k1 k3 k0 k2 ] 4769 /// [k0 k2 k1 k3 ] 4770 /// Extended =+[k1 k3 k0 k2 ] 4771 /// [k0 k2 ] 4772 /// Extracted=+[k1 k3 ] 4773 /// 4774 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4775 EVT VT = N->getValueType(0); 4776 SDLoc DL(N); 4777 4778 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4779 4780 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4781 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4782 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4783 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4784 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4785 4786 if (VT.is64BitVector()) { 4787 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4788 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4789 DAG.getIntPtrConstant(0, DL)); 4790 } else { 4791 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4792 DAG.getIntPtrConstant(0, DL)); 4793 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4794 } 4795 } 4796 4797 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4798 const ARMSubtarget *ST) { 4799 EVT VT = N->getValueType(0); 4800 4801 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4802 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4803 VT == MVT::v4i16 || VT == MVT::v8i16) && 4804 "Unexpected type for custom ctpop lowering"); 4805 4806 if (VT.getVectorElementType() == MVT::i32) 4807 return lowerCTPOP32BitElements(N, DAG); 4808 else 4809 return lowerCTPOP16BitElements(N, DAG); 4810 } 4811 4812 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4813 const ARMSubtarget *ST) { 4814 EVT VT = N->getValueType(0); 4815 SDLoc dl(N); 4816 4817 if (!VT.isVector()) 4818 return SDValue(); 4819 4820 // Lower vector shifts on NEON to use VSHL. 4821 assert(ST->hasNEON() && "unexpected vector shift"); 4822 4823 // Left shifts translate directly to the vshiftu intrinsic. 4824 if (N->getOpcode() == ISD::SHL) 4825 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4826 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4827 MVT::i32), 4828 N->getOperand(0), N->getOperand(1)); 4829 4830 assert((N->getOpcode() == ISD::SRA || 4831 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4832 4833 // NEON uses the same intrinsics for both left and right shifts. For 4834 // right shifts, the shift amounts are negative, so negate the vector of 4835 // shift amounts. 4836 EVT ShiftVT = N->getOperand(1).getValueType(); 4837 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4838 getZeroVector(ShiftVT, DAG, dl), 4839 N->getOperand(1)); 4840 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4841 Intrinsic::arm_neon_vshifts : 4842 Intrinsic::arm_neon_vshiftu); 4843 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4844 DAG.getConstant(vshiftInt, dl, MVT::i32), 4845 N->getOperand(0), NegatedCount); 4846 } 4847 4848 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4849 const ARMSubtarget *ST) { 4850 EVT VT = N->getValueType(0); 4851 SDLoc dl(N); 4852 4853 // We can get here for a node like i32 = ISD::SHL i32, i64 4854 if (VT != MVT::i64) 4855 return SDValue(); 4856 4857 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4858 "Unknown shift to lower!"); 4859 4860 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4861 if (!isOneConstant(N->getOperand(1))) 4862 return SDValue(); 4863 4864 // If we are in thumb mode, we don't have RRX. 4865 if (ST->isThumb1Only()) return SDValue(); 4866 4867 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4868 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4869 DAG.getConstant(0, dl, MVT::i32)); 4870 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4871 DAG.getConstant(1, dl, MVT::i32)); 4872 4873 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4874 // captures the result into a carry flag. 4875 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4876 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4877 4878 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4879 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4880 4881 // Merge the pieces into a single i64 value. 4882 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4883 } 4884 4885 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4886 SDValue TmpOp0, TmpOp1; 4887 bool Invert = false; 4888 bool Swap = false; 4889 unsigned Opc = 0; 4890 4891 SDValue Op0 = Op.getOperand(0); 4892 SDValue Op1 = Op.getOperand(1); 4893 SDValue CC = Op.getOperand(2); 4894 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 4895 EVT VT = Op.getValueType(); 4896 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4897 SDLoc dl(Op); 4898 4899 if (CmpVT.getVectorElementType() == MVT::i64) 4900 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 4901 // but it's possible that our operands are 64-bit but our result is 32-bit. 4902 // Bail in this case. 4903 return SDValue(); 4904 4905 if (Op1.getValueType().isFloatingPoint()) { 4906 switch (SetCCOpcode) { 4907 default: llvm_unreachable("Illegal FP comparison"); 4908 case ISD::SETUNE: 4909 case ISD::SETNE: Invert = true; // Fallthrough 4910 case ISD::SETOEQ: 4911 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4912 case ISD::SETOLT: 4913 case ISD::SETLT: Swap = true; // Fallthrough 4914 case ISD::SETOGT: 4915 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4916 case ISD::SETOLE: 4917 case ISD::SETLE: Swap = true; // Fallthrough 4918 case ISD::SETOGE: 4919 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4920 case ISD::SETUGE: Swap = true; // Fallthrough 4921 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4922 case ISD::SETUGT: Swap = true; // Fallthrough 4923 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4924 case ISD::SETUEQ: Invert = true; // Fallthrough 4925 case ISD::SETONE: 4926 // Expand this to (OLT | OGT). 4927 TmpOp0 = Op0; 4928 TmpOp1 = Op1; 4929 Opc = ISD::OR; 4930 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4931 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 4932 break; 4933 case ISD::SETUO: Invert = true; // Fallthrough 4934 case ISD::SETO: 4935 // Expand this to (OLT | OGE). 4936 TmpOp0 = Op0; 4937 TmpOp1 = Op1; 4938 Opc = ISD::OR; 4939 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4940 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 4941 break; 4942 } 4943 } else { 4944 // Integer comparisons. 4945 switch (SetCCOpcode) { 4946 default: llvm_unreachable("Illegal integer comparison"); 4947 case ISD::SETNE: Invert = true; 4948 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4949 case ISD::SETLT: Swap = true; 4950 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4951 case ISD::SETLE: Swap = true; 4952 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4953 case ISD::SETULT: Swap = true; 4954 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4955 case ISD::SETULE: Swap = true; 4956 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4957 } 4958 4959 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4960 if (Opc == ARMISD::VCEQ) { 4961 4962 SDValue AndOp; 4963 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4964 AndOp = Op0; 4965 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4966 AndOp = Op1; 4967 4968 // Ignore bitconvert. 4969 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4970 AndOp = AndOp.getOperand(0); 4971 4972 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4973 Opc = ARMISD::VTST; 4974 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 4975 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 4976 Invert = !Invert; 4977 } 4978 } 4979 } 4980 4981 if (Swap) 4982 std::swap(Op0, Op1); 4983 4984 // If one of the operands is a constant vector zero, attempt to fold the 4985 // comparison to a specialized compare-against-zero form. 4986 SDValue SingleOp; 4987 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4988 SingleOp = Op0; 4989 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4990 if (Opc == ARMISD::VCGE) 4991 Opc = ARMISD::VCLEZ; 4992 else if (Opc == ARMISD::VCGT) 4993 Opc = ARMISD::VCLTZ; 4994 SingleOp = Op1; 4995 } 4996 4997 SDValue Result; 4998 if (SingleOp.getNode()) { 4999 switch (Opc) { 5000 case ARMISD::VCEQ: 5001 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5002 case ARMISD::VCGE: 5003 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5004 case ARMISD::VCLEZ: 5005 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5006 case ARMISD::VCGT: 5007 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5008 case ARMISD::VCLTZ: 5009 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5010 default: 5011 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5012 } 5013 } else { 5014 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5015 } 5016 5017 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5018 5019 if (Invert) 5020 Result = DAG.getNOT(dl, Result, VT); 5021 5022 return Result; 5023 } 5024 5025 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5026 SDValue LHS = Op.getOperand(0); 5027 SDValue RHS = Op.getOperand(1); 5028 SDValue Carry = Op.getOperand(2); 5029 SDValue Cond = Op.getOperand(3); 5030 SDLoc DL(Op); 5031 5032 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5033 5034 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5035 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5036 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5037 5038 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5039 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5040 SDValue ARMcc = DAG.getConstant( 5041 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5042 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5043 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5044 Cmp.getValue(1), SDValue()); 5045 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5046 CCR, Chain.getValue(1)); 5047 } 5048 5049 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5050 /// valid vector constant for a NEON instruction with a "modified immediate" 5051 /// operand (e.g., VMOV). If so, return the encoded value. 5052 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5053 unsigned SplatBitSize, SelectionDAG &DAG, 5054 const SDLoc &dl, EVT &VT, bool is128Bits, 5055 NEONModImmType type) { 5056 unsigned OpCmode, Imm; 5057 5058 // SplatBitSize is set to the smallest size that splats the vector, so a 5059 // zero vector will always have SplatBitSize == 8. However, NEON modified 5060 // immediate instructions others than VMOV do not support the 8-bit encoding 5061 // of a zero vector, and the default encoding of zero is supposed to be the 5062 // 32-bit version. 5063 if (SplatBits == 0) 5064 SplatBitSize = 32; 5065 5066 switch (SplatBitSize) { 5067 case 8: 5068 if (type != VMOVModImm) 5069 return SDValue(); 5070 // Any 1-byte value is OK. Op=0, Cmode=1110. 5071 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5072 OpCmode = 0xe; 5073 Imm = SplatBits; 5074 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5075 break; 5076 5077 case 16: 5078 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5079 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5080 if ((SplatBits & ~0xff) == 0) { 5081 // Value = 0x00nn: Op=x, Cmode=100x. 5082 OpCmode = 0x8; 5083 Imm = SplatBits; 5084 break; 5085 } 5086 if ((SplatBits & ~0xff00) == 0) { 5087 // Value = 0xnn00: Op=x, Cmode=101x. 5088 OpCmode = 0xa; 5089 Imm = SplatBits >> 8; 5090 break; 5091 } 5092 return SDValue(); 5093 5094 case 32: 5095 // NEON's 32-bit VMOV supports splat values where: 5096 // * only one byte is nonzero, or 5097 // * the least significant byte is 0xff and the second byte is nonzero, or 5098 // * the least significant 2 bytes are 0xff and the third is nonzero. 5099 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5100 if ((SplatBits & ~0xff) == 0) { 5101 // Value = 0x000000nn: Op=x, Cmode=000x. 5102 OpCmode = 0; 5103 Imm = SplatBits; 5104 break; 5105 } 5106 if ((SplatBits & ~0xff00) == 0) { 5107 // Value = 0x0000nn00: Op=x, Cmode=001x. 5108 OpCmode = 0x2; 5109 Imm = SplatBits >> 8; 5110 break; 5111 } 5112 if ((SplatBits & ~0xff0000) == 0) { 5113 // Value = 0x00nn0000: Op=x, Cmode=010x. 5114 OpCmode = 0x4; 5115 Imm = SplatBits >> 16; 5116 break; 5117 } 5118 if ((SplatBits & ~0xff000000) == 0) { 5119 // Value = 0xnn000000: Op=x, Cmode=011x. 5120 OpCmode = 0x6; 5121 Imm = SplatBits >> 24; 5122 break; 5123 } 5124 5125 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5126 if (type == OtherModImm) return SDValue(); 5127 5128 if ((SplatBits & ~0xffff) == 0 && 5129 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5130 // Value = 0x0000nnff: Op=x, Cmode=1100. 5131 OpCmode = 0xc; 5132 Imm = SplatBits >> 8; 5133 break; 5134 } 5135 5136 if ((SplatBits & ~0xffffff) == 0 && 5137 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5138 // Value = 0x00nnffff: Op=x, Cmode=1101. 5139 OpCmode = 0xd; 5140 Imm = SplatBits >> 16; 5141 break; 5142 } 5143 5144 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5145 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5146 // VMOV.I32. A (very) minor optimization would be to replicate the value 5147 // and fall through here to test for a valid 64-bit splat. But, then the 5148 // caller would also need to check and handle the change in size. 5149 return SDValue(); 5150 5151 case 64: { 5152 if (type != VMOVModImm) 5153 return SDValue(); 5154 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5155 uint64_t BitMask = 0xff; 5156 uint64_t Val = 0; 5157 unsigned ImmMask = 1; 5158 Imm = 0; 5159 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5160 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5161 Val |= BitMask; 5162 Imm |= ImmMask; 5163 } else if ((SplatBits & BitMask) != 0) { 5164 return SDValue(); 5165 } 5166 BitMask <<= 8; 5167 ImmMask <<= 1; 5168 } 5169 5170 if (DAG.getDataLayout().isBigEndian()) 5171 // swap higher and lower 32 bit word 5172 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5173 5174 // Op=1, Cmode=1110. 5175 OpCmode = 0x1e; 5176 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5177 break; 5178 } 5179 5180 default: 5181 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5182 } 5183 5184 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5185 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5186 } 5187 5188 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5189 const ARMSubtarget *ST) const { 5190 if (!ST->hasVFP3()) 5191 return SDValue(); 5192 5193 bool IsDouble = Op.getValueType() == MVT::f64; 5194 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5195 5196 // Use the default (constant pool) lowering for double constants when we have 5197 // an SP-only FPU 5198 if (IsDouble && Subtarget->isFPOnlySP()) 5199 return SDValue(); 5200 5201 // Try splatting with a VMOV.f32... 5202 const APFloat &FPVal = CFP->getValueAPF(); 5203 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5204 5205 if (ImmVal != -1) { 5206 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5207 // We have code in place to select a valid ConstantFP already, no need to 5208 // do any mangling. 5209 return Op; 5210 } 5211 5212 // It's a float and we are trying to use NEON operations where 5213 // possible. Lower it to a splat followed by an extract. 5214 SDLoc DL(Op); 5215 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5216 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5217 NewVal); 5218 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5219 DAG.getConstant(0, DL, MVT::i32)); 5220 } 5221 5222 // The rest of our options are NEON only, make sure that's allowed before 5223 // proceeding.. 5224 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5225 return SDValue(); 5226 5227 EVT VMovVT; 5228 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5229 5230 // It wouldn't really be worth bothering for doubles except for one very 5231 // important value, which does happen to match: 0.0. So make sure we don't do 5232 // anything stupid. 5233 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5234 return SDValue(); 5235 5236 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5237 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5238 VMovVT, false, VMOVModImm); 5239 if (NewVal != SDValue()) { 5240 SDLoc DL(Op); 5241 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5242 NewVal); 5243 if (IsDouble) 5244 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5245 5246 // It's a float: cast and extract a vector element. 5247 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5248 VecConstant); 5249 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5250 DAG.getConstant(0, DL, MVT::i32)); 5251 } 5252 5253 // Finally, try a VMVN.i32 5254 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5255 false, VMVNModImm); 5256 if (NewVal != SDValue()) { 5257 SDLoc DL(Op); 5258 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5259 5260 if (IsDouble) 5261 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5262 5263 // It's a float: cast and extract a vector element. 5264 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5265 VecConstant); 5266 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5267 DAG.getConstant(0, DL, MVT::i32)); 5268 } 5269 5270 return SDValue(); 5271 } 5272 5273 // check if an VEXT instruction can handle the shuffle mask when the 5274 // vector sources of the shuffle are the same. 5275 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5276 unsigned NumElts = VT.getVectorNumElements(); 5277 5278 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5279 if (M[0] < 0) 5280 return false; 5281 5282 Imm = M[0]; 5283 5284 // If this is a VEXT shuffle, the immediate value is the index of the first 5285 // element. The other shuffle indices must be the successive elements after 5286 // the first one. 5287 unsigned ExpectedElt = Imm; 5288 for (unsigned i = 1; i < NumElts; ++i) { 5289 // Increment the expected index. If it wraps around, just follow it 5290 // back to index zero and keep going. 5291 ++ExpectedElt; 5292 if (ExpectedElt == NumElts) 5293 ExpectedElt = 0; 5294 5295 if (M[i] < 0) continue; // ignore UNDEF indices 5296 if (ExpectedElt != static_cast<unsigned>(M[i])) 5297 return false; 5298 } 5299 5300 return true; 5301 } 5302 5303 5304 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5305 bool &ReverseVEXT, unsigned &Imm) { 5306 unsigned NumElts = VT.getVectorNumElements(); 5307 ReverseVEXT = false; 5308 5309 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5310 if (M[0] < 0) 5311 return false; 5312 5313 Imm = M[0]; 5314 5315 // If this is a VEXT shuffle, the immediate value is the index of the first 5316 // element. The other shuffle indices must be the successive elements after 5317 // the first one. 5318 unsigned ExpectedElt = Imm; 5319 for (unsigned i = 1; i < NumElts; ++i) { 5320 // Increment the expected index. If it wraps around, it may still be 5321 // a VEXT but the source vectors must be swapped. 5322 ExpectedElt += 1; 5323 if (ExpectedElt == NumElts * 2) { 5324 ExpectedElt = 0; 5325 ReverseVEXT = true; 5326 } 5327 5328 if (M[i] < 0) continue; // ignore UNDEF indices 5329 if (ExpectedElt != static_cast<unsigned>(M[i])) 5330 return false; 5331 } 5332 5333 // Adjust the index value if the source operands will be swapped. 5334 if (ReverseVEXT) 5335 Imm -= NumElts; 5336 5337 return true; 5338 } 5339 5340 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5341 /// instruction with the specified blocksize. (The order of the elements 5342 /// within each block of the vector is reversed.) 5343 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5344 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5345 "Only possible block sizes for VREV are: 16, 32, 64"); 5346 5347 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5348 if (EltSz == 64) 5349 return false; 5350 5351 unsigned NumElts = VT.getVectorNumElements(); 5352 unsigned BlockElts = M[0] + 1; 5353 // If the first shuffle index is UNDEF, be optimistic. 5354 if (M[0] < 0) 5355 BlockElts = BlockSize / EltSz; 5356 5357 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5358 return false; 5359 5360 for (unsigned i = 0; i < NumElts; ++i) { 5361 if (M[i] < 0) continue; // ignore UNDEF indices 5362 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5363 return false; 5364 } 5365 5366 return true; 5367 } 5368 5369 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5370 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5371 // range, then 0 is placed into the resulting vector. So pretty much any mask 5372 // of 8 elements can work here. 5373 return VT == MVT::v8i8 && M.size() == 8; 5374 } 5375 5376 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5377 // checking that pairs of elements in the shuffle mask represent the same index 5378 // in each vector, incrementing the expected index by 2 at each step. 5379 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5380 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5381 // v2={e,f,g,h} 5382 // WhichResult gives the offset for each element in the mask based on which 5383 // of the two results it belongs to. 5384 // 5385 // The transpose can be represented either as: 5386 // result1 = shufflevector v1, v2, result1_shuffle_mask 5387 // result2 = shufflevector v1, v2, result2_shuffle_mask 5388 // where v1/v2 and the shuffle masks have the same number of elements 5389 // (here WhichResult (see below) indicates which result is being checked) 5390 // 5391 // or as: 5392 // results = shufflevector v1, v2, shuffle_mask 5393 // where both results are returned in one vector and the shuffle mask has twice 5394 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5395 // want to check the low half and high half of the shuffle mask as if it were 5396 // the other case 5397 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5398 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5399 if (EltSz == 64) 5400 return false; 5401 5402 unsigned NumElts = VT.getVectorNumElements(); 5403 if (M.size() != NumElts && M.size() != NumElts*2) 5404 return false; 5405 5406 // If the mask is twice as long as the input vector then we need to check the 5407 // upper and lower parts of the mask with a matching value for WhichResult 5408 // FIXME: A mask with only even values will be rejected in case the first 5409 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5410 // M[0] is used to determine WhichResult 5411 for (unsigned i = 0; i < M.size(); i += NumElts) { 5412 if (M.size() == NumElts * 2) 5413 WhichResult = i / NumElts; 5414 else 5415 WhichResult = M[i] == 0 ? 0 : 1; 5416 for (unsigned j = 0; j < NumElts; j += 2) { 5417 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5418 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5419 return false; 5420 } 5421 } 5422 5423 if (M.size() == NumElts*2) 5424 WhichResult = 0; 5425 5426 return true; 5427 } 5428 5429 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5430 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5431 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5432 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5433 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5434 if (EltSz == 64) 5435 return false; 5436 5437 unsigned NumElts = VT.getVectorNumElements(); 5438 if (M.size() != NumElts && M.size() != NumElts*2) 5439 return false; 5440 5441 for (unsigned i = 0; i < M.size(); i += NumElts) { 5442 if (M.size() == NumElts * 2) 5443 WhichResult = i / NumElts; 5444 else 5445 WhichResult = M[i] == 0 ? 0 : 1; 5446 for (unsigned j = 0; j < NumElts; j += 2) { 5447 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5448 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5449 return false; 5450 } 5451 } 5452 5453 if (M.size() == NumElts*2) 5454 WhichResult = 0; 5455 5456 return true; 5457 } 5458 5459 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5460 // that the mask elements are either all even and in steps of size 2 or all odd 5461 // and in steps of size 2. 5462 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5463 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5464 // v2={e,f,g,h} 5465 // Requires similar checks to that of isVTRNMask with 5466 // respect the how results are returned. 5467 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5468 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5469 if (EltSz == 64) 5470 return false; 5471 5472 unsigned NumElts = VT.getVectorNumElements(); 5473 if (M.size() != NumElts && M.size() != NumElts*2) 5474 return false; 5475 5476 for (unsigned i = 0; i < M.size(); i += NumElts) { 5477 WhichResult = M[i] == 0 ? 0 : 1; 5478 for (unsigned j = 0; j < NumElts; ++j) { 5479 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5480 return false; 5481 } 5482 } 5483 5484 if (M.size() == NumElts*2) 5485 WhichResult = 0; 5486 5487 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5488 if (VT.is64BitVector() && EltSz == 32) 5489 return false; 5490 5491 return true; 5492 } 5493 5494 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5495 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5496 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5497 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5498 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5499 if (EltSz == 64) 5500 return false; 5501 5502 unsigned NumElts = VT.getVectorNumElements(); 5503 if (M.size() != NumElts && M.size() != NumElts*2) 5504 return false; 5505 5506 unsigned Half = NumElts / 2; 5507 for (unsigned i = 0; i < M.size(); i += NumElts) { 5508 WhichResult = M[i] == 0 ? 0 : 1; 5509 for (unsigned j = 0; j < NumElts; j += Half) { 5510 unsigned Idx = WhichResult; 5511 for (unsigned k = 0; k < Half; ++k) { 5512 int MIdx = M[i + j + k]; 5513 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5514 return false; 5515 Idx += 2; 5516 } 5517 } 5518 } 5519 5520 if (M.size() == NumElts*2) 5521 WhichResult = 0; 5522 5523 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5524 if (VT.is64BitVector() && EltSz == 32) 5525 return false; 5526 5527 return true; 5528 } 5529 5530 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5531 // that pairs of elements of the shufflemask represent the same index in each 5532 // vector incrementing sequentially through the vectors. 5533 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5534 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5535 // v2={e,f,g,h} 5536 // Requires similar checks to that of isVTRNMask with respect the how results 5537 // are returned. 5538 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5539 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5540 if (EltSz == 64) 5541 return false; 5542 5543 unsigned NumElts = VT.getVectorNumElements(); 5544 if (M.size() != NumElts && M.size() != NumElts*2) 5545 return false; 5546 5547 for (unsigned i = 0; i < M.size(); i += NumElts) { 5548 WhichResult = M[i] == 0 ? 0 : 1; 5549 unsigned Idx = WhichResult * NumElts / 2; 5550 for (unsigned j = 0; j < NumElts; j += 2) { 5551 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5552 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5553 return false; 5554 Idx += 1; 5555 } 5556 } 5557 5558 if (M.size() == NumElts*2) 5559 WhichResult = 0; 5560 5561 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5562 if (VT.is64BitVector() && EltSz == 32) 5563 return false; 5564 5565 return true; 5566 } 5567 5568 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5569 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5570 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5571 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5572 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5573 if (EltSz == 64) 5574 return false; 5575 5576 unsigned NumElts = VT.getVectorNumElements(); 5577 if (M.size() != NumElts && M.size() != NumElts*2) 5578 return false; 5579 5580 for (unsigned i = 0; i < M.size(); i += NumElts) { 5581 WhichResult = M[i] == 0 ? 0 : 1; 5582 unsigned Idx = WhichResult * NumElts / 2; 5583 for (unsigned j = 0; j < NumElts; j += 2) { 5584 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5585 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5586 return false; 5587 Idx += 1; 5588 } 5589 } 5590 5591 if (M.size() == NumElts*2) 5592 WhichResult = 0; 5593 5594 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5595 if (VT.is64BitVector() && EltSz == 32) 5596 return false; 5597 5598 return true; 5599 } 5600 5601 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5602 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5603 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5604 unsigned &WhichResult, 5605 bool &isV_UNDEF) { 5606 isV_UNDEF = false; 5607 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5608 return ARMISD::VTRN; 5609 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5610 return ARMISD::VUZP; 5611 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5612 return ARMISD::VZIP; 5613 5614 isV_UNDEF = true; 5615 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5616 return ARMISD::VTRN; 5617 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5618 return ARMISD::VUZP; 5619 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5620 return ARMISD::VZIP; 5621 5622 return 0; 5623 } 5624 5625 /// \return true if this is a reverse operation on an vector. 5626 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5627 unsigned NumElts = VT.getVectorNumElements(); 5628 // Make sure the mask has the right size. 5629 if (NumElts != M.size()) 5630 return false; 5631 5632 // Look for <15, ..., 3, -1, 1, 0>. 5633 for (unsigned i = 0; i != NumElts; ++i) 5634 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5635 return false; 5636 5637 return true; 5638 } 5639 5640 // If N is an integer constant that can be moved into a register in one 5641 // instruction, return an SDValue of such a constant (will become a MOV 5642 // instruction). Otherwise return null. 5643 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5644 const ARMSubtarget *ST, const SDLoc &dl) { 5645 uint64_t Val; 5646 if (!isa<ConstantSDNode>(N)) 5647 return SDValue(); 5648 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5649 5650 if (ST->isThumb1Only()) { 5651 if (Val <= 255 || ~Val <= 255) 5652 return DAG.getConstant(Val, dl, MVT::i32); 5653 } else { 5654 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5655 return DAG.getConstant(Val, dl, MVT::i32); 5656 } 5657 return SDValue(); 5658 } 5659 5660 // If this is a case we can't handle, return null and let the default 5661 // expansion code take care of it. 5662 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5663 const ARMSubtarget *ST) const { 5664 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5665 SDLoc dl(Op); 5666 EVT VT = Op.getValueType(); 5667 5668 APInt SplatBits, SplatUndef; 5669 unsigned SplatBitSize; 5670 bool HasAnyUndefs; 5671 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5672 if (SplatBitSize <= 64) { 5673 // Check if an immediate VMOV works. 5674 EVT VmovVT; 5675 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5676 SplatUndef.getZExtValue(), SplatBitSize, 5677 DAG, dl, VmovVT, VT.is128BitVector(), 5678 VMOVModImm); 5679 if (Val.getNode()) { 5680 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5681 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5682 } 5683 5684 // Try an immediate VMVN. 5685 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5686 Val = isNEONModifiedImm(NegatedImm, 5687 SplatUndef.getZExtValue(), SplatBitSize, 5688 DAG, dl, VmovVT, VT.is128BitVector(), 5689 VMVNModImm); 5690 if (Val.getNode()) { 5691 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5692 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5693 } 5694 5695 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5696 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5697 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5698 if (ImmVal != -1) { 5699 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5700 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5701 } 5702 } 5703 } 5704 } 5705 5706 // Scan through the operands to see if only one value is used. 5707 // 5708 // As an optimisation, even if more than one value is used it may be more 5709 // profitable to splat with one value then change some lanes. 5710 // 5711 // Heuristically we decide to do this if the vector has a "dominant" value, 5712 // defined as splatted to more than half of the lanes. 5713 unsigned NumElts = VT.getVectorNumElements(); 5714 bool isOnlyLowElement = true; 5715 bool usesOnlyOneValue = true; 5716 bool hasDominantValue = false; 5717 bool isConstant = true; 5718 5719 // Map of the number of times a particular SDValue appears in the 5720 // element list. 5721 DenseMap<SDValue, unsigned> ValueCounts; 5722 SDValue Value; 5723 for (unsigned i = 0; i < NumElts; ++i) { 5724 SDValue V = Op.getOperand(i); 5725 if (V.isUndef()) 5726 continue; 5727 if (i > 0) 5728 isOnlyLowElement = false; 5729 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5730 isConstant = false; 5731 5732 ValueCounts.insert(std::make_pair(V, 0)); 5733 unsigned &Count = ValueCounts[V]; 5734 5735 // Is this value dominant? (takes up more than half of the lanes) 5736 if (++Count > (NumElts / 2)) { 5737 hasDominantValue = true; 5738 Value = V; 5739 } 5740 } 5741 if (ValueCounts.size() != 1) 5742 usesOnlyOneValue = false; 5743 if (!Value.getNode() && ValueCounts.size() > 0) 5744 Value = ValueCounts.begin()->first; 5745 5746 if (ValueCounts.size() == 0) 5747 return DAG.getUNDEF(VT); 5748 5749 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5750 // Keep going if we are hitting this case. 5751 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5752 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5753 5754 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5755 5756 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5757 // i32 and try again. 5758 if (hasDominantValue && EltSize <= 32) { 5759 if (!isConstant) { 5760 SDValue N; 5761 5762 // If we are VDUPing a value that comes directly from a vector, that will 5763 // cause an unnecessary move to and from a GPR, where instead we could 5764 // just use VDUPLANE. We can only do this if the lane being extracted 5765 // is at a constant index, as the VDUP from lane instructions only have 5766 // constant-index forms. 5767 ConstantSDNode *constIndex; 5768 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5769 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5770 // We need to create a new undef vector to use for the VDUPLANE if the 5771 // size of the vector from which we get the value is different than the 5772 // size of the vector that we need to create. We will insert the element 5773 // such that the register coalescer will remove unnecessary copies. 5774 if (VT != Value->getOperand(0).getValueType()) { 5775 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5776 VT.getVectorNumElements(); 5777 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5778 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5779 Value, DAG.getConstant(index, dl, MVT::i32)), 5780 DAG.getConstant(index, dl, MVT::i32)); 5781 } else 5782 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5783 Value->getOperand(0), Value->getOperand(1)); 5784 } else 5785 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5786 5787 if (!usesOnlyOneValue) { 5788 // The dominant value was splatted as 'N', but we now have to insert 5789 // all differing elements. 5790 for (unsigned I = 0; I < NumElts; ++I) { 5791 if (Op.getOperand(I) == Value) 5792 continue; 5793 SmallVector<SDValue, 3> Ops; 5794 Ops.push_back(N); 5795 Ops.push_back(Op.getOperand(I)); 5796 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5797 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5798 } 5799 } 5800 return N; 5801 } 5802 if (VT.getVectorElementType().isFloatingPoint()) { 5803 SmallVector<SDValue, 8> Ops; 5804 for (unsigned i = 0; i < NumElts; ++i) 5805 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5806 Op.getOperand(i))); 5807 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5808 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 5809 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5810 if (Val.getNode()) 5811 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5812 } 5813 if (usesOnlyOneValue) { 5814 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5815 if (isConstant && Val.getNode()) 5816 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5817 } 5818 } 5819 5820 // If all elements are constants and the case above didn't get hit, fall back 5821 // to the default expansion, which will generate a load from the constant 5822 // pool. 5823 if (isConstant) 5824 return SDValue(); 5825 5826 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5827 if (NumElts >= 4) { 5828 SDValue shuffle = ReconstructShuffle(Op, DAG); 5829 if (shuffle != SDValue()) 5830 return shuffle; 5831 } 5832 5833 // Vectors with 32- or 64-bit elements can be built by directly assigning 5834 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5835 // will be legalized. 5836 if (EltSize >= 32) { 5837 // Do the expansion with floating-point types, since that is what the VFP 5838 // registers are defined to use, and since i64 is not legal. 5839 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5840 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5841 SmallVector<SDValue, 8> Ops; 5842 for (unsigned i = 0; i < NumElts; ++i) 5843 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5844 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5845 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5846 } 5847 5848 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5849 // know the default expansion would otherwise fall back on something even 5850 // worse. For a vector with one or two non-undef values, that's 5851 // scalar_to_vector for the elements followed by a shuffle (provided the 5852 // shuffle is valid for the target) and materialization element by element 5853 // on the stack followed by a load for everything else. 5854 if (!isConstant && !usesOnlyOneValue) { 5855 SDValue Vec = DAG.getUNDEF(VT); 5856 for (unsigned i = 0 ; i < NumElts; ++i) { 5857 SDValue V = Op.getOperand(i); 5858 if (V.isUndef()) 5859 continue; 5860 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5861 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5862 } 5863 return Vec; 5864 } 5865 5866 return SDValue(); 5867 } 5868 5869 // Gather data to see if the operation can be modelled as a 5870 // shuffle in combination with VEXTs. 5871 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5872 SelectionDAG &DAG) const { 5873 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5874 SDLoc dl(Op); 5875 EVT VT = Op.getValueType(); 5876 unsigned NumElts = VT.getVectorNumElements(); 5877 5878 struct ShuffleSourceInfo { 5879 SDValue Vec; 5880 unsigned MinElt; 5881 unsigned MaxElt; 5882 5883 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5884 // be compatible with the shuffle we intend to construct. As a result 5885 // ShuffleVec will be some sliding window into the original Vec. 5886 SDValue ShuffleVec; 5887 5888 // Code should guarantee that element i in Vec starts at element "WindowBase 5889 // + i * WindowScale in ShuffleVec". 5890 int WindowBase; 5891 int WindowScale; 5892 5893 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5894 ShuffleSourceInfo(SDValue Vec) 5895 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5896 WindowScale(1) {} 5897 }; 5898 5899 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5900 // node. 5901 SmallVector<ShuffleSourceInfo, 2> Sources; 5902 for (unsigned i = 0; i < NumElts; ++i) { 5903 SDValue V = Op.getOperand(i); 5904 if (V.isUndef()) 5905 continue; 5906 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5907 // A shuffle can only come from building a vector from various 5908 // elements of other vectors. 5909 return SDValue(); 5910 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 5911 // Furthermore, shuffles require a constant mask, whereas extractelts 5912 // accept variable indices. 5913 return SDValue(); 5914 } 5915 5916 // Add this element source to the list if it's not already there. 5917 SDValue SourceVec = V.getOperand(0); 5918 auto Source = find(Sources, SourceVec); 5919 if (Source == Sources.end()) 5920 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5921 5922 // Update the minimum and maximum lane number seen. 5923 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5924 Source->MinElt = std::min(Source->MinElt, EltNo); 5925 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5926 } 5927 5928 // Currently only do something sane when at most two source vectors 5929 // are involved. 5930 if (Sources.size() > 2) 5931 return SDValue(); 5932 5933 // Find out the smallest element size among result and two sources, and use 5934 // it as element size to build the shuffle_vector. 5935 EVT SmallestEltTy = VT.getVectorElementType(); 5936 for (auto &Source : Sources) { 5937 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5938 if (SrcEltTy.bitsLT(SmallestEltTy)) 5939 SmallestEltTy = SrcEltTy; 5940 } 5941 unsigned ResMultiplier = 5942 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5943 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5944 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5945 5946 // If the source vector is too wide or too narrow, we may nevertheless be able 5947 // to construct a compatible shuffle either by concatenating it with UNDEF or 5948 // extracting a suitable range of elements. 5949 for (auto &Src : Sources) { 5950 EVT SrcVT = Src.ShuffleVec.getValueType(); 5951 5952 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5953 continue; 5954 5955 // This stage of the search produces a source with the same element type as 5956 // the original, but with a total width matching the BUILD_VECTOR output. 5957 EVT EltVT = SrcVT.getVectorElementType(); 5958 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5959 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5960 5961 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5962 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 5963 return SDValue(); 5964 // We can pad out the smaller vector for free, so if it's part of a 5965 // shuffle... 5966 Src.ShuffleVec = 5967 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5968 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5969 continue; 5970 } 5971 5972 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 5973 return SDValue(); 5974 5975 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5976 // Span too large for a VEXT to cope 5977 return SDValue(); 5978 } 5979 5980 if (Src.MinElt >= NumSrcElts) { 5981 // The extraction can just take the second half 5982 Src.ShuffleVec = 5983 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5984 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5985 Src.WindowBase = -NumSrcElts; 5986 } else if (Src.MaxElt < NumSrcElts) { 5987 // The extraction can just take the first half 5988 Src.ShuffleVec = 5989 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5990 DAG.getConstant(0, dl, MVT::i32)); 5991 } else { 5992 // An actual VEXT is needed 5993 SDValue VEXTSrc1 = 5994 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5995 DAG.getConstant(0, dl, MVT::i32)); 5996 SDValue VEXTSrc2 = 5997 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5998 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5999 6000 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6001 VEXTSrc2, 6002 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6003 Src.WindowBase = -Src.MinElt; 6004 } 6005 } 6006 6007 // Another possible incompatibility occurs from the vector element types. We 6008 // can fix this by bitcasting the source vectors to the same type we intend 6009 // for the shuffle. 6010 for (auto &Src : Sources) { 6011 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6012 if (SrcEltTy == SmallestEltTy) 6013 continue; 6014 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6015 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6016 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6017 Src.WindowBase *= Src.WindowScale; 6018 } 6019 6020 // Final sanity check before we try to actually produce a shuffle. 6021 DEBUG( 6022 for (auto Src : Sources) 6023 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6024 ); 6025 6026 // The stars all align, our next step is to produce the mask for the shuffle. 6027 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6028 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 6029 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6030 SDValue Entry = Op.getOperand(i); 6031 if (Entry.isUndef()) 6032 continue; 6033 6034 auto Src = find(Sources, Entry.getOperand(0)); 6035 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6036 6037 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6038 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6039 // segment. 6040 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6041 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6042 VT.getVectorElementType().getSizeInBits()); 6043 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6044 6045 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6046 // starting at the appropriate offset. 6047 int *LaneMask = &Mask[i * ResMultiplier]; 6048 6049 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6050 ExtractBase += NumElts * (Src - Sources.begin()); 6051 for (int j = 0; j < LanesDefined; ++j) 6052 LaneMask[j] = ExtractBase + j; 6053 } 6054 6055 // Final check before we try to produce nonsense... 6056 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6057 return SDValue(); 6058 6059 // We can't handle more than two sources. This should have already 6060 // been checked before this point. 6061 assert(Sources.size() <= 2 && "Too many sources!"); 6062 6063 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6064 for (unsigned i = 0; i < Sources.size(); ++i) 6065 ShuffleOps[i] = Sources[i].ShuffleVec; 6066 6067 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6068 ShuffleOps[1], Mask); 6069 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6070 } 6071 6072 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6073 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6074 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6075 /// are assumed to be legal. 6076 bool 6077 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6078 EVT VT) const { 6079 if (VT.getVectorNumElements() == 4 && 6080 (VT.is128BitVector() || VT.is64BitVector())) { 6081 unsigned PFIndexes[4]; 6082 for (unsigned i = 0; i != 4; ++i) { 6083 if (M[i] < 0) 6084 PFIndexes[i] = 8; 6085 else 6086 PFIndexes[i] = M[i]; 6087 } 6088 6089 // Compute the index in the perfect shuffle table. 6090 unsigned PFTableIndex = 6091 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6092 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6093 unsigned Cost = (PFEntry >> 30); 6094 6095 if (Cost <= 4) 6096 return true; 6097 } 6098 6099 bool ReverseVEXT, isV_UNDEF; 6100 unsigned Imm, WhichResult; 6101 6102 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6103 return (EltSize >= 32 || 6104 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6105 isVREVMask(M, VT, 64) || 6106 isVREVMask(M, VT, 32) || 6107 isVREVMask(M, VT, 16) || 6108 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6109 isVTBLMask(M, VT) || 6110 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6111 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6112 } 6113 6114 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6115 /// the specified operations to build the shuffle. 6116 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6117 SDValue RHS, SelectionDAG &DAG, 6118 const SDLoc &dl) { 6119 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6120 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6121 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6122 6123 enum { 6124 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6125 OP_VREV, 6126 OP_VDUP0, 6127 OP_VDUP1, 6128 OP_VDUP2, 6129 OP_VDUP3, 6130 OP_VEXT1, 6131 OP_VEXT2, 6132 OP_VEXT3, 6133 OP_VUZPL, // VUZP, left result 6134 OP_VUZPR, // VUZP, right result 6135 OP_VZIPL, // VZIP, left result 6136 OP_VZIPR, // VZIP, right result 6137 OP_VTRNL, // VTRN, left result 6138 OP_VTRNR // VTRN, right result 6139 }; 6140 6141 if (OpNum == OP_COPY) { 6142 if (LHSID == (1*9+2)*9+3) return LHS; 6143 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6144 return RHS; 6145 } 6146 6147 SDValue OpLHS, OpRHS; 6148 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6149 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6150 EVT VT = OpLHS.getValueType(); 6151 6152 switch (OpNum) { 6153 default: llvm_unreachable("Unknown shuffle opcode!"); 6154 case OP_VREV: 6155 // VREV divides the vector in half and swaps within the half. 6156 if (VT.getVectorElementType() == MVT::i32 || 6157 VT.getVectorElementType() == MVT::f32) 6158 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6159 // vrev <4 x i16> -> VREV32 6160 if (VT.getVectorElementType() == MVT::i16) 6161 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6162 // vrev <4 x i8> -> VREV16 6163 assert(VT.getVectorElementType() == MVT::i8); 6164 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6165 case OP_VDUP0: 6166 case OP_VDUP1: 6167 case OP_VDUP2: 6168 case OP_VDUP3: 6169 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6170 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6171 case OP_VEXT1: 6172 case OP_VEXT2: 6173 case OP_VEXT3: 6174 return DAG.getNode(ARMISD::VEXT, dl, VT, 6175 OpLHS, OpRHS, 6176 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6177 case OP_VUZPL: 6178 case OP_VUZPR: 6179 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6180 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6181 case OP_VZIPL: 6182 case OP_VZIPR: 6183 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6184 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6185 case OP_VTRNL: 6186 case OP_VTRNR: 6187 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6188 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6189 } 6190 } 6191 6192 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6193 ArrayRef<int> ShuffleMask, 6194 SelectionDAG &DAG) { 6195 // Check to see if we can use the VTBL instruction. 6196 SDValue V1 = Op.getOperand(0); 6197 SDValue V2 = Op.getOperand(1); 6198 SDLoc DL(Op); 6199 6200 SmallVector<SDValue, 8> VTBLMask; 6201 for (ArrayRef<int>::iterator 6202 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6203 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6204 6205 if (V2.getNode()->isUndef()) 6206 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6207 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6208 6209 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6210 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6211 } 6212 6213 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6214 SelectionDAG &DAG) { 6215 SDLoc DL(Op); 6216 SDValue OpLHS = Op.getOperand(0); 6217 EVT VT = OpLHS.getValueType(); 6218 6219 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6220 "Expect an v8i16/v16i8 type"); 6221 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6222 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6223 // extract the first 8 bytes into the top double word and the last 8 bytes 6224 // into the bottom double word. The v8i16 case is similar. 6225 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6226 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6227 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6228 } 6229 6230 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6231 SDValue V1 = Op.getOperand(0); 6232 SDValue V2 = Op.getOperand(1); 6233 SDLoc dl(Op); 6234 EVT VT = Op.getValueType(); 6235 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6236 6237 // Convert shuffles that are directly supported on NEON to target-specific 6238 // DAG nodes, instead of keeping them as shuffles and matching them again 6239 // during code selection. This is more efficient and avoids the possibility 6240 // of inconsistencies between legalization and selection. 6241 // FIXME: floating-point vectors should be canonicalized to integer vectors 6242 // of the same time so that they get CSEd properly. 6243 ArrayRef<int> ShuffleMask = SVN->getMask(); 6244 6245 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6246 if (EltSize <= 32) { 6247 if (SVN->isSplat()) { 6248 int Lane = SVN->getSplatIndex(); 6249 // If this is undef splat, generate it via "just" vdup, if possible. 6250 if (Lane == -1) Lane = 0; 6251 6252 // Test if V1 is a SCALAR_TO_VECTOR. 6253 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6254 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6255 } 6256 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6257 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6258 // reaches it). 6259 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6260 !isa<ConstantSDNode>(V1.getOperand(0))) { 6261 bool IsScalarToVector = true; 6262 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6263 if (!V1.getOperand(i).isUndef()) { 6264 IsScalarToVector = false; 6265 break; 6266 } 6267 if (IsScalarToVector) 6268 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6269 } 6270 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6271 DAG.getConstant(Lane, dl, MVT::i32)); 6272 } 6273 6274 bool ReverseVEXT; 6275 unsigned Imm; 6276 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6277 if (ReverseVEXT) 6278 std::swap(V1, V2); 6279 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6280 DAG.getConstant(Imm, dl, MVT::i32)); 6281 } 6282 6283 if (isVREVMask(ShuffleMask, VT, 64)) 6284 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6285 if (isVREVMask(ShuffleMask, VT, 32)) 6286 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6287 if (isVREVMask(ShuffleMask, VT, 16)) 6288 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6289 6290 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6291 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6292 DAG.getConstant(Imm, dl, MVT::i32)); 6293 } 6294 6295 // Check for Neon shuffles that modify both input vectors in place. 6296 // If both results are used, i.e., if there are two shuffles with the same 6297 // source operands and with masks corresponding to both results of one of 6298 // these operations, DAG memoization will ensure that a single node is 6299 // used for both shuffles. 6300 unsigned WhichResult; 6301 bool isV_UNDEF; 6302 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6303 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6304 if (isV_UNDEF) 6305 V2 = V1; 6306 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6307 .getValue(WhichResult); 6308 } 6309 6310 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6311 // shuffles that produce a result larger than their operands with: 6312 // shuffle(concat(v1, undef), concat(v2, undef)) 6313 // -> 6314 // shuffle(concat(v1, v2), undef) 6315 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6316 // 6317 // This is useful in the general case, but there are special cases where 6318 // native shuffles produce larger results: the two-result ops. 6319 // 6320 // Look through the concat when lowering them: 6321 // shuffle(concat(v1, v2), undef) 6322 // -> 6323 // concat(VZIP(v1, v2):0, :1) 6324 // 6325 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6326 SDValue SubV1 = V1->getOperand(0); 6327 SDValue SubV2 = V1->getOperand(1); 6328 EVT SubVT = SubV1.getValueType(); 6329 6330 // We expect these to have been canonicalized to -1. 6331 assert(all_of(ShuffleMask, [&](int i) { 6332 return i < (int)VT.getVectorNumElements(); 6333 }) && "Unexpected shuffle index into UNDEF operand!"); 6334 6335 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6336 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6337 if (isV_UNDEF) 6338 SubV2 = SubV1; 6339 assert((WhichResult == 0) && 6340 "In-place shuffle of concat can only have one result!"); 6341 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6342 SubV1, SubV2); 6343 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6344 Res.getValue(1)); 6345 } 6346 } 6347 } 6348 6349 // If the shuffle is not directly supported and it has 4 elements, use 6350 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6351 unsigned NumElts = VT.getVectorNumElements(); 6352 if (NumElts == 4) { 6353 unsigned PFIndexes[4]; 6354 for (unsigned i = 0; i != 4; ++i) { 6355 if (ShuffleMask[i] < 0) 6356 PFIndexes[i] = 8; 6357 else 6358 PFIndexes[i] = ShuffleMask[i]; 6359 } 6360 6361 // Compute the index in the perfect shuffle table. 6362 unsigned PFTableIndex = 6363 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6364 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6365 unsigned Cost = (PFEntry >> 30); 6366 6367 if (Cost <= 4) 6368 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6369 } 6370 6371 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6372 if (EltSize >= 32) { 6373 // Do the expansion with floating-point types, since that is what the VFP 6374 // registers are defined to use, and since i64 is not legal. 6375 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6376 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6377 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6378 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6379 SmallVector<SDValue, 8> Ops; 6380 for (unsigned i = 0; i < NumElts; ++i) { 6381 if (ShuffleMask[i] < 0) 6382 Ops.push_back(DAG.getUNDEF(EltVT)); 6383 else 6384 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6385 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6386 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6387 dl, MVT::i32))); 6388 } 6389 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6390 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6391 } 6392 6393 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6394 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6395 6396 if (VT == MVT::v8i8) 6397 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6398 return NewOp; 6399 6400 return SDValue(); 6401 } 6402 6403 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6404 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6405 SDValue Lane = Op.getOperand(2); 6406 if (!isa<ConstantSDNode>(Lane)) 6407 return SDValue(); 6408 6409 return Op; 6410 } 6411 6412 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6413 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6414 SDValue Lane = Op.getOperand(1); 6415 if (!isa<ConstantSDNode>(Lane)) 6416 return SDValue(); 6417 6418 SDValue Vec = Op.getOperand(0); 6419 if (Op.getValueType() == MVT::i32 && 6420 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6421 SDLoc dl(Op); 6422 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6423 } 6424 6425 return Op; 6426 } 6427 6428 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6429 // The only time a CONCAT_VECTORS operation can have legal types is when 6430 // two 64-bit vectors are concatenated to a 128-bit vector. 6431 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6432 "unexpected CONCAT_VECTORS"); 6433 SDLoc dl(Op); 6434 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6435 SDValue Op0 = Op.getOperand(0); 6436 SDValue Op1 = Op.getOperand(1); 6437 if (!Op0.isUndef()) 6438 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6439 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6440 DAG.getIntPtrConstant(0, dl)); 6441 if (!Op1.isUndef()) 6442 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6443 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6444 DAG.getIntPtrConstant(1, dl)); 6445 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6446 } 6447 6448 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6449 /// element has been zero/sign-extended, depending on the isSigned parameter, 6450 /// from an integer type half its size. 6451 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6452 bool isSigned) { 6453 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6454 EVT VT = N->getValueType(0); 6455 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6456 SDNode *BVN = N->getOperand(0).getNode(); 6457 if (BVN->getValueType(0) != MVT::v4i32 || 6458 BVN->getOpcode() != ISD::BUILD_VECTOR) 6459 return false; 6460 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6461 unsigned HiElt = 1 - LoElt; 6462 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6463 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6464 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6465 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6466 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6467 return false; 6468 if (isSigned) { 6469 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6470 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6471 return true; 6472 } else { 6473 if (Hi0->isNullValue() && Hi1->isNullValue()) 6474 return true; 6475 } 6476 return false; 6477 } 6478 6479 if (N->getOpcode() != ISD::BUILD_VECTOR) 6480 return false; 6481 6482 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6483 SDNode *Elt = N->getOperand(i).getNode(); 6484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6485 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6486 unsigned HalfSize = EltSize / 2; 6487 if (isSigned) { 6488 if (!isIntN(HalfSize, C->getSExtValue())) 6489 return false; 6490 } else { 6491 if (!isUIntN(HalfSize, C->getZExtValue())) 6492 return false; 6493 } 6494 continue; 6495 } 6496 return false; 6497 } 6498 6499 return true; 6500 } 6501 6502 /// isSignExtended - Check if a node is a vector value that is sign-extended 6503 /// or a constant BUILD_VECTOR with sign-extended elements. 6504 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6505 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6506 return true; 6507 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6508 return true; 6509 return false; 6510 } 6511 6512 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6513 /// or a constant BUILD_VECTOR with zero-extended elements. 6514 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6515 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6516 return true; 6517 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6518 return true; 6519 return false; 6520 } 6521 6522 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6523 if (OrigVT.getSizeInBits() >= 64) 6524 return OrigVT; 6525 6526 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6527 6528 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6529 switch (OrigSimpleTy) { 6530 default: llvm_unreachable("Unexpected Vector Type"); 6531 case MVT::v2i8: 6532 case MVT::v2i16: 6533 return MVT::v2i32; 6534 case MVT::v4i8: 6535 return MVT::v4i16; 6536 } 6537 } 6538 6539 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6540 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6541 /// We insert the required extension here to get the vector to fill a D register. 6542 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6543 const EVT &OrigTy, 6544 const EVT &ExtTy, 6545 unsigned ExtOpcode) { 6546 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6547 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6548 // 64-bits we need to insert a new extension so that it will be 64-bits. 6549 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6550 if (OrigTy.getSizeInBits() >= 64) 6551 return N; 6552 6553 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6554 EVT NewVT = getExtensionTo64Bits(OrigTy); 6555 6556 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6557 } 6558 6559 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6560 /// does not do any sign/zero extension. If the original vector is less 6561 /// than 64 bits, an appropriate extension will be added after the load to 6562 /// reach a total size of 64 bits. We have to add the extension separately 6563 /// because ARM does not have a sign/zero extending load for vectors. 6564 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6565 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6566 6567 // The load already has the right type. 6568 if (ExtendedTy == LD->getMemoryVT()) 6569 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6570 LD->getBasePtr(), LD->getPointerInfo(), 6571 LD->getAlignment(), LD->getMemOperand()->getFlags()); 6572 6573 // We need to create a zextload/sextload. We cannot just create a load 6574 // followed by a zext/zext node because LowerMUL is also run during normal 6575 // operation legalization where we can't create illegal types. 6576 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6577 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6578 LD->getMemoryVT(), LD->getAlignment(), 6579 LD->getMemOperand()->getFlags()); 6580 } 6581 6582 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6583 /// extending load, or BUILD_VECTOR with extended elements, return the 6584 /// unextended value. The unextended vector should be 64 bits so that it can 6585 /// be used as an operand to a VMULL instruction. If the original vector size 6586 /// before extension is less than 64 bits we add a an extension to resize 6587 /// the vector to 64 bits. 6588 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6589 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6590 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6591 N->getOperand(0)->getValueType(0), 6592 N->getValueType(0), 6593 N->getOpcode()); 6594 6595 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6596 return SkipLoadExtensionForVMULL(LD, DAG); 6597 6598 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6599 // have been legalized as a BITCAST from v4i32. 6600 if (N->getOpcode() == ISD::BITCAST) { 6601 SDNode *BVN = N->getOperand(0).getNode(); 6602 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6603 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6604 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6605 return DAG.getBuildVector( 6606 MVT::v2i32, SDLoc(N), 6607 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 6608 } 6609 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6610 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6611 EVT VT = N->getValueType(0); 6612 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6613 unsigned NumElts = VT.getVectorNumElements(); 6614 MVT TruncVT = MVT::getIntegerVT(EltSize); 6615 SmallVector<SDValue, 8> Ops; 6616 SDLoc dl(N); 6617 for (unsigned i = 0; i != NumElts; ++i) { 6618 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6619 const APInt &CInt = C->getAPIntValue(); 6620 // Element types smaller than 32 bits are not legal, so use i32 elements. 6621 // The values are implicitly truncated so sext vs. zext doesn't matter. 6622 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6623 } 6624 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 6625 } 6626 6627 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6628 unsigned Opcode = N->getOpcode(); 6629 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6630 SDNode *N0 = N->getOperand(0).getNode(); 6631 SDNode *N1 = N->getOperand(1).getNode(); 6632 return N0->hasOneUse() && N1->hasOneUse() && 6633 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6634 } 6635 return false; 6636 } 6637 6638 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6639 unsigned Opcode = N->getOpcode(); 6640 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6641 SDNode *N0 = N->getOperand(0).getNode(); 6642 SDNode *N1 = N->getOperand(1).getNode(); 6643 return N0->hasOneUse() && N1->hasOneUse() && 6644 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6645 } 6646 return false; 6647 } 6648 6649 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6650 // Multiplications are only custom-lowered for 128-bit vectors so that 6651 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6652 EVT VT = Op.getValueType(); 6653 assert(VT.is128BitVector() && VT.isInteger() && 6654 "unexpected type for custom-lowering ISD::MUL"); 6655 SDNode *N0 = Op.getOperand(0).getNode(); 6656 SDNode *N1 = Op.getOperand(1).getNode(); 6657 unsigned NewOpc = 0; 6658 bool isMLA = false; 6659 bool isN0SExt = isSignExtended(N0, DAG); 6660 bool isN1SExt = isSignExtended(N1, DAG); 6661 if (isN0SExt && isN1SExt) 6662 NewOpc = ARMISD::VMULLs; 6663 else { 6664 bool isN0ZExt = isZeroExtended(N0, DAG); 6665 bool isN1ZExt = isZeroExtended(N1, DAG); 6666 if (isN0ZExt && isN1ZExt) 6667 NewOpc = ARMISD::VMULLu; 6668 else if (isN1SExt || isN1ZExt) { 6669 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6670 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6671 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6672 NewOpc = ARMISD::VMULLs; 6673 isMLA = true; 6674 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6675 NewOpc = ARMISD::VMULLu; 6676 isMLA = true; 6677 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6678 std::swap(N0, N1); 6679 NewOpc = ARMISD::VMULLu; 6680 isMLA = true; 6681 } 6682 } 6683 6684 if (!NewOpc) { 6685 if (VT == MVT::v2i64) 6686 // Fall through to expand this. It is not legal. 6687 return SDValue(); 6688 else 6689 // Other vector multiplications are legal. 6690 return Op; 6691 } 6692 } 6693 6694 // Legalize to a VMULL instruction. 6695 SDLoc DL(Op); 6696 SDValue Op0; 6697 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6698 if (!isMLA) { 6699 Op0 = SkipExtensionForVMULL(N0, DAG); 6700 assert(Op0.getValueType().is64BitVector() && 6701 Op1.getValueType().is64BitVector() && 6702 "unexpected types for extended operands to VMULL"); 6703 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6704 } 6705 6706 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6707 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6708 // vmull q0, d4, d6 6709 // vmlal q0, d5, d6 6710 // is faster than 6711 // vaddl q0, d4, d5 6712 // vmovl q1, d6 6713 // vmul q0, q0, q1 6714 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6715 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6716 EVT Op1VT = Op1.getValueType(); 6717 return DAG.getNode(N0->getOpcode(), DL, VT, 6718 DAG.getNode(NewOpc, DL, VT, 6719 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6720 DAG.getNode(NewOpc, DL, VT, 6721 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6722 } 6723 6724 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 6725 SelectionDAG &DAG) { 6726 // TODO: Should this propagate fast-math-flags? 6727 6728 // Convert to float 6729 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6730 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6731 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6732 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6733 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6734 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6735 // Get reciprocal estimate. 6736 // float4 recip = vrecpeq_f32(yf); 6737 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6738 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6739 Y); 6740 // Because char has a smaller range than uchar, we can actually get away 6741 // without any newton steps. This requires that we use a weird bias 6742 // of 0xb000, however (again, this has been exhaustively tested). 6743 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6744 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6745 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6746 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 6747 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6748 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6749 // Convert back to short. 6750 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6751 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6752 return X; 6753 } 6754 6755 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 6756 SelectionDAG &DAG) { 6757 // TODO: Should this propagate fast-math-flags? 6758 6759 SDValue N2; 6760 // Convert to float. 6761 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6762 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6763 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6764 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6765 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6766 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6767 6768 // Use reciprocal estimate and one refinement step. 6769 // float4 recip = vrecpeq_f32(yf); 6770 // recip *= vrecpsq_f32(yf, recip); 6771 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6772 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6773 N1); 6774 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6775 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6776 N1, N2); 6777 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6778 // Because short has a smaller range than ushort, we can actually get away 6779 // with only a single newton step. This requires that we use a weird bias 6780 // of 89, however (again, this has been exhaustively tested). 6781 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6782 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6783 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6784 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 6785 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6786 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6787 // Convert back to integer and return. 6788 // return vmovn_s32(vcvt_s32_f32(result)); 6789 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6790 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6791 return N0; 6792 } 6793 6794 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6795 EVT VT = Op.getValueType(); 6796 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6797 "unexpected type for custom-lowering ISD::SDIV"); 6798 6799 SDLoc dl(Op); 6800 SDValue N0 = Op.getOperand(0); 6801 SDValue N1 = Op.getOperand(1); 6802 SDValue N2, N3; 6803 6804 if (VT == MVT::v8i8) { 6805 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6806 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6807 6808 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6809 DAG.getIntPtrConstant(4, dl)); 6810 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6811 DAG.getIntPtrConstant(4, dl)); 6812 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6813 DAG.getIntPtrConstant(0, dl)); 6814 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6815 DAG.getIntPtrConstant(0, dl)); 6816 6817 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6818 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6819 6820 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6821 N0 = LowerCONCAT_VECTORS(N0, DAG); 6822 6823 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6824 return N0; 6825 } 6826 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6827 } 6828 6829 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6830 // TODO: Should this propagate fast-math-flags? 6831 EVT VT = Op.getValueType(); 6832 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6833 "unexpected type for custom-lowering ISD::UDIV"); 6834 6835 SDLoc dl(Op); 6836 SDValue N0 = Op.getOperand(0); 6837 SDValue N1 = Op.getOperand(1); 6838 SDValue N2, N3; 6839 6840 if (VT == MVT::v8i8) { 6841 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6842 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6843 6844 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6845 DAG.getIntPtrConstant(4, dl)); 6846 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6847 DAG.getIntPtrConstant(4, dl)); 6848 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6849 DAG.getIntPtrConstant(0, dl)); 6850 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6851 DAG.getIntPtrConstant(0, dl)); 6852 6853 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6854 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6855 6856 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6857 N0 = LowerCONCAT_VECTORS(N0, DAG); 6858 6859 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6860 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6861 MVT::i32), 6862 N0); 6863 return N0; 6864 } 6865 6866 // v4i16 sdiv ... Convert to float. 6867 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6868 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6869 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6870 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6871 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6872 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6873 6874 // Use reciprocal estimate and two refinement steps. 6875 // float4 recip = vrecpeq_f32(yf); 6876 // recip *= vrecpsq_f32(yf, recip); 6877 // recip *= vrecpsq_f32(yf, recip); 6878 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6879 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6880 BN1); 6881 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6882 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6883 BN1, N2); 6884 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6885 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6886 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6887 BN1, N2); 6888 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6889 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6890 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6891 // and that it will never cause us to return an answer too large). 6892 // float4 result = as_float4(as_int4(xf*recip) + 2); 6893 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6894 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6895 N1 = DAG.getConstant(2, dl, MVT::v4i32); 6896 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6897 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6898 // Convert back to integer and return. 6899 // return vmovn_u32(vcvt_s32_f32(result)); 6900 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6901 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6902 return N0; 6903 } 6904 6905 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6906 EVT VT = Op.getNode()->getValueType(0); 6907 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6908 6909 unsigned Opc; 6910 bool ExtraOp = false; 6911 switch (Op.getOpcode()) { 6912 default: llvm_unreachable("Invalid code"); 6913 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6914 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6915 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6916 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6917 } 6918 6919 if (!ExtraOp) 6920 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6921 Op.getOperand(1)); 6922 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6923 Op.getOperand(1), Op.getOperand(2)); 6924 } 6925 6926 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6927 assert(Subtarget->isTargetDarwin()); 6928 6929 // For iOS, we want to call an alternative entry point: __sincos_stret, 6930 // return values are passed via sret. 6931 SDLoc dl(Op); 6932 SDValue Arg = Op.getOperand(0); 6933 EVT ArgVT = Arg.getValueType(); 6934 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6935 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6936 6937 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6938 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6939 6940 // Pair of floats / doubles used to pass the result. 6941 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6942 auto &DL = DAG.getDataLayout(); 6943 6944 ArgListTy Args; 6945 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 6946 SDValue SRet; 6947 if (ShouldUseSRet) { 6948 // Create stack object for sret. 6949 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6950 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6951 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 6952 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 6953 6954 ArgListEntry Entry; 6955 Entry.Node = SRet; 6956 Entry.Ty = RetTy->getPointerTo(); 6957 Entry.isSExt = false; 6958 Entry.isZExt = false; 6959 Entry.isSRet = true; 6960 Args.push_back(Entry); 6961 RetTy = Type::getVoidTy(*DAG.getContext()); 6962 } 6963 6964 ArgListEntry Entry; 6965 Entry.Node = Arg; 6966 Entry.Ty = ArgTy; 6967 Entry.isSExt = false; 6968 Entry.isZExt = false; 6969 Args.push_back(Entry); 6970 6971 const char *LibcallName = 6972 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 6973 RTLIB::Libcall LC = 6974 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 6975 CallingConv::ID CC = getLibcallCallingConv(LC); 6976 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6977 6978 TargetLowering::CallLoweringInfo CLI(DAG); 6979 CLI.setDebugLoc(dl) 6980 .setChain(DAG.getEntryNode()) 6981 .setCallee(CC, RetTy, Callee, std::move(Args)) 6982 .setDiscardResult(ShouldUseSRet); 6983 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6984 6985 if (!ShouldUseSRet) 6986 return CallResult.first; 6987 6988 SDValue LoadSin = 6989 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 6990 6991 // Address of cos field. 6992 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6993 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6994 SDValue LoadCos = 6995 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 6996 6997 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6998 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6999 LoadSin.getValue(0), LoadCos.getValue(0)); 7000 } 7001 7002 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7003 bool Signed, 7004 SDValue &Chain) const { 7005 EVT VT = Op.getValueType(); 7006 assert((VT == MVT::i32 || VT == MVT::i64) && 7007 "unexpected type for custom lowering DIV"); 7008 SDLoc dl(Op); 7009 7010 const auto &DL = DAG.getDataLayout(); 7011 const auto &TLI = DAG.getTargetLoweringInfo(); 7012 7013 const char *Name = nullptr; 7014 if (Signed) 7015 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7016 else 7017 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7018 7019 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7020 7021 ARMTargetLowering::ArgListTy Args; 7022 7023 for (auto AI : {1, 0}) { 7024 ArgListEntry Arg; 7025 Arg.Node = Op.getOperand(AI); 7026 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7027 Args.push_back(Arg); 7028 } 7029 7030 CallLoweringInfo CLI(DAG); 7031 CLI.setDebugLoc(dl) 7032 .setChain(Chain) 7033 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7034 ES, std::move(Args)); 7035 7036 return LowerCallTo(CLI).first; 7037 } 7038 7039 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7040 bool Signed) const { 7041 assert(Op.getValueType() == MVT::i32 && 7042 "unexpected type for custom lowering DIV"); 7043 SDLoc dl(Op); 7044 7045 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7046 DAG.getEntryNode(), Op.getOperand(1)); 7047 7048 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7049 } 7050 7051 void ARMTargetLowering::ExpandDIV_Windows( 7052 SDValue Op, SelectionDAG &DAG, bool Signed, 7053 SmallVectorImpl<SDValue> &Results) const { 7054 const auto &DL = DAG.getDataLayout(); 7055 const auto &TLI = DAG.getTargetLoweringInfo(); 7056 7057 assert(Op.getValueType() == MVT::i64 && 7058 "unexpected type for custom lowering DIV"); 7059 SDLoc dl(Op); 7060 7061 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 7062 DAG.getConstant(0, dl, MVT::i32)); 7063 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 7064 DAG.getConstant(1, dl, MVT::i32)); 7065 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 7066 7067 SDValue DBZCHK = 7068 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 7069 7070 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7071 7072 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7073 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7074 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7075 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7076 7077 Results.push_back(Lower); 7078 Results.push_back(Upper); 7079 } 7080 7081 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7082 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7083 // Acquire/Release load/store is not legal for targets without a dmb or 7084 // equivalent available. 7085 return SDValue(); 7086 7087 // Monotonic load/store is legal for all targets. 7088 return Op; 7089 } 7090 7091 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7092 SmallVectorImpl<SDValue> &Results, 7093 SelectionDAG &DAG, 7094 const ARMSubtarget *Subtarget) { 7095 SDLoc DL(N); 7096 // Under Power Management extensions, the cycle-count is: 7097 // mrc p15, #0, <Rt>, c9, c13, #0 7098 SDValue Ops[] = { N->getOperand(0), // Chain 7099 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7100 DAG.getConstant(15, DL, MVT::i32), 7101 DAG.getConstant(0, DL, MVT::i32), 7102 DAG.getConstant(9, DL, MVT::i32), 7103 DAG.getConstant(13, DL, MVT::i32), 7104 DAG.getConstant(0, DL, MVT::i32) 7105 }; 7106 7107 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7108 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7109 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7110 DAG.getConstant(0, DL, MVT::i32))); 7111 Results.push_back(Cycles32.getValue(1)); 7112 } 7113 7114 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7115 SDLoc dl(V.getNode()); 7116 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7117 SDValue VHi = DAG.getAnyExtOrTrunc( 7118 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7119 dl, MVT::i32); 7120 SDValue RegClass = 7121 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7122 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7123 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7124 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7125 return SDValue( 7126 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7127 } 7128 7129 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7130 SmallVectorImpl<SDValue> & Results, 7131 SelectionDAG &DAG) { 7132 assert(N->getValueType(0) == MVT::i64 && 7133 "AtomicCmpSwap on types less than 64 should be legal"); 7134 SDValue Ops[] = {N->getOperand(1), 7135 createGPRPairNode(DAG, N->getOperand(2)), 7136 createGPRPairNode(DAG, N->getOperand(3)), 7137 N->getOperand(0)}; 7138 SDNode *CmpSwap = DAG.getMachineNode( 7139 ARM::CMP_SWAP_64, SDLoc(N), 7140 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7141 7142 MachineFunction &MF = DAG.getMachineFunction(); 7143 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7144 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7145 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7146 7147 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7148 SDValue(CmpSwap, 0))); 7149 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7150 SDValue(CmpSwap, 0))); 7151 Results.push_back(SDValue(CmpSwap, 2)); 7152 } 7153 7154 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7155 switch (Op.getOpcode()) { 7156 default: llvm_unreachable("Don't know how to custom lower this!"); 7157 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7158 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7159 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7160 case ISD::GlobalAddress: 7161 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7162 default: llvm_unreachable("unknown object format"); 7163 case Triple::COFF: 7164 return LowerGlobalAddressWindows(Op, DAG); 7165 case Triple::ELF: 7166 return LowerGlobalAddressELF(Op, DAG); 7167 case Triple::MachO: 7168 return LowerGlobalAddressDarwin(Op, DAG); 7169 } 7170 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7171 case ISD::SELECT: return LowerSELECT(Op, DAG); 7172 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7173 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7174 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7175 case ISD::VASTART: return LowerVASTART(Op, DAG); 7176 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7177 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7178 case ISD::SINT_TO_FP: 7179 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7180 case ISD::FP_TO_SINT: 7181 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7182 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7183 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7184 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7185 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7186 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7187 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7188 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7189 Subtarget); 7190 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7191 case ISD::SHL: 7192 case ISD::SRL: 7193 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7194 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7195 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7196 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7197 case ISD::SRL_PARTS: 7198 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7199 case ISD::CTTZ: 7200 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7201 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7202 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7203 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7204 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7205 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7206 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7207 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7208 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7209 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7210 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7211 case ISD::MUL: return LowerMUL(Op, DAG); 7212 case ISD::SDIV: 7213 if (Subtarget->isTargetWindows()) 7214 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7215 return LowerSDIV(Op, DAG); 7216 case ISD::UDIV: 7217 if (Subtarget->isTargetWindows()) 7218 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7219 return LowerUDIV(Op, DAG); 7220 case ISD::ADDC: 7221 case ISD::ADDE: 7222 case ISD::SUBC: 7223 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7224 case ISD::SADDO: 7225 case ISD::UADDO: 7226 case ISD::SSUBO: 7227 case ISD::USUBO: 7228 return LowerXALUO(Op, DAG); 7229 case ISD::ATOMIC_LOAD: 7230 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7231 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7232 case ISD::SDIVREM: 7233 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7234 case ISD::DYNAMIC_STACKALLOC: 7235 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7236 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7237 llvm_unreachable("Don't know how to custom lower this!"); 7238 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7239 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7240 case ARMISD::WIN__DBZCHK: return SDValue(); 7241 } 7242 } 7243 7244 /// ReplaceNodeResults - Replace the results of node with an illegal result 7245 /// type with new values built out of custom code. 7246 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7247 SmallVectorImpl<SDValue> &Results, 7248 SelectionDAG &DAG) const { 7249 SDValue Res; 7250 switch (N->getOpcode()) { 7251 default: 7252 llvm_unreachable("Don't know how to custom expand this!"); 7253 case ISD::READ_REGISTER: 7254 ExpandREAD_REGISTER(N, Results, DAG); 7255 break; 7256 case ISD::BITCAST: 7257 Res = ExpandBITCAST(N, DAG); 7258 break; 7259 case ISD::SRL: 7260 case ISD::SRA: 7261 Res = Expand64BitShift(N, DAG, Subtarget); 7262 break; 7263 case ISD::SREM: 7264 case ISD::UREM: 7265 Res = LowerREM(N, DAG); 7266 break; 7267 case ISD::SDIVREM: 7268 case ISD::UDIVREM: 7269 Res = LowerDivRem(SDValue(N, 0), DAG); 7270 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7271 Results.push_back(Res.getValue(0)); 7272 Results.push_back(Res.getValue(1)); 7273 return; 7274 case ISD::READCYCLECOUNTER: 7275 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7276 return; 7277 case ISD::UDIV: 7278 case ISD::SDIV: 7279 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7280 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7281 Results); 7282 case ISD::ATOMIC_CMP_SWAP: 7283 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7284 return; 7285 } 7286 if (Res.getNode()) 7287 Results.push_back(Res); 7288 } 7289 7290 //===----------------------------------------------------------------------===// 7291 // ARM Scheduler Hooks 7292 //===----------------------------------------------------------------------===// 7293 7294 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7295 /// registers the function context. 7296 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7297 MachineBasicBlock *MBB, 7298 MachineBasicBlock *DispatchBB, 7299 int FI) const { 7300 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7301 "ROPI/RWPI not currently supported with SjLj"); 7302 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7303 DebugLoc dl = MI.getDebugLoc(); 7304 MachineFunction *MF = MBB->getParent(); 7305 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7306 MachineConstantPool *MCP = MF->getConstantPool(); 7307 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7308 const Function *F = MF->getFunction(); 7309 7310 bool isThumb = Subtarget->isThumb(); 7311 bool isThumb2 = Subtarget->isThumb2(); 7312 7313 unsigned PCLabelId = AFI->createPICLabelUId(); 7314 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7315 ARMConstantPoolValue *CPV = 7316 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7317 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7318 7319 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7320 : &ARM::GPRRegClass; 7321 7322 // Grab constant pool and fixed stack memory operands. 7323 MachineMemOperand *CPMMO = 7324 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7325 MachineMemOperand::MOLoad, 4, 4); 7326 7327 MachineMemOperand *FIMMOSt = 7328 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7329 MachineMemOperand::MOStore, 4, 4); 7330 7331 // Load the address of the dispatch MBB into the jump buffer. 7332 if (isThumb2) { 7333 // Incoming value: jbuf 7334 // ldr.n r5, LCPI1_1 7335 // orr r5, r5, #1 7336 // add r5, pc 7337 // str r5, [$jbuf, #+4] ; &jbuf[1] 7338 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7339 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7340 .addConstantPoolIndex(CPI) 7341 .addMemOperand(CPMMO)); 7342 // Set the low bit because of thumb mode. 7343 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7344 AddDefaultCC( 7345 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7346 .addReg(NewVReg1, RegState::Kill) 7347 .addImm(0x01))); 7348 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7349 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7350 .addReg(NewVReg2, RegState::Kill) 7351 .addImm(PCLabelId); 7352 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7353 .addReg(NewVReg3, RegState::Kill) 7354 .addFrameIndex(FI) 7355 .addImm(36) // &jbuf[1] :: pc 7356 .addMemOperand(FIMMOSt)); 7357 } else if (isThumb) { 7358 // Incoming value: jbuf 7359 // ldr.n r1, LCPI1_4 7360 // add r1, pc 7361 // mov r2, #1 7362 // orrs r1, r2 7363 // add r2, $jbuf, #+4 ; &jbuf[1] 7364 // str r1, [r2] 7365 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7366 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7367 .addConstantPoolIndex(CPI) 7368 .addMemOperand(CPMMO)); 7369 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7370 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7371 .addReg(NewVReg1, RegState::Kill) 7372 .addImm(PCLabelId); 7373 // Set the low bit because of thumb mode. 7374 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7375 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7376 .addReg(ARM::CPSR, RegState::Define) 7377 .addImm(1)); 7378 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7379 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7380 .addReg(ARM::CPSR, RegState::Define) 7381 .addReg(NewVReg2, RegState::Kill) 7382 .addReg(NewVReg3, RegState::Kill)); 7383 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7384 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7385 .addFrameIndex(FI) 7386 .addImm(36); // &jbuf[1] :: pc 7387 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7388 .addReg(NewVReg4, RegState::Kill) 7389 .addReg(NewVReg5, RegState::Kill) 7390 .addImm(0) 7391 .addMemOperand(FIMMOSt)); 7392 } else { 7393 // Incoming value: jbuf 7394 // ldr r1, LCPI1_1 7395 // add r1, pc, r1 7396 // str r1, [$jbuf, #+4] ; &jbuf[1] 7397 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7398 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7399 .addConstantPoolIndex(CPI) 7400 .addImm(0) 7401 .addMemOperand(CPMMO)); 7402 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7403 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7404 .addReg(NewVReg1, RegState::Kill) 7405 .addImm(PCLabelId)); 7406 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7407 .addReg(NewVReg2, RegState::Kill) 7408 .addFrameIndex(FI) 7409 .addImm(36) // &jbuf[1] :: pc 7410 .addMemOperand(FIMMOSt)); 7411 } 7412 } 7413 7414 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 7415 MachineBasicBlock *MBB) const { 7416 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7417 DebugLoc dl = MI.getDebugLoc(); 7418 MachineFunction *MF = MBB->getParent(); 7419 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7420 MachineFrameInfo &MFI = MF->getFrameInfo(); 7421 int FI = MFI.getFunctionContextIndex(); 7422 7423 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7424 : &ARM::GPRnopcRegClass; 7425 7426 // Get a mapping of the call site numbers to all of the landing pads they're 7427 // associated with. 7428 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7429 unsigned MaxCSNum = 0; 7430 MachineModuleInfo &MMI = MF->getMMI(); 7431 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7432 ++BB) { 7433 if (!BB->isEHPad()) continue; 7434 7435 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7436 // pad. 7437 for (MachineBasicBlock::iterator 7438 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7439 if (!II->isEHLabel()) continue; 7440 7441 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7442 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7443 7444 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7445 for (SmallVectorImpl<unsigned>::iterator 7446 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7447 CSI != CSE; ++CSI) { 7448 CallSiteNumToLPad[*CSI].push_back(&*BB); 7449 MaxCSNum = std::max(MaxCSNum, *CSI); 7450 } 7451 break; 7452 } 7453 } 7454 7455 // Get an ordered list of the machine basic blocks for the jump table. 7456 std::vector<MachineBasicBlock*> LPadList; 7457 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7458 LPadList.reserve(CallSiteNumToLPad.size()); 7459 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7460 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7461 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7462 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7463 LPadList.push_back(*II); 7464 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7465 } 7466 } 7467 7468 assert(!LPadList.empty() && 7469 "No landing pad destinations for the dispatch jump table!"); 7470 7471 // Create the jump table and associated information. 7472 MachineJumpTableInfo *JTI = 7473 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7474 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7475 7476 // Create the MBBs for the dispatch code. 7477 7478 // Shove the dispatch's address into the return slot in the function context. 7479 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7480 DispatchBB->setIsEHPad(); 7481 7482 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7483 unsigned trap_opcode; 7484 if (Subtarget->isThumb()) 7485 trap_opcode = ARM::tTRAP; 7486 else 7487 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7488 7489 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7490 DispatchBB->addSuccessor(TrapBB); 7491 7492 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7493 DispatchBB->addSuccessor(DispContBB); 7494 7495 // Insert and MBBs. 7496 MF->insert(MF->end(), DispatchBB); 7497 MF->insert(MF->end(), DispContBB); 7498 MF->insert(MF->end(), TrapBB); 7499 7500 // Insert code into the entry block that creates and registers the function 7501 // context. 7502 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7503 7504 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7505 MachinePointerInfo::getFixedStack(*MF, FI), 7506 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7507 7508 MachineInstrBuilder MIB; 7509 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7510 7511 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7512 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7513 7514 // Add a register mask with no preserved registers. This results in all 7515 // registers being marked as clobbered. 7516 MIB.addRegMask(RI.getNoPreservedMask()); 7517 7518 bool IsPositionIndependent = isPositionIndependent(); 7519 unsigned NumLPads = LPadList.size(); 7520 if (Subtarget->isThumb2()) { 7521 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7522 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7523 .addFrameIndex(FI) 7524 .addImm(4) 7525 .addMemOperand(FIMMOLd)); 7526 7527 if (NumLPads < 256) { 7528 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7529 .addReg(NewVReg1) 7530 .addImm(LPadList.size())); 7531 } else { 7532 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7533 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7534 .addImm(NumLPads & 0xFFFF)); 7535 7536 unsigned VReg2 = VReg1; 7537 if ((NumLPads & 0xFFFF0000) != 0) { 7538 VReg2 = MRI->createVirtualRegister(TRC); 7539 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7540 .addReg(VReg1) 7541 .addImm(NumLPads >> 16)); 7542 } 7543 7544 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7545 .addReg(NewVReg1) 7546 .addReg(VReg2)); 7547 } 7548 7549 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7550 .addMBB(TrapBB) 7551 .addImm(ARMCC::HI) 7552 .addReg(ARM::CPSR); 7553 7554 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7555 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7556 .addJumpTableIndex(MJTI)); 7557 7558 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7559 AddDefaultCC( 7560 AddDefaultPred( 7561 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7562 .addReg(NewVReg3, RegState::Kill) 7563 .addReg(NewVReg1) 7564 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7565 7566 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7567 .addReg(NewVReg4, RegState::Kill) 7568 .addReg(NewVReg1) 7569 .addJumpTableIndex(MJTI); 7570 } else if (Subtarget->isThumb()) { 7571 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7572 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7573 .addFrameIndex(FI) 7574 .addImm(1) 7575 .addMemOperand(FIMMOLd)); 7576 7577 if (NumLPads < 256) { 7578 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7579 .addReg(NewVReg1) 7580 .addImm(NumLPads)); 7581 } else { 7582 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7583 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7584 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7585 7586 // MachineConstantPool wants an explicit alignment. 7587 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7588 if (Align == 0) 7589 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7590 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7591 7592 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7593 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7594 .addReg(VReg1, RegState::Define) 7595 .addConstantPoolIndex(Idx)); 7596 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7597 .addReg(NewVReg1) 7598 .addReg(VReg1)); 7599 } 7600 7601 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7602 .addMBB(TrapBB) 7603 .addImm(ARMCC::HI) 7604 .addReg(ARM::CPSR); 7605 7606 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7607 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7608 .addReg(ARM::CPSR, RegState::Define) 7609 .addReg(NewVReg1) 7610 .addImm(2)); 7611 7612 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7613 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7614 .addJumpTableIndex(MJTI)); 7615 7616 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7617 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7618 .addReg(ARM::CPSR, RegState::Define) 7619 .addReg(NewVReg2, RegState::Kill) 7620 .addReg(NewVReg3)); 7621 7622 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7623 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7624 7625 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7626 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7627 .addReg(NewVReg4, RegState::Kill) 7628 .addImm(0) 7629 .addMemOperand(JTMMOLd)); 7630 7631 unsigned NewVReg6 = NewVReg5; 7632 if (IsPositionIndependent) { 7633 NewVReg6 = MRI->createVirtualRegister(TRC); 7634 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7635 .addReg(ARM::CPSR, RegState::Define) 7636 .addReg(NewVReg5, RegState::Kill) 7637 .addReg(NewVReg3)); 7638 } 7639 7640 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7641 .addReg(NewVReg6, RegState::Kill) 7642 .addJumpTableIndex(MJTI); 7643 } else { 7644 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7645 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7646 .addFrameIndex(FI) 7647 .addImm(4) 7648 .addMemOperand(FIMMOLd)); 7649 7650 if (NumLPads < 256) { 7651 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7652 .addReg(NewVReg1) 7653 .addImm(NumLPads)); 7654 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7655 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7656 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7657 .addImm(NumLPads & 0xFFFF)); 7658 7659 unsigned VReg2 = VReg1; 7660 if ((NumLPads & 0xFFFF0000) != 0) { 7661 VReg2 = MRI->createVirtualRegister(TRC); 7662 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7663 .addReg(VReg1) 7664 .addImm(NumLPads >> 16)); 7665 } 7666 7667 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7668 .addReg(NewVReg1) 7669 .addReg(VReg2)); 7670 } else { 7671 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7672 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7673 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7674 7675 // MachineConstantPool wants an explicit alignment. 7676 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7677 if (Align == 0) 7678 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7679 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7680 7681 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7682 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7683 .addReg(VReg1, RegState::Define) 7684 .addConstantPoolIndex(Idx) 7685 .addImm(0)); 7686 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7687 .addReg(NewVReg1) 7688 .addReg(VReg1, RegState::Kill)); 7689 } 7690 7691 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7692 .addMBB(TrapBB) 7693 .addImm(ARMCC::HI) 7694 .addReg(ARM::CPSR); 7695 7696 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7697 AddDefaultCC( 7698 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7699 .addReg(NewVReg1) 7700 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7701 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7702 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7703 .addJumpTableIndex(MJTI)); 7704 7705 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7706 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7707 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7708 AddDefaultPred( 7709 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7710 .addReg(NewVReg3, RegState::Kill) 7711 .addReg(NewVReg4) 7712 .addImm(0) 7713 .addMemOperand(JTMMOLd)); 7714 7715 if (IsPositionIndependent) { 7716 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7717 .addReg(NewVReg5, RegState::Kill) 7718 .addReg(NewVReg4) 7719 .addJumpTableIndex(MJTI); 7720 } else { 7721 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7722 .addReg(NewVReg5, RegState::Kill) 7723 .addJumpTableIndex(MJTI); 7724 } 7725 } 7726 7727 // Add the jump table entries as successors to the MBB. 7728 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7729 for (std::vector<MachineBasicBlock*>::iterator 7730 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7731 MachineBasicBlock *CurMBB = *I; 7732 if (SeenMBBs.insert(CurMBB).second) 7733 DispContBB->addSuccessor(CurMBB); 7734 } 7735 7736 // N.B. the order the invoke BBs are processed in doesn't matter here. 7737 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7738 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7739 for (MachineBasicBlock *BB : InvokeBBs) { 7740 7741 // Remove the landing pad successor from the invoke block and replace it 7742 // with the new dispatch block. 7743 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7744 BB->succ_end()); 7745 while (!Successors.empty()) { 7746 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7747 if (SMBB->isEHPad()) { 7748 BB->removeSuccessor(SMBB); 7749 MBBLPads.push_back(SMBB); 7750 } 7751 } 7752 7753 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7754 BB->normalizeSuccProbs(); 7755 7756 // Find the invoke call and mark all of the callee-saved registers as 7757 // 'implicit defined' so that they're spilled. This prevents code from 7758 // moving instructions to before the EH block, where they will never be 7759 // executed. 7760 for (MachineBasicBlock::reverse_iterator 7761 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7762 if (!II->isCall()) continue; 7763 7764 DenseMap<unsigned, bool> DefRegs; 7765 for (MachineInstr::mop_iterator 7766 OI = II->operands_begin(), OE = II->operands_end(); 7767 OI != OE; ++OI) { 7768 if (!OI->isReg()) continue; 7769 DefRegs[OI->getReg()] = true; 7770 } 7771 7772 MachineInstrBuilder MIB(*MF, &*II); 7773 7774 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7775 unsigned Reg = SavedRegs[i]; 7776 if (Subtarget->isThumb2() && 7777 !ARM::tGPRRegClass.contains(Reg) && 7778 !ARM::hGPRRegClass.contains(Reg)) 7779 continue; 7780 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7781 continue; 7782 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7783 continue; 7784 if (!DefRegs[Reg]) 7785 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7786 } 7787 7788 break; 7789 } 7790 } 7791 7792 // Mark all former landing pads as non-landing pads. The dispatch is the only 7793 // landing pad now. 7794 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7795 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7796 (*I)->setIsEHPad(false); 7797 7798 // The instruction is gone now. 7799 MI.eraseFromParent(); 7800 } 7801 7802 static 7803 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7804 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7805 E = MBB->succ_end(); I != E; ++I) 7806 if (*I != Succ) 7807 return *I; 7808 llvm_unreachable("Expecting a BB with two successors!"); 7809 } 7810 7811 /// Return the load opcode for a given load size. If load size >= 8, 7812 /// neon opcode will be returned. 7813 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7814 if (LdSize >= 8) 7815 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7816 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7817 if (IsThumb1) 7818 return LdSize == 4 ? ARM::tLDRi 7819 : LdSize == 2 ? ARM::tLDRHi 7820 : LdSize == 1 ? ARM::tLDRBi : 0; 7821 if (IsThumb2) 7822 return LdSize == 4 ? ARM::t2LDR_POST 7823 : LdSize == 2 ? ARM::t2LDRH_POST 7824 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7825 return LdSize == 4 ? ARM::LDR_POST_IMM 7826 : LdSize == 2 ? ARM::LDRH_POST 7827 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7828 } 7829 7830 /// Return the store opcode for a given store size. If store size >= 8, 7831 /// neon opcode will be returned. 7832 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7833 if (StSize >= 8) 7834 return StSize == 16 ? ARM::VST1q32wb_fixed 7835 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7836 if (IsThumb1) 7837 return StSize == 4 ? ARM::tSTRi 7838 : StSize == 2 ? ARM::tSTRHi 7839 : StSize == 1 ? ARM::tSTRBi : 0; 7840 if (IsThumb2) 7841 return StSize == 4 ? ARM::t2STR_POST 7842 : StSize == 2 ? ARM::t2STRH_POST 7843 : StSize == 1 ? ARM::t2STRB_POST : 0; 7844 return StSize == 4 ? ARM::STR_POST_IMM 7845 : StSize == 2 ? ARM::STRH_POST 7846 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7847 } 7848 7849 /// Emit a post-increment load operation with given size. The instructions 7850 /// will be added to BB at Pos. 7851 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 7852 const TargetInstrInfo *TII, const DebugLoc &dl, 7853 unsigned LdSize, unsigned Data, unsigned AddrIn, 7854 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7855 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7856 assert(LdOpc != 0 && "Should have a load opcode"); 7857 if (LdSize >= 8) { 7858 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7859 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7860 .addImm(0)); 7861 } else if (IsThumb1) { 7862 // load + update AddrIn 7863 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7864 .addReg(AddrIn).addImm(0)); 7865 MachineInstrBuilder MIB = 7866 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7867 MIB = AddDefaultT1CC(MIB); 7868 MIB.addReg(AddrIn).addImm(LdSize); 7869 AddDefaultPred(MIB); 7870 } else if (IsThumb2) { 7871 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7872 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7873 .addImm(LdSize)); 7874 } else { // arm 7875 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7876 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7877 .addReg(0).addImm(LdSize)); 7878 } 7879 } 7880 7881 /// Emit a post-increment store operation with given size. The instructions 7882 /// will be added to BB at Pos. 7883 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 7884 const TargetInstrInfo *TII, const DebugLoc &dl, 7885 unsigned StSize, unsigned Data, unsigned AddrIn, 7886 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7887 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7888 assert(StOpc != 0 && "Should have a store opcode"); 7889 if (StSize >= 8) { 7890 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7891 .addReg(AddrIn).addImm(0).addReg(Data)); 7892 } else if (IsThumb1) { 7893 // store + update AddrIn 7894 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7895 .addReg(AddrIn).addImm(0)); 7896 MachineInstrBuilder MIB = 7897 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7898 MIB = AddDefaultT1CC(MIB); 7899 MIB.addReg(AddrIn).addImm(StSize); 7900 AddDefaultPred(MIB); 7901 } else if (IsThumb2) { 7902 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7903 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7904 } else { // arm 7905 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7906 .addReg(Data).addReg(AddrIn).addReg(0) 7907 .addImm(StSize)); 7908 } 7909 } 7910 7911 MachineBasicBlock * 7912 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 7913 MachineBasicBlock *BB) const { 7914 // This pseudo instruction has 3 operands: dst, src, size 7915 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7916 // Otherwise, we will generate unrolled scalar copies. 7917 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7918 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7919 MachineFunction::iterator It = ++BB->getIterator(); 7920 7921 unsigned dest = MI.getOperand(0).getReg(); 7922 unsigned src = MI.getOperand(1).getReg(); 7923 unsigned SizeVal = MI.getOperand(2).getImm(); 7924 unsigned Align = MI.getOperand(3).getImm(); 7925 DebugLoc dl = MI.getDebugLoc(); 7926 7927 MachineFunction *MF = BB->getParent(); 7928 MachineRegisterInfo &MRI = MF->getRegInfo(); 7929 unsigned UnitSize = 0; 7930 const TargetRegisterClass *TRC = nullptr; 7931 const TargetRegisterClass *VecTRC = nullptr; 7932 7933 bool IsThumb1 = Subtarget->isThumb1Only(); 7934 bool IsThumb2 = Subtarget->isThumb2(); 7935 bool IsThumb = Subtarget->isThumb(); 7936 7937 if (Align & 1) { 7938 UnitSize = 1; 7939 } else if (Align & 2) { 7940 UnitSize = 2; 7941 } else { 7942 // Check whether we can use NEON instructions. 7943 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7944 Subtarget->hasNEON()) { 7945 if ((Align % 16 == 0) && SizeVal >= 16) 7946 UnitSize = 16; 7947 else if ((Align % 8 == 0) && SizeVal >= 8) 7948 UnitSize = 8; 7949 } 7950 // Can't use NEON instructions. 7951 if (UnitSize == 0) 7952 UnitSize = 4; 7953 } 7954 7955 // Select the correct opcode and register class for unit size load/store 7956 bool IsNeon = UnitSize >= 8; 7957 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7958 if (IsNeon) 7959 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7960 : UnitSize == 8 ? &ARM::DPRRegClass 7961 : nullptr; 7962 7963 unsigned BytesLeft = SizeVal % UnitSize; 7964 unsigned LoopSize = SizeVal - BytesLeft; 7965 7966 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7967 // Use LDR and STR to copy. 7968 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7969 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7970 unsigned srcIn = src; 7971 unsigned destIn = dest; 7972 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7973 unsigned srcOut = MRI.createVirtualRegister(TRC); 7974 unsigned destOut = MRI.createVirtualRegister(TRC); 7975 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7976 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7977 IsThumb1, IsThumb2); 7978 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7979 IsThumb1, IsThumb2); 7980 srcIn = srcOut; 7981 destIn = destOut; 7982 } 7983 7984 // Handle the leftover bytes with LDRB and STRB. 7985 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7986 // [destOut] = STRB_POST(scratch, destIn, 1) 7987 for (unsigned i = 0; i < BytesLeft; i++) { 7988 unsigned srcOut = MRI.createVirtualRegister(TRC); 7989 unsigned destOut = MRI.createVirtualRegister(TRC); 7990 unsigned scratch = MRI.createVirtualRegister(TRC); 7991 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7992 IsThumb1, IsThumb2); 7993 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7994 IsThumb1, IsThumb2); 7995 srcIn = srcOut; 7996 destIn = destOut; 7997 } 7998 MI.eraseFromParent(); // The instruction is gone now. 7999 return BB; 8000 } 8001 8002 // Expand the pseudo op to a loop. 8003 // thisMBB: 8004 // ... 8005 // movw varEnd, # --> with thumb2 8006 // movt varEnd, # 8007 // ldrcp varEnd, idx --> without thumb2 8008 // fallthrough --> loopMBB 8009 // loopMBB: 8010 // PHI varPhi, varEnd, varLoop 8011 // PHI srcPhi, src, srcLoop 8012 // PHI destPhi, dst, destLoop 8013 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8014 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8015 // subs varLoop, varPhi, #UnitSize 8016 // bne loopMBB 8017 // fallthrough --> exitMBB 8018 // exitMBB: 8019 // epilogue to handle left-over bytes 8020 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8021 // [destOut] = STRB_POST(scratch, destLoop, 1) 8022 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8023 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8024 MF->insert(It, loopMBB); 8025 MF->insert(It, exitMBB); 8026 8027 // Transfer the remainder of BB and its successor edges to exitMBB. 8028 exitMBB->splice(exitMBB->begin(), BB, 8029 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8030 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8031 8032 // Load an immediate to varEnd. 8033 unsigned varEnd = MRI.createVirtualRegister(TRC); 8034 if (Subtarget->useMovt(*MF)) { 8035 unsigned Vtmp = varEnd; 8036 if ((LoopSize & 0xFFFF0000) != 0) 8037 Vtmp = MRI.createVirtualRegister(TRC); 8038 AddDefaultPred(BuildMI(BB, dl, 8039 TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), 8040 Vtmp).addImm(LoopSize & 0xFFFF)); 8041 8042 if ((LoopSize & 0xFFFF0000) != 0) 8043 AddDefaultPred(BuildMI(BB, dl, 8044 TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), 8045 varEnd) 8046 .addReg(Vtmp) 8047 .addImm(LoopSize >> 16)); 8048 } else { 8049 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8050 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8051 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8052 8053 // MachineConstantPool wants an explicit alignment. 8054 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8055 if (Align == 0) 8056 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8057 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8058 8059 if (IsThumb) 8060 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 8061 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 8062 else 8063 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 8064 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 8065 } 8066 BB->addSuccessor(loopMBB); 8067 8068 // Generate the loop body: 8069 // varPhi = PHI(varLoop, varEnd) 8070 // srcPhi = PHI(srcLoop, src) 8071 // destPhi = PHI(destLoop, dst) 8072 MachineBasicBlock *entryBB = BB; 8073 BB = loopMBB; 8074 unsigned varLoop = MRI.createVirtualRegister(TRC); 8075 unsigned varPhi = MRI.createVirtualRegister(TRC); 8076 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8077 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8078 unsigned destLoop = MRI.createVirtualRegister(TRC); 8079 unsigned destPhi = MRI.createVirtualRegister(TRC); 8080 8081 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8082 .addReg(varLoop).addMBB(loopMBB) 8083 .addReg(varEnd).addMBB(entryBB); 8084 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8085 .addReg(srcLoop).addMBB(loopMBB) 8086 .addReg(src).addMBB(entryBB); 8087 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8088 .addReg(destLoop).addMBB(loopMBB) 8089 .addReg(dest).addMBB(entryBB); 8090 8091 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8092 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8093 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8094 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8095 IsThumb1, IsThumb2); 8096 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8097 IsThumb1, IsThumb2); 8098 8099 // Decrement loop variable by UnitSize. 8100 if (IsThumb1) { 8101 MachineInstrBuilder MIB = 8102 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 8103 MIB = AddDefaultT1CC(MIB); 8104 MIB.addReg(varPhi).addImm(UnitSize); 8105 AddDefaultPred(MIB); 8106 } else { 8107 MachineInstrBuilder MIB = 8108 BuildMI(*BB, BB->end(), dl, 8109 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8110 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 8111 MIB->getOperand(5).setReg(ARM::CPSR); 8112 MIB->getOperand(5).setIsDef(true); 8113 } 8114 BuildMI(*BB, BB->end(), dl, 8115 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8116 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8117 8118 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8119 BB->addSuccessor(loopMBB); 8120 BB->addSuccessor(exitMBB); 8121 8122 // Add epilogue to handle BytesLeft. 8123 BB = exitMBB; 8124 auto StartOfExit = exitMBB->begin(); 8125 8126 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8127 // [destOut] = STRB_POST(scratch, destLoop, 1) 8128 unsigned srcIn = srcLoop; 8129 unsigned destIn = destLoop; 8130 for (unsigned i = 0; i < BytesLeft; i++) { 8131 unsigned srcOut = MRI.createVirtualRegister(TRC); 8132 unsigned destOut = MRI.createVirtualRegister(TRC); 8133 unsigned scratch = MRI.createVirtualRegister(TRC); 8134 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8135 IsThumb1, IsThumb2); 8136 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8137 IsThumb1, IsThumb2); 8138 srcIn = srcOut; 8139 destIn = destOut; 8140 } 8141 8142 MI.eraseFromParent(); // The instruction is gone now. 8143 return BB; 8144 } 8145 8146 MachineBasicBlock * 8147 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8148 MachineBasicBlock *MBB) const { 8149 const TargetMachine &TM = getTargetMachine(); 8150 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8151 DebugLoc DL = MI.getDebugLoc(); 8152 8153 assert(Subtarget->isTargetWindows() && 8154 "__chkstk is only supported on Windows"); 8155 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8156 8157 // __chkstk takes the number of words to allocate on the stack in R4, and 8158 // returns the stack adjustment in number of bytes in R4. This will not 8159 // clober any other registers (other than the obvious lr). 8160 // 8161 // Although, technically, IP should be considered a register which may be 8162 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8163 // thumb-2 environment, so there is no interworking required. As a result, we 8164 // do not expect a veneer to be emitted by the linker, clobbering IP. 8165 // 8166 // Each module receives its own copy of __chkstk, so no import thunk is 8167 // required, again, ensuring that IP is not clobbered. 8168 // 8169 // Finally, although some linkers may theoretically provide a trampoline for 8170 // out of range calls (which is quite common due to a 32M range limitation of 8171 // branches for Thumb), we can generate the long-call version via 8172 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8173 // IP. 8174 8175 switch (TM.getCodeModel()) { 8176 case CodeModel::Small: 8177 case CodeModel::Medium: 8178 case CodeModel::Default: 8179 case CodeModel::Kernel: 8180 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8181 .addImm((unsigned)ARMCC::AL).addReg(0) 8182 .addExternalSymbol("__chkstk") 8183 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8184 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8185 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8186 break; 8187 case CodeModel::Large: 8188 case CodeModel::JITDefault: { 8189 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8190 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8191 8192 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8193 .addExternalSymbol("__chkstk"); 8194 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8195 .addImm((unsigned)ARMCC::AL).addReg(0) 8196 .addReg(Reg, RegState::Kill) 8197 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8198 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8199 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8200 break; 8201 } 8202 } 8203 8204 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 8205 ARM::SP) 8206 .addReg(ARM::SP, RegState::Kill) 8207 .addReg(ARM::R4, RegState::Kill) 8208 .setMIFlags(MachineInstr::FrameSetup))); 8209 8210 MI.eraseFromParent(); 8211 return MBB; 8212 } 8213 8214 MachineBasicBlock * 8215 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8216 MachineBasicBlock *MBB) const { 8217 DebugLoc DL = MI.getDebugLoc(); 8218 MachineFunction *MF = MBB->getParent(); 8219 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8220 8221 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8222 MF->insert(++MBB->getIterator(), ContBB); 8223 ContBB->splice(ContBB->begin(), MBB, 8224 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8225 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8226 8227 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8228 MF->push_back(TrapBB); 8229 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 8230 MBB->addSuccessor(TrapBB); 8231 8232 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 8233 .addReg(MI.getOperand(0).getReg()) 8234 .addMBB(TrapBB); 8235 AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB)); 8236 MBB->addSuccessor(ContBB); 8237 8238 MI.eraseFromParent(); 8239 return ContBB; 8240 } 8241 8242 MachineBasicBlock * 8243 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8244 MachineBasicBlock *BB) const { 8245 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8246 DebugLoc dl = MI.getDebugLoc(); 8247 bool isThumb2 = Subtarget->isThumb2(); 8248 switch (MI.getOpcode()) { 8249 default: { 8250 MI.dump(); 8251 llvm_unreachable("Unexpected instr type to insert"); 8252 } 8253 8254 // Thumb1 post-indexed loads are really just single-register LDMs. 8255 case ARM::tLDR_postidx: { 8256 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8257 .addOperand(MI.getOperand(1)) // Rn_wb 8258 .addOperand(MI.getOperand(2)) // Rn 8259 .addOperand(MI.getOperand(3)) // PredImm 8260 .addOperand(MI.getOperand(4)) // PredReg 8261 .addOperand(MI.getOperand(0)); // Rt 8262 MI.eraseFromParent(); 8263 return BB; 8264 } 8265 8266 // The Thumb2 pre-indexed stores have the same MI operands, they just 8267 // define them differently in the .td files from the isel patterns, so 8268 // they need pseudos. 8269 case ARM::t2STR_preidx: 8270 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8271 return BB; 8272 case ARM::t2STRB_preidx: 8273 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 8274 return BB; 8275 case ARM::t2STRH_preidx: 8276 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 8277 return BB; 8278 8279 case ARM::STRi_preidx: 8280 case ARM::STRBi_preidx: { 8281 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 8282 : ARM::STRB_PRE_IMM; 8283 // Decode the offset. 8284 unsigned Offset = MI.getOperand(4).getImm(); 8285 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8286 Offset = ARM_AM::getAM2Offset(Offset); 8287 if (isSub) 8288 Offset = -Offset; 8289 8290 MachineMemOperand *MMO = *MI.memoperands_begin(); 8291 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8292 .addOperand(MI.getOperand(0)) // Rn_wb 8293 .addOperand(MI.getOperand(1)) // Rt 8294 .addOperand(MI.getOperand(2)) // Rn 8295 .addImm(Offset) // offset (skip GPR==zero_reg) 8296 .addOperand(MI.getOperand(5)) // pred 8297 .addOperand(MI.getOperand(6)) 8298 .addMemOperand(MMO); 8299 MI.eraseFromParent(); 8300 return BB; 8301 } 8302 case ARM::STRr_preidx: 8303 case ARM::STRBr_preidx: 8304 case ARM::STRH_preidx: { 8305 unsigned NewOpc; 8306 switch (MI.getOpcode()) { 8307 default: llvm_unreachable("unexpected opcode!"); 8308 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8309 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8310 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8311 } 8312 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8313 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 8314 MIB.addOperand(MI.getOperand(i)); 8315 MI.eraseFromParent(); 8316 return BB; 8317 } 8318 8319 case ARM::tMOVCCr_pseudo: { 8320 // To "insert" a SELECT_CC instruction, we actually have to insert the 8321 // diamond control-flow pattern. The incoming instruction knows the 8322 // destination vreg to set, the condition code register to branch on, the 8323 // true/false values to select between, and a branch opcode to use. 8324 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8325 MachineFunction::iterator It = ++BB->getIterator(); 8326 8327 // thisMBB: 8328 // ... 8329 // TrueVal = ... 8330 // cmpTY ccX, r1, r2 8331 // bCC copy1MBB 8332 // fallthrough --> copy0MBB 8333 MachineBasicBlock *thisMBB = BB; 8334 MachineFunction *F = BB->getParent(); 8335 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8336 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8337 F->insert(It, copy0MBB); 8338 F->insert(It, sinkMBB); 8339 8340 // Transfer the remainder of BB and its successor edges to sinkMBB. 8341 sinkMBB->splice(sinkMBB->begin(), BB, 8342 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8343 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8344 8345 BB->addSuccessor(copy0MBB); 8346 BB->addSuccessor(sinkMBB); 8347 8348 BuildMI(BB, dl, TII->get(ARM::tBcc)) 8349 .addMBB(sinkMBB) 8350 .addImm(MI.getOperand(3).getImm()) 8351 .addReg(MI.getOperand(4).getReg()); 8352 8353 // copy0MBB: 8354 // %FalseValue = ... 8355 // # fallthrough to sinkMBB 8356 BB = copy0MBB; 8357 8358 // Update machine-CFG edges 8359 BB->addSuccessor(sinkMBB); 8360 8361 // sinkMBB: 8362 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8363 // ... 8364 BB = sinkMBB; 8365 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 8366 .addReg(MI.getOperand(1).getReg()) 8367 .addMBB(copy0MBB) 8368 .addReg(MI.getOperand(2).getReg()) 8369 .addMBB(thisMBB); 8370 8371 MI.eraseFromParent(); // The pseudo instruction is gone now. 8372 return BB; 8373 } 8374 8375 case ARM::BCCi64: 8376 case ARM::BCCZi64: { 8377 // If there is an unconditional branch to the other successor, remove it. 8378 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8379 8380 // Compare both parts that make up the double comparison separately for 8381 // equality. 8382 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 8383 8384 unsigned LHS1 = MI.getOperand(1).getReg(); 8385 unsigned LHS2 = MI.getOperand(2).getReg(); 8386 if (RHSisZero) { 8387 AddDefaultPred(BuildMI(BB, dl, 8388 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8389 .addReg(LHS1).addImm(0)); 8390 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8391 .addReg(LHS2).addImm(0) 8392 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8393 } else { 8394 unsigned RHS1 = MI.getOperand(3).getReg(); 8395 unsigned RHS2 = MI.getOperand(4).getReg(); 8396 AddDefaultPred(BuildMI(BB, dl, 8397 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8398 .addReg(LHS1).addReg(RHS1)); 8399 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8400 .addReg(LHS2).addReg(RHS2) 8401 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8402 } 8403 8404 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 8405 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8406 if (MI.getOperand(0).getImm() == ARMCC::NE) 8407 std::swap(destMBB, exitMBB); 8408 8409 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8410 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8411 if (isThumb2) 8412 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8413 else 8414 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8415 8416 MI.eraseFromParent(); // The pseudo instruction is gone now. 8417 return BB; 8418 } 8419 8420 case ARM::Int_eh_sjlj_setjmp: 8421 case ARM::Int_eh_sjlj_setjmp_nofp: 8422 case ARM::tInt_eh_sjlj_setjmp: 8423 case ARM::t2Int_eh_sjlj_setjmp: 8424 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8425 return BB; 8426 8427 case ARM::Int_eh_sjlj_setup_dispatch: 8428 EmitSjLjDispatchBlock(MI, BB); 8429 return BB; 8430 8431 case ARM::ABS: 8432 case ARM::t2ABS: { 8433 // To insert an ABS instruction, we have to insert the 8434 // diamond control-flow pattern. The incoming instruction knows the 8435 // source vreg to test against 0, the destination vreg to set, 8436 // the condition code register to branch on, the 8437 // true/false values to select between, and a branch opcode to use. 8438 // It transforms 8439 // V1 = ABS V0 8440 // into 8441 // V2 = MOVS V0 8442 // BCC (branch to SinkBB if V0 >= 0) 8443 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8444 // SinkBB: V1 = PHI(V2, V3) 8445 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8446 MachineFunction::iterator BBI = ++BB->getIterator(); 8447 MachineFunction *Fn = BB->getParent(); 8448 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8449 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8450 Fn->insert(BBI, RSBBB); 8451 Fn->insert(BBI, SinkBB); 8452 8453 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 8454 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 8455 bool ABSSrcKIll = MI.getOperand(1).isKill(); 8456 bool isThumb2 = Subtarget->isThumb2(); 8457 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8458 // In Thumb mode S must not be specified if source register is the SP or 8459 // PC and if destination register is the SP, so restrict register class 8460 unsigned NewRsbDstReg = 8461 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8462 8463 // Transfer the remainder of BB and its successor edges to sinkMBB. 8464 SinkBB->splice(SinkBB->begin(), BB, 8465 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8466 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8467 8468 BB->addSuccessor(RSBBB); 8469 BB->addSuccessor(SinkBB); 8470 8471 // fall through to SinkMBB 8472 RSBBB->addSuccessor(SinkBB); 8473 8474 // insert a cmp at the end of BB 8475 AddDefaultPred(BuildMI(BB, dl, 8476 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8477 .addReg(ABSSrcReg).addImm(0)); 8478 8479 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8480 BuildMI(BB, dl, 8481 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8482 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8483 8484 // insert rsbri in RSBBB 8485 // Note: BCC and rsbri will be converted into predicated rsbmi 8486 // by if-conversion pass 8487 BuildMI(*RSBBB, RSBBB->begin(), dl, 8488 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8489 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8490 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8491 8492 // insert PHI in SinkBB, 8493 // reuse ABSDstReg to not change uses of ABS instruction 8494 BuildMI(*SinkBB, SinkBB->begin(), dl, 8495 TII->get(ARM::PHI), ABSDstReg) 8496 .addReg(NewRsbDstReg).addMBB(RSBBB) 8497 .addReg(ABSSrcReg).addMBB(BB); 8498 8499 // remove ABS instruction 8500 MI.eraseFromParent(); 8501 8502 // return last added BB 8503 return SinkBB; 8504 } 8505 case ARM::COPY_STRUCT_BYVAL_I32: 8506 ++NumLoopByVals; 8507 return EmitStructByval(MI, BB); 8508 case ARM::WIN__CHKSTK: 8509 return EmitLowered__chkstk(MI, BB); 8510 case ARM::WIN__DBZCHK: 8511 return EmitLowered__dbzchk(MI, BB); 8512 } 8513 } 8514 8515 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8516 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8517 /// instead of as a custom inserter because we need the use list from the SDNode. 8518 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8519 MachineInstr &MI, const SDNode *Node) { 8520 bool isThumb1 = Subtarget->isThumb1Only(); 8521 8522 DebugLoc DL = MI.getDebugLoc(); 8523 MachineFunction *MF = MI.getParent()->getParent(); 8524 MachineRegisterInfo &MRI = MF->getRegInfo(); 8525 MachineInstrBuilder MIB(*MF, MI); 8526 8527 // If the new dst/src is unused mark it as dead. 8528 if (!Node->hasAnyUseOfValue(0)) { 8529 MI.getOperand(0).setIsDead(true); 8530 } 8531 if (!Node->hasAnyUseOfValue(1)) { 8532 MI.getOperand(1).setIsDead(true); 8533 } 8534 8535 // The MEMCPY both defines and kills the scratch registers. 8536 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 8537 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8538 : &ARM::GPRRegClass); 8539 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8540 } 8541 } 8542 8543 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8544 SDNode *Node) const { 8545 if (MI.getOpcode() == ARM::MEMCPY) { 8546 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8547 return; 8548 } 8549 8550 const MCInstrDesc *MCID = &MI.getDesc(); 8551 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8552 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8553 // operand is still set to noreg. If needed, set the optional operand's 8554 // register to CPSR, and remove the redundant implicit def. 8555 // 8556 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8557 8558 // Rename pseudo opcodes. 8559 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 8560 if (NewOpc) { 8561 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8562 MCID = &TII->get(NewOpc); 8563 8564 assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 && 8565 "converted opcode should be the same except for cc_out"); 8566 8567 MI.setDesc(*MCID); 8568 8569 // Add the optional cc_out operand 8570 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8571 } 8572 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8573 8574 // Any ARM instruction that sets the 's' bit should specify an optional 8575 // "cc_out" operand in the last operand position. 8576 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8577 assert(!NewOpc && "Optional cc_out operand required"); 8578 return; 8579 } 8580 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8581 // since we already have an optional CPSR def. 8582 bool definesCPSR = false; 8583 bool deadCPSR = false; 8584 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 8585 ++i) { 8586 const MachineOperand &MO = MI.getOperand(i); 8587 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8588 definesCPSR = true; 8589 if (MO.isDead()) 8590 deadCPSR = true; 8591 MI.RemoveOperand(i); 8592 break; 8593 } 8594 } 8595 if (!definesCPSR) { 8596 assert(!NewOpc && "Optional cc_out operand required"); 8597 return; 8598 } 8599 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8600 if (deadCPSR) { 8601 assert(!MI.getOperand(ccOutIdx).getReg() && 8602 "expect uninitialized optional cc_out operand"); 8603 return; 8604 } 8605 8606 // If this instruction was defined with an optional CPSR def and its dag node 8607 // had a live implicit CPSR def, then activate the optional CPSR def. 8608 MachineOperand &MO = MI.getOperand(ccOutIdx); 8609 MO.setReg(ARM::CPSR); 8610 MO.setIsDef(true); 8611 } 8612 8613 //===----------------------------------------------------------------------===// 8614 // ARM Optimization Hooks 8615 //===----------------------------------------------------------------------===// 8616 8617 // Helper function that checks if N is a null or all ones constant. 8618 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8619 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8620 } 8621 8622 // Return true if N is conditionally 0 or all ones. 8623 // Detects these expressions where cc is an i1 value: 8624 // 8625 // (select cc 0, y) [AllOnes=0] 8626 // (select cc y, 0) [AllOnes=0] 8627 // (zext cc) [AllOnes=0] 8628 // (sext cc) [AllOnes=0/1] 8629 // (select cc -1, y) [AllOnes=1] 8630 // (select cc y, -1) [AllOnes=1] 8631 // 8632 // Invert is set when N is the null/all ones constant when CC is false. 8633 // OtherOp is set to the alternative value of N. 8634 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8635 SDValue &CC, bool &Invert, 8636 SDValue &OtherOp, 8637 SelectionDAG &DAG) { 8638 switch (N->getOpcode()) { 8639 default: return false; 8640 case ISD::SELECT: { 8641 CC = N->getOperand(0); 8642 SDValue N1 = N->getOperand(1); 8643 SDValue N2 = N->getOperand(2); 8644 if (isZeroOrAllOnes(N1, AllOnes)) { 8645 Invert = false; 8646 OtherOp = N2; 8647 return true; 8648 } 8649 if (isZeroOrAllOnes(N2, AllOnes)) { 8650 Invert = true; 8651 OtherOp = N1; 8652 return true; 8653 } 8654 return false; 8655 } 8656 case ISD::ZERO_EXTEND: 8657 // (zext cc) can never be the all ones value. 8658 if (AllOnes) 8659 return false; 8660 // Fall through. 8661 case ISD::SIGN_EXTEND: { 8662 SDLoc dl(N); 8663 EVT VT = N->getValueType(0); 8664 CC = N->getOperand(0); 8665 if (CC.getValueType() != MVT::i1) 8666 return false; 8667 Invert = !AllOnes; 8668 if (AllOnes) 8669 // When looking for an AllOnes constant, N is an sext, and the 'other' 8670 // value is 0. 8671 OtherOp = DAG.getConstant(0, dl, VT); 8672 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8673 // When looking for a 0 constant, N can be zext or sext. 8674 OtherOp = DAG.getConstant(1, dl, VT); 8675 else 8676 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8677 VT); 8678 return true; 8679 } 8680 } 8681 } 8682 8683 // Combine a constant select operand into its use: 8684 // 8685 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8686 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8687 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8688 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8689 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8690 // 8691 // The transform is rejected if the select doesn't have a constant operand that 8692 // is null, or all ones when AllOnes is set. 8693 // 8694 // Also recognize sext/zext from i1: 8695 // 8696 // (add (zext cc), x) -> (select cc (add x, 1), x) 8697 // (add (sext cc), x) -> (select cc (add x, -1), x) 8698 // 8699 // These transformations eventually create predicated instructions. 8700 // 8701 // @param N The node to transform. 8702 // @param Slct The N operand that is a select. 8703 // @param OtherOp The other N operand (x above). 8704 // @param DCI Context. 8705 // @param AllOnes Require the select constant to be all ones instead of null. 8706 // @returns The new node, or SDValue() on failure. 8707 static 8708 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8709 TargetLowering::DAGCombinerInfo &DCI, 8710 bool AllOnes = false) { 8711 SelectionDAG &DAG = DCI.DAG; 8712 EVT VT = N->getValueType(0); 8713 SDValue NonConstantVal; 8714 SDValue CCOp; 8715 bool SwapSelectOps; 8716 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8717 NonConstantVal, DAG)) 8718 return SDValue(); 8719 8720 // Slct is now know to be the desired identity constant when CC is true. 8721 SDValue TrueVal = OtherOp; 8722 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8723 OtherOp, NonConstantVal); 8724 // Unless SwapSelectOps says CC should be false. 8725 if (SwapSelectOps) 8726 std::swap(TrueVal, FalseVal); 8727 8728 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8729 CCOp, TrueVal, FalseVal); 8730 } 8731 8732 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8733 static 8734 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8735 TargetLowering::DAGCombinerInfo &DCI) { 8736 SDValue N0 = N->getOperand(0); 8737 SDValue N1 = N->getOperand(1); 8738 if (N0.getNode()->hasOneUse()) 8739 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 8740 return Result; 8741 if (N1.getNode()->hasOneUse()) 8742 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 8743 return Result; 8744 return SDValue(); 8745 } 8746 8747 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8748 // (only after legalization). 8749 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8750 TargetLowering::DAGCombinerInfo &DCI, 8751 const ARMSubtarget *Subtarget) { 8752 8753 // Only perform optimization if after legalize, and if NEON is available. We 8754 // also expected both operands to be BUILD_VECTORs. 8755 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8756 || N0.getOpcode() != ISD::BUILD_VECTOR 8757 || N1.getOpcode() != ISD::BUILD_VECTOR) 8758 return SDValue(); 8759 8760 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8761 EVT VT = N->getValueType(0); 8762 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8763 return SDValue(); 8764 8765 // Check that the vector operands are of the right form. 8766 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8767 // operands, where N is the size of the formed vector. 8768 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8769 // index such that we have a pair wise add pattern. 8770 8771 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8772 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8773 return SDValue(); 8774 SDValue Vec = N0->getOperand(0)->getOperand(0); 8775 SDNode *V = Vec.getNode(); 8776 unsigned nextIndex = 0; 8777 8778 // For each operands to the ADD which are BUILD_VECTORs, 8779 // check to see if each of their operands are an EXTRACT_VECTOR with 8780 // the same vector and appropriate index. 8781 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8782 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8783 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8784 8785 SDValue ExtVec0 = N0->getOperand(i); 8786 SDValue ExtVec1 = N1->getOperand(i); 8787 8788 // First operand is the vector, verify its the same. 8789 if (V != ExtVec0->getOperand(0).getNode() || 8790 V != ExtVec1->getOperand(0).getNode()) 8791 return SDValue(); 8792 8793 // Second is the constant, verify its correct. 8794 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8795 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8796 8797 // For the constant, we want to see all the even or all the odd. 8798 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8799 || C1->getZExtValue() != nextIndex+1) 8800 return SDValue(); 8801 8802 // Increment index. 8803 nextIndex+=2; 8804 } else 8805 return SDValue(); 8806 } 8807 8808 // Create VPADDL node. 8809 SelectionDAG &DAG = DCI.DAG; 8810 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8811 8812 SDLoc dl(N); 8813 8814 // Build operand list. 8815 SmallVector<SDValue, 8> Ops; 8816 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8817 TLI.getPointerTy(DAG.getDataLayout()))); 8818 8819 // Input is the vector. 8820 Ops.push_back(Vec); 8821 8822 // Get widened type and narrowed type. 8823 MVT widenType; 8824 unsigned numElem = VT.getVectorNumElements(); 8825 8826 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8827 switch (inputLaneType.getSimpleVT().SimpleTy) { 8828 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8829 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8830 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8831 default: 8832 llvm_unreachable("Invalid vector element type for padd optimization."); 8833 } 8834 8835 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8836 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8837 return DAG.getNode(ExtOp, dl, VT, tmp); 8838 } 8839 8840 static SDValue findMUL_LOHI(SDValue V) { 8841 if (V->getOpcode() == ISD::UMUL_LOHI || 8842 V->getOpcode() == ISD::SMUL_LOHI) 8843 return V; 8844 return SDValue(); 8845 } 8846 8847 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8848 TargetLowering::DAGCombinerInfo &DCI, 8849 const ARMSubtarget *Subtarget) { 8850 8851 // Look for multiply add opportunities. 8852 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8853 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8854 // a glue link from the first add to the second add. 8855 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8856 // a S/UMLAL instruction. 8857 // UMUL_LOHI 8858 // / :lo \ :hi 8859 // / \ [no multiline comment] 8860 // loAdd -> ADDE | 8861 // \ :glue / 8862 // \ / 8863 // ADDC <- hiAdd 8864 // 8865 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8866 SDValue AddcOp0 = AddcNode->getOperand(0); 8867 SDValue AddcOp1 = AddcNode->getOperand(1); 8868 8869 // Check if the two operands are from the same mul_lohi node. 8870 if (AddcOp0.getNode() == AddcOp1.getNode()) 8871 return SDValue(); 8872 8873 assert(AddcNode->getNumValues() == 2 && 8874 AddcNode->getValueType(0) == MVT::i32 && 8875 "Expect ADDC with two result values. First: i32"); 8876 8877 // Check that we have a glued ADDC node. 8878 if (AddcNode->getValueType(1) != MVT::Glue) 8879 return SDValue(); 8880 8881 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8882 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8883 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8884 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8885 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8886 return SDValue(); 8887 8888 // Look for the glued ADDE. 8889 SDNode* AddeNode = AddcNode->getGluedUser(); 8890 if (!AddeNode) 8891 return SDValue(); 8892 8893 // Make sure it is really an ADDE. 8894 if (AddeNode->getOpcode() != ISD::ADDE) 8895 return SDValue(); 8896 8897 assert(AddeNode->getNumOperands() == 3 && 8898 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8899 "ADDE node has the wrong inputs"); 8900 8901 // Check for the triangle shape. 8902 SDValue AddeOp0 = AddeNode->getOperand(0); 8903 SDValue AddeOp1 = AddeNode->getOperand(1); 8904 8905 // Make sure that the ADDE operands are not coming from the same node. 8906 if (AddeOp0.getNode() == AddeOp1.getNode()) 8907 return SDValue(); 8908 8909 // Find the MUL_LOHI node walking up ADDE's operands. 8910 bool IsLeftOperandMUL = false; 8911 SDValue MULOp = findMUL_LOHI(AddeOp0); 8912 if (MULOp == SDValue()) 8913 MULOp = findMUL_LOHI(AddeOp1); 8914 else 8915 IsLeftOperandMUL = true; 8916 if (MULOp == SDValue()) 8917 return SDValue(); 8918 8919 // Figure out the right opcode. 8920 unsigned Opc = MULOp->getOpcode(); 8921 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8922 8923 // Figure out the high and low input values to the MLAL node. 8924 SDValue* HiAdd = nullptr; 8925 SDValue* LoMul = nullptr; 8926 SDValue* LowAdd = nullptr; 8927 8928 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8929 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8930 return SDValue(); 8931 8932 if (IsLeftOperandMUL) 8933 HiAdd = &AddeOp1; 8934 else 8935 HiAdd = &AddeOp0; 8936 8937 8938 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8939 // whose low result is fed to the ADDC we are checking. 8940 8941 if (AddcOp0 == MULOp.getValue(0)) { 8942 LoMul = &AddcOp0; 8943 LowAdd = &AddcOp1; 8944 } 8945 if (AddcOp1 == MULOp.getValue(0)) { 8946 LoMul = &AddcOp1; 8947 LowAdd = &AddcOp0; 8948 } 8949 8950 if (!LoMul) 8951 return SDValue(); 8952 8953 // Create the merged node. 8954 SelectionDAG &DAG = DCI.DAG; 8955 8956 // Build operand list. 8957 SmallVector<SDValue, 8> Ops; 8958 Ops.push_back(LoMul->getOperand(0)); 8959 Ops.push_back(LoMul->getOperand(1)); 8960 Ops.push_back(*LowAdd); 8961 Ops.push_back(*HiAdd); 8962 8963 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8964 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8965 8966 // Replace the ADDs' nodes uses by the MLA node's values. 8967 SDValue HiMLALResult(MLALNode.getNode(), 1); 8968 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8969 8970 SDValue LoMLALResult(MLALNode.getNode(), 0); 8971 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8972 8973 // Return original node to notify the driver to stop replacing. 8974 SDValue resNode(AddcNode, 0); 8975 return resNode; 8976 } 8977 8978 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode, 8979 TargetLowering::DAGCombinerInfo &DCI, 8980 const ARMSubtarget *Subtarget) { 8981 // UMAAL is similar to UMLAL except that it adds two unsigned values. 8982 // While trying to combine for the other MLAL nodes, first search for the 8983 // chance to use UMAAL. Check if Addc uses another addc node which can first 8984 // be combined into a UMLAL. The other pattern is AddcNode being combined 8985 // into an UMLAL and then using another addc is handled in ISelDAGToDAG. 8986 8987 if (!Subtarget->hasV6Ops() || 8988 (Subtarget->isThumb() && !Subtarget->hasThumb2())) 8989 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 8990 8991 SDNode *PrevAddc = nullptr; 8992 if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC) 8993 PrevAddc = AddcNode->getOperand(0).getNode(); 8994 else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC) 8995 PrevAddc = AddcNode->getOperand(1).getNode(); 8996 8997 // If there's no addc chains, just return a search for any MLAL. 8998 if (PrevAddc == nullptr) 8999 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9000 9001 // Try to convert the addc operand to an MLAL and if that fails try to 9002 // combine AddcNode. 9003 SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget); 9004 if (MLAL != SDValue(PrevAddc, 0)) 9005 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9006 9007 // Find the converted UMAAL or quit if it doesn't exist. 9008 SDNode *UmlalNode = nullptr; 9009 SDValue AddHi; 9010 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9011 UmlalNode = AddcNode->getOperand(0).getNode(); 9012 AddHi = AddcNode->getOperand(1); 9013 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9014 UmlalNode = AddcNode->getOperand(1).getNode(); 9015 AddHi = AddcNode->getOperand(0); 9016 } else { 9017 return SDValue(); 9018 } 9019 9020 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9021 // the ADDC as well as Zero. 9022 auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3)); 9023 9024 if (!Zero || Zero->getZExtValue() != 0) 9025 return SDValue(); 9026 9027 // Check that we have a glued ADDC node. 9028 if (AddcNode->getValueType(1) != MVT::Glue) 9029 return SDValue(); 9030 9031 // Look for the glued ADDE. 9032 SDNode* AddeNode = AddcNode->getGluedUser(); 9033 if (!AddeNode) 9034 return SDValue(); 9035 9036 if ((AddeNode->getOperand(0).getNode() == Zero && 9037 AddeNode->getOperand(1).getNode() == UmlalNode) || 9038 (AddeNode->getOperand(0).getNode() == UmlalNode && 9039 AddeNode->getOperand(1).getNode() == Zero)) { 9040 9041 SelectionDAG &DAG = DCI.DAG; 9042 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9043 UmlalNode->getOperand(2), AddHi }; 9044 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9045 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9046 9047 // Replace the ADDs' nodes uses by the UMAAL node's values. 9048 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9049 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9050 9051 // Return original node to notify the driver to stop replacing. 9052 return SDValue(AddcNode, 0); 9053 } 9054 return SDValue(); 9055 } 9056 9057 /// PerformADDCCombine - Target-specific dag combine transform from 9058 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or 9059 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 9060 static SDValue PerformADDCCombine(SDNode *N, 9061 TargetLowering::DAGCombinerInfo &DCI, 9062 const ARMSubtarget *Subtarget) { 9063 9064 if (Subtarget->isThumb1Only()) return SDValue(); 9065 9066 // Only perform the checks after legalize when the pattern is available. 9067 if (DCI.isBeforeLegalize()) return SDValue(); 9068 9069 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 9070 } 9071 9072 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 9073 /// operands N0 and N1. This is a helper for PerformADDCombine that is 9074 /// called with the default operands, and if that fails, with commuted 9075 /// operands. 9076 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 9077 TargetLowering::DAGCombinerInfo &DCI, 9078 const ARMSubtarget *Subtarget){ 9079 9080 // Attempt to create vpaddl for this add. 9081 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget)) 9082 return Result; 9083 9084 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9085 if (N0.getNode()->hasOneUse()) 9086 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 9087 return Result; 9088 return SDValue(); 9089 } 9090 9091 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 9092 /// 9093 static SDValue PerformADDCombine(SDNode *N, 9094 TargetLowering::DAGCombinerInfo &DCI, 9095 const ARMSubtarget *Subtarget) { 9096 SDValue N0 = N->getOperand(0); 9097 SDValue N1 = N->getOperand(1); 9098 9099 // First try with the default operand order. 9100 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 9101 return Result; 9102 9103 // If that didn't work, try again with the operands commuted. 9104 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 9105 } 9106 9107 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 9108 /// 9109 static SDValue PerformSUBCombine(SDNode *N, 9110 TargetLowering::DAGCombinerInfo &DCI) { 9111 SDValue N0 = N->getOperand(0); 9112 SDValue N1 = N->getOperand(1); 9113 9114 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9115 if (N1.getNode()->hasOneUse()) 9116 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 9117 return Result; 9118 9119 return SDValue(); 9120 } 9121 9122 /// PerformVMULCombine 9123 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 9124 /// special multiplier accumulator forwarding. 9125 /// vmul d3, d0, d2 9126 /// vmla d3, d1, d2 9127 /// is faster than 9128 /// vadd d3, d0, d1 9129 /// vmul d3, d3, d2 9130 // However, for (A + B) * (A + B), 9131 // vadd d2, d0, d1 9132 // vmul d3, d0, d2 9133 // vmla d3, d1, d2 9134 // is slower than 9135 // vadd d2, d0, d1 9136 // vmul d3, d2, d2 9137 static SDValue PerformVMULCombine(SDNode *N, 9138 TargetLowering::DAGCombinerInfo &DCI, 9139 const ARMSubtarget *Subtarget) { 9140 if (!Subtarget->hasVMLxForwarding()) 9141 return SDValue(); 9142 9143 SelectionDAG &DAG = DCI.DAG; 9144 SDValue N0 = N->getOperand(0); 9145 SDValue N1 = N->getOperand(1); 9146 unsigned Opcode = N0.getOpcode(); 9147 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9148 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 9149 Opcode = N1.getOpcode(); 9150 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9151 Opcode != ISD::FADD && Opcode != ISD::FSUB) 9152 return SDValue(); 9153 std::swap(N0, N1); 9154 } 9155 9156 if (N0 == N1) 9157 return SDValue(); 9158 9159 EVT VT = N->getValueType(0); 9160 SDLoc DL(N); 9161 SDValue N00 = N0->getOperand(0); 9162 SDValue N01 = N0->getOperand(1); 9163 return DAG.getNode(Opcode, DL, VT, 9164 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 9165 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 9166 } 9167 9168 static SDValue PerformMULCombine(SDNode *N, 9169 TargetLowering::DAGCombinerInfo &DCI, 9170 const ARMSubtarget *Subtarget) { 9171 SelectionDAG &DAG = DCI.DAG; 9172 9173 if (Subtarget->isThumb1Only()) 9174 return SDValue(); 9175 9176 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9177 return SDValue(); 9178 9179 EVT VT = N->getValueType(0); 9180 if (VT.is64BitVector() || VT.is128BitVector()) 9181 return PerformVMULCombine(N, DCI, Subtarget); 9182 if (VT != MVT::i32) 9183 return SDValue(); 9184 9185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9186 if (!C) 9187 return SDValue(); 9188 9189 int64_t MulAmt = C->getSExtValue(); 9190 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 9191 9192 ShiftAmt = ShiftAmt & (32 - 1); 9193 SDValue V = N->getOperand(0); 9194 SDLoc DL(N); 9195 9196 SDValue Res; 9197 MulAmt >>= ShiftAmt; 9198 9199 if (MulAmt >= 0) { 9200 if (isPowerOf2_32(MulAmt - 1)) { 9201 // (mul x, 2^N + 1) => (add (shl x, N), x) 9202 Res = DAG.getNode(ISD::ADD, DL, VT, 9203 V, 9204 DAG.getNode(ISD::SHL, DL, VT, 9205 V, 9206 DAG.getConstant(Log2_32(MulAmt - 1), DL, 9207 MVT::i32))); 9208 } else if (isPowerOf2_32(MulAmt + 1)) { 9209 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9210 Res = DAG.getNode(ISD::SUB, DL, VT, 9211 DAG.getNode(ISD::SHL, DL, VT, 9212 V, 9213 DAG.getConstant(Log2_32(MulAmt + 1), DL, 9214 MVT::i32)), 9215 V); 9216 } else 9217 return SDValue(); 9218 } else { 9219 uint64_t MulAmtAbs = -MulAmt; 9220 if (isPowerOf2_32(MulAmtAbs + 1)) { 9221 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 9222 Res = DAG.getNode(ISD::SUB, DL, VT, 9223 V, 9224 DAG.getNode(ISD::SHL, DL, VT, 9225 V, 9226 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 9227 MVT::i32))); 9228 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 9229 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 9230 Res = DAG.getNode(ISD::ADD, DL, VT, 9231 V, 9232 DAG.getNode(ISD::SHL, DL, VT, 9233 V, 9234 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 9235 MVT::i32))); 9236 Res = DAG.getNode(ISD::SUB, DL, VT, 9237 DAG.getConstant(0, DL, MVT::i32), Res); 9238 9239 } else 9240 return SDValue(); 9241 } 9242 9243 if (ShiftAmt != 0) 9244 Res = DAG.getNode(ISD::SHL, DL, VT, 9245 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 9246 9247 // Do not add new nodes to DAG combiner worklist. 9248 DCI.CombineTo(N, Res, false); 9249 return SDValue(); 9250 } 9251 9252 static SDValue PerformANDCombine(SDNode *N, 9253 TargetLowering::DAGCombinerInfo &DCI, 9254 const ARMSubtarget *Subtarget) { 9255 9256 // Attempt to use immediate-form VBIC 9257 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9258 SDLoc dl(N); 9259 EVT VT = N->getValueType(0); 9260 SelectionDAG &DAG = DCI.DAG; 9261 9262 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9263 return SDValue(); 9264 9265 APInt SplatBits, SplatUndef; 9266 unsigned SplatBitSize; 9267 bool HasAnyUndefs; 9268 if (BVN && 9269 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9270 if (SplatBitSize <= 64) { 9271 EVT VbicVT; 9272 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9273 SplatUndef.getZExtValue(), SplatBitSize, 9274 DAG, dl, VbicVT, VT.is128BitVector(), 9275 OtherModImm); 9276 if (Val.getNode()) { 9277 SDValue Input = 9278 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9279 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9280 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9281 } 9282 } 9283 } 9284 9285 if (!Subtarget->isThumb1Only()) { 9286 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9287 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9288 return Result; 9289 } 9290 9291 return SDValue(); 9292 } 9293 9294 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9295 static SDValue PerformORCombine(SDNode *N, 9296 TargetLowering::DAGCombinerInfo &DCI, 9297 const ARMSubtarget *Subtarget) { 9298 // Attempt to use immediate-form VORR 9299 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9300 SDLoc dl(N); 9301 EVT VT = N->getValueType(0); 9302 SelectionDAG &DAG = DCI.DAG; 9303 9304 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9305 return SDValue(); 9306 9307 APInt SplatBits, SplatUndef; 9308 unsigned SplatBitSize; 9309 bool HasAnyUndefs; 9310 if (BVN && Subtarget->hasNEON() && 9311 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9312 if (SplatBitSize <= 64) { 9313 EVT VorrVT; 9314 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9315 SplatUndef.getZExtValue(), SplatBitSize, 9316 DAG, dl, VorrVT, VT.is128BitVector(), 9317 OtherModImm); 9318 if (Val.getNode()) { 9319 SDValue Input = 9320 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9321 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9322 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9323 } 9324 } 9325 } 9326 9327 if (!Subtarget->isThumb1Only()) { 9328 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9329 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9330 return Result; 9331 } 9332 9333 // The code below optimizes (or (and X, Y), Z). 9334 // The AND operand needs to have a single user to make these optimizations 9335 // profitable. 9336 SDValue N0 = N->getOperand(0); 9337 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9338 return SDValue(); 9339 SDValue N1 = N->getOperand(1); 9340 9341 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9342 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9343 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9344 APInt SplatUndef; 9345 unsigned SplatBitSize; 9346 bool HasAnyUndefs; 9347 9348 APInt SplatBits0, SplatBits1; 9349 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9350 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9351 // Ensure that the second operand of both ands are constants 9352 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9353 HasAnyUndefs) && !HasAnyUndefs) { 9354 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9355 HasAnyUndefs) && !HasAnyUndefs) { 9356 // Ensure that the bit width of the constants are the same and that 9357 // the splat arguments are logical inverses as per the pattern we 9358 // are trying to simplify. 9359 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9360 SplatBits0 == ~SplatBits1) { 9361 // Canonicalize the vector type to make instruction selection 9362 // simpler. 9363 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9364 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9365 N0->getOperand(1), 9366 N0->getOperand(0), 9367 N1->getOperand(0)); 9368 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9369 } 9370 } 9371 } 9372 } 9373 9374 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9375 // reasonable. 9376 9377 // BFI is only available on V6T2+ 9378 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9379 return SDValue(); 9380 9381 SDLoc DL(N); 9382 // 1) or (and A, mask), val => ARMbfi A, val, mask 9383 // iff (val & mask) == val 9384 // 9385 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9386 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9387 // && mask == ~mask2 9388 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9389 // && ~mask == mask2 9390 // (i.e., copy a bitfield value into another bitfield of the same width) 9391 9392 if (VT != MVT::i32) 9393 return SDValue(); 9394 9395 SDValue N00 = N0.getOperand(0); 9396 9397 // The value and the mask need to be constants so we can verify this is 9398 // actually a bitfield set. If the mask is 0xffff, we can do better 9399 // via a movt instruction, so don't use BFI in that case. 9400 SDValue MaskOp = N0.getOperand(1); 9401 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9402 if (!MaskC) 9403 return SDValue(); 9404 unsigned Mask = MaskC->getZExtValue(); 9405 if (Mask == 0xffff) 9406 return SDValue(); 9407 SDValue Res; 9408 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9409 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9410 if (N1C) { 9411 unsigned Val = N1C->getZExtValue(); 9412 if ((Val & ~Mask) != Val) 9413 return SDValue(); 9414 9415 if (ARM::isBitFieldInvertedMask(Mask)) { 9416 Val >>= countTrailingZeros(~Mask); 9417 9418 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9419 DAG.getConstant(Val, DL, MVT::i32), 9420 DAG.getConstant(Mask, DL, MVT::i32)); 9421 9422 // Do not add new nodes to DAG combiner worklist. 9423 DCI.CombineTo(N, Res, false); 9424 return SDValue(); 9425 } 9426 } else if (N1.getOpcode() == ISD::AND) { 9427 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9428 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9429 if (!N11C) 9430 return SDValue(); 9431 unsigned Mask2 = N11C->getZExtValue(); 9432 9433 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9434 // as is to match. 9435 if (ARM::isBitFieldInvertedMask(Mask) && 9436 (Mask == ~Mask2)) { 9437 // The pack halfword instruction works better for masks that fit it, 9438 // so use that when it's available. 9439 if (Subtarget->hasT2ExtractPack() && 9440 (Mask == 0xffff || Mask == 0xffff0000)) 9441 return SDValue(); 9442 // 2a 9443 unsigned amt = countTrailingZeros(Mask2); 9444 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9445 DAG.getConstant(amt, DL, MVT::i32)); 9446 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9447 DAG.getConstant(Mask, DL, MVT::i32)); 9448 // Do not add new nodes to DAG combiner worklist. 9449 DCI.CombineTo(N, Res, false); 9450 return SDValue(); 9451 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9452 (~Mask == Mask2)) { 9453 // The pack halfword instruction works better for masks that fit it, 9454 // so use that when it's available. 9455 if (Subtarget->hasT2ExtractPack() && 9456 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9457 return SDValue(); 9458 // 2b 9459 unsigned lsb = countTrailingZeros(Mask); 9460 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9461 DAG.getConstant(lsb, DL, MVT::i32)); 9462 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9463 DAG.getConstant(Mask2, DL, MVT::i32)); 9464 // Do not add new nodes to DAG combiner worklist. 9465 DCI.CombineTo(N, Res, false); 9466 return SDValue(); 9467 } 9468 } 9469 9470 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9471 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9472 ARM::isBitFieldInvertedMask(~Mask)) { 9473 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9474 // where lsb(mask) == #shamt and masked bits of B are known zero. 9475 SDValue ShAmt = N00.getOperand(1); 9476 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9477 unsigned LSB = countTrailingZeros(Mask); 9478 if (ShAmtC != LSB) 9479 return SDValue(); 9480 9481 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9482 DAG.getConstant(~Mask, DL, MVT::i32)); 9483 9484 // Do not add new nodes to DAG combiner worklist. 9485 DCI.CombineTo(N, Res, false); 9486 } 9487 9488 return SDValue(); 9489 } 9490 9491 static SDValue PerformXORCombine(SDNode *N, 9492 TargetLowering::DAGCombinerInfo &DCI, 9493 const ARMSubtarget *Subtarget) { 9494 EVT VT = N->getValueType(0); 9495 SelectionDAG &DAG = DCI.DAG; 9496 9497 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9498 return SDValue(); 9499 9500 if (!Subtarget->isThumb1Only()) { 9501 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9502 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9503 return Result; 9504 } 9505 9506 return SDValue(); 9507 } 9508 9509 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9510 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9511 // their position in "to" (Rd). 9512 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9513 assert(N->getOpcode() == ARMISD::BFI); 9514 9515 SDValue From = N->getOperand(1); 9516 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9517 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9518 9519 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9520 // #C in the base of the SHR. 9521 if (From->getOpcode() == ISD::SRL && 9522 isa<ConstantSDNode>(From->getOperand(1))) { 9523 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9524 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9525 FromMask <<= Shift.getLimitedValue(31); 9526 From = From->getOperand(0); 9527 } 9528 9529 return From; 9530 } 9531 9532 // If A and B contain one contiguous set of bits, does A | B == A . B? 9533 // 9534 // Neither A nor B must be zero. 9535 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9536 unsigned LastActiveBitInA = A.countTrailingZeros(); 9537 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9538 return LastActiveBitInA - 1 == FirstActiveBitInB; 9539 } 9540 9541 static SDValue FindBFIToCombineWith(SDNode *N) { 9542 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9543 // if one exists. 9544 APInt ToMask, FromMask; 9545 SDValue From = ParseBFI(N, ToMask, FromMask); 9546 SDValue To = N->getOperand(0); 9547 9548 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9549 // aren't compatible, but not if they set the same bit in their destination as 9550 // we do (or that of any BFI we're going to combine with). 9551 SDValue V = To; 9552 APInt CombinedToMask = ToMask; 9553 while (V.getOpcode() == ARMISD::BFI) { 9554 APInt NewToMask, NewFromMask; 9555 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9556 if (NewFrom != From) { 9557 // This BFI has a different base. Keep going. 9558 CombinedToMask |= NewToMask; 9559 V = V.getOperand(0); 9560 continue; 9561 } 9562 9563 // Do the written bits conflict with any we've seen so far? 9564 if ((NewToMask & CombinedToMask).getBoolValue()) 9565 // Conflicting bits - bail out because going further is unsafe. 9566 return SDValue(); 9567 9568 // Are the new bits contiguous when combined with the old bits? 9569 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9570 BitsProperlyConcatenate(FromMask, NewFromMask)) 9571 return V; 9572 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9573 BitsProperlyConcatenate(NewFromMask, FromMask)) 9574 return V; 9575 9576 // We've seen a write to some bits, so track it. 9577 CombinedToMask |= NewToMask; 9578 // Keep going... 9579 V = V.getOperand(0); 9580 } 9581 9582 return SDValue(); 9583 } 9584 9585 static SDValue PerformBFICombine(SDNode *N, 9586 TargetLowering::DAGCombinerInfo &DCI) { 9587 SDValue N1 = N->getOperand(1); 9588 if (N1.getOpcode() == ISD::AND) { 9589 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9590 // the bits being cleared by the AND are not demanded by the BFI. 9591 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9592 if (!N11C) 9593 return SDValue(); 9594 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9595 unsigned LSB = countTrailingZeros(~InvMask); 9596 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9597 assert(Width < 9598 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9599 "undefined behavior"); 9600 unsigned Mask = (1u << Width) - 1; 9601 unsigned Mask2 = N11C->getZExtValue(); 9602 if ((Mask & (~Mask2)) == 0) 9603 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9604 N->getOperand(0), N1.getOperand(0), 9605 N->getOperand(2)); 9606 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9607 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9608 // Keep track of any consecutive bits set that all come from the same base 9609 // value. We can combine these together into a single BFI. 9610 SDValue CombineBFI = FindBFIToCombineWith(N); 9611 if (CombineBFI == SDValue()) 9612 return SDValue(); 9613 9614 // We've found a BFI. 9615 APInt ToMask1, FromMask1; 9616 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9617 9618 APInt ToMask2, FromMask2; 9619 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9620 assert(From1 == From2); 9621 (void)From2; 9622 9623 // First, unlink CombineBFI. 9624 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9625 // Then create a new BFI, combining the two together. 9626 APInt NewFromMask = FromMask1 | FromMask2; 9627 APInt NewToMask = ToMask1 | ToMask2; 9628 9629 EVT VT = N->getValueType(0); 9630 SDLoc dl(N); 9631 9632 if (NewFromMask[0] == 0) 9633 From1 = DCI.DAG.getNode( 9634 ISD::SRL, dl, VT, From1, 9635 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9636 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9637 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9638 } 9639 return SDValue(); 9640 } 9641 9642 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9643 /// ARMISD::VMOVRRD. 9644 static SDValue PerformVMOVRRDCombine(SDNode *N, 9645 TargetLowering::DAGCombinerInfo &DCI, 9646 const ARMSubtarget *Subtarget) { 9647 // vmovrrd(vmovdrr x, y) -> x,y 9648 SDValue InDouble = N->getOperand(0); 9649 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9650 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9651 9652 // vmovrrd(load f64) -> (load i32), (load i32) 9653 SDNode *InNode = InDouble.getNode(); 9654 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9655 InNode->getValueType(0) == MVT::f64 && 9656 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9657 !cast<LoadSDNode>(InNode)->isVolatile()) { 9658 // TODO: Should this be done for non-FrameIndex operands? 9659 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9660 9661 SelectionDAG &DAG = DCI.DAG; 9662 SDLoc DL(LD); 9663 SDValue BasePtr = LD->getBasePtr(); 9664 SDValue NewLD1 = 9665 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 9666 LD->getAlignment(), LD->getMemOperand()->getFlags()); 9667 9668 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9669 DAG.getConstant(4, DL, MVT::i32)); 9670 SDValue NewLD2 = DAG.getLoad( 9671 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 9672 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 9673 9674 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9675 if (DCI.DAG.getDataLayout().isBigEndian()) 9676 std::swap (NewLD1, NewLD2); 9677 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9678 return Result; 9679 } 9680 9681 return SDValue(); 9682 } 9683 9684 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9685 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9686 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9687 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9688 SDValue Op0 = N->getOperand(0); 9689 SDValue Op1 = N->getOperand(1); 9690 if (Op0.getOpcode() == ISD::BITCAST) 9691 Op0 = Op0.getOperand(0); 9692 if (Op1.getOpcode() == ISD::BITCAST) 9693 Op1 = Op1.getOperand(0); 9694 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9695 Op0.getNode() == Op1.getNode() && 9696 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9697 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9698 N->getValueType(0), Op0.getOperand(0)); 9699 return SDValue(); 9700 } 9701 9702 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9703 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9704 /// i64 vector to have f64 elements, since the value can then be loaded 9705 /// directly into a VFP register. 9706 static bool hasNormalLoadOperand(SDNode *N) { 9707 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9708 for (unsigned i = 0; i < NumElts; ++i) { 9709 SDNode *Elt = N->getOperand(i).getNode(); 9710 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9711 return true; 9712 } 9713 return false; 9714 } 9715 9716 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9717 /// ISD::BUILD_VECTOR. 9718 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9719 TargetLowering::DAGCombinerInfo &DCI, 9720 const ARMSubtarget *Subtarget) { 9721 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9722 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9723 // into a pair of GPRs, which is fine when the value is used as a scalar, 9724 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9725 SelectionDAG &DAG = DCI.DAG; 9726 if (N->getNumOperands() == 2) 9727 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 9728 return RV; 9729 9730 // Load i64 elements as f64 values so that type legalization does not split 9731 // them up into i32 values. 9732 EVT VT = N->getValueType(0); 9733 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9734 return SDValue(); 9735 SDLoc dl(N); 9736 SmallVector<SDValue, 8> Ops; 9737 unsigned NumElts = VT.getVectorNumElements(); 9738 for (unsigned i = 0; i < NumElts; ++i) { 9739 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9740 Ops.push_back(V); 9741 // Make the DAGCombiner fold the bitcast. 9742 DCI.AddToWorklist(V.getNode()); 9743 } 9744 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9745 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 9746 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9747 } 9748 9749 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9750 static SDValue 9751 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9752 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9753 // At that time, we may have inserted bitcasts from integer to float. 9754 // If these bitcasts have survived DAGCombine, change the lowering of this 9755 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9756 // force to use floating point types. 9757 9758 // Make sure we can change the type of the vector. 9759 // This is possible iff: 9760 // 1. The vector is only used in a bitcast to a integer type. I.e., 9761 // 1.1. Vector is used only once. 9762 // 1.2. Use is a bit convert to an integer type. 9763 // 2. The size of its operands are 32-bits (64-bits are not legal). 9764 EVT VT = N->getValueType(0); 9765 EVT EltVT = VT.getVectorElementType(); 9766 9767 // Check 1.1. and 2. 9768 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9769 return SDValue(); 9770 9771 // By construction, the input type must be float. 9772 assert(EltVT == MVT::f32 && "Unexpected type!"); 9773 9774 // Check 1.2. 9775 SDNode *Use = *N->use_begin(); 9776 if (Use->getOpcode() != ISD::BITCAST || 9777 Use->getValueType(0).isFloatingPoint()) 9778 return SDValue(); 9779 9780 // Check profitability. 9781 // Model is, if more than half of the relevant operands are bitcast from 9782 // i32, turn the build_vector into a sequence of insert_vector_elt. 9783 // Relevant operands are everything that is not statically 9784 // (i.e., at compile time) bitcasted. 9785 unsigned NumOfBitCastedElts = 0; 9786 unsigned NumElts = VT.getVectorNumElements(); 9787 unsigned NumOfRelevantElts = NumElts; 9788 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9789 SDValue Elt = N->getOperand(Idx); 9790 if (Elt->getOpcode() == ISD::BITCAST) { 9791 // Assume only bit cast to i32 will go away. 9792 if (Elt->getOperand(0).getValueType() == MVT::i32) 9793 ++NumOfBitCastedElts; 9794 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 9795 // Constants are statically casted, thus do not count them as 9796 // relevant operands. 9797 --NumOfRelevantElts; 9798 } 9799 9800 // Check if more than half of the elements require a non-free bitcast. 9801 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9802 return SDValue(); 9803 9804 SelectionDAG &DAG = DCI.DAG; 9805 // Create the new vector type. 9806 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9807 // Check if the type is legal. 9808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9809 if (!TLI.isTypeLegal(VecVT)) 9810 return SDValue(); 9811 9812 // Combine: 9813 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9814 // => BITCAST INSERT_VECTOR_ELT 9815 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9816 // (BITCAST EN), N. 9817 SDValue Vec = DAG.getUNDEF(VecVT); 9818 SDLoc dl(N); 9819 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9820 SDValue V = N->getOperand(Idx); 9821 if (V.isUndef()) 9822 continue; 9823 if (V.getOpcode() == ISD::BITCAST && 9824 V->getOperand(0).getValueType() == MVT::i32) 9825 // Fold obvious case. 9826 V = V.getOperand(0); 9827 else { 9828 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9829 // Make the DAGCombiner fold the bitcasts. 9830 DCI.AddToWorklist(V.getNode()); 9831 } 9832 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9833 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9834 } 9835 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9836 // Make the DAGCombiner fold the bitcasts. 9837 DCI.AddToWorklist(Vec.getNode()); 9838 return Vec; 9839 } 9840 9841 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9842 /// ISD::INSERT_VECTOR_ELT. 9843 static SDValue PerformInsertEltCombine(SDNode *N, 9844 TargetLowering::DAGCombinerInfo &DCI) { 9845 // Bitcast an i64 load inserted into a vector to f64. 9846 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9847 EVT VT = N->getValueType(0); 9848 SDNode *Elt = N->getOperand(1).getNode(); 9849 if (VT.getVectorElementType() != MVT::i64 || 9850 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9851 return SDValue(); 9852 9853 SelectionDAG &DAG = DCI.DAG; 9854 SDLoc dl(N); 9855 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9856 VT.getVectorNumElements()); 9857 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9858 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9859 // Make the DAGCombiner fold the bitcasts. 9860 DCI.AddToWorklist(Vec.getNode()); 9861 DCI.AddToWorklist(V.getNode()); 9862 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9863 Vec, V, N->getOperand(2)); 9864 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9865 } 9866 9867 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9868 /// ISD::VECTOR_SHUFFLE. 9869 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9870 // The LLVM shufflevector instruction does not require the shuffle mask 9871 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9872 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9873 // operands do not match the mask length, they are extended by concatenating 9874 // them with undef vectors. That is probably the right thing for other 9875 // targets, but for NEON it is better to concatenate two double-register 9876 // size vector operands into a single quad-register size vector. Do that 9877 // transformation here: 9878 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9879 // shuffle(concat(v1, v2), undef) 9880 SDValue Op0 = N->getOperand(0); 9881 SDValue Op1 = N->getOperand(1); 9882 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9883 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9884 Op0.getNumOperands() != 2 || 9885 Op1.getNumOperands() != 2) 9886 return SDValue(); 9887 SDValue Concat0Op1 = Op0.getOperand(1); 9888 SDValue Concat1Op1 = Op1.getOperand(1); 9889 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 9890 return SDValue(); 9891 // Skip the transformation if any of the types are illegal. 9892 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9893 EVT VT = N->getValueType(0); 9894 if (!TLI.isTypeLegal(VT) || 9895 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9896 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9897 return SDValue(); 9898 9899 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9900 Op0.getOperand(0), Op1.getOperand(0)); 9901 // Translate the shuffle mask. 9902 SmallVector<int, 16> NewMask; 9903 unsigned NumElts = VT.getVectorNumElements(); 9904 unsigned HalfElts = NumElts/2; 9905 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9906 for (unsigned n = 0; n < NumElts; ++n) { 9907 int MaskElt = SVN->getMaskElt(n); 9908 int NewElt = -1; 9909 if (MaskElt < (int)HalfElts) 9910 NewElt = MaskElt; 9911 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9912 NewElt = HalfElts + MaskElt - NumElts; 9913 NewMask.push_back(NewElt); 9914 } 9915 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9916 DAG.getUNDEF(VT), NewMask); 9917 } 9918 9919 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9920 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9921 /// base address updates. 9922 /// For generic load/stores, the memory type is assumed to be a vector. 9923 /// The caller is assumed to have checked legality. 9924 static SDValue CombineBaseUpdate(SDNode *N, 9925 TargetLowering::DAGCombinerInfo &DCI) { 9926 SelectionDAG &DAG = DCI.DAG; 9927 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9928 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9929 const bool isStore = N->getOpcode() == ISD::STORE; 9930 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9931 SDValue Addr = N->getOperand(AddrOpIdx); 9932 MemSDNode *MemN = cast<MemSDNode>(N); 9933 SDLoc dl(N); 9934 9935 // Search for a use of the address operand that is an increment. 9936 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9937 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9938 SDNode *User = *UI; 9939 if (User->getOpcode() != ISD::ADD || 9940 UI.getUse().getResNo() != Addr.getResNo()) 9941 continue; 9942 9943 // Check that the add is independent of the load/store. Otherwise, folding 9944 // it would create a cycle. 9945 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9946 continue; 9947 9948 // Find the new opcode for the updating load/store. 9949 bool isLoadOp = true; 9950 bool isLaneOp = false; 9951 unsigned NewOpc = 0; 9952 unsigned NumVecs = 0; 9953 if (isIntrinsic) { 9954 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9955 switch (IntNo) { 9956 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9957 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9958 NumVecs = 1; break; 9959 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9960 NumVecs = 2; break; 9961 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9962 NumVecs = 3; break; 9963 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9964 NumVecs = 4; break; 9965 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9966 NumVecs = 2; isLaneOp = true; break; 9967 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9968 NumVecs = 3; isLaneOp = true; break; 9969 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9970 NumVecs = 4; isLaneOp = true; break; 9971 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9972 NumVecs = 1; isLoadOp = false; break; 9973 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9974 NumVecs = 2; isLoadOp = false; break; 9975 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9976 NumVecs = 3; isLoadOp = false; break; 9977 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9978 NumVecs = 4; isLoadOp = false; break; 9979 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9980 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9981 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9982 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9983 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9984 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9985 } 9986 } else { 9987 isLaneOp = true; 9988 switch (N->getOpcode()) { 9989 default: llvm_unreachable("unexpected opcode for Neon base update"); 9990 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9991 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9992 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9993 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9994 NumVecs = 1; isLaneOp = false; break; 9995 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9996 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9997 } 9998 } 9999 10000 // Find the size of memory referenced by the load/store. 10001 EVT VecTy; 10002 if (isLoadOp) { 10003 VecTy = N->getValueType(0); 10004 } else if (isIntrinsic) { 10005 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 10006 } else { 10007 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 10008 VecTy = N->getOperand(1).getValueType(); 10009 } 10010 10011 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 10012 if (isLaneOp) 10013 NumBytes /= VecTy.getVectorNumElements(); 10014 10015 // If the increment is a constant, it must match the memory ref size. 10016 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10017 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 10018 uint64_t IncVal = CInc->getZExtValue(); 10019 if (IncVal != NumBytes) 10020 continue; 10021 } else if (NumBytes >= 3 * 16) { 10022 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 10023 // separate instructions that make it harder to use a non-constant update. 10024 continue; 10025 } 10026 10027 // OK, we found an ADD we can fold into the base update. 10028 // Now, create a _UPD node, taking care of not breaking alignment. 10029 10030 EVT AlignedVecTy = VecTy; 10031 unsigned Alignment = MemN->getAlignment(); 10032 10033 // If this is a less-than-standard-aligned load/store, change the type to 10034 // match the standard alignment. 10035 // The alignment is overlooked when selecting _UPD variants; and it's 10036 // easier to introduce bitcasts here than fix that. 10037 // There are 3 ways to get to this base-update combine: 10038 // - intrinsics: they are assumed to be properly aligned (to the standard 10039 // alignment of the memory type), so we don't need to do anything. 10040 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 10041 // intrinsics, so, likewise, there's nothing to do. 10042 // - generic load/store instructions: the alignment is specified as an 10043 // explicit operand, rather than implicitly as the standard alignment 10044 // of the memory type (like the intrisics). We need to change the 10045 // memory type to match the explicit alignment. That way, we don't 10046 // generate non-standard-aligned ARMISD::VLDx nodes. 10047 if (isa<LSBaseSDNode>(N)) { 10048 if (Alignment == 0) 10049 Alignment = 1; 10050 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 10051 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 10052 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 10053 assert(!isLaneOp && "Unexpected generic load/store lane."); 10054 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 10055 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 10056 } 10057 // Don't set an explicit alignment on regular load/stores that we want 10058 // to transform to VLD/VST 1_UPD nodes. 10059 // This matches the behavior of regular load/stores, which only get an 10060 // explicit alignment if the MMO alignment is larger than the standard 10061 // alignment of the memory type. 10062 // Intrinsics, however, always get an explicit alignment, set to the 10063 // alignment of the MMO. 10064 Alignment = 1; 10065 } 10066 10067 // Create the new updating load/store node. 10068 // First, create an SDVTList for the new updating node's results. 10069 EVT Tys[6]; 10070 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 10071 unsigned n; 10072 for (n = 0; n < NumResultVecs; ++n) 10073 Tys[n] = AlignedVecTy; 10074 Tys[n++] = MVT::i32; 10075 Tys[n] = MVT::Other; 10076 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 10077 10078 // Then, gather the new node's operands. 10079 SmallVector<SDValue, 8> Ops; 10080 Ops.push_back(N->getOperand(0)); // incoming chain 10081 Ops.push_back(N->getOperand(AddrOpIdx)); 10082 Ops.push_back(Inc); 10083 10084 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 10085 // Try to match the intrinsic's signature 10086 Ops.push_back(StN->getValue()); 10087 } else { 10088 // Loads (and of course intrinsics) match the intrinsics' signature, 10089 // so just add all but the alignment operand. 10090 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 10091 Ops.push_back(N->getOperand(i)); 10092 } 10093 10094 // For all node types, the alignment operand is always the last one. 10095 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 10096 10097 // If this is a non-standard-aligned STORE, the penultimate operand is the 10098 // stored value. Bitcast it to the aligned type. 10099 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 10100 SDValue &StVal = Ops[Ops.size()-2]; 10101 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 10102 } 10103 10104 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 10105 Ops, AlignedVecTy, 10106 MemN->getMemOperand()); 10107 10108 // Update the uses. 10109 SmallVector<SDValue, 5> NewResults; 10110 for (unsigned i = 0; i < NumResultVecs; ++i) 10111 NewResults.push_back(SDValue(UpdN.getNode(), i)); 10112 10113 // If this is an non-standard-aligned LOAD, the first result is the loaded 10114 // value. Bitcast it to the expected result type. 10115 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 10116 SDValue &LdVal = NewResults[0]; 10117 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 10118 } 10119 10120 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 10121 DCI.CombineTo(N, NewResults); 10122 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 10123 10124 break; 10125 } 10126 return SDValue(); 10127 } 10128 10129 static SDValue PerformVLDCombine(SDNode *N, 10130 TargetLowering::DAGCombinerInfo &DCI) { 10131 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10132 return SDValue(); 10133 10134 return CombineBaseUpdate(N, DCI); 10135 } 10136 10137 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 10138 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 10139 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 10140 /// return true. 10141 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10142 SelectionDAG &DAG = DCI.DAG; 10143 EVT VT = N->getValueType(0); 10144 // vldN-dup instructions only support 64-bit vectors for N > 1. 10145 if (!VT.is64BitVector()) 10146 return false; 10147 10148 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 10149 SDNode *VLD = N->getOperand(0).getNode(); 10150 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 10151 return false; 10152 unsigned NumVecs = 0; 10153 unsigned NewOpc = 0; 10154 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 10155 if (IntNo == Intrinsic::arm_neon_vld2lane) { 10156 NumVecs = 2; 10157 NewOpc = ARMISD::VLD2DUP; 10158 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 10159 NumVecs = 3; 10160 NewOpc = ARMISD::VLD3DUP; 10161 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 10162 NumVecs = 4; 10163 NewOpc = ARMISD::VLD4DUP; 10164 } else { 10165 return false; 10166 } 10167 10168 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 10169 // numbers match the load. 10170 unsigned VLDLaneNo = 10171 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 10172 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10173 UI != UE; ++UI) { 10174 // Ignore uses of the chain result. 10175 if (UI.getUse().getResNo() == NumVecs) 10176 continue; 10177 SDNode *User = *UI; 10178 if (User->getOpcode() != ARMISD::VDUPLANE || 10179 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 10180 return false; 10181 } 10182 10183 // Create the vldN-dup node. 10184 EVT Tys[5]; 10185 unsigned n; 10186 for (n = 0; n < NumVecs; ++n) 10187 Tys[n] = VT; 10188 Tys[n] = MVT::Other; 10189 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 10190 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 10191 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 10192 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 10193 Ops, VLDMemInt->getMemoryVT(), 10194 VLDMemInt->getMemOperand()); 10195 10196 // Update the uses. 10197 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10198 UI != UE; ++UI) { 10199 unsigned ResNo = UI.getUse().getResNo(); 10200 // Ignore uses of the chain result. 10201 if (ResNo == NumVecs) 10202 continue; 10203 SDNode *User = *UI; 10204 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 10205 } 10206 10207 // Now the vldN-lane intrinsic is dead except for its chain result. 10208 // Update uses of the chain. 10209 std::vector<SDValue> VLDDupResults; 10210 for (unsigned n = 0; n < NumVecs; ++n) 10211 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 10212 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 10213 DCI.CombineTo(VLD, VLDDupResults); 10214 10215 return true; 10216 } 10217 10218 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 10219 /// ARMISD::VDUPLANE. 10220 static SDValue PerformVDUPLANECombine(SDNode *N, 10221 TargetLowering::DAGCombinerInfo &DCI) { 10222 SDValue Op = N->getOperand(0); 10223 10224 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 10225 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 10226 if (CombineVLDDUP(N, DCI)) 10227 return SDValue(N, 0); 10228 10229 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 10230 // redundant. Ignore bit_converts for now; element sizes are checked below. 10231 while (Op.getOpcode() == ISD::BITCAST) 10232 Op = Op.getOperand(0); 10233 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 10234 return SDValue(); 10235 10236 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 10237 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 10238 // The canonical VMOV for a zero vector uses a 32-bit element size. 10239 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10240 unsigned EltBits; 10241 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 10242 EltSize = 8; 10243 EVT VT = N->getValueType(0); 10244 if (EltSize > VT.getVectorElementType().getSizeInBits()) 10245 return SDValue(); 10246 10247 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 10248 } 10249 10250 static SDValue PerformLOADCombine(SDNode *N, 10251 TargetLowering::DAGCombinerInfo &DCI) { 10252 EVT VT = N->getValueType(0); 10253 10254 // If this is a legal vector load, try to combine it into a VLD1_UPD. 10255 if (ISD::isNormalLoad(N) && VT.isVector() && 10256 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10257 return CombineBaseUpdate(N, DCI); 10258 10259 return SDValue(); 10260 } 10261 10262 /// PerformSTORECombine - Target-specific dag combine xforms for 10263 /// ISD::STORE. 10264 static SDValue PerformSTORECombine(SDNode *N, 10265 TargetLowering::DAGCombinerInfo &DCI) { 10266 StoreSDNode *St = cast<StoreSDNode>(N); 10267 if (St->isVolatile()) 10268 return SDValue(); 10269 10270 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10271 // pack all of the elements in one place. Next, store to memory in fewer 10272 // chunks. 10273 SDValue StVal = St->getValue(); 10274 EVT VT = StVal.getValueType(); 10275 if (St->isTruncatingStore() && VT.isVector()) { 10276 SelectionDAG &DAG = DCI.DAG; 10277 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10278 EVT StVT = St->getMemoryVT(); 10279 unsigned NumElems = VT.getVectorNumElements(); 10280 assert(StVT != VT && "Cannot truncate to the same type"); 10281 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 10282 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 10283 10284 // From, To sizes and ElemCount must be pow of two 10285 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10286 10287 // We are going to use the original vector elt for storing. 10288 // Accumulated smaller vector elements must be a multiple of the store size. 10289 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10290 10291 unsigned SizeRatio = FromEltSz / ToEltSz; 10292 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10293 10294 // Create a type on which we perform the shuffle. 10295 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10296 NumElems*SizeRatio); 10297 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10298 10299 SDLoc DL(St); 10300 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10301 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10302 for (unsigned i = 0; i < NumElems; ++i) 10303 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10304 ? (i + 1) * SizeRatio - 1 10305 : i * SizeRatio; 10306 10307 // Can't shuffle using an illegal type. 10308 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10309 10310 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10311 DAG.getUNDEF(WideVec.getValueType()), 10312 ShuffleVec); 10313 // At this point all of the data is stored at the bottom of the 10314 // register. We now need to save it to mem. 10315 10316 // Find the largest store unit 10317 MVT StoreType = MVT::i8; 10318 for (MVT Tp : MVT::integer_valuetypes()) { 10319 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10320 StoreType = Tp; 10321 } 10322 // Didn't find a legal store type. 10323 if (!TLI.isTypeLegal(StoreType)) 10324 return SDValue(); 10325 10326 // Bitcast the original vector into a vector of store-size units 10327 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10328 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10329 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10330 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10331 SmallVector<SDValue, 8> Chains; 10332 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10333 TLI.getPointerTy(DAG.getDataLayout())); 10334 SDValue BasePtr = St->getBasePtr(); 10335 10336 // Perform one or more big stores into memory. 10337 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10338 for (unsigned I = 0; I < E; I++) { 10339 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10340 StoreType, ShuffWide, 10341 DAG.getIntPtrConstant(I, DL)); 10342 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10343 St->getPointerInfo(), St->getAlignment(), 10344 St->getMemOperand()->getFlags()); 10345 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10346 Increment); 10347 Chains.push_back(Ch); 10348 } 10349 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10350 } 10351 10352 if (!ISD::isNormalStore(St)) 10353 return SDValue(); 10354 10355 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10356 // ARM stores of arguments in the same cache line. 10357 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10358 StVal.getNode()->hasOneUse()) { 10359 SelectionDAG &DAG = DCI.DAG; 10360 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10361 SDLoc DL(St); 10362 SDValue BasePtr = St->getBasePtr(); 10363 SDValue NewST1 = DAG.getStore( 10364 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 10365 BasePtr, St->getPointerInfo(), St->getAlignment(), 10366 St->getMemOperand()->getFlags()); 10367 10368 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10369 DAG.getConstant(4, DL, MVT::i32)); 10370 return DAG.getStore(NewST1.getValue(0), DL, 10371 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10372 OffsetPtr, St->getPointerInfo(), 10373 std::min(4U, St->getAlignment() / 2), 10374 St->getMemOperand()->getFlags()); 10375 } 10376 10377 if (StVal.getValueType() == MVT::i64 && 10378 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10379 10380 // Bitcast an i64 store extracted from a vector to f64. 10381 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10382 SelectionDAG &DAG = DCI.DAG; 10383 SDLoc dl(StVal); 10384 SDValue IntVec = StVal.getOperand(0); 10385 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10386 IntVec.getValueType().getVectorNumElements()); 10387 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10388 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10389 Vec, StVal.getOperand(1)); 10390 dl = SDLoc(N); 10391 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10392 // Make the DAGCombiner fold the bitcasts. 10393 DCI.AddToWorklist(Vec.getNode()); 10394 DCI.AddToWorklist(ExtElt.getNode()); 10395 DCI.AddToWorklist(V.getNode()); 10396 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10397 St->getPointerInfo(), St->getAlignment(), 10398 St->getMemOperand()->getFlags(), St->getAAInfo()); 10399 } 10400 10401 // If this is a legal vector store, try to combine it into a VST1_UPD. 10402 if (ISD::isNormalStore(N) && VT.isVector() && 10403 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10404 return CombineBaseUpdate(N, DCI); 10405 10406 return SDValue(); 10407 } 10408 10409 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10410 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10411 /// when the VMUL has a constant operand that is a power of 2. 10412 /// 10413 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10414 /// vmul.f32 d16, d17, d16 10415 /// vcvt.s32.f32 d16, d16 10416 /// becomes: 10417 /// vcvt.s32.f32 d16, d16, #3 10418 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10419 const ARMSubtarget *Subtarget) { 10420 if (!Subtarget->hasNEON()) 10421 return SDValue(); 10422 10423 SDValue Op = N->getOperand(0); 10424 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10425 Op.getOpcode() != ISD::FMUL) 10426 return SDValue(); 10427 10428 SDValue ConstVec = Op->getOperand(1); 10429 if (!isa<BuildVectorSDNode>(ConstVec)) 10430 return SDValue(); 10431 10432 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10433 uint32_t FloatBits = FloatTy.getSizeInBits(); 10434 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10435 uint32_t IntBits = IntTy.getSizeInBits(); 10436 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10437 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10438 // These instructions only exist converting from f32 to i32. We can handle 10439 // smaller integers by generating an extra truncate, but larger ones would 10440 // be lossy. We also can't handle more then 4 lanes, since these intructions 10441 // only support v2i32/v4i32 types. 10442 return SDValue(); 10443 } 10444 10445 BitVector UndefElements; 10446 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10447 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10448 if (C == -1 || C == 0 || C > 32) 10449 return SDValue(); 10450 10451 SDLoc dl(N); 10452 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10453 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10454 Intrinsic::arm_neon_vcvtfp2fxu; 10455 SDValue FixConv = DAG.getNode( 10456 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10457 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10458 DAG.getConstant(C, dl, MVT::i32)); 10459 10460 if (IntBits < FloatBits) 10461 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10462 10463 return FixConv; 10464 } 10465 10466 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10467 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10468 /// when the VDIV has a constant operand that is a power of 2. 10469 /// 10470 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10471 /// vcvt.f32.s32 d16, d16 10472 /// vdiv.f32 d16, d17, d16 10473 /// becomes: 10474 /// vcvt.f32.s32 d16, d16, #3 10475 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10476 const ARMSubtarget *Subtarget) { 10477 if (!Subtarget->hasNEON()) 10478 return SDValue(); 10479 10480 SDValue Op = N->getOperand(0); 10481 unsigned OpOpcode = Op.getNode()->getOpcode(); 10482 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 10483 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10484 return SDValue(); 10485 10486 SDValue ConstVec = N->getOperand(1); 10487 if (!isa<BuildVectorSDNode>(ConstVec)) 10488 return SDValue(); 10489 10490 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10491 uint32_t FloatBits = FloatTy.getSizeInBits(); 10492 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10493 uint32_t IntBits = IntTy.getSizeInBits(); 10494 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10495 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10496 // These instructions only exist converting from i32 to f32. We can handle 10497 // smaller integers by generating an extra extend, but larger ones would 10498 // be lossy. We also can't handle more then 4 lanes, since these intructions 10499 // only support v2i32/v4i32 types. 10500 return SDValue(); 10501 } 10502 10503 BitVector UndefElements; 10504 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10505 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10506 if (C == -1 || C == 0 || C > 32) 10507 return SDValue(); 10508 10509 SDLoc dl(N); 10510 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10511 SDValue ConvInput = Op.getOperand(0); 10512 if (IntBits < FloatBits) 10513 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10514 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10515 ConvInput); 10516 10517 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10518 Intrinsic::arm_neon_vcvtfxu2fp; 10519 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10520 Op.getValueType(), 10521 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10522 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10523 } 10524 10525 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10526 /// operand of a vector shift operation, where all the elements of the 10527 /// build_vector must have the same constant integer value. 10528 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10529 // Ignore bit_converts. 10530 while (Op.getOpcode() == ISD::BITCAST) 10531 Op = Op.getOperand(0); 10532 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10533 APInt SplatBits, SplatUndef; 10534 unsigned SplatBitSize; 10535 bool HasAnyUndefs; 10536 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10537 HasAnyUndefs, ElementBits) || 10538 SplatBitSize > ElementBits) 10539 return false; 10540 Cnt = SplatBits.getSExtValue(); 10541 return true; 10542 } 10543 10544 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10545 /// operand of a vector shift left operation. That value must be in the range: 10546 /// 0 <= Value < ElementBits for a left shift; or 10547 /// 0 <= Value <= ElementBits for a long left shift. 10548 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10549 assert(VT.isVector() && "vector shift count is not a vector type"); 10550 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10551 if (! getVShiftImm(Op, ElementBits, Cnt)) 10552 return false; 10553 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10554 } 10555 10556 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10557 /// operand of a vector shift right operation. For a shift opcode, the value 10558 /// is positive, but for an intrinsic the value count must be negative. The 10559 /// absolute value must be in the range: 10560 /// 1 <= |Value| <= ElementBits for a right shift; or 10561 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10562 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10563 int64_t &Cnt) { 10564 assert(VT.isVector() && "vector shift count is not a vector type"); 10565 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10566 if (! getVShiftImm(Op, ElementBits, Cnt)) 10567 return false; 10568 if (!isIntrinsic) 10569 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10570 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10571 Cnt = -Cnt; 10572 return true; 10573 } 10574 return false; 10575 } 10576 10577 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10578 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10579 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10580 switch (IntNo) { 10581 default: 10582 // Don't do anything for most intrinsics. 10583 break; 10584 10585 // Vector shifts: check for immediate versions and lower them. 10586 // Note: This is done during DAG combining instead of DAG legalizing because 10587 // the build_vectors for 64-bit vector element shift counts are generally 10588 // not legal, and it is hard to see their values after they get legalized to 10589 // loads from a constant pool. 10590 case Intrinsic::arm_neon_vshifts: 10591 case Intrinsic::arm_neon_vshiftu: 10592 case Intrinsic::arm_neon_vrshifts: 10593 case Intrinsic::arm_neon_vrshiftu: 10594 case Intrinsic::arm_neon_vrshiftn: 10595 case Intrinsic::arm_neon_vqshifts: 10596 case Intrinsic::arm_neon_vqshiftu: 10597 case Intrinsic::arm_neon_vqshiftsu: 10598 case Intrinsic::arm_neon_vqshiftns: 10599 case Intrinsic::arm_neon_vqshiftnu: 10600 case Intrinsic::arm_neon_vqshiftnsu: 10601 case Intrinsic::arm_neon_vqrshiftns: 10602 case Intrinsic::arm_neon_vqrshiftnu: 10603 case Intrinsic::arm_neon_vqrshiftnsu: { 10604 EVT VT = N->getOperand(1).getValueType(); 10605 int64_t Cnt; 10606 unsigned VShiftOpc = 0; 10607 10608 switch (IntNo) { 10609 case Intrinsic::arm_neon_vshifts: 10610 case Intrinsic::arm_neon_vshiftu: 10611 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10612 VShiftOpc = ARMISD::VSHL; 10613 break; 10614 } 10615 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10616 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10617 ARMISD::VSHRs : ARMISD::VSHRu); 10618 break; 10619 } 10620 return SDValue(); 10621 10622 case Intrinsic::arm_neon_vrshifts: 10623 case Intrinsic::arm_neon_vrshiftu: 10624 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10625 break; 10626 return SDValue(); 10627 10628 case Intrinsic::arm_neon_vqshifts: 10629 case Intrinsic::arm_neon_vqshiftu: 10630 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10631 break; 10632 return SDValue(); 10633 10634 case Intrinsic::arm_neon_vqshiftsu: 10635 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10636 break; 10637 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10638 10639 case Intrinsic::arm_neon_vrshiftn: 10640 case Intrinsic::arm_neon_vqshiftns: 10641 case Intrinsic::arm_neon_vqshiftnu: 10642 case Intrinsic::arm_neon_vqshiftnsu: 10643 case Intrinsic::arm_neon_vqrshiftns: 10644 case Intrinsic::arm_neon_vqrshiftnu: 10645 case Intrinsic::arm_neon_vqrshiftnsu: 10646 // Narrowing shifts require an immediate right shift. 10647 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10648 break; 10649 llvm_unreachable("invalid shift count for narrowing vector shift " 10650 "intrinsic"); 10651 10652 default: 10653 llvm_unreachable("unhandled vector shift"); 10654 } 10655 10656 switch (IntNo) { 10657 case Intrinsic::arm_neon_vshifts: 10658 case Intrinsic::arm_neon_vshiftu: 10659 // Opcode already set above. 10660 break; 10661 case Intrinsic::arm_neon_vrshifts: 10662 VShiftOpc = ARMISD::VRSHRs; break; 10663 case Intrinsic::arm_neon_vrshiftu: 10664 VShiftOpc = ARMISD::VRSHRu; break; 10665 case Intrinsic::arm_neon_vrshiftn: 10666 VShiftOpc = ARMISD::VRSHRN; break; 10667 case Intrinsic::arm_neon_vqshifts: 10668 VShiftOpc = ARMISD::VQSHLs; break; 10669 case Intrinsic::arm_neon_vqshiftu: 10670 VShiftOpc = ARMISD::VQSHLu; break; 10671 case Intrinsic::arm_neon_vqshiftsu: 10672 VShiftOpc = ARMISD::VQSHLsu; break; 10673 case Intrinsic::arm_neon_vqshiftns: 10674 VShiftOpc = ARMISD::VQSHRNs; break; 10675 case Intrinsic::arm_neon_vqshiftnu: 10676 VShiftOpc = ARMISD::VQSHRNu; break; 10677 case Intrinsic::arm_neon_vqshiftnsu: 10678 VShiftOpc = ARMISD::VQSHRNsu; break; 10679 case Intrinsic::arm_neon_vqrshiftns: 10680 VShiftOpc = ARMISD::VQRSHRNs; break; 10681 case Intrinsic::arm_neon_vqrshiftnu: 10682 VShiftOpc = ARMISD::VQRSHRNu; break; 10683 case Intrinsic::arm_neon_vqrshiftnsu: 10684 VShiftOpc = ARMISD::VQRSHRNsu; break; 10685 } 10686 10687 SDLoc dl(N); 10688 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10689 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10690 } 10691 10692 case Intrinsic::arm_neon_vshiftins: { 10693 EVT VT = N->getOperand(1).getValueType(); 10694 int64_t Cnt; 10695 unsigned VShiftOpc = 0; 10696 10697 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10698 VShiftOpc = ARMISD::VSLI; 10699 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10700 VShiftOpc = ARMISD::VSRI; 10701 else { 10702 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10703 } 10704 10705 SDLoc dl(N); 10706 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10707 N->getOperand(1), N->getOperand(2), 10708 DAG.getConstant(Cnt, dl, MVT::i32)); 10709 } 10710 10711 case Intrinsic::arm_neon_vqrshifts: 10712 case Intrinsic::arm_neon_vqrshiftu: 10713 // No immediate versions of these to check for. 10714 break; 10715 } 10716 10717 return SDValue(); 10718 } 10719 10720 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10721 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10722 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10723 /// vector element shift counts are generally not legal, and it is hard to see 10724 /// their values after they get legalized to loads from a constant pool. 10725 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10726 const ARMSubtarget *ST) { 10727 EVT VT = N->getValueType(0); 10728 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10729 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10730 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10731 SDValue N1 = N->getOperand(1); 10732 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10733 SDValue N0 = N->getOperand(0); 10734 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10735 DAG.MaskedValueIsZero(N0.getOperand(0), 10736 APInt::getHighBitsSet(32, 16))) 10737 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10738 } 10739 } 10740 10741 // Nothing to be done for scalar shifts. 10742 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10743 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10744 return SDValue(); 10745 10746 assert(ST->hasNEON() && "unexpected vector shift"); 10747 int64_t Cnt; 10748 10749 switch (N->getOpcode()) { 10750 default: llvm_unreachable("unexpected shift opcode"); 10751 10752 case ISD::SHL: 10753 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10754 SDLoc dl(N); 10755 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10756 DAG.getConstant(Cnt, dl, MVT::i32)); 10757 } 10758 break; 10759 10760 case ISD::SRA: 10761 case ISD::SRL: 10762 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10763 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10764 ARMISD::VSHRs : ARMISD::VSHRu); 10765 SDLoc dl(N); 10766 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10767 DAG.getConstant(Cnt, dl, MVT::i32)); 10768 } 10769 } 10770 return SDValue(); 10771 } 10772 10773 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10774 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10775 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10776 const ARMSubtarget *ST) { 10777 SDValue N0 = N->getOperand(0); 10778 10779 // Check for sign- and zero-extensions of vector extract operations of 8- 10780 // and 16-bit vector elements. NEON supports these directly. They are 10781 // handled during DAG combining because type legalization will promote them 10782 // to 32-bit types and it is messy to recognize the operations after that. 10783 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10784 SDValue Vec = N0.getOperand(0); 10785 SDValue Lane = N0.getOperand(1); 10786 EVT VT = N->getValueType(0); 10787 EVT EltVT = N0.getValueType(); 10788 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10789 10790 if (VT == MVT::i32 && 10791 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10792 TLI.isTypeLegal(Vec.getValueType()) && 10793 isa<ConstantSDNode>(Lane)) { 10794 10795 unsigned Opc = 0; 10796 switch (N->getOpcode()) { 10797 default: llvm_unreachable("unexpected opcode"); 10798 case ISD::SIGN_EXTEND: 10799 Opc = ARMISD::VGETLANEs; 10800 break; 10801 case ISD::ZERO_EXTEND: 10802 case ISD::ANY_EXTEND: 10803 Opc = ARMISD::VGETLANEu; 10804 break; 10805 } 10806 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10807 } 10808 } 10809 10810 return SDValue(); 10811 } 10812 10813 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10814 APInt &KnownOne) { 10815 if (Op.getOpcode() == ARMISD::BFI) { 10816 // Conservatively, we can recurse down the first operand 10817 // and just mask out all affected bits. 10818 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10819 10820 // The operand to BFI is already a mask suitable for removing the bits it 10821 // sets. 10822 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10823 const APInt &Mask = CI->getAPIntValue(); 10824 KnownZero &= Mask; 10825 KnownOne &= Mask; 10826 return; 10827 } 10828 if (Op.getOpcode() == ARMISD::CMOV) { 10829 APInt KZ2(KnownZero.getBitWidth(), 0); 10830 APInt KO2(KnownOne.getBitWidth(), 0); 10831 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 10832 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 10833 10834 KnownZero &= KZ2; 10835 KnownOne &= KO2; 10836 return; 10837 } 10838 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 10839 } 10840 10841 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 10842 // If we have a CMOV, OR and AND combination such as: 10843 // if (x & CN) 10844 // y |= CM; 10845 // 10846 // And: 10847 // * CN is a single bit; 10848 // * All bits covered by CM are known zero in y 10849 // 10850 // Then we can convert this into a sequence of BFI instructions. This will 10851 // always be a win if CM is a single bit, will always be no worse than the 10852 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 10853 // three bits (due to the extra IT instruction). 10854 10855 SDValue Op0 = CMOV->getOperand(0); 10856 SDValue Op1 = CMOV->getOperand(1); 10857 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 10858 auto CC = CCNode->getAPIntValue().getLimitedValue(); 10859 SDValue CmpZ = CMOV->getOperand(4); 10860 10861 // The compare must be against zero. 10862 if (!isNullConstant(CmpZ->getOperand(1))) 10863 return SDValue(); 10864 10865 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 10866 SDValue And = CmpZ->getOperand(0); 10867 if (And->getOpcode() != ISD::AND) 10868 return SDValue(); 10869 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 10870 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 10871 return SDValue(); 10872 SDValue X = And->getOperand(0); 10873 10874 if (CC == ARMCC::EQ) { 10875 // We're performing an "equal to zero" compare. Swap the operands so we 10876 // canonicalize on a "not equal to zero" compare. 10877 std::swap(Op0, Op1); 10878 } else { 10879 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 10880 } 10881 10882 if (Op1->getOpcode() != ISD::OR) 10883 return SDValue(); 10884 10885 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 10886 if (!OrC) 10887 return SDValue(); 10888 SDValue Y = Op1->getOperand(0); 10889 10890 if (Op0 != Y) 10891 return SDValue(); 10892 10893 // Now, is it profitable to continue? 10894 APInt OrCI = OrC->getAPIntValue(); 10895 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 10896 if (OrCI.countPopulation() > Heuristic) 10897 return SDValue(); 10898 10899 // Lastly, can we determine that the bits defined by OrCI 10900 // are zero in Y? 10901 APInt KnownZero, KnownOne; 10902 computeKnownBits(DAG, Y, KnownZero, KnownOne); 10903 if ((OrCI & KnownZero) != OrCI) 10904 return SDValue(); 10905 10906 // OK, we can do the combine. 10907 SDValue V = Y; 10908 SDLoc dl(X); 10909 EVT VT = X.getValueType(); 10910 unsigned BitInX = AndC->getAPIntValue().logBase2(); 10911 10912 if (BitInX != 0) { 10913 // We must shift X first. 10914 X = DAG.getNode(ISD::SRL, dl, VT, X, 10915 DAG.getConstant(BitInX, dl, VT)); 10916 } 10917 10918 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 10919 BitInY < NumActiveBits; ++BitInY) { 10920 if (OrCI[BitInY] == 0) 10921 continue; 10922 APInt Mask(VT.getSizeInBits(), 0); 10923 Mask.setBit(BitInY); 10924 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 10925 // Confusingly, the operand is an *inverted* mask. 10926 DAG.getConstant(~Mask, dl, VT)); 10927 } 10928 10929 return V; 10930 } 10931 10932 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 10933 SDValue 10934 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 10935 SDValue Cmp = N->getOperand(4); 10936 if (Cmp.getOpcode() != ARMISD::CMPZ) 10937 // Only looking at NE cases. 10938 return SDValue(); 10939 10940 EVT VT = N->getValueType(0); 10941 SDLoc dl(N); 10942 SDValue LHS = Cmp.getOperand(0); 10943 SDValue RHS = Cmp.getOperand(1); 10944 SDValue Chain = N->getOperand(0); 10945 SDValue BB = N->getOperand(1); 10946 SDValue ARMcc = N->getOperand(2); 10947 ARMCC::CondCodes CC = 10948 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10949 10950 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 10951 // -> (brcond Chain BB CC CPSR Cmp) 10952 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 10953 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 10954 LHS->getOperand(0)->hasOneUse()) { 10955 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 10956 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 10957 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10958 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10959 if ((LHS00C && LHS00C->getZExtValue() == 0) && 10960 (LHS01C && LHS01C->getZExtValue() == 1) && 10961 (LHS1C && LHS1C->getZExtValue() == 1) && 10962 (RHSC && RHSC->getZExtValue() == 0)) { 10963 return DAG.getNode( 10964 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 10965 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 10966 } 10967 } 10968 10969 return SDValue(); 10970 } 10971 10972 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10973 SDValue 10974 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10975 SDValue Cmp = N->getOperand(4); 10976 if (Cmp.getOpcode() != ARMISD::CMPZ) 10977 // Only looking at EQ and NE cases. 10978 return SDValue(); 10979 10980 EVT VT = N->getValueType(0); 10981 SDLoc dl(N); 10982 SDValue LHS = Cmp.getOperand(0); 10983 SDValue RHS = Cmp.getOperand(1); 10984 SDValue FalseVal = N->getOperand(0); 10985 SDValue TrueVal = N->getOperand(1); 10986 SDValue ARMcc = N->getOperand(2); 10987 ARMCC::CondCodes CC = 10988 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10989 10990 // BFI is only available on V6T2+. 10991 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 10992 SDValue R = PerformCMOVToBFICombine(N, DAG); 10993 if (R) 10994 return R; 10995 } 10996 10997 // Simplify 10998 // mov r1, r0 10999 // cmp r1, x 11000 // mov r0, y 11001 // moveq r0, x 11002 // to 11003 // cmp r0, x 11004 // movne r0, y 11005 // 11006 // mov r1, r0 11007 // cmp r1, x 11008 // mov r0, x 11009 // movne r0, y 11010 // to 11011 // cmp r0, x 11012 // movne r0, y 11013 /// FIXME: Turn this into a target neutral optimization? 11014 SDValue Res; 11015 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 11016 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 11017 N->getOperand(3), Cmp); 11018 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 11019 SDValue ARMcc; 11020 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 11021 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 11022 N->getOperand(3), NewCmp); 11023 } 11024 11025 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 11026 // -> (cmov F T CC CPSR Cmp) 11027 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 11028 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 11029 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11030 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11031 if ((LHS0C && LHS0C->getZExtValue() == 0) && 11032 (LHS1C && LHS1C->getZExtValue() == 1) && 11033 (RHSC && RHSC->getZExtValue() == 0)) { 11034 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 11035 LHS->getOperand(2), LHS->getOperand(3), 11036 LHS->getOperand(4)); 11037 } 11038 } 11039 11040 if (Res.getNode()) { 11041 APInt KnownZero, KnownOne; 11042 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 11043 // Capture demanded bits information that would be otherwise lost. 11044 if (KnownZero == 0xfffffffe) 11045 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11046 DAG.getValueType(MVT::i1)); 11047 else if (KnownZero == 0xffffff00) 11048 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11049 DAG.getValueType(MVT::i8)); 11050 else if (KnownZero == 0xffff0000) 11051 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11052 DAG.getValueType(MVT::i16)); 11053 } 11054 11055 return Res; 11056 } 11057 11058 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 11059 DAGCombinerInfo &DCI) const { 11060 switch (N->getOpcode()) { 11061 default: break; 11062 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 11063 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 11064 case ISD::SUB: return PerformSUBCombine(N, DCI); 11065 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 11066 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 11067 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 11068 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 11069 case ARMISD::BFI: return PerformBFICombine(N, DCI); 11070 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 11071 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 11072 case ISD::STORE: return PerformSTORECombine(N, DCI); 11073 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 11074 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 11075 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 11076 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 11077 case ISD::FP_TO_SINT: 11078 case ISD::FP_TO_UINT: 11079 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 11080 case ISD::FDIV: 11081 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 11082 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 11083 case ISD::SHL: 11084 case ISD::SRA: 11085 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 11086 case ISD::SIGN_EXTEND: 11087 case ISD::ZERO_EXTEND: 11088 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 11089 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 11090 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 11091 case ISD::LOAD: return PerformLOADCombine(N, DCI); 11092 case ARMISD::VLD2DUP: 11093 case ARMISD::VLD3DUP: 11094 case ARMISD::VLD4DUP: 11095 return PerformVLDCombine(N, DCI); 11096 case ARMISD::BUILD_VECTOR: 11097 return PerformARMBUILD_VECTORCombine(N, DCI); 11098 case ISD::INTRINSIC_VOID: 11099 case ISD::INTRINSIC_W_CHAIN: 11100 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11101 case Intrinsic::arm_neon_vld1: 11102 case Intrinsic::arm_neon_vld2: 11103 case Intrinsic::arm_neon_vld3: 11104 case Intrinsic::arm_neon_vld4: 11105 case Intrinsic::arm_neon_vld2lane: 11106 case Intrinsic::arm_neon_vld3lane: 11107 case Intrinsic::arm_neon_vld4lane: 11108 case Intrinsic::arm_neon_vst1: 11109 case Intrinsic::arm_neon_vst2: 11110 case Intrinsic::arm_neon_vst3: 11111 case Intrinsic::arm_neon_vst4: 11112 case Intrinsic::arm_neon_vst2lane: 11113 case Intrinsic::arm_neon_vst3lane: 11114 case Intrinsic::arm_neon_vst4lane: 11115 return PerformVLDCombine(N, DCI); 11116 default: break; 11117 } 11118 break; 11119 } 11120 return SDValue(); 11121 } 11122 11123 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 11124 EVT VT) const { 11125 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 11126 } 11127 11128 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 11129 unsigned, 11130 unsigned, 11131 bool *Fast) const { 11132 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 11133 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 11134 11135 switch (VT.getSimpleVT().SimpleTy) { 11136 default: 11137 return false; 11138 case MVT::i8: 11139 case MVT::i16: 11140 case MVT::i32: { 11141 // Unaligned access can use (for example) LRDB, LRDH, LDR 11142 if (AllowsUnaligned) { 11143 if (Fast) 11144 *Fast = Subtarget->hasV7Ops(); 11145 return true; 11146 } 11147 return false; 11148 } 11149 case MVT::f64: 11150 case MVT::v2f64: { 11151 // For any little-endian targets with neon, we can support unaligned ld/st 11152 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 11153 // A big-endian target may also explicitly support unaligned accesses 11154 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 11155 if (Fast) 11156 *Fast = true; 11157 return true; 11158 } 11159 return false; 11160 } 11161 } 11162 } 11163 11164 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 11165 unsigned AlignCheck) { 11166 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 11167 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 11168 } 11169 11170 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 11171 unsigned DstAlign, unsigned SrcAlign, 11172 bool IsMemset, bool ZeroMemset, 11173 bool MemcpyStrSrc, 11174 MachineFunction &MF) const { 11175 const Function *F = MF.getFunction(); 11176 11177 // See if we can use NEON instructions for this... 11178 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 11179 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 11180 bool Fast; 11181 if (Size >= 16 && 11182 (memOpAlign(SrcAlign, DstAlign, 16) || 11183 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 11184 return MVT::v2f64; 11185 } else if (Size >= 8 && 11186 (memOpAlign(SrcAlign, DstAlign, 8) || 11187 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 11188 Fast))) { 11189 return MVT::f64; 11190 } 11191 } 11192 11193 // Lowering to i32/i16 if the size permits. 11194 if (Size >= 4) 11195 return MVT::i32; 11196 else if (Size >= 2) 11197 return MVT::i16; 11198 11199 // Let the target-independent logic figure it out. 11200 return MVT::Other; 11201 } 11202 11203 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 11204 if (Val.getOpcode() != ISD::LOAD) 11205 return false; 11206 11207 EVT VT1 = Val.getValueType(); 11208 if (!VT1.isSimple() || !VT1.isInteger() || 11209 !VT2.isSimple() || !VT2.isInteger()) 11210 return false; 11211 11212 switch (VT1.getSimpleVT().SimpleTy) { 11213 default: break; 11214 case MVT::i1: 11215 case MVT::i8: 11216 case MVT::i16: 11217 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 11218 return true; 11219 } 11220 11221 return false; 11222 } 11223 11224 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 11225 EVT VT = ExtVal.getValueType(); 11226 11227 if (!isTypeLegal(VT)) 11228 return false; 11229 11230 // Don't create a loadext if we can fold the extension into a wide/long 11231 // instruction. 11232 // If there's more than one user instruction, the loadext is desirable no 11233 // matter what. There can be two uses by the same instruction. 11234 if (ExtVal->use_empty() || 11235 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 11236 return true; 11237 11238 SDNode *U = *ExtVal->use_begin(); 11239 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 11240 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 11241 return false; 11242 11243 return true; 11244 } 11245 11246 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 11247 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11248 return false; 11249 11250 if (!isTypeLegal(EVT::getEVT(Ty1))) 11251 return false; 11252 11253 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 11254 11255 // Assuming the caller doesn't have a zeroext or signext return parameter, 11256 // truncation all the way down to i1 is valid. 11257 return true; 11258 } 11259 11260 11261 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11262 if (V < 0) 11263 return false; 11264 11265 unsigned Scale = 1; 11266 switch (VT.getSimpleVT().SimpleTy) { 11267 default: return false; 11268 case MVT::i1: 11269 case MVT::i8: 11270 // Scale == 1; 11271 break; 11272 case MVT::i16: 11273 // Scale == 2; 11274 Scale = 2; 11275 break; 11276 case MVT::i32: 11277 // Scale == 4; 11278 Scale = 4; 11279 break; 11280 } 11281 11282 if ((V & (Scale - 1)) != 0) 11283 return false; 11284 V /= Scale; 11285 return V == (V & ((1LL << 5) - 1)); 11286 } 11287 11288 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11289 const ARMSubtarget *Subtarget) { 11290 bool isNeg = false; 11291 if (V < 0) { 11292 isNeg = true; 11293 V = - V; 11294 } 11295 11296 switch (VT.getSimpleVT().SimpleTy) { 11297 default: return false; 11298 case MVT::i1: 11299 case MVT::i8: 11300 case MVT::i16: 11301 case MVT::i32: 11302 // + imm12 or - imm8 11303 if (isNeg) 11304 return V == (V & ((1LL << 8) - 1)); 11305 return V == (V & ((1LL << 12) - 1)); 11306 case MVT::f32: 11307 case MVT::f64: 11308 // Same as ARM mode. FIXME: NEON? 11309 if (!Subtarget->hasVFP2()) 11310 return false; 11311 if ((V & 3) != 0) 11312 return false; 11313 V >>= 2; 11314 return V == (V & ((1LL << 8) - 1)); 11315 } 11316 } 11317 11318 /// isLegalAddressImmediate - Return true if the integer value can be used 11319 /// as the offset of the target addressing mode for load / store of the 11320 /// given type. 11321 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11322 const ARMSubtarget *Subtarget) { 11323 if (V == 0) 11324 return true; 11325 11326 if (!VT.isSimple()) 11327 return false; 11328 11329 if (Subtarget->isThumb1Only()) 11330 return isLegalT1AddressImmediate(V, VT); 11331 else if (Subtarget->isThumb2()) 11332 return isLegalT2AddressImmediate(V, VT, Subtarget); 11333 11334 // ARM mode. 11335 if (V < 0) 11336 V = - V; 11337 switch (VT.getSimpleVT().SimpleTy) { 11338 default: return false; 11339 case MVT::i1: 11340 case MVT::i8: 11341 case MVT::i32: 11342 // +- imm12 11343 return V == (V & ((1LL << 12) - 1)); 11344 case MVT::i16: 11345 // +- imm8 11346 return V == (V & ((1LL << 8) - 1)); 11347 case MVT::f32: 11348 case MVT::f64: 11349 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11350 return false; 11351 if ((V & 3) != 0) 11352 return false; 11353 V >>= 2; 11354 return V == (V & ((1LL << 8) - 1)); 11355 } 11356 } 11357 11358 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11359 EVT VT) const { 11360 int Scale = AM.Scale; 11361 if (Scale < 0) 11362 return false; 11363 11364 switch (VT.getSimpleVT().SimpleTy) { 11365 default: return false; 11366 case MVT::i1: 11367 case MVT::i8: 11368 case MVT::i16: 11369 case MVT::i32: 11370 if (Scale == 1) 11371 return true; 11372 // r + r << imm 11373 Scale = Scale & ~1; 11374 return Scale == 2 || Scale == 4 || Scale == 8; 11375 case MVT::i64: 11376 // r + r 11377 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11378 return true; 11379 return false; 11380 case MVT::isVoid: 11381 // Note, we allow "void" uses (basically, uses that aren't loads or 11382 // stores), because arm allows folding a scale into many arithmetic 11383 // operations. This should be made more precise and revisited later. 11384 11385 // Allow r << imm, but the imm has to be a multiple of two. 11386 if (Scale & 1) return false; 11387 return isPowerOf2_32(Scale); 11388 } 11389 } 11390 11391 /// isLegalAddressingMode - Return true if the addressing mode represented 11392 /// by AM is legal for this target, for a load/store of the specified type. 11393 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11394 const AddrMode &AM, Type *Ty, 11395 unsigned AS) const { 11396 EVT VT = getValueType(DL, Ty, true); 11397 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 11398 return false; 11399 11400 // Can never fold addr of global into load/store. 11401 if (AM.BaseGV) 11402 return false; 11403 11404 switch (AM.Scale) { 11405 case 0: // no scale reg, must be "r+i" or "r", or "i". 11406 break; 11407 case 1: 11408 if (Subtarget->isThumb1Only()) 11409 return false; 11410 // FALL THROUGH. 11411 default: 11412 // ARM doesn't support any R+R*scale+imm addr modes. 11413 if (AM.BaseOffs) 11414 return false; 11415 11416 if (!VT.isSimple()) 11417 return false; 11418 11419 if (Subtarget->isThumb2()) 11420 return isLegalT2ScaledAddressingMode(AM, VT); 11421 11422 int Scale = AM.Scale; 11423 switch (VT.getSimpleVT().SimpleTy) { 11424 default: return false; 11425 case MVT::i1: 11426 case MVT::i8: 11427 case MVT::i32: 11428 if (Scale < 0) Scale = -Scale; 11429 if (Scale == 1) 11430 return true; 11431 // r + r << imm 11432 return isPowerOf2_32(Scale & ~1); 11433 case MVT::i16: 11434 case MVT::i64: 11435 // r + r 11436 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11437 return true; 11438 return false; 11439 11440 case MVT::isVoid: 11441 // Note, we allow "void" uses (basically, uses that aren't loads or 11442 // stores), because arm allows folding a scale into many arithmetic 11443 // operations. This should be made more precise and revisited later. 11444 11445 // Allow r << imm, but the imm has to be a multiple of two. 11446 if (Scale & 1) return false; 11447 return isPowerOf2_32(Scale); 11448 } 11449 } 11450 return true; 11451 } 11452 11453 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11454 /// icmp immediate, that is the target has icmp instructions which can compare 11455 /// a register against the immediate without having to materialize the 11456 /// immediate into a register. 11457 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11458 // Thumb2 and ARM modes can use cmn for negative immediates. 11459 if (!Subtarget->isThumb()) 11460 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11461 if (Subtarget->isThumb2()) 11462 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11463 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11464 return Imm >= 0 && Imm <= 255; 11465 } 11466 11467 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11468 /// *or sub* immediate, that is the target has add or sub instructions which can 11469 /// add a register with the immediate without having to materialize the 11470 /// immediate into a register. 11471 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11472 // Same encoding for add/sub, just flip the sign. 11473 int64_t AbsImm = std::abs(Imm); 11474 if (!Subtarget->isThumb()) 11475 return ARM_AM::getSOImmVal(AbsImm) != -1; 11476 if (Subtarget->isThumb2()) 11477 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11478 // Thumb1 only has 8-bit unsigned immediate. 11479 return AbsImm >= 0 && AbsImm <= 255; 11480 } 11481 11482 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11483 bool isSEXTLoad, SDValue &Base, 11484 SDValue &Offset, bool &isInc, 11485 SelectionDAG &DAG) { 11486 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11487 return false; 11488 11489 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11490 // AddressingMode 3 11491 Base = Ptr->getOperand(0); 11492 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11493 int RHSC = (int)RHS->getZExtValue(); 11494 if (RHSC < 0 && RHSC > -256) { 11495 assert(Ptr->getOpcode() == ISD::ADD); 11496 isInc = false; 11497 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11498 return true; 11499 } 11500 } 11501 isInc = (Ptr->getOpcode() == ISD::ADD); 11502 Offset = Ptr->getOperand(1); 11503 return true; 11504 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11505 // AddressingMode 2 11506 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11507 int RHSC = (int)RHS->getZExtValue(); 11508 if (RHSC < 0 && RHSC > -0x1000) { 11509 assert(Ptr->getOpcode() == ISD::ADD); 11510 isInc = false; 11511 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11512 Base = Ptr->getOperand(0); 11513 return true; 11514 } 11515 } 11516 11517 if (Ptr->getOpcode() == ISD::ADD) { 11518 isInc = true; 11519 ARM_AM::ShiftOpc ShOpcVal= 11520 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11521 if (ShOpcVal != ARM_AM::no_shift) { 11522 Base = Ptr->getOperand(1); 11523 Offset = Ptr->getOperand(0); 11524 } else { 11525 Base = Ptr->getOperand(0); 11526 Offset = Ptr->getOperand(1); 11527 } 11528 return true; 11529 } 11530 11531 isInc = (Ptr->getOpcode() == ISD::ADD); 11532 Base = Ptr->getOperand(0); 11533 Offset = Ptr->getOperand(1); 11534 return true; 11535 } 11536 11537 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11538 return false; 11539 } 11540 11541 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11542 bool isSEXTLoad, SDValue &Base, 11543 SDValue &Offset, bool &isInc, 11544 SelectionDAG &DAG) { 11545 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11546 return false; 11547 11548 Base = Ptr->getOperand(0); 11549 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11550 int RHSC = (int)RHS->getZExtValue(); 11551 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11552 assert(Ptr->getOpcode() == ISD::ADD); 11553 isInc = false; 11554 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11555 return true; 11556 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11557 isInc = Ptr->getOpcode() == ISD::ADD; 11558 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11559 return true; 11560 } 11561 } 11562 11563 return false; 11564 } 11565 11566 /// getPreIndexedAddressParts - returns true by value, base pointer and 11567 /// offset pointer and addressing mode by reference if the node's address 11568 /// can be legally represented as pre-indexed load / store address. 11569 bool 11570 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11571 SDValue &Offset, 11572 ISD::MemIndexedMode &AM, 11573 SelectionDAG &DAG) const { 11574 if (Subtarget->isThumb1Only()) 11575 return false; 11576 11577 EVT VT; 11578 SDValue Ptr; 11579 bool isSEXTLoad = false; 11580 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11581 Ptr = LD->getBasePtr(); 11582 VT = LD->getMemoryVT(); 11583 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11584 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11585 Ptr = ST->getBasePtr(); 11586 VT = ST->getMemoryVT(); 11587 } else 11588 return false; 11589 11590 bool isInc; 11591 bool isLegal = false; 11592 if (Subtarget->isThumb2()) 11593 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11594 Offset, isInc, DAG); 11595 else 11596 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11597 Offset, isInc, DAG); 11598 if (!isLegal) 11599 return false; 11600 11601 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11602 return true; 11603 } 11604 11605 /// getPostIndexedAddressParts - returns true by value, base pointer and 11606 /// offset pointer and addressing mode by reference if this node can be 11607 /// combined with a load / store to form a post-indexed load / store. 11608 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11609 SDValue &Base, 11610 SDValue &Offset, 11611 ISD::MemIndexedMode &AM, 11612 SelectionDAG &DAG) const { 11613 EVT VT; 11614 SDValue Ptr; 11615 bool isSEXTLoad = false, isNonExt; 11616 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11617 VT = LD->getMemoryVT(); 11618 Ptr = LD->getBasePtr(); 11619 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11620 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 11621 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11622 VT = ST->getMemoryVT(); 11623 Ptr = ST->getBasePtr(); 11624 isNonExt = !ST->isTruncatingStore(); 11625 } else 11626 return false; 11627 11628 if (Subtarget->isThumb1Only()) { 11629 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 11630 // must be non-extending/truncating, i32, with an offset of 4. 11631 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 11632 if (Op->getOpcode() != ISD::ADD || !isNonExt) 11633 return false; 11634 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 11635 if (!RHS || RHS->getZExtValue() != 4) 11636 return false; 11637 11638 Offset = Op->getOperand(1); 11639 Base = Op->getOperand(0); 11640 AM = ISD::POST_INC; 11641 return true; 11642 } 11643 11644 bool isInc; 11645 bool isLegal = false; 11646 if (Subtarget->isThumb2()) 11647 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11648 isInc, DAG); 11649 else 11650 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11651 isInc, DAG); 11652 if (!isLegal) 11653 return false; 11654 11655 if (Ptr != Base) { 11656 // Swap base ptr and offset to catch more post-index load / store when 11657 // it's legal. In Thumb2 mode, offset must be an immediate. 11658 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11659 !Subtarget->isThumb2()) 11660 std::swap(Base, Offset); 11661 11662 // Post-indexed load / store update the base pointer. 11663 if (Ptr != Base) 11664 return false; 11665 } 11666 11667 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11668 return true; 11669 } 11670 11671 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11672 APInt &KnownZero, 11673 APInt &KnownOne, 11674 const SelectionDAG &DAG, 11675 unsigned Depth) const { 11676 unsigned BitWidth = KnownOne.getBitWidth(); 11677 KnownZero = KnownOne = APInt(BitWidth, 0); 11678 switch (Op.getOpcode()) { 11679 default: break; 11680 case ARMISD::ADDC: 11681 case ARMISD::ADDE: 11682 case ARMISD::SUBC: 11683 case ARMISD::SUBE: 11684 // These nodes' second result is a boolean 11685 if (Op.getResNo() == 0) 11686 break; 11687 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11688 break; 11689 case ARMISD::CMOV: { 11690 // Bits are known zero/one if known on the LHS and RHS. 11691 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11692 if (KnownZero == 0 && KnownOne == 0) return; 11693 11694 APInt KnownZeroRHS, KnownOneRHS; 11695 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11696 KnownZero &= KnownZeroRHS; 11697 KnownOne &= KnownOneRHS; 11698 return; 11699 } 11700 case ISD::INTRINSIC_W_CHAIN: { 11701 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11702 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11703 switch (IntID) { 11704 default: return; 11705 case Intrinsic::arm_ldaex: 11706 case Intrinsic::arm_ldrex: { 11707 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11708 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11709 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11710 return; 11711 } 11712 } 11713 } 11714 } 11715 } 11716 11717 //===----------------------------------------------------------------------===// 11718 // ARM Inline Assembly Support 11719 //===----------------------------------------------------------------------===// 11720 11721 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11722 // Looking for "rev" which is V6+. 11723 if (!Subtarget->hasV6Ops()) 11724 return false; 11725 11726 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11727 std::string AsmStr = IA->getAsmString(); 11728 SmallVector<StringRef, 4> AsmPieces; 11729 SplitString(AsmStr, AsmPieces, ";\n"); 11730 11731 switch (AsmPieces.size()) { 11732 default: return false; 11733 case 1: 11734 AsmStr = AsmPieces[0]; 11735 AsmPieces.clear(); 11736 SplitString(AsmStr, AsmPieces, " \t,"); 11737 11738 // rev $0, $1 11739 if (AsmPieces.size() == 3 && 11740 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11741 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11742 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11743 if (Ty && Ty->getBitWidth() == 32) 11744 return IntrinsicLowering::LowerToByteSwap(CI); 11745 } 11746 break; 11747 } 11748 11749 return false; 11750 } 11751 11752 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 11753 // At this point, we have to lower this constraint to something else, so we 11754 // lower it to an "r" or "w". However, by doing this we will force the result 11755 // to be in register, while the X constraint is much more permissive. 11756 // 11757 // Although we are correct (we are free to emit anything, without 11758 // constraints), we might break use cases that would expect us to be more 11759 // efficient and emit something else. 11760 if (!Subtarget->hasVFP2()) 11761 return "r"; 11762 if (ConstraintVT.isFloatingPoint()) 11763 return "w"; 11764 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 11765 (ConstraintVT.getSizeInBits() == 64 || 11766 ConstraintVT.getSizeInBits() == 128)) 11767 return "w"; 11768 11769 return "r"; 11770 } 11771 11772 /// getConstraintType - Given a constraint letter, return the type of 11773 /// constraint it is for this target. 11774 ARMTargetLowering::ConstraintType 11775 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11776 if (Constraint.size() == 1) { 11777 switch (Constraint[0]) { 11778 default: break; 11779 case 'l': return C_RegisterClass; 11780 case 'w': return C_RegisterClass; 11781 case 'h': return C_RegisterClass; 11782 case 'x': return C_RegisterClass; 11783 case 't': return C_RegisterClass; 11784 case 'j': return C_Other; // Constant for movw. 11785 // An address with a single base register. Due to the way we 11786 // currently handle addresses it is the same as an 'r' memory constraint. 11787 case 'Q': return C_Memory; 11788 } 11789 } else if (Constraint.size() == 2) { 11790 switch (Constraint[0]) { 11791 default: break; 11792 // All 'U+' constraints are addresses. 11793 case 'U': return C_Memory; 11794 } 11795 } 11796 return TargetLowering::getConstraintType(Constraint); 11797 } 11798 11799 /// Examine constraint type and operand type and determine a weight value. 11800 /// This object must already have been set up with the operand type 11801 /// and the current alternative constraint selected. 11802 TargetLowering::ConstraintWeight 11803 ARMTargetLowering::getSingleConstraintMatchWeight( 11804 AsmOperandInfo &info, const char *constraint) const { 11805 ConstraintWeight weight = CW_Invalid; 11806 Value *CallOperandVal = info.CallOperandVal; 11807 // If we don't have a value, we can't do a match, 11808 // but allow it at the lowest weight. 11809 if (!CallOperandVal) 11810 return CW_Default; 11811 Type *type = CallOperandVal->getType(); 11812 // Look at the constraint type. 11813 switch (*constraint) { 11814 default: 11815 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11816 break; 11817 case 'l': 11818 if (type->isIntegerTy()) { 11819 if (Subtarget->isThumb()) 11820 weight = CW_SpecificReg; 11821 else 11822 weight = CW_Register; 11823 } 11824 break; 11825 case 'w': 11826 if (type->isFloatingPointTy()) 11827 weight = CW_Register; 11828 break; 11829 } 11830 return weight; 11831 } 11832 11833 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 11834 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 11835 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 11836 if (Constraint.size() == 1) { 11837 // GCC ARM Constraint Letters 11838 switch (Constraint[0]) { 11839 case 'l': // Low regs or general regs. 11840 if (Subtarget->isThumb()) 11841 return RCPair(0U, &ARM::tGPRRegClass); 11842 return RCPair(0U, &ARM::GPRRegClass); 11843 case 'h': // High regs or no regs. 11844 if (Subtarget->isThumb()) 11845 return RCPair(0U, &ARM::hGPRRegClass); 11846 break; 11847 case 'r': 11848 if (Subtarget->isThumb1Only()) 11849 return RCPair(0U, &ARM::tGPRRegClass); 11850 return RCPair(0U, &ARM::GPRRegClass); 11851 case 'w': 11852 if (VT == MVT::Other) 11853 break; 11854 if (VT == MVT::f32) 11855 return RCPair(0U, &ARM::SPRRegClass); 11856 if (VT.getSizeInBits() == 64) 11857 return RCPair(0U, &ARM::DPRRegClass); 11858 if (VT.getSizeInBits() == 128) 11859 return RCPair(0U, &ARM::QPRRegClass); 11860 break; 11861 case 'x': 11862 if (VT == MVT::Other) 11863 break; 11864 if (VT == MVT::f32) 11865 return RCPair(0U, &ARM::SPR_8RegClass); 11866 if (VT.getSizeInBits() == 64) 11867 return RCPair(0U, &ARM::DPR_8RegClass); 11868 if (VT.getSizeInBits() == 128) 11869 return RCPair(0U, &ARM::QPR_8RegClass); 11870 break; 11871 case 't': 11872 if (VT == MVT::f32) 11873 return RCPair(0U, &ARM::SPRRegClass); 11874 break; 11875 } 11876 } 11877 if (StringRef("{cc}").equals_lower(Constraint)) 11878 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 11879 11880 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11881 } 11882 11883 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 11884 /// vector. If it is invalid, don't add anything to Ops. 11885 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11886 std::string &Constraint, 11887 std::vector<SDValue>&Ops, 11888 SelectionDAG &DAG) const { 11889 SDValue Result; 11890 11891 // Currently only support length 1 constraints. 11892 if (Constraint.length() != 1) return; 11893 11894 char ConstraintLetter = Constraint[0]; 11895 switch (ConstraintLetter) { 11896 default: break; 11897 case 'j': 11898 case 'I': case 'J': case 'K': case 'L': 11899 case 'M': case 'N': case 'O': 11900 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11901 if (!C) 11902 return; 11903 11904 int64_t CVal64 = C->getSExtValue(); 11905 int CVal = (int) CVal64; 11906 // None of these constraints allow values larger than 32 bits. Check 11907 // that the value fits in an int. 11908 if (CVal != CVal64) 11909 return; 11910 11911 switch (ConstraintLetter) { 11912 case 'j': 11913 // Constant suitable for movw, must be between 0 and 11914 // 65535. 11915 if (Subtarget->hasV6T2Ops()) 11916 if (CVal >= 0 && CVal <= 65535) 11917 break; 11918 return; 11919 case 'I': 11920 if (Subtarget->isThumb1Only()) { 11921 // This must be a constant between 0 and 255, for ADD 11922 // immediates. 11923 if (CVal >= 0 && CVal <= 255) 11924 break; 11925 } else if (Subtarget->isThumb2()) { 11926 // A constant that can be used as an immediate value in a 11927 // data-processing instruction. 11928 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11929 break; 11930 } else { 11931 // A constant that can be used as an immediate value in a 11932 // data-processing instruction. 11933 if (ARM_AM::getSOImmVal(CVal) != -1) 11934 break; 11935 } 11936 return; 11937 11938 case 'J': 11939 if (Subtarget->isThumb1Only()) { 11940 // This must be a constant between -255 and -1, for negated ADD 11941 // immediates. This can be used in GCC with an "n" modifier that 11942 // prints the negated value, for use with SUB instructions. It is 11943 // not useful otherwise but is implemented for compatibility. 11944 if (CVal >= -255 && CVal <= -1) 11945 break; 11946 } else { 11947 // This must be a constant between -4095 and 4095. It is not clear 11948 // what this constraint is intended for. Implemented for 11949 // compatibility with GCC. 11950 if (CVal >= -4095 && CVal <= 4095) 11951 break; 11952 } 11953 return; 11954 11955 case 'K': 11956 if (Subtarget->isThumb1Only()) { 11957 // A 32-bit value where only one byte has a nonzero value. Exclude 11958 // zero to match GCC. This constraint is used by GCC internally for 11959 // constants that can be loaded with a move/shift combination. 11960 // It is not useful otherwise but is implemented for compatibility. 11961 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11962 break; 11963 } else if (Subtarget->isThumb2()) { 11964 // A constant whose bitwise inverse can be used as an immediate 11965 // value in a data-processing instruction. This can be used in GCC 11966 // with a "B" modifier that prints the inverted value, for use with 11967 // BIC and MVN instructions. It is not useful otherwise but is 11968 // implemented for compatibility. 11969 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11970 break; 11971 } else { 11972 // A constant whose bitwise inverse can be used as an immediate 11973 // value in a data-processing instruction. This can be used in GCC 11974 // with a "B" modifier that prints the inverted value, for use with 11975 // BIC and MVN instructions. It is not useful otherwise but is 11976 // implemented for compatibility. 11977 if (ARM_AM::getSOImmVal(~CVal) != -1) 11978 break; 11979 } 11980 return; 11981 11982 case 'L': 11983 if (Subtarget->isThumb1Only()) { 11984 // This must be a constant between -7 and 7, 11985 // for 3-operand ADD/SUB immediate instructions. 11986 if (CVal >= -7 && CVal < 7) 11987 break; 11988 } else if (Subtarget->isThumb2()) { 11989 // A constant whose negation can be used as an immediate value in a 11990 // data-processing instruction. This can be used in GCC with an "n" 11991 // modifier that prints the negated value, for use with SUB 11992 // instructions. It is not useful otherwise but is implemented for 11993 // compatibility. 11994 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11995 break; 11996 } else { 11997 // A constant whose negation can be used as an immediate value in a 11998 // data-processing instruction. This can be used in GCC with an "n" 11999 // modifier that prints the negated value, for use with SUB 12000 // instructions. It is not useful otherwise but is implemented for 12001 // compatibility. 12002 if (ARM_AM::getSOImmVal(-CVal) != -1) 12003 break; 12004 } 12005 return; 12006 12007 case 'M': 12008 if (Subtarget->isThumb1Only()) { 12009 // This must be a multiple of 4 between 0 and 1020, for 12010 // ADD sp + immediate. 12011 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 12012 break; 12013 } else { 12014 // A power of two or a constant between 0 and 32. This is used in 12015 // GCC for the shift amount on shifted register operands, but it is 12016 // useful in general for any shift amounts. 12017 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 12018 break; 12019 } 12020 return; 12021 12022 case 'N': 12023 if (Subtarget->isThumb()) { // FIXME thumb2 12024 // This must be a constant between 0 and 31, for shift amounts. 12025 if (CVal >= 0 && CVal <= 31) 12026 break; 12027 } 12028 return; 12029 12030 case 'O': 12031 if (Subtarget->isThumb()) { // FIXME thumb2 12032 // This must be a multiple of 4 between -508 and 508, for 12033 // ADD/SUB sp = sp + immediate. 12034 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 12035 break; 12036 } 12037 return; 12038 } 12039 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 12040 break; 12041 } 12042 12043 if (Result.getNode()) { 12044 Ops.push_back(Result); 12045 return; 12046 } 12047 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12048 } 12049 12050 static RTLIB::Libcall getDivRemLibcall( 12051 const SDNode *N, MVT::SimpleValueType SVT) { 12052 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12053 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12054 "Unhandled Opcode in getDivRemLibcall"); 12055 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12056 N->getOpcode() == ISD::SREM; 12057 RTLIB::Libcall LC; 12058 switch (SVT) { 12059 default: llvm_unreachable("Unexpected request for libcall!"); 12060 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 12061 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 12062 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 12063 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 12064 } 12065 return LC; 12066 } 12067 12068 static TargetLowering::ArgListTy getDivRemArgList( 12069 const SDNode *N, LLVMContext *Context) { 12070 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12071 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12072 "Unhandled Opcode in getDivRemArgList"); 12073 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12074 N->getOpcode() == ISD::SREM; 12075 TargetLowering::ArgListTy Args; 12076 TargetLowering::ArgListEntry Entry; 12077 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12078 EVT ArgVT = N->getOperand(i).getValueType(); 12079 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 12080 Entry.Node = N->getOperand(i); 12081 Entry.Ty = ArgTy; 12082 Entry.isSExt = isSigned; 12083 Entry.isZExt = !isSigned; 12084 Args.push_back(Entry); 12085 } 12086 return Args; 12087 } 12088 12089 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 12090 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 12091 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) && 12092 "Register-based DivRem lowering only"); 12093 unsigned Opcode = Op->getOpcode(); 12094 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 12095 "Invalid opcode for Div/Rem lowering"); 12096 bool isSigned = (Opcode == ISD::SDIVREM); 12097 EVT VT = Op->getValueType(0); 12098 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 12099 12100 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 12101 VT.getSimpleVT().SimpleTy); 12102 SDValue InChain = DAG.getEntryNode(); 12103 12104 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 12105 DAG.getContext()); 12106 12107 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12108 getPointerTy(DAG.getDataLayout())); 12109 12110 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 12111 12112 SDLoc dl(Op); 12113 TargetLowering::CallLoweringInfo CLI(DAG); 12114 CLI.setDebugLoc(dl).setChain(InChain) 12115 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 12116 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 12117 12118 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 12119 return CallInfo.first; 12120 } 12121 12122 // Lowers REM using divmod helpers 12123 // see RTABI section 4.2/4.3 12124 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 12125 // Build return types (div and rem) 12126 std::vector<Type*> RetTyParams; 12127 Type *RetTyElement; 12128 12129 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 12130 default: llvm_unreachable("Unexpected request for libcall!"); 12131 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 12132 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 12133 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 12134 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 12135 } 12136 12137 RetTyParams.push_back(RetTyElement); 12138 RetTyParams.push_back(RetTyElement); 12139 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 12140 Type *RetTy = StructType::get(*DAG.getContext(), ret); 12141 12142 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 12143 SimpleTy); 12144 SDValue InChain = DAG.getEntryNode(); 12145 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 12146 bool isSigned = N->getOpcode() == ISD::SREM; 12147 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12148 getPointerTy(DAG.getDataLayout())); 12149 12150 // Lower call 12151 CallLoweringInfo CLI(DAG); 12152 CLI.setChain(InChain) 12153 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 12154 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 12155 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 12156 12157 // Return second (rem) result operand (first contains div) 12158 SDNode *ResNode = CallResult.first.getNode(); 12159 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 12160 return ResNode->getOperand(1); 12161 } 12162 12163 SDValue 12164 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 12165 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 12166 SDLoc DL(Op); 12167 12168 // Get the inputs. 12169 SDValue Chain = Op.getOperand(0); 12170 SDValue Size = Op.getOperand(1); 12171 12172 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 12173 DAG.getConstant(2, DL, MVT::i32)); 12174 12175 SDValue Flag; 12176 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 12177 Flag = Chain.getValue(1); 12178 12179 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 12180 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 12181 12182 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 12183 Chain = NewSP.getValue(1); 12184 12185 SDValue Ops[2] = { NewSP, Chain }; 12186 return DAG.getMergeValues(Ops, DL); 12187 } 12188 12189 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 12190 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 12191 "Unexpected type for custom-lowering FP_EXTEND"); 12192 12193 RTLIB::Libcall LC; 12194 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 12195 12196 SDValue SrcVal = Op.getOperand(0); 12197 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12198 SDLoc(Op)).first; 12199 } 12200 12201 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 12202 assert(Op.getOperand(0).getValueType() == MVT::f64 && 12203 Subtarget->isFPOnlySP() && 12204 "Unexpected type for custom-lowering FP_ROUND"); 12205 12206 RTLIB::Libcall LC; 12207 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 12208 12209 SDValue SrcVal = Op.getOperand(0); 12210 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12211 SDLoc(Op)).first; 12212 } 12213 12214 bool 12215 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12216 // The ARM target isn't yet aware of offsets. 12217 return false; 12218 } 12219 12220 bool ARM::isBitFieldInvertedMask(unsigned v) { 12221 if (v == 0xffffffff) 12222 return false; 12223 12224 // there can be 1's on either or both "outsides", all the "inside" 12225 // bits must be 0's 12226 return isShiftedMask_32(~v); 12227 } 12228 12229 /// isFPImmLegal - Returns true if the target can instruction select the 12230 /// specified FP immediate natively. If false, the legalizer will 12231 /// materialize the FP immediate as a load from a constant pool. 12232 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 12233 if (!Subtarget->hasVFP3()) 12234 return false; 12235 if (VT == MVT::f32) 12236 return ARM_AM::getFP32Imm(Imm) != -1; 12237 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 12238 return ARM_AM::getFP64Imm(Imm) != -1; 12239 return false; 12240 } 12241 12242 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 12243 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 12244 /// specified in the intrinsic calls. 12245 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12246 const CallInst &I, 12247 unsigned Intrinsic) const { 12248 switch (Intrinsic) { 12249 case Intrinsic::arm_neon_vld1: 12250 case Intrinsic::arm_neon_vld2: 12251 case Intrinsic::arm_neon_vld3: 12252 case Intrinsic::arm_neon_vld4: 12253 case Intrinsic::arm_neon_vld2lane: 12254 case Intrinsic::arm_neon_vld3lane: 12255 case Intrinsic::arm_neon_vld4lane: { 12256 Info.opc = ISD::INTRINSIC_W_CHAIN; 12257 // Conservatively set memVT to the entire set of vectors loaded. 12258 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12259 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 12260 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12261 Info.ptrVal = I.getArgOperand(0); 12262 Info.offset = 0; 12263 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12264 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12265 Info.vol = false; // volatile loads with NEON intrinsics not supported 12266 Info.readMem = true; 12267 Info.writeMem = false; 12268 return true; 12269 } 12270 case Intrinsic::arm_neon_vst1: 12271 case Intrinsic::arm_neon_vst2: 12272 case Intrinsic::arm_neon_vst3: 12273 case Intrinsic::arm_neon_vst4: 12274 case Intrinsic::arm_neon_vst2lane: 12275 case Intrinsic::arm_neon_vst3lane: 12276 case Intrinsic::arm_neon_vst4lane: { 12277 Info.opc = ISD::INTRINSIC_VOID; 12278 // Conservatively set memVT to the entire set of vectors stored. 12279 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12280 unsigned NumElts = 0; 12281 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 12282 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 12283 if (!ArgTy->isVectorTy()) 12284 break; 12285 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 12286 } 12287 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12288 Info.ptrVal = I.getArgOperand(0); 12289 Info.offset = 0; 12290 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12291 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12292 Info.vol = false; // volatile stores with NEON intrinsics not supported 12293 Info.readMem = false; 12294 Info.writeMem = true; 12295 return true; 12296 } 12297 case Intrinsic::arm_ldaex: 12298 case Intrinsic::arm_ldrex: { 12299 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12300 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12301 Info.opc = ISD::INTRINSIC_W_CHAIN; 12302 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12303 Info.ptrVal = I.getArgOperand(0); 12304 Info.offset = 0; 12305 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12306 Info.vol = true; 12307 Info.readMem = true; 12308 Info.writeMem = false; 12309 return true; 12310 } 12311 case Intrinsic::arm_stlex: 12312 case Intrinsic::arm_strex: { 12313 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12314 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12315 Info.opc = ISD::INTRINSIC_W_CHAIN; 12316 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12317 Info.ptrVal = I.getArgOperand(1); 12318 Info.offset = 0; 12319 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12320 Info.vol = true; 12321 Info.readMem = false; 12322 Info.writeMem = true; 12323 return true; 12324 } 12325 case Intrinsic::arm_stlexd: 12326 case Intrinsic::arm_strexd: { 12327 Info.opc = ISD::INTRINSIC_W_CHAIN; 12328 Info.memVT = MVT::i64; 12329 Info.ptrVal = I.getArgOperand(2); 12330 Info.offset = 0; 12331 Info.align = 8; 12332 Info.vol = true; 12333 Info.readMem = false; 12334 Info.writeMem = true; 12335 return true; 12336 } 12337 case Intrinsic::arm_ldaexd: 12338 case Intrinsic::arm_ldrexd: { 12339 Info.opc = ISD::INTRINSIC_W_CHAIN; 12340 Info.memVT = MVT::i64; 12341 Info.ptrVal = I.getArgOperand(0); 12342 Info.offset = 0; 12343 Info.align = 8; 12344 Info.vol = true; 12345 Info.readMem = true; 12346 Info.writeMem = false; 12347 return true; 12348 } 12349 default: 12350 break; 12351 } 12352 12353 return false; 12354 } 12355 12356 /// \brief Returns true if it is beneficial to convert a load of a constant 12357 /// to just the constant itself. 12358 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12359 Type *Ty) const { 12360 assert(Ty->isIntegerTy()); 12361 12362 unsigned Bits = Ty->getPrimitiveSizeInBits(); 12363 if (Bits == 0 || Bits > 32) 12364 return false; 12365 return true; 12366 } 12367 12368 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 12369 ARM_MB::MemBOpt Domain) const { 12370 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12371 12372 // First, if the target has no DMB, see what fallback we can use. 12373 if (!Subtarget->hasDataBarrier()) { 12374 // Some ARMv6 cpus can support data barriers with an mcr instruction. 12375 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 12376 // here. 12377 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 12378 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 12379 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 12380 Builder.getInt32(0), Builder.getInt32(7), 12381 Builder.getInt32(10), Builder.getInt32(5)}; 12382 return Builder.CreateCall(MCR, args); 12383 } else { 12384 // Instead of using barriers, atomic accesses on these subtargets use 12385 // libcalls. 12386 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 12387 } 12388 } else { 12389 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 12390 // Only a full system barrier exists in the M-class architectures. 12391 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 12392 Constant *CDomain = Builder.getInt32(Domain); 12393 return Builder.CreateCall(DMB, CDomain); 12394 } 12395 } 12396 12397 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 12398 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 12399 AtomicOrdering Ord, bool IsStore, 12400 bool IsLoad) const { 12401 switch (Ord) { 12402 case AtomicOrdering::NotAtomic: 12403 case AtomicOrdering::Unordered: 12404 llvm_unreachable("Invalid fence: unordered/non-atomic"); 12405 case AtomicOrdering::Monotonic: 12406 case AtomicOrdering::Acquire: 12407 return nullptr; // Nothing to do 12408 case AtomicOrdering::SequentiallyConsistent: 12409 if (!IsStore) 12410 return nullptr; // Nothing to do 12411 /*FALLTHROUGH*/ 12412 case AtomicOrdering::Release: 12413 case AtomicOrdering::AcquireRelease: 12414 if (Subtarget->preferISHSTBarriers()) 12415 return makeDMB(Builder, ARM_MB::ISHST); 12416 // FIXME: add a comment with a link to documentation justifying this. 12417 else 12418 return makeDMB(Builder, ARM_MB::ISH); 12419 } 12420 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 12421 } 12422 12423 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 12424 AtomicOrdering Ord, bool IsStore, 12425 bool IsLoad) const { 12426 switch (Ord) { 12427 case AtomicOrdering::NotAtomic: 12428 case AtomicOrdering::Unordered: 12429 llvm_unreachable("Invalid fence: unordered/not-atomic"); 12430 case AtomicOrdering::Monotonic: 12431 case AtomicOrdering::Release: 12432 return nullptr; // Nothing to do 12433 case AtomicOrdering::Acquire: 12434 case AtomicOrdering::AcquireRelease: 12435 case AtomicOrdering::SequentiallyConsistent: 12436 return makeDMB(Builder, ARM_MB::ISH); 12437 } 12438 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 12439 } 12440 12441 // Loads and stores less than 64-bits are already atomic; ones above that 12442 // are doomed anyway, so defer to the default libcall and blame the OS when 12443 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12444 // anything for those. 12445 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12446 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12447 return (Size == 64) && !Subtarget->isMClass(); 12448 } 12449 12450 // Loads and stores less than 64-bits are already atomic; ones above that 12451 // are doomed anyway, so defer to the default libcall and blame the OS when 12452 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12453 // anything for those. 12454 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12455 // guarantee, see DDI0406C ARM architecture reference manual, 12456 // sections A8.8.72-74 LDRD) 12457 TargetLowering::AtomicExpansionKind 12458 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12459 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12460 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12461 : AtomicExpansionKind::None; 12462 } 12463 12464 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12465 // and up to 64 bits on the non-M profiles 12466 TargetLowering::AtomicExpansionKind 12467 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12468 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12469 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12470 ? AtomicExpansionKind::LLSC 12471 : AtomicExpansionKind::None; 12472 } 12473 12474 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12475 AtomicCmpXchgInst *AI) const { 12476 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 12477 // implement cmpxchg without spilling. If the address being exchanged is also 12478 // on the stack and close enough to the spill slot, this can lead to a 12479 // situation where the monitor always gets cleared and the atomic operation 12480 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 12481 return getTargetMachine().getOptLevel() != 0; 12482 } 12483 12484 bool ARMTargetLowering::shouldInsertFencesForAtomic( 12485 const Instruction *I) const { 12486 return InsertFencesForAtomic; 12487 } 12488 12489 // This has so far only been implemented for MachO. 12490 bool ARMTargetLowering::useLoadStackGuardNode() const { 12491 return Subtarget->isTargetMachO(); 12492 } 12493 12494 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12495 unsigned &Cost) const { 12496 // If we do not have NEON, vector types are not natively supported. 12497 if (!Subtarget->hasNEON()) 12498 return false; 12499 12500 // Floating point values and vector values map to the same register file. 12501 // Therefore, although we could do a store extract of a vector type, this is 12502 // better to leave at float as we have more freedom in the addressing mode for 12503 // those. 12504 if (VectorTy->isFPOrFPVectorTy()) 12505 return false; 12506 12507 // If the index is unknown at compile time, this is very expensive to lower 12508 // and it is not possible to combine the store with the extract. 12509 if (!isa<ConstantInt>(Idx)) 12510 return false; 12511 12512 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12513 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12514 // We can do a store + vector extract on any vector that fits perfectly in a D 12515 // or Q register. 12516 if (BitWidth == 64 || BitWidth == 128) { 12517 Cost = 0; 12518 return true; 12519 } 12520 return false; 12521 } 12522 12523 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12524 return Subtarget->hasV6T2Ops(); 12525 } 12526 12527 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12528 return Subtarget->hasV6T2Ops(); 12529 } 12530 12531 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12532 AtomicOrdering Ord) const { 12533 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12534 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12535 bool IsAcquire = isAcquireOrStronger(Ord); 12536 12537 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12538 // intrinsic must return {i32, i32} and we have to recombine them into a 12539 // single i64 here. 12540 if (ValTy->getPrimitiveSizeInBits() == 64) { 12541 Intrinsic::ID Int = 12542 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12543 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12544 12545 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12546 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12547 12548 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12549 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12550 if (!Subtarget->isLittle()) 12551 std::swap (Lo, Hi); 12552 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12553 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12554 return Builder.CreateOr( 12555 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12556 } 12557 12558 Type *Tys[] = { Addr->getType() }; 12559 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12560 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12561 12562 return Builder.CreateTruncOrBitCast( 12563 Builder.CreateCall(Ldrex, Addr), 12564 cast<PointerType>(Addr->getType())->getElementType()); 12565 } 12566 12567 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12568 IRBuilder<> &Builder) const { 12569 if (!Subtarget->hasV7Ops()) 12570 return; 12571 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12572 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12573 } 12574 12575 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12576 Value *Addr, 12577 AtomicOrdering Ord) const { 12578 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12579 bool IsRelease = isReleaseOrStronger(Ord); 12580 12581 // Since the intrinsics must have legal type, the i64 intrinsics take two 12582 // parameters: "i32, i32". We must marshal Val into the appropriate form 12583 // before the call. 12584 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12585 Intrinsic::ID Int = 12586 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12587 Function *Strex = Intrinsic::getDeclaration(M, Int); 12588 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12589 12590 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12591 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12592 if (!Subtarget->isLittle()) 12593 std::swap (Lo, Hi); 12594 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12595 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12596 } 12597 12598 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12599 Type *Tys[] = { Addr->getType() }; 12600 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12601 12602 return Builder.CreateCall( 12603 Strex, {Builder.CreateZExtOrBitCast( 12604 Val, Strex->getFunctionType()->getParamType(0)), 12605 Addr}); 12606 } 12607 12608 /// \brief Lower an interleaved load into a vldN intrinsic. 12609 /// 12610 /// E.g. Lower an interleaved load (Factor = 2): 12611 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12612 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12613 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12614 /// 12615 /// Into: 12616 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12617 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12618 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12619 bool ARMTargetLowering::lowerInterleavedLoad( 12620 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12621 ArrayRef<unsigned> Indices, unsigned Factor) const { 12622 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12623 "Invalid interleave factor"); 12624 assert(!Shuffles.empty() && "Empty shufflevector input"); 12625 assert(Shuffles.size() == Indices.size() && 12626 "Unmatched number of shufflevectors and indices"); 12627 12628 VectorType *VecTy = Shuffles[0]->getType(); 12629 Type *EltTy = VecTy->getVectorElementType(); 12630 12631 const DataLayout &DL = LI->getModule()->getDataLayout(); 12632 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12633 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12634 12635 // Skip if we do not have NEON and skip illegal vector types and vector types 12636 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12637 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12638 return false; 12639 12640 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12641 // load integer vectors first and then convert to pointer vectors. 12642 if (EltTy->isPointerTy()) 12643 VecTy = 12644 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12645 12646 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12647 Intrinsic::arm_neon_vld3, 12648 Intrinsic::arm_neon_vld4}; 12649 12650 IRBuilder<> Builder(LI); 12651 SmallVector<Value *, 2> Ops; 12652 12653 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12654 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12655 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12656 12657 Type *Tys[] = { VecTy, Int8Ptr }; 12658 Function *VldnFunc = 12659 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12660 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12661 12662 // Replace uses of each shufflevector with the corresponding vector loaded 12663 // by ldN. 12664 for (unsigned i = 0; i < Shuffles.size(); i++) { 12665 ShuffleVectorInst *SV = Shuffles[i]; 12666 unsigned Index = Indices[i]; 12667 12668 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12669 12670 // Convert the integer vector to pointer vector if the element is pointer. 12671 if (EltTy->isPointerTy()) 12672 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12673 12674 SV->replaceAllUsesWith(SubVec); 12675 } 12676 12677 return true; 12678 } 12679 12680 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12681 /// 12682 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12683 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12684 unsigned NumElts) { 12685 SmallVector<Constant *, 16> Mask; 12686 for (unsigned i = 0; i < NumElts; i++) 12687 Mask.push_back(Builder.getInt32(Start + i)); 12688 12689 return ConstantVector::get(Mask); 12690 } 12691 12692 /// \brief Lower an interleaved store into a vstN intrinsic. 12693 /// 12694 /// E.g. Lower an interleaved store (Factor = 3): 12695 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12696 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12697 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12698 /// 12699 /// Into: 12700 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12701 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12702 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12703 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12704 /// 12705 /// Note that the new shufflevectors will be removed and we'll only generate one 12706 /// vst3 instruction in CodeGen. 12707 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12708 ShuffleVectorInst *SVI, 12709 unsigned Factor) const { 12710 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12711 "Invalid interleave factor"); 12712 12713 VectorType *VecTy = SVI->getType(); 12714 assert(VecTy->getVectorNumElements() % Factor == 0 && 12715 "Invalid interleaved store"); 12716 12717 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12718 Type *EltTy = VecTy->getVectorElementType(); 12719 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12720 12721 const DataLayout &DL = SI->getModule()->getDataLayout(); 12722 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12723 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12724 12725 // Skip if we do not have NEON and skip illegal vector types and vector types 12726 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12727 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12728 EltIs64Bits) 12729 return false; 12730 12731 Value *Op0 = SVI->getOperand(0); 12732 Value *Op1 = SVI->getOperand(1); 12733 IRBuilder<> Builder(SI); 12734 12735 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12736 // vectors to integer vectors. 12737 if (EltTy->isPointerTy()) { 12738 Type *IntTy = DL.getIntPtrType(EltTy); 12739 12740 // Convert to the corresponding integer vector. 12741 Type *IntVecTy = 12742 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12743 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12744 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12745 12746 SubVecTy = VectorType::get(IntTy, NumSubElts); 12747 } 12748 12749 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12750 Intrinsic::arm_neon_vst3, 12751 Intrinsic::arm_neon_vst4}; 12752 SmallVector<Value *, 6> Ops; 12753 12754 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12755 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12756 12757 Type *Tys[] = { Int8Ptr, SubVecTy }; 12758 Function *VstNFunc = Intrinsic::getDeclaration( 12759 SI->getModule(), StoreInts[Factor - 2], Tys); 12760 12761 // Split the shufflevector operands into sub vectors for the new vstN call. 12762 for (unsigned i = 0; i < Factor; i++) 12763 Ops.push_back(Builder.CreateShuffleVector( 12764 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12765 12766 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12767 Builder.CreateCall(VstNFunc, Ops); 12768 return true; 12769 } 12770 12771 enum HABaseType { 12772 HA_UNKNOWN = 0, 12773 HA_FLOAT, 12774 HA_DOUBLE, 12775 HA_VECT64, 12776 HA_VECT128 12777 }; 12778 12779 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12780 uint64_t &Members) { 12781 if (auto *ST = dyn_cast<StructType>(Ty)) { 12782 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12783 uint64_t SubMembers = 0; 12784 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12785 return false; 12786 Members += SubMembers; 12787 } 12788 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12789 uint64_t SubMembers = 0; 12790 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12791 return false; 12792 Members += SubMembers * AT->getNumElements(); 12793 } else if (Ty->isFloatTy()) { 12794 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12795 return false; 12796 Members = 1; 12797 Base = HA_FLOAT; 12798 } else if (Ty->isDoubleTy()) { 12799 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12800 return false; 12801 Members = 1; 12802 Base = HA_DOUBLE; 12803 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12804 Members = 1; 12805 switch (Base) { 12806 case HA_FLOAT: 12807 case HA_DOUBLE: 12808 return false; 12809 case HA_VECT64: 12810 return VT->getBitWidth() == 64; 12811 case HA_VECT128: 12812 return VT->getBitWidth() == 128; 12813 case HA_UNKNOWN: 12814 switch (VT->getBitWidth()) { 12815 case 64: 12816 Base = HA_VECT64; 12817 return true; 12818 case 128: 12819 Base = HA_VECT128; 12820 return true; 12821 default: 12822 return false; 12823 } 12824 } 12825 } 12826 12827 return (Members > 0 && Members <= 4); 12828 } 12829 12830 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 12831 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 12832 /// passing according to AAPCS rules. 12833 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 12834 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12835 if (getEffectiveCallingConv(CallConv, isVarArg) != 12836 CallingConv::ARM_AAPCS_VFP) 12837 return false; 12838 12839 HABaseType Base = HA_UNKNOWN; 12840 uint64_t Members = 0; 12841 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 12842 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 12843 12844 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 12845 return IsHA || IsIntArray; 12846 } 12847 12848 unsigned ARMTargetLowering::getExceptionPointerRegister( 12849 const Constant *PersonalityFn) const { 12850 // Platforms which do not use SjLj EH may return values in these registers 12851 // via the personality function. 12852 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 12853 } 12854 12855 unsigned ARMTargetLowering::getExceptionSelectorRegister( 12856 const Constant *PersonalityFn) const { 12857 // Platforms which do not use SjLj EH may return values in these registers 12858 // via the personality function. 12859 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 12860 } 12861 12862 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12863 // Update IsSplitCSR in ARMFunctionInfo. 12864 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 12865 AFI->setIsSplitCSR(true); 12866 } 12867 12868 void ARMTargetLowering::insertCopiesSplitCSR( 12869 MachineBasicBlock *Entry, 12870 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12871 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12872 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12873 if (!IStart) 12874 return; 12875 12876 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 12877 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12878 MachineBasicBlock::iterator MBBI = Entry->begin(); 12879 for (const MCPhysReg *I = IStart; *I; ++I) { 12880 const TargetRegisterClass *RC = nullptr; 12881 if (ARM::GPRRegClass.contains(*I)) 12882 RC = &ARM::GPRRegClass; 12883 else if (ARM::DPRRegClass.contains(*I)) 12884 RC = &ARM::DPRRegClass; 12885 else 12886 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12887 12888 unsigned NewVR = MRI->createVirtualRegister(RC); 12889 // Create copy from CSR to a virtual register. 12890 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12891 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12892 // nounwind. If we want to generalize this later, we may need to emit 12893 // CFI pseudo-instructions. 12894 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12895 Attribute::NoUnwind) && 12896 "Function should be nounwind in insertCopiesSplitCSR!"); 12897 Entry->addLiveIn(*I); 12898 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12899 .addReg(*I); 12900 12901 // Insert the copy-back instructions right before the terminator. 12902 for (auto *Exit : Exits) 12903 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12904 TII->get(TargetOpcode::COPY), *I) 12905 .addReg(NewVR); 12906 } 12907 } 12908