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/CodeGen/CallingConvLower.h" 27 #include "llvm/CodeGen/IntrinsicLowering.h" 28 #include "llvm/CodeGen/MachineBasicBlock.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineFunction.h" 31 #include "llvm/CodeGen/MachineInstrBuilder.h" 32 #include "llvm/CodeGen/MachineJumpTableInfo.h" 33 #include "llvm/CodeGen/MachineModuleInfo.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/SelectionDAG.h" 36 #include "llvm/IR/CallingConv.h" 37 #include "llvm/IR/Constants.h" 38 #include "llvm/IR/Function.h" 39 #include "llvm/IR/GlobalValue.h" 40 #include "llvm/IR/IRBuilder.h" 41 #include "llvm/IR/Instruction.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/Intrinsics.h" 44 #include "llvm/IR/Type.h" 45 #include "llvm/MC/MCSectionMachO.h" 46 #include "llvm/Support/CommandLine.h" 47 #include "llvm/Support/Debug.h" 48 #include "llvm/Support/ErrorHandling.h" 49 #include "llvm/Support/MathExtras.h" 50 #include "llvm/Target/TargetOptions.h" 51 #include <utility> 52 using namespace llvm; 53 54 #define DEBUG_TYPE "arm-isel" 55 56 STATISTIC(NumTailCalls, "Number of tail calls"); 57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 58 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 59 60 cl::opt<bool> 61 EnableARMLongCalls("arm-long-calls", cl::Hidden, 62 cl::desc("Generate calls via indirect call instructions"), 63 cl::init(false)); 64 65 static cl::opt<bool> 66 ARMInterworking("arm-interworking", cl::Hidden, 67 cl::desc("Enable / disable ARM interworking (for debugging only)"), 68 cl::init(true)); 69 70 namespace { 71 class ARMCCState : public CCState { 72 public: 73 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 74 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 75 ParmContext PC) 76 : CCState(CC, isVarArg, MF, locs, C) { 77 assert(((PC == Call) || (PC == Prologue)) && 78 "ARMCCState users must specify whether their context is call" 79 "or prologue generation."); 80 CallOrPrologue = PC; 81 } 82 }; 83 } 84 85 // The APCS parameter registers. 86 static const MCPhysReg GPRArgRegs[] = { 87 ARM::R0, ARM::R1, ARM::R2, ARM::R3 88 }; 89 90 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 91 MVT PromotedBitwiseVT) { 92 if (VT != PromotedLdStVT) { 93 setOperationAction(ISD::LOAD, VT, Promote); 94 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 95 96 setOperationAction(ISD::STORE, VT, Promote); 97 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 98 } 99 100 MVT ElemTy = VT.getVectorElementType(); 101 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 102 setOperationAction(ISD::SETCC, VT, Custom); 103 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 105 if (ElemTy == MVT::i32) { 106 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 107 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 108 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 109 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 110 } else { 111 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 112 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 113 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 114 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 115 } 116 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 117 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 118 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 119 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 120 setOperationAction(ISD::SELECT, VT, Expand); 121 setOperationAction(ISD::SELECT_CC, VT, Expand); 122 setOperationAction(ISD::VSELECT, VT, Expand); 123 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 124 if (VT.isInteger()) { 125 setOperationAction(ISD::SHL, VT, Custom); 126 setOperationAction(ISD::SRA, VT, Custom); 127 setOperationAction(ISD::SRL, VT, Custom); 128 } 129 130 // Promote all bit-wise operations. 131 if (VT.isInteger() && VT != PromotedBitwiseVT) { 132 setOperationAction(ISD::AND, VT, Promote); 133 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 134 setOperationAction(ISD::OR, VT, Promote); 135 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 136 setOperationAction(ISD::XOR, VT, Promote); 137 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 138 } 139 140 // Neon does not support vector divide/remainder operations. 141 setOperationAction(ISD::SDIV, VT, Expand); 142 setOperationAction(ISD::UDIV, VT, Expand); 143 setOperationAction(ISD::FDIV, VT, Expand); 144 setOperationAction(ISD::SREM, VT, Expand); 145 setOperationAction(ISD::UREM, VT, Expand); 146 setOperationAction(ISD::FREM, VT, Expand); 147 } 148 149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 150 addRegisterClass(VT, &ARM::DPRRegClass); 151 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 152 } 153 154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 155 addRegisterClass(VT, &ARM::DPairRegClass); 156 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 157 } 158 159 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 160 const ARMSubtarget &STI) 161 : TargetLowering(TM), Subtarget(&STI) { 162 RegInfo = Subtarget->getRegisterInfo(); 163 Itins = Subtarget->getInstrItineraryData(); 164 165 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 166 167 if (Subtarget->isTargetMachO()) { 168 // Uses VFP for Thumb libfuncs if available. 169 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 170 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) { 171 // Single-precision floating-point arithmetic. 172 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp"); 173 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp"); 174 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp"); 175 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp"); 176 177 // Double-precision floating-point arithmetic. 178 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp"); 179 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp"); 180 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp"); 181 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp"); 182 183 // Single-precision comparisons. 184 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp"); 185 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp"); 186 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp"); 187 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp"); 188 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp"); 189 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp"); 190 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp"); 191 setLibcallName(RTLIB::O_F32, "__unordsf2vfp"); 192 193 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE); 194 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE); 195 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE); 196 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE); 197 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE); 198 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE); 199 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE); 200 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ); 201 202 // Double-precision comparisons. 203 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp"); 204 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp"); 205 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp"); 206 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp"); 207 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp"); 208 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp"); 209 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp"); 210 setLibcallName(RTLIB::O_F64, "__unorddf2vfp"); 211 212 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE); 213 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE); 214 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE); 215 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE); 216 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE); 217 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE); 218 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE); 219 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ); 220 221 // Floating-point to integer conversions. 222 // i64 conversions are done via library routines even when generating VFP 223 // instructions, so use the same ones. 224 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp"); 225 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp"); 226 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp"); 227 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp"); 228 229 // Conversions between floating types. 230 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp"); 231 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp"); 232 233 // Integer to floating-point conversions. 234 // i64 conversions are done via library routines even when generating VFP 235 // instructions, so use the same ones. 236 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 237 // e.g., __floatunsidf vs. __floatunssidfvfp. 238 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp"); 239 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp"); 240 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp"); 241 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp"); 242 } 243 } 244 245 // These libcalls are not available in 32-bit. 246 setLibcallName(RTLIB::SHL_I128, nullptr); 247 setLibcallName(RTLIB::SRL_I128, nullptr); 248 setLibcallName(RTLIB::SRA_I128, nullptr); 249 250 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() && 251 !Subtarget->isTargetWindows()) { 252 static const struct { 253 const RTLIB::Libcall Op; 254 const char * const Name; 255 const CallingConv::ID CC; 256 const ISD::CondCode Cond; 257 } LibraryCalls[] = { 258 // Double-precision floating-point arithmetic helper functions 259 // RTABI chapter 4.1.2, Table 2 260 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 261 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 262 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 263 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 264 265 // Double-precision floating-point comparison helper functions 266 // RTABI chapter 4.1.2, Table 3 267 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 268 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 269 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 270 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 271 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 272 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 273 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 274 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 275 276 // Single-precision floating-point arithmetic helper functions 277 // RTABI chapter 4.1.2, Table 4 278 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 279 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 280 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 281 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 282 283 // Single-precision floating-point comparison helper functions 284 // RTABI chapter 4.1.2, Table 5 285 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 286 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 287 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 288 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 289 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 290 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 291 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 292 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 293 294 // Floating-point to integer conversions. 295 // RTABI chapter 4.1.2, Table 6 296 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 297 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 298 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 299 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 300 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 301 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 302 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 303 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 304 305 // Conversions between floating types. 306 // RTABI chapter 4.1.2, Table 7 307 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 308 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 309 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 310 311 // Integer to floating-point conversions. 312 // RTABI chapter 4.1.2, Table 8 313 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 314 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 315 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 316 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 317 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 318 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 319 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 320 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 322 // Long long helper functions 323 // RTABI chapter 4.2, Table 9 324 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 325 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 326 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 327 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 328 329 // Integer division functions 330 // RTABI chapter 4.3.1 331 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 335 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 336 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 337 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 340 // Memory operations 341 // RTABI chapter 4.3.4 342 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 { RTLIB::MEMSET, "__aeabi_memset", 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 355 if (Subtarget->isTargetWindows()) { 356 static const struct { 357 const RTLIB::Libcall Op; 358 const char * const Name; 359 const CallingConv::ID CC; 360 } LibraryCalls[] = { 361 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 362 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 363 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 364 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 365 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 366 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 367 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 368 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 369 }; 370 371 for (const auto &LC : LibraryCalls) { 372 setLibcallName(LC.Op, LC.Name); 373 setLibcallCallingConv(LC.Op, LC.CC); 374 } 375 } 376 377 // Use divmod compiler-rt calls for iOS 5.0 and later. 378 if (Subtarget->getTargetTriple().isiOS() && 379 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) { 380 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 381 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 382 } 383 384 // The half <-> float conversion functions are always soft-float, but are 385 // needed for some targets which use a hard-float calling convention by 386 // default. 387 if (Subtarget->isAAPCS_ABI()) { 388 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 389 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 390 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 391 } else { 392 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 393 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 394 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 395 } 396 397 if (Subtarget->isThumb1Only()) 398 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 399 else 400 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 401 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() && 402 !Subtarget->isThumb1Only()) { 403 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 404 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 405 } 406 407 for (MVT VT : MVT::vector_valuetypes()) { 408 for (MVT InnerVT : MVT::vector_valuetypes()) { 409 setTruncStoreAction(VT, InnerVT, Expand); 410 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 411 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 412 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 413 } 414 415 setOperationAction(ISD::MULHS, VT, Expand); 416 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 417 setOperationAction(ISD::MULHU, VT, Expand); 418 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 419 420 setOperationAction(ISD::BSWAP, VT, Expand); 421 } 422 423 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 424 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 425 426 if (Subtarget->hasNEON()) { 427 addDRTypeForNEON(MVT::v2f32); 428 addDRTypeForNEON(MVT::v8i8); 429 addDRTypeForNEON(MVT::v4i16); 430 addDRTypeForNEON(MVT::v2i32); 431 addDRTypeForNEON(MVT::v1i64); 432 433 addQRTypeForNEON(MVT::v4f32); 434 addQRTypeForNEON(MVT::v2f64); 435 addQRTypeForNEON(MVT::v16i8); 436 addQRTypeForNEON(MVT::v8i16); 437 addQRTypeForNEON(MVT::v4i32); 438 addQRTypeForNEON(MVT::v2i64); 439 440 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 441 // neither Neon nor VFP support any arithmetic operations on it. 442 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 443 // supported for v4f32. 444 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 445 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 446 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 447 // FIXME: Code duplication: FDIV and FREM are expanded always, see 448 // ARMTargetLowering::addTypeForNEON method for details. 449 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 450 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 451 // FIXME: Create unittest. 452 // In another words, find a way when "copysign" appears in DAG with vector 453 // operands. 454 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 455 // FIXME: Code duplication: SETCC has custom operation action, see 456 // ARMTargetLowering::addTypeForNEON method for details. 457 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 458 // FIXME: Create unittest for FNEG and for FABS. 459 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 460 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 461 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 462 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 463 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 464 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 465 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 466 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 467 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 468 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 469 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 470 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 471 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 472 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 473 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 474 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 475 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 476 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 477 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 478 479 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 480 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 481 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 482 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 483 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 484 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 485 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 486 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 487 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 488 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 489 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 490 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 491 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 492 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 493 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 494 495 // Mark v2f32 intrinsics. 496 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 497 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 498 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 499 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 500 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 501 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 502 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 503 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 504 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 505 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 506 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 507 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 508 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 509 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 510 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 511 512 // Neon does not support some operations on v1i64 and v2i64 types. 513 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 514 // Custom handling for some quad-vector types to detect VMULL. 515 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 516 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 517 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 518 // Custom handling for some vector types to avoid expensive expansions 519 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 520 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 521 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 522 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 523 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 524 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 525 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 526 // a destination type that is wider than the source, and nor does 527 // it have a FP_TO_[SU]INT instruction with a narrower destination than 528 // source. 529 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 530 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 531 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 532 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 533 534 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 535 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 536 537 // NEON does not have single instruction CTPOP for vectors with element 538 // types wider than 8-bits. However, custom lowering can leverage the 539 // v8i8/v16i8 vcnt instruction. 540 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 541 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 542 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 543 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 544 545 // NEON only has FMA instructions as of VFP4. 546 if (!Subtarget->hasVFP4()) { 547 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 548 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 549 } 550 551 setTargetDAGCombine(ISD::INTRINSIC_VOID); 552 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 553 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 554 setTargetDAGCombine(ISD::SHL); 555 setTargetDAGCombine(ISD::SRL); 556 setTargetDAGCombine(ISD::SRA); 557 setTargetDAGCombine(ISD::SIGN_EXTEND); 558 setTargetDAGCombine(ISD::ZERO_EXTEND); 559 setTargetDAGCombine(ISD::ANY_EXTEND); 560 setTargetDAGCombine(ISD::SELECT_CC); 561 setTargetDAGCombine(ISD::BUILD_VECTOR); 562 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 563 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 564 setTargetDAGCombine(ISD::STORE); 565 setTargetDAGCombine(ISD::FP_TO_SINT); 566 setTargetDAGCombine(ISD::FP_TO_UINT); 567 setTargetDAGCombine(ISD::FDIV); 568 setTargetDAGCombine(ISD::LOAD); 569 570 // It is legal to extload from v4i8 to v4i16 or v4i32. 571 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8, 572 MVT::v4i16, MVT::v2i16, 573 MVT::v2i32}; 574 for (unsigned i = 0; i < 6; ++i) { 575 for (MVT VT : MVT::integer_vector_valuetypes()) { 576 setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal); 577 setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal); 578 setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], Legal); 579 } 580 } 581 } 582 583 // ARM and Thumb2 support UMLAL/SMLAL. 584 if (!Subtarget->isThumb1Only()) 585 setTargetDAGCombine(ISD::ADDC); 586 587 if (Subtarget->isFPOnlySP()) { 588 // When targetting a floating-point unit with only single-precision 589 // operations, f64 is legal for the few double-precision instructions which 590 // are present However, no double-precision operations other than moves, 591 // loads and stores are provided by the hardware. 592 setOperationAction(ISD::FADD, MVT::f64, Expand); 593 setOperationAction(ISD::FSUB, MVT::f64, Expand); 594 setOperationAction(ISD::FMUL, MVT::f64, Expand); 595 setOperationAction(ISD::FMA, MVT::f64, Expand); 596 setOperationAction(ISD::FDIV, MVT::f64, Expand); 597 setOperationAction(ISD::FREM, MVT::f64, Expand); 598 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 599 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 600 setOperationAction(ISD::FNEG, MVT::f64, Expand); 601 setOperationAction(ISD::FABS, MVT::f64, Expand); 602 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 603 setOperationAction(ISD::FSIN, MVT::f64, Expand); 604 setOperationAction(ISD::FCOS, MVT::f64, Expand); 605 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 606 setOperationAction(ISD::FPOW, MVT::f64, Expand); 607 setOperationAction(ISD::FLOG, MVT::f64, Expand); 608 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 609 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 610 setOperationAction(ISD::FEXP, MVT::f64, Expand); 611 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 612 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 613 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 614 setOperationAction(ISD::FRINT, MVT::f64, Expand); 615 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 616 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 617 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 618 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 619 } 620 621 computeRegisterProperties(); 622 623 // ARM does not have floating-point extending loads. 624 for (MVT VT : MVT::fp_valuetypes()) { 625 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 626 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 627 } 628 629 // ... or truncating stores 630 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 631 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 632 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 633 634 // ARM does not have i1 sign extending load. 635 for (MVT VT : MVT::integer_valuetypes()) 636 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 637 638 // ARM supports all 4 flavors of integer indexed load / store. 639 if (!Subtarget->isThumb1Only()) { 640 for (unsigned im = (unsigned)ISD::PRE_INC; 641 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 642 setIndexedLoadAction(im, MVT::i1, Legal); 643 setIndexedLoadAction(im, MVT::i8, Legal); 644 setIndexedLoadAction(im, MVT::i16, Legal); 645 setIndexedLoadAction(im, MVT::i32, Legal); 646 setIndexedStoreAction(im, MVT::i1, Legal); 647 setIndexedStoreAction(im, MVT::i8, Legal); 648 setIndexedStoreAction(im, MVT::i16, Legal); 649 setIndexedStoreAction(im, MVT::i32, Legal); 650 } 651 } 652 653 setOperationAction(ISD::SADDO, MVT::i32, Custom); 654 setOperationAction(ISD::UADDO, MVT::i32, Custom); 655 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 656 setOperationAction(ISD::USUBO, MVT::i32, Custom); 657 658 // i64 operation support. 659 setOperationAction(ISD::MUL, MVT::i64, Expand); 660 setOperationAction(ISD::MULHU, MVT::i32, Expand); 661 if (Subtarget->isThumb1Only()) { 662 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 663 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 664 } 665 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 666 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP())) 667 setOperationAction(ISD::MULHS, MVT::i32, Expand); 668 669 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 670 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 671 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 672 setOperationAction(ISD::SRL, MVT::i64, Custom); 673 setOperationAction(ISD::SRA, MVT::i64, Custom); 674 675 if (!Subtarget->isThumb1Only()) { 676 // FIXME: We should do this for Thumb1 as well. 677 setOperationAction(ISD::ADDC, MVT::i32, Custom); 678 setOperationAction(ISD::ADDE, MVT::i32, Custom); 679 setOperationAction(ISD::SUBC, MVT::i32, Custom); 680 setOperationAction(ISD::SUBE, MVT::i32, Custom); 681 } 682 683 // ARM does not have ROTL. 684 setOperationAction(ISD::ROTL, MVT::i32, Expand); 685 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 686 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 687 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 688 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 689 690 // These just redirect to CTTZ and CTLZ on ARM. 691 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand); 692 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand); 693 694 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 695 696 // Only ARMv6 has BSWAP. 697 if (!Subtarget->hasV6Ops()) 698 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 699 700 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) && 701 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) { 702 // These are expanded into libcalls if the cpu doesn't have HW divider. 703 setOperationAction(ISD::SDIV, MVT::i32, Expand); 704 setOperationAction(ISD::UDIV, MVT::i32, Expand); 705 } 706 707 // FIXME: Also set divmod for SREM on EABI 708 setOperationAction(ISD::SREM, MVT::i32, Expand); 709 setOperationAction(ISD::UREM, MVT::i32, Expand); 710 // Register based DivRem for AEABI (RTABI 4.2) 711 if (Subtarget->isTargetAEABI()) { 712 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 713 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 714 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 715 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 716 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 717 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 718 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 719 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 720 721 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 722 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 723 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 724 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 725 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 726 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 727 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 728 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 729 730 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 731 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 732 } else { 733 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 734 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 735 } 736 737 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 738 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 739 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom); 740 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 741 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 742 743 setOperationAction(ISD::TRAP, MVT::Other, Legal); 744 745 // Use the default implementation. 746 setOperationAction(ISD::VASTART, MVT::Other, Custom); 747 setOperationAction(ISD::VAARG, MVT::Other, Expand); 748 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 749 setOperationAction(ISD::VAEND, MVT::Other, Expand); 750 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 751 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 752 753 if (!Subtarget->isTargetMachO()) { 754 // Non-MachO platforms may return values in these registers via the 755 // personality function. 756 setExceptionPointerRegister(ARM::R0); 757 setExceptionSelectorRegister(ARM::R1); 758 } 759 760 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 761 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 762 else 763 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 764 765 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 766 // the default expansion. If we are targeting a single threaded system, 767 // then set them all for expand so we can lower them later into their 768 // non-atomic form. 769 if (TM.Options.ThreadModel == ThreadModel::Single) 770 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand); 771 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) { 772 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 773 // to ldrex/strex loops already. 774 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 775 776 // On v8, we have particularly efficient implementations of atomic fences 777 // if they can be combined with nearby atomic loads and stores. 778 if (!Subtarget->hasV8Ops()) { 779 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 780 setInsertFencesForAtomic(true); 781 } 782 } else { 783 // If there's anything we can use as a barrier, go through custom lowering 784 // for ATOMIC_FENCE. 785 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 786 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 787 788 // Set them all for expansion, which will force libcalls. 789 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 790 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 791 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 792 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 793 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 794 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 795 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 796 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 797 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 798 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 799 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 800 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 801 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 802 // Unordered/Monotonic case. 803 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 804 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 805 } 806 807 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 808 809 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 810 if (!Subtarget->hasV6Ops()) { 811 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 812 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 813 } 814 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 815 816 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() && 817 !Subtarget->isThumb1Only()) { 818 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 819 // iff target supports vfp2. 820 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 821 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 822 } 823 824 // We want to custom lower some of our intrinsics. 825 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 826 if (Subtarget->isTargetDarwin()) { 827 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 828 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 829 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 830 } 831 832 setOperationAction(ISD::SETCC, MVT::i32, Expand); 833 setOperationAction(ISD::SETCC, MVT::f32, Expand); 834 setOperationAction(ISD::SETCC, MVT::f64, Expand); 835 setOperationAction(ISD::SELECT, MVT::i32, Custom); 836 setOperationAction(ISD::SELECT, MVT::f32, Custom); 837 setOperationAction(ISD::SELECT, MVT::f64, Custom); 838 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 839 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 840 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 841 842 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 843 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 844 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 845 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 846 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 847 848 // We don't support sin/cos/fmod/copysign/pow 849 setOperationAction(ISD::FSIN, MVT::f64, Expand); 850 setOperationAction(ISD::FSIN, MVT::f32, Expand); 851 setOperationAction(ISD::FCOS, MVT::f32, Expand); 852 setOperationAction(ISD::FCOS, MVT::f64, Expand); 853 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 854 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 855 setOperationAction(ISD::FREM, MVT::f64, Expand); 856 setOperationAction(ISD::FREM, MVT::f32, Expand); 857 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() && 858 !Subtarget->isThumb1Only()) { 859 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 860 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 861 } 862 setOperationAction(ISD::FPOW, MVT::f64, Expand); 863 setOperationAction(ISD::FPOW, MVT::f32, Expand); 864 865 if (!Subtarget->hasVFP4()) { 866 setOperationAction(ISD::FMA, MVT::f64, Expand); 867 setOperationAction(ISD::FMA, MVT::f32, Expand); 868 } 869 870 // Various VFP goodness 871 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) { 872 // int <-> fp are custom expanded into bit_convert + ARMISD ops. 873 if (Subtarget->hasVFP2()) { 874 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 875 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 876 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 877 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 878 } 879 880 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 881 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 882 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 883 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 884 } 885 886 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 887 if (!Subtarget->hasFP16()) { 888 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 889 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 890 } 891 } 892 893 // Combine sin / cos into one node or libcall if possible. 894 if (Subtarget->hasSinCos()) { 895 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 896 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 897 if (Subtarget->getTargetTriple().isiOS()) { 898 // For iOS, we don't want to the normal expansion of a libcall to 899 // sincos. We want to issue a libcall to __sincos_stret. 900 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 901 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 902 } 903 } 904 905 // FP-ARMv8 implements a lot of rounding-like FP operations. 906 if (Subtarget->hasFPARMv8()) { 907 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 908 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 909 setOperationAction(ISD::FROUND, MVT::f32, Legal); 910 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 911 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 912 setOperationAction(ISD::FRINT, MVT::f32, Legal); 913 if (!Subtarget->isFPOnlySP()) { 914 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 915 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 916 setOperationAction(ISD::FROUND, MVT::f64, Legal); 917 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 918 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 919 setOperationAction(ISD::FRINT, MVT::f64, Legal); 920 } 921 } 922 // We have target-specific dag combine patterns for the following nodes: 923 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 924 setTargetDAGCombine(ISD::ADD); 925 setTargetDAGCombine(ISD::SUB); 926 setTargetDAGCombine(ISD::MUL); 927 setTargetDAGCombine(ISD::AND); 928 setTargetDAGCombine(ISD::OR); 929 setTargetDAGCombine(ISD::XOR); 930 931 if (Subtarget->hasV6Ops()) 932 setTargetDAGCombine(ISD::SRL); 933 934 setStackPointerRegisterToSaveRestore(ARM::SP); 935 936 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() || 937 !Subtarget->hasVFP2()) 938 setSchedulingPreference(Sched::RegPressure); 939 else 940 setSchedulingPreference(Sched::Hybrid); 941 942 //// temporary - rewrite interface to use type 943 MaxStoresPerMemset = 8; 944 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 945 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 946 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2; 947 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 948 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2; 949 950 // On ARM arguments smaller than 4 bytes are extended, so all arguments 951 // are at least 4 bytes aligned. 952 setMinStackArgumentAlignment(4); 953 954 // Prefer likely predicted branches to selects on out-of-order cores. 955 PredictableSelectIsExpensive = Subtarget->isLikeA9(); 956 957 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 958 } 959 960 // FIXME: It might make sense to define the representative register class as the 961 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 962 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 963 // SPR's representative would be DPR_VFP2. This should work well if register 964 // pressure tracking were modified such that a register use would increment the 965 // pressure of the register class's representative and all of it's super 966 // classes' representatives transitively. We have not implemented this because 967 // of the difficulty prior to coalescing of modeling operand register classes 968 // due to the common occurrence of cross class copies and subregister insertions 969 // and extractions. 970 std::pair<const TargetRegisterClass*, uint8_t> 971 ARMTargetLowering::findRepresentativeClass(MVT VT) const{ 972 const TargetRegisterClass *RRC = nullptr; 973 uint8_t Cost = 1; 974 switch (VT.SimpleTy) { 975 default: 976 return TargetLowering::findRepresentativeClass(VT); 977 // Use DPR as representative register class for all floating point 978 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 979 // the cost is 1 for both f32 and f64. 980 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 981 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 982 RRC = &ARM::DPRRegClass; 983 // When NEON is used for SP, only half of the register file is available 984 // because operations that define both SP and DP results will be constrained 985 // to the VFP2 class (D0-D15). We currently model this constraint prior to 986 // coalescing by double-counting the SP regs. See the FIXME above. 987 if (Subtarget->useNEONForSinglePrecisionFP()) 988 Cost = 2; 989 break; 990 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 991 case MVT::v4f32: case MVT::v2f64: 992 RRC = &ARM::DPRRegClass; 993 Cost = 2; 994 break; 995 case MVT::v4i64: 996 RRC = &ARM::DPRRegClass; 997 Cost = 4; 998 break; 999 case MVT::v8i64: 1000 RRC = &ARM::DPRRegClass; 1001 Cost = 8; 1002 break; 1003 } 1004 return std::make_pair(RRC, Cost); 1005 } 1006 1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1008 switch (Opcode) { 1009 default: return nullptr; 1010 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1011 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1012 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1013 case ARMISD::CALL: return "ARMISD::CALL"; 1014 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1015 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1016 case ARMISD::tCALL: return "ARMISD::tCALL"; 1017 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1018 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1019 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1020 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1021 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1022 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1023 case ARMISD::CMP: return "ARMISD::CMP"; 1024 case ARMISD::CMN: return "ARMISD::CMN"; 1025 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1026 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1027 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1028 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1029 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1030 1031 case ARMISD::CMOV: return "ARMISD::CMOV"; 1032 1033 case ARMISD::RBIT: return "ARMISD::RBIT"; 1034 1035 case ARMISD::FTOSI: return "ARMISD::FTOSI"; 1036 case ARMISD::FTOUI: return "ARMISD::FTOUI"; 1037 case ARMISD::SITOF: return "ARMISD::SITOF"; 1038 case ARMISD::UITOF: return "ARMISD::UITOF"; 1039 1040 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1041 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1042 case ARMISD::RRX: return "ARMISD::RRX"; 1043 1044 case ARMISD::ADDC: return "ARMISD::ADDC"; 1045 case ARMISD::ADDE: return "ARMISD::ADDE"; 1046 case ARMISD::SUBC: return "ARMISD::SUBC"; 1047 case ARMISD::SUBE: return "ARMISD::SUBE"; 1048 1049 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1050 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1051 1052 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1053 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP"; 1054 1055 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1056 1057 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1058 1059 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1060 1061 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1062 1063 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1064 1065 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1066 1067 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1068 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1069 case ARMISD::VCGE: return "ARMISD::VCGE"; 1070 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1071 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1072 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1073 case ARMISD::VCGT: return "ARMISD::VCGT"; 1074 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1075 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1076 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1077 case ARMISD::VTST: return "ARMISD::VTST"; 1078 1079 case ARMISD::VSHL: return "ARMISD::VSHL"; 1080 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1081 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1082 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1083 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1084 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1085 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1086 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1087 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1088 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1089 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1090 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1091 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1092 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1093 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1094 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1095 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1096 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1097 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1098 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1099 case ARMISD::VDUP: return "ARMISD::VDUP"; 1100 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1101 case ARMISD::VEXT: return "ARMISD::VEXT"; 1102 case ARMISD::VREV64: return "ARMISD::VREV64"; 1103 case ARMISD::VREV32: return "ARMISD::VREV32"; 1104 case ARMISD::VREV16: return "ARMISD::VREV16"; 1105 case ARMISD::VZIP: return "ARMISD::VZIP"; 1106 case ARMISD::VUZP: return "ARMISD::VUZP"; 1107 case ARMISD::VTRN: return "ARMISD::VTRN"; 1108 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1109 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1110 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1111 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1112 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1113 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1114 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1115 case ARMISD::FMAX: return "ARMISD::FMAX"; 1116 case ARMISD::FMIN: return "ARMISD::FMIN"; 1117 case ARMISD::VMAXNM: return "ARMISD::VMAX"; 1118 case ARMISD::VMINNM: return "ARMISD::VMIN"; 1119 case ARMISD::BFI: return "ARMISD::BFI"; 1120 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1121 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1122 case ARMISD::VBSL: return "ARMISD::VBSL"; 1123 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1124 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1125 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1126 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1127 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1128 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1129 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1130 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1131 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1132 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1133 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1134 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1135 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1136 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1137 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1138 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1139 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1140 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1141 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1142 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1143 } 1144 } 1145 1146 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const { 1147 if (!VT.isVector()) return getPointerTy(); 1148 return VT.changeVectorElementTypeToInteger(); 1149 } 1150 1151 /// getRegClassFor - Return the register class that should be used for the 1152 /// specified value type. 1153 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1154 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1155 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1156 // load / store 4 to 8 consecutive D registers. 1157 if (Subtarget->hasNEON()) { 1158 if (VT == MVT::v4i64) 1159 return &ARM::QQPRRegClass; 1160 if (VT == MVT::v8i64) 1161 return &ARM::QQQQPRRegClass; 1162 } 1163 return TargetLowering::getRegClassFor(VT); 1164 } 1165 1166 // Create a fast isel object. 1167 FastISel * 1168 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1169 const TargetLibraryInfo *libInfo) const { 1170 return ARM::createFastISel(funcInfo, libInfo); 1171 } 1172 1173 /// getMaximalGlobalOffset - Returns the maximal possible offset which can 1174 /// be used for loads / stores from the global. 1175 unsigned ARMTargetLowering::getMaximalGlobalOffset() const { 1176 return (Subtarget->isThumb1Only() ? 127 : 4095); 1177 } 1178 1179 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1180 unsigned NumVals = N->getNumValues(); 1181 if (!NumVals) 1182 return Sched::RegPressure; 1183 1184 for (unsigned i = 0; i != NumVals; ++i) { 1185 EVT VT = N->getValueType(i); 1186 if (VT == MVT::Glue || VT == MVT::Other) 1187 continue; 1188 if (VT.isFloatingPoint() || VT.isVector()) 1189 return Sched::ILP; 1190 } 1191 1192 if (!N->isMachineOpcode()) 1193 return Sched::RegPressure; 1194 1195 // Load are scheduled for latency even if there instruction itinerary 1196 // is not available. 1197 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1198 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1199 1200 if (MCID.getNumDefs() == 0) 1201 return Sched::RegPressure; 1202 if (!Itins->isEmpty() && 1203 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1204 return Sched::ILP; 1205 1206 return Sched::RegPressure; 1207 } 1208 1209 //===----------------------------------------------------------------------===// 1210 // Lowering Code 1211 //===----------------------------------------------------------------------===// 1212 1213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1215 switch (CC) { 1216 default: llvm_unreachable("Unknown condition code!"); 1217 case ISD::SETNE: return ARMCC::NE; 1218 case ISD::SETEQ: return ARMCC::EQ; 1219 case ISD::SETGT: return ARMCC::GT; 1220 case ISD::SETGE: return ARMCC::GE; 1221 case ISD::SETLT: return ARMCC::LT; 1222 case ISD::SETLE: return ARMCC::LE; 1223 case ISD::SETUGT: return ARMCC::HI; 1224 case ISD::SETUGE: return ARMCC::HS; 1225 case ISD::SETULT: return ARMCC::LO; 1226 case ISD::SETULE: return ARMCC::LS; 1227 } 1228 } 1229 1230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1232 ARMCC::CondCodes &CondCode2) { 1233 CondCode2 = ARMCC::AL; 1234 switch (CC) { 1235 default: llvm_unreachable("Unknown FP condition!"); 1236 case ISD::SETEQ: 1237 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1238 case ISD::SETGT: 1239 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1240 case ISD::SETGE: 1241 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1242 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1243 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1244 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1245 case ISD::SETO: CondCode = ARMCC::VC; break; 1246 case ISD::SETUO: CondCode = ARMCC::VS; break; 1247 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1248 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1249 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1250 case ISD::SETLT: 1251 case ISD::SETULT: CondCode = ARMCC::LT; break; 1252 case ISD::SETLE: 1253 case ISD::SETULE: CondCode = ARMCC::LE; break; 1254 case ISD::SETNE: 1255 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1256 } 1257 } 1258 1259 //===----------------------------------------------------------------------===// 1260 // Calling Convention Implementation 1261 //===----------------------------------------------------------------------===// 1262 1263 #include "ARMGenCallingConv.inc" 1264 1265 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1266 /// account presence of floating point hardware and calling convention 1267 /// limitations, such as support for variadic functions. 1268 CallingConv::ID 1269 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1270 bool isVarArg) const { 1271 switch (CC) { 1272 default: 1273 llvm_unreachable("Unsupported calling convention"); 1274 case CallingConv::ARM_AAPCS: 1275 case CallingConv::ARM_APCS: 1276 case CallingConv::GHC: 1277 return CC; 1278 case CallingConv::ARM_AAPCS_VFP: 1279 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1280 case CallingConv::C: 1281 if (!Subtarget->isAAPCS_ABI()) 1282 return CallingConv::ARM_APCS; 1283 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1284 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1285 !isVarArg) 1286 return CallingConv::ARM_AAPCS_VFP; 1287 else 1288 return CallingConv::ARM_AAPCS; 1289 case CallingConv::Fast: 1290 if (!Subtarget->isAAPCS_ABI()) { 1291 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1292 return CallingConv::Fast; 1293 return CallingConv::ARM_APCS; 1294 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1295 return CallingConv::ARM_AAPCS_VFP; 1296 else 1297 return CallingConv::ARM_AAPCS; 1298 } 1299 } 1300 1301 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1302 /// CallingConvention. 1303 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1304 bool Return, 1305 bool isVarArg) const { 1306 switch (getEffectiveCallingConv(CC, isVarArg)) { 1307 default: 1308 llvm_unreachable("Unsupported calling convention"); 1309 case CallingConv::ARM_APCS: 1310 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1311 case CallingConv::ARM_AAPCS: 1312 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1313 case CallingConv::ARM_AAPCS_VFP: 1314 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1315 case CallingConv::Fast: 1316 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1317 case CallingConv::GHC: 1318 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1319 } 1320 } 1321 1322 /// LowerCallResult - Lower the result values of a call into the 1323 /// appropriate copies out of appropriate physical registers. 1324 SDValue 1325 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1326 CallingConv::ID CallConv, bool isVarArg, 1327 const SmallVectorImpl<ISD::InputArg> &Ins, 1328 SDLoc dl, SelectionDAG &DAG, 1329 SmallVectorImpl<SDValue> &InVals, 1330 bool isThisReturn, SDValue ThisVal) const { 1331 1332 // Assign locations to each value returned by this call. 1333 SmallVector<CCValAssign, 16> RVLocs; 1334 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1335 *DAG.getContext(), Call); 1336 CCInfo.AnalyzeCallResult(Ins, 1337 CCAssignFnForNode(CallConv, /* Return*/ true, 1338 isVarArg)); 1339 1340 // Copy all of the result registers out of their specified physreg. 1341 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1342 CCValAssign VA = RVLocs[i]; 1343 1344 // Pass 'this' value directly from the argument to return value, to avoid 1345 // reg unit interference 1346 if (i == 0 && isThisReturn) { 1347 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1348 "unexpected return calling convention register assignment"); 1349 InVals.push_back(ThisVal); 1350 continue; 1351 } 1352 1353 SDValue Val; 1354 if (VA.needsCustom()) { 1355 // Handle f64 or half of a v2f64. 1356 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1357 InFlag); 1358 Chain = Lo.getValue(1); 1359 InFlag = Lo.getValue(2); 1360 VA = RVLocs[++i]; // skip ahead to next loc 1361 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1362 InFlag); 1363 Chain = Hi.getValue(1); 1364 InFlag = Hi.getValue(2); 1365 if (!Subtarget->isLittle()) 1366 std::swap (Lo, Hi); 1367 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1368 1369 if (VA.getLocVT() == MVT::v2f64) { 1370 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1371 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1372 DAG.getConstant(0, MVT::i32)); 1373 1374 VA = RVLocs[++i]; // skip ahead to next loc 1375 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1376 Chain = Lo.getValue(1); 1377 InFlag = Lo.getValue(2); 1378 VA = RVLocs[++i]; // skip ahead to next loc 1379 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1380 Chain = Hi.getValue(1); 1381 InFlag = Hi.getValue(2); 1382 if (!Subtarget->isLittle()) 1383 std::swap (Lo, Hi); 1384 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1385 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1386 DAG.getConstant(1, MVT::i32)); 1387 } 1388 } else { 1389 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1390 InFlag); 1391 Chain = Val.getValue(1); 1392 InFlag = Val.getValue(2); 1393 } 1394 1395 switch (VA.getLocInfo()) { 1396 default: llvm_unreachable("Unknown loc info!"); 1397 case CCValAssign::Full: break; 1398 case CCValAssign::BCvt: 1399 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1400 break; 1401 } 1402 1403 InVals.push_back(Val); 1404 } 1405 1406 return Chain; 1407 } 1408 1409 /// LowerMemOpCallTo - Store the argument to the stack. 1410 SDValue 1411 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1412 SDValue StackPtr, SDValue Arg, 1413 SDLoc dl, SelectionDAG &DAG, 1414 const CCValAssign &VA, 1415 ISD::ArgFlagsTy Flags) const { 1416 unsigned LocMemOffset = VA.getLocMemOffset(); 1417 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 1418 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 1419 return DAG.getStore(Chain, dl, Arg, PtrOff, 1420 MachinePointerInfo::getStack(LocMemOffset), 1421 false, false, 0); 1422 } 1423 1424 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1425 SDValue Chain, SDValue &Arg, 1426 RegsToPassVector &RegsToPass, 1427 CCValAssign &VA, CCValAssign &NextVA, 1428 SDValue &StackPtr, 1429 SmallVectorImpl<SDValue> &MemOpChains, 1430 ISD::ArgFlagsTy Flags) const { 1431 1432 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1433 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1434 unsigned id = Subtarget->isLittle() ? 0 : 1; 1435 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1436 1437 if (NextVA.isRegLoc()) 1438 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1439 else { 1440 assert(NextVA.isMemLoc()); 1441 if (!StackPtr.getNode()) 1442 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy()); 1443 1444 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1445 dl, DAG, NextVA, 1446 Flags)); 1447 } 1448 } 1449 1450 /// LowerCall - Lowering a call into a callseq_start <- 1451 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1452 /// nodes. 1453 SDValue 1454 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1455 SmallVectorImpl<SDValue> &InVals) const { 1456 SelectionDAG &DAG = CLI.DAG; 1457 SDLoc &dl = CLI.DL; 1458 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1459 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1460 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1461 SDValue Chain = CLI.Chain; 1462 SDValue Callee = CLI.Callee; 1463 bool &isTailCall = CLI.IsTailCall; 1464 CallingConv::ID CallConv = CLI.CallConv; 1465 bool doesNotRet = CLI.DoesNotReturn; 1466 bool isVarArg = CLI.IsVarArg; 1467 1468 MachineFunction &MF = DAG.getMachineFunction(); 1469 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1470 bool isThisReturn = false; 1471 bool isSibCall = false; 1472 1473 // Disable tail calls if they're not supported. 1474 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls) 1475 isTailCall = false; 1476 1477 if (isTailCall) { 1478 // Check if it's really possible to do a tail call. 1479 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1480 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1481 Outs, OutVals, Ins, DAG); 1482 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1483 report_fatal_error("failed to perform tail call elimination on a call " 1484 "site marked musttail"); 1485 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1486 // detected sibcalls. 1487 if (isTailCall) { 1488 ++NumTailCalls; 1489 isSibCall = true; 1490 } 1491 } 1492 1493 // Analyze operands of the call, assigning locations to each operand. 1494 SmallVector<CCValAssign, 16> ArgLocs; 1495 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1496 *DAG.getContext(), Call); 1497 CCInfo.AnalyzeCallOperands(Outs, 1498 CCAssignFnForNode(CallConv, /* Return*/ false, 1499 isVarArg)); 1500 1501 // Get a count of how many bytes are to be pushed on the stack. 1502 unsigned NumBytes = CCInfo.getNextStackOffset(); 1503 1504 // For tail calls, memory operands are available in our caller's stack. 1505 if (isSibCall) 1506 NumBytes = 0; 1507 1508 // Adjust the stack pointer for the new arguments... 1509 // These operations are automatically eliminated by the prolog/epilog pass 1510 if (!isSibCall) 1511 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 1512 dl); 1513 1514 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy()); 1515 1516 RegsToPassVector RegsToPass; 1517 SmallVector<SDValue, 8> MemOpChains; 1518 1519 // Walk the register/memloc assignments, inserting copies/loads. In the case 1520 // of tail call optimization, arguments are handled later. 1521 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1522 i != e; 1523 ++i, ++realArgIdx) { 1524 CCValAssign &VA = ArgLocs[i]; 1525 SDValue Arg = OutVals[realArgIdx]; 1526 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1527 bool isByVal = Flags.isByVal(); 1528 1529 // Promote the value if needed. 1530 switch (VA.getLocInfo()) { 1531 default: llvm_unreachable("Unknown loc info!"); 1532 case CCValAssign::Full: break; 1533 case CCValAssign::SExt: 1534 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1535 break; 1536 case CCValAssign::ZExt: 1537 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1538 break; 1539 case CCValAssign::AExt: 1540 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1541 break; 1542 case CCValAssign::BCvt: 1543 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1544 break; 1545 } 1546 1547 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1548 if (VA.needsCustom()) { 1549 if (VA.getLocVT() == MVT::v2f64) { 1550 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1551 DAG.getConstant(0, MVT::i32)); 1552 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1553 DAG.getConstant(1, MVT::i32)); 1554 1555 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1556 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1557 1558 VA = ArgLocs[++i]; // skip ahead to next loc 1559 if (VA.isRegLoc()) { 1560 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1561 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1562 } else { 1563 assert(VA.isMemLoc()); 1564 1565 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1566 dl, DAG, VA, Flags)); 1567 } 1568 } else { 1569 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1570 StackPtr, MemOpChains, Flags); 1571 } 1572 } else if (VA.isRegLoc()) { 1573 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1574 assert(VA.getLocVT() == MVT::i32 && 1575 "unexpected calling convention register assignment"); 1576 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1577 "unexpected use of 'returned'"); 1578 isThisReturn = true; 1579 } 1580 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1581 } else if (isByVal) { 1582 assert(VA.isMemLoc()); 1583 unsigned offset = 0; 1584 1585 // True if this byval aggregate will be split between registers 1586 // and memory. 1587 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1588 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1589 1590 if (CurByValIdx < ByValArgsCount) { 1591 1592 unsigned RegBegin, RegEnd; 1593 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1594 1595 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1596 unsigned int i, j; 1597 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1598 SDValue Const = DAG.getConstant(4*i, MVT::i32); 1599 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1600 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1601 MachinePointerInfo(), 1602 false, false, false, 1603 DAG.InferPtrAlignment(AddArg)); 1604 MemOpChains.push_back(Load.getValue(1)); 1605 RegsToPass.push_back(std::make_pair(j, Load)); 1606 } 1607 1608 // If parameter size outsides register area, "offset" value 1609 // helps us to calculate stack slot for remained part properly. 1610 offset = RegEnd - RegBegin; 1611 1612 CCInfo.nextInRegsParam(); 1613 } 1614 1615 if (Flags.getByValSize() > 4*offset) { 1616 unsigned LocMemOffset = VA.getLocMemOffset(); 1617 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset); 1618 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, 1619 StkPtrOff); 1620 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset); 1621 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset); 1622 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, 1623 MVT::i32); 1624 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32); 1625 1626 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1627 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1628 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1629 Ops)); 1630 } 1631 } else if (!isSibCall) { 1632 assert(VA.isMemLoc()); 1633 1634 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1635 dl, DAG, VA, Flags)); 1636 } 1637 } 1638 1639 if (!MemOpChains.empty()) 1640 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1641 1642 // Build a sequence of copy-to-reg nodes chained together with token chain 1643 // and flag operands which copy the outgoing args into the appropriate regs. 1644 SDValue InFlag; 1645 // Tail call byval lowering might overwrite argument registers so in case of 1646 // tail call optimization the copies to registers are lowered later. 1647 if (!isTailCall) 1648 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1649 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1650 RegsToPass[i].second, InFlag); 1651 InFlag = Chain.getValue(1); 1652 } 1653 1654 // For tail calls lower the arguments to the 'real' stack slot. 1655 if (isTailCall) { 1656 // Force all the incoming stack arguments to be loaded from the stack 1657 // before any new outgoing arguments are stored to the stack, because the 1658 // outgoing stack slots may alias the incoming argument stack slots, and 1659 // the alias isn't otherwise explicit. This is slightly more conservative 1660 // than necessary, because it means that each store effectively depends 1661 // on every argument instead of just those arguments it would clobber. 1662 1663 // Do not flag preceding copytoreg stuff together with the following stuff. 1664 InFlag = SDValue(); 1665 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1666 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1667 RegsToPass[i].second, InFlag); 1668 InFlag = Chain.getValue(1); 1669 } 1670 InFlag = SDValue(); 1671 } 1672 1673 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1674 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1675 // node so that legalize doesn't hack it. 1676 bool isDirect = false; 1677 bool isARMFunc = false; 1678 bool isLocalARMFunc = false; 1679 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1680 1681 if (EnableARMLongCalls) { 1682 assert((Subtarget->isTargetWindows() || 1683 getTargetMachine().getRelocationModel() == Reloc::Static) && 1684 "long-calls with non-static relocation model!"); 1685 // Handle a global address or an external symbol. If it's not one of 1686 // those, the target's already in a register, so we don't need to do 1687 // anything extra. 1688 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1689 const GlobalValue *GV = G->getGlobal(); 1690 // Create a constant pool entry for the callee address 1691 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1692 ARMConstantPoolValue *CPV = 1693 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1694 1695 // Get the address of the callee into a register 1696 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4); 1697 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1698 Callee = DAG.getLoad(getPointerTy(), dl, 1699 DAG.getEntryNode(), CPAddr, 1700 MachinePointerInfo::getConstantPool(), 1701 false, false, false, 0); 1702 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1703 const char *Sym = S->getSymbol(); 1704 1705 // Create a constant pool entry for the callee address 1706 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1707 ARMConstantPoolValue *CPV = 1708 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1709 ARMPCLabelIndex, 0); 1710 // Get the address of the callee into a register 1711 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4); 1712 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1713 Callee = DAG.getLoad(getPointerTy(), dl, 1714 DAG.getEntryNode(), CPAddr, 1715 MachinePointerInfo::getConstantPool(), 1716 false, false, false, 0); 1717 } 1718 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1719 const GlobalValue *GV = G->getGlobal(); 1720 isDirect = true; 1721 bool isExt = GV->isDeclaration() || GV->isWeakForLinker(); 1722 bool isStub = (isExt && Subtarget->isTargetMachO()) && 1723 getTargetMachine().getRelocationModel() != Reloc::Static; 1724 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1725 // ARM call to a local ARM function is predicable. 1726 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking); 1727 // tBX takes a register source operand. 1728 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1729 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1730 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(), 1731 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 1732 0, ARMII::MO_NONLAZY)); 1733 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee, 1734 MachinePointerInfo::getGOT(), false, false, true, 0); 1735 } else if (Subtarget->isTargetCOFF()) { 1736 assert(Subtarget->isTargetWindows() && 1737 "Windows is the only supported COFF target"); 1738 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1739 ? ARMII::MO_DLLIMPORT 1740 : ARMII::MO_NO_FLAG; 1741 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0, 1742 TargetFlags); 1743 if (GV->hasDLLImportStorageClass()) 1744 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 1745 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(), 1746 Callee), MachinePointerInfo::getGOT(), 1747 false, false, false, 0); 1748 } else { 1749 // On ELF targets for PIC code, direct calls should go through the PLT 1750 unsigned OpFlags = 0; 1751 if (Subtarget->isTargetELF() && 1752 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1753 OpFlags = ARMII::MO_PLT; 1754 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 1755 } 1756 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1757 isDirect = true; 1758 bool isStub = Subtarget->isTargetMachO() && 1759 getTargetMachine().getRelocationModel() != Reloc::Static; 1760 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1761 // tBX takes a register source operand. 1762 const char *Sym = S->getSymbol(); 1763 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1764 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1765 ARMConstantPoolValue *CPV = 1766 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1767 ARMPCLabelIndex, 4); 1768 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4); 1769 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1770 Callee = DAG.getLoad(getPointerTy(), dl, 1771 DAG.getEntryNode(), CPAddr, 1772 MachinePointerInfo::getConstantPool(), 1773 false, false, false, 0); 1774 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 1775 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, 1776 getPointerTy(), Callee, PICLabel); 1777 } else { 1778 unsigned OpFlags = 0; 1779 // On ELF targets for PIC code, direct calls should go through the PLT 1780 if (Subtarget->isTargetELF() && 1781 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1782 OpFlags = ARMII::MO_PLT; 1783 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags); 1784 } 1785 } 1786 1787 // FIXME: handle tail calls differently. 1788 unsigned CallOpc; 1789 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute( 1790 AttributeSet::FunctionIndex, Attribute::MinSize); 1791 if (Subtarget->isThumb()) { 1792 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1793 CallOpc = ARMISD::CALL_NOLINK; 1794 else 1795 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL; 1796 } else { 1797 if (!isDirect && !Subtarget->hasV5TOps()) 1798 CallOpc = ARMISD::CALL_NOLINK; 1799 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1800 // Emit regular call when code size is the priority 1801 !HasMinSizeAttr) 1802 // "mov lr, pc; b _foo" to avoid confusing the RSP 1803 CallOpc = ARMISD::CALL_NOLINK; 1804 else 1805 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1806 } 1807 1808 std::vector<SDValue> Ops; 1809 Ops.push_back(Chain); 1810 Ops.push_back(Callee); 1811 1812 // Add argument registers to the end of the list so that they are known live 1813 // into the call. 1814 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1815 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1816 RegsToPass[i].second.getValueType())); 1817 1818 // Add a register mask operand representing the call-preserved registers. 1819 if (!isTailCall) { 1820 const uint32_t *Mask; 1821 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1822 if (isThisReturn) { 1823 // For 'this' returns, use the R0-preserving mask if applicable 1824 Mask = ARI->getThisReturnPreservedMask(CallConv); 1825 if (!Mask) { 1826 // Set isThisReturn to false if the calling convention is not one that 1827 // allows 'returned' to be modeled in this way, so LowerCallResult does 1828 // not try to pass 'this' straight through 1829 isThisReturn = false; 1830 Mask = ARI->getCallPreservedMask(CallConv); 1831 } 1832 } else 1833 Mask = ARI->getCallPreservedMask(CallConv); 1834 1835 assert(Mask && "Missing call preserved mask for calling convention"); 1836 Ops.push_back(DAG.getRegisterMask(Mask)); 1837 } 1838 1839 if (InFlag.getNode()) 1840 Ops.push_back(InFlag); 1841 1842 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1843 if (isTailCall) 1844 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1845 1846 // Returns a chain and a flag for retval copy to use. 1847 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1848 InFlag = Chain.getValue(1); 1849 1850 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 1851 DAG.getIntPtrConstant(0, true), InFlag, dl); 1852 if (!Ins.empty()) 1853 InFlag = Chain.getValue(1); 1854 1855 // Handle result values, copying them out of physregs into vregs that we 1856 // return. 1857 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1858 InVals, isThisReturn, 1859 isThisReturn ? OutVals[0] : SDValue()); 1860 } 1861 1862 /// HandleByVal - Every parameter *after* a byval parameter is passed 1863 /// on the stack. Remember the next parameter register to allocate, 1864 /// and then confiscate the rest of the parameter registers to insure 1865 /// this. 1866 void 1867 ARMTargetLowering::HandleByVal( 1868 CCState *State, unsigned &size, unsigned Align) const { 1869 unsigned reg = State->AllocateReg(GPRArgRegs, 4); 1870 assert((State->getCallOrPrologue() == Prologue || 1871 State->getCallOrPrologue() == Call) && 1872 "unhandled ParmContext"); 1873 1874 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) { 1875 if (Subtarget->isAAPCS_ABI() && Align > 4) { 1876 unsigned AlignInRegs = Align / 4; 1877 unsigned Waste = (ARM::R4 - reg) % AlignInRegs; 1878 for (unsigned i = 0; i < Waste; ++i) 1879 reg = State->AllocateReg(GPRArgRegs, 4); 1880 } 1881 if (reg != 0) { 1882 unsigned excess = 4 * (ARM::R4 - reg); 1883 1884 // Special case when NSAA != SP and parameter size greater than size of 1885 // all remained GPR regs. In that case we can't split parameter, we must 1886 // send it to stack. We also must set NCRN to R4, so waste all 1887 // remained registers. 1888 const unsigned NSAAOffset = State->getNextStackOffset(); 1889 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) { 1890 while (State->AllocateReg(GPRArgRegs, 4)) 1891 ; 1892 return; 1893 } 1894 1895 // First register for byval parameter is the first register that wasn't 1896 // allocated before this method call, so it would be "reg". 1897 // If parameter is small enough to be saved in range [reg, r4), then 1898 // the end (first after last) register would be reg + param-size-in-regs, 1899 // else parameter would be splitted between registers and stack, 1900 // end register would be r4 in this case. 1901 unsigned ByValRegBegin = reg; 1902 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4; 1903 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 1904 // Note, first register is allocated in the beginning of function already, 1905 // allocate remained amount of registers we need. 1906 for (unsigned i = reg+1; i != ByValRegEnd; ++i) 1907 State->AllocateReg(GPRArgRegs, 4); 1908 // A byval parameter that is split between registers and memory needs its 1909 // size truncated here. 1910 // In the case where the entire structure fits in registers, we set the 1911 // size in memory to zero. 1912 if (size < excess) 1913 size = 0; 1914 else 1915 size -= excess; 1916 } 1917 } 1918 } 1919 1920 /// MatchingStackOffset - Return true if the given stack call argument is 1921 /// already available in the same position (relatively) of the caller's 1922 /// incoming argument stack. 1923 static 1924 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 1925 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 1926 const TargetInstrInfo *TII) { 1927 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 1928 int FI = INT_MAX; 1929 if (Arg.getOpcode() == ISD::CopyFromReg) { 1930 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 1931 if (!TargetRegisterInfo::isVirtualRegister(VR)) 1932 return false; 1933 MachineInstr *Def = MRI->getVRegDef(VR); 1934 if (!Def) 1935 return false; 1936 if (!Flags.isByVal()) { 1937 if (!TII->isLoadFromStackSlot(Def, FI)) 1938 return false; 1939 } else { 1940 return false; 1941 } 1942 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 1943 if (Flags.isByVal()) 1944 // ByVal argument is passed in as a pointer but it's now being 1945 // dereferenced. e.g. 1946 // define @foo(%struct.X* %A) { 1947 // tail call @bar(%struct.X* byval %A) 1948 // } 1949 return false; 1950 SDValue Ptr = Ld->getBasePtr(); 1951 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 1952 if (!FINode) 1953 return false; 1954 FI = FINode->getIndex(); 1955 } else 1956 return false; 1957 1958 assert(FI != INT_MAX); 1959 if (!MFI->isFixedObjectIndex(FI)) 1960 return false; 1961 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 1962 } 1963 1964 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 1965 /// for tail call optimization. Targets which want to do tail call 1966 /// optimization should implement this function. 1967 bool 1968 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 1969 CallingConv::ID CalleeCC, 1970 bool isVarArg, 1971 bool isCalleeStructRet, 1972 bool isCallerStructRet, 1973 const SmallVectorImpl<ISD::OutputArg> &Outs, 1974 const SmallVectorImpl<SDValue> &OutVals, 1975 const SmallVectorImpl<ISD::InputArg> &Ins, 1976 SelectionDAG& DAG) const { 1977 const Function *CallerF = DAG.getMachineFunction().getFunction(); 1978 CallingConv::ID CallerCC = CallerF->getCallingConv(); 1979 bool CCMatch = CallerCC == CalleeCC; 1980 1981 // Look for obvious safe cases to perform tail call optimization that do not 1982 // require ABI changes. This is what gcc calls sibcall. 1983 1984 // Do not sibcall optimize vararg calls unless the call site is not passing 1985 // any arguments. 1986 if (isVarArg && !Outs.empty()) 1987 return false; 1988 1989 // Exception-handling functions need a special set of instructions to indicate 1990 // a return to the hardware. Tail-calling another function would probably 1991 // break this. 1992 if (CallerF->hasFnAttribute("interrupt")) 1993 return false; 1994 1995 // Also avoid sibcall optimization if either caller or callee uses struct 1996 // return semantics. 1997 if (isCalleeStructRet || isCallerStructRet) 1998 return false; 1999 2000 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo:: 2001 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as 2002 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation 2003 // support in the assembler and linker to be used. This would need to be 2004 // fixed to fully support tail calls in Thumb1. 2005 // 2006 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take 2007 // LR. This means if we need to reload LR, it takes an extra instructions, 2008 // which outweighs the value of the tail call; but here we don't know yet 2009 // whether LR is going to be used. Probably the right approach is to 2010 // generate the tail call here and turn it back into CALL/RET in 2011 // emitEpilogue if LR is used. 2012 2013 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls, 2014 // but we need to make sure there are enough registers; the only valid 2015 // registers are the 4 used for parameters. We don't currently do this 2016 // case. 2017 if (Subtarget->isThumb1Only()) 2018 return false; 2019 2020 // Externally-defined functions with weak linkage should not be 2021 // tail-called on ARM when the OS does not support dynamic 2022 // pre-emption of symbols, as the AAELF spec requires normal calls 2023 // to undefined weak functions to be replaced with a NOP or jump to the 2024 // next instruction. The behaviour of branch instructions in this 2025 // situation (as used for tail calls) is implementation-defined, so we 2026 // cannot rely on the linker replacing the tail call with a return. 2027 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2028 const GlobalValue *GV = G->getGlobal(); 2029 const Triple TT(getTargetMachine().getTargetTriple()); 2030 if (GV->hasExternalWeakLinkage() && 2031 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2032 return false; 2033 } 2034 2035 // If the calling conventions do not match, then we'd better make sure the 2036 // results are returned in the same way as what the caller expects. 2037 if (!CCMatch) { 2038 SmallVector<CCValAssign, 16> RVLocs1; 2039 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1, 2040 *DAG.getContext(), Call); 2041 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg)); 2042 2043 SmallVector<CCValAssign, 16> RVLocs2; 2044 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2, 2045 *DAG.getContext(), Call); 2046 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg)); 2047 2048 if (RVLocs1.size() != RVLocs2.size()) 2049 return false; 2050 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2051 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2052 return false; 2053 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2054 return false; 2055 if (RVLocs1[i].isRegLoc()) { 2056 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2057 return false; 2058 } else { 2059 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2060 return false; 2061 } 2062 } 2063 } 2064 2065 // If Caller's vararg or byval argument has been split between registers and 2066 // stack, do not perform tail call, since part of the argument is in caller's 2067 // local frame. 2068 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction(). 2069 getInfo<ARMFunctionInfo>(); 2070 if (AFI_Caller->getArgRegsSaveSize()) 2071 return false; 2072 2073 // If the callee takes no arguments then go on to check the results of the 2074 // call. 2075 if (!Outs.empty()) { 2076 // Check if stack adjustment is needed. For now, do not do this if any 2077 // argument is passed on the stack. 2078 SmallVector<CCValAssign, 16> ArgLocs; 2079 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs, 2080 *DAG.getContext(), Call); 2081 CCInfo.AnalyzeCallOperands(Outs, 2082 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2083 if (CCInfo.getNextStackOffset()) { 2084 MachineFunction &MF = DAG.getMachineFunction(); 2085 2086 // Check if the arguments are already laid out in the right way as 2087 // the caller's fixed stack objects. 2088 MachineFrameInfo *MFI = MF.getFrameInfo(); 2089 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2090 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2091 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2092 i != e; 2093 ++i, ++realArgIdx) { 2094 CCValAssign &VA = ArgLocs[i]; 2095 EVT RegVT = VA.getLocVT(); 2096 SDValue Arg = OutVals[realArgIdx]; 2097 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2098 if (VA.getLocInfo() == CCValAssign::Indirect) 2099 return false; 2100 if (VA.needsCustom()) { 2101 // f64 and vector types are split into multiple registers or 2102 // register/stack-slot combinations. The types will not match 2103 // the registers; give up on memory f64 refs until we figure 2104 // out what to do about this. 2105 if (!VA.isRegLoc()) 2106 return false; 2107 if (!ArgLocs[++i].isRegLoc()) 2108 return false; 2109 if (RegVT == MVT::v2f64) { 2110 if (!ArgLocs[++i].isRegLoc()) 2111 return false; 2112 if (!ArgLocs[++i].isRegLoc()) 2113 return false; 2114 } 2115 } else if (!VA.isRegLoc()) { 2116 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2117 MFI, MRI, TII)) 2118 return false; 2119 } 2120 } 2121 } 2122 } 2123 2124 return true; 2125 } 2126 2127 bool 2128 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2129 MachineFunction &MF, bool isVarArg, 2130 const SmallVectorImpl<ISD::OutputArg> &Outs, 2131 LLVMContext &Context) const { 2132 SmallVector<CCValAssign, 16> RVLocs; 2133 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2134 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2135 isVarArg)); 2136 } 2137 2138 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2139 SDLoc DL, SelectionDAG &DAG) { 2140 const MachineFunction &MF = DAG.getMachineFunction(); 2141 const Function *F = MF.getFunction(); 2142 2143 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2144 2145 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2146 // version of the "preferred return address". These offsets affect the return 2147 // instruction if this is a return from PL1 without hypervisor extensions. 2148 // IRQ/FIQ: +4 "subs pc, lr, #4" 2149 // SWI: 0 "subs pc, lr, #0" 2150 // ABORT: +4 "subs pc, lr, #4" 2151 // UNDEF: +4/+2 "subs pc, lr, #0" 2152 // UNDEF varies depending on where the exception came from ARM or Thumb 2153 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2154 2155 int64_t LROffset; 2156 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2157 IntKind == "ABORT") 2158 LROffset = 4; 2159 else if (IntKind == "SWI" || IntKind == "UNDEF") 2160 LROffset = 0; 2161 else 2162 report_fatal_error("Unsupported interrupt attribute. If present, value " 2163 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2164 2165 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false)); 2166 2167 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2168 } 2169 2170 SDValue 2171 ARMTargetLowering::LowerReturn(SDValue Chain, 2172 CallingConv::ID CallConv, bool isVarArg, 2173 const SmallVectorImpl<ISD::OutputArg> &Outs, 2174 const SmallVectorImpl<SDValue> &OutVals, 2175 SDLoc dl, SelectionDAG &DAG) const { 2176 2177 // CCValAssign - represent the assignment of the return value to a location. 2178 SmallVector<CCValAssign, 16> RVLocs; 2179 2180 // CCState - Info about the registers and stack slots. 2181 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2182 *DAG.getContext(), Call); 2183 2184 // Analyze outgoing return values. 2185 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2186 isVarArg)); 2187 2188 SDValue Flag; 2189 SmallVector<SDValue, 4> RetOps; 2190 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2191 bool isLittleEndian = Subtarget->isLittle(); 2192 2193 MachineFunction &MF = DAG.getMachineFunction(); 2194 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2195 AFI->setReturnRegsCount(RVLocs.size()); 2196 2197 // Copy the result values into the output registers. 2198 for (unsigned i = 0, realRVLocIdx = 0; 2199 i != RVLocs.size(); 2200 ++i, ++realRVLocIdx) { 2201 CCValAssign &VA = RVLocs[i]; 2202 assert(VA.isRegLoc() && "Can only return in registers!"); 2203 2204 SDValue Arg = OutVals[realRVLocIdx]; 2205 2206 switch (VA.getLocInfo()) { 2207 default: llvm_unreachable("Unknown loc info!"); 2208 case CCValAssign::Full: break; 2209 case CCValAssign::BCvt: 2210 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2211 break; 2212 } 2213 2214 if (VA.needsCustom()) { 2215 if (VA.getLocVT() == MVT::v2f64) { 2216 // Extract the first half and return it in two registers. 2217 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2218 DAG.getConstant(0, MVT::i32)); 2219 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2220 DAG.getVTList(MVT::i32, MVT::i32), Half); 2221 2222 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2223 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2224 Flag); 2225 Flag = Chain.getValue(1); 2226 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2227 VA = RVLocs[++i]; // skip ahead to next loc 2228 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2229 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2230 Flag); 2231 Flag = Chain.getValue(1); 2232 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2233 VA = RVLocs[++i]; // skip ahead to next loc 2234 2235 // Extract the 2nd half and fall through to handle it as an f64 value. 2236 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2237 DAG.getConstant(1, MVT::i32)); 2238 } 2239 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2240 // available. 2241 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2242 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2243 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2244 fmrrd.getValue(isLittleEndian ? 0 : 1), 2245 Flag); 2246 Flag = Chain.getValue(1); 2247 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2248 VA = RVLocs[++i]; // skip ahead to next loc 2249 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2250 fmrrd.getValue(isLittleEndian ? 1 : 0), 2251 Flag); 2252 } else 2253 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2254 2255 // Guarantee that all emitted copies are 2256 // stuck together, avoiding something bad. 2257 Flag = Chain.getValue(1); 2258 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2259 } 2260 2261 // Update chain and glue. 2262 RetOps[0] = Chain; 2263 if (Flag.getNode()) 2264 RetOps.push_back(Flag); 2265 2266 // CPUs which aren't M-class use a special sequence to return from 2267 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2268 // though we use "subs pc, lr, #N"). 2269 // 2270 // M-class CPUs actually use a normal return sequence with a special 2271 // (hardware-provided) value in LR, so the normal code path works. 2272 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2273 !Subtarget->isMClass()) { 2274 if (Subtarget->isThumb1Only()) 2275 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2276 return LowerInterruptReturn(RetOps, dl, DAG); 2277 } 2278 2279 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2280 } 2281 2282 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2283 if (N->getNumValues() != 1) 2284 return false; 2285 if (!N->hasNUsesOfValue(1, 0)) 2286 return false; 2287 2288 SDValue TCChain = Chain; 2289 SDNode *Copy = *N->use_begin(); 2290 if (Copy->getOpcode() == ISD::CopyToReg) { 2291 // If the copy has a glue operand, we conservatively assume it isn't safe to 2292 // perform a tail call. 2293 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2294 return false; 2295 TCChain = Copy->getOperand(0); 2296 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2297 SDNode *VMov = Copy; 2298 // f64 returned in a pair of GPRs. 2299 SmallPtrSet<SDNode*, 2> Copies; 2300 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2301 UI != UE; ++UI) { 2302 if (UI->getOpcode() != ISD::CopyToReg) 2303 return false; 2304 Copies.insert(*UI); 2305 } 2306 if (Copies.size() > 2) 2307 return false; 2308 2309 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2310 UI != UE; ++UI) { 2311 SDValue UseChain = UI->getOperand(0); 2312 if (Copies.count(UseChain.getNode())) 2313 // Second CopyToReg 2314 Copy = *UI; 2315 else { 2316 // We are at the top of this chain. 2317 // If the copy has a glue operand, we conservatively assume it 2318 // isn't safe to perform a tail call. 2319 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2320 return false; 2321 // First CopyToReg 2322 TCChain = UseChain; 2323 } 2324 } 2325 } else if (Copy->getOpcode() == ISD::BITCAST) { 2326 // f32 returned in a single GPR. 2327 if (!Copy->hasOneUse()) 2328 return false; 2329 Copy = *Copy->use_begin(); 2330 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2331 return false; 2332 // If the copy has a glue operand, we conservatively assume it isn't safe to 2333 // perform a tail call. 2334 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2335 return false; 2336 TCChain = Copy->getOperand(0); 2337 } else { 2338 return false; 2339 } 2340 2341 bool HasRet = false; 2342 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2343 UI != UE; ++UI) { 2344 if (UI->getOpcode() != ARMISD::RET_FLAG && 2345 UI->getOpcode() != ARMISD::INTRET_FLAG) 2346 return false; 2347 HasRet = true; 2348 } 2349 2350 if (!HasRet) 2351 return false; 2352 2353 Chain = TCChain; 2354 return true; 2355 } 2356 2357 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2358 if (!Subtarget->supportsTailCall()) 2359 return false; 2360 2361 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls) 2362 return false; 2363 2364 return !Subtarget->isThumb1Only(); 2365 } 2366 2367 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2368 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2369 // one of the above mentioned nodes. It has to be wrapped because otherwise 2370 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2371 // be used to form addressing mode. These wrapped nodes will be selected 2372 // into MOVi. 2373 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2374 EVT PtrVT = Op.getValueType(); 2375 // FIXME there is no actual debug info here 2376 SDLoc dl(Op); 2377 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2378 SDValue Res; 2379 if (CP->isMachineConstantPoolEntry()) 2380 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2381 CP->getAlignment()); 2382 else 2383 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2384 CP->getAlignment()); 2385 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2386 } 2387 2388 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2389 return MachineJumpTableInfo::EK_Inline; 2390 } 2391 2392 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2393 SelectionDAG &DAG) const { 2394 MachineFunction &MF = DAG.getMachineFunction(); 2395 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2396 unsigned ARMPCLabelIndex = 0; 2397 SDLoc DL(Op); 2398 EVT PtrVT = getPointerTy(); 2399 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2400 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2401 SDValue CPAddr; 2402 if (RelocM == Reloc::Static) { 2403 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2404 } else { 2405 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2406 ARMPCLabelIndex = AFI->createPICLabelUId(); 2407 ARMConstantPoolValue *CPV = 2408 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2409 ARMCP::CPBlockAddress, PCAdj); 2410 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2411 } 2412 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2413 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2414 MachinePointerInfo::getConstantPool(), 2415 false, false, false, 0); 2416 if (RelocM == Reloc::Static) 2417 return Result; 2418 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2419 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2420 } 2421 2422 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2423 SDValue 2424 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2425 SelectionDAG &DAG) const { 2426 SDLoc dl(GA); 2427 EVT PtrVT = getPointerTy(); 2428 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2429 MachineFunction &MF = DAG.getMachineFunction(); 2430 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2431 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2432 ARMConstantPoolValue *CPV = 2433 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2434 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2435 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2436 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2437 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2438 MachinePointerInfo::getConstantPool(), 2439 false, false, false, 0); 2440 SDValue Chain = Argument.getValue(1); 2441 2442 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2443 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2444 2445 // call __tls_get_addr. 2446 ArgListTy Args; 2447 ArgListEntry Entry; 2448 Entry.Node = Argument; 2449 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2450 Args.push_back(Entry); 2451 2452 // FIXME: is there useful debug info available here? 2453 TargetLowering::CallLoweringInfo CLI(DAG); 2454 CLI.setDebugLoc(dl).setChain(Chain) 2455 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2456 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args), 2457 0); 2458 2459 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2460 return CallResult.first; 2461 } 2462 2463 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2464 // "local exec" model. 2465 SDValue 2466 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2467 SelectionDAG &DAG, 2468 TLSModel::Model model) const { 2469 const GlobalValue *GV = GA->getGlobal(); 2470 SDLoc dl(GA); 2471 SDValue Offset; 2472 SDValue Chain = DAG.getEntryNode(); 2473 EVT PtrVT = getPointerTy(); 2474 // Get the Thread Pointer 2475 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2476 2477 if (model == TLSModel::InitialExec) { 2478 MachineFunction &MF = DAG.getMachineFunction(); 2479 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2480 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2481 // Initial exec model. 2482 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2483 ARMConstantPoolValue *CPV = 2484 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2485 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2486 true); 2487 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2488 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2489 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, 2490 MachinePointerInfo::getConstantPool(), 2491 false, false, false, 0); 2492 Chain = Offset.getValue(1); 2493 2494 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2495 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2496 2497 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, 2498 MachinePointerInfo::getConstantPool(), 2499 false, false, false, 0); 2500 } else { 2501 // local exec model 2502 assert(model == TLSModel::LocalExec); 2503 ARMConstantPoolValue *CPV = 2504 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2505 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2506 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2507 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, 2508 MachinePointerInfo::getConstantPool(), 2509 false, false, false, 0); 2510 } 2511 2512 // The address of the thread local variable is the add of the thread 2513 // pointer with the offset of the variable. 2514 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2515 } 2516 2517 SDValue 2518 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2519 // TODO: implement the "local dynamic" model 2520 assert(Subtarget->isTargetELF() && 2521 "TLS not implemented for non-ELF targets"); 2522 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2523 2524 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2525 2526 switch (model) { 2527 case TLSModel::GeneralDynamic: 2528 case TLSModel::LocalDynamic: 2529 return LowerToTLSGeneralDynamicModel(GA, DAG); 2530 case TLSModel::InitialExec: 2531 case TLSModel::LocalExec: 2532 return LowerToTLSExecModels(GA, DAG, model); 2533 } 2534 llvm_unreachable("bogus TLS model"); 2535 } 2536 2537 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2538 SelectionDAG &DAG) const { 2539 EVT PtrVT = getPointerTy(); 2540 SDLoc dl(Op); 2541 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2542 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2543 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility(); 2544 ARMConstantPoolValue *CPV = 2545 ARMConstantPoolConstant::Create(GV, 2546 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT); 2547 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2548 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2549 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 2550 CPAddr, 2551 MachinePointerInfo::getConstantPool(), 2552 false, false, false, 0); 2553 SDValue Chain = Result.getValue(1); 2554 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT); 2555 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT); 2556 if (!UseGOTOFF) 2557 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2558 MachinePointerInfo::getGOT(), 2559 false, false, false, 0); 2560 return Result; 2561 } 2562 2563 // If we have T2 ops, we can materialize the address directly via movt/movw 2564 // pair. This is always cheaper. 2565 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2566 ++NumMovwMovt; 2567 // FIXME: Once remat is capable of dealing with instructions with register 2568 // operands, expand this into two nodes. 2569 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2570 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2571 } else { 2572 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2573 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2574 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, 2575 MachinePointerInfo::getConstantPool(), 2576 false, false, false, 0); 2577 } 2578 } 2579 2580 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2581 SelectionDAG &DAG) const { 2582 EVT PtrVT = getPointerTy(); 2583 SDLoc dl(Op); 2584 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2585 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2586 2587 if (Subtarget->useMovt(DAG.getMachineFunction())) 2588 ++NumMovwMovt; 2589 2590 // FIXME: Once remat is capable of dealing with instructions with register 2591 // operands, expand this into multiple nodes 2592 unsigned Wrapper = 2593 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2594 2595 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2596 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2597 2598 if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) 2599 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2600 MachinePointerInfo::getGOT(), false, false, false, 0); 2601 return Result; 2602 } 2603 2604 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2605 SelectionDAG &DAG) const { 2606 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2607 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2608 "Windows on ARM expects to use movw/movt"); 2609 2610 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2611 const ARMII::TOF TargetFlags = 2612 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2613 EVT PtrVT = getPointerTy(); 2614 SDValue Result; 2615 SDLoc DL(Op); 2616 2617 ++NumMovwMovt; 2618 2619 // FIXME: Once remat is capable of dealing with instructions with register 2620 // operands, expand this into two nodes. 2621 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2622 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2623 TargetFlags)); 2624 if (GV->hasDLLImportStorageClass()) 2625 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2626 MachinePointerInfo::getGOT(), false, false, false, 0); 2627 return Result; 2628 } 2629 2630 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op, 2631 SelectionDAG &DAG) const { 2632 assert(Subtarget->isTargetELF() && 2633 "GLOBAL OFFSET TABLE not implemented for non-ELF targets"); 2634 MachineFunction &MF = DAG.getMachineFunction(); 2635 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2636 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2637 EVT PtrVT = getPointerTy(); 2638 SDLoc dl(Op); 2639 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2640 ARMConstantPoolValue *CPV = 2641 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_", 2642 ARMPCLabelIndex, PCAdj); 2643 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2644 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2645 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, 2646 MachinePointerInfo::getConstantPool(), 2647 false, false, false, 0); 2648 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2649 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2650 } 2651 2652 SDValue 2653 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2654 SDLoc dl(Op); 2655 SDValue Val = DAG.getConstant(0, MVT::i32); 2656 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2657 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2658 Op.getOperand(1), Val); 2659 } 2660 2661 SDValue 2662 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2663 SDLoc dl(Op); 2664 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2665 Op.getOperand(1), DAG.getConstant(0, MVT::i32)); 2666 } 2667 2668 SDValue 2669 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2670 const ARMSubtarget *Subtarget) const { 2671 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2672 SDLoc dl(Op); 2673 switch (IntNo) { 2674 default: return SDValue(); // Don't custom lower most intrinsics. 2675 case Intrinsic::arm_rbit: { 2676 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2677 "RBIT intrinsic must have i32 type!"); 2678 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1)); 2679 } 2680 case Intrinsic::arm_thread_pointer: { 2681 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2682 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2683 } 2684 case Intrinsic::eh_sjlj_lsda: { 2685 MachineFunction &MF = DAG.getMachineFunction(); 2686 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2687 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2688 EVT PtrVT = getPointerTy(); 2689 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2690 SDValue CPAddr; 2691 unsigned PCAdj = (RelocM != Reloc::PIC_) 2692 ? 0 : (Subtarget->isThumb() ? 4 : 8); 2693 ARMConstantPoolValue *CPV = 2694 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2695 ARMCP::CPLSDA, PCAdj); 2696 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2697 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2698 SDValue Result = 2699 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, 2700 MachinePointerInfo::getConstantPool(), 2701 false, false, false, 0); 2702 2703 if (RelocM == Reloc::PIC_) { 2704 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2705 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2706 } 2707 return Result; 2708 } 2709 case Intrinsic::arm_neon_vmulls: 2710 case Intrinsic::arm_neon_vmullu: { 2711 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2712 ? ARMISD::VMULLs : ARMISD::VMULLu; 2713 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2714 Op.getOperand(1), Op.getOperand(2)); 2715 } 2716 } 2717 } 2718 2719 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 2720 const ARMSubtarget *Subtarget) { 2721 // FIXME: handle "fence singlethread" more efficiently. 2722 SDLoc dl(Op); 2723 if (!Subtarget->hasDataBarrier()) { 2724 // Some ARMv6 cpus can support data barriers with an mcr instruction. 2725 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 2726 // here. 2727 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 2728 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 2729 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 2730 DAG.getConstant(0, MVT::i32)); 2731 } 2732 2733 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 2734 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 2735 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 2736 if (Subtarget->isMClass()) { 2737 // Only a full system barrier exists in the M-class architectures. 2738 Domain = ARM_MB::SY; 2739 } else if (Subtarget->isSwift() && Ord == Release) { 2740 // Swift happens to implement ISHST barriers in a way that's compatible with 2741 // Release semantics but weaker than ISH so we'd be fools not to use 2742 // it. Beware: other processors probably don't! 2743 Domain = ARM_MB::ISHST; 2744 } 2745 2746 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 2747 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32), 2748 DAG.getConstant(Domain, MVT::i32)); 2749 } 2750 2751 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 2752 const ARMSubtarget *Subtarget) { 2753 // ARM pre v5TE and Thumb1 does not have preload instructions. 2754 if (!(Subtarget->isThumb2() || 2755 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 2756 // Just preserve the chain. 2757 return Op.getOperand(0); 2758 2759 SDLoc dl(Op); 2760 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 2761 if (!isRead && 2762 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 2763 // ARMv7 with MP extension has PLDW. 2764 return Op.getOperand(0); 2765 2766 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2767 if (Subtarget->isThumb()) { 2768 // Invert the bits. 2769 isRead = ~isRead & 1; 2770 isData = ~isData & 1; 2771 } 2772 2773 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 2774 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32), 2775 DAG.getConstant(isData, MVT::i32)); 2776 } 2777 2778 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 2779 MachineFunction &MF = DAG.getMachineFunction(); 2780 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 2781 2782 // vastart just stores the address of the VarArgsFrameIndex slot into the 2783 // memory location argument. 2784 SDLoc dl(Op); 2785 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2786 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2787 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2788 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2789 MachinePointerInfo(SV), false, false, 0); 2790 } 2791 2792 SDValue 2793 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA, 2794 SDValue &Root, SelectionDAG &DAG, 2795 SDLoc dl) const { 2796 MachineFunction &MF = DAG.getMachineFunction(); 2797 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2798 2799 const TargetRegisterClass *RC; 2800 if (AFI->isThumb1OnlyFunction()) 2801 RC = &ARM::tGPRRegClass; 2802 else 2803 RC = &ARM::GPRRegClass; 2804 2805 // Transform the arguments stored in physical registers into virtual ones. 2806 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2807 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 2808 2809 SDValue ArgValue2; 2810 if (NextVA.isMemLoc()) { 2811 MachineFrameInfo *MFI = MF.getFrameInfo(); 2812 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 2813 2814 // Create load node to retrieve arguments from the stack. 2815 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 2816 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, 2817 MachinePointerInfo::getFixedStack(FI), 2818 false, false, false, 0); 2819 } else { 2820 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 2821 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 2822 } 2823 if (!Subtarget->isLittle()) 2824 std::swap (ArgValue, ArgValue2); 2825 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 2826 } 2827 2828 void 2829 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF, 2830 unsigned InRegsParamRecordIdx, 2831 unsigned ArgSize, 2832 unsigned &ArgRegsSize, 2833 unsigned &ArgRegsSaveSize) 2834 const { 2835 unsigned NumGPRs; 2836 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 2837 unsigned RBegin, REnd; 2838 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 2839 NumGPRs = REnd - RBegin; 2840 } else { 2841 unsigned int firstUnalloced; 2842 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs, 2843 sizeof(GPRArgRegs) / 2844 sizeof(GPRArgRegs[0])); 2845 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0; 2846 } 2847 2848 unsigned Align = Subtarget->getFrameLowering()->getStackAlignment(); 2849 ArgRegsSize = NumGPRs * 4; 2850 2851 // If parameter is split between stack and GPRs... 2852 if (NumGPRs && Align > 4 && 2853 (ArgRegsSize < ArgSize || 2854 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) { 2855 // Add padding for part of param recovered from GPRs. For example, 2856 // if Align == 8, its last byte must be at address K*8 - 1. 2857 // We need to do it, since remained (stack) part of parameter has 2858 // stack alignment, and we need to "attach" "GPRs head" without gaps 2859 // to it: 2860 // Stack: 2861 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes... 2862 // [ [padding] [GPRs head] ] [ Tail passed via stack .... 2863 // 2864 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2865 unsigned Padding = 2866 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align); 2867 ArgRegsSaveSize = ArgRegsSize + Padding; 2868 } else 2869 // We don't need to extend regs save size for byval parameters if they 2870 // are passed via GPRs only. 2871 ArgRegsSaveSize = ArgRegsSize; 2872 } 2873 2874 // The remaining GPRs hold either the beginning of variable-argument 2875 // data, or the beginning of an aggregate passed by value (usually 2876 // byval). Either way, we allocate stack slots adjacent to the data 2877 // provided by our caller, and store the unallocated registers there. 2878 // If this is a variadic function, the va_list pointer will begin with 2879 // these values; otherwise, this reassembles a (byval) structure that 2880 // was split between registers and memory. 2881 // Return: The frame index registers were stored into. 2882 int 2883 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 2884 SDLoc dl, SDValue &Chain, 2885 const Value *OrigArg, 2886 unsigned InRegsParamRecordIdx, 2887 unsigned OffsetFromOrigArg, 2888 unsigned ArgOffset, 2889 unsigned ArgSize, 2890 bool ForceMutable, 2891 unsigned ByValStoreOffset, 2892 unsigned TotalArgRegsSaveSize) const { 2893 2894 // Currently, two use-cases possible: 2895 // Case #1. Non-var-args function, and we meet first byval parameter. 2896 // Setup first unallocated register as first byval register; 2897 // eat all remained registers 2898 // (these two actions are performed by HandleByVal method). 2899 // Then, here, we initialize stack frame with 2900 // "store-reg" instructions. 2901 // Case #2. Var-args function, that doesn't contain byval parameters. 2902 // The same: eat all remained unallocated registers, 2903 // initialize stack frame. 2904 2905 MachineFunction &MF = DAG.getMachineFunction(); 2906 MachineFrameInfo *MFI = MF.getFrameInfo(); 2907 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2908 unsigned firstRegToSaveIndex, lastRegToSaveIndex; 2909 unsigned RBegin, REnd; 2910 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 2911 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 2912 firstRegToSaveIndex = RBegin - ARM::R0; 2913 lastRegToSaveIndex = REnd - ARM::R0; 2914 } else { 2915 firstRegToSaveIndex = CCInfo.getFirstUnallocated 2916 (GPRArgRegs, array_lengthof(GPRArgRegs)); 2917 lastRegToSaveIndex = 4; 2918 } 2919 2920 unsigned ArgRegsSize, ArgRegsSaveSize; 2921 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize, 2922 ArgRegsSize, ArgRegsSaveSize); 2923 2924 // Store any by-val regs to their spots on the stack so that they may be 2925 // loaded by deferencing the result of formal parameter pointer or va_next. 2926 // Note: once stack area for byval/varargs registers 2927 // was initialized, it can't be initialized again. 2928 if (ArgRegsSaveSize) { 2929 unsigned Padding = ArgRegsSaveSize - ArgRegsSize; 2930 2931 if (Padding) { 2932 assert(AFI->getStoredByValParamsPadding() == 0 && 2933 "The only parameter may be padded."); 2934 AFI->setStoredByValParamsPadding(Padding); 2935 } 2936 2937 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize, 2938 Padding + 2939 ByValStoreOffset - 2940 (int64_t)TotalArgRegsSaveSize, 2941 false); 2942 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy()); 2943 if (Padding) { 2944 MFI->CreateFixedObject(Padding, 2945 ArgOffset + ByValStoreOffset - 2946 (int64_t)ArgRegsSaveSize, 2947 false); 2948 } 2949 2950 SmallVector<SDValue, 4> MemOps; 2951 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex; 2952 ++firstRegToSaveIndex, ++i) { 2953 const TargetRegisterClass *RC; 2954 if (AFI->isThumb1OnlyFunction()) 2955 RC = &ARM::tGPRRegClass; 2956 else 2957 RC = &ARM::GPRRegClass; 2958 2959 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC); 2960 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 2961 SDValue Store = 2962 DAG.getStore(Val.getValue(1), dl, Val, FIN, 2963 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i), 2964 false, false, 0); 2965 MemOps.push_back(Store); 2966 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN, 2967 DAG.getConstant(4, getPointerTy())); 2968 } 2969 2970 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize()); 2971 2972 if (!MemOps.empty()) 2973 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 2974 return FrameIndex; 2975 } else { 2976 if (ArgSize == 0) { 2977 // We cannot allocate a zero-byte object for the first variadic argument, 2978 // so just make up a size. 2979 ArgSize = 4; 2980 } 2981 // This will point to the next argument passed via stack. 2982 return MFI->CreateFixedObject( 2983 ArgSize, ArgOffset, !ForceMutable); 2984 } 2985 } 2986 2987 // Setup stack frame, the va_list pointer will start from. 2988 void 2989 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 2990 SDLoc dl, SDValue &Chain, 2991 unsigned ArgOffset, 2992 unsigned TotalArgRegsSaveSize, 2993 bool ForceMutable) const { 2994 MachineFunction &MF = DAG.getMachineFunction(); 2995 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2996 2997 // Try to store any remaining integer argument regs 2998 // to their spots on the stack so that they may be loaded by deferencing 2999 // the result of va_next. 3000 // If there is no regs to be stored, just point address after last 3001 // argument passed via stack. 3002 int FrameIndex = 3003 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3004 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable, 3005 0, TotalArgRegsSaveSize); 3006 3007 AFI->setVarArgsFrameIndex(FrameIndex); 3008 } 3009 3010 SDValue 3011 ARMTargetLowering::LowerFormalArguments(SDValue Chain, 3012 CallingConv::ID CallConv, bool isVarArg, 3013 const SmallVectorImpl<ISD::InputArg> 3014 &Ins, 3015 SDLoc dl, SelectionDAG &DAG, 3016 SmallVectorImpl<SDValue> &InVals) 3017 const { 3018 MachineFunction &MF = DAG.getMachineFunction(); 3019 MachineFrameInfo *MFI = MF.getFrameInfo(); 3020 3021 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3022 3023 // Assign locations to all of the incoming arguments. 3024 SmallVector<CCValAssign, 16> ArgLocs; 3025 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3026 *DAG.getContext(), Prologue); 3027 CCInfo.AnalyzeFormalArguments(Ins, 3028 CCAssignFnForNode(CallConv, /* Return*/ false, 3029 isVarArg)); 3030 3031 SmallVector<SDValue, 16> ArgValues; 3032 int lastInsIndex = -1; 3033 SDValue ArgValue; 3034 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3035 unsigned CurArgIdx = 0; 3036 3037 // Initially ArgRegsSaveSize is zero. 3038 // Then we increase this value each time we meet byval parameter. 3039 // We also increase this value in case of varargs function. 3040 AFI->setArgRegsSaveSize(0); 3041 3042 unsigned ByValStoreOffset = 0; 3043 unsigned TotalArgRegsSaveSize = 0; 3044 unsigned ArgRegsSaveSizeMaxAlign = 4; 3045 3046 // Calculate the amount of stack space that we need to allocate to store 3047 // byval and variadic arguments that are passed in registers. 3048 // We need to know this before we allocate the first byval or variadic 3049 // argument, as they will be allocated a stack slot below the CFA (Canonical 3050 // Frame Address, the stack pointer at entry to the function). 3051 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3052 CCValAssign &VA = ArgLocs[i]; 3053 if (VA.isMemLoc()) { 3054 int index = VA.getValNo(); 3055 if (index != lastInsIndex) { 3056 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3057 if (Flags.isByVal()) { 3058 unsigned ExtraArgRegsSize; 3059 unsigned ExtraArgRegsSaveSize; 3060 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(), 3061 Flags.getByValSize(), 3062 ExtraArgRegsSize, ExtraArgRegsSaveSize); 3063 3064 TotalArgRegsSaveSize += ExtraArgRegsSaveSize; 3065 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign) 3066 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign(); 3067 CCInfo.nextInRegsParam(); 3068 } 3069 lastInsIndex = index; 3070 } 3071 } 3072 } 3073 CCInfo.rewindByValRegsInfo(); 3074 lastInsIndex = -1; 3075 if (isVarArg && MFI->hasVAStart()) { 3076 unsigned ExtraArgRegsSize; 3077 unsigned ExtraArgRegsSaveSize; 3078 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0, 3079 ExtraArgRegsSize, ExtraArgRegsSaveSize); 3080 TotalArgRegsSaveSize += ExtraArgRegsSaveSize; 3081 } 3082 // If the arg regs save area contains N-byte aligned values, the 3083 // bottom of it must be at least N-byte aligned. 3084 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign); 3085 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U); 3086 3087 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3088 CCValAssign &VA = ArgLocs[i]; 3089 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx); 3090 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex; 3091 // Arguments stored in registers. 3092 if (VA.isRegLoc()) { 3093 EVT RegVT = VA.getLocVT(); 3094 3095 if (VA.needsCustom()) { 3096 // f64 and vector types are split up into multiple registers or 3097 // combinations of registers and stack slots. 3098 if (VA.getLocVT() == MVT::v2f64) { 3099 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3100 Chain, DAG, dl); 3101 VA = ArgLocs[++i]; // skip ahead to next loc 3102 SDValue ArgValue2; 3103 if (VA.isMemLoc()) { 3104 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 3105 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 3106 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3107 MachinePointerInfo::getFixedStack(FI), 3108 false, false, false, 0); 3109 } else { 3110 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3111 Chain, DAG, dl); 3112 } 3113 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3114 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3115 ArgValue, ArgValue1, DAG.getIntPtrConstant(0)); 3116 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3117 ArgValue, ArgValue2, DAG.getIntPtrConstant(1)); 3118 } else 3119 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3120 3121 } else { 3122 const TargetRegisterClass *RC; 3123 3124 if (RegVT == MVT::f32) 3125 RC = &ARM::SPRRegClass; 3126 else if (RegVT == MVT::f64) 3127 RC = &ARM::DPRRegClass; 3128 else if (RegVT == MVT::v2f64) 3129 RC = &ARM::QPRRegClass; 3130 else if (RegVT == MVT::i32) 3131 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3132 : &ARM::GPRRegClass; 3133 else 3134 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3135 3136 // Transform the arguments in physical registers into virtual ones. 3137 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3138 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3139 } 3140 3141 // If this is an 8 or 16-bit value, it is really passed promoted 3142 // to 32 bits. Insert an assert[sz]ext to capture this, then 3143 // truncate to the right size. 3144 switch (VA.getLocInfo()) { 3145 default: llvm_unreachable("Unknown loc info!"); 3146 case CCValAssign::Full: break; 3147 case CCValAssign::BCvt: 3148 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3149 break; 3150 case CCValAssign::SExt: 3151 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3152 DAG.getValueType(VA.getValVT())); 3153 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3154 break; 3155 case CCValAssign::ZExt: 3156 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3157 DAG.getValueType(VA.getValVT())); 3158 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3159 break; 3160 } 3161 3162 InVals.push_back(ArgValue); 3163 3164 } else { // VA.isRegLoc() 3165 3166 // sanity check 3167 assert(VA.isMemLoc()); 3168 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3169 3170 int index = ArgLocs[i].getValNo(); 3171 3172 // Some Ins[] entries become multiple ArgLoc[] entries. 3173 // Process them only once. 3174 if (index != lastInsIndex) 3175 { 3176 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3177 // FIXME: For now, all byval parameter objects are marked mutable. 3178 // This can be changed with more analysis. 3179 // In case of tail call optimization mark all arguments mutable. 3180 // Since they could be overwritten by lowering of arguments in case of 3181 // a tail call. 3182 if (Flags.isByVal()) { 3183 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3184 3185 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign()); 3186 int FrameIndex = StoreByValRegs( 3187 CCInfo, DAG, dl, Chain, CurOrigArg, 3188 CurByValIndex, 3189 Ins[VA.getValNo()].PartOffset, 3190 VA.getLocMemOffset(), 3191 Flags.getByValSize(), 3192 true /*force mutable frames*/, 3193 ByValStoreOffset, 3194 TotalArgRegsSaveSize); 3195 ByValStoreOffset += Flags.getByValSize(); 3196 ByValStoreOffset = std::min(ByValStoreOffset, 16U); 3197 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy())); 3198 CCInfo.nextInRegsParam(); 3199 } else { 3200 unsigned FIOffset = VA.getLocMemOffset(); 3201 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3202 FIOffset, true); 3203 3204 // Create load nodes to retrieve arguments from the stack. 3205 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 3206 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3207 MachinePointerInfo::getFixedStack(FI), 3208 false, false, false, 0)); 3209 } 3210 lastInsIndex = index; 3211 } 3212 } 3213 } 3214 3215 // varargs 3216 if (isVarArg && MFI->hasVAStart()) 3217 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3218 CCInfo.getNextStackOffset(), 3219 TotalArgRegsSaveSize); 3220 3221 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3222 3223 return Chain; 3224 } 3225 3226 /// isFloatingPointZero - Return true if this is +0.0. 3227 static bool isFloatingPointZero(SDValue Op) { 3228 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3229 return CFP->getValueAPF().isPosZero(); 3230 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3231 // Maybe this has already been legalized into the constant pool? 3232 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3233 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3234 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3235 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3236 return CFP->getValueAPF().isPosZero(); 3237 } 3238 } else if (Op->getOpcode() == ISD::BITCAST && 3239 Op->getValueType(0) == MVT::f64) { 3240 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3241 // created by LowerConstantFP(). 3242 SDValue BitcastOp = Op->getOperand(0); 3243 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) { 3244 SDValue MoveOp = BitcastOp->getOperand(0); 3245 if (MoveOp->getOpcode() == ISD::TargetConstant && 3246 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) { 3247 return true; 3248 } 3249 } 3250 } 3251 return false; 3252 } 3253 3254 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3255 /// the given operands. 3256 SDValue 3257 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3258 SDValue &ARMcc, SelectionDAG &DAG, 3259 SDLoc dl) const { 3260 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3261 unsigned C = RHSC->getZExtValue(); 3262 if (!isLegalICmpImmediate(C)) { 3263 // Constant does not fit, try adjusting it by one? 3264 switch (CC) { 3265 default: break; 3266 case ISD::SETLT: 3267 case ISD::SETGE: 3268 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3269 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3270 RHS = DAG.getConstant(C-1, MVT::i32); 3271 } 3272 break; 3273 case ISD::SETULT: 3274 case ISD::SETUGE: 3275 if (C != 0 && isLegalICmpImmediate(C-1)) { 3276 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3277 RHS = DAG.getConstant(C-1, MVT::i32); 3278 } 3279 break; 3280 case ISD::SETLE: 3281 case ISD::SETGT: 3282 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3283 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3284 RHS = DAG.getConstant(C+1, MVT::i32); 3285 } 3286 break; 3287 case ISD::SETULE: 3288 case ISD::SETUGT: 3289 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3290 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3291 RHS = DAG.getConstant(C+1, MVT::i32); 3292 } 3293 break; 3294 } 3295 } 3296 } 3297 3298 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3299 ARMISD::NodeType CompareType; 3300 switch (CondCode) { 3301 default: 3302 CompareType = ARMISD::CMP; 3303 break; 3304 case ARMCC::EQ: 3305 case ARMCC::NE: 3306 // Uses only Z Flag 3307 CompareType = ARMISD::CMPZ; 3308 break; 3309 } 3310 ARMcc = DAG.getConstant(CondCode, MVT::i32); 3311 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3312 } 3313 3314 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3315 SDValue 3316 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG, 3317 SDLoc dl) const { 3318 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3319 SDValue Cmp; 3320 if (!isFloatingPointZero(RHS)) 3321 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3322 else 3323 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3324 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3325 } 3326 3327 /// duplicateCmp - Glue values can have only one use, so this function 3328 /// duplicates a comparison node. 3329 SDValue 3330 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3331 unsigned Opc = Cmp.getOpcode(); 3332 SDLoc DL(Cmp); 3333 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3334 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3335 3336 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3337 Cmp = Cmp.getOperand(0); 3338 Opc = Cmp.getOpcode(); 3339 if (Opc == ARMISD::CMPFP) 3340 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3341 else { 3342 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3343 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3344 } 3345 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3346 } 3347 3348 std::pair<SDValue, SDValue> 3349 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3350 SDValue &ARMcc) const { 3351 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3352 3353 SDValue Value, OverflowCmp; 3354 SDValue LHS = Op.getOperand(0); 3355 SDValue RHS = Op.getOperand(1); 3356 3357 3358 // FIXME: We are currently always generating CMPs because we don't support 3359 // generating CMN through the backend. This is not as good as the natural 3360 // CMP case because it causes a register dependency and cannot be folded 3361 // later. 3362 3363 switch (Op.getOpcode()) { 3364 default: 3365 llvm_unreachable("Unknown overflow instruction!"); 3366 case ISD::SADDO: 3367 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32); 3368 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS); 3369 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS); 3370 break; 3371 case ISD::UADDO: 3372 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32); 3373 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS); 3374 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS); 3375 break; 3376 case ISD::SSUBO: 3377 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32); 3378 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS); 3379 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS); 3380 break; 3381 case ISD::USUBO: 3382 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32); 3383 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS); 3384 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS); 3385 break; 3386 } // switch (...) 3387 3388 return std::make_pair(Value, OverflowCmp); 3389 } 3390 3391 3392 SDValue 3393 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3394 // Let legalize expand this if it isn't a legal type yet. 3395 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3396 return SDValue(); 3397 3398 SDValue Value, OverflowCmp; 3399 SDValue ARMcc; 3400 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3401 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3402 // We use 0 and 1 as false and true values. 3403 SDValue TVal = DAG.getConstant(1, MVT::i32); 3404 SDValue FVal = DAG.getConstant(0, MVT::i32); 3405 EVT VT = Op.getValueType(); 3406 3407 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal, 3408 ARMcc, CCR, OverflowCmp); 3409 3410 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3411 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow); 3412 } 3413 3414 3415 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3416 SDValue Cond = Op.getOperand(0); 3417 SDValue SelectTrue = Op.getOperand(1); 3418 SDValue SelectFalse = Op.getOperand(2); 3419 SDLoc dl(Op); 3420 unsigned Opc = Cond.getOpcode(); 3421 3422 if (Cond.getResNo() == 1 && 3423 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3424 Opc == ISD::USUBO)) { 3425 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3426 return SDValue(); 3427 3428 SDValue Value, OverflowCmp; 3429 SDValue ARMcc; 3430 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3431 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3432 EVT VT = Op.getValueType(); 3433 3434 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR, 3435 OverflowCmp, DAG); 3436 } 3437 3438 // Convert: 3439 // 3440 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3441 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3442 // 3443 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3444 const ConstantSDNode *CMOVTrue = 3445 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3446 const ConstantSDNode *CMOVFalse = 3447 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3448 3449 if (CMOVTrue && CMOVFalse) { 3450 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3451 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3452 3453 SDValue True; 3454 SDValue False; 3455 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3456 True = SelectTrue; 3457 False = SelectFalse; 3458 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3459 True = SelectFalse; 3460 False = SelectTrue; 3461 } 3462 3463 if (True.getNode() && False.getNode()) { 3464 EVT VT = Op.getValueType(); 3465 SDValue ARMcc = Cond.getOperand(2); 3466 SDValue CCR = Cond.getOperand(3); 3467 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3468 assert(True.getValueType() == VT); 3469 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3470 } 3471 } 3472 } 3473 3474 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3475 // undefined bits before doing a full-word comparison with zero. 3476 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3477 DAG.getConstant(1, Cond.getValueType())); 3478 3479 return DAG.getSelectCC(dl, Cond, 3480 DAG.getConstant(0, Cond.getValueType()), 3481 SelectTrue, SelectFalse, ISD::SETNE); 3482 } 3483 3484 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) { 3485 if (CC == ISD::SETNE) 3486 return ISD::SETEQ; 3487 return ISD::getSetCCInverse(CC, true); 3488 } 3489 3490 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3491 bool &swpCmpOps, bool &swpVselOps) { 3492 // Start by selecting the GE condition code for opcodes that return true for 3493 // 'equality' 3494 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3495 CC == ISD::SETULE) 3496 CondCode = ARMCC::GE; 3497 3498 // and GT for opcodes that return false for 'equality'. 3499 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3500 CC == ISD::SETULT) 3501 CondCode = ARMCC::GT; 3502 3503 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3504 // to swap the compare operands. 3505 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3506 CC == ISD::SETULT) 3507 swpCmpOps = true; 3508 3509 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3510 // If we have an unordered opcode, we need to swap the operands to the VSEL 3511 // instruction (effectively negating the condition). 3512 // 3513 // This also has the effect of swapping which one of 'less' or 'greater' 3514 // returns true, so we also swap the compare operands. It also switches 3515 // whether we return true for 'equality', so we compensate by picking the 3516 // opposite condition code to our original choice. 3517 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3518 CC == ISD::SETUGT) { 3519 swpCmpOps = !swpCmpOps; 3520 swpVselOps = !swpVselOps; 3521 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3522 } 3523 3524 // 'ordered' is 'anything but unordered', so use the VS condition code and 3525 // swap the VSEL operands. 3526 if (CC == ISD::SETO) { 3527 CondCode = ARMCC::VS; 3528 swpVselOps = true; 3529 } 3530 3531 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3532 // code and swap the VSEL operands. 3533 if (CC == ISD::SETUNE) { 3534 CondCode = ARMCC::EQ; 3535 swpVselOps = true; 3536 } 3537 } 3538 3539 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal, 3540 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3541 SDValue Cmp, SelectionDAG &DAG) const { 3542 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3543 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3544 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3545 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3546 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3547 3548 SDValue TrueLow = TrueVal.getValue(0); 3549 SDValue TrueHigh = TrueVal.getValue(1); 3550 SDValue FalseLow = FalseVal.getValue(0); 3551 SDValue FalseHigh = FalseVal.getValue(1); 3552 3553 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3554 ARMcc, CCR, Cmp); 3555 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3556 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3557 3558 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3559 } else { 3560 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3561 Cmp); 3562 } 3563 } 3564 3565 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3566 EVT VT = Op.getValueType(); 3567 SDValue LHS = Op.getOperand(0); 3568 SDValue RHS = Op.getOperand(1); 3569 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3570 SDValue TrueVal = Op.getOperand(2); 3571 SDValue FalseVal = Op.getOperand(3); 3572 SDLoc dl(Op); 3573 3574 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3575 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3576 dl); 3577 3578 // If softenSetCCOperands only returned one value, we should compare it to 3579 // zero. 3580 if (!RHS.getNode()) { 3581 RHS = DAG.getConstant(0, LHS.getValueType()); 3582 CC = ISD::SETNE; 3583 } 3584 } 3585 3586 if (LHS.getValueType() == MVT::i32) { 3587 // Try to generate VSEL on ARMv8. 3588 // The VSEL instruction can't use all the usual ARM condition 3589 // codes: it only has two bits to select the condition code, so it's 3590 // constrained to use only GE, GT, VS and EQ. 3591 // 3592 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3593 // swap the operands of the previous compare instruction (effectively 3594 // inverting the compare condition, swapping 'less' and 'greater') and 3595 // sometimes need to swap the operands to the VSEL (which inverts the 3596 // condition in the sense of firing whenever the previous condition didn't) 3597 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3598 TrueVal.getValueType() == MVT::f64)) { 3599 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3600 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3601 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3602 CC = getInverseCCForVSEL(CC); 3603 std::swap(TrueVal, FalseVal); 3604 } 3605 } 3606 3607 SDValue ARMcc; 3608 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3609 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3610 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3611 } 3612 3613 ARMCC::CondCodes CondCode, CondCode2; 3614 FPCCToARMCC(CC, CondCode, CondCode2); 3615 3616 // Try to generate VSEL on ARMv8. 3617 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3618 TrueVal.getValueType() == MVT::f64)) { 3619 // We can select VMAXNM/VMINNM from a compare followed by a select with the 3620 // same operands, as follows: 3621 // c = fcmp [ogt, olt, ugt, ult] a, b 3622 // select c, a, b 3623 // We only do this in unsafe-fp-math, because signed zeros and NaNs are 3624 // handled differently than the original code sequence. 3625 if (getTargetMachine().Options.UnsafeFPMath) { 3626 if (LHS == TrueVal && RHS == FalseVal) { 3627 if (CC == ISD::SETOGT || CC == ISD::SETUGT) 3628 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal); 3629 if (CC == ISD::SETOLT || CC == ISD::SETULT) 3630 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal); 3631 } else if (LHS == FalseVal && RHS == TrueVal) { 3632 if (CC == ISD::SETOLT || CC == ISD::SETULT) 3633 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal); 3634 if (CC == ISD::SETOGT || CC == ISD::SETUGT) 3635 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal); 3636 } 3637 } 3638 3639 bool swpCmpOps = false; 3640 bool swpVselOps = false; 3641 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3642 3643 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3644 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3645 if (swpCmpOps) 3646 std::swap(LHS, RHS); 3647 if (swpVselOps) 3648 std::swap(TrueVal, FalseVal); 3649 } 3650 } 3651 3652 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32); 3653 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3654 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3655 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3656 if (CondCode2 != ARMCC::AL) { 3657 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32); 3658 // FIXME: Needs another CMP because flag can have but one use. 3659 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3660 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3661 } 3662 return Result; 3663 } 3664 3665 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3666 /// to morph to an integer compare sequence. 3667 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3668 const ARMSubtarget *Subtarget) { 3669 SDNode *N = Op.getNode(); 3670 if (!N->hasOneUse()) 3671 // Otherwise it requires moving the value from fp to integer registers. 3672 return false; 3673 if (!N->getNumValues()) 3674 return false; 3675 EVT VT = Op.getValueType(); 3676 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3677 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3678 // vmrs are very slow, e.g. cortex-a8. 3679 return false; 3680 3681 if (isFloatingPointZero(Op)) { 3682 SeenZero = true; 3683 return true; 3684 } 3685 return ISD::isNormalLoad(N); 3686 } 3687 3688 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3689 if (isFloatingPointZero(Op)) 3690 return DAG.getConstant(0, MVT::i32); 3691 3692 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3693 return DAG.getLoad(MVT::i32, SDLoc(Op), 3694 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3695 Ld->isVolatile(), Ld->isNonTemporal(), 3696 Ld->isInvariant(), Ld->getAlignment()); 3697 3698 llvm_unreachable("Unknown VFP cmp argument!"); 3699 } 3700 3701 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3702 SDValue &RetVal1, SDValue &RetVal2) { 3703 if (isFloatingPointZero(Op)) { 3704 RetVal1 = DAG.getConstant(0, MVT::i32); 3705 RetVal2 = DAG.getConstant(0, MVT::i32); 3706 return; 3707 } 3708 3709 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3710 SDValue Ptr = Ld->getBasePtr(); 3711 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op), 3712 Ld->getChain(), Ptr, 3713 Ld->getPointerInfo(), 3714 Ld->isVolatile(), Ld->isNonTemporal(), 3715 Ld->isInvariant(), Ld->getAlignment()); 3716 3717 EVT PtrType = Ptr.getValueType(); 3718 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3719 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op), 3720 PtrType, Ptr, DAG.getConstant(4, PtrType)); 3721 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op), 3722 Ld->getChain(), NewPtr, 3723 Ld->getPointerInfo().getWithOffset(4), 3724 Ld->isVolatile(), Ld->isNonTemporal(), 3725 Ld->isInvariant(), NewAlign); 3726 return; 3727 } 3728 3729 llvm_unreachable("Unknown VFP cmp argument!"); 3730 } 3731 3732 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 3733 /// f32 and even f64 comparisons to integer ones. 3734 SDValue 3735 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 3736 SDValue Chain = Op.getOperand(0); 3737 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3738 SDValue LHS = Op.getOperand(2); 3739 SDValue RHS = Op.getOperand(3); 3740 SDValue Dest = Op.getOperand(4); 3741 SDLoc dl(Op); 3742 3743 bool LHSSeenZero = false; 3744 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 3745 bool RHSSeenZero = false; 3746 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 3747 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 3748 // If unsafe fp math optimization is enabled and there are no other uses of 3749 // the CMP operands, and the condition code is EQ or NE, we can optimize it 3750 // to an integer comparison. 3751 if (CC == ISD::SETOEQ) 3752 CC = ISD::SETEQ; 3753 else if (CC == ISD::SETUNE) 3754 CC = ISD::SETNE; 3755 3756 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32); 3757 SDValue ARMcc; 3758 if (LHS.getValueType() == MVT::f32) { 3759 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3760 bitcastf32Toi32(LHS, DAG), Mask); 3761 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3762 bitcastf32Toi32(RHS, DAG), Mask); 3763 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3764 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3765 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3766 Chain, Dest, ARMcc, CCR, Cmp); 3767 } 3768 3769 SDValue LHS1, LHS2; 3770 SDValue RHS1, RHS2; 3771 expandf64Toi32(LHS, DAG, LHS1, LHS2); 3772 expandf64Toi32(RHS, DAG, RHS1, RHS2); 3773 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 3774 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 3775 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3776 ARMcc = DAG.getConstant(CondCode, MVT::i32); 3777 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3778 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 3779 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 3780 } 3781 3782 return SDValue(); 3783 } 3784 3785 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3786 SDValue Chain = Op.getOperand(0); 3787 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3788 SDValue LHS = Op.getOperand(2); 3789 SDValue RHS = Op.getOperand(3); 3790 SDValue Dest = Op.getOperand(4); 3791 SDLoc dl(Op); 3792 3793 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3794 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3795 dl); 3796 3797 // If softenSetCCOperands only returned one value, we should compare it to 3798 // zero. 3799 if (!RHS.getNode()) { 3800 RHS = DAG.getConstant(0, LHS.getValueType()); 3801 CC = ISD::SETNE; 3802 } 3803 } 3804 3805 if (LHS.getValueType() == MVT::i32) { 3806 SDValue ARMcc; 3807 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3808 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3809 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3810 Chain, Dest, ARMcc, CCR, Cmp); 3811 } 3812 3813 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3814 3815 if (getTargetMachine().Options.UnsafeFPMath && 3816 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 3817 CC == ISD::SETNE || CC == ISD::SETUNE)) { 3818 SDValue Result = OptimizeVFPBrcond(Op, DAG); 3819 if (Result.getNode()) 3820 return Result; 3821 } 3822 3823 ARMCC::CondCodes CondCode, CondCode2; 3824 FPCCToARMCC(CC, CondCode, CondCode2); 3825 3826 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32); 3827 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3828 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3829 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3830 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 3831 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3832 if (CondCode2 != ARMCC::AL) { 3833 ARMcc = DAG.getConstant(CondCode2, MVT::i32); 3834 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 3835 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3836 } 3837 return Res; 3838 } 3839 3840 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 3841 SDValue Chain = Op.getOperand(0); 3842 SDValue Table = Op.getOperand(1); 3843 SDValue Index = Op.getOperand(2); 3844 SDLoc dl(Op); 3845 3846 EVT PTy = getPointerTy(); 3847 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 3848 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3849 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy); 3850 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 3851 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId); 3852 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy)); 3853 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 3854 if (Subtarget->isThumb2()) { 3855 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 3856 // which does another jump to the destination. This also makes it easier 3857 // to translate it to TBB / TBH later. 3858 // FIXME: This might not work if the function is extremely large. 3859 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 3860 Addr, Op.getOperand(2), JTI, UId); 3861 } 3862 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 3863 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 3864 MachinePointerInfo::getJumpTable(), 3865 false, false, false, 0); 3866 Chain = Addr.getValue(1); 3867 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 3868 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId); 3869 } else { 3870 Addr = DAG.getLoad(PTy, dl, Chain, Addr, 3871 MachinePointerInfo::getJumpTable(), 3872 false, false, false, 0); 3873 Chain = Addr.getValue(1); 3874 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId); 3875 } 3876 } 3877 3878 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 3879 EVT VT = Op.getValueType(); 3880 SDLoc dl(Op); 3881 3882 if (Op.getValueType().getVectorElementType() == MVT::i32) { 3883 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 3884 return Op; 3885 return DAG.UnrollVectorOp(Op.getNode()); 3886 } 3887 3888 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 3889 "Invalid type for custom lowering!"); 3890 if (VT != MVT::v4i16) 3891 return DAG.UnrollVectorOp(Op.getNode()); 3892 3893 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 3894 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 3895 } 3896 3897 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 3898 EVT VT = Op.getValueType(); 3899 if (VT.isVector()) 3900 return LowerVectorFP_TO_INT(Op, DAG); 3901 3902 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 3903 RTLIB::Libcall LC; 3904 if (Op.getOpcode() == ISD::FP_TO_SINT) 3905 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 3906 Op.getValueType()); 3907 else 3908 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 3909 Op.getValueType()); 3910 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1, 3911 /*isSigned*/ false, SDLoc(Op)).first; 3912 } 3913 3914 SDLoc dl(Op); 3915 unsigned Opc; 3916 3917 switch (Op.getOpcode()) { 3918 default: llvm_unreachable("Invalid opcode!"); 3919 case ISD::FP_TO_SINT: 3920 Opc = ARMISD::FTOSI; 3921 break; 3922 case ISD::FP_TO_UINT: 3923 Opc = ARMISD::FTOUI; 3924 break; 3925 } 3926 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0)); 3927 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3928 } 3929 3930 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 3931 EVT VT = Op.getValueType(); 3932 SDLoc dl(Op); 3933 3934 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 3935 if (VT.getVectorElementType() == MVT::f32) 3936 return Op; 3937 return DAG.UnrollVectorOp(Op.getNode()); 3938 } 3939 3940 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 3941 "Invalid type for custom lowering!"); 3942 if (VT != MVT::v4f32) 3943 return DAG.UnrollVectorOp(Op.getNode()); 3944 3945 unsigned CastOpc; 3946 unsigned Opc; 3947 switch (Op.getOpcode()) { 3948 default: llvm_unreachable("Invalid opcode!"); 3949 case ISD::SINT_TO_FP: 3950 CastOpc = ISD::SIGN_EXTEND; 3951 Opc = ISD::SINT_TO_FP; 3952 break; 3953 case ISD::UINT_TO_FP: 3954 CastOpc = ISD::ZERO_EXTEND; 3955 Opc = ISD::UINT_TO_FP; 3956 break; 3957 } 3958 3959 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 3960 return DAG.getNode(Opc, dl, VT, Op); 3961 } 3962 3963 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 3964 EVT VT = Op.getValueType(); 3965 if (VT.isVector()) 3966 return LowerVectorINT_TO_FP(Op, DAG); 3967 3968 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 3969 RTLIB::Libcall LC; 3970 if (Op.getOpcode() == ISD::SINT_TO_FP) 3971 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 3972 Op.getValueType()); 3973 else 3974 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 3975 Op.getValueType()); 3976 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1, 3977 /*isSigned*/ false, SDLoc(Op)).first; 3978 } 3979 3980 SDLoc dl(Op); 3981 unsigned Opc; 3982 3983 switch (Op.getOpcode()) { 3984 default: llvm_unreachable("Invalid opcode!"); 3985 case ISD::SINT_TO_FP: 3986 Opc = ARMISD::SITOF; 3987 break; 3988 case ISD::UINT_TO_FP: 3989 Opc = ARMISD::UITOF; 3990 break; 3991 } 3992 3993 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0)); 3994 return DAG.getNode(Opc, dl, VT, Op); 3995 } 3996 3997 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 3998 // Implement fcopysign with a fabs and a conditional fneg. 3999 SDValue Tmp0 = Op.getOperand(0); 4000 SDValue Tmp1 = Op.getOperand(1); 4001 SDLoc dl(Op); 4002 EVT VT = Op.getValueType(); 4003 EVT SrcVT = Tmp1.getValueType(); 4004 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4005 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4006 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4007 4008 if (UseNEON) { 4009 // Use VBSL to copy the sign bit. 4010 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4011 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4012 DAG.getTargetConstant(EncodedVal, MVT::i32)); 4013 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4014 if (VT == MVT::f64) 4015 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4016 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4017 DAG.getConstant(32, MVT::i32)); 4018 else /*if (VT == MVT::f32)*/ 4019 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4020 if (SrcVT == MVT::f32) { 4021 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4022 if (VT == MVT::f64) 4023 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4024 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4025 DAG.getConstant(32, MVT::i32)); 4026 } else if (VT == MVT::f32) 4027 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4028 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4029 DAG.getConstant(32, MVT::i32)); 4030 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4031 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4032 4033 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4034 MVT::i32); 4035 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4036 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4037 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4038 4039 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4040 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4041 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4042 if (VT == MVT::f32) { 4043 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4044 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4045 DAG.getConstant(0, MVT::i32)); 4046 } else { 4047 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4048 } 4049 4050 return Res; 4051 } 4052 4053 // Bitcast operand 1 to i32. 4054 if (SrcVT == MVT::f64) 4055 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4056 Tmp1).getValue(1); 4057 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4058 4059 // Or in the signbit with integer operations. 4060 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32); 4061 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32); 4062 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4063 if (VT == MVT::f32) { 4064 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4065 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4066 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4067 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4068 } 4069 4070 // f64: Or the high part with signbit and then combine two parts. 4071 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4072 Tmp0); 4073 SDValue Lo = Tmp0.getValue(0); 4074 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4075 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4076 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4077 } 4078 4079 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4080 MachineFunction &MF = DAG.getMachineFunction(); 4081 MachineFrameInfo *MFI = MF.getFrameInfo(); 4082 MFI->setReturnAddressIsTaken(true); 4083 4084 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4085 return SDValue(); 4086 4087 EVT VT = Op.getValueType(); 4088 SDLoc dl(Op); 4089 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4090 if (Depth) { 4091 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4092 SDValue Offset = DAG.getConstant(4, MVT::i32); 4093 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4094 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4095 MachinePointerInfo(), false, false, false, 0); 4096 } 4097 4098 // Return LR, which contains the return address. Mark it an implicit live-in. 4099 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4100 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4101 } 4102 4103 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4104 const ARMBaseRegisterInfo &ARI = 4105 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4106 MachineFunction &MF = DAG.getMachineFunction(); 4107 MachineFrameInfo *MFI = MF.getFrameInfo(); 4108 MFI->setFrameAddressIsTaken(true); 4109 4110 EVT VT = Op.getValueType(); 4111 SDLoc dl(Op); // FIXME probably not meaningful 4112 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4113 unsigned FrameReg = ARI.getFrameRegister(MF); 4114 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4115 while (Depth--) 4116 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4117 MachinePointerInfo(), 4118 false, false, false, 0); 4119 return FrameAddr; 4120 } 4121 4122 // FIXME? Maybe this could be a TableGen attribute on some registers and 4123 // this table could be generated automatically from RegInfo. 4124 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, 4125 EVT VT) const { 4126 unsigned Reg = StringSwitch<unsigned>(RegName) 4127 .Case("sp", ARM::SP) 4128 .Default(0); 4129 if (Reg) 4130 return Reg; 4131 report_fatal_error("Invalid register name global variable"); 4132 } 4133 4134 /// ExpandBITCAST - If the target supports VFP, this function is called to 4135 /// expand a bit convert where either the source or destination type is i64 to 4136 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4137 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4138 /// vectors), since the legalizer won't know what to do with that. 4139 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4140 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4141 SDLoc dl(N); 4142 SDValue Op = N->getOperand(0); 4143 4144 // This function is only supposed to be called for i64 types, either as the 4145 // source or destination of the bit convert. 4146 EVT SrcVT = Op.getValueType(); 4147 EVT DstVT = N->getValueType(0); 4148 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4149 "ExpandBITCAST called for non-i64 type"); 4150 4151 // Turn i64->f64 into VMOVDRR. 4152 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4153 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4154 DAG.getConstant(0, MVT::i32)); 4155 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4156 DAG.getConstant(1, MVT::i32)); 4157 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4158 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4159 } 4160 4161 // Turn f64->i64 into VMOVRRD. 4162 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4163 SDValue Cvt; 4164 if (TLI.isBigEndian() && SrcVT.isVector() && 4165 SrcVT.getVectorNumElements() > 1) 4166 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4167 DAG.getVTList(MVT::i32, MVT::i32), 4168 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4169 else 4170 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4171 DAG.getVTList(MVT::i32, MVT::i32), Op); 4172 // Merge the pieces into a single i64 value. 4173 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4174 } 4175 4176 return SDValue(); 4177 } 4178 4179 /// getZeroVector - Returns a vector of specified type with all zero elements. 4180 /// Zero vectors are used to represent vector negation and in those cases 4181 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4182 /// not support i64 elements, so sometimes the zero vectors will need to be 4183 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4184 /// zero vector. 4185 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) { 4186 assert(VT.isVector() && "Expected a vector type"); 4187 // The canonical modified immediate encoding of a zero vector is....0! 4188 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32); 4189 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4190 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4191 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4192 } 4193 4194 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4195 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4196 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4197 SelectionDAG &DAG) const { 4198 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4199 EVT VT = Op.getValueType(); 4200 unsigned VTBits = VT.getSizeInBits(); 4201 SDLoc dl(Op); 4202 SDValue ShOpLo = Op.getOperand(0); 4203 SDValue ShOpHi = Op.getOperand(1); 4204 SDValue ShAmt = Op.getOperand(2); 4205 SDValue ARMcc; 4206 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4207 4208 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4209 4210 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4211 DAG.getConstant(VTBits, MVT::i32), ShAmt); 4212 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4213 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4214 DAG.getConstant(VTBits, MVT::i32)); 4215 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4216 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4217 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4218 4219 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4220 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE, 4221 ARMcc, DAG, dl); 4222 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4223 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4224 CCR, Cmp); 4225 4226 SDValue Ops[2] = { Lo, Hi }; 4227 return DAG.getMergeValues(Ops, dl); 4228 } 4229 4230 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4231 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4232 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4233 SelectionDAG &DAG) const { 4234 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4235 EVT VT = Op.getValueType(); 4236 unsigned VTBits = VT.getSizeInBits(); 4237 SDLoc dl(Op); 4238 SDValue ShOpLo = Op.getOperand(0); 4239 SDValue ShOpHi = Op.getOperand(1); 4240 SDValue ShAmt = Op.getOperand(2); 4241 SDValue ARMcc; 4242 4243 assert(Op.getOpcode() == ISD::SHL_PARTS); 4244 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4245 DAG.getConstant(VTBits, MVT::i32), ShAmt); 4246 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4247 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4248 DAG.getConstant(VTBits, MVT::i32)); 4249 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4250 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4251 4252 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4253 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4254 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE, 4255 ARMcc, DAG, dl); 4256 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4257 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4258 CCR, Cmp); 4259 4260 SDValue Ops[2] = { Lo, Hi }; 4261 return DAG.getMergeValues(Ops, dl); 4262 } 4263 4264 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4265 SelectionDAG &DAG) const { 4266 // The rounding mode is in bits 23:22 of the FPSCR. 4267 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4268 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4269 // so that the shift + and get folded into a bitfield extract. 4270 SDLoc dl(Op); 4271 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4272 DAG.getConstant(Intrinsic::arm_get_fpscr, 4273 MVT::i32)); 4274 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4275 DAG.getConstant(1U << 22, MVT::i32)); 4276 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4277 DAG.getConstant(22, MVT::i32)); 4278 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4279 DAG.getConstant(3, MVT::i32)); 4280 } 4281 4282 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4283 const ARMSubtarget *ST) { 4284 EVT VT = N->getValueType(0); 4285 SDLoc dl(N); 4286 4287 if (!ST->hasV6T2Ops()) 4288 return SDValue(); 4289 4290 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0)); 4291 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4292 } 4293 4294 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4295 /// for each 16-bit element from operand, repeated. The basic idea is to 4296 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4297 /// 4298 /// Trace for v4i16: 4299 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4300 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4301 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4302 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4303 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4304 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4305 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4306 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4307 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4308 EVT VT = N->getValueType(0); 4309 SDLoc DL(N); 4310 4311 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4312 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4313 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4314 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4315 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4316 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4317 } 4318 4319 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4320 /// bit-count for each 16-bit element from the operand. We need slightly 4321 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4322 /// 64/128-bit registers. 4323 /// 4324 /// Trace for v4i16: 4325 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4326 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4327 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4328 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4329 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4330 EVT VT = N->getValueType(0); 4331 SDLoc DL(N); 4332 4333 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4334 if (VT.is64BitVector()) { 4335 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4336 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4337 DAG.getIntPtrConstant(0)); 4338 } else { 4339 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4340 BitCounts, DAG.getIntPtrConstant(0)); 4341 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4342 } 4343 } 4344 4345 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4346 /// bit-count for each 32-bit element from the operand. The idea here is 4347 /// to split the vector into 16-bit elements, leverage the 16-bit count 4348 /// routine, and then combine the results. 4349 /// 4350 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4351 /// input = [v0 v1 ] (vi: 32-bit elements) 4352 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4353 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4354 /// vrev: N0 = [k1 k0 k3 k2 ] 4355 /// [k0 k1 k2 k3 ] 4356 /// N1 =+[k1 k0 k3 k2 ] 4357 /// [k0 k2 k1 k3 ] 4358 /// N2 =+[k1 k3 k0 k2 ] 4359 /// [k0 k2 k1 k3 ] 4360 /// Extended =+[k1 k3 k0 k2 ] 4361 /// [k0 k2 ] 4362 /// Extracted=+[k1 k3 ] 4363 /// 4364 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4365 EVT VT = N->getValueType(0); 4366 SDLoc DL(N); 4367 4368 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4369 4370 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4371 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4372 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4373 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4374 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4375 4376 if (VT.is64BitVector()) { 4377 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4378 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4379 DAG.getIntPtrConstant(0)); 4380 } else { 4381 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4382 DAG.getIntPtrConstant(0)); 4383 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4384 } 4385 } 4386 4387 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4388 const ARMSubtarget *ST) { 4389 EVT VT = N->getValueType(0); 4390 4391 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4392 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4393 VT == MVT::v4i16 || VT == MVT::v8i16) && 4394 "Unexpected type for custom ctpop lowering"); 4395 4396 if (VT.getVectorElementType() == MVT::i32) 4397 return lowerCTPOP32BitElements(N, DAG); 4398 else 4399 return lowerCTPOP16BitElements(N, DAG); 4400 } 4401 4402 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4403 const ARMSubtarget *ST) { 4404 EVT VT = N->getValueType(0); 4405 SDLoc dl(N); 4406 4407 if (!VT.isVector()) 4408 return SDValue(); 4409 4410 // Lower vector shifts on NEON to use VSHL. 4411 assert(ST->hasNEON() && "unexpected vector shift"); 4412 4413 // Left shifts translate directly to the vshiftu intrinsic. 4414 if (N->getOpcode() == ISD::SHL) 4415 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4416 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32), 4417 N->getOperand(0), N->getOperand(1)); 4418 4419 assert((N->getOpcode() == ISD::SRA || 4420 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4421 4422 // NEON uses the same intrinsics for both left and right shifts. For 4423 // right shifts, the shift amounts are negative, so negate the vector of 4424 // shift amounts. 4425 EVT ShiftVT = N->getOperand(1).getValueType(); 4426 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4427 getZeroVector(ShiftVT, DAG, dl), 4428 N->getOperand(1)); 4429 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4430 Intrinsic::arm_neon_vshifts : 4431 Intrinsic::arm_neon_vshiftu); 4432 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4433 DAG.getConstant(vshiftInt, MVT::i32), 4434 N->getOperand(0), NegatedCount); 4435 } 4436 4437 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4438 const ARMSubtarget *ST) { 4439 EVT VT = N->getValueType(0); 4440 SDLoc dl(N); 4441 4442 // We can get here for a node like i32 = ISD::SHL i32, i64 4443 if (VT != MVT::i64) 4444 return SDValue(); 4445 4446 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4447 "Unknown shift to lower!"); 4448 4449 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4450 if (!isa<ConstantSDNode>(N->getOperand(1)) || 4451 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1) 4452 return SDValue(); 4453 4454 // If we are in thumb mode, we don't have RRX. 4455 if (ST->isThumb1Only()) return SDValue(); 4456 4457 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4458 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4459 DAG.getConstant(0, MVT::i32)); 4460 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4461 DAG.getConstant(1, MVT::i32)); 4462 4463 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4464 // captures the result into a carry flag. 4465 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4466 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4467 4468 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4469 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4470 4471 // Merge the pieces into a single i64 value. 4472 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4473 } 4474 4475 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4476 SDValue TmpOp0, TmpOp1; 4477 bool Invert = false; 4478 bool Swap = false; 4479 unsigned Opc = 0; 4480 4481 SDValue Op0 = Op.getOperand(0); 4482 SDValue Op1 = Op.getOperand(1); 4483 SDValue CC = Op.getOperand(2); 4484 EVT VT = Op.getValueType(); 4485 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4486 SDLoc dl(Op); 4487 4488 if (Op1.getValueType().isFloatingPoint()) { 4489 switch (SetCCOpcode) { 4490 default: llvm_unreachable("Illegal FP comparison"); 4491 case ISD::SETUNE: 4492 case ISD::SETNE: Invert = true; // Fallthrough 4493 case ISD::SETOEQ: 4494 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4495 case ISD::SETOLT: 4496 case ISD::SETLT: Swap = true; // Fallthrough 4497 case ISD::SETOGT: 4498 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4499 case ISD::SETOLE: 4500 case ISD::SETLE: Swap = true; // Fallthrough 4501 case ISD::SETOGE: 4502 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4503 case ISD::SETUGE: Swap = true; // Fallthrough 4504 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4505 case ISD::SETUGT: Swap = true; // Fallthrough 4506 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4507 case ISD::SETUEQ: Invert = true; // Fallthrough 4508 case ISD::SETONE: 4509 // Expand this to (OLT | OGT). 4510 TmpOp0 = Op0; 4511 TmpOp1 = Op1; 4512 Opc = ISD::OR; 4513 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0); 4514 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1); 4515 break; 4516 case ISD::SETUO: Invert = true; // Fallthrough 4517 case ISD::SETO: 4518 // Expand this to (OLT | OGE). 4519 TmpOp0 = Op0; 4520 TmpOp1 = Op1; 4521 Opc = ISD::OR; 4522 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0); 4523 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1); 4524 break; 4525 } 4526 } else { 4527 // Integer comparisons. 4528 switch (SetCCOpcode) { 4529 default: llvm_unreachable("Illegal integer comparison"); 4530 case ISD::SETNE: Invert = true; 4531 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4532 case ISD::SETLT: Swap = true; 4533 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4534 case ISD::SETLE: Swap = true; 4535 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4536 case ISD::SETULT: Swap = true; 4537 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4538 case ISD::SETULE: Swap = true; 4539 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4540 } 4541 4542 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4543 if (Opc == ARMISD::VCEQ) { 4544 4545 SDValue AndOp; 4546 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4547 AndOp = Op0; 4548 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4549 AndOp = Op1; 4550 4551 // Ignore bitconvert. 4552 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4553 AndOp = AndOp.getOperand(0); 4554 4555 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4556 Opc = ARMISD::VTST; 4557 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0)); 4558 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1)); 4559 Invert = !Invert; 4560 } 4561 } 4562 } 4563 4564 if (Swap) 4565 std::swap(Op0, Op1); 4566 4567 // If one of the operands is a constant vector zero, attempt to fold the 4568 // comparison to a specialized compare-against-zero form. 4569 SDValue SingleOp; 4570 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4571 SingleOp = Op0; 4572 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4573 if (Opc == ARMISD::VCGE) 4574 Opc = ARMISD::VCLEZ; 4575 else if (Opc == ARMISD::VCGT) 4576 Opc = ARMISD::VCLTZ; 4577 SingleOp = Op1; 4578 } 4579 4580 SDValue Result; 4581 if (SingleOp.getNode()) { 4582 switch (Opc) { 4583 case ARMISD::VCEQ: 4584 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break; 4585 case ARMISD::VCGE: 4586 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break; 4587 case ARMISD::VCLEZ: 4588 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break; 4589 case ARMISD::VCGT: 4590 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break; 4591 case ARMISD::VCLTZ: 4592 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break; 4593 default: 4594 Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 4595 } 4596 } else { 4597 Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 4598 } 4599 4600 if (Invert) 4601 Result = DAG.getNOT(dl, Result, VT); 4602 4603 return Result; 4604 } 4605 4606 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4607 /// valid vector constant for a NEON instruction with a "modified immediate" 4608 /// operand (e.g., VMOV). If so, return the encoded value. 4609 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4610 unsigned SplatBitSize, SelectionDAG &DAG, 4611 EVT &VT, bool is128Bits, NEONModImmType type) { 4612 unsigned OpCmode, Imm; 4613 4614 // SplatBitSize is set to the smallest size that splats the vector, so a 4615 // zero vector will always have SplatBitSize == 8. However, NEON modified 4616 // immediate instructions others than VMOV do not support the 8-bit encoding 4617 // of a zero vector, and the default encoding of zero is supposed to be the 4618 // 32-bit version. 4619 if (SplatBits == 0) 4620 SplatBitSize = 32; 4621 4622 switch (SplatBitSize) { 4623 case 8: 4624 if (type != VMOVModImm) 4625 return SDValue(); 4626 // Any 1-byte value is OK. Op=0, Cmode=1110. 4627 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4628 OpCmode = 0xe; 4629 Imm = SplatBits; 4630 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4631 break; 4632 4633 case 16: 4634 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4635 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4636 if ((SplatBits & ~0xff) == 0) { 4637 // Value = 0x00nn: Op=x, Cmode=100x. 4638 OpCmode = 0x8; 4639 Imm = SplatBits; 4640 break; 4641 } 4642 if ((SplatBits & ~0xff00) == 0) { 4643 // Value = 0xnn00: Op=x, Cmode=101x. 4644 OpCmode = 0xa; 4645 Imm = SplatBits >> 8; 4646 break; 4647 } 4648 return SDValue(); 4649 4650 case 32: 4651 // NEON's 32-bit VMOV supports splat values where: 4652 // * only one byte is nonzero, or 4653 // * the least significant byte is 0xff and the second byte is nonzero, or 4654 // * the least significant 2 bytes are 0xff and the third is nonzero. 4655 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4656 if ((SplatBits & ~0xff) == 0) { 4657 // Value = 0x000000nn: Op=x, Cmode=000x. 4658 OpCmode = 0; 4659 Imm = SplatBits; 4660 break; 4661 } 4662 if ((SplatBits & ~0xff00) == 0) { 4663 // Value = 0x0000nn00: Op=x, Cmode=001x. 4664 OpCmode = 0x2; 4665 Imm = SplatBits >> 8; 4666 break; 4667 } 4668 if ((SplatBits & ~0xff0000) == 0) { 4669 // Value = 0x00nn0000: Op=x, Cmode=010x. 4670 OpCmode = 0x4; 4671 Imm = SplatBits >> 16; 4672 break; 4673 } 4674 if ((SplatBits & ~0xff000000) == 0) { 4675 // Value = 0xnn000000: Op=x, Cmode=011x. 4676 OpCmode = 0x6; 4677 Imm = SplatBits >> 24; 4678 break; 4679 } 4680 4681 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 4682 if (type == OtherModImm) return SDValue(); 4683 4684 if ((SplatBits & ~0xffff) == 0 && 4685 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 4686 // Value = 0x0000nnff: Op=x, Cmode=1100. 4687 OpCmode = 0xc; 4688 Imm = SplatBits >> 8; 4689 break; 4690 } 4691 4692 if ((SplatBits & ~0xffffff) == 0 && 4693 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 4694 // Value = 0x00nnffff: Op=x, Cmode=1101. 4695 OpCmode = 0xd; 4696 Imm = SplatBits >> 16; 4697 break; 4698 } 4699 4700 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 4701 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 4702 // VMOV.I32. A (very) minor optimization would be to replicate the value 4703 // and fall through here to test for a valid 64-bit splat. But, then the 4704 // caller would also need to check and handle the change in size. 4705 return SDValue(); 4706 4707 case 64: { 4708 if (type != VMOVModImm) 4709 return SDValue(); 4710 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 4711 uint64_t BitMask = 0xff; 4712 uint64_t Val = 0; 4713 unsigned ImmMask = 1; 4714 Imm = 0; 4715 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 4716 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 4717 Val |= BitMask; 4718 Imm |= ImmMask; 4719 } else if ((SplatBits & BitMask) != 0) { 4720 return SDValue(); 4721 } 4722 BitMask <<= 8; 4723 ImmMask <<= 1; 4724 } 4725 4726 if (DAG.getTargetLoweringInfo().isBigEndian()) 4727 // swap higher and lower 32 bit word 4728 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 4729 4730 // Op=1, Cmode=1110. 4731 OpCmode = 0x1e; 4732 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 4733 break; 4734 } 4735 4736 default: 4737 llvm_unreachable("unexpected size for isNEONModifiedImm"); 4738 } 4739 4740 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 4741 return DAG.getTargetConstant(EncodedVal, MVT::i32); 4742 } 4743 4744 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 4745 const ARMSubtarget *ST) const { 4746 if (!ST->hasVFP3()) 4747 return SDValue(); 4748 4749 bool IsDouble = Op.getValueType() == MVT::f64; 4750 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 4751 4752 // Use the default (constant pool) lowering for double constants when we have 4753 // an SP-only FPU 4754 if (IsDouble && Subtarget->isFPOnlySP()) 4755 return SDValue(); 4756 4757 // Try splatting with a VMOV.f32... 4758 APFloat FPVal = CFP->getValueAPF(); 4759 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 4760 4761 if (ImmVal != -1) { 4762 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 4763 // We have code in place to select a valid ConstantFP already, no need to 4764 // do any mangling. 4765 return Op; 4766 } 4767 4768 // It's a float and we are trying to use NEON operations where 4769 // possible. Lower it to a splat followed by an extract. 4770 SDLoc DL(Op); 4771 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32); 4772 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 4773 NewVal); 4774 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 4775 DAG.getConstant(0, MVT::i32)); 4776 } 4777 4778 // The rest of our options are NEON only, make sure that's allowed before 4779 // proceeding.. 4780 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 4781 return SDValue(); 4782 4783 EVT VMovVT; 4784 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 4785 4786 // It wouldn't really be worth bothering for doubles except for one very 4787 // important value, which does happen to match: 0.0. So make sure we don't do 4788 // anything stupid. 4789 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 4790 return SDValue(); 4791 4792 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 4793 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT, 4794 false, VMOVModImm); 4795 if (NewVal != SDValue()) { 4796 SDLoc DL(Op); 4797 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 4798 NewVal); 4799 if (IsDouble) 4800 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 4801 4802 // It's a float: cast and extract a vector element. 4803 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 4804 VecConstant); 4805 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 4806 DAG.getConstant(0, MVT::i32)); 4807 } 4808 4809 // Finally, try a VMVN.i32 4810 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT, 4811 false, VMVNModImm); 4812 if (NewVal != SDValue()) { 4813 SDLoc DL(Op); 4814 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 4815 4816 if (IsDouble) 4817 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 4818 4819 // It's a float: cast and extract a vector element. 4820 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 4821 VecConstant); 4822 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 4823 DAG.getConstant(0, MVT::i32)); 4824 } 4825 4826 return SDValue(); 4827 } 4828 4829 // check if an VEXT instruction can handle the shuffle mask when the 4830 // vector sources of the shuffle are the same. 4831 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 4832 unsigned NumElts = VT.getVectorNumElements(); 4833 4834 // Assume that the first shuffle index is not UNDEF. Fail if it is. 4835 if (M[0] < 0) 4836 return false; 4837 4838 Imm = M[0]; 4839 4840 // If this is a VEXT shuffle, the immediate value is the index of the first 4841 // element. The other shuffle indices must be the successive elements after 4842 // the first one. 4843 unsigned ExpectedElt = Imm; 4844 for (unsigned i = 1; i < NumElts; ++i) { 4845 // Increment the expected index. If it wraps around, just follow it 4846 // back to index zero and keep going. 4847 ++ExpectedElt; 4848 if (ExpectedElt == NumElts) 4849 ExpectedElt = 0; 4850 4851 if (M[i] < 0) continue; // ignore UNDEF indices 4852 if (ExpectedElt != static_cast<unsigned>(M[i])) 4853 return false; 4854 } 4855 4856 return true; 4857 } 4858 4859 4860 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 4861 bool &ReverseVEXT, unsigned &Imm) { 4862 unsigned NumElts = VT.getVectorNumElements(); 4863 ReverseVEXT = false; 4864 4865 // Assume that the first shuffle index is not UNDEF. Fail if it is. 4866 if (M[0] < 0) 4867 return false; 4868 4869 Imm = M[0]; 4870 4871 // If this is a VEXT shuffle, the immediate value is the index of the first 4872 // element. The other shuffle indices must be the successive elements after 4873 // the first one. 4874 unsigned ExpectedElt = Imm; 4875 for (unsigned i = 1; i < NumElts; ++i) { 4876 // Increment the expected index. If it wraps around, it may still be 4877 // a VEXT but the source vectors must be swapped. 4878 ExpectedElt += 1; 4879 if (ExpectedElt == NumElts * 2) { 4880 ExpectedElt = 0; 4881 ReverseVEXT = true; 4882 } 4883 4884 if (M[i] < 0) continue; // ignore UNDEF indices 4885 if (ExpectedElt != static_cast<unsigned>(M[i])) 4886 return false; 4887 } 4888 4889 // Adjust the index value if the source operands will be swapped. 4890 if (ReverseVEXT) 4891 Imm -= NumElts; 4892 4893 return true; 4894 } 4895 4896 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 4897 /// instruction with the specified blocksize. (The order of the elements 4898 /// within each block of the vector is reversed.) 4899 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 4900 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 4901 "Only possible block sizes for VREV are: 16, 32, 64"); 4902 4903 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4904 if (EltSz == 64) 4905 return false; 4906 4907 unsigned NumElts = VT.getVectorNumElements(); 4908 unsigned BlockElts = M[0] + 1; 4909 // If the first shuffle index is UNDEF, be optimistic. 4910 if (M[0] < 0) 4911 BlockElts = BlockSize / EltSz; 4912 4913 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 4914 return false; 4915 4916 for (unsigned i = 0; i < NumElts; ++i) { 4917 if (M[i] < 0) continue; // ignore UNDEF indices 4918 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 4919 return false; 4920 } 4921 4922 return true; 4923 } 4924 4925 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 4926 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 4927 // range, then 0 is placed into the resulting vector. So pretty much any mask 4928 // of 8 elements can work here. 4929 return VT == MVT::v8i8 && M.size() == 8; 4930 } 4931 4932 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 4933 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4934 if (EltSz == 64) 4935 return false; 4936 4937 unsigned NumElts = VT.getVectorNumElements(); 4938 WhichResult = (M[0] == 0 ? 0 : 1); 4939 for (unsigned i = 0; i < NumElts; i += 2) { 4940 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) || 4941 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult)) 4942 return false; 4943 } 4944 return true; 4945 } 4946 4947 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 4948 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 4949 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 4950 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 4951 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4952 if (EltSz == 64) 4953 return false; 4954 4955 unsigned NumElts = VT.getVectorNumElements(); 4956 WhichResult = (M[0] == 0 ? 0 : 1); 4957 for (unsigned i = 0; i < NumElts; i += 2) { 4958 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) || 4959 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult)) 4960 return false; 4961 } 4962 return true; 4963 } 4964 4965 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 4966 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4967 if (EltSz == 64) 4968 return false; 4969 4970 unsigned NumElts = VT.getVectorNumElements(); 4971 WhichResult = (M[0] == 0 ? 0 : 1); 4972 for (unsigned i = 0; i != NumElts; ++i) { 4973 if (M[i] < 0) continue; // ignore UNDEF indices 4974 if ((unsigned) M[i] != 2 * i + WhichResult) 4975 return false; 4976 } 4977 4978 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 4979 if (VT.is64BitVector() && EltSz == 32) 4980 return false; 4981 4982 return true; 4983 } 4984 4985 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 4986 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 4987 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 4988 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 4989 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4990 if (EltSz == 64) 4991 return false; 4992 4993 unsigned Half = VT.getVectorNumElements() / 2; 4994 WhichResult = (M[0] == 0 ? 0 : 1); 4995 for (unsigned j = 0; j != 2; ++j) { 4996 unsigned Idx = WhichResult; 4997 for (unsigned i = 0; i != Half; ++i) { 4998 int MIdx = M[i + j * Half]; 4999 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5000 return false; 5001 Idx += 2; 5002 } 5003 } 5004 5005 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5006 if (VT.is64BitVector() && EltSz == 32) 5007 return false; 5008 5009 return true; 5010 } 5011 5012 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5013 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5014 if (EltSz == 64) 5015 return false; 5016 5017 unsigned NumElts = VT.getVectorNumElements(); 5018 WhichResult = (M[0] == 0 ? 0 : 1); 5019 unsigned Idx = WhichResult * NumElts / 2; 5020 for (unsigned i = 0; i != NumElts; i += 2) { 5021 if ((M[i] >= 0 && (unsigned) M[i] != Idx) || 5022 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts)) 5023 return false; 5024 Idx += 1; 5025 } 5026 5027 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5028 if (VT.is64BitVector() && EltSz == 32) 5029 return false; 5030 5031 return true; 5032 } 5033 5034 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5035 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5036 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5037 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5038 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5039 if (EltSz == 64) 5040 return false; 5041 5042 unsigned NumElts = VT.getVectorNumElements(); 5043 WhichResult = (M[0] == 0 ? 0 : 1); 5044 unsigned Idx = WhichResult * NumElts / 2; 5045 for (unsigned i = 0; i != NumElts; i += 2) { 5046 if ((M[i] >= 0 && (unsigned) M[i] != Idx) || 5047 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx)) 5048 return false; 5049 Idx += 1; 5050 } 5051 5052 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5053 if (VT.is64BitVector() && EltSz == 32) 5054 return false; 5055 5056 return true; 5057 } 5058 5059 /// \return true if this is a reverse operation on an vector. 5060 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5061 unsigned NumElts = VT.getVectorNumElements(); 5062 // Make sure the mask has the right size. 5063 if (NumElts != M.size()) 5064 return false; 5065 5066 // Look for <15, ..., 3, -1, 1, 0>. 5067 for (unsigned i = 0; i != NumElts; ++i) 5068 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5069 return false; 5070 5071 return true; 5072 } 5073 5074 // If N is an integer constant that can be moved into a register in one 5075 // instruction, return an SDValue of such a constant (will become a MOV 5076 // instruction). Otherwise return null. 5077 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5078 const ARMSubtarget *ST, SDLoc dl) { 5079 uint64_t Val; 5080 if (!isa<ConstantSDNode>(N)) 5081 return SDValue(); 5082 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5083 5084 if (ST->isThumb1Only()) { 5085 if (Val <= 255 || ~Val <= 255) 5086 return DAG.getConstant(Val, MVT::i32); 5087 } else { 5088 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5089 return DAG.getConstant(Val, MVT::i32); 5090 } 5091 return SDValue(); 5092 } 5093 5094 // If this is a case we can't handle, return null and let the default 5095 // expansion code take care of it. 5096 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5097 const ARMSubtarget *ST) const { 5098 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5099 SDLoc dl(Op); 5100 EVT VT = Op.getValueType(); 5101 5102 APInt SplatBits, SplatUndef; 5103 unsigned SplatBitSize; 5104 bool HasAnyUndefs; 5105 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5106 if (SplatBitSize <= 64) { 5107 // Check if an immediate VMOV works. 5108 EVT VmovVT; 5109 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5110 SplatUndef.getZExtValue(), SplatBitSize, 5111 DAG, VmovVT, VT.is128BitVector(), 5112 VMOVModImm); 5113 if (Val.getNode()) { 5114 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5115 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5116 } 5117 5118 // Try an immediate VMVN. 5119 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5120 Val = isNEONModifiedImm(NegatedImm, 5121 SplatUndef.getZExtValue(), SplatBitSize, 5122 DAG, VmovVT, VT.is128BitVector(), 5123 VMVNModImm); 5124 if (Val.getNode()) { 5125 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5126 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5127 } 5128 5129 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5130 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5131 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5132 if (ImmVal != -1) { 5133 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32); 5134 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5135 } 5136 } 5137 } 5138 } 5139 5140 // Scan through the operands to see if only one value is used. 5141 // 5142 // As an optimisation, even if more than one value is used it may be more 5143 // profitable to splat with one value then change some lanes. 5144 // 5145 // Heuristically we decide to do this if the vector has a "dominant" value, 5146 // defined as splatted to more than half of the lanes. 5147 unsigned NumElts = VT.getVectorNumElements(); 5148 bool isOnlyLowElement = true; 5149 bool usesOnlyOneValue = true; 5150 bool hasDominantValue = false; 5151 bool isConstant = true; 5152 5153 // Map of the number of times a particular SDValue appears in the 5154 // element list. 5155 DenseMap<SDValue, unsigned> ValueCounts; 5156 SDValue Value; 5157 for (unsigned i = 0; i < NumElts; ++i) { 5158 SDValue V = Op.getOperand(i); 5159 if (V.getOpcode() == ISD::UNDEF) 5160 continue; 5161 if (i > 0) 5162 isOnlyLowElement = false; 5163 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5164 isConstant = false; 5165 5166 ValueCounts.insert(std::make_pair(V, 0)); 5167 unsigned &Count = ValueCounts[V]; 5168 5169 // Is this value dominant? (takes up more than half of the lanes) 5170 if (++Count > (NumElts / 2)) { 5171 hasDominantValue = true; 5172 Value = V; 5173 } 5174 } 5175 if (ValueCounts.size() != 1) 5176 usesOnlyOneValue = false; 5177 if (!Value.getNode() && ValueCounts.size() > 0) 5178 Value = ValueCounts.begin()->first; 5179 5180 if (ValueCounts.size() == 0) 5181 return DAG.getUNDEF(VT); 5182 5183 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5184 // Keep going if we are hitting this case. 5185 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5186 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5187 5188 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5189 5190 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5191 // i32 and try again. 5192 if (hasDominantValue && EltSize <= 32) { 5193 if (!isConstant) { 5194 SDValue N; 5195 5196 // If we are VDUPing a value that comes directly from a vector, that will 5197 // cause an unnecessary move to and from a GPR, where instead we could 5198 // just use VDUPLANE. We can only do this if the lane being extracted 5199 // is at a constant index, as the VDUP from lane instructions only have 5200 // constant-index forms. 5201 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5202 isa<ConstantSDNode>(Value->getOperand(1))) { 5203 // We need to create a new undef vector to use for the VDUPLANE if the 5204 // size of the vector from which we get the value is different than the 5205 // size of the vector that we need to create. We will insert the element 5206 // such that the register coalescer will remove unnecessary copies. 5207 if (VT != Value->getOperand(0).getValueType()) { 5208 ConstantSDNode *constIndex; 5209 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)); 5210 assert(constIndex && "The index is not a constant!"); 5211 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5212 VT.getVectorNumElements(); 5213 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5214 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5215 Value, DAG.getConstant(index, MVT::i32)), 5216 DAG.getConstant(index, MVT::i32)); 5217 } else 5218 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5219 Value->getOperand(0), Value->getOperand(1)); 5220 } else 5221 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5222 5223 if (!usesOnlyOneValue) { 5224 // The dominant value was splatted as 'N', but we now have to insert 5225 // all differing elements. 5226 for (unsigned I = 0; I < NumElts; ++I) { 5227 if (Op.getOperand(I) == Value) 5228 continue; 5229 SmallVector<SDValue, 3> Ops; 5230 Ops.push_back(N); 5231 Ops.push_back(Op.getOperand(I)); 5232 Ops.push_back(DAG.getConstant(I, MVT::i32)); 5233 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5234 } 5235 } 5236 return N; 5237 } 5238 if (VT.getVectorElementType().isFloatingPoint()) { 5239 SmallVector<SDValue, 8> Ops; 5240 for (unsigned i = 0; i < NumElts; ++i) 5241 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5242 Op.getOperand(i))); 5243 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5244 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 5245 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5246 if (Val.getNode()) 5247 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5248 } 5249 if (usesOnlyOneValue) { 5250 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5251 if (isConstant && Val.getNode()) 5252 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5253 } 5254 } 5255 5256 // If all elements are constants and the case above didn't get hit, fall back 5257 // to the default expansion, which will generate a load from the constant 5258 // pool. 5259 if (isConstant) 5260 return SDValue(); 5261 5262 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5263 if (NumElts >= 4) { 5264 SDValue shuffle = ReconstructShuffle(Op, DAG); 5265 if (shuffle != SDValue()) 5266 return shuffle; 5267 } 5268 5269 // Vectors with 32- or 64-bit elements can be built by directly assigning 5270 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5271 // will be legalized. 5272 if (EltSize >= 32) { 5273 // Do the expansion with floating-point types, since that is what the VFP 5274 // registers are defined to use, and since i64 is not legal. 5275 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5276 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5277 SmallVector<SDValue, 8> Ops; 5278 for (unsigned i = 0; i < NumElts; ++i) 5279 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5280 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5281 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5282 } 5283 5284 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5285 // know the default expansion would otherwise fall back on something even 5286 // worse. For a vector with one or two non-undef values, that's 5287 // scalar_to_vector for the elements followed by a shuffle (provided the 5288 // shuffle is valid for the target) and materialization element by element 5289 // on the stack followed by a load for everything else. 5290 if (!isConstant && !usesOnlyOneValue) { 5291 SDValue Vec = DAG.getUNDEF(VT); 5292 for (unsigned i = 0 ; i < NumElts; ++i) { 5293 SDValue V = Op.getOperand(i); 5294 if (V.getOpcode() == ISD::UNDEF) 5295 continue; 5296 SDValue LaneIdx = DAG.getConstant(i, MVT::i32); 5297 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5298 } 5299 return Vec; 5300 } 5301 5302 return SDValue(); 5303 } 5304 5305 // Gather data to see if the operation can be modelled as a 5306 // shuffle in combination with VEXTs. 5307 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5308 SelectionDAG &DAG) const { 5309 SDLoc dl(Op); 5310 EVT VT = Op.getValueType(); 5311 unsigned NumElts = VT.getVectorNumElements(); 5312 5313 SmallVector<SDValue, 2> SourceVecs; 5314 SmallVector<unsigned, 2> MinElts; 5315 SmallVector<unsigned, 2> MaxElts; 5316 5317 for (unsigned i = 0; i < NumElts; ++i) { 5318 SDValue V = Op.getOperand(i); 5319 if (V.getOpcode() == ISD::UNDEF) 5320 continue; 5321 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5322 // A shuffle can only come from building a vector from various 5323 // elements of other vectors. 5324 return SDValue(); 5325 } else if (V.getOperand(0).getValueType().getVectorElementType() != 5326 VT.getVectorElementType()) { 5327 // This code doesn't know how to handle shuffles where the vector 5328 // element types do not match (this happens because type legalization 5329 // promotes the return type of EXTRACT_VECTOR_ELT). 5330 // FIXME: It might be appropriate to extend this code to handle 5331 // mismatched types. 5332 return SDValue(); 5333 } 5334 5335 // Record this extraction against the appropriate vector if possible... 5336 SDValue SourceVec = V.getOperand(0); 5337 // If the element number isn't a constant, we can't effectively 5338 // analyze what's going on. 5339 if (!isa<ConstantSDNode>(V.getOperand(1))) 5340 return SDValue(); 5341 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5342 bool FoundSource = false; 5343 for (unsigned j = 0; j < SourceVecs.size(); ++j) { 5344 if (SourceVecs[j] == SourceVec) { 5345 if (MinElts[j] > EltNo) 5346 MinElts[j] = EltNo; 5347 if (MaxElts[j] < EltNo) 5348 MaxElts[j] = EltNo; 5349 FoundSource = true; 5350 break; 5351 } 5352 } 5353 5354 // Or record a new source if not... 5355 if (!FoundSource) { 5356 SourceVecs.push_back(SourceVec); 5357 MinElts.push_back(EltNo); 5358 MaxElts.push_back(EltNo); 5359 } 5360 } 5361 5362 // Currently only do something sane when at most two source vectors 5363 // involved. 5364 if (SourceVecs.size() > 2) 5365 return SDValue(); 5366 5367 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) }; 5368 int VEXTOffsets[2] = {0, 0}; 5369 5370 // This loop extracts the usage patterns of the source vectors 5371 // and prepares appropriate SDValues for a shuffle if possible. 5372 for (unsigned i = 0; i < SourceVecs.size(); ++i) { 5373 if (SourceVecs[i].getValueType() == VT) { 5374 // No VEXT necessary 5375 ShuffleSrcs[i] = SourceVecs[i]; 5376 VEXTOffsets[i] = 0; 5377 continue; 5378 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) { 5379 // It probably isn't worth padding out a smaller vector just to 5380 // break it down again in a shuffle. 5381 return SDValue(); 5382 } 5383 5384 // Since only 64-bit and 128-bit vectors are legal on ARM and 5385 // we've eliminated the other cases... 5386 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts && 5387 "unexpected vector sizes in ReconstructShuffle"); 5388 5389 if (MaxElts[i] - MinElts[i] >= NumElts) { 5390 // Span too large for a VEXT to cope 5391 return SDValue(); 5392 } 5393 5394 if (MinElts[i] >= NumElts) { 5395 // The extraction can just take the second half 5396 VEXTOffsets[i] = NumElts; 5397 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5398 SourceVecs[i], 5399 DAG.getIntPtrConstant(NumElts)); 5400 } else if (MaxElts[i] < NumElts) { 5401 // The extraction can just take the first half 5402 VEXTOffsets[i] = 0; 5403 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5404 SourceVecs[i], 5405 DAG.getIntPtrConstant(0)); 5406 } else { 5407 // An actual VEXT is needed 5408 VEXTOffsets[i] = MinElts[i]; 5409 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5410 SourceVecs[i], 5411 DAG.getIntPtrConstant(0)); 5412 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5413 SourceVecs[i], 5414 DAG.getIntPtrConstant(NumElts)); 5415 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2, 5416 DAG.getConstant(VEXTOffsets[i], MVT::i32)); 5417 } 5418 } 5419 5420 SmallVector<int, 8> Mask; 5421 5422 for (unsigned i = 0; i < NumElts; ++i) { 5423 SDValue Entry = Op.getOperand(i); 5424 if (Entry.getOpcode() == ISD::UNDEF) { 5425 Mask.push_back(-1); 5426 continue; 5427 } 5428 5429 SDValue ExtractVec = Entry.getOperand(0); 5430 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i) 5431 .getOperand(1))->getSExtValue(); 5432 if (ExtractVec == SourceVecs[0]) { 5433 Mask.push_back(ExtractElt - VEXTOffsets[0]); 5434 } else { 5435 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]); 5436 } 5437 } 5438 5439 // Final check before we try to produce nonsense... 5440 if (isShuffleMaskLegal(Mask, VT)) 5441 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1], 5442 &Mask[0]); 5443 5444 return SDValue(); 5445 } 5446 5447 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5448 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5449 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5450 /// are assumed to be legal. 5451 bool 5452 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5453 EVT VT) const { 5454 if (VT.getVectorNumElements() == 4 && 5455 (VT.is128BitVector() || VT.is64BitVector())) { 5456 unsigned PFIndexes[4]; 5457 for (unsigned i = 0; i != 4; ++i) { 5458 if (M[i] < 0) 5459 PFIndexes[i] = 8; 5460 else 5461 PFIndexes[i] = M[i]; 5462 } 5463 5464 // Compute the index in the perfect shuffle table. 5465 unsigned PFTableIndex = 5466 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5467 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5468 unsigned Cost = (PFEntry >> 30); 5469 5470 if (Cost <= 4) 5471 return true; 5472 } 5473 5474 bool ReverseVEXT; 5475 unsigned Imm, WhichResult; 5476 5477 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5478 return (EltSize >= 32 || 5479 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5480 isVREVMask(M, VT, 64) || 5481 isVREVMask(M, VT, 32) || 5482 isVREVMask(M, VT, 16) || 5483 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5484 isVTBLMask(M, VT) || 5485 isVTRNMask(M, VT, WhichResult) || 5486 isVUZPMask(M, VT, WhichResult) || 5487 isVZIPMask(M, VT, WhichResult) || 5488 isVTRN_v_undef_Mask(M, VT, WhichResult) || 5489 isVUZP_v_undef_Mask(M, VT, WhichResult) || 5490 isVZIP_v_undef_Mask(M, VT, WhichResult) || 5491 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5492 } 5493 5494 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5495 /// the specified operations to build the shuffle. 5496 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5497 SDValue RHS, SelectionDAG &DAG, 5498 SDLoc dl) { 5499 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5500 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5501 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5502 5503 enum { 5504 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5505 OP_VREV, 5506 OP_VDUP0, 5507 OP_VDUP1, 5508 OP_VDUP2, 5509 OP_VDUP3, 5510 OP_VEXT1, 5511 OP_VEXT2, 5512 OP_VEXT3, 5513 OP_VUZPL, // VUZP, left result 5514 OP_VUZPR, // VUZP, right result 5515 OP_VZIPL, // VZIP, left result 5516 OP_VZIPR, // VZIP, right result 5517 OP_VTRNL, // VTRN, left result 5518 OP_VTRNR // VTRN, right result 5519 }; 5520 5521 if (OpNum == OP_COPY) { 5522 if (LHSID == (1*9+2)*9+3) return LHS; 5523 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 5524 return RHS; 5525 } 5526 5527 SDValue OpLHS, OpRHS; 5528 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5529 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5530 EVT VT = OpLHS.getValueType(); 5531 5532 switch (OpNum) { 5533 default: llvm_unreachable("Unknown shuffle opcode!"); 5534 case OP_VREV: 5535 // VREV divides the vector in half and swaps within the half. 5536 if (VT.getVectorElementType() == MVT::i32 || 5537 VT.getVectorElementType() == MVT::f32) 5538 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 5539 // vrev <4 x i16> -> VREV32 5540 if (VT.getVectorElementType() == MVT::i16) 5541 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 5542 // vrev <4 x i8> -> VREV16 5543 assert(VT.getVectorElementType() == MVT::i8); 5544 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 5545 case OP_VDUP0: 5546 case OP_VDUP1: 5547 case OP_VDUP2: 5548 case OP_VDUP3: 5549 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5550 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32)); 5551 case OP_VEXT1: 5552 case OP_VEXT2: 5553 case OP_VEXT3: 5554 return DAG.getNode(ARMISD::VEXT, dl, VT, 5555 OpLHS, OpRHS, 5556 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32)); 5557 case OP_VUZPL: 5558 case OP_VUZPR: 5559 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 5560 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 5561 case OP_VZIPL: 5562 case OP_VZIPR: 5563 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 5564 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 5565 case OP_VTRNL: 5566 case OP_VTRNR: 5567 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 5568 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 5569 } 5570 } 5571 5572 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 5573 ArrayRef<int> ShuffleMask, 5574 SelectionDAG &DAG) { 5575 // Check to see if we can use the VTBL instruction. 5576 SDValue V1 = Op.getOperand(0); 5577 SDValue V2 = Op.getOperand(1); 5578 SDLoc DL(Op); 5579 5580 SmallVector<SDValue, 8> VTBLMask; 5581 for (ArrayRef<int>::iterator 5582 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 5583 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32)); 5584 5585 if (V2.getNode()->getOpcode() == ISD::UNDEF) 5586 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 5587 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 5588 5589 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 5590 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 5591 } 5592 5593 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 5594 SelectionDAG &DAG) { 5595 SDLoc DL(Op); 5596 SDValue OpLHS = Op.getOperand(0); 5597 EVT VT = OpLHS.getValueType(); 5598 5599 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 5600 "Expect an v8i16/v16i8 type"); 5601 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 5602 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 5603 // extract the first 8 bytes into the top double word and the last 8 bytes 5604 // into the bottom double word. The v8i16 case is similar. 5605 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 5606 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 5607 DAG.getConstant(ExtractNum, MVT::i32)); 5608 } 5609 5610 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 5611 SDValue V1 = Op.getOperand(0); 5612 SDValue V2 = Op.getOperand(1); 5613 SDLoc dl(Op); 5614 EVT VT = Op.getValueType(); 5615 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 5616 5617 // Convert shuffles that are directly supported on NEON to target-specific 5618 // DAG nodes, instead of keeping them as shuffles and matching them again 5619 // during code selection. This is more efficient and avoids the possibility 5620 // of inconsistencies between legalization and selection. 5621 // FIXME: floating-point vectors should be canonicalized to integer vectors 5622 // of the same time so that they get CSEd properly. 5623 ArrayRef<int> ShuffleMask = SVN->getMask(); 5624 5625 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5626 if (EltSize <= 32) { 5627 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 5628 int Lane = SVN->getSplatIndex(); 5629 // If this is undef splat, generate it via "just" vdup, if possible. 5630 if (Lane == -1) Lane = 0; 5631 5632 // Test if V1 is a SCALAR_TO_VECTOR. 5633 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5634 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 5635 } 5636 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 5637 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 5638 // reaches it). 5639 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 5640 !isa<ConstantSDNode>(V1.getOperand(0))) { 5641 bool IsScalarToVector = true; 5642 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 5643 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) { 5644 IsScalarToVector = false; 5645 break; 5646 } 5647 if (IsScalarToVector) 5648 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 5649 } 5650 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 5651 DAG.getConstant(Lane, MVT::i32)); 5652 } 5653 5654 bool ReverseVEXT; 5655 unsigned Imm; 5656 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 5657 if (ReverseVEXT) 5658 std::swap(V1, V2); 5659 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 5660 DAG.getConstant(Imm, MVT::i32)); 5661 } 5662 5663 if (isVREVMask(ShuffleMask, VT, 64)) 5664 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 5665 if (isVREVMask(ShuffleMask, VT, 32)) 5666 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 5667 if (isVREVMask(ShuffleMask, VT, 16)) 5668 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 5669 5670 if (V2->getOpcode() == ISD::UNDEF && 5671 isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 5672 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 5673 DAG.getConstant(Imm, MVT::i32)); 5674 } 5675 5676 // Check for Neon shuffles that modify both input vectors in place. 5677 // If both results are used, i.e., if there are two shuffles with the same 5678 // source operands and with masks corresponding to both results of one of 5679 // these operations, DAG memoization will ensure that a single node is 5680 // used for both shuffles. 5681 unsigned WhichResult; 5682 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5683 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 5684 V1, V2).getValue(WhichResult); 5685 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5686 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 5687 V1, V2).getValue(WhichResult); 5688 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5689 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 5690 V1, V2).getValue(WhichResult); 5691 5692 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5693 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 5694 V1, V1).getValue(WhichResult); 5695 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5696 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 5697 V1, V1).getValue(WhichResult); 5698 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5699 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 5700 V1, V1).getValue(WhichResult); 5701 } 5702 5703 // If the shuffle is not directly supported and it has 4 elements, use 5704 // the PerfectShuffle-generated table to synthesize it from other shuffles. 5705 unsigned NumElts = VT.getVectorNumElements(); 5706 if (NumElts == 4) { 5707 unsigned PFIndexes[4]; 5708 for (unsigned i = 0; i != 4; ++i) { 5709 if (ShuffleMask[i] < 0) 5710 PFIndexes[i] = 8; 5711 else 5712 PFIndexes[i] = ShuffleMask[i]; 5713 } 5714 5715 // Compute the index in the perfect shuffle table. 5716 unsigned PFTableIndex = 5717 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5718 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5719 unsigned Cost = (PFEntry >> 30); 5720 5721 if (Cost <= 4) 5722 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 5723 } 5724 5725 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 5726 if (EltSize >= 32) { 5727 // Do the expansion with floating-point types, since that is what the VFP 5728 // registers are defined to use, and since i64 is not legal. 5729 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5730 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5731 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 5732 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 5733 SmallVector<SDValue, 8> Ops; 5734 for (unsigned i = 0; i < NumElts; ++i) { 5735 if (ShuffleMask[i] < 0) 5736 Ops.push_back(DAG.getUNDEF(EltVT)); 5737 else 5738 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 5739 ShuffleMask[i] < (int)NumElts ? V1 : V2, 5740 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 5741 MVT::i32))); 5742 } 5743 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5744 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5745 } 5746 5747 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 5748 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 5749 5750 if (VT == MVT::v8i8) { 5751 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG); 5752 if (NewOp.getNode()) 5753 return NewOp; 5754 } 5755 5756 return SDValue(); 5757 } 5758 5759 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 5760 // INSERT_VECTOR_ELT is legal only for immediate indexes. 5761 SDValue Lane = Op.getOperand(2); 5762 if (!isa<ConstantSDNode>(Lane)) 5763 return SDValue(); 5764 5765 return Op; 5766 } 5767 5768 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 5769 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 5770 SDValue Lane = Op.getOperand(1); 5771 if (!isa<ConstantSDNode>(Lane)) 5772 return SDValue(); 5773 5774 SDValue Vec = Op.getOperand(0); 5775 if (Op.getValueType() == MVT::i32 && 5776 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 5777 SDLoc dl(Op); 5778 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 5779 } 5780 5781 return Op; 5782 } 5783 5784 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5785 // The only time a CONCAT_VECTORS operation can have legal types is when 5786 // two 64-bit vectors are concatenated to a 128-bit vector. 5787 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 5788 "unexpected CONCAT_VECTORS"); 5789 SDLoc dl(Op); 5790 SDValue Val = DAG.getUNDEF(MVT::v2f64); 5791 SDValue Op0 = Op.getOperand(0); 5792 SDValue Op1 = Op.getOperand(1); 5793 if (Op0.getOpcode() != ISD::UNDEF) 5794 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 5795 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 5796 DAG.getIntPtrConstant(0)); 5797 if (Op1.getOpcode() != ISD::UNDEF) 5798 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 5799 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 5800 DAG.getIntPtrConstant(1)); 5801 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 5802 } 5803 5804 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 5805 /// element has been zero/sign-extended, depending on the isSigned parameter, 5806 /// from an integer type half its size. 5807 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 5808 bool isSigned) { 5809 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 5810 EVT VT = N->getValueType(0); 5811 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 5812 SDNode *BVN = N->getOperand(0).getNode(); 5813 if (BVN->getValueType(0) != MVT::v4i32 || 5814 BVN->getOpcode() != ISD::BUILD_VECTOR) 5815 return false; 5816 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0; 5817 unsigned HiElt = 1 - LoElt; 5818 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 5819 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 5820 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 5821 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 5822 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 5823 return false; 5824 if (isSigned) { 5825 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 5826 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 5827 return true; 5828 } else { 5829 if (Hi0->isNullValue() && Hi1->isNullValue()) 5830 return true; 5831 } 5832 return false; 5833 } 5834 5835 if (N->getOpcode() != ISD::BUILD_VECTOR) 5836 return false; 5837 5838 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 5839 SDNode *Elt = N->getOperand(i).getNode(); 5840 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 5841 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5842 unsigned HalfSize = EltSize / 2; 5843 if (isSigned) { 5844 if (!isIntN(HalfSize, C->getSExtValue())) 5845 return false; 5846 } else { 5847 if (!isUIntN(HalfSize, C->getZExtValue())) 5848 return false; 5849 } 5850 continue; 5851 } 5852 return false; 5853 } 5854 5855 return true; 5856 } 5857 5858 /// isSignExtended - Check if a node is a vector value that is sign-extended 5859 /// or a constant BUILD_VECTOR with sign-extended elements. 5860 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 5861 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 5862 return true; 5863 if (isExtendedBUILD_VECTOR(N, DAG, true)) 5864 return true; 5865 return false; 5866 } 5867 5868 /// isZeroExtended - Check if a node is a vector value that is zero-extended 5869 /// or a constant BUILD_VECTOR with zero-extended elements. 5870 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 5871 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 5872 return true; 5873 if (isExtendedBUILD_VECTOR(N, DAG, false)) 5874 return true; 5875 return false; 5876 } 5877 5878 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 5879 if (OrigVT.getSizeInBits() >= 64) 5880 return OrigVT; 5881 5882 assert(OrigVT.isSimple() && "Expecting a simple value type"); 5883 5884 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 5885 switch (OrigSimpleTy) { 5886 default: llvm_unreachable("Unexpected Vector Type"); 5887 case MVT::v2i8: 5888 case MVT::v2i16: 5889 return MVT::v2i32; 5890 case MVT::v4i8: 5891 return MVT::v4i16; 5892 } 5893 } 5894 5895 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 5896 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 5897 /// We insert the required extension here to get the vector to fill a D register. 5898 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 5899 const EVT &OrigTy, 5900 const EVT &ExtTy, 5901 unsigned ExtOpcode) { 5902 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 5903 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 5904 // 64-bits we need to insert a new extension so that it will be 64-bits. 5905 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 5906 if (OrigTy.getSizeInBits() >= 64) 5907 return N; 5908 5909 // Must extend size to at least 64 bits to be used as an operand for VMULL. 5910 EVT NewVT = getExtensionTo64Bits(OrigTy); 5911 5912 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 5913 } 5914 5915 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 5916 /// does not do any sign/zero extension. If the original vector is less 5917 /// than 64 bits, an appropriate extension will be added after the load to 5918 /// reach a total size of 64 bits. We have to add the extension separately 5919 /// because ARM does not have a sign/zero extending load for vectors. 5920 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 5921 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 5922 5923 // The load already has the right type. 5924 if (ExtendedTy == LD->getMemoryVT()) 5925 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 5926 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 5927 LD->isNonTemporal(), LD->isInvariant(), 5928 LD->getAlignment()); 5929 5930 // We need to create a zextload/sextload. We cannot just create a load 5931 // followed by a zext/zext node because LowerMUL is also run during normal 5932 // operation legalization where we can't create illegal types. 5933 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 5934 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 5935 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 5936 LD->isNonTemporal(), LD->getAlignment()); 5937 } 5938 5939 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 5940 /// extending load, or BUILD_VECTOR with extended elements, return the 5941 /// unextended value. The unextended vector should be 64 bits so that it can 5942 /// be used as an operand to a VMULL instruction. If the original vector size 5943 /// before extension is less than 64 bits we add a an extension to resize 5944 /// the vector to 64 bits. 5945 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 5946 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 5947 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 5948 N->getOperand(0)->getValueType(0), 5949 N->getValueType(0), 5950 N->getOpcode()); 5951 5952 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 5953 return SkipLoadExtensionForVMULL(LD, DAG); 5954 5955 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 5956 // have been legalized as a BITCAST from v4i32. 5957 if (N->getOpcode() == ISD::BITCAST) { 5958 SDNode *BVN = N->getOperand(0).getNode(); 5959 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 5960 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 5961 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0; 5962 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32, 5963 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2)); 5964 } 5965 // Construct a new BUILD_VECTOR with elements truncated to half the size. 5966 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 5967 EVT VT = N->getValueType(0); 5968 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 5969 unsigned NumElts = VT.getVectorNumElements(); 5970 MVT TruncVT = MVT::getIntegerVT(EltSize); 5971 SmallVector<SDValue, 8> Ops; 5972 for (unsigned i = 0; i != NumElts; ++i) { 5973 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 5974 const APInt &CInt = C->getAPIntValue(); 5975 // Element types smaller than 32 bits are not legal, so use i32 elements. 5976 // The values are implicitly truncated so sext vs. zext doesn't matter. 5977 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32)); 5978 } 5979 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 5980 MVT::getVectorVT(TruncVT, NumElts), Ops); 5981 } 5982 5983 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 5984 unsigned Opcode = N->getOpcode(); 5985 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 5986 SDNode *N0 = N->getOperand(0).getNode(); 5987 SDNode *N1 = N->getOperand(1).getNode(); 5988 return N0->hasOneUse() && N1->hasOneUse() && 5989 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 5990 } 5991 return false; 5992 } 5993 5994 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 5995 unsigned Opcode = N->getOpcode(); 5996 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 5997 SDNode *N0 = N->getOperand(0).getNode(); 5998 SDNode *N1 = N->getOperand(1).getNode(); 5999 return N0->hasOneUse() && N1->hasOneUse() && 6000 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6001 } 6002 return false; 6003 } 6004 6005 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6006 // Multiplications are only custom-lowered for 128-bit vectors so that 6007 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6008 EVT VT = Op.getValueType(); 6009 assert(VT.is128BitVector() && VT.isInteger() && 6010 "unexpected type for custom-lowering ISD::MUL"); 6011 SDNode *N0 = Op.getOperand(0).getNode(); 6012 SDNode *N1 = Op.getOperand(1).getNode(); 6013 unsigned NewOpc = 0; 6014 bool isMLA = false; 6015 bool isN0SExt = isSignExtended(N0, DAG); 6016 bool isN1SExt = isSignExtended(N1, DAG); 6017 if (isN0SExt && isN1SExt) 6018 NewOpc = ARMISD::VMULLs; 6019 else { 6020 bool isN0ZExt = isZeroExtended(N0, DAG); 6021 bool isN1ZExt = isZeroExtended(N1, DAG); 6022 if (isN0ZExt && isN1ZExt) 6023 NewOpc = ARMISD::VMULLu; 6024 else if (isN1SExt || isN1ZExt) { 6025 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6026 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6027 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6028 NewOpc = ARMISD::VMULLs; 6029 isMLA = true; 6030 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6031 NewOpc = ARMISD::VMULLu; 6032 isMLA = true; 6033 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6034 std::swap(N0, N1); 6035 NewOpc = ARMISD::VMULLu; 6036 isMLA = true; 6037 } 6038 } 6039 6040 if (!NewOpc) { 6041 if (VT == MVT::v2i64) 6042 // Fall through to expand this. It is not legal. 6043 return SDValue(); 6044 else 6045 // Other vector multiplications are legal. 6046 return Op; 6047 } 6048 } 6049 6050 // Legalize to a VMULL instruction. 6051 SDLoc DL(Op); 6052 SDValue Op0; 6053 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6054 if (!isMLA) { 6055 Op0 = SkipExtensionForVMULL(N0, DAG); 6056 assert(Op0.getValueType().is64BitVector() && 6057 Op1.getValueType().is64BitVector() && 6058 "unexpected types for extended operands to VMULL"); 6059 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6060 } 6061 6062 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6063 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6064 // vmull q0, d4, d6 6065 // vmlal q0, d5, d6 6066 // is faster than 6067 // vaddl q0, d4, d5 6068 // vmovl q1, d6 6069 // vmul q0, q0, q1 6070 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6071 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6072 EVT Op1VT = Op1.getValueType(); 6073 return DAG.getNode(N0->getOpcode(), DL, VT, 6074 DAG.getNode(NewOpc, DL, VT, 6075 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6076 DAG.getNode(NewOpc, DL, VT, 6077 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6078 } 6079 6080 static SDValue 6081 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 6082 // Convert to float 6083 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6084 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6085 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6086 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6087 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6088 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6089 // Get reciprocal estimate. 6090 // float4 recip = vrecpeq_f32(yf); 6091 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6092 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y); 6093 // Because char has a smaller range than uchar, we can actually get away 6094 // without any newton steps. This requires that we use a weird bias 6095 // of 0xb000, however (again, this has been exhaustively tested). 6096 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6097 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6098 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6099 Y = DAG.getConstant(0xb000, MVT::i32); 6100 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y); 6101 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6102 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6103 // Convert back to short. 6104 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6105 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6106 return X; 6107 } 6108 6109 static SDValue 6110 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 6111 SDValue N2; 6112 // Convert to float. 6113 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6114 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6115 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6116 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6117 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6118 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6119 6120 // Use reciprocal estimate and one refinement step. 6121 // float4 recip = vrecpeq_f32(yf); 6122 // recip *= vrecpsq_f32(yf, recip); 6123 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6124 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1); 6125 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6126 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32), 6127 N1, N2); 6128 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6129 // Because short has a smaller range than ushort, we can actually get away 6130 // with only a single newton step. This requires that we use a weird bias 6131 // of 89, however (again, this has been exhaustively tested). 6132 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6133 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6134 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6135 N1 = DAG.getConstant(0x89, MVT::i32); 6136 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 6137 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6138 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6139 // Convert back to integer and return. 6140 // return vmovn_s32(vcvt_s32_f32(result)); 6141 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6142 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6143 return N0; 6144 } 6145 6146 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6147 EVT VT = Op.getValueType(); 6148 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6149 "unexpected type for custom-lowering ISD::SDIV"); 6150 6151 SDLoc dl(Op); 6152 SDValue N0 = Op.getOperand(0); 6153 SDValue N1 = Op.getOperand(1); 6154 SDValue N2, N3; 6155 6156 if (VT == MVT::v8i8) { 6157 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6158 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6159 6160 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6161 DAG.getIntPtrConstant(4)); 6162 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6163 DAG.getIntPtrConstant(4)); 6164 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6165 DAG.getIntPtrConstant(0)); 6166 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6167 DAG.getIntPtrConstant(0)); 6168 6169 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6170 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6171 6172 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6173 N0 = LowerCONCAT_VECTORS(N0, DAG); 6174 6175 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6176 return N0; 6177 } 6178 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6179 } 6180 6181 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6182 EVT VT = Op.getValueType(); 6183 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6184 "unexpected type for custom-lowering ISD::UDIV"); 6185 6186 SDLoc dl(Op); 6187 SDValue N0 = Op.getOperand(0); 6188 SDValue N1 = Op.getOperand(1); 6189 SDValue N2, N3; 6190 6191 if (VT == MVT::v8i8) { 6192 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6193 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6194 6195 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6196 DAG.getIntPtrConstant(4)); 6197 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6198 DAG.getIntPtrConstant(4)); 6199 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6200 DAG.getIntPtrConstant(0)); 6201 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6202 DAG.getIntPtrConstant(0)); 6203 6204 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6205 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6206 6207 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6208 N0 = LowerCONCAT_VECTORS(N0, DAG); 6209 6210 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6211 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32), 6212 N0); 6213 return N0; 6214 } 6215 6216 // v4i16 sdiv ... Convert to float. 6217 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6218 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6219 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6220 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6221 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6222 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6223 6224 // Use reciprocal estimate and two refinement steps. 6225 // float4 recip = vrecpeq_f32(yf); 6226 // recip *= vrecpsq_f32(yf, recip); 6227 // recip *= vrecpsq_f32(yf, recip); 6228 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6229 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1); 6230 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6231 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32), 6232 BN1, N2); 6233 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6234 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6235 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32), 6236 BN1, N2); 6237 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6238 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6239 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6240 // and that it will never cause us to return an answer too large). 6241 // float4 result = as_float4(as_int4(xf*recip) + 2); 6242 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6243 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6244 N1 = DAG.getConstant(2, MVT::i32); 6245 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 6246 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6247 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6248 // Convert back to integer and return. 6249 // return vmovn_u32(vcvt_s32_f32(result)); 6250 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6251 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6252 return N0; 6253 } 6254 6255 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6256 EVT VT = Op.getNode()->getValueType(0); 6257 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6258 6259 unsigned Opc; 6260 bool ExtraOp = false; 6261 switch (Op.getOpcode()) { 6262 default: llvm_unreachable("Invalid code"); 6263 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6264 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6265 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6266 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6267 } 6268 6269 if (!ExtraOp) 6270 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6271 Op.getOperand(1)); 6272 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6273 Op.getOperand(1), Op.getOperand(2)); 6274 } 6275 6276 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6277 assert(Subtarget->isTargetDarwin()); 6278 6279 // For iOS, we want to call an alternative entry point: __sincos_stret, 6280 // return values are passed via sret. 6281 SDLoc dl(Op); 6282 SDValue Arg = Op.getOperand(0); 6283 EVT ArgVT = Arg.getValueType(); 6284 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6285 6286 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6287 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6288 6289 // Pair of floats / doubles used to pass the result. 6290 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6291 6292 // Create stack object for sret. 6293 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy); 6294 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy); 6295 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6296 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy()); 6297 6298 ArgListTy Args; 6299 ArgListEntry Entry; 6300 6301 Entry.Node = SRet; 6302 Entry.Ty = RetTy->getPointerTo(); 6303 Entry.isSExt = false; 6304 Entry.isZExt = false; 6305 Entry.isSRet = true; 6306 Args.push_back(Entry); 6307 6308 Entry.Node = Arg; 6309 Entry.Ty = ArgTy; 6310 Entry.isSExt = false; 6311 Entry.isZExt = false; 6312 Args.push_back(Entry); 6313 6314 const char *LibcallName = (ArgVT == MVT::f64) 6315 ? "__sincos_stret" : "__sincosf_stret"; 6316 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy()); 6317 6318 TargetLowering::CallLoweringInfo CLI(DAG); 6319 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 6320 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee, 6321 std::move(Args), 0) 6322 .setDiscardResult(); 6323 6324 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6325 6326 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6327 MachinePointerInfo(), false, false, false, 0); 6328 6329 // Address of cos field. 6330 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet, 6331 DAG.getIntPtrConstant(ArgVT.getStoreSize())); 6332 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6333 MachinePointerInfo(), false, false, false, 0); 6334 6335 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6336 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6337 LoadSin.getValue(0), LoadCos.getValue(0)); 6338 } 6339 6340 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 6341 // Monotonic load/store is legal for all targets 6342 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic) 6343 return Op; 6344 6345 // Acquire/Release load/store is not legal for targets without a 6346 // dmb or equivalent available. 6347 return SDValue(); 6348 } 6349 6350 static void ReplaceREADCYCLECOUNTER(SDNode *N, 6351 SmallVectorImpl<SDValue> &Results, 6352 SelectionDAG &DAG, 6353 const ARMSubtarget *Subtarget) { 6354 SDLoc DL(N); 6355 SDValue Cycles32, OutChain; 6356 6357 if (Subtarget->hasPerfMon()) { 6358 // Under Power Management extensions, the cycle-count is: 6359 // mrc p15, #0, <Rt>, c9, c13, #0 6360 SDValue Ops[] = { N->getOperand(0), // Chain 6361 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32), 6362 DAG.getConstant(15, MVT::i32), 6363 DAG.getConstant(0, MVT::i32), 6364 DAG.getConstant(9, MVT::i32), 6365 DAG.getConstant(13, MVT::i32), 6366 DAG.getConstant(0, MVT::i32) 6367 }; 6368 6369 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6370 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6371 OutChain = Cycles32.getValue(1); 6372 } else { 6373 // Intrinsic is defined to return 0 on unsupported platforms. Technically 6374 // there are older ARM CPUs that have implementation-specific ways of 6375 // obtaining this information (FIXME!). 6376 Cycles32 = DAG.getConstant(0, MVT::i32); 6377 OutChain = DAG.getEntryNode(); 6378 } 6379 6380 6381 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, 6382 Cycles32, DAG.getConstant(0, MVT::i32)); 6383 Results.push_back(Cycles64); 6384 Results.push_back(OutChain); 6385 } 6386 6387 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6388 switch (Op.getOpcode()) { 6389 default: llvm_unreachable("Don't know how to custom lower this!"); 6390 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 6391 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 6392 case ISD::GlobalAddress: 6393 switch (Subtarget->getTargetTriple().getObjectFormat()) { 6394 default: llvm_unreachable("unknown object format"); 6395 case Triple::COFF: 6396 return LowerGlobalAddressWindows(Op, DAG); 6397 case Triple::ELF: 6398 return LowerGlobalAddressELF(Op, DAG); 6399 case Triple::MachO: 6400 return LowerGlobalAddressDarwin(Op, DAG); 6401 } 6402 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 6403 case ISD::SELECT: return LowerSELECT(Op, DAG); 6404 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 6405 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 6406 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 6407 case ISD::VASTART: return LowerVASTART(Op, DAG); 6408 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 6409 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 6410 case ISD::SINT_TO_FP: 6411 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 6412 case ISD::FP_TO_SINT: 6413 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 6414 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 6415 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 6416 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 6417 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG); 6418 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 6419 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 6420 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 6421 Subtarget); 6422 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 6423 case ISD::SHL: 6424 case ISD::SRL: 6425 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 6426 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 6427 case ISD::SRL_PARTS: 6428 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 6429 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 6430 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 6431 case ISD::SETCC: return LowerVSETCC(Op, DAG); 6432 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 6433 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 6434 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 6435 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 6436 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 6437 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 6438 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 6439 case ISD::MUL: return LowerMUL(Op, DAG); 6440 case ISD::SDIV: return LowerSDIV(Op, DAG); 6441 case ISD::UDIV: return LowerUDIV(Op, DAG); 6442 case ISD::ADDC: 6443 case ISD::ADDE: 6444 case ISD::SUBC: 6445 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 6446 case ISD::SADDO: 6447 case ISD::UADDO: 6448 case ISD::SSUBO: 6449 case ISD::USUBO: 6450 return LowerXALUO(Op, DAG); 6451 case ISD::ATOMIC_LOAD: 6452 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 6453 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 6454 case ISD::SDIVREM: 6455 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 6456 case ISD::DYNAMIC_STACKALLOC: 6457 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 6458 return LowerDYNAMIC_STACKALLOC(Op, DAG); 6459 llvm_unreachable("Don't know how to custom lower this!"); 6460 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 6461 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 6462 } 6463 } 6464 6465 /// ReplaceNodeResults - Replace the results of node with an illegal result 6466 /// type with new values built out of custom code. 6467 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 6468 SmallVectorImpl<SDValue>&Results, 6469 SelectionDAG &DAG) const { 6470 SDValue Res; 6471 switch (N->getOpcode()) { 6472 default: 6473 llvm_unreachable("Don't know how to custom expand this!"); 6474 case ISD::BITCAST: 6475 Res = ExpandBITCAST(N, DAG); 6476 break; 6477 case ISD::SRL: 6478 case ISD::SRA: 6479 Res = Expand64BitShift(N, DAG, Subtarget); 6480 break; 6481 case ISD::READCYCLECOUNTER: 6482 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 6483 return; 6484 } 6485 if (Res.getNode()) 6486 Results.push_back(Res); 6487 } 6488 6489 //===----------------------------------------------------------------------===// 6490 // ARM Scheduler Hooks 6491 //===----------------------------------------------------------------------===// 6492 6493 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 6494 /// registers the function context. 6495 void ARMTargetLowering:: 6496 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 6497 MachineBasicBlock *DispatchBB, int FI) const { 6498 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 6499 DebugLoc dl = MI->getDebugLoc(); 6500 MachineFunction *MF = MBB->getParent(); 6501 MachineRegisterInfo *MRI = &MF->getRegInfo(); 6502 MachineConstantPool *MCP = MF->getConstantPool(); 6503 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 6504 const Function *F = MF->getFunction(); 6505 6506 bool isThumb = Subtarget->isThumb(); 6507 bool isThumb2 = Subtarget->isThumb2(); 6508 6509 unsigned PCLabelId = AFI->createPICLabelUId(); 6510 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 6511 ARMConstantPoolValue *CPV = 6512 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 6513 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 6514 6515 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 6516 : &ARM::GPRRegClass; 6517 6518 // Grab constant pool and fixed stack memory operands. 6519 MachineMemOperand *CPMMO = 6520 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(), 6521 MachineMemOperand::MOLoad, 4, 4); 6522 6523 MachineMemOperand *FIMMOSt = 6524 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), 6525 MachineMemOperand::MOStore, 4, 4); 6526 6527 // Load the address of the dispatch MBB into the jump buffer. 6528 if (isThumb2) { 6529 // Incoming value: jbuf 6530 // ldr.n r5, LCPI1_1 6531 // orr r5, r5, #1 6532 // add r5, pc 6533 // str r5, [$jbuf, #+4] ; &jbuf[1] 6534 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6535 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 6536 .addConstantPoolIndex(CPI) 6537 .addMemOperand(CPMMO)); 6538 // Set the low bit because of thumb mode. 6539 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6540 AddDefaultCC( 6541 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 6542 .addReg(NewVReg1, RegState::Kill) 6543 .addImm(0x01))); 6544 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6545 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 6546 .addReg(NewVReg2, RegState::Kill) 6547 .addImm(PCLabelId); 6548 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 6549 .addReg(NewVReg3, RegState::Kill) 6550 .addFrameIndex(FI) 6551 .addImm(36) // &jbuf[1] :: pc 6552 .addMemOperand(FIMMOSt)); 6553 } else if (isThumb) { 6554 // Incoming value: jbuf 6555 // ldr.n r1, LCPI1_4 6556 // add r1, pc 6557 // mov r2, #1 6558 // orrs r1, r2 6559 // add r2, $jbuf, #+4 ; &jbuf[1] 6560 // str r1, [r2] 6561 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6562 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 6563 .addConstantPoolIndex(CPI) 6564 .addMemOperand(CPMMO)); 6565 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6566 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 6567 .addReg(NewVReg1, RegState::Kill) 6568 .addImm(PCLabelId); 6569 // Set the low bit because of thumb mode. 6570 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6571 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 6572 .addReg(ARM::CPSR, RegState::Define) 6573 .addImm(1)); 6574 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 6575 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 6576 .addReg(ARM::CPSR, RegState::Define) 6577 .addReg(NewVReg2, RegState::Kill) 6578 .addReg(NewVReg3, RegState::Kill)); 6579 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 6580 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 6581 .addFrameIndex(FI) 6582 .addImm(36); // &jbuf[1] :: pc 6583 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 6584 .addReg(NewVReg4, RegState::Kill) 6585 .addReg(NewVReg5, RegState::Kill) 6586 .addImm(0) 6587 .addMemOperand(FIMMOSt)); 6588 } else { 6589 // Incoming value: jbuf 6590 // ldr r1, LCPI1_1 6591 // add r1, pc, r1 6592 // str r1, [$jbuf, #+4] ; &jbuf[1] 6593 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6594 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 6595 .addConstantPoolIndex(CPI) 6596 .addImm(0) 6597 .addMemOperand(CPMMO)); 6598 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6599 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 6600 .addReg(NewVReg1, RegState::Kill) 6601 .addImm(PCLabelId)); 6602 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 6603 .addReg(NewVReg2, RegState::Kill) 6604 .addFrameIndex(FI) 6605 .addImm(36) // &jbuf[1] :: pc 6606 .addMemOperand(FIMMOSt)); 6607 } 6608 } 6609 6610 MachineBasicBlock *ARMTargetLowering:: 6611 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const { 6612 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 6613 DebugLoc dl = MI->getDebugLoc(); 6614 MachineFunction *MF = MBB->getParent(); 6615 MachineRegisterInfo *MRI = &MF->getRegInfo(); 6616 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 6617 MachineFrameInfo *MFI = MF->getFrameInfo(); 6618 int FI = MFI->getFunctionContextIndex(); 6619 6620 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 6621 : &ARM::GPRnopcRegClass; 6622 6623 // Get a mapping of the call site numbers to all of the landing pads they're 6624 // associated with. 6625 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 6626 unsigned MaxCSNum = 0; 6627 MachineModuleInfo &MMI = MF->getMMI(); 6628 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 6629 ++BB) { 6630 if (!BB->isLandingPad()) continue; 6631 6632 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 6633 // pad. 6634 for (MachineBasicBlock::iterator 6635 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 6636 if (!II->isEHLabel()) continue; 6637 6638 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 6639 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 6640 6641 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 6642 for (SmallVectorImpl<unsigned>::iterator 6643 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 6644 CSI != CSE; ++CSI) { 6645 CallSiteNumToLPad[*CSI].push_back(BB); 6646 MaxCSNum = std::max(MaxCSNum, *CSI); 6647 } 6648 break; 6649 } 6650 } 6651 6652 // Get an ordered list of the machine basic blocks for the jump table. 6653 std::vector<MachineBasicBlock*> LPadList; 6654 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs; 6655 LPadList.reserve(CallSiteNumToLPad.size()); 6656 for (unsigned I = 1; I <= MaxCSNum; ++I) { 6657 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 6658 for (SmallVectorImpl<MachineBasicBlock*>::iterator 6659 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 6660 LPadList.push_back(*II); 6661 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 6662 } 6663 } 6664 6665 assert(!LPadList.empty() && 6666 "No landing pad destinations for the dispatch jump table!"); 6667 6668 // Create the jump table and associated information. 6669 MachineJumpTableInfo *JTI = 6670 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 6671 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 6672 unsigned UId = AFI->createJumpTableUId(); 6673 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 6674 6675 // Create the MBBs for the dispatch code. 6676 6677 // Shove the dispatch's address into the return slot in the function context. 6678 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 6679 DispatchBB->setIsLandingPad(); 6680 6681 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 6682 unsigned trap_opcode; 6683 if (Subtarget->isThumb()) 6684 trap_opcode = ARM::tTRAP; 6685 else 6686 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 6687 6688 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 6689 DispatchBB->addSuccessor(TrapBB); 6690 6691 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 6692 DispatchBB->addSuccessor(DispContBB); 6693 6694 // Insert and MBBs. 6695 MF->insert(MF->end(), DispatchBB); 6696 MF->insert(MF->end(), DispContBB); 6697 MF->insert(MF->end(), TrapBB); 6698 6699 // Insert code into the entry block that creates and registers the function 6700 // context. 6701 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 6702 6703 MachineMemOperand *FIMMOLd = 6704 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), 6705 MachineMemOperand::MOLoad | 6706 MachineMemOperand::MOVolatile, 4, 4); 6707 6708 MachineInstrBuilder MIB; 6709 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 6710 6711 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 6712 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 6713 6714 // Add a register mask with no preserved registers. This results in all 6715 // registers being marked as clobbered. 6716 MIB.addRegMask(RI.getNoPreservedMask()); 6717 6718 unsigned NumLPads = LPadList.size(); 6719 if (Subtarget->isThumb2()) { 6720 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6721 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 6722 .addFrameIndex(FI) 6723 .addImm(4) 6724 .addMemOperand(FIMMOLd)); 6725 6726 if (NumLPads < 256) { 6727 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 6728 .addReg(NewVReg1) 6729 .addImm(LPadList.size())); 6730 } else { 6731 unsigned VReg1 = MRI->createVirtualRegister(TRC); 6732 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 6733 .addImm(NumLPads & 0xFFFF)); 6734 6735 unsigned VReg2 = VReg1; 6736 if ((NumLPads & 0xFFFF0000) != 0) { 6737 VReg2 = MRI->createVirtualRegister(TRC); 6738 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 6739 .addReg(VReg1) 6740 .addImm(NumLPads >> 16)); 6741 } 6742 6743 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 6744 .addReg(NewVReg1) 6745 .addReg(VReg2)); 6746 } 6747 6748 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 6749 .addMBB(TrapBB) 6750 .addImm(ARMCC::HI) 6751 .addReg(ARM::CPSR); 6752 6753 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6754 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 6755 .addJumpTableIndex(MJTI) 6756 .addImm(UId)); 6757 6758 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 6759 AddDefaultCC( 6760 AddDefaultPred( 6761 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 6762 .addReg(NewVReg3, RegState::Kill) 6763 .addReg(NewVReg1) 6764 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 6765 6766 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 6767 .addReg(NewVReg4, RegState::Kill) 6768 .addReg(NewVReg1) 6769 .addJumpTableIndex(MJTI) 6770 .addImm(UId); 6771 } else if (Subtarget->isThumb()) { 6772 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6773 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 6774 .addFrameIndex(FI) 6775 .addImm(1) 6776 .addMemOperand(FIMMOLd)); 6777 6778 if (NumLPads < 256) { 6779 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 6780 .addReg(NewVReg1) 6781 .addImm(NumLPads)); 6782 } else { 6783 MachineConstantPool *ConstantPool = MF->getConstantPool(); 6784 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 6785 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 6786 6787 // MachineConstantPool wants an explicit alignment. 6788 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty); 6789 if (Align == 0) 6790 Align = getDataLayout()->getTypeAllocSize(C->getType()); 6791 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 6792 6793 unsigned VReg1 = MRI->createVirtualRegister(TRC); 6794 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 6795 .addReg(VReg1, RegState::Define) 6796 .addConstantPoolIndex(Idx)); 6797 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 6798 .addReg(NewVReg1) 6799 .addReg(VReg1)); 6800 } 6801 6802 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 6803 .addMBB(TrapBB) 6804 .addImm(ARMCC::HI) 6805 .addReg(ARM::CPSR); 6806 6807 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6808 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 6809 .addReg(ARM::CPSR, RegState::Define) 6810 .addReg(NewVReg1) 6811 .addImm(2)); 6812 6813 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6814 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 6815 .addJumpTableIndex(MJTI) 6816 .addImm(UId)); 6817 6818 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 6819 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 6820 .addReg(ARM::CPSR, RegState::Define) 6821 .addReg(NewVReg2, RegState::Kill) 6822 .addReg(NewVReg3)); 6823 6824 MachineMemOperand *JTMMOLd = 6825 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(), 6826 MachineMemOperand::MOLoad, 4, 4); 6827 6828 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 6829 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 6830 .addReg(NewVReg4, RegState::Kill) 6831 .addImm(0) 6832 .addMemOperand(JTMMOLd)); 6833 6834 unsigned NewVReg6 = NewVReg5; 6835 if (RelocM == Reloc::PIC_) { 6836 NewVReg6 = MRI->createVirtualRegister(TRC); 6837 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 6838 .addReg(ARM::CPSR, RegState::Define) 6839 .addReg(NewVReg5, RegState::Kill) 6840 .addReg(NewVReg3)); 6841 } 6842 6843 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 6844 .addReg(NewVReg6, RegState::Kill) 6845 .addJumpTableIndex(MJTI) 6846 .addImm(UId); 6847 } else { 6848 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6849 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 6850 .addFrameIndex(FI) 6851 .addImm(4) 6852 .addMemOperand(FIMMOLd)); 6853 6854 if (NumLPads < 256) { 6855 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 6856 .addReg(NewVReg1) 6857 .addImm(NumLPads)); 6858 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 6859 unsigned VReg1 = MRI->createVirtualRegister(TRC); 6860 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 6861 .addImm(NumLPads & 0xFFFF)); 6862 6863 unsigned VReg2 = VReg1; 6864 if ((NumLPads & 0xFFFF0000) != 0) { 6865 VReg2 = MRI->createVirtualRegister(TRC); 6866 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 6867 .addReg(VReg1) 6868 .addImm(NumLPads >> 16)); 6869 } 6870 6871 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 6872 .addReg(NewVReg1) 6873 .addReg(VReg2)); 6874 } else { 6875 MachineConstantPool *ConstantPool = MF->getConstantPool(); 6876 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 6877 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 6878 6879 // MachineConstantPool wants an explicit alignment. 6880 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty); 6881 if (Align == 0) 6882 Align = getDataLayout()->getTypeAllocSize(C->getType()); 6883 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 6884 6885 unsigned VReg1 = MRI->createVirtualRegister(TRC); 6886 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 6887 .addReg(VReg1, RegState::Define) 6888 .addConstantPoolIndex(Idx) 6889 .addImm(0)); 6890 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 6891 .addReg(NewVReg1) 6892 .addReg(VReg1, RegState::Kill)); 6893 } 6894 6895 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 6896 .addMBB(TrapBB) 6897 .addImm(ARMCC::HI) 6898 .addReg(ARM::CPSR); 6899 6900 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6901 AddDefaultCC( 6902 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 6903 .addReg(NewVReg1) 6904 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 6905 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 6906 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 6907 .addJumpTableIndex(MJTI) 6908 .addImm(UId)); 6909 6910 MachineMemOperand *JTMMOLd = 6911 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(), 6912 MachineMemOperand::MOLoad, 4, 4); 6913 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 6914 AddDefaultPred( 6915 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 6916 .addReg(NewVReg3, RegState::Kill) 6917 .addReg(NewVReg4) 6918 .addImm(0) 6919 .addMemOperand(JTMMOLd)); 6920 6921 if (RelocM == Reloc::PIC_) { 6922 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 6923 .addReg(NewVReg5, RegState::Kill) 6924 .addReg(NewVReg4) 6925 .addJumpTableIndex(MJTI) 6926 .addImm(UId); 6927 } else { 6928 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 6929 .addReg(NewVReg5, RegState::Kill) 6930 .addJumpTableIndex(MJTI) 6931 .addImm(UId); 6932 } 6933 } 6934 6935 // Add the jump table entries as successors to the MBB. 6936 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 6937 for (std::vector<MachineBasicBlock*>::iterator 6938 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 6939 MachineBasicBlock *CurMBB = *I; 6940 if (SeenMBBs.insert(CurMBB).second) 6941 DispContBB->addSuccessor(CurMBB); 6942 } 6943 6944 // N.B. the order the invoke BBs are processed in doesn't matter here. 6945 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 6946 SmallVector<MachineBasicBlock*, 64> MBBLPads; 6947 for (MachineBasicBlock *BB : InvokeBBs) { 6948 6949 // Remove the landing pad successor from the invoke block and replace it 6950 // with the new dispatch block. 6951 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 6952 BB->succ_end()); 6953 while (!Successors.empty()) { 6954 MachineBasicBlock *SMBB = Successors.pop_back_val(); 6955 if (SMBB->isLandingPad()) { 6956 BB->removeSuccessor(SMBB); 6957 MBBLPads.push_back(SMBB); 6958 } 6959 } 6960 6961 BB->addSuccessor(DispatchBB); 6962 6963 // Find the invoke call and mark all of the callee-saved registers as 6964 // 'implicit defined' so that they're spilled. This prevents code from 6965 // moving instructions to before the EH block, where they will never be 6966 // executed. 6967 for (MachineBasicBlock::reverse_iterator 6968 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 6969 if (!II->isCall()) continue; 6970 6971 DenseMap<unsigned, bool> DefRegs; 6972 for (MachineInstr::mop_iterator 6973 OI = II->operands_begin(), OE = II->operands_end(); 6974 OI != OE; ++OI) { 6975 if (!OI->isReg()) continue; 6976 DefRegs[OI->getReg()] = true; 6977 } 6978 6979 MachineInstrBuilder MIB(*MF, &*II); 6980 6981 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 6982 unsigned Reg = SavedRegs[i]; 6983 if (Subtarget->isThumb2() && 6984 !ARM::tGPRRegClass.contains(Reg) && 6985 !ARM::hGPRRegClass.contains(Reg)) 6986 continue; 6987 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 6988 continue; 6989 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 6990 continue; 6991 if (!DefRegs[Reg]) 6992 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 6993 } 6994 6995 break; 6996 } 6997 } 6998 6999 // Mark all former landing pads as non-landing pads. The dispatch is the only 7000 // landing pad now. 7001 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7002 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7003 (*I)->setIsLandingPad(false); 7004 7005 // The instruction is gone now. 7006 MI->eraseFromParent(); 7007 7008 return MBB; 7009 } 7010 7011 static 7012 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7013 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7014 E = MBB->succ_end(); I != E; ++I) 7015 if (*I != Succ) 7016 return *I; 7017 llvm_unreachable("Expecting a BB with two successors!"); 7018 } 7019 7020 /// Return the load opcode for a given load size. If load size >= 8, 7021 /// neon opcode will be returned. 7022 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7023 if (LdSize >= 8) 7024 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7025 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7026 if (IsThumb1) 7027 return LdSize == 4 ? ARM::tLDRi 7028 : LdSize == 2 ? ARM::tLDRHi 7029 : LdSize == 1 ? ARM::tLDRBi : 0; 7030 if (IsThumb2) 7031 return LdSize == 4 ? ARM::t2LDR_POST 7032 : LdSize == 2 ? ARM::t2LDRH_POST 7033 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7034 return LdSize == 4 ? ARM::LDR_POST_IMM 7035 : LdSize == 2 ? ARM::LDRH_POST 7036 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7037 } 7038 7039 /// Return the store opcode for a given store size. If store size >= 8, 7040 /// neon opcode will be returned. 7041 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7042 if (StSize >= 8) 7043 return StSize == 16 ? ARM::VST1q32wb_fixed 7044 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7045 if (IsThumb1) 7046 return StSize == 4 ? ARM::tSTRi 7047 : StSize == 2 ? ARM::tSTRHi 7048 : StSize == 1 ? ARM::tSTRBi : 0; 7049 if (IsThumb2) 7050 return StSize == 4 ? ARM::t2STR_POST 7051 : StSize == 2 ? ARM::t2STRH_POST 7052 : StSize == 1 ? ARM::t2STRB_POST : 0; 7053 return StSize == 4 ? ARM::STR_POST_IMM 7054 : StSize == 2 ? ARM::STRH_POST 7055 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7056 } 7057 7058 /// Emit a post-increment load operation with given size. The instructions 7059 /// will be added to BB at Pos. 7060 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7061 const TargetInstrInfo *TII, DebugLoc dl, 7062 unsigned LdSize, unsigned Data, unsigned AddrIn, 7063 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7064 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7065 assert(LdOpc != 0 && "Should have a load opcode"); 7066 if (LdSize >= 8) { 7067 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7068 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7069 .addImm(0)); 7070 } else if (IsThumb1) { 7071 // load + update AddrIn 7072 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7073 .addReg(AddrIn).addImm(0)); 7074 MachineInstrBuilder MIB = 7075 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7076 MIB = AddDefaultT1CC(MIB); 7077 MIB.addReg(AddrIn).addImm(LdSize); 7078 AddDefaultPred(MIB); 7079 } else if (IsThumb2) { 7080 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7081 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7082 .addImm(LdSize)); 7083 } else { // arm 7084 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7085 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7086 .addReg(0).addImm(LdSize)); 7087 } 7088 } 7089 7090 /// Emit a post-increment store operation with given size. The instructions 7091 /// will be added to BB at Pos. 7092 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7093 const TargetInstrInfo *TII, DebugLoc dl, 7094 unsigned StSize, unsigned Data, unsigned AddrIn, 7095 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7096 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7097 assert(StOpc != 0 && "Should have a store opcode"); 7098 if (StSize >= 8) { 7099 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7100 .addReg(AddrIn).addImm(0).addReg(Data)); 7101 } else if (IsThumb1) { 7102 // store + update AddrIn 7103 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7104 .addReg(AddrIn).addImm(0)); 7105 MachineInstrBuilder MIB = 7106 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7107 MIB = AddDefaultT1CC(MIB); 7108 MIB.addReg(AddrIn).addImm(StSize); 7109 AddDefaultPred(MIB); 7110 } else if (IsThumb2) { 7111 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7112 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7113 } else { // arm 7114 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7115 .addReg(Data).addReg(AddrIn).addReg(0) 7116 .addImm(StSize)); 7117 } 7118 } 7119 7120 MachineBasicBlock * 7121 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7122 MachineBasicBlock *BB) const { 7123 // This pseudo instruction has 3 operands: dst, src, size 7124 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7125 // Otherwise, we will generate unrolled scalar copies. 7126 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7127 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7128 MachineFunction::iterator It = BB; 7129 ++It; 7130 7131 unsigned dest = MI->getOperand(0).getReg(); 7132 unsigned src = MI->getOperand(1).getReg(); 7133 unsigned SizeVal = MI->getOperand(2).getImm(); 7134 unsigned Align = MI->getOperand(3).getImm(); 7135 DebugLoc dl = MI->getDebugLoc(); 7136 7137 MachineFunction *MF = BB->getParent(); 7138 MachineRegisterInfo &MRI = MF->getRegInfo(); 7139 unsigned UnitSize = 0; 7140 const TargetRegisterClass *TRC = nullptr; 7141 const TargetRegisterClass *VecTRC = nullptr; 7142 7143 bool IsThumb1 = Subtarget->isThumb1Only(); 7144 bool IsThumb2 = Subtarget->isThumb2(); 7145 7146 if (Align & 1) { 7147 UnitSize = 1; 7148 } else if (Align & 2) { 7149 UnitSize = 2; 7150 } else { 7151 // Check whether we can use NEON instructions. 7152 if (!MF->getFunction()->getAttributes(). 7153 hasAttribute(AttributeSet::FunctionIndex, 7154 Attribute::NoImplicitFloat) && 7155 Subtarget->hasNEON()) { 7156 if ((Align % 16 == 0) && SizeVal >= 16) 7157 UnitSize = 16; 7158 else if ((Align % 8 == 0) && SizeVal >= 8) 7159 UnitSize = 8; 7160 } 7161 // Can't use NEON instructions. 7162 if (UnitSize == 0) 7163 UnitSize = 4; 7164 } 7165 7166 // Select the correct opcode and register class for unit size load/store 7167 bool IsNeon = UnitSize >= 8; 7168 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7169 if (IsNeon) 7170 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7171 : UnitSize == 8 ? &ARM::DPRRegClass 7172 : nullptr; 7173 7174 unsigned BytesLeft = SizeVal % UnitSize; 7175 unsigned LoopSize = SizeVal - BytesLeft; 7176 7177 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7178 // Use LDR and STR to copy. 7179 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7180 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7181 unsigned srcIn = src; 7182 unsigned destIn = dest; 7183 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7184 unsigned srcOut = MRI.createVirtualRegister(TRC); 7185 unsigned destOut = MRI.createVirtualRegister(TRC); 7186 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7187 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7188 IsThumb1, IsThumb2); 7189 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7190 IsThumb1, IsThumb2); 7191 srcIn = srcOut; 7192 destIn = destOut; 7193 } 7194 7195 // Handle the leftover bytes with LDRB and STRB. 7196 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7197 // [destOut] = STRB_POST(scratch, destIn, 1) 7198 for (unsigned i = 0; i < BytesLeft; i++) { 7199 unsigned srcOut = MRI.createVirtualRegister(TRC); 7200 unsigned destOut = MRI.createVirtualRegister(TRC); 7201 unsigned scratch = MRI.createVirtualRegister(TRC); 7202 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7203 IsThumb1, IsThumb2); 7204 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7205 IsThumb1, IsThumb2); 7206 srcIn = srcOut; 7207 destIn = destOut; 7208 } 7209 MI->eraseFromParent(); // The instruction is gone now. 7210 return BB; 7211 } 7212 7213 // Expand the pseudo op to a loop. 7214 // thisMBB: 7215 // ... 7216 // movw varEnd, # --> with thumb2 7217 // movt varEnd, # 7218 // ldrcp varEnd, idx --> without thumb2 7219 // fallthrough --> loopMBB 7220 // loopMBB: 7221 // PHI varPhi, varEnd, varLoop 7222 // PHI srcPhi, src, srcLoop 7223 // PHI destPhi, dst, destLoop 7224 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7225 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7226 // subs varLoop, varPhi, #UnitSize 7227 // bne loopMBB 7228 // fallthrough --> exitMBB 7229 // exitMBB: 7230 // epilogue to handle left-over bytes 7231 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7232 // [destOut] = STRB_POST(scratch, destLoop, 1) 7233 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7234 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7235 MF->insert(It, loopMBB); 7236 MF->insert(It, exitMBB); 7237 7238 // Transfer the remainder of BB and its successor edges to exitMBB. 7239 exitMBB->splice(exitMBB->begin(), BB, 7240 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7241 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7242 7243 // Load an immediate to varEnd. 7244 unsigned varEnd = MRI.createVirtualRegister(TRC); 7245 if (IsThumb2) { 7246 unsigned Vtmp = varEnd; 7247 if ((LoopSize & 0xFFFF0000) != 0) 7248 Vtmp = MRI.createVirtualRegister(TRC); 7249 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp) 7250 .addImm(LoopSize & 0xFFFF)); 7251 7252 if ((LoopSize & 0xFFFF0000) != 0) 7253 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd) 7254 .addReg(Vtmp).addImm(LoopSize >> 16)); 7255 } else { 7256 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7257 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7258 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 7259 7260 // MachineConstantPool wants an explicit alignment. 7261 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty); 7262 if (Align == 0) 7263 Align = getDataLayout()->getTypeAllocSize(C->getType()); 7264 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7265 7266 if (IsThumb1) 7267 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 7268 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 7269 else 7270 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 7271 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 7272 } 7273 BB->addSuccessor(loopMBB); 7274 7275 // Generate the loop body: 7276 // varPhi = PHI(varLoop, varEnd) 7277 // srcPhi = PHI(srcLoop, src) 7278 // destPhi = PHI(destLoop, dst) 7279 MachineBasicBlock *entryBB = BB; 7280 BB = loopMBB; 7281 unsigned varLoop = MRI.createVirtualRegister(TRC); 7282 unsigned varPhi = MRI.createVirtualRegister(TRC); 7283 unsigned srcLoop = MRI.createVirtualRegister(TRC); 7284 unsigned srcPhi = MRI.createVirtualRegister(TRC); 7285 unsigned destLoop = MRI.createVirtualRegister(TRC); 7286 unsigned destPhi = MRI.createVirtualRegister(TRC); 7287 7288 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 7289 .addReg(varLoop).addMBB(loopMBB) 7290 .addReg(varEnd).addMBB(entryBB); 7291 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 7292 .addReg(srcLoop).addMBB(loopMBB) 7293 .addReg(src).addMBB(entryBB); 7294 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 7295 .addReg(destLoop).addMBB(loopMBB) 7296 .addReg(dest).addMBB(entryBB); 7297 7298 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7299 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 7300 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7301 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 7302 IsThumb1, IsThumb2); 7303 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 7304 IsThumb1, IsThumb2); 7305 7306 // Decrement loop variable by UnitSize. 7307 if (IsThumb1) { 7308 MachineInstrBuilder MIB = 7309 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 7310 MIB = AddDefaultT1CC(MIB); 7311 MIB.addReg(varPhi).addImm(UnitSize); 7312 AddDefaultPred(MIB); 7313 } else { 7314 MachineInstrBuilder MIB = 7315 BuildMI(*BB, BB->end(), dl, 7316 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 7317 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 7318 MIB->getOperand(5).setReg(ARM::CPSR); 7319 MIB->getOperand(5).setIsDef(true); 7320 } 7321 BuildMI(*BB, BB->end(), dl, 7322 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7323 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 7324 7325 // loopMBB can loop back to loopMBB or fall through to exitMBB. 7326 BB->addSuccessor(loopMBB); 7327 BB->addSuccessor(exitMBB); 7328 7329 // Add epilogue to handle BytesLeft. 7330 BB = exitMBB; 7331 MachineInstr *StartOfExit = exitMBB->begin(); 7332 7333 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7334 // [destOut] = STRB_POST(scratch, destLoop, 1) 7335 unsigned srcIn = srcLoop; 7336 unsigned destIn = destLoop; 7337 for (unsigned i = 0; i < BytesLeft; i++) { 7338 unsigned srcOut = MRI.createVirtualRegister(TRC); 7339 unsigned destOut = MRI.createVirtualRegister(TRC); 7340 unsigned scratch = MRI.createVirtualRegister(TRC); 7341 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 7342 IsThumb1, IsThumb2); 7343 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 7344 IsThumb1, IsThumb2); 7345 srcIn = srcOut; 7346 destIn = destOut; 7347 } 7348 7349 MI->eraseFromParent(); // The instruction is gone now. 7350 return BB; 7351 } 7352 7353 MachineBasicBlock * 7354 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 7355 MachineBasicBlock *MBB) const { 7356 const TargetMachine &TM = getTargetMachine(); 7357 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 7358 DebugLoc DL = MI->getDebugLoc(); 7359 7360 assert(Subtarget->isTargetWindows() && 7361 "__chkstk is only supported on Windows"); 7362 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 7363 7364 // __chkstk takes the number of words to allocate on the stack in R4, and 7365 // returns the stack adjustment in number of bytes in R4. This will not 7366 // clober any other registers (other than the obvious lr). 7367 // 7368 // Although, technically, IP should be considered a register which may be 7369 // clobbered, the call itself will not touch it. Windows on ARM is a pure 7370 // thumb-2 environment, so there is no interworking required. As a result, we 7371 // do not expect a veneer to be emitted by the linker, clobbering IP. 7372 // 7373 // Each module receives its own copy of __chkstk, so no import thunk is 7374 // required, again, ensuring that IP is not clobbered. 7375 // 7376 // Finally, although some linkers may theoretically provide a trampoline for 7377 // out of range calls (which is quite common due to a 32M range limitation of 7378 // branches for Thumb), we can generate the long-call version via 7379 // -mcmodel=large, alleviating the need for the trampoline which may clobber 7380 // IP. 7381 7382 switch (TM.getCodeModel()) { 7383 case CodeModel::Small: 7384 case CodeModel::Medium: 7385 case CodeModel::Default: 7386 case CodeModel::Kernel: 7387 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 7388 .addImm((unsigned)ARMCC::AL).addReg(0) 7389 .addExternalSymbol("__chkstk") 7390 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7391 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7392 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7393 break; 7394 case CodeModel::Large: 7395 case CodeModel::JITDefault: { 7396 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 7397 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 7398 7399 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 7400 .addExternalSymbol("__chkstk"); 7401 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 7402 .addImm((unsigned)ARMCC::AL).addReg(0) 7403 .addReg(Reg, RegState::Kill) 7404 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7405 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7406 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7407 break; 7408 } 7409 } 7410 7411 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 7412 ARM::SP) 7413 .addReg(ARM::SP).addReg(ARM::R4))); 7414 7415 MI->eraseFromParent(); 7416 return MBB; 7417 } 7418 7419 MachineBasicBlock * 7420 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 7421 MachineBasicBlock *BB) const { 7422 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7423 DebugLoc dl = MI->getDebugLoc(); 7424 bool isThumb2 = Subtarget->isThumb2(); 7425 switch (MI->getOpcode()) { 7426 default: { 7427 MI->dump(); 7428 llvm_unreachable("Unexpected instr type to insert"); 7429 } 7430 // The Thumb2 pre-indexed stores have the same MI operands, they just 7431 // define them differently in the .td files from the isel patterns, so 7432 // they need pseudos. 7433 case ARM::t2STR_preidx: 7434 MI->setDesc(TII->get(ARM::t2STR_PRE)); 7435 return BB; 7436 case ARM::t2STRB_preidx: 7437 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 7438 return BB; 7439 case ARM::t2STRH_preidx: 7440 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 7441 return BB; 7442 7443 case ARM::STRi_preidx: 7444 case ARM::STRBi_preidx: { 7445 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 7446 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 7447 // Decode the offset. 7448 unsigned Offset = MI->getOperand(4).getImm(); 7449 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 7450 Offset = ARM_AM::getAM2Offset(Offset); 7451 if (isSub) 7452 Offset = -Offset; 7453 7454 MachineMemOperand *MMO = *MI->memoperands_begin(); 7455 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 7456 .addOperand(MI->getOperand(0)) // Rn_wb 7457 .addOperand(MI->getOperand(1)) // Rt 7458 .addOperand(MI->getOperand(2)) // Rn 7459 .addImm(Offset) // offset (skip GPR==zero_reg) 7460 .addOperand(MI->getOperand(5)) // pred 7461 .addOperand(MI->getOperand(6)) 7462 .addMemOperand(MMO); 7463 MI->eraseFromParent(); 7464 return BB; 7465 } 7466 case ARM::STRr_preidx: 7467 case ARM::STRBr_preidx: 7468 case ARM::STRH_preidx: { 7469 unsigned NewOpc; 7470 switch (MI->getOpcode()) { 7471 default: llvm_unreachable("unexpected opcode!"); 7472 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 7473 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 7474 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 7475 } 7476 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 7477 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 7478 MIB.addOperand(MI->getOperand(i)); 7479 MI->eraseFromParent(); 7480 return BB; 7481 } 7482 7483 case ARM::tMOVCCr_pseudo: { 7484 // To "insert" a SELECT_CC instruction, we actually have to insert the 7485 // diamond control-flow pattern. The incoming instruction knows the 7486 // destination vreg to set, the condition code register to branch on, the 7487 // true/false values to select between, and a branch opcode to use. 7488 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7489 MachineFunction::iterator It = BB; 7490 ++It; 7491 7492 // thisMBB: 7493 // ... 7494 // TrueVal = ... 7495 // cmpTY ccX, r1, r2 7496 // bCC copy1MBB 7497 // fallthrough --> copy0MBB 7498 MachineBasicBlock *thisMBB = BB; 7499 MachineFunction *F = BB->getParent(); 7500 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 7501 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 7502 F->insert(It, copy0MBB); 7503 F->insert(It, sinkMBB); 7504 7505 // Transfer the remainder of BB and its successor edges to sinkMBB. 7506 sinkMBB->splice(sinkMBB->begin(), BB, 7507 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7508 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 7509 7510 BB->addSuccessor(copy0MBB); 7511 BB->addSuccessor(sinkMBB); 7512 7513 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 7514 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 7515 7516 // copy0MBB: 7517 // %FalseValue = ... 7518 // # fallthrough to sinkMBB 7519 BB = copy0MBB; 7520 7521 // Update machine-CFG edges 7522 BB->addSuccessor(sinkMBB); 7523 7524 // sinkMBB: 7525 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 7526 // ... 7527 BB = sinkMBB; 7528 BuildMI(*BB, BB->begin(), dl, 7529 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 7530 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 7531 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 7532 7533 MI->eraseFromParent(); // The pseudo instruction is gone now. 7534 return BB; 7535 } 7536 7537 case ARM::BCCi64: 7538 case ARM::BCCZi64: { 7539 // If there is an unconditional branch to the other successor, remove it. 7540 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7541 7542 // Compare both parts that make up the double comparison separately for 7543 // equality. 7544 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 7545 7546 unsigned LHS1 = MI->getOperand(1).getReg(); 7547 unsigned LHS2 = MI->getOperand(2).getReg(); 7548 if (RHSisZero) { 7549 AddDefaultPred(BuildMI(BB, dl, 7550 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 7551 .addReg(LHS1).addImm(0)); 7552 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 7553 .addReg(LHS2).addImm(0) 7554 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 7555 } else { 7556 unsigned RHS1 = MI->getOperand(3).getReg(); 7557 unsigned RHS2 = MI->getOperand(4).getReg(); 7558 AddDefaultPred(BuildMI(BB, dl, 7559 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 7560 .addReg(LHS1).addReg(RHS1)); 7561 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 7562 .addReg(LHS2).addReg(RHS2) 7563 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 7564 } 7565 7566 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 7567 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 7568 if (MI->getOperand(0).getImm() == ARMCC::NE) 7569 std::swap(destMBB, exitMBB); 7570 7571 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7572 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 7573 if (isThumb2) 7574 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 7575 else 7576 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 7577 7578 MI->eraseFromParent(); // The pseudo instruction is gone now. 7579 return BB; 7580 } 7581 7582 case ARM::Int_eh_sjlj_setjmp: 7583 case ARM::Int_eh_sjlj_setjmp_nofp: 7584 case ARM::tInt_eh_sjlj_setjmp: 7585 case ARM::t2Int_eh_sjlj_setjmp: 7586 case ARM::t2Int_eh_sjlj_setjmp_nofp: 7587 EmitSjLjDispatchBlock(MI, BB); 7588 return BB; 7589 7590 case ARM::ABS: 7591 case ARM::t2ABS: { 7592 // To insert an ABS instruction, we have to insert the 7593 // diamond control-flow pattern. The incoming instruction knows the 7594 // source vreg to test against 0, the destination vreg to set, 7595 // the condition code register to branch on, the 7596 // true/false values to select between, and a branch opcode to use. 7597 // It transforms 7598 // V1 = ABS V0 7599 // into 7600 // V2 = MOVS V0 7601 // BCC (branch to SinkBB if V0 >= 0) 7602 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 7603 // SinkBB: V1 = PHI(V2, V3) 7604 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7605 MachineFunction::iterator BBI = BB; 7606 ++BBI; 7607 MachineFunction *Fn = BB->getParent(); 7608 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 7609 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 7610 Fn->insert(BBI, RSBBB); 7611 Fn->insert(BBI, SinkBB); 7612 7613 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 7614 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 7615 bool isThumb2 = Subtarget->isThumb2(); 7616 MachineRegisterInfo &MRI = Fn->getRegInfo(); 7617 // In Thumb mode S must not be specified if source register is the SP or 7618 // PC and if destination register is the SP, so restrict register class 7619 unsigned NewRsbDstReg = 7620 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 7621 7622 // Transfer the remainder of BB and its successor edges to sinkMBB. 7623 SinkBB->splice(SinkBB->begin(), BB, 7624 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7625 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 7626 7627 BB->addSuccessor(RSBBB); 7628 BB->addSuccessor(SinkBB); 7629 7630 // fall through to SinkMBB 7631 RSBBB->addSuccessor(SinkBB); 7632 7633 // insert a cmp at the end of BB 7634 AddDefaultPred(BuildMI(BB, dl, 7635 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 7636 .addReg(ABSSrcReg).addImm(0)); 7637 7638 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 7639 BuildMI(BB, dl, 7640 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 7641 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 7642 7643 // insert rsbri in RSBBB 7644 // Note: BCC and rsbri will be converted into predicated rsbmi 7645 // by if-conversion pass 7646 BuildMI(*RSBBB, RSBBB->begin(), dl, 7647 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 7648 .addReg(ABSSrcReg, RegState::Kill) 7649 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 7650 7651 // insert PHI in SinkBB, 7652 // reuse ABSDstReg to not change uses of ABS instruction 7653 BuildMI(*SinkBB, SinkBB->begin(), dl, 7654 TII->get(ARM::PHI), ABSDstReg) 7655 .addReg(NewRsbDstReg).addMBB(RSBBB) 7656 .addReg(ABSSrcReg).addMBB(BB); 7657 7658 // remove ABS instruction 7659 MI->eraseFromParent(); 7660 7661 // return last added BB 7662 return SinkBB; 7663 } 7664 case ARM::COPY_STRUCT_BYVAL_I32: 7665 ++NumLoopByVals; 7666 return EmitStructByval(MI, BB); 7667 case ARM::WIN__CHKSTK: 7668 return EmitLowered__chkstk(MI, BB); 7669 } 7670 } 7671 7672 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 7673 SDNode *Node) const { 7674 const MCInstrDesc *MCID = &MI->getDesc(); 7675 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 7676 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 7677 // operand is still set to noreg. If needed, set the optional operand's 7678 // register to CPSR, and remove the redundant implicit def. 7679 // 7680 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 7681 7682 // Rename pseudo opcodes. 7683 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 7684 if (NewOpc) { 7685 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 7686 MCID = &TII->get(NewOpc); 7687 7688 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 7689 "converted opcode should be the same except for cc_out"); 7690 7691 MI->setDesc(*MCID); 7692 7693 // Add the optional cc_out operand 7694 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 7695 } 7696 unsigned ccOutIdx = MCID->getNumOperands() - 1; 7697 7698 // Any ARM instruction that sets the 's' bit should specify an optional 7699 // "cc_out" operand in the last operand position. 7700 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 7701 assert(!NewOpc && "Optional cc_out operand required"); 7702 return; 7703 } 7704 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 7705 // since we already have an optional CPSR def. 7706 bool definesCPSR = false; 7707 bool deadCPSR = false; 7708 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 7709 i != e; ++i) { 7710 const MachineOperand &MO = MI->getOperand(i); 7711 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 7712 definesCPSR = true; 7713 if (MO.isDead()) 7714 deadCPSR = true; 7715 MI->RemoveOperand(i); 7716 break; 7717 } 7718 } 7719 if (!definesCPSR) { 7720 assert(!NewOpc && "Optional cc_out operand required"); 7721 return; 7722 } 7723 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 7724 if (deadCPSR) { 7725 assert(!MI->getOperand(ccOutIdx).getReg() && 7726 "expect uninitialized optional cc_out operand"); 7727 return; 7728 } 7729 7730 // If this instruction was defined with an optional CPSR def and its dag node 7731 // had a live implicit CPSR def, then activate the optional CPSR def. 7732 MachineOperand &MO = MI->getOperand(ccOutIdx); 7733 MO.setReg(ARM::CPSR); 7734 MO.setIsDef(true); 7735 } 7736 7737 //===----------------------------------------------------------------------===// 7738 // ARM Optimization Hooks 7739 //===----------------------------------------------------------------------===// 7740 7741 // Helper function that checks if N is a null or all ones constant. 7742 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 7743 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N); 7744 if (!C) 7745 return false; 7746 return AllOnes ? C->isAllOnesValue() : C->isNullValue(); 7747 } 7748 7749 // Return true if N is conditionally 0 or all ones. 7750 // Detects these expressions where cc is an i1 value: 7751 // 7752 // (select cc 0, y) [AllOnes=0] 7753 // (select cc y, 0) [AllOnes=0] 7754 // (zext cc) [AllOnes=0] 7755 // (sext cc) [AllOnes=0/1] 7756 // (select cc -1, y) [AllOnes=1] 7757 // (select cc y, -1) [AllOnes=1] 7758 // 7759 // Invert is set when N is the null/all ones constant when CC is false. 7760 // OtherOp is set to the alternative value of N. 7761 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 7762 SDValue &CC, bool &Invert, 7763 SDValue &OtherOp, 7764 SelectionDAG &DAG) { 7765 switch (N->getOpcode()) { 7766 default: return false; 7767 case ISD::SELECT: { 7768 CC = N->getOperand(0); 7769 SDValue N1 = N->getOperand(1); 7770 SDValue N2 = N->getOperand(2); 7771 if (isZeroOrAllOnes(N1, AllOnes)) { 7772 Invert = false; 7773 OtherOp = N2; 7774 return true; 7775 } 7776 if (isZeroOrAllOnes(N2, AllOnes)) { 7777 Invert = true; 7778 OtherOp = N1; 7779 return true; 7780 } 7781 return false; 7782 } 7783 case ISD::ZERO_EXTEND: 7784 // (zext cc) can never be the all ones value. 7785 if (AllOnes) 7786 return false; 7787 // Fall through. 7788 case ISD::SIGN_EXTEND: { 7789 EVT VT = N->getValueType(0); 7790 CC = N->getOperand(0); 7791 if (CC.getValueType() != MVT::i1) 7792 return false; 7793 Invert = !AllOnes; 7794 if (AllOnes) 7795 // When looking for an AllOnes constant, N is an sext, and the 'other' 7796 // value is 0. 7797 OtherOp = DAG.getConstant(0, VT); 7798 else if (N->getOpcode() == ISD::ZERO_EXTEND) 7799 // When looking for a 0 constant, N can be zext or sext. 7800 OtherOp = DAG.getConstant(1, VT); 7801 else 7802 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT); 7803 return true; 7804 } 7805 } 7806 } 7807 7808 // Combine a constant select operand into its use: 7809 // 7810 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 7811 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 7812 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 7813 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 7814 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 7815 // 7816 // The transform is rejected if the select doesn't have a constant operand that 7817 // is null, or all ones when AllOnes is set. 7818 // 7819 // Also recognize sext/zext from i1: 7820 // 7821 // (add (zext cc), x) -> (select cc (add x, 1), x) 7822 // (add (sext cc), x) -> (select cc (add x, -1), x) 7823 // 7824 // These transformations eventually create predicated instructions. 7825 // 7826 // @param N The node to transform. 7827 // @param Slct The N operand that is a select. 7828 // @param OtherOp The other N operand (x above). 7829 // @param DCI Context. 7830 // @param AllOnes Require the select constant to be all ones instead of null. 7831 // @returns The new node, or SDValue() on failure. 7832 static 7833 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7834 TargetLowering::DAGCombinerInfo &DCI, 7835 bool AllOnes = false) { 7836 SelectionDAG &DAG = DCI.DAG; 7837 EVT VT = N->getValueType(0); 7838 SDValue NonConstantVal; 7839 SDValue CCOp; 7840 bool SwapSelectOps; 7841 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 7842 NonConstantVal, DAG)) 7843 return SDValue(); 7844 7845 // Slct is now know to be the desired identity constant when CC is true. 7846 SDValue TrueVal = OtherOp; 7847 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 7848 OtherOp, NonConstantVal); 7849 // Unless SwapSelectOps says CC should be false. 7850 if (SwapSelectOps) 7851 std::swap(TrueVal, FalseVal); 7852 7853 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7854 CCOp, TrueVal, FalseVal); 7855 } 7856 7857 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7858 static 7859 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 7860 TargetLowering::DAGCombinerInfo &DCI) { 7861 SDValue N0 = N->getOperand(0); 7862 SDValue N1 = N->getOperand(1); 7863 if (N0.getNode()->hasOneUse()) { 7864 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes); 7865 if (Result.getNode()) 7866 return Result; 7867 } 7868 if (N1.getNode()->hasOneUse()) { 7869 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes); 7870 if (Result.getNode()) 7871 return Result; 7872 } 7873 return SDValue(); 7874 } 7875 7876 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 7877 // (only after legalization). 7878 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 7879 TargetLowering::DAGCombinerInfo &DCI, 7880 const ARMSubtarget *Subtarget) { 7881 7882 // Only perform optimization if after legalize, and if NEON is available. We 7883 // also expected both operands to be BUILD_VECTORs. 7884 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 7885 || N0.getOpcode() != ISD::BUILD_VECTOR 7886 || N1.getOpcode() != ISD::BUILD_VECTOR) 7887 return SDValue(); 7888 7889 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 7890 EVT VT = N->getValueType(0); 7891 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 7892 return SDValue(); 7893 7894 // Check that the vector operands are of the right form. 7895 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 7896 // operands, where N is the size of the formed vector. 7897 // Each EXTRACT_VECTOR should have the same input vector and odd or even 7898 // index such that we have a pair wise add pattern. 7899 7900 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 7901 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7902 return SDValue(); 7903 SDValue Vec = N0->getOperand(0)->getOperand(0); 7904 SDNode *V = Vec.getNode(); 7905 unsigned nextIndex = 0; 7906 7907 // For each operands to the ADD which are BUILD_VECTORs, 7908 // check to see if each of their operands are an EXTRACT_VECTOR with 7909 // the same vector and appropriate index. 7910 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 7911 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 7912 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 7913 7914 SDValue ExtVec0 = N0->getOperand(i); 7915 SDValue ExtVec1 = N1->getOperand(i); 7916 7917 // First operand is the vector, verify its the same. 7918 if (V != ExtVec0->getOperand(0).getNode() || 7919 V != ExtVec1->getOperand(0).getNode()) 7920 return SDValue(); 7921 7922 // Second is the constant, verify its correct. 7923 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 7924 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 7925 7926 // For the constant, we want to see all the even or all the odd. 7927 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 7928 || C1->getZExtValue() != nextIndex+1) 7929 return SDValue(); 7930 7931 // Increment index. 7932 nextIndex+=2; 7933 } else 7934 return SDValue(); 7935 } 7936 7937 // Create VPADDL node. 7938 SelectionDAG &DAG = DCI.DAG; 7939 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7940 7941 // Build operand list. 7942 SmallVector<SDValue, 8> Ops; 7943 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, 7944 TLI.getPointerTy())); 7945 7946 // Input is the vector. 7947 Ops.push_back(Vec); 7948 7949 // Get widened type and narrowed type. 7950 MVT widenType; 7951 unsigned numElem = VT.getVectorNumElements(); 7952 7953 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 7954 switch (inputLaneType.getSimpleVT().SimpleTy) { 7955 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 7956 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 7957 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 7958 default: 7959 llvm_unreachable("Invalid vector element type for padd optimization."); 7960 } 7961 7962 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops); 7963 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 7964 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp); 7965 } 7966 7967 static SDValue findMUL_LOHI(SDValue V) { 7968 if (V->getOpcode() == ISD::UMUL_LOHI || 7969 V->getOpcode() == ISD::SMUL_LOHI) 7970 return V; 7971 return SDValue(); 7972 } 7973 7974 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 7975 TargetLowering::DAGCombinerInfo &DCI, 7976 const ARMSubtarget *Subtarget) { 7977 7978 if (Subtarget->isThumb1Only()) return SDValue(); 7979 7980 // Only perform the checks after legalize when the pattern is available. 7981 if (DCI.isBeforeLegalize()) return SDValue(); 7982 7983 // Look for multiply add opportunities. 7984 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 7985 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 7986 // a glue link from the first add to the second add. 7987 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 7988 // a S/UMLAL instruction. 7989 // loAdd UMUL_LOHI 7990 // \ / :lo \ :hi 7991 // \ / \ [no multiline comment] 7992 // ADDC | hiAdd 7993 // \ :glue / / 7994 // \ / / 7995 // ADDE 7996 // 7997 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 7998 SDValue AddcOp0 = AddcNode->getOperand(0); 7999 SDValue AddcOp1 = AddcNode->getOperand(1); 8000 8001 // Check if the two operands are from the same mul_lohi node. 8002 if (AddcOp0.getNode() == AddcOp1.getNode()) 8003 return SDValue(); 8004 8005 assert(AddcNode->getNumValues() == 2 && 8006 AddcNode->getValueType(0) == MVT::i32 && 8007 "Expect ADDC with two result values. First: i32"); 8008 8009 // Check that we have a glued ADDC node. 8010 if (AddcNode->getValueType(1) != MVT::Glue) 8011 return SDValue(); 8012 8013 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8014 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8015 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8016 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8017 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8018 return SDValue(); 8019 8020 // Look for the glued ADDE. 8021 SDNode* AddeNode = AddcNode->getGluedUser(); 8022 if (!AddeNode) 8023 return SDValue(); 8024 8025 // Make sure it is really an ADDE. 8026 if (AddeNode->getOpcode() != ISD::ADDE) 8027 return SDValue(); 8028 8029 assert(AddeNode->getNumOperands() == 3 && 8030 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8031 "ADDE node has the wrong inputs"); 8032 8033 // Check for the triangle shape. 8034 SDValue AddeOp0 = AddeNode->getOperand(0); 8035 SDValue AddeOp1 = AddeNode->getOperand(1); 8036 8037 // Make sure that the ADDE operands are not coming from the same node. 8038 if (AddeOp0.getNode() == AddeOp1.getNode()) 8039 return SDValue(); 8040 8041 // Find the MUL_LOHI node walking up ADDE's operands. 8042 bool IsLeftOperandMUL = false; 8043 SDValue MULOp = findMUL_LOHI(AddeOp0); 8044 if (MULOp == SDValue()) 8045 MULOp = findMUL_LOHI(AddeOp1); 8046 else 8047 IsLeftOperandMUL = true; 8048 if (MULOp == SDValue()) 8049 return SDValue(); 8050 8051 // Figure out the right opcode. 8052 unsigned Opc = MULOp->getOpcode(); 8053 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8054 8055 // Figure out the high and low input values to the MLAL node. 8056 SDValue* HiAdd = nullptr; 8057 SDValue* LoMul = nullptr; 8058 SDValue* LowAdd = nullptr; 8059 8060 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8061 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8062 return SDValue(); 8063 8064 if (IsLeftOperandMUL) 8065 HiAdd = &AddeOp1; 8066 else 8067 HiAdd = &AddeOp0; 8068 8069 8070 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8071 // whose low result is fed to the ADDC we are checking. 8072 8073 if (AddcOp0 == MULOp.getValue(0)) { 8074 LoMul = &AddcOp0; 8075 LowAdd = &AddcOp1; 8076 } 8077 if (AddcOp1 == MULOp.getValue(0)) { 8078 LoMul = &AddcOp1; 8079 LowAdd = &AddcOp0; 8080 } 8081 8082 if (!LoMul) 8083 return SDValue(); 8084 8085 // Create the merged node. 8086 SelectionDAG &DAG = DCI.DAG; 8087 8088 // Build operand list. 8089 SmallVector<SDValue, 8> Ops; 8090 Ops.push_back(LoMul->getOperand(0)); 8091 Ops.push_back(LoMul->getOperand(1)); 8092 Ops.push_back(*LowAdd); 8093 Ops.push_back(*HiAdd); 8094 8095 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8096 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8097 8098 // Replace the ADDs' nodes uses by the MLA node's values. 8099 SDValue HiMLALResult(MLALNode.getNode(), 1); 8100 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8101 8102 SDValue LoMLALResult(MLALNode.getNode(), 0); 8103 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8104 8105 // Return original node to notify the driver to stop replacing. 8106 SDValue resNode(AddcNode, 0); 8107 return resNode; 8108 } 8109 8110 /// PerformADDCCombine - Target-specific dag combine transform from 8111 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 8112 static SDValue PerformADDCCombine(SDNode *N, 8113 TargetLowering::DAGCombinerInfo &DCI, 8114 const ARMSubtarget *Subtarget) { 8115 8116 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 8117 8118 } 8119 8120 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 8121 /// operands N0 and N1. This is a helper for PerformADDCombine that is 8122 /// called with the default operands, and if that fails, with commuted 8123 /// operands. 8124 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 8125 TargetLowering::DAGCombinerInfo &DCI, 8126 const ARMSubtarget *Subtarget){ 8127 8128 // Attempt to create vpaddl for this add. 8129 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget); 8130 if (Result.getNode()) 8131 return Result; 8132 8133 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8134 if (N0.getNode()->hasOneUse()) { 8135 SDValue Result = combineSelectAndUse(N, N0, N1, DCI); 8136 if (Result.getNode()) return Result; 8137 } 8138 return SDValue(); 8139 } 8140 8141 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 8142 /// 8143 static SDValue PerformADDCombine(SDNode *N, 8144 TargetLowering::DAGCombinerInfo &DCI, 8145 const ARMSubtarget *Subtarget) { 8146 SDValue N0 = N->getOperand(0); 8147 SDValue N1 = N->getOperand(1); 8148 8149 // First try with the default operand order. 8150 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget); 8151 if (Result.getNode()) 8152 return Result; 8153 8154 // If that didn't work, try again with the operands commuted. 8155 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 8156 } 8157 8158 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 8159 /// 8160 static SDValue PerformSUBCombine(SDNode *N, 8161 TargetLowering::DAGCombinerInfo &DCI) { 8162 SDValue N0 = N->getOperand(0); 8163 SDValue N1 = N->getOperand(1); 8164 8165 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8166 if (N1.getNode()->hasOneUse()) { 8167 SDValue Result = combineSelectAndUse(N, N1, N0, DCI); 8168 if (Result.getNode()) return Result; 8169 } 8170 8171 return SDValue(); 8172 } 8173 8174 /// PerformVMULCombine 8175 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 8176 /// special multiplier accumulator forwarding. 8177 /// vmul d3, d0, d2 8178 /// vmla d3, d1, d2 8179 /// is faster than 8180 /// vadd d3, d0, d1 8181 /// vmul d3, d3, d2 8182 // However, for (A + B) * (A + B), 8183 // vadd d2, d0, d1 8184 // vmul d3, d0, d2 8185 // vmla d3, d1, d2 8186 // is slower than 8187 // vadd d2, d0, d1 8188 // vmul d3, d2, d2 8189 static SDValue PerformVMULCombine(SDNode *N, 8190 TargetLowering::DAGCombinerInfo &DCI, 8191 const ARMSubtarget *Subtarget) { 8192 if (!Subtarget->hasVMLxForwarding()) 8193 return SDValue(); 8194 8195 SelectionDAG &DAG = DCI.DAG; 8196 SDValue N0 = N->getOperand(0); 8197 SDValue N1 = N->getOperand(1); 8198 unsigned Opcode = N0.getOpcode(); 8199 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8200 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 8201 Opcode = N1.getOpcode(); 8202 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8203 Opcode != ISD::FADD && Opcode != ISD::FSUB) 8204 return SDValue(); 8205 std::swap(N0, N1); 8206 } 8207 8208 if (N0 == N1) 8209 return SDValue(); 8210 8211 EVT VT = N->getValueType(0); 8212 SDLoc DL(N); 8213 SDValue N00 = N0->getOperand(0); 8214 SDValue N01 = N0->getOperand(1); 8215 return DAG.getNode(Opcode, DL, VT, 8216 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 8217 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 8218 } 8219 8220 static SDValue PerformMULCombine(SDNode *N, 8221 TargetLowering::DAGCombinerInfo &DCI, 8222 const ARMSubtarget *Subtarget) { 8223 SelectionDAG &DAG = DCI.DAG; 8224 8225 if (Subtarget->isThumb1Only()) 8226 return SDValue(); 8227 8228 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8229 return SDValue(); 8230 8231 EVT VT = N->getValueType(0); 8232 if (VT.is64BitVector() || VT.is128BitVector()) 8233 return PerformVMULCombine(N, DCI, Subtarget); 8234 if (VT != MVT::i32) 8235 return SDValue(); 8236 8237 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8238 if (!C) 8239 return SDValue(); 8240 8241 int64_t MulAmt = C->getSExtValue(); 8242 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 8243 8244 ShiftAmt = ShiftAmt & (32 - 1); 8245 SDValue V = N->getOperand(0); 8246 SDLoc DL(N); 8247 8248 SDValue Res; 8249 MulAmt >>= ShiftAmt; 8250 8251 if (MulAmt >= 0) { 8252 if (isPowerOf2_32(MulAmt - 1)) { 8253 // (mul x, 2^N + 1) => (add (shl x, N), x) 8254 Res = DAG.getNode(ISD::ADD, DL, VT, 8255 V, 8256 DAG.getNode(ISD::SHL, DL, VT, 8257 V, 8258 DAG.getConstant(Log2_32(MulAmt - 1), 8259 MVT::i32))); 8260 } else if (isPowerOf2_32(MulAmt + 1)) { 8261 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8262 Res = DAG.getNode(ISD::SUB, DL, VT, 8263 DAG.getNode(ISD::SHL, DL, VT, 8264 V, 8265 DAG.getConstant(Log2_32(MulAmt + 1), 8266 MVT::i32)), 8267 V); 8268 } else 8269 return SDValue(); 8270 } else { 8271 uint64_t MulAmtAbs = -MulAmt; 8272 if (isPowerOf2_32(MulAmtAbs + 1)) { 8273 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8274 Res = DAG.getNode(ISD::SUB, DL, VT, 8275 V, 8276 DAG.getNode(ISD::SHL, DL, VT, 8277 V, 8278 DAG.getConstant(Log2_32(MulAmtAbs + 1), 8279 MVT::i32))); 8280 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 8281 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8282 Res = DAG.getNode(ISD::ADD, DL, VT, 8283 V, 8284 DAG.getNode(ISD::SHL, DL, VT, 8285 V, 8286 DAG.getConstant(Log2_32(MulAmtAbs-1), 8287 MVT::i32))); 8288 Res = DAG.getNode(ISD::SUB, DL, VT, 8289 DAG.getConstant(0, MVT::i32),Res); 8290 8291 } else 8292 return SDValue(); 8293 } 8294 8295 if (ShiftAmt != 0) 8296 Res = DAG.getNode(ISD::SHL, DL, VT, 8297 Res, DAG.getConstant(ShiftAmt, MVT::i32)); 8298 8299 // Do not add new nodes to DAG combiner worklist. 8300 DCI.CombineTo(N, Res, false); 8301 return SDValue(); 8302 } 8303 8304 static SDValue PerformANDCombine(SDNode *N, 8305 TargetLowering::DAGCombinerInfo &DCI, 8306 const ARMSubtarget *Subtarget) { 8307 8308 // Attempt to use immediate-form VBIC 8309 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8310 SDLoc dl(N); 8311 EVT VT = N->getValueType(0); 8312 SelectionDAG &DAG = DCI.DAG; 8313 8314 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8315 return SDValue(); 8316 8317 APInt SplatBits, SplatUndef; 8318 unsigned SplatBitSize; 8319 bool HasAnyUndefs; 8320 if (BVN && 8321 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8322 if (SplatBitSize <= 64) { 8323 EVT VbicVT; 8324 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 8325 SplatUndef.getZExtValue(), SplatBitSize, 8326 DAG, VbicVT, VT.is128BitVector(), 8327 OtherModImm); 8328 if (Val.getNode()) { 8329 SDValue Input = 8330 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 8331 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 8332 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 8333 } 8334 } 8335 } 8336 8337 if (!Subtarget->isThumb1Only()) { 8338 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 8339 SDValue Result = combineSelectAndUseCommutative(N, true, DCI); 8340 if (Result.getNode()) 8341 return Result; 8342 } 8343 8344 return SDValue(); 8345 } 8346 8347 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 8348 static SDValue PerformORCombine(SDNode *N, 8349 TargetLowering::DAGCombinerInfo &DCI, 8350 const ARMSubtarget *Subtarget) { 8351 // Attempt to use immediate-form VORR 8352 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8353 SDLoc dl(N); 8354 EVT VT = N->getValueType(0); 8355 SelectionDAG &DAG = DCI.DAG; 8356 8357 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8358 return SDValue(); 8359 8360 APInt SplatBits, SplatUndef; 8361 unsigned SplatBitSize; 8362 bool HasAnyUndefs; 8363 if (BVN && Subtarget->hasNEON() && 8364 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8365 if (SplatBitSize <= 64) { 8366 EVT VorrVT; 8367 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 8368 SplatUndef.getZExtValue(), SplatBitSize, 8369 DAG, VorrVT, VT.is128BitVector(), 8370 OtherModImm); 8371 if (Val.getNode()) { 8372 SDValue Input = 8373 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 8374 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 8375 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 8376 } 8377 } 8378 } 8379 8380 if (!Subtarget->isThumb1Only()) { 8381 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8382 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 8383 if (Result.getNode()) 8384 return Result; 8385 } 8386 8387 // The code below optimizes (or (and X, Y), Z). 8388 // The AND operand needs to have a single user to make these optimizations 8389 // profitable. 8390 SDValue N0 = N->getOperand(0); 8391 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 8392 return SDValue(); 8393 SDValue N1 = N->getOperand(1); 8394 8395 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 8396 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 8397 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 8398 APInt SplatUndef; 8399 unsigned SplatBitSize; 8400 bool HasAnyUndefs; 8401 8402 APInt SplatBits0, SplatBits1; 8403 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 8404 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 8405 // Ensure that the second operand of both ands are constants 8406 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 8407 HasAnyUndefs) && !HasAnyUndefs) { 8408 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 8409 HasAnyUndefs) && !HasAnyUndefs) { 8410 // Ensure that the bit width of the constants are the same and that 8411 // the splat arguments are logical inverses as per the pattern we 8412 // are trying to simplify. 8413 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 8414 SplatBits0 == ~SplatBits1) { 8415 // Canonicalize the vector type to make instruction selection 8416 // simpler. 8417 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 8418 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 8419 N0->getOperand(1), 8420 N0->getOperand(0), 8421 N1->getOperand(0)); 8422 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 8423 } 8424 } 8425 } 8426 } 8427 8428 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 8429 // reasonable. 8430 8431 // BFI is only available on V6T2+ 8432 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 8433 return SDValue(); 8434 8435 SDLoc DL(N); 8436 // 1) or (and A, mask), val => ARMbfi A, val, mask 8437 // iff (val & mask) == val 8438 // 8439 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 8440 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 8441 // && mask == ~mask2 8442 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 8443 // && ~mask == mask2 8444 // (i.e., copy a bitfield value into another bitfield of the same width) 8445 8446 if (VT != MVT::i32) 8447 return SDValue(); 8448 8449 SDValue N00 = N0.getOperand(0); 8450 8451 // The value and the mask need to be constants so we can verify this is 8452 // actually a bitfield set. If the mask is 0xffff, we can do better 8453 // via a movt instruction, so don't use BFI in that case. 8454 SDValue MaskOp = N0.getOperand(1); 8455 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 8456 if (!MaskC) 8457 return SDValue(); 8458 unsigned Mask = MaskC->getZExtValue(); 8459 if (Mask == 0xffff) 8460 return SDValue(); 8461 SDValue Res; 8462 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 8463 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 8464 if (N1C) { 8465 unsigned Val = N1C->getZExtValue(); 8466 if ((Val & ~Mask) != Val) 8467 return SDValue(); 8468 8469 if (ARM::isBitFieldInvertedMask(Mask)) { 8470 Val >>= countTrailingZeros(~Mask); 8471 8472 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 8473 DAG.getConstant(Val, MVT::i32), 8474 DAG.getConstant(Mask, MVT::i32)); 8475 8476 // Do not add new nodes to DAG combiner worklist. 8477 DCI.CombineTo(N, Res, false); 8478 return SDValue(); 8479 } 8480 } else if (N1.getOpcode() == ISD::AND) { 8481 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 8482 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 8483 if (!N11C) 8484 return SDValue(); 8485 unsigned Mask2 = N11C->getZExtValue(); 8486 8487 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 8488 // as is to match. 8489 if (ARM::isBitFieldInvertedMask(Mask) && 8490 (Mask == ~Mask2)) { 8491 // The pack halfword instruction works better for masks that fit it, 8492 // so use that when it's available. 8493 if (Subtarget->hasT2ExtractPack() && 8494 (Mask == 0xffff || Mask == 0xffff0000)) 8495 return SDValue(); 8496 // 2a 8497 unsigned amt = countTrailingZeros(Mask2); 8498 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 8499 DAG.getConstant(amt, MVT::i32)); 8500 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 8501 DAG.getConstant(Mask, MVT::i32)); 8502 // Do not add new nodes to DAG combiner worklist. 8503 DCI.CombineTo(N, Res, false); 8504 return SDValue(); 8505 } else if (ARM::isBitFieldInvertedMask(~Mask) && 8506 (~Mask == Mask2)) { 8507 // The pack halfword instruction works better for masks that fit it, 8508 // so use that when it's available. 8509 if (Subtarget->hasT2ExtractPack() && 8510 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 8511 return SDValue(); 8512 // 2b 8513 unsigned lsb = countTrailingZeros(Mask); 8514 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 8515 DAG.getConstant(lsb, MVT::i32)); 8516 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 8517 DAG.getConstant(Mask2, MVT::i32)); 8518 // Do not add new nodes to DAG combiner worklist. 8519 DCI.CombineTo(N, Res, false); 8520 return SDValue(); 8521 } 8522 } 8523 8524 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 8525 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 8526 ARM::isBitFieldInvertedMask(~Mask)) { 8527 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 8528 // where lsb(mask) == #shamt and masked bits of B are known zero. 8529 SDValue ShAmt = N00.getOperand(1); 8530 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 8531 unsigned LSB = countTrailingZeros(Mask); 8532 if (ShAmtC != LSB) 8533 return SDValue(); 8534 8535 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 8536 DAG.getConstant(~Mask, MVT::i32)); 8537 8538 // Do not add new nodes to DAG combiner worklist. 8539 DCI.CombineTo(N, Res, false); 8540 } 8541 8542 return SDValue(); 8543 } 8544 8545 static SDValue PerformXORCombine(SDNode *N, 8546 TargetLowering::DAGCombinerInfo &DCI, 8547 const ARMSubtarget *Subtarget) { 8548 EVT VT = N->getValueType(0); 8549 SelectionDAG &DAG = DCI.DAG; 8550 8551 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8552 return SDValue(); 8553 8554 if (!Subtarget->isThumb1Only()) { 8555 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8556 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 8557 if (Result.getNode()) 8558 return Result; 8559 } 8560 8561 return SDValue(); 8562 } 8563 8564 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 8565 /// the bits being cleared by the AND are not demanded by the BFI. 8566 static SDValue PerformBFICombine(SDNode *N, 8567 TargetLowering::DAGCombinerInfo &DCI) { 8568 SDValue N1 = N->getOperand(1); 8569 if (N1.getOpcode() == ISD::AND) { 8570 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 8571 if (!N11C) 8572 return SDValue(); 8573 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 8574 unsigned LSB = countTrailingZeros(~InvMask); 8575 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 8576 assert(Width < 8577 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 8578 "undefined behavior"); 8579 unsigned Mask = (1u << Width) - 1; 8580 unsigned Mask2 = N11C->getZExtValue(); 8581 if ((Mask & (~Mask2)) == 0) 8582 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 8583 N->getOperand(0), N1.getOperand(0), 8584 N->getOperand(2)); 8585 } 8586 return SDValue(); 8587 } 8588 8589 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 8590 /// ARMISD::VMOVRRD. 8591 static SDValue PerformVMOVRRDCombine(SDNode *N, 8592 TargetLowering::DAGCombinerInfo &DCI, 8593 const ARMSubtarget *Subtarget) { 8594 // vmovrrd(vmovdrr x, y) -> x,y 8595 SDValue InDouble = N->getOperand(0); 8596 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 8597 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 8598 8599 // vmovrrd(load f64) -> (load i32), (load i32) 8600 SDNode *InNode = InDouble.getNode(); 8601 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 8602 InNode->getValueType(0) == MVT::f64 && 8603 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 8604 !cast<LoadSDNode>(InNode)->isVolatile()) { 8605 // TODO: Should this be done for non-FrameIndex operands? 8606 LoadSDNode *LD = cast<LoadSDNode>(InNode); 8607 8608 SelectionDAG &DAG = DCI.DAG; 8609 SDLoc DL(LD); 8610 SDValue BasePtr = LD->getBasePtr(); 8611 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 8612 LD->getPointerInfo(), LD->isVolatile(), 8613 LD->isNonTemporal(), LD->isInvariant(), 8614 LD->getAlignment()); 8615 8616 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 8617 DAG.getConstant(4, MVT::i32)); 8618 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 8619 LD->getPointerInfo(), LD->isVolatile(), 8620 LD->isNonTemporal(), LD->isInvariant(), 8621 std::min(4U, LD->getAlignment() / 2)); 8622 8623 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 8624 if (DCI.DAG.getTargetLoweringInfo().isBigEndian()) 8625 std::swap (NewLD1, NewLD2); 8626 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 8627 return Result; 8628 } 8629 8630 return SDValue(); 8631 } 8632 8633 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 8634 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 8635 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 8636 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 8637 SDValue Op0 = N->getOperand(0); 8638 SDValue Op1 = N->getOperand(1); 8639 if (Op0.getOpcode() == ISD::BITCAST) 8640 Op0 = Op0.getOperand(0); 8641 if (Op1.getOpcode() == ISD::BITCAST) 8642 Op1 = Op1.getOperand(0); 8643 if (Op0.getOpcode() == ARMISD::VMOVRRD && 8644 Op0.getNode() == Op1.getNode() && 8645 Op0.getResNo() == 0 && Op1.getResNo() == 1) 8646 return DAG.getNode(ISD::BITCAST, SDLoc(N), 8647 N->getValueType(0), Op0.getOperand(0)); 8648 return SDValue(); 8649 } 8650 8651 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 8652 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 8653 /// i64 vector to have f64 elements, since the value can then be loaded 8654 /// directly into a VFP register. 8655 static bool hasNormalLoadOperand(SDNode *N) { 8656 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 8657 for (unsigned i = 0; i < NumElts; ++i) { 8658 SDNode *Elt = N->getOperand(i).getNode(); 8659 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 8660 return true; 8661 } 8662 return false; 8663 } 8664 8665 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 8666 /// ISD::BUILD_VECTOR. 8667 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 8668 TargetLowering::DAGCombinerInfo &DCI, 8669 const ARMSubtarget *Subtarget) { 8670 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 8671 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 8672 // into a pair of GPRs, which is fine when the value is used as a scalar, 8673 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 8674 SelectionDAG &DAG = DCI.DAG; 8675 if (N->getNumOperands() == 2) { 8676 SDValue RV = PerformVMOVDRRCombine(N, DAG); 8677 if (RV.getNode()) 8678 return RV; 8679 } 8680 8681 // Load i64 elements as f64 values so that type legalization does not split 8682 // them up into i32 values. 8683 EVT VT = N->getValueType(0); 8684 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 8685 return SDValue(); 8686 SDLoc dl(N); 8687 SmallVector<SDValue, 8> Ops; 8688 unsigned NumElts = VT.getVectorNumElements(); 8689 for (unsigned i = 0; i < NumElts; ++i) { 8690 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 8691 Ops.push_back(V); 8692 // Make the DAGCombiner fold the bitcast. 8693 DCI.AddToWorklist(V.getNode()); 8694 } 8695 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 8696 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops); 8697 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 8698 } 8699 8700 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 8701 static SDValue 8702 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 8703 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 8704 // At that time, we may have inserted bitcasts from integer to float. 8705 // If these bitcasts have survived DAGCombine, change the lowering of this 8706 // BUILD_VECTOR in something more vector friendly, i.e., that does not 8707 // force to use floating point types. 8708 8709 // Make sure we can change the type of the vector. 8710 // This is possible iff: 8711 // 1. The vector is only used in a bitcast to a integer type. I.e., 8712 // 1.1. Vector is used only once. 8713 // 1.2. Use is a bit convert to an integer type. 8714 // 2. The size of its operands are 32-bits (64-bits are not legal). 8715 EVT VT = N->getValueType(0); 8716 EVT EltVT = VT.getVectorElementType(); 8717 8718 // Check 1.1. and 2. 8719 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 8720 return SDValue(); 8721 8722 // By construction, the input type must be float. 8723 assert(EltVT == MVT::f32 && "Unexpected type!"); 8724 8725 // Check 1.2. 8726 SDNode *Use = *N->use_begin(); 8727 if (Use->getOpcode() != ISD::BITCAST || 8728 Use->getValueType(0).isFloatingPoint()) 8729 return SDValue(); 8730 8731 // Check profitability. 8732 // Model is, if more than half of the relevant operands are bitcast from 8733 // i32, turn the build_vector into a sequence of insert_vector_elt. 8734 // Relevant operands are everything that is not statically 8735 // (i.e., at compile time) bitcasted. 8736 unsigned NumOfBitCastedElts = 0; 8737 unsigned NumElts = VT.getVectorNumElements(); 8738 unsigned NumOfRelevantElts = NumElts; 8739 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 8740 SDValue Elt = N->getOperand(Idx); 8741 if (Elt->getOpcode() == ISD::BITCAST) { 8742 // Assume only bit cast to i32 will go away. 8743 if (Elt->getOperand(0).getValueType() == MVT::i32) 8744 ++NumOfBitCastedElts; 8745 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt)) 8746 // Constants are statically casted, thus do not count them as 8747 // relevant operands. 8748 --NumOfRelevantElts; 8749 } 8750 8751 // Check if more than half of the elements require a non-free bitcast. 8752 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 8753 return SDValue(); 8754 8755 SelectionDAG &DAG = DCI.DAG; 8756 // Create the new vector type. 8757 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 8758 // Check if the type is legal. 8759 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8760 if (!TLI.isTypeLegal(VecVT)) 8761 return SDValue(); 8762 8763 // Combine: 8764 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 8765 // => BITCAST INSERT_VECTOR_ELT 8766 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 8767 // (BITCAST EN), N. 8768 SDValue Vec = DAG.getUNDEF(VecVT); 8769 SDLoc dl(N); 8770 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 8771 SDValue V = N->getOperand(Idx); 8772 if (V.getOpcode() == ISD::UNDEF) 8773 continue; 8774 if (V.getOpcode() == ISD::BITCAST && 8775 V->getOperand(0).getValueType() == MVT::i32) 8776 // Fold obvious case. 8777 V = V.getOperand(0); 8778 else { 8779 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 8780 // Make the DAGCombiner fold the bitcasts. 8781 DCI.AddToWorklist(V.getNode()); 8782 } 8783 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32); 8784 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 8785 } 8786 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 8787 // Make the DAGCombiner fold the bitcasts. 8788 DCI.AddToWorklist(Vec.getNode()); 8789 return Vec; 8790 } 8791 8792 /// PerformInsertEltCombine - Target-specific dag combine xforms for 8793 /// ISD::INSERT_VECTOR_ELT. 8794 static SDValue PerformInsertEltCombine(SDNode *N, 8795 TargetLowering::DAGCombinerInfo &DCI) { 8796 // Bitcast an i64 load inserted into a vector to f64. 8797 // Otherwise, the i64 value will be legalized to a pair of i32 values. 8798 EVT VT = N->getValueType(0); 8799 SDNode *Elt = N->getOperand(1).getNode(); 8800 if (VT.getVectorElementType() != MVT::i64 || 8801 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 8802 return SDValue(); 8803 8804 SelectionDAG &DAG = DCI.DAG; 8805 SDLoc dl(N); 8806 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 8807 VT.getVectorNumElements()); 8808 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 8809 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 8810 // Make the DAGCombiner fold the bitcasts. 8811 DCI.AddToWorklist(Vec.getNode()); 8812 DCI.AddToWorklist(V.getNode()); 8813 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 8814 Vec, V, N->getOperand(2)); 8815 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 8816 } 8817 8818 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 8819 /// ISD::VECTOR_SHUFFLE. 8820 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 8821 // The LLVM shufflevector instruction does not require the shuffle mask 8822 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 8823 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 8824 // operands do not match the mask length, they are extended by concatenating 8825 // them with undef vectors. That is probably the right thing for other 8826 // targets, but for NEON it is better to concatenate two double-register 8827 // size vector operands into a single quad-register size vector. Do that 8828 // transformation here: 8829 // shuffle(concat(v1, undef), concat(v2, undef)) -> 8830 // shuffle(concat(v1, v2), undef) 8831 SDValue Op0 = N->getOperand(0); 8832 SDValue Op1 = N->getOperand(1); 8833 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 8834 Op1.getOpcode() != ISD::CONCAT_VECTORS || 8835 Op0.getNumOperands() != 2 || 8836 Op1.getNumOperands() != 2) 8837 return SDValue(); 8838 SDValue Concat0Op1 = Op0.getOperand(1); 8839 SDValue Concat1Op1 = Op1.getOperand(1); 8840 if (Concat0Op1.getOpcode() != ISD::UNDEF || 8841 Concat1Op1.getOpcode() != ISD::UNDEF) 8842 return SDValue(); 8843 // Skip the transformation if any of the types are illegal. 8844 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8845 EVT VT = N->getValueType(0); 8846 if (!TLI.isTypeLegal(VT) || 8847 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 8848 !TLI.isTypeLegal(Concat1Op1.getValueType())) 8849 return SDValue(); 8850 8851 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 8852 Op0.getOperand(0), Op1.getOperand(0)); 8853 // Translate the shuffle mask. 8854 SmallVector<int, 16> NewMask; 8855 unsigned NumElts = VT.getVectorNumElements(); 8856 unsigned HalfElts = NumElts/2; 8857 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 8858 for (unsigned n = 0; n < NumElts; ++n) { 8859 int MaskElt = SVN->getMaskElt(n); 8860 int NewElt = -1; 8861 if (MaskElt < (int)HalfElts) 8862 NewElt = MaskElt; 8863 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 8864 NewElt = HalfElts + MaskElt - NumElts; 8865 NewMask.push_back(NewElt); 8866 } 8867 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 8868 DAG.getUNDEF(VT), NewMask.data()); 8869 } 8870 8871 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 8872 /// NEON load/store intrinsics, and generic vector load/stores, to merge 8873 /// base address updates. 8874 /// For generic load/stores, the memory type is assumed to be a vector. 8875 /// The caller is assumed to have checked legality. 8876 static SDValue CombineBaseUpdate(SDNode *N, 8877 TargetLowering::DAGCombinerInfo &DCI) { 8878 SelectionDAG &DAG = DCI.DAG; 8879 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 8880 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 8881 bool isStore = N->getOpcode() == ISD::STORE; 8882 unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 8883 SDValue Addr = N->getOperand(AddrOpIdx); 8884 8885 // Search for a use of the address operand that is an increment. 8886 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 8887 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 8888 SDNode *User = *UI; 8889 if (User->getOpcode() != ISD::ADD || 8890 UI.getUse().getResNo() != Addr.getResNo()) 8891 continue; 8892 8893 // Check that the add is independent of the load/store. Otherwise, folding 8894 // it would create a cycle. 8895 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 8896 continue; 8897 8898 // Find the new opcode for the updating load/store. 8899 bool isLoad = true; 8900 bool isLaneOp = false; 8901 unsigned NewOpc = 0; 8902 unsigned NumVecs = 0; 8903 if (isIntrinsic) { 8904 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 8905 switch (IntNo) { 8906 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 8907 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 8908 NumVecs = 1; break; 8909 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 8910 NumVecs = 2; break; 8911 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 8912 NumVecs = 3; break; 8913 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 8914 NumVecs = 4; break; 8915 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 8916 NumVecs = 2; isLaneOp = true; break; 8917 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 8918 NumVecs = 3; isLaneOp = true; break; 8919 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 8920 NumVecs = 4; isLaneOp = true; break; 8921 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 8922 NumVecs = 1; isLoad = false; break; 8923 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 8924 NumVecs = 2; isLoad = false; break; 8925 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 8926 NumVecs = 3; isLoad = false; break; 8927 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 8928 NumVecs = 4; isLoad = false; break; 8929 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 8930 NumVecs = 2; isLoad = false; isLaneOp = true; break; 8931 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 8932 NumVecs = 3; isLoad = false; isLaneOp = true; break; 8933 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 8934 NumVecs = 4; isLoad = false; isLaneOp = true; break; 8935 } 8936 } else { 8937 isLaneOp = true; 8938 switch (N->getOpcode()) { 8939 default: llvm_unreachable("unexpected opcode for Neon base update"); 8940 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 8941 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 8942 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 8943 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 8944 NumVecs = 1; isLaneOp = false; break; 8945 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 8946 NumVecs = 1; isLoad = false; isLaneOp = false; break; 8947 } 8948 } 8949 8950 // Find the size of memory referenced by the load/store. 8951 EVT VecTy; 8952 if (isLoad) 8953 VecTy = N->getValueType(0); 8954 else if (isIntrinsic) 8955 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 8956 else 8957 VecTy = N->getOperand(1).getValueType(); 8958 8959 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 8960 if (isLaneOp) 8961 NumBytes /= VecTy.getVectorNumElements(); 8962 8963 // If the increment is a constant, it must match the memory ref size. 8964 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 8965 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 8966 uint64_t IncVal = CInc->getZExtValue(); 8967 if (IncVal != NumBytes) 8968 continue; 8969 } else if (NumBytes >= 3 * 16) { 8970 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 8971 // separate instructions that make it harder to use a non-constant update. 8972 continue; 8973 } 8974 8975 EVT AlignedVecTy = VecTy; 8976 8977 // If this is a less-than-standard-aligned load/store, change the type to 8978 // match the standard alignment. 8979 // The alignment is overlooked when selecting _UPD variants; and it's 8980 // easier to introduce bitcasts here than fix that. 8981 // There are 3 ways to get to this base-update combine: 8982 // - intrinsics: they are assumed to be properly aligned (to the standard 8983 // alignment of the memory type), so we don't need to do anything. 8984 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 8985 // intrinsics, so, likewise, there's nothing to do. 8986 // - generic load/store instructions: the alignment is specified as an 8987 // explicit operand, rather than implicitly as the standard alignment 8988 // of the memory type (like the intrisics). We need to change the 8989 // memory type to match the explicit alignment. That way, we don't 8990 // generate non-standard-aligned ARMISD::VLDx nodes. 8991 if (LSBaseSDNode *LSN = dyn_cast<LSBaseSDNode>(N)) { 8992 unsigned Alignment = LSN->getAlignment(); 8993 if (Alignment == 0) 8994 Alignment = 1; 8995 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 8996 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 8997 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 8998 assert(!isLaneOp && "Unexpected generic load/store lane."); 8999 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 9000 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 9001 } 9002 } 9003 9004 // Create the new updating load/store node. 9005 // First, create an SDVTList for the new updating node's results. 9006 EVT Tys[6]; 9007 unsigned NumResultVecs = (isLoad ? NumVecs : 0); 9008 unsigned n; 9009 for (n = 0; n < NumResultVecs; ++n) 9010 Tys[n] = AlignedVecTy; 9011 Tys[n++] = MVT::i32; 9012 Tys[n] = MVT::Other; 9013 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 9014 9015 // Then, gather the new node's operands. 9016 SmallVector<SDValue, 8> Ops; 9017 Ops.push_back(N->getOperand(0)); // incoming chain 9018 Ops.push_back(N->getOperand(AddrOpIdx)); 9019 Ops.push_back(Inc); 9020 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 9021 // Try to match the intrinsic's signature 9022 Ops.push_back(StN->getValue()); 9023 Ops.push_back(DAG.getConstant(StN->getAlignment(), MVT::i32)); 9024 } else { 9025 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) 9026 Ops.push_back(N->getOperand(i)); 9027 } 9028 9029 // If this is a non-standard-aligned store, the penultimate operand is the 9030 // stored value. Bitcast it to the aligned type. 9031 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 9032 SDValue &StVal = Ops[Ops.size()-2]; 9033 StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal); 9034 } 9035 9036 MemSDNode *MemInt = cast<MemSDNode>(N); 9037 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, 9038 Ops, AlignedVecTy, 9039 MemInt->getMemOperand()); 9040 9041 // Update the uses. 9042 std::vector<SDValue> NewResults; 9043 for (unsigned i = 0; i < NumResultVecs; ++i) { 9044 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9045 } 9046 9047 // If this is an non-standard-aligned load, the first result is the loaded 9048 // value. Bitcast it to the expected result type. 9049 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 9050 SDValue &LdVal = NewResults[0]; 9051 LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal); 9052 } 9053 9054 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 9055 DCI.CombineTo(N, NewResults); 9056 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9057 9058 break; 9059 } 9060 return SDValue(); 9061 } 9062 9063 static SDValue PerformVLDCombine(SDNode *N, 9064 TargetLowering::DAGCombinerInfo &DCI) { 9065 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9066 return SDValue(); 9067 9068 return CombineBaseUpdate(N, DCI); 9069 } 9070 9071 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 9072 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 9073 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 9074 /// return true. 9075 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9076 SelectionDAG &DAG = DCI.DAG; 9077 EVT VT = N->getValueType(0); 9078 // vldN-dup instructions only support 64-bit vectors for N > 1. 9079 if (!VT.is64BitVector()) 9080 return false; 9081 9082 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 9083 SDNode *VLD = N->getOperand(0).getNode(); 9084 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 9085 return false; 9086 unsigned NumVecs = 0; 9087 unsigned NewOpc = 0; 9088 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 9089 if (IntNo == Intrinsic::arm_neon_vld2lane) { 9090 NumVecs = 2; 9091 NewOpc = ARMISD::VLD2DUP; 9092 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 9093 NumVecs = 3; 9094 NewOpc = ARMISD::VLD3DUP; 9095 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 9096 NumVecs = 4; 9097 NewOpc = ARMISD::VLD4DUP; 9098 } else { 9099 return false; 9100 } 9101 9102 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 9103 // numbers match the load. 9104 unsigned VLDLaneNo = 9105 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 9106 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9107 UI != UE; ++UI) { 9108 // Ignore uses of the chain result. 9109 if (UI.getUse().getResNo() == NumVecs) 9110 continue; 9111 SDNode *User = *UI; 9112 if (User->getOpcode() != ARMISD::VDUPLANE || 9113 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 9114 return false; 9115 } 9116 9117 // Create the vldN-dup node. 9118 EVT Tys[5]; 9119 unsigned n; 9120 for (n = 0; n < NumVecs; ++n) 9121 Tys[n] = VT; 9122 Tys[n] = MVT::Other; 9123 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 9124 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 9125 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 9126 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 9127 Ops, VLDMemInt->getMemoryVT(), 9128 VLDMemInt->getMemOperand()); 9129 9130 // Update the uses. 9131 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9132 UI != UE; ++UI) { 9133 unsigned ResNo = UI.getUse().getResNo(); 9134 // Ignore uses of the chain result. 9135 if (ResNo == NumVecs) 9136 continue; 9137 SDNode *User = *UI; 9138 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 9139 } 9140 9141 // Now the vldN-lane intrinsic is dead except for its chain result. 9142 // Update uses of the chain. 9143 std::vector<SDValue> VLDDupResults; 9144 for (unsigned n = 0; n < NumVecs; ++n) 9145 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 9146 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 9147 DCI.CombineTo(VLD, VLDDupResults); 9148 9149 return true; 9150 } 9151 9152 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 9153 /// ARMISD::VDUPLANE. 9154 static SDValue PerformVDUPLANECombine(SDNode *N, 9155 TargetLowering::DAGCombinerInfo &DCI) { 9156 SDValue Op = N->getOperand(0); 9157 9158 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 9159 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 9160 if (CombineVLDDUP(N, DCI)) 9161 return SDValue(N, 0); 9162 9163 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 9164 // redundant. Ignore bit_converts for now; element sizes are checked below. 9165 while (Op.getOpcode() == ISD::BITCAST) 9166 Op = Op.getOperand(0); 9167 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 9168 return SDValue(); 9169 9170 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 9171 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 9172 // The canonical VMOV for a zero vector uses a 32-bit element size. 9173 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9174 unsigned EltBits; 9175 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 9176 EltSize = 8; 9177 EVT VT = N->getValueType(0); 9178 if (EltSize > VT.getVectorElementType().getSizeInBits()) 9179 return SDValue(); 9180 9181 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 9182 } 9183 9184 static SDValue PerformLOADCombine(SDNode *N, 9185 TargetLowering::DAGCombinerInfo &DCI) { 9186 EVT VT = N->getValueType(0); 9187 9188 // If this is a legal vector load, try to combine it into a VLD1_UPD. 9189 if (ISD::isNormalLoad(N) && VT.isVector() && 9190 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9191 return CombineBaseUpdate(N, DCI); 9192 9193 return SDValue(); 9194 } 9195 9196 /// PerformSTORECombine - Target-specific dag combine xforms for 9197 /// ISD::STORE. 9198 static SDValue PerformSTORECombine(SDNode *N, 9199 TargetLowering::DAGCombinerInfo &DCI) { 9200 StoreSDNode *St = cast<StoreSDNode>(N); 9201 if (St->isVolatile()) 9202 return SDValue(); 9203 9204 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 9205 // pack all of the elements in one place. Next, store to memory in fewer 9206 // chunks. 9207 SDValue StVal = St->getValue(); 9208 EVT VT = StVal.getValueType(); 9209 if (St->isTruncatingStore() && VT.isVector()) { 9210 SelectionDAG &DAG = DCI.DAG; 9211 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9212 EVT StVT = St->getMemoryVT(); 9213 unsigned NumElems = VT.getVectorNumElements(); 9214 assert(StVT != VT && "Cannot truncate to the same type"); 9215 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 9216 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 9217 9218 // From, To sizes and ElemCount must be pow of two 9219 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 9220 9221 // We are going to use the original vector elt for storing. 9222 // Accumulated smaller vector elements must be a multiple of the store size. 9223 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 9224 9225 unsigned SizeRatio = FromEltSz / ToEltSz; 9226 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 9227 9228 // Create a type on which we perform the shuffle. 9229 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 9230 NumElems*SizeRatio); 9231 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 9232 9233 SDLoc DL(St); 9234 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 9235 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 9236 for (unsigned i = 0; i < NumElems; ++i) 9237 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio; 9238 9239 // Can't shuffle using an illegal type. 9240 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 9241 9242 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 9243 DAG.getUNDEF(WideVec.getValueType()), 9244 ShuffleVec.data()); 9245 // At this point all of the data is stored at the bottom of the 9246 // register. We now need to save it to mem. 9247 9248 // Find the largest store unit 9249 MVT StoreType = MVT::i8; 9250 for (MVT Tp : MVT::integer_valuetypes()) { 9251 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 9252 StoreType = Tp; 9253 } 9254 // Didn't find a legal store type. 9255 if (!TLI.isTypeLegal(StoreType)) 9256 return SDValue(); 9257 9258 // Bitcast the original vector into a vector of store-size units 9259 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 9260 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 9261 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 9262 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 9263 SmallVector<SDValue, 8> Chains; 9264 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, 9265 TLI.getPointerTy()); 9266 SDValue BasePtr = St->getBasePtr(); 9267 9268 // Perform one or more big stores into memory. 9269 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 9270 for (unsigned I = 0; I < E; I++) { 9271 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 9272 StoreType, ShuffWide, 9273 DAG.getIntPtrConstant(I)); 9274 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 9275 St->getPointerInfo(), St->isVolatile(), 9276 St->isNonTemporal(), St->getAlignment()); 9277 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 9278 Increment); 9279 Chains.push_back(Ch); 9280 } 9281 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 9282 } 9283 9284 if (!ISD::isNormalStore(St)) 9285 return SDValue(); 9286 9287 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 9288 // ARM stores of arguments in the same cache line. 9289 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 9290 StVal.getNode()->hasOneUse()) { 9291 SelectionDAG &DAG = DCI.DAG; 9292 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian(); 9293 SDLoc DL(St); 9294 SDValue BasePtr = St->getBasePtr(); 9295 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 9296 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 9297 BasePtr, St->getPointerInfo(), St->isVolatile(), 9298 St->isNonTemporal(), St->getAlignment()); 9299 9300 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9301 DAG.getConstant(4, MVT::i32)); 9302 return DAG.getStore(NewST1.getValue(0), DL, 9303 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 9304 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 9305 St->isNonTemporal(), 9306 std::min(4U, St->getAlignment() / 2)); 9307 } 9308 9309 if (StVal.getValueType() == MVT::i64 && 9310 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9311 9312 // Bitcast an i64 store extracted from a vector to f64. 9313 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9314 SelectionDAG &DAG = DCI.DAG; 9315 SDLoc dl(StVal); 9316 SDValue IntVec = StVal.getOperand(0); 9317 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9318 IntVec.getValueType().getVectorNumElements()); 9319 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 9320 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 9321 Vec, StVal.getOperand(1)); 9322 dl = SDLoc(N); 9323 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 9324 // Make the DAGCombiner fold the bitcasts. 9325 DCI.AddToWorklist(Vec.getNode()); 9326 DCI.AddToWorklist(ExtElt.getNode()); 9327 DCI.AddToWorklist(V.getNode()); 9328 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 9329 St->getPointerInfo(), St->isVolatile(), 9330 St->isNonTemporal(), St->getAlignment(), 9331 St->getAAInfo()); 9332 } 9333 9334 // If this is a legal vector store, try to combine it into a VST1_UPD. 9335 if (ISD::isNormalStore(N) && VT.isVector() && 9336 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9337 return CombineBaseUpdate(N, DCI); 9338 9339 return SDValue(); 9340 } 9341 9342 // isConstVecPow2 - Return true if each vector element is a power of 2, all 9343 // elements are the same constant, C, and Log2(C) ranges from 1 to 32. 9344 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C) 9345 { 9346 integerPart cN; 9347 integerPart c0 = 0; 9348 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements(); 9349 I != E; I++) { 9350 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I)); 9351 if (!C) 9352 return false; 9353 9354 bool isExact; 9355 APFloat APF = C->getValueAPF(); 9356 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact) 9357 != APFloat::opOK || !isExact) 9358 return false; 9359 9360 c0 = (I == 0) ? cN : c0; 9361 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32) 9362 return false; 9363 } 9364 C = c0; 9365 return true; 9366 } 9367 9368 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 9369 /// can replace combinations of VMUL and VCVT (floating-point to integer) 9370 /// when the VMUL has a constant operand that is a power of 2. 9371 /// 9372 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 9373 /// vmul.f32 d16, d17, d16 9374 /// vcvt.s32.f32 d16, d16 9375 /// becomes: 9376 /// vcvt.s32.f32 d16, d16, #3 9377 static SDValue PerformVCVTCombine(SDNode *N, 9378 TargetLowering::DAGCombinerInfo &DCI, 9379 const ARMSubtarget *Subtarget) { 9380 SelectionDAG &DAG = DCI.DAG; 9381 SDValue Op = N->getOperand(0); 9382 9383 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() || 9384 Op.getOpcode() != ISD::FMUL) 9385 return SDValue(); 9386 9387 uint64_t C; 9388 SDValue N0 = Op->getOperand(0); 9389 SDValue ConstVec = Op->getOperand(1); 9390 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 9391 9392 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR || 9393 !isConstVecPow2(ConstVec, isSigned, C)) 9394 return SDValue(); 9395 9396 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 9397 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 9398 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 9399 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 || 9400 NumLanes > 4) { 9401 // These instructions only exist converting from f32 to i32. We can handle 9402 // smaller integers by generating an extra truncate, but larger ones would 9403 // be lossy. We also can't handle more then 4 lanes, since these intructions 9404 // only support v2i32/v4i32 types. 9405 return SDValue(); 9406 } 9407 9408 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 9409 Intrinsic::arm_neon_vcvtfp2fxu; 9410 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), 9411 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 9412 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0, 9413 DAG.getConstant(Log2_64(C), MVT::i32)); 9414 9415 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits()) 9416 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv); 9417 9418 return FixConv; 9419 } 9420 9421 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 9422 /// can replace combinations of VCVT (integer to floating-point) and VDIV 9423 /// when the VDIV has a constant operand that is a power of 2. 9424 /// 9425 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 9426 /// vcvt.f32.s32 d16, d16 9427 /// vdiv.f32 d16, d17, d16 9428 /// becomes: 9429 /// vcvt.f32.s32 d16, d16, #3 9430 static SDValue PerformVDIVCombine(SDNode *N, 9431 TargetLowering::DAGCombinerInfo &DCI, 9432 const ARMSubtarget *Subtarget) { 9433 SelectionDAG &DAG = DCI.DAG; 9434 SDValue Op = N->getOperand(0); 9435 unsigned OpOpcode = Op.getNode()->getOpcode(); 9436 9437 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() || 9438 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 9439 return SDValue(); 9440 9441 uint64_t C; 9442 SDValue ConstVec = N->getOperand(1); 9443 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 9444 9445 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR || 9446 !isConstVecPow2(ConstVec, isSigned, C)) 9447 return SDValue(); 9448 9449 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 9450 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 9451 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) { 9452 // These instructions only exist converting from i32 to f32. We can handle 9453 // smaller integers by generating an extra extend, but larger ones would 9454 // be lossy. 9455 return SDValue(); 9456 } 9457 9458 SDValue ConvInput = Op.getOperand(0); 9459 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 9460 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits()) 9461 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9462 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 9463 ConvInput); 9464 9465 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 9466 Intrinsic::arm_neon_vcvtfxu2fp; 9467 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), 9468 Op.getValueType(), 9469 DAG.getConstant(IntrinsicOpcode, MVT::i32), 9470 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32)); 9471 } 9472 9473 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 9474 /// operand of a vector shift operation, where all the elements of the 9475 /// build_vector must have the same constant integer value. 9476 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 9477 // Ignore bit_converts. 9478 while (Op.getOpcode() == ISD::BITCAST) 9479 Op = Op.getOperand(0); 9480 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9481 APInt SplatBits, SplatUndef; 9482 unsigned SplatBitSize; 9483 bool HasAnyUndefs; 9484 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 9485 HasAnyUndefs, ElementBits) || 9486 SplatBitSize > ElementBits) 9487 return false; 9488 Cnt = SplatBits.getSExtValue(); 9489 return true; 9490 } 9491 9492 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 9493 /// operand of a vector shift left operation. That value must be in the range: 9494 /// 0 <= Value < ElementBits for a left shift; or 9495 /// 0 <= Value <= ElementBits for a long left shift. 9496 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 9497 assert(VT.isVector() && "vector shift count is not a vector type"); 9498 unsigned ElementBits = VT.getVectorElementType().getSizeInBits(); 9499 if (! getVShiftImm(Op, ElementBits, Cnt)) 9500 return false; 9501 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 9502 } 9503 9504 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 9505 /// operand of a vector shift right operation. For a shift opcode, the value 9506 /// is positive, but for an intrinsic the value count must be negative. The 9507 /// absolute value must be in the range: 9508 /// 1 <= |Value| <= ElementBits for a right shift; or 9509 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 9510 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 9511 int64_t &Cnt) { 9512 assert(VT.isVector() && "vector shift count is not a vector type"); 9513 unsigned ElementBits = VT.getVectorElementType().getSizeInBits(); 9514 if (! getVShiftImm(Op, ElementBits, Cnt)) 9515 return false; 9516 if (isIntrinsic) 9517 Cnt = -Cnt; 9518 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 9519 } 9520 9521 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 9522 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 9523 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9524 switch (IntNo) { 9525 default: 9526 // Don't do anything for most intrinsics. 9527 break; 9528 9529 // Vector shifts: check for immediate versions and lower them. 9530 // Note: This is done during DAG combining instead of DAG legalizing because 9531 // the build_vectors for 64-bit vector element shift counts are generally 9532 // not legal, and it is hard to see their values after they get legalized to 9533 // loads from a constant pool. 9534 case Intrinsic::arm_neon_vshifts: 9535 case Intrinsic::arm_neon_vshiftu: 9536 case Intrinsic::arm_neon_vrshifts: 9537 case Intrinsic::arm_neon_vrshiftu: 9538 case Intrinsic::arm_neon_vrshiftn: 9539 case Intrinsic::arm_neon_vqshifts: 9540 case Intrinsic::arm_neon_vqshiftu: 9541 case Intrinsic::arm_neon_vqshiftsu: 9542 case Intrinsic::arm_neon_vqshiftns: 9543 case Intrinsic::arm_neon_vqshiftnu: 9544 case Intrinsic::arm_neon_vqshiftnsu: 9545 case Intrinsic::arm_neon_vqrshiftns: 9546 case Intrinsic::arm_neon_vqrshiftnu: 9547 case Intrinsic::arm_neon_vqrshiftnsu: { 9548 EVT VT = N->getOperand(1).getValueType(); 9549 int64_t Cnt; 9550 unsigned VShiftOpc = 0; 9551 9552 switch (IntNo) { 9553 case Intrinsic::arm_neon_vshifts: 9554 case Intrinsic::arm_neon_vshiftu: 9555 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 9556 VShiftOpc = ARMISD::VSHL; 9557 break; 9558 } 9559 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 9560 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 9561 ARMISD::VSHRs : ARMISD::VSHRu); 9562 break; 9563 } 9564 return SDValue(); 9565 9566 case Intrinsic::arm_neon_vrshifts: 9567 case Intrinsic::arm_neon_vrshiftu: 9568 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 9569 break; 9570 return SDValue(); 9571 9572 case Intrinsic::arm_neon_vqshifts: 9573 case Intrinsic::arm_neon_vqshiftu: 9574 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 9575 break; 9576 return SDValue(); 9577 9578 case Intrinsic::arm_neon_vqshiftsu: 9579 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 9580 break; 9581 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 9582 9583 case Intrinsic::arm_neon_vrshiftn: 9584 case Intrinsic::arm_neon_vqshiftns: 9585 case Intrinsic::arm_neon_vqshiftnu: 9586 case Intrinsic::arm_neon_vqshiftnsu: 9587 case Intrinsic::arm_neon_vqrshiftns: 9588 case Intrinsic::arm_neon_vqrshiftnu: 9589 case Intrinsic::arm_neon_vqrshiftnsu: 9590 // Narrowing shifts require an immediate right shift. 9591 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 9592 break; 9593 llvm_unreachable("invalid shift count for narrowing vector shift " 9594 "intrinsic"); 9595 9596 default: 9597 llvm_unreachable("unhandled vector shift"); 9598 } 9599 9600 switch (IntNo) { 9601 case Intrinsic::arm_neon_vshifts: 9602 case Intrinsic::arm_neon_vshiftu: 9603 // Opcode already set above. 9604 break; 9605 case Intrinsic::arm_neon_vrshifts: 9606 VShiftOpc = ARMISD::VRSHRs; break; 9607 case Intrinsic::arm_neon_vrshiftu: 9608 VShiftOpc = ARMISD::VRSHRu; break; 9609 case Intrinsic::arm_neon_vrshiftn: 9610 VShiftOpc = ARMISD::VRSHRN; break; 9611 case Intrinsic::arm_neon_vqshifts: 9612 VShiftOpc = ARMISD::VQSHLs; break; 9613 case Intrinsic::arm_neon_vqshiftu: 9614 VShiftOpc = ARMISD::VQSHLu; break; 9615 case Intrinsic::arm_neon_vqshiftsu: 9616 VShiftOpc = ARMISD::VQSHLsu; break; 9617 case Intrinsic::arm_neon_vqshiftns: 9618 VShiftOpc = ARMISD::VQSHRNs; break; 9619 case Intrinsic::arm_neon_vqshiftnu: 9620 VShiftOpc = ARMISD::VQSHRNu; break; 9621 case Intrinsic::arm_neon_vqshiftnsu: 9622 VShiftOpc = ARMISD::VQSHRNsu; break; 9623 case Intrinsic::arm_neon_vqrshiftns: 9624 VShiftOpc = ARMISD::VQRSHRNs; break; 9625 case Intrinsic::arm_neon_vqrshiftnu: 9626 VShiftOpc = ARMISD::VQRSHRNu; break; 9627 case Intrinsic::arm_neon_vqrshiftnsu: 9628 VShiftOpc = ARMISD::VQRSHRNsu; break; 9629 } 9630 9631 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0), 9632 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32)); 9633 } 9634 9635 case Intrinsic::arm_neon_vshiftins: { 9636 EVT VT = N->getOperand(1).getValueType(); 9637 int64_t Cnt; 9638 unsigned VShiftOpc = 0; 9639 9640 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 9641 VShiftOpc = ARMISD::VSLI; 9642 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 9643 VShiftOpc = ARMISD::VSRI; 9644 else { 9645 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 9646 } 9647 9648 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0), 9649 N->getOperand(1), N->getOperand(2), 9650 DAG.getConstant(Cnt, MVT::i32)); 9651 } 9652 9653 case Intrinsic::arm_neon_vqrshifts: 9654 case Intrinsic::arm_neon_vqrshiftu: 9655 // No immediate versions of these to check for. 9656 break; 9657 } 9658 9659 return SDValue(); 9660 } 9661 9662 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 9663 /// lowers them. As with the vector shift intrinsics, this is done during DAG 9664 /// combining instead of DAG legalizing because the build_vectors for 64-bit 9665 /// vector element shift counts are generally not legal, and it is hard to see 9666 /// their values after they get legalized to loads from a constant pool. 9667 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 9668 const ARMSubtarget *ST) { 9669 EVT VT = N->getValueType(0); 9670 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 9671 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 9672 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 9673 SDValue N1 = N->getOperand(1); 9674 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 9675 SDValue N0 = N->getOperand(0); 9676 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 9677 DAG.MaskedValueIsZero(N0.getOperand(0), 9678 APInt::getHighBitsSet(32, 16))) 9679 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 9680 } 9681 } 9682 9683 // Nothing to be done for scalar shifts. 9684 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9685 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 9686 return SDValue(); 9687 9688 assert(ST->hasNEON() && "unexpected vector shift"); 9689 int64_t Cnt; 9690 9691 switch (N->getOpcode()) { 9692 default: llvm_unreachable("unexpected shift opcode"); 9693 9694 case ISD::SHL: 9695 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 9696 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0), 9697 DAG.getConstant(Cnt, MVT::i32)); 9698 break; 9699 9700 case ISD::SRA: 9701 case ISD::SRL: 9702 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 9703 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 9704 ARMISD::VSHRs : ARMISD::VSHRu); 9705 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0), 9706 DAG.getConstant(Cnt, MVT::i32)); 9707 } 9708 } 9709 return SDValue(); 9710 } 9711 9712 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 9713 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 9714 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 9715 const ARMSubtarget *ST) { 9716 SDValue N0 = N->getOperand(0); 9717 9718 // Check for sign- and zero-extensions of vector extract operations of 8- 9719 // and 16-bit vector elements. NEON supports these directly. They are 9720 // handled during DAG combining because type legalization will promote them 9721 // to 32-bit types and it is messy to recognize the operations after that. 9722 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9723 SDValue Vec = N0.getOperand(0); 9724 SDValue Lane = N0.getOperand(1); 9725 EVT VT = N->getValueType(0); 9726 EVT EltVT = N0.getValueType(); 9727 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9728 9729 if (VT == MVT::i32 && 9730 (EltVT == MVT::i8 || EltVT == MVT::i16) && 9731 TLI.isTypeLegal(Vec.getValueType()) && 9732 isa<ConstantSDNode>(Lane)) { 9733 9734 unsigned Opc = 0; 9735 switch (N->getOpcode()) { 9736 default: llvm_unreachable("unexpected opcode"); 9737 case ISD::SIGN_EXTEND: 9738 Opc = ARMISD::VGETLANEs; 9739 break; 9740 case ISD::ZERO_EXTEND: 9741 case ISD::ANY_EXTEND: 9742 Opc = ARMISD::VGETLANEu; 9743 break; 9744 } 9745 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 9746 } 9747 } 9748 9749 return SDValue(); 9750 } 9751 9752 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC 9753 /// to match f32 max/min patterns to use NEON vmax/vmin instructions. 9754 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG, 9755 const ARMSubtarget *ST) { 9756 // If the target supports NEON, try to use vmax/vmin instructions for f32 9757 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set, 9758 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is 9759 // a NaN; only do the transformation when it matches that behavior. 9760 9761 // For now only do this when using NEON for FP operations; if using VFP, it 9762 // is not obvious that the benefit outweighs the cost of switching to the 9763 // NEON pipeline. 9764 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() || 9765 N->getValueType(0) != MVT::f32) 9766 return SDValue(); 9767 9768 SDValue CondLHS = N->getOperand(0); 9769 SDValue CondRHS = N->getOperand(1); 9770 SDValue LHS = N->getOperand(2); 9771 SDValue RHS = N->getOperand(3); 9772 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 9773 9774 unsigned Opcode = 0; 9775 bool IsReversed; 9776 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) { 9777 IsReversed = false; // x CC y ? x : y 9778 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) { 9779 IsReversed = true ; // x CC y ? y : x 9780 } else { 9781 return SDValue(); 9782 } 9783 9784 bool IsUnordered; 9785 switch (CC) { 9786 default: break; 9787 case ISD::SETOLT: 9788 case ISD::SETOLE: 9789 case ISD::SETLT: 9790 case ISD::SETLE: 9791 case ISD::SETULT: 9792 case ISD::SETULE: 9793 // If LHS is NaN, an ordered comparison will be false and the result will 9794 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS 9795 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN. 9796 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE); 9797 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS)) 9798 break; 9799 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin 9800 // will return -0, so vmin can only be used for unsafe math or if one of 9801 // the operands is known to be nonzero. 9802 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) && 9803 !DAG.getTarget().Options.UnsafeFPMath && 9804 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 9805 break; 9806 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN; 9807 break; 9808 9809 case ISD::SETOGT: 9810 case ISD::SETOGE: 9811 case ISD::SETGT: 9812 case ISD::SETGE: 9813 case ISD::SETUGT: 9814 case ISD::SETUGE: 9815 // If LHS is NaN, an ordered comparison will be false and the result will 9816 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS 9817 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN. 9818 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE); 9819 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS)) 9820 break; 9821 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax 9822 // will return +0, so vmax can only be used for unsafe math or if one of 9823 // the operands is known to be nonzero. 9824 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) && 9825 !DAG.getTarget().Options.UnsafeFPMath && 9826 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 9827 break; 9828 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX; 9829 break; 9830 } 9831 9832 if (!Opcode) 9833 return SDValue(); 9834 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS); 9835 } 9836 9837 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 9838 SDValue 9839 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 9840 SDValue Cmp = N->getOperand(4); 9841 if (Cmp.getOpcode() != ARMISD::CMPZ) 9842 // Only looking at EQ and NE cases. 9843 return SDValue(); 9844 9845 EVT VT = N->getValueType(0); 9846 SDLoc dl(N); 9847 SDValue LHS = Cmp.getOperand(0); 9848 SDValue RHS = Cmp.getOperand(1); 9849 SDValue FalseVal = N->getOperand(0); 9850 SDValue TrueVal = N->getOperand(1); 9851 SDValue ARMcc = N->getOperand(2); 9852 ARMCC::CondCodes CC = 9853 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 9854 9855 // Simplify 9856 // mov r1, r0 9857 // cmp r1, x 9858 // mov r0, y 9859 // moveq r0, x 9860 // to 9861 // cmp r0, x 9862 // movne r0, y 9863 // 9864 // mov r1, r0 9865 // cmp r1, x 9866 // mov r0, x 9867 // movne r0, y 9868 // to 9869 // cmp r0, x 9870 // movne r0, y 9871 /// FIXME: Turn this into a target neutral optimization? 9872 SDValue Res; 9873 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 9874 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 9875 N->getOperand(3), Cmp); 9876 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 9877 SDValue ARMcc; 9878 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 9879 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 9880 N->getOperand(3), NewCmp); 9881 } 9882 9883 if (Res.getNode()) { 9884 APInt KnownZero, KnownOne; 9885 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 9886 // Capture demanded bits information that would be otherwise lost. 9887 if (KnownZero == 0xfffffffe) 9888 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 9889 DAG.getValueType(MVT::i1)); 9890 else if (KnownZero == 0xffffff00) 9891 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 9892 DAG.getValueType(MVT::i8)); 9893 else if (KnownZero == 0xffff0000) 9894 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 9895 DAG.getValueType(MVT::i16)); 9896 } 9897 9898 return Res; 9899 } 9900 9901 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 9902 DAGCombinerInfo &DCI) const { 9903 switch (N->getOpcode()) { 9904 default: break; 9905 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 9906 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 9907 case ISD::SUB: return PerformSUBCombine(N, DCI); 9908 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 9909 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 9910 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 9911 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 9912 case ARMISD::BFI: return PerformBFICombine(N, DCI); 9913 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 9914 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 9915 case ISD::STORE: return PerformSTORECombine(N, DCI); 9916 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 9917 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 9918 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 9919 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 9920 case ISD::FP_TO_SINT: 9921 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget); 9922 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget); 9923 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 9924 case ISD::SHL: 9925 case ISD::SRA: 9926 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 9927 case ISD::SIGN_EXTEND: 9928 case ISD::ZERO_EXTEND: 9929 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 9930 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget); 9931 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 9932 case ISD::LOAD: return PerformLOADCombine(N, DCI); 9933 case ARMISD::VLD2DUP: 9934 case ARMISD::VLD3DUP: 9935 case ARMISD::VLD4DUP: 9936 return PerformVLDCombine(N, DCI); 9937 case ARMISD::BUILD_VECTOR: 9938 return PerformARMBUILD_VECTORCombine(N, DCI); 9939 case ISD::INTRINSIC_VOID: 9940 case ISD::INTRINSIC_W_CHAIN: 9941 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 9942 case Intrinsic::arm_neon_vld1: 9943 case Intrinsic::arm_neon_vld2: 9944 case Intrinsic::arm_neon_vld3: 9945 case Intrinsic::arm_neon_vld4: 9946 case Intrinsic::arm_neon_vld2lane: 9947 case Intrinsic::arm_neon_vld3lane: 9948 case Intrinsic::arm_neon_vld4lane: 9949 case Intrinsic::arm_neon_vst1: 9950 case Intrinsic::arm_neon_vst2: 9951 case Intrinsic::arm_neon_vst3: 9952 case Intrinsic::arm_neon_vst4: 9953 case Intrinsic::arm_neon_vst2lane: 9954 case Intrinsic::arm_neon_vst3lane: 9955 case Intrinsic::arm_neon_vst4lane: 9956 return PerformVLDCombine(N, DCI); 9957 default: break; 9958 } 9959 break; 9960 } 9961 return SDValue(); 9962 } 9963 9964 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 9965 EVT VT) const { 9966 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 9967 } 9968 9969 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 9970 unsigned, 9971 unsigned, 9972 bool *Fast) const { 9973 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 9974 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 9975 9976 switch (VT.getSimpleVT().SimpleTy) { 9977 default: 9978 return false; 9979 case MVT::i8: 9980 case MVT::i16: 9981 case MVT::i32: { 9982 // Unaligned access can use (for example) LRDB, LRDH, LDR 9983 if (AllowsUnaligned) { 9984 if (Fast) 9985 *Fast = Subtarget->hasV7Ops(); 9986 return true; 9987 } 9988 return false; 9989 } 9990 case MVT::f64: 9991 case MVT::v2f64: { 9992 // For any little-endian targets with neon, we can support unaligned ld/st 9993 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 9994 // A big-endian target may also explicitly support unaligned accesses 9995 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) { 9996 if (Fast) 9997 *Fast = true; 9998 return true; 9999 } 10000 return false; 10001 } 10002 } 10003 } 10004 10005 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 10006 unsigned AlignCheck) { 10007 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 10008 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 10009 } 10010 10011 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 10012 unsigned DstAlign, unsigned SrcAlign, 10013 bool IsMemset, bool ZeroMemset, 10014 bool MemcpyStrSrc, 10015 MachineFunction &MF) const { 10016 const Function *F = MF.getFunction(); 10017 10018 // See if we can use NEON instructions for this... 10019 if ((!IsMemset || ZeroMemset) && 10020 Subtarget->hasNEON() && 10021 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 10022 Attribute::NoImplicitFloat)) { 10023 bool Fast; 10024 if (Size >= 16 && 10025 (memOpAlign(SrcAlign, DstAlign, 16) || 10026 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 10027 return MVT::v2f64; 10028 } else if (Size >= 8 && 10029 (memOpAlign(SrcAlign, DstAlign, 8) || 10030 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 10031 Fast))) { 10032 return MVT::f64; 10033 } 10034 } 10035 10036 // Lowering to i32/i16 if the size permits. 10037 if (Size >= 4) 10038 return MVT::i32; 10039 else if (Size >= 2) 10040 return MVT::i16; 10041 10042 // Let the target-independent logic figure it out. 10043 return MVT::Other; 10044 } 10045 10046 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10047 if (Val.getOpcode() != ISD::LOAD) 10048 return false; 10049 10050 EVT VT1 = Val.getValueType(); 10051 if (!VT1.isSimple() || !VT1.isInteger() || 10052 !VT2.isSimple() || !VT2.isInteger()) 10053 return false; 10054 10055 switch (VT1.getSimpleVT().SimpleTy) { 10056 default: break; 10057 case MVT::i1: 10058 case MVT::i8: 10059 case MVT::i16: 10060 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 10061 return true; 10062 } 10063 10064 return false; 10065 } 10066 10067 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 10068 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10069 return false; 10070 10071 if (!isTypeLegal(EVT::getEVT(Ty1))) 10072 return false; 10073 10074 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 10075 10076 // Assuming the caller doesn't have a zeroext or signext return parameter, 10077 // truncation all the way down to i1 is valid. 10078 return true; 10079 } 10080 10081 10082 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 10083 if (V < 0) 10084 return false; 10085 10086 unsigned Scale = 1; 10087 switch (VT.getSimpleVT().SimpleTy) { 10088 default: return false; 10089 case MVT::i1: 10090 case MVT::i8: 10091 // Scale == 1; 10092 break; 10093 case MVT::i16: 10094 // Scale == 2; 10095 Scale = 2; 10096 break; 10097 case MVT::i32: 10098 // Scale == 4; 10099 Scale = 4; 10100 break; 10101 } 10102 10103 if ((V & (Scale - 1)) != 0) 10104 return false; 10105 V /= Scale; 10106 return V == (V & ((1LL << 5) - 1)); 10107 } 10108 10109 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 10110 const ARMSubtarget *Subtarget) { 10111 bool isNeg = false; 10112 if (V < 0) { 10113 isNeg = true; 10114 V = - V; 10115 } 10116 10117 switch (VT.getSimpleVT().SimpleTy) { 10118 default: return false; 10119 case MVT::i1: 10120 case MVT::i8: 10121 case MVT::i16: 10122 case MVT::i32: 10123 // + imm12 or - imm8 10124 if (isNeg) 10125 return V == (V & ((1LL << 8) - 1)); 10126 return V == (V & ((1LL << 12) - 1)); 10127 case MVT::f32: 10128 case MVT::f64: 10129 // Same as ARM mode. FIXME: NEON? 10130 if (!Subtarget->hasVFP2()) 10131 return false; 10132 if ((V & 3) != 0) 10133 return false; 10134 V >>= 2; 10135 return V == (V & ((1LL << 8) - 1)); 10136 } 10137 } 10138 10139 /// isLegalAddressImmediate - Return true if the integer value can be used 10140 /// as the offset of the target addressing mode for load / store of the 10141 /// given type. 10142 static bool isLegalAddressImmediate(int64_t V, EVT VT, 10143 const ARMSubtarget *Subtarget) { 10144 if (V == 0) 10145 return true; 10146 10147 if (!VT.isSimple()) 10148 return false; 10149 10150 if (Subtarget->isThumb1Only()) 10151 return isLegalT1AddressImmediate(V, VT); 10152 else if (Subtarget->isThumb2()) 10153 return isLegalT2AddressImmediate(V, VT, Subtarget); 10154 10155 // ARM mode. 10156 if (V < 0) 10157 V = - V; 10158 switch (VT.getSimpleVT().SimpleTy) { 10159 default: return false; 10160 case MVT::i1: 10161 case MVT::i8: 10162 case MVT::i32: 10163 // +- imm12 10164 return V == (V & ((1LL << 12) - 1)); 10165 case MVT::i16: 10166 // +- imm8 10167 return V == (V & ((1LL << 8) - 1)); 10168 case MVT::f32: 10169 case MVT::f64: 10170 if (!Subtarget->hasVFP2()) // FIXME: NEON? 10171 return false; 10172 if ((V & 3) != 0) 10173 return false; 10174 V >>= 2; 10175 return V == (V & ((1LL << 8) - 1)); 10176 } 10177 } 10178 10179 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 10180 EVT VT) const { 10181 int Scale = AM.Scale; 10182 if (Scale < 0) 10183 return false; 10184 10185 switch (VT.getSimpleVT().SimpleTy) { 10186 default: return false; 10187 case MVT::i1: 10188 case MVT::i8: 10189 case MVT::i16: 10190 case MVT::i32: 10191 if (Scale == 1) 10192 return true; 10193 // r + r << imm 10194 Scale = Scale & ~1; 10195 return Scale == 2 || Scale == 4 || Scale == 8; 10196 case MVT::i64: 10197 // r + r 10198 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 10199 return true; 10200 return false; 10201 case MVT::isVoid: 10202 // Note, we allow "void" uses (basically, uses that aren't loads or 10203 // stores), because arm allows folding a scale into many arithmetic 10204 // operations. This should be made more precise and revisited later. 10205 10206 // Allow r << imm, but the imm has to be a multiple of two. 10207 if (Scale & 1) return false; 10208 return isPowerOf2_32(Scale); 10209 } 10210 } 10211 10212 /// isLegalAddressingMode - Return true if the addressing mode represented 10213 /// by AM is legal for this target, for a load/store of the specified type. 10214 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM, 10215 Type *Ty) const { 10216 EVT VT = getValueType(Ty, true); 10217 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 10218 return false; 10219 10220 // Can never fold addr of global into load/store. 10221 if (AM.BaseGV) 10222 return false; 10223 10224 switch (AM.Scale) { 10225 case 0: // no scale reg, must be "r+i" or "r", or "i". 10226 break; 10227 case 1: 10228 if (Subtarget->isThumb1Only()) 10229 return false; 10230 // FALL THROUGH. 10231 default: 10232 // ARM doesn't support any R+R*scale+imm addr modes. 10233 if (AM.BaseOffs) 10234 return false; 10235 10236 if (!VT.isSimple()) 10237 return false; 10238 10239 if (Subtarget->isThumb2()) 10240 return isLegalT2ScaledAddressingMode(AM, VT); 10241 10242 int Scale = AM.Scale; 10243 switch (VT.getSimpleVT().SimpleTy) { 10244 default: return false; 10245 case MVT::i1: 10246 case MVT::i8: 10247 case MVT::i32: 10248 if (Scale < 0) Scale = -Scale; 10249 if (Scale == 1) 10250 return true; 10251 // r + r << imm 10252 return isPowerOf2_32(Scale & ~1); 10253 case MVT::i16: 10254 case MVT::i64: 10255 // r + r 10256 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 10257 return true; 10258 return false; 10259 10260 case MVT::isVoid: 10261 // Note, we allow "void" uses (basically, uses that aren't loads or 10262 // stores), because arm allows folding a scale into many arithmetic 10263 // operations. This should be made more precise and revisited later. 10264 10265 // Allow r << imm, but the imm has to be a multiple of two. 10266 if (Scale & 1) return false; 10267 return isPowerOf2_32(Scale); 10268 } 10269 } 10270 return true; 10271 } 10272 10273 /// isLegalICmpImmediate - Return true if the specified immediate is legal 10274 /// icmp immediate, that is the target has icmp instructions which can compare 10275 /// a register against the immediate without having to materialize the 10276 /// immediate into a register. 10277 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 10278 // Thumb2 and ARM modes can use cmn for negative immediates. 10279 if (!Subtarget->isThumb()) 10280 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1; 10281 if (Subtarget->isThumb2()) 10282 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1; 10283 // Thumb1 doesn't have cmn, and only 8-bit immediates. 10284 return Imm >= 0 && Imm <= 255; 10285 } 10286 10287 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 10288 /// *or sub* immediate, that is the target has add or sub instructions which can 10289 /// add a register with the immediate without having to materialize the 10290 /// immediate into a register. 10291 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 10292 // Same encoding for add/sub, just flip the sign. 10293 int64_t AbsImm = llvm::abs64(Imm); 10294 if (!Subtarget->isThumb()) 10295 return ARM_AM::getSOImmVal(AbsImm) != -1; 10296 if (Subtarget->isThumb2()) 10297 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 10298 // Thumb1 only has 8-bit unsigned immediate. 10299 return AbsImm >= 0 && AbsImm <= 255; 10300 } 10301 10302 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 10303 bool isSEXTLoad, SDValue &Base, 10304 SDValue &Offset, bool &isInc, 10305 SelectionDAG &DAG) { 10306 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 10307 return false; 10308 10309 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 10310 // AddressingMode 3 10311 Base = Ptr->getOperand(0); 10312 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 10313 int RHSC = (int)RHS->getZExtValue(); 10314 if (RHSC < 0 && RHSC > -256) { 10315 assert(Ptr->getOpcode() == ISD::ADD); 10316 isInc = false; 10317 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0)); 10318 return true; 10319 } 10320 } 10321 isInc = (Ptr->getOpcode() == ISD::ADD); 10322 Offset = Ptr->getOperand(1); 10323 return true; 10324 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 10325 // AddressingMode 2 10326 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 10327 int RHSC = (int)RHS->getZExtValue(); 10328 if (RHSC < 0 && RHSC > -0x1000) { 10329 assert(Ptr->getOpcode() == ISD::ADD); 10330 isInc = false; 10331 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0)); 10332 Base = Ptr->getOperand(0); 10333 return true; 10334 } 10335 } 10336 10337 if (Ptr->getOpcode() == ISD::ADD) { 10338 isInc = true; 10339 ARM_AM::ShiftOpc ShOpcVal= 10340 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 10341 if (ShOpcVal != ARM_AM::no_shift) { 10342 Base = Ptr->getOperand(1); 10343 Offset = Ptr->getOperand(0); 10344 } else { 10345 Base = Ptr->getOperand(0); 10346 Offset = Ptr->getOperand(1); 10347 } 10348 return true; 10349 } 10350 10351 isInc = (Ptr->getOpcode() == ISD::ADD); 10352 Base = Ptr->getOperand(0); 10353 Offset = Ptr->getOperand(1); 10354 return true; 10355 } 10356 10357 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 10358 return false; 10359 } 10360 10361 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 10362 bool isSEXTLoad, SDValue &Base, 10363 SDValue &Offset, bool &isInc, 10364 SelectionDAG &DAG) { 10365 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 10366 return false; 10367 10368 Base = Ptr->getOperand(0); 10369 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 10370 int RHSC = (int)RHS->getZExtValue(); 10371 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 10372 assert(Ptr->getOpcode() == ISD::ADD); 10373 isInc = false; 10374 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0)); 10375 return true; 10376 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 10377 isInc = Ptr->getOpcode() == ISD::ADD; 10378 Offset = DAG.getConstant(RHSC, RHS->getValueType(0)); 10379 return true; 10380 } 10381 } 10382 10383 return false; 10384 } 10385 10386 /// getPreIndexedAddressParts - returns true by value, base pointer and 10387 /// offset pointer and addressing mode by reference if the node's address 10388 /// can be legally represented as pre-indexed load / store address. 10389 bool 10390 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 10391 SDValue &Offset, 10392 ISD::MemIndexedMode &AM, 10393 SelectionDAG &DAG) const { 10394 if (Subtarget->isThumb1Only()) 10395 return false; 10396 10397 EVT VT; 10398 SDValue Ptr; 10399 bool isSEXTLoad = false; 10400 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10401 Ptr = LD->getBasePtr(); 10402 VT = LD->getMemoryVT(); 10403 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 10404 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10405 Ptr = ST->getBasePtr(); 10406 VT = ST->getMemoryVT(); 10407 } else 10408 return false; 10409 10410 bool isInc; 10411 bool isLegal = false; 10412 if (Subtarget->isThumb2()) 10413 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 10414 Offset, isInc, DAG); 10415 else 10416 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 10417 Offset, isInc, DAG); 10418 if (!isLegal) 10419 return false; 10420 10421 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 10422 return true; 10423 } 10424 10425 /// getPostIndexedAddressParts - returns true by value, base pointer and 10426 /// offset pointer and addressing mode by reference if this node can be 10427 /// combined with a load / store to form a post-indexed load / store. 10428 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 10429 SDValue &Base, 10430 SDValue &Offset, 10431 ISD::MemIndexedMode &AM, 10432 SelectionDAG &DAG) const { 10433 if (Subtarget->isThumb1Only()) 10434 return false; 10435 10436 EVT VT; 10437 SDValue Ptr; 10438 bool isSEXTLoad = false; 10439 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10440 VT = LD->getMemoryVT(); 10441 Ptr = LD->getBasePtr(); 10442 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 10443 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10444 VT = ST->getMemoryVT(); 10445 Ptr = ST->getBasePtr(); 10446 } else 10447 return false; 10448 10449 bool isInc; 10450 bool isLegal = false; 10451 if (Subtarget->isThumb2()) 10452 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 10453 isInc, DAG); 10454 else 10455 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 10456 isInc, DAG); 10457 if (!isLegal) 10458 return false; 10459 10460 if (Ptr != Base) { 10461 // Swap base ptr and offset to catch more post-index load / store when 10462 // it's legal. In Thumb2 mode, offset must be an immediate. 10463 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 10464 !Subtarget->isThumb2()) 10465 std::swap(Base, Offset); 10466 10467 // Post-indexed load / store update the base pointer. 10468 if (Ptr != Base) 10469 return false; 10470 } 10471 10472 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 10473 return true; 10474 } 10475 10476 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 10477 APInt &KnownZero, 10478 APInt &KnownOne, 10479 const SelectionDAG &DAG, 10480 unsigned Depth) const { 10481 unsigned BitWidth = KnownOne.getBitWidth(); 10482 KnownZero = KnownOne = APInt(BitWidth, 0); 10483 switch (Op.getOpcode()) { 10484 default: break; 10485 case ARMISD::ADDC: 10486 case ARMISD::ADDE: 10487 case ARMISD::SUBC: 10488 case ARMISD::SUBE: 10489 // These nodes' second result is a boolean 10490 if (Op.getResNo() == 0) 10491 break; 10492 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 10493 break; 10494 case ARMISD::CMOV: { 10495 // Bits are known zero/one if known on the LHS and RHS. 10496 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 10497 if (KnownZero == 0 && KnownOne == 0) return; 10498 10499 APInt KnownZeroRHS, KnownOneRHS; 10500 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 10501 KnownZero &= KnownZeroRHS; 10502 KnownOne &= KnownOneRHS; 10503 return; 10504 } 10505 case ISD::INTRINSIC_W_CHAIN: { 10506 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 10507 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 10508 switch (IntID) { 10509 default: return; 10510 case Intrinsic::arm_ldaex: 10511 case Intrinsic::arm_ldrex: { 10512 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 10513 unsigned MemBits = VT.getScalarType().getSizeInBits(); 10514 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 10515 return; 10516 } 10517 } 10518 } 10519 } 10520 } 10521 10522 //===----------------------------------------------------------------------===// 10523 // ARM Inline Assembly Support 10524 //===----------------------------------------------------------------------===// 10525 10526 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 10527 // Looking for "rev" which is V6+. 10528 if (!Subtarget->hasV6Ops()) 10529 return false; 10530 10531 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 10532 std::string AsmStr = IA->getAsmString(); 10533 SmallVector<StringRef, 4> AsmPieces; 10534 SplitString(AsmStr, AsmPieces, ";\n"); 10535 10536 switch (AsmPieces.size()) { 10537 default: return false; 10538 case 1: 10539 AsmStr = AsmPieces[0]; 10540 AsmPieces.clear(); 10541 SplitString(AsmStr, AsmPieces, " \t,"); 10542 10543 // rev $0, $1 10544 if (AsmPieces.size() == 3 && 10545 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 10546 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 10547 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 10548 if (Ty && Ty->getBitWidth() == 32) 10549 return IntrinsicLowering::LowerToByteSwap(CI); 10550 } 10551 break; 10552 } 10553 10554 return false; 10555 } 10556 10557 /// getConstraintType - Given a constraint letter, return the type of 10558 /// constraint it is for this target. 10559 ARMTargetLowering::ConstraintType 10560 ARMTargetLowering::getConstraintType(const std::string &Constraint) const { 10561 if (Constraint.size() == 1) { 10562 switch (Constraint[0]) { 10563 default: break; 10564 case 'l': return C_RegisterClass; 10565 case 'w': return C_RegisterClass; 10566 case 'h': return C_RegisterClass; 10567 case 'x': return C_RegisterClass; 10568 case 't': return C_RegisterClass; 10569 case 'j': return C_Other; // Constant for movw. 10570 // An address with a single base register. Due to the way we 10571 // currently handle addresses it is the same as an 'r' memory constraint. 10572 case 'Q': return C_Memory; 10573 } 10574 } else if (Constraint.size() == 2) { 10575 switch (Constraint[0]) { 10576 default: break; 10577 // All 'U+' constraints are addresses. 10578 case 'U': return C_Memory; 10579 } 10580 } 10581 return TargetLowering::getConstraintType(Constraint); 10582 } 10583 10584 /// Examine constraint type and operand type and determine a weight value. 10585 /// This object must already have been set up with the operand type 10586 /// and the current alternative constraint selected. 10587 TargetLowering::ConstraintWeight 10588 ARMTargetLowering::getSingleConstraintMatchWeight( 10589 AsmOperandInfo &info, const char *constraint) const { 10590 ConstraintWeight weight = CW_Invalid; 10591 Value *CallOperandVal = info.CallOperandVal; 10592 // If we don't have a value, we can't do a match, 10593 // but allow it at the lowest weight. 10594 if (!CallOperandVal) 10595 return CW_Default; 10596 Type *type = CallOperandVal->getType(); 10597 // Look at the constraint type. 10598 switch (*constraint) { 10599 default: 10600 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 10601 break; 10602 case 'l': 10603 if (type->isIntegerTy()) { 10604 if (Subtarget->isThumb()) 10605 weight = CW_SpecificReg; 10606 else 10607 weight = CW_Register; 10608 } 10609 break; 10610 case 'w': 10611 if (type->isFloatingPointTy()) 10612 weight = CW_Register; 10613 break; 10614 } 10615 return weight; 10616 } 10617 10618 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 10619 RCPair 10620 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 10621 MVT VT) const { 10622 if (Constraint.size() == 1) { 10623 // GCC ARM Constraint Letters 10624 switch (Constraint[0]) { 10625 case 'l': // Low regs or general regs. 10626 if (Subtarget->isThumb()) 10627 return RCPair(0U, &ARM::tGPRRegClass); 10628 return RCPair(0U, &ARM::GPRRegClass); 10629 case 'h': // High regs or no regs. 10630 if (Subtarget->isThumb()) 10631 return RCPair(0U, &ARM::hGPRRegClass); 10632 break; 10633 case 'r': 10634 if (Subtarget->isThumb1Only()) 10635 return RCPair(0U, &ARM::tGPRRegClass); 10636 return RCPair(0U, &ARM::GPRRegClass); 10637 case 'w': 10638 if (VT == MVT::Other) 10639 break; 10640 if (VT == MVT::f32) 10641 return RCPair(0U, &ARM::SPRRegClass); 10642 if (VT.getSizeInBits() == 64) 10643 return RCPair(0U, &ARM::DPRRegClass); 10644 if (VT.getSizeInBits() == 128) 10645 return RCPair(0U, &ARM::QPRRegClass); 10646 break; 10647 case 'x': 10648 if (VT == MVT::Other) 10649 break; 10650 if (VT == MVT::f32) 10651 return RCPair(0U, &ARM::SPR_8RegClass); 10652 if (VT.getSizeInBits() == 64) 10653 return RCPair(0U, &ARM::DPR_8RegClass); 10654 if (VT.getSizeInBits() == 128) 10655 return RCPair(0U, &ARM::QPR_8RegClass); 10656 break; 10657 case 't': 10658 if (VT == MVT::f32) 10659 return RCPair(0U, &ARM::SPRRegClass); 10660 break; 10661 } 10662 } 10663 if (StringRef("{cc}").equals_lower(Constraint)) 10664 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 10665 10666 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 10667 } 10668 10669 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 10670 /// vector. If it is invalid, don't add anything to Ops. 10671 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 10672 std::string &Constraint, 10673 std::vector<SDValue>&Ops, 10674 SelectionDAG &DAG) const { 10675 SDValue Result; 10676 10677 // Currently only support length 1 constraints. 10678 if (Constraint.length() != 1) return; 10679 10680 char ConstraintLetter = Constraint[0]; 10681 switch (ConstraintLetter) { 10682 default: break; 10683 case 'j': 10684 case 'I': case 'J': case 'K': case 'L': 10685 case 'M': case 'N': case 'O': 10686 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 10687 if (!C) 10688 return; 10689 10690 int64_t CVal64 = C->getSExtValue(); 10691 int CVal = (int) CVal64; 10692 // None of these constraints allow values larger than 32 bits. Check 10693 // that the value fits in an int. 10694 if (CVal != CVal64) 10695 return; 10696 10697 switch (ConstraintLetter) { 10698 case 'j': 10699 // Constant suitable for movw, must be between 0 and 10700 // 65535. 10701 if (Subtarget->hasV6T2Ops()) 10702 if (CVal >= 0 && CVal <= 65535) 10703 break; 10704 return; 10705 case 'I': 10706 if (Subtarget->isThumb1Only()) { 10707 // This must be a constant between 0 and 255, for ADD 10708 // immediates. 10709 if (CVal >= 0 && CVal <= 255) 10710 break; 10711 } else if (Subtarget->isThumb2()) { 10712 // A constant that can be used as an immediate value in a 10713 // data-processing instruction. 10714 if (ARM_AM::getT2SOImmVal(CVal) != -1) 10715 break; 10716 } else { 10717 // A constant that can be used as an immediate value in a 10718 // data-processing instruction. 10719 if (ARM_AM::getSOImmVal(CVal) != -1) 10720 break; 10721 } 10722 return; 10723 10724 case 'J': 10725 if (Subtarget->isThumb()) { // FIXME thumb2 10726 // This must be a constant between -255 and -1, for negated ADD 10727 // immediates. This can be used in GCC with an "n" modifier that 10728 // prints the negated value, for use with SUB instructions. It is 10729 // not useful otherwise but is implemented for compatibility. 10730 if (CVal >= -255 && CVal <= -1) 10731 break; 10732 } else { 10733 // This must be a constant between -4095 and 4095. It is not clear 10734 // what this constraint is intended for. Implemented for 10735 // compatibility with GCC. 10736 if (CVal >= -4095 && CVal <= 4095) 10737 break; 10738 } 10739 return; 10740 10741 case 'K': 10742 if (Subtarget->isThumb1Only()) { 10743 // A 32-bit value where only one byte has a nonzero value. Exclude 10744 // zero to match GCC. This constraint is used by GCC internally for 10745 // constants that can be loaded with a move/shift combination. 10746 // It is not useful otherwise but is implemented for compatibility. 10747 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 10748 break; 10749 } else if (Subtarget->isThumb2()) { 10750 // A constant whose bitwise inverse can be used as an immediate 10751 // value in a data-processing instruction. This can be used in GCC 10752 // with a "B" modifier that prints the inverted value, for use with 10753 // BIC and MVN instructions. It is not useful otherwise but is 10754 // implemented for compatibility. 10755 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 10756 break; 10757 } else { 10758 // A constant whose bitwise inverse can be used as an immediate 10759 // value in a data-processing instruction. This can be used in GCC 10760 // with a "B" modifier that prints the inverted value, for use with 10761 // BIC and MVN instructions. It is not useful otherwise but is 10762 // implemented for compatibility. 10763 if (ARM_AM::getSOImmVal(~CVal) != -1) 10764 break; 10765 } 10766 return; 10767 10768 case 'L': 10769 if (Subtarget->isThumb1Only()) { 10770 // This must be a constant between -7 and 7, 10771 // for 3-operand ADD/SUB immediate instructions. 10772 if (CVal >= -7 && CVal < 7) 10773 break; 10774 } else if (Subtarget->isThumb2()) { 10775 // A constant whose negation can be used as an immediate value in a 10776 // data-processing instruction. This can be used in GCC with an "n" 10777 // modifier that prints the negated value, for use with SUB 10778 // instructions. It is not useful otherwise but is implemented for 10779 // compatibility. 10780 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 10781 break; 10782 } else { 10783 // A constant whose negation can be used as an immediate value in a 10784 // data-processing instruction. This can be used in GCC with an "n" 10785 // modifier that prints the negated value, for use with SUB 10786 // instructions. It is not useful otherwise but is implemented for 10787 // compatibility. 10788 if (ARM_AM::getSOImmVal(-CVal) != -1) 10789 break; 10790 } 10791 return; 10792 10793 case 'M': 10794 if (Subtarget->isThumb()) { // FIXME thumb2 10795 // This must be a multiple of 4 between 0 and 1020, for 10796 // ADD sp + immediate. 10797 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 10798 break; 10799 } else { 10800 // A power of two or a constant between 0 and 32. This is used in 10801 // GCC for the shift amount on shifted register operands, but it is 10802 // useful in general for any shift amounts. 10803 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 10804 break; 10805 } 10806 return; 10807 10808 case 'N': 10809 if (Subtarget->isThumb()) { // FIXME thumb2 10810 // This must be a constant between 0 and 31, for shift amounts. 10811 if (CVal >= 0 && CVal <= 31) 10812 break; 10813 } 10814 return; 10815 10816 case 'O': 10817 if (Subtarget->isThumb()) { // FIXME thumb2 10818 // This must be a multiple of 4 between -508 and 508, for 10819 // ADD/SUB sp = sp + immediate. 10820 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 10821 break; 10822 } 10823 return; 10824 } 10825 Result = DAG.getTargetConstant(CVal, Op.getValueType()); 10826 break; 10827 } 10828 10829 if (Result.getNode()) { 10830 Ops.push_back(Result); 10831 return; 10832 } 10833 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10834 } 10835 10836 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 10837 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only"); 10838 unsigned Opcode = Op->getOpcode(); 10839 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 10840 "Invalid opcode for Div/Rem lowering"); 10841 bool isSigned = (Opcode == ISD::SDIVREM); 10842 EVT VT = Op->getValueType(0); 10843 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 10844 10845 RTLIB::Libcall LC; 10846 switch (VT.getSimpleVT().SimpleTy) { 10847 default: llvm_unreachable("Unexpected request for libcall!"); 10848 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 10849 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 10850 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 10851 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 10852 } 10853 10854 SDValue InChain = DAG.getEntryNode(); 10855 10856 TargetLowering::ArgListTy Args; 10857 TargetLowering::ArgListEntry Entry; 10858 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) { 10859 EVT ArgVT = Op->getOperand(i).getValueType(); 10860 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 10861 Entry.Node = Op->getOperand(i); 10862 Entry.Ty = ArgTy; 10863 Entry.isSExt = isSigned; 10864 Entry.isZExt = !isSigned; 10865 Args.push_back(Entry); 10866 } 10867 10868 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 10869 getPointerTy()); 10870 10871 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 10872 10873 SDLoc dl(Op); 10874 TargetLowering::CallLoweringInfo CLI(DAG); 10875 CLI.setDebugLoc(dl).setChain(InChain) 10876 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 10877 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 10878 10879 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 10880 return CallInfo.first; 10881 } 10882 10883 SDValue 10884 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 10885 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 10886 SDLoc DL(Op); 10887 10888 // Get the inputs. 10889 SDValue Chain = Op.getOperand(0); 10890 SDValue Size = Op.getOperand(1); 10891 10892 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 10893 DAG.getConstant(2, MVT::i32)); 10894 10895 SDValue Flag; 10896 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 10897 Flag = Chain.getValue(1); 10898 10899 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10900 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 10901 10902 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 10903 Chain = NewSP.getValue(1); 10904 10905 SDValue Ops[2] = { NewSP, Chain }; 10906 return DAG.getMergeValues(Ops, DL); 10907 } 10908 10909 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10910 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 10911 "Unexpected type for custom-lowering FP_EXTEND"); 10912 10913 RTLIB::Libcall LC; 10914 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 10915 10916 SDValue SrcVal = Op.getOperand(0); 10917 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1, 10918 /*isSigned*/ false, SDLoc(Op)).first; 10919 } 10920 10921 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10922 assert(Op.getOperand(0).getValueType() == MVT::f64 && 10923 Subtarget->isFPOnlySP() && 10924 "Unexpected type for custom-lowering FP_ROUND"); 10925 10926 RTLIB::Libcall LC; 10927 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 10928 10929 SDValue SrcVal = Op.getOperand(0); 10930 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1, 10931 /*isSigned*/ false, SDLoc(Op)).first; 10932 } 10933 10934 bool 10935 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 10936 // The ARM target isn't yet aware of offsets. 10937 return false; 10938 } 10939 10940 bool ARM::isBitFieldInvertedMask(unsigned v) { 10941 if (v == 0xffffffff) 10942 return false; 10943 10944 // there can be 1's on either or both "outsides", all the "inside" 10945 // bits must be 0's 10946 unsigned TO = CountTrailingOnes_32(v); 10947 unsigned LO = CountLeadingOnes_32(v); 10948 v = (v >> TO) << TO; 10949 v = (v << LO) >> LO; 10950 return v == 0; 10951 } 10952 10953 /// isFPImmLegal - Returns true if the target can instruction select the 10954 /// specified FP immediate natively. If false, the legalizer will 10955 /// materialize the FP immediate as a load from a constant pool. 10956 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 10957 if (!Subtarget->hasVFP3()) 10958 return false; 10959 if (VT == MVT::f32) 10960 return ARM_AM::getFP32Imm(Imm) != -1; 10961 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 10962 return ARM_AM::getFP64Imm(Imm) != -1; 10963 return false; 10964 } 10965 10966 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 10967 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 10968 /// specified in the intrinsic calls. 10969 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 10970 const CallInst &I, 10971 unsigned Intrinsic) const { 10972 switch (Intrinsic) { 10973 case Intrinsic::arm_neon_vld1: 10974 case Intrinsic::arm_neon_vld2: 10975 case Intrinsic::arm_neon_vld3: 10976 case Intrinsic::arm_neon_vld4: 10977 case Intrinsic::arm_neon_vld2lane: 10978 case Intrinsic::arm_neon_vld3lane: 10979 case Intrinsic::arm_neon_vld4lane: { 10980 Info.opc = ISD::INTRINSIC_W_CHAIN; 10981 // Conservatively set memVT to the entire set of vectors loaded. 10982 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8; 10983 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 10984 Info.ptrVal = I.getArgOperand(0); 10985 Info.offset = 0; 10986 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 10987 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 10988 Info.vol = false; // volatile loads with NEON intrinsics not supported 10989 Info.readMem = true; 10990 Info.writeMem = false; 10991 return true; 10992 } 10993 case Intrinsic::arm_neon_vst1: 10994 case Intrinsic::arm_neon_vst2: 10995 case Intrinsic::arm_neon_vst3: 10996 case Intrinsic::arm_neon_vst4: 10997 case Intrinsic::arm_neon_vst2lane: 10998 case Intrinsic::arm_neon_vst3lane: 10999 case Intrinsic::arm_neon_vst4lane: { 11000 Info.opc = ISD::INTRINSIC_VOID; 11001 // Conservatively set memVT to the entire set of vectors stored. 11002 unsigned NumElts = 0; 11003 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 11004 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 11005 if (!ArgTy->isVectorTy()) 11006 break; 11007 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8; 11008 } 11009 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11010 Info.ptrVal = I.getArgOperand(0); 11011 Info.offset = 0; 11012 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11013 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11014 Info.vol = false; // volatile stores with NEON intrinsics not supported 11015 Info.readMem = false; 11016 Info.writeMem = true; 11017 return true; 11018 } 11019 case Intrinsic::arm_ldaex: 11020 case Intrinsic::arm_ldrex: { 11021 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 11022 Info.opc = ISD::INTRINSIC_W_CHAIN; 11023 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11024 Info.ptrVal = I.getArgOperand(0); 11025 Info.offset = 0; 11026 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType()); 11027 Info.vol = true; 11028 Info.readMem = true; 11029 Info.writeMem = false; 11030 return true; 11031 } 11032 case Intrinsic::arm_stlex: 11033 case Intrinsic::arm_strex: { 11034 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 11035 Info.opc = ISD::INTRINSIC_W_CHAIN; 11036 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11037 Info.ptrVal = I.getArgOperand(1); 11038 Info.offset = 0; 11039 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType()); 11040 Info.vol = true; 11041 Info.readMem = false; 11042 Info.writeMem = true; 11043 return true; 11044 } 11045 case Intrinsic::arm_stlexd: 11046 case Intrinsic::arm_strexd: { 11047 Info.opc = ISD::INTRINSIC_W_CHAIN; 11048 Info.memVT = MVT::i64; 11049 Info.ptrVal = I.getArgOperand(2); 11050 Info.offset = 0; 11051 Info.align = 8; 11052 Info.vol = true; 11053 Info.readMem = false; 11054 Info.writeMem = true; 11055 return true; 11056 } 11057 case Intrinsic::arm_ldaexd: 11058 case Intrinsic::arm_ldrexd: { 11059 Info.opc = ISD::INTRINSIC_W_CHAIN; 11060 Info.memVT = MVT::i64; 11061 Info.ptrVal = I.getArgOperand(0); 11062 Info.offset = 0; 11063 Info.align = 8; 11064 Info.vol = true; 11065 Info.readMem = true; 11066 Info.writeMem = false; 11067 return true; 11068 } 11069 default: 11070 break; 11071 } 11072 11073 return false; 11074 } 11075 11076 /// \brief Returns true if it is beneficial to convert a load of a constant 11077 /// to just the constant itself. 11078 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 11079 Type *Ty) const { 11080 assert(Ty->isIntegerTy()); 11081 11082 unsigned Bits = Ty->getPrimitiveSizeInBits(); 11083 if (Bits == 0 || Bits > 32) 11084 return false; 11085 return true; 11086 } 11087 11088 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; } 11089 11090 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 11091 ARM_MB::MemBOpt Domain) const { 11092 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11093 11094 // First, if the target has no DMB, see what fallback we can use. 11095 if (!Subtarget->hasDataBarrier()) { 11096 // Some ARMv6 cpus can support data barriers with an mcr instruction. 11097 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 11098 // here. 11099 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 11100 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 11101 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 11102 Builder.getInt32(0), Builder.getInt32(7), 11103 Builder.getInt32(10), Builder.getInt32(5)}; 11104 return Builder.CreateCall(MCR, args); 11105 } else { 11106 // Instead of using barriers, atomic accesses on these subtargets use 11107 // libcalls. 11108 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 11109 } 11110 } else { 11111 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 11112 // Only a full system barrier exists in the M-class architectures. 11113 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 11114 Constant *CDomain = Builder.getInt32(Domain); 11115 return Builder.CreateCall(DMB, CDomain); 11116 } 11117 } 11118 11119 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11120 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11121 AtomicOrdering Ord, bool IsStore, 11122 bool IsLoad) const { 11123 if (!getInsertFencesForAtomic()) 11124 return nullptr; 11125 11126 switch (Ord) { 11127 case NotAtomic: 11128 case Unordered: 11129 llvm_unreachable("Invalid fence: unordered/non-atomic"); 11130 case Monotonic: 11131 case Acquire: 11132 return nullptr; // Nothing to do 11133 case SequentiallyConsistent: 11134 if (!IsStore) 11135 return nullptr; // Nothing to do 11136 /*FALLTHROUGH*/ 11137 case Release: 11138 case AcquireRelease: 11139 if (Subtarget->isSwift()) 11140 return makeDMB(Builder, ARM_MB::ISHST); 11141 // FIXME: add a comment with a link to documentation justifying this. 11142 else 11143 return makeDMB(Builder, ARM_MB::ISH); 11144 } 11145 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 11146 } 11147 11148 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11149 AtomicOrdering Ord, bool IsStore, 11150 bool IsLoad) const { 11151 if (!getInsertFencesForAtomic()) 11152 return nullptr; 11153 11154 switch (Ord) { 11155 case NotAtomic: 11156 case Unordered: 11157 llvm_unreachable("Invalid fence: unordered/not-atomic"); 11158 case Monotonic: 11159 case Release: 11160 return nullptr; // Nothing to do 11161 case Acquire: 11162 case AcquireRelease: 11163 case SequentiallyConsistent: 11164 return makeDMB(Builder, ARM_MB::ISH); 11165 } 11166 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 11167 } 11168 11169 // Loads and stores less than 64-bits are already atomic; ones above that 11170 // are doomed anyway, so defer to the default libcall and blame the OS when 11171 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 11172 // anything for those. 11173 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 11174 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 11175 return (Size == 64) && !Subtarget->isMClass(); 11176 } 11177 11178 // Loads and stores less than 64-bits are already atomic; ones above that 11179 // are doomed anyway, so defer to the default libcall and blame the OS when 11180 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 11181 // anything for those. 11182 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 11183 // guarantee, see DDI0406C ARM architecture reference manual, 11184 // sections A8.8.72-74 LDRD) 11185 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 11186 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 11187 return (Size == 64) && !Subtarget->isMClass(); 11188 } 11189 11190 // For the real atomic operations, we have ldrex/strex up to 32 bits, 11191 // and up to 64 bits on the non-M profiles 11192 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11193 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11194 return Size <= (Subtarget->isMClass() ? 32U : 64U); 11195 } 11196 11197 // This has so far only been implemented for MachO. 11198 bool ARMTargetLowering::useLoadStackGuardNode() const { 11199 return Subtarget->isTargetMachO(); 11200 } 11201 11202 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 11203 unsigned &Cost) const { 11204 // If we do not have NEON, vector types are not natively supported. 11205 if (!Subtarget->hasNEON()) 11206 return false; 11207 11208 // Floating point values and vector values map to the same register file. 11209 // Therefore, althought we could do a store extract of a vector type, this is 11210 // better to leave at float as we have more freedom in the addressing mode for 11211 // those. 11212 if (VectorTy->isFPOrFPVectorTy()) 11213 return false; 11214 11215 // If the index is unknown at compile time, this is very expensive to lower 11216 // and it is not possible to combine the store with the extract. 11217 if (!isa<ConstantInt>(Idx)) 11218 return false; 11219 11220 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 11221 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 11222 // We can do a store + vector extract on any vector that fits perfectly in a D 11223 // or Q register. 11224 if (BitWidth == 64 || BitWidth == 128) { 11225 Cost = 0; 11226 return true; 11227 } 11228 return false; 11229 } 11230 11231 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 11232 AtomicOrdering Ord) const { 11233 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11234 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 11235 bool IsAcquire = isAtLeastAcquire(Ord); 11236 11237 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 11238 // intrinsic must return {i32, i32} and we have to recombine them into a 11239 // single i64 here. 11240 if (ValTy->getPrimitiveSizeInBits() == 64) { 11241 Intrinsic::ID Int = 11242 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 11243 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 11244 11245 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 11246 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 11247 11248 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 11249 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 11250 if (!Subtarget->isLittle()) 11251 std::swap (Lo, Hi); 11252 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 11253 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 11254 return Builder.CreateOr( 11255 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 11256 } 11257 11258 Type *Tys[] = { Addr->getType() }; 11259 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 11260 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 11261 11262 return Builder.CreateTruncOrBitCast( 11263 Builder.CreateCall(Ldrex, Addr), 11264 cast<PointerType>(Addr->getType())->getElementType()); 11265 } 11266 11267 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 11268 Value *Addr, 11269 AtomicOrdering Ord) const { 11270 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11271 bool IsRelease = isAtLeastRelease(Ord); 11272 11273 // Since the intrinsics must have legal type, the i64 intrinsics take two 11274 // parameters: "i32, i32". We must marshal Val into the appropriate form 11275 // before the call. 11276 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 11277 Intrinsic::ID Int = 11278 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 11279 Function *Strex = Intrinsic::getDeclaration(M, Int); 11280 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 11281 11282 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 11283 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 11284 if (!Subtarget->isLittle()) 11285 std::swap (Lo, Hi); 11286 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 11287 return Builder.CreateCall3(Strex, Lo, Hi, Addr); 11288 } 11289 11290 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 11291 Type *Tys[] = { Addr->getType() }; 11292 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 11293 11294 return Builder.CreateCall2( 11295 Strex, Builder.CreateZExtOrBitCast( 11296 Val, Strex->getFunctionType()->getParamType(0)), 11297 Addr); 11298 } 11299 11300 enum HABaseType { 11301 HA_UNKNOWN = 0, 11302 HA_FLOAT, 11303 HA_DOUBLE, 11304 HA_VECT64, 11305 HA_VECT128 11306 }; 11307 11308 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 11309 uint64_t &Members) { 11310 if (const StructType *ST = dyn_cast<StructType>(Ty)) { 11311 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 11312 uint64_t SubMembers = 0; 11313 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 11314 return false; 11315 Members += SubMembers; 11316 } 11317 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 11318 uint64_t SubMembers = 0; 11319 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 11320 return false; 11321 Members += SubMembers * AT->getNumElements(); 11322 } else if (Ty->isFloatTy()) { 11323 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 11324 return false; 11325 Members = 1; 11326 Base = HA_FLOAT; 11327 } else if (Ty->isDoubleTy()) { 11328 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 11329 return false; 11330 Members = 1; 11331 Base = HA_DOUBLE; 11332 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) { 11333 Members = 1; 11334 switch (Base) { 11335 case HA_FLOAT: 11336 case HA_DOUBLE: 11337 return false; 11338 case HA_VECT64: 11339 return VT->getBitWidth() == 64; 11340 case HA_VECT128: 11341 return VT->getBitWidth() == 128; 11342 case HA_UNKNOWN: 11343 switch (VT->getBitWidth()) { 11344 case 64: 11345 Base = HA_VECT64; 11346 return true; 11347 case 128: 11348 Base = HA_VECT128; 11349 return true; 11350 default: 11351 return false; 11352 } 11353 } 11354 } 11355 11356 return (Members > 0 && Members <= 4); 11357 } 11358 11359 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate. 11360 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 11361 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 11362 if (getEffectiveCallingConv(CallConv, isVarArg) != 11363 CallingConv::ARM_AAPCS_VFP) 11364 return false; 11365 11366 HABaseType Base = HA_UNKNOWN; 11367 uint64_t Members = 0; 11368 bool result = isHomogeneousAggregate(Ty, Base, Members); 11369 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump()); 11370 return result; 11371 } 11372