1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMCallingConv.h" 17 #include "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMPerfectShuffle.h" 20 #include "ARMSubtarget.h" 21 #include "ARMTargetMachine.h" 22 #include "ARMTargetObjectFile.h" 23 #include "MCTargetDesc/ARMAddressingModes.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringSwitch.h" 27 #include "llvm/CodeGen/Analysis.h" 28 #include "llvm/CodeGen/CallingConvLower.h" 29 #include "llvm/CodeGen/IntrinsicLowering.h" 30 #include "llvm/CodeGen/MachineBasicBlock.h" 31 #include "llvm/CodeGen/MachineFrameInfo.h" 32 #include "llvm/CodeGen/MachineFunction.h" 33 #include "llvm/CodeGen/MachineInstrBuilder.h" 34 #include "llvm/CodeGen/MachineJumpTableInfo.h" 35 #include "llvm/CodeGen/MachineModuleInfo.h" 36 #include "llvm/CodeGen/MachineRegisterInfo.h" 37 #include "llvm/CodeGen/SelectionDAG.h" 38 #include "llvm/IR/CallingConv.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GlobalValue.h" 42 #include "llvm/IR/IRBuilder.h" 43 #include "llvm/IR/Instruction.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/IR/IntrinsicInst.h" 46 #include "llvm/IR/Intrinsics.h" 47 #include "llvm/IR/Type.h" 48 #include "llvm/MC/MCSectionMachO.h" 49 #include "llvm/Support/CommandLine.h" 50 #include "llvm/Support/Debug.h" 51 #include "llvm/Support/ErrorHandling.h" 52 #include "llvm/Support/MathExtras.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include "llvm/Target/TargetOptions.h" 55 #include <utility> 56 using namespace llvm; 57 58 #define DEBUG_TYPE "arm-isel" 59 60 STATISTIC(NumTailCalls, "Number of tail calls"); 61 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 62 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 63 64 static cl::opt<bool> 65 ARMInterworking("arm-interworking", cl::Hidden, 66 cl::desc("Enable / disable ARM interworking (for debugging only)"), 67 cl::init(true)); 68 69 namespace { 70 class ARMCCState : public CCState { 71 public: 72 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 73 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 74 ParmContext PC) 75 : CCState(CC, isVarArg, MF, locs, C) { 76 assert(((PC == Call) || (PC == Prologue)) && 77 "ARMCCState users must specify whether their context is call" 78 "or prologue generation."); 79 CallOrPrologue = PC; 80 } 81 }; 82 } 83 84 // The APCS parameter registers. 85 static const MCPhysReg GPRArgRegs[] = { 86 ARM::R0, ARM::R1, ARM::R2, ARM::R3 87 }; 88 89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 90 MVT PromotedBitwiseVT) { 91 if (VT != PromotedLdStVT) { 92 setOperationAction(ISD::LOAD, VT, Promote); 93 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 94 95 setOperationAction(ISD::STORE, VT, Promote); 96 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 97 } 98 99 MVT ElemTy = VT.getVectorElementType(); 100 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 101 setOperationAction(ISD::SETCC, VT, Custom); 102 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 104 if (ElemTy == MVT::i32) { 105 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 106 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 107 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 108 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 109 } else { 110 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 111 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 112 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 113 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 114 } 115 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 116 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 117 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 118 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 119 setOperationAction(ISD::SELECT, VT, Expand); 120 setOperationAction(ISD::SELECT_CC, VT, Expand); 121 setOperationAction(ISD::VSELECT, VT, Expand); 122 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 123 if (VT.isInteger()) { 124 setOperationAction(ISD::SHL, VT, Custom); 125 setOperationAction(ISD::SRA, VT, Custom); 126 setOperationAction(ISD::SRL, VT, Custom); 127 } 128 129 // Promote all bit-wise operations. 130 if (VT.isInteger() && VT != PromotedBitwiseVT) { 131 setOperationAction(ISD::AND, VT, Promote); 132 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 133 setOperationAction(ISD::OR, VT, Promote); 134 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 135 setOperationAction(ISD::XOR, VT, Promote); 136 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 137 } 138 139 // Neon does not support vector divide/remainder operations. 140 setOperationAction(ISD::SDIV, VT, Expand); 141 setOperationAction(ISD::UDIV, VT, Expand); 142 setOperationAction(ISD::FDIV, VT, Expand); 143 setOperationAction(ISD::SREM, VT, Expand); 144 setOperationAction(ISD::UREM, VT, Expand); 145 setOperationAction(ISD::FREM, VT, Expand); 146 147 if (!VT.isFloatingPoint() && 148 VT != MVT::v2i64 && VT != MVT::v1i64) 149 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 150 setOperationAction(Opcode, VT, Legal); 151 } 152 153 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 154 addRegisterClass(VT, &ARM::DPRRegClass); 155 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 156 } 157 158 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 159 addRegisterClass(VT, &ARM::DPairRegClass); 160 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 161 } 162 163 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 164 const ARMSubtarget &STI) 165 : TargetLowering(TM), Subtarget(&STI) { 166 RegInfo = Subtarget->getRegisterInfo(); 167 Itins = Subtarget->getInstrItineraryData(); 168 169 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 170 171 if (Subtarget->isTargetMachO()) { 172 // Uses VFP for Thumb libfuncs if available. 173 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 174 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 175 static const struct { 176 const RTLIB::Libcall Op; 177 const char * const Name; 178 const ISD::CondCode Cond; 179 } LibraryCalls[] = { 180 // Single-precision floating-point arithmetic. 181 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 182 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 183 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 184 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 185 186 // Double-precision floating-point arithmetic. 187 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 188 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 189 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 190 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 191 192 // Single-precision comparisons. 193 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 194 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 195 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 196 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 197 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 198 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 199 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 200 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 201 202 // Double-precision comparisons. 203 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 204 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 205 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 206 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 207 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 208 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 209 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 210 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 211 212 // Floating-point to integer conversions. 213 // i64 conversions are done via library routines even when generating VFP 214 // instructions, so use the same ones. 215 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 216 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 217 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 218 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 219 220 // Conversions between floating types. 221 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 222 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 223 224 // Integer to floating-point conversions. 225 // i64 conversions are done via library routines even when generating VFP 226 // instructions, so use the same ones. 227 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 228 // e.g., __floatunsidf vs. __floatunssidfvfp. 229 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 230 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 231 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 232 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 233 }; 234 235 for (const auto &LC : LibraryCalls) { 236 setLibcallName(LC.Op, LC.Name); 237 if (LC.Cond != ISD::SETCC_INVALID) 238 setCmpLibcallCC(LC.Op, LC.Cond); 239 } 240 } 241 242 // Set the correct calling convention for ARMv7k WatchOS. It's just 243 // AAPCS_VFP for functions as simple as libcalls. 244 if (Subtarget->isTargetWatchABI()) { 245 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 246 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 247 } 248 } 249 250 // These libcalls are not available in 32-bit. 251 setLibcallName(RTLIB::SHL_I128, nullptr); 252 setLibcallName(RTLIB::SRL_I128, nullptr); 253 setLibcallName(RTLIB::SRA_I128, nullptr); 254 255 // RTLIB 256 if (Subtarget->isAAPCS_ABI() && 257 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 258 Subtarget->isTargetAndroid())) { 259 static const struct { 260 const RTLIB::Libcall Op; 261 const char * const Name; 262 const CallingConv::ID CC; 263 const ISD::CondCode Cond; 264 } LibraryCalls[] = { 265 // Double-precision floating-point arithmetic helper functions 266 // RTABI chapter 4.1.2, Table 2 267 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 268 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 269 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 270 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 271 272 // Double-precision floating-point comparison helper functions 273 // RTABI chapter 4.1.2, Table 3 274 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 275 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 276 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 277 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 278 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 279 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 280 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 281 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 282 283 // Single-precision floating-point arithmetic helper functions 284 // RTABI chapter 4.1.2, Table 4 285 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 286 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 287 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 288 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 289 290 // Single-precision floating-point comparison helper functions 291 // RTABI chapter 4.1.2, Table 5 292 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 293 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 294 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 295 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 296 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 297 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 298 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 299 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 300 301 // Floating-point to integer conversions. 302 // RTABI chapter 4.1.2, Table 6 303 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 304 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 305 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 306 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 307 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 308 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 309 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 310 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 311 312 // Conversions between floating types. 313 // RTABI chapter 4.1.2, Table 7 314 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 315 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 316 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 317 318 // Integer to floating-point conversions. 319 // RTABI chapter 4.1.2, Table 8 320 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 322 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 323 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 324 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 325 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 326 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 327 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 328 329 // Long long helper functions 330 // RTABI chapter 4.2, Table 9 331 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 335 336 // Integer division functions 337 // RTABI chapter 4.3.1 338 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 345 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 346 }; 347 348 for (const auto &LC : LibraryCalls) { 349 setLibcallName(LC.Op, LC.Name); 350 setLibcallCallingConv(LC.Op, LC.CC); 351 if (LC.Cond != ISD::SETCC_INVALID) 352 setCmpLibcallCC(LC.Op, LC.Cond); 353 } 354 355 // EABI dependent RTLIB 356 if (TM.Options.EABIVersion == EABI::EABI4 || 357 TM.Options.EABIVersion == EABI::EABI5) { 358 static const struct { 359 const RTLIB::Libcall Op; 360 const char *const Name; 361 const CallingConv::ID CC; 362 const ISD::CondCode Cond; 363 } MemOpsLibraryCalls[] = { 364 // Memory operations 365 // RTABI chapter 4.3.4 366 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 367 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 369 }; 370 371 for (const auto &LC : MemOpsLibraryCalls) { 372 setLibcallName(LC.Op, LC.Name); 373 setLibcallCallingConv(LC.Op, LC.CC); 374 if (LC.Cond != ISD::SETCC_INVALID) 375 setCmpLibcallCC(LC.Op, LC.Cond); 376 } 377 } 378 } 379 380 if (Subtarget->isTargetWindows()) { 381 static const struct { 382 const RTLIB::Libcall Op; 383 const char * const Name; 384 const CallingConv::ID CC; 385 } LibraryCalls[] = { 386 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 387 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 388 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 389 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 390 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 391 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 392 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 393 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 394 }; 395 396 for (const auto &LC : LibraryCalls) { 397 setLibcallName(LC.Op, LC.Name); 398 setLibcallCallingConv(LC.Op, LC.CC); 399 } 400 } 401 402 // Use divmod compiler-rt calls for iOS 5.0 and later. 403 if (Subtarget->isTargetWatchOS() || 404 (Subtarget->isTargetIOS() && 405 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 406 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 407 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 408 } 409 410 // The half <-> float conversion functions are always soft-float, but are 411 // needed for some targets which use a hard-float calling convention by 412 // default. 413 if (Subtarget->isAAPCS_ABI()) { 414 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 415 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 416 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 417 } else { 418 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 419 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 420 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 421 } 422 423 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 424 // a __gnu_ prefix (which is the default). 425 if (Subtarget->isTargetAEABI()) { 426 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 427 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 428 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 429 } 430 431 if (Subtarget->isThumb1Only()) 432 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 433 else 434 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 435 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 436 !Subtarget->isThumb1Only()) { 437 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 438 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 439 } 440 441 for (MVT VT : MVT::vector_valuetypes()) { 442 for (MVT InnerVT : MVT::vector_valuetypes()) { 443 setTruncStoreAction(VT, InnerVT, Expand); 444 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 445 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 446 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 447 } 448 449 setOperationAction(ISD::MULHS, VT, Expand); 450 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 451 setOperationAction(ISD::MULHU, VT, Expand); 452 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 453 454 setOperationAction(ISD::BSWAP, VT, Expand); 455 } 456 457 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 458 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 459 460 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 461 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 462 463 if (Subtarget->hasNEON()) { 464 addDRTypeForNEON(MVT::v2f32); 465 addDRTypeForNEON(MVT::v8i8); 466 addDRTypeForNEON(MVT::v4i16); 467 addDRTypeForNEON(MVT::v2i32); 468 addDRTypeForNEON(MVT::v1i64); 469 470 addQRTypeForNEON(MVT::v4f32); 471 addQRTypeForNEON(MVT::v2f64); 472 addQRTypeForNEON(MVT::v16i8); 473 addQRTypeForNEON(MVT::v8i16); 474 addQRTypeForNEON(MVT::v4i32); 475 addQRTypeForNEON(MVT::v2i64); 476 477 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 478 // neither Neon nor VFP support any arithmetic operations on it. 479 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 480 // supported for v4f32. 481 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 482 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 483 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 484 // FIXME: Code duplication: FDIV and FREM are expanded always, see 485 // ARMTargetLowering::addTypeForNEON method for details. 486 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 487 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 488 // FIXME: Create unittest. 489 // In another words, find a way when "copysign" appears in DAG with vector 490 // operands. 491 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 492 // FIXME: Code duplication: SETCC has custom operation action, see 493 // ARMTargetLowering::addTypeForNEON method for details. 494 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 495 // FIXME: Create unittest for FNEG and for FABS. 496 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 497 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 498 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 499 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 500 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 501 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 502 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 503 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 504 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 505 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 506 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 507 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 508 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 509 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 510 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 511 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 512 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 513 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 514 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 515 516 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 517 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 518 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 519 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 520 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 521 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 522 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 523 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 524 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 525 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 526 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 527 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 528 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 529 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 530 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 531 532 // Mark v2f32 intrinsics. 533 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 534 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 535 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 536 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 537 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 538 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 539 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 540 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 541 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 542 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 543 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 544 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 545 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 546 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 547 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 548 549 // Neon does not support some operations on v1i64 and v2i64 types. 550 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 551 // Custom handling for some quad-vector types to detect VMULL. 552 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 553 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 554 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 555 // Custom handling for some vector types to avoid expensive expansions 556 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 557 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 558 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 559 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 560 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 561 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 562 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 563 // a destination type that is wider than the source, and nor does 564 // it have a FP_TO_[SU]INT instruction with a narrower destination than 565 // source. 566 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 567 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 568 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 569 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 570 571 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 572 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 573 574 // NEON does not have single instruction CTPOP for vectors with element 575 // types wider than 8-bits. However, custom lowering can leverage the 576 // v8i8/v16i8 vcnt instruction. 577 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 578 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 579 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 580 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 581 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 582 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 583 584 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 585 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 586 587 // NEON does not have single instruction CTTZ for vectors. 588 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 589 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 590 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 591 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 592 593 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 594 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 595 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 596 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 597 598 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 599 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 600 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 602 603 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 605 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 606 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 607 608 // NEON only has FMA instructions as of VFP4. 609 if (!Subtarget->hasVFP4()) { 610 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 611 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 612 } 613 614 setTargetDAGCombine(ISD::INTRINSIC_VOID); 615 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 616 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 617 setTargetDAGCombine(ISD::SHL); 618 setTargetDAGCombine(ISD::SRL); 619 setTargetDAGCombine(ISD::SRA); 620 setTargetDAGCombine(ISD::SIGN_EXTEND); 621 setTargetDAGCombine(ISD::ZERO_EXTEND); 622 setTargetDAGCombine(ISD::ANY_EXTEND); 623 setTargetDAGCombine(ISD::BUILD_VECTOR); 624 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 625 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 626 setTargetDAGCombine(ISD::STORE); 627 setTargetDAGCombine(ISD::FP_TO_SINT); 628 setTargetDAGCombine(ISD::FP_TO_UINT); 629 setTargetDAGCombine(ISD::FDIV); 630 setTargetDAGCombine(ISD::LOAD); 631 632 // It is legal to extload from v4i8 to v4i16 or v4i32. 633 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 634 MVT::v2i32}) { 635 for (MVT VT : MVT::integer_vector_valuetypes()) { 636 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 637 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 638 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 639 } 640 } 641 } 642 643 // ARM and Thumb2 support UMLAL/SMLAL. 644 if (!Subtarget->isThumb1Only()) 645 setTargetDAGCombine(ISD::ADDC); 646 647 if (Subtarget->isFPOnlySP()) { 648 // When targeting a floating-point unit with only single-precision 649 // operations, f64 is legal for the few double-precision instructions which 650 // are present However, no double-precision operations other than moves, 651 // loads and stores are provided by the hardware. 652 setOperationAction(ISD::FADD, MVT::f64, Expand); 653 setOperationAction(ISD::FSUB, MVT::f64, Expand); 654 setOperationAction(ISD::FMUL, MVT::f64, Expand); 655 setOperationAction(ISD::FMA, MVT::f64, Expand); 656 setOperationAction(ISD::FDIV, MVT::f64, Expand); 657 setOperationAction(ISD::FREM, MVT::f64, Expand); 658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 659 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 660 setOperationAction(ISD::FNEG, MVT::f64, Expand); 661 setOperationAction(ISD::FABS, MVT::f64, Expand); 662 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 663 setOperationAction(ISD::FSIN, MVT::f64, Expand); 664 setOperationAction(ISD::FCOS, MVT::f64, Expand); 665 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 666 setOperationAction(ISD::FPOW, MVT::f64, Expand); 667 setOperationAction(ISD::FLOG, MVT::f64, Expand); 668 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 669 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 670 setOperationAction(ISD::FEXP, MVT::f64, Expand); 671 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 672 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 673 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 674 setOperationAction(ISD::FRINT, MVT::f64, Expand); 675 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 676 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 677 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 678 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 679 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 680 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 681 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 682 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 683 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 684 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 685 } 686 687 computeRegisterProperties(Subtarget->getRegisterInfo()); 688 689 // ARM does not have floating-point extending loads. 690 for (MVT VT : MVT::fp_valuetypes()) { 691 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 692 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 693 } 694 695 // ... or truncating stores 696 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 697 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 698 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 699 700 // ARM does not have i1 sign extending load. 701 for (MVT VT : MVT::integer_valuetypes()) 702 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 703 704 // ARM supports all 4 flavors of integer indexed load / store. 705 if (!Subtarget->isThumb1Only()) { 706 for (unsigned im = (unsigned)ISD::PRE_INC; 707 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 708 setIndexedLoadAction(im, MVT::i1, Legal); 709 setIndexedLoadAction(im, MVT::i8, Legal); 710 setIndexedLoadAction(im, MVT::i16, Legal); 711 setIndexedLoadAction(im, MVT::i32, Legal); 712 setIndexedStoreAction(im, MVT::i1, Legal); 713 setIndexedStoreAction(im, MVT::i8, Legal); 714 setIndexedStoreAction(im, MVT::i16, Legal); 715 setIndexedStoreAction(im, MVT::i32, Legal); 716 } 717 } 718 719 setOperationAction(ISD::SADDO, MVT::i32, Custom); 720 setOperationAction(ISD::UADDO, MVT::i32, Custom); 721 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 722 setOperationAction(ISD::USUBO, MVT::i32, Custom); 723 724 // i64 operation support. 725 setOperationAction(ISD::MUL, MVT::i64, Expand); 726 setOperationAction(ISD::MULHU, MVT::i32, Expand); 727 if (Subtarget->isThumb1Only()) { 728 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 729 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 730 } 731 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 732 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 733 setOperationAction(ISD::MULHS, MVT::i32, Expand); 734 735 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 736 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 737 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 738 setOperationAction(ISD::SRL, MVT::i64, Custom); 739 setOperationAction(ISD::SRA, MVT::i64, Custom); 740 741 if (!Subtarget->isThumb1Only()) { 742 // FIXME: We should do this for Thumb1 as well. 743 setOperationAction(ISD::ADDC, MVT::i32, Custom); 744 setOperationAction(ISD::ADDE, MVT::i32, Custom); 745 setOperationAction(ISD::SUBC, MVT::i32, Custom); 746 setOperationAction(ISD::SUBE, MVT::i32, Custom); 747 } 748 749 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 750 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 751 752 // ARM does not have ROTL. 753 setOperationAction(ISD::ROTL, MVT::i32, Expand); 754 for (MVT VT : MVT::vector_valuetypes()) { 755 setOperationAction(ISD::ROTL, VT, Expand); 756 setOperationAction(ISD::ROTR, VT, Expand); 757 } 758 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 759 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 760 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 761 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 762 763 // @llvm.readcyclecounter requires the Performance Monitors extension. 764 // Default to the 0 expansion on unsupported platforms. 765 // FIXME: Technically there are older ARM CPUs that have 766 // implementation-specific ways of obtaining this information. 767 if (Subtarget->hasPerfMon()) 768 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 769 770 // Only ARMv6 has BSWAP. 771 if (!Subtarget->hasV6Ops()) 772 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 773 774 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 775 : Subtarget->hasDivideInARMMode(); 776 if (!hasDivide) { 777 // These are expanded into libcalls if the cpu doesn't have HW divider. 778 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 779 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 780 } 781 782 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 783 setOperationAction(ISD::SDIV, MVT::i32, Custom); 784 setOperationAction(ISD::UDIV, MVT::i32, Custom); 785 786 setOperationAction(ISD::SDIV, MVT::i64, Custom); 787 setOperationAction(ISD::UDIV, MVT::i64, Custom); 788 } 789 790 setOperationAction(ISD::SREM, MVT::i32, Expand); 791 setOperationAction(ISD::UREM, MVT::i32, Expand); 792 // Register based DivRem for AEABI (RTABI 4.2) 793 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 794 Subtarget->isTargetGNUAEABI()) { 795 setOperationAction(ISD::SREM, MVT::i64, Custom); 796 setOperationAction(ISD::UREM, MVT::i64, Custom); 797 798 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 799 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 800 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 801 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 802 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 803 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 804 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 805 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 806 807 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 808 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 809 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 810 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 811 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 812 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 813 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 814 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 815 816 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 817 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 818 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 819 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 820 } else { 821 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 822 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 823 } 824 825 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 826 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 827 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 828 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 829 830 setOperationAction(ISD::TRAP, MVT::Other, Legal); 831 832 // Use the default implementation. 833 setOperationAction(ISD::VASTART, MVT::Other, Custom); 834 setOperationAction(ISD::VAARG, MVT::Other, Expand); 835 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 836 setOperationAction(ISD::VAEND, MVT::Other, Expand); 837 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 838 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 839 840 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 841 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 842 else 843 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 844 845 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 846 // the default expansion. 847 InsertFencesForAtomic = false; 848 if (Subtarget->hasAnyDataBarrier() && 849 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 850 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 851 // to ldrex/strex loops already. 852 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 853 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 854 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 855 856 // On v8, we have particularly efficient implementations of atomic fences 857 // if they can be combined with nearby atomic loads and stores. 858 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 859 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 860 InsertFencesForAtomic = true; 861 } 862 } else { 863 // If there's anything we can use as a barrier, go through custom lowering 864 // for ATOMIC_FENCE. 865 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 866 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 867 868 // Set them all for expansion, which will force libcalls. 869 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 870 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 871 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 872 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 873 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 874 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 875 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 876 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 877 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 878 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 879 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 880 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 881 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 882 // Unordered/Monotonic case. 883 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 884 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 885 } 886 887 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 888 889 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 890 if (!Subtarget->hasV6Ops()) { 891 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 892 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 893 } 894 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 895 896 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 897 !Subtarget->isThumb1Only()) { 898 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 899 // iff target supports vfp2. 900 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 901 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 902 } 903 904 // We want to custom lower some of our intrinsics. 905 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 906 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 907 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 908 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 909 if (Subtarget->useSjLjEH()) 910 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 911 912 setOperationAction(ISD::SETCC, MVT::i32, Expand); 913 setOperationAction(ISD::SETCC, MVT::f32, Expand); 914 setOperationAction(ISD::SETCC, MVT::f64, Expand); 915 setOperationAction(ISD::SELECT, MVT::i32, Custom); 916 setOperationAction(ISD::SELECT, MVT::f32, Custom); 917 setOperationAction(ISD::SELECT, MVT::f64, Custom); 918 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 919 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 920 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 921 922 // Thumb-1 cannot currently select ARMISD::SUBE. 923 if (!Subtarget->isThumb1Only()) 924 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 925 926 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 927 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 928 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 929 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 930 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 931 932 // We don't support sin/cos/fmod/copysign/pow 933 setOperationAction(ISD::FSIN, MVT::f64, Expand); 934 setOperationAction(ISD::FSIN, MVT::f32, Expand); 935 setOperationAction(ISD::FCOS, MVT::f32, Expand); 936 setOperationAction(ISD::FCOS, MVT::f64, Expand); 937 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 938 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 939 setOperationAction(ISD::FREM, MVT::f64, Expand); 940 setOperationAction(ISD::FREM, MVT::f32, Expand); 941 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 942 !Subtarget->isThumb1Only()) { 943 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 944 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 945 } 946 setOperationAction(ISD::FPOW, MVT::f64, Expand); 947 setOperationAction(ISD::FPOW, MVT::f32, Expand); 948 949 if (!Subtarget->hasVFP4()) { 950 setOperationAction(ISD::FMA, MVT::f64, Expand); 951 setOperationAction(ISD::FMA, MVT::f32, Expand); 952 } 953 954 // Various VFP goodness 955 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 956 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 957 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 958 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 959 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 960 } 961 962 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 963 if (!Subtarget->hasFP16()) { 964 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 965 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 966 } 967 } 968 969 // Combine sin / cos into one node or libcall if possible. 970 if (Subtarget->hasSinCos()) { 971 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 972 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 973 if (Subtarget->isTargetWatchABI()) { 974 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 975 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 976 } 977 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 978 // For iOS, we don't want to the normal expansion of a libcall to 979 // sincos. We want to issue a libcall to __sincos_stret. 980 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 981 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 982 } 983 } 984 985 // FP-ARMv8 implements a lot of rounding-like FP operations. 986 if (Subtarget->hasFPARMv8()) { 987 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 988 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 989 setOperationAction(ISD::FROUND, MVT::f32, Legal); 990 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 991 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 992 setOperationAction(ISD::FRINT, MVT::f32, Legal); 993 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 994 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 995 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 996 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 997 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 998 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 999 1000 if (!Subtarget->isFPOnlySP()) { 1001 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1002 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1003 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1004 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1005 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1006 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1007 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1008 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1009 } 1010 } 1011 1012 if (Subtarget->hasNEON()) { 1013 // vmin and vmax aren't available in a scalar form, so we use 1014 // a NEON instruction with an undef lane instead. 1015 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1016 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1017 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1018 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1019 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1020 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1021 } 1022 1023 // We have target-specific dag combine patterns for the following nodes: 1024 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1025 setTargetDAGCombine(ISD::ADD); 1026 setTargetDAGCombine(ISD::SUB); 1027 setTargetDAGCombine(ISD::MUL); 1028 setTargetDAGCombine(ISD::AND); 1029 setTargetDAGCombine(ISD::OR); 1030 setTargetDAGCombine(ISD::XOR); 1031 1032 if (Subtarget->hasV6Ops()) 1033 setTargetDAGCombine(ISD::SRL); 1034 1035 setStackPointerRegisterToSaveRestore(ARM::SP); 1036 1037 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1038 !Subtarget->hasVFP2()) 1039 setSchedulingPreference(Sched::RegPressure); 1040 else 1041 setSchedulingPreference(Sched::Hybrid); 1042 1043 //// temporary - rewrite interface to use type 1044 MaxStoresPerMemset = 8; 1045 MaxStoresPerMemsetOptSize = 4; 1046 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1047 MaxStoresPerMemcpyOptSize = 2; 1048 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1049 MaxStoresPerMemmoveOptSize = 2; 1050 1051 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1052 // are at least 4 bytes aligned. 1053 setMinStackArgumentAlignment(4); 1054 1055 // Prefer likely predicted branches to selects on out-of-order cores. 1056 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1057 1058 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1059 } 1060 1061 bool ARMTargetLowering::useSoftFloat() const { 1062 return Subtarget->useSoftFloat(); 1063 } 1064 1065 // FIXME: It might make sense to define the representative register class as the 1066 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1067 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1068 // SPR's representative would be DPR_VFP2. This should work well if register 1069 // pressure tracking were modified such that a register use would increment the 1070 // pressure of the register class's representative and all of it's super 1071 // classes' representatives transitively. We have not implemented this because 1072 // of the difficulty prior to coalescing of modeling operand register classes 1073 // due to the common occurrence of cross class copies and subregister insertions 1074 // and extractions. 1075 std::pair<const TargetRegisterClass *, uint8_t> 1076 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1077 MVT VT) const { 1078 const TargetRegisterClass *RRC = nullptr; 1079 uint8_t Cost = 1; 1080 switch (VT.SimpleTy) { 1081 default: 1082 return TargetLowering::findRepresentativeClass(TRI, VT); 1083 // Use DPR as representative register class for all floating point 1084 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1085 // the cost is 1 for both f32 and f64. 1086 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1087 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1088 RRC = &ARM::DPRRegClass; 1089 // When NEON is used for SP, only half of the register file is available 1090 // because operations that define both SP and DP results will be constrained 1091 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1092 // coalescing by double-counting the SP regs. See the FIXME above. 1093 if (Subtarget->useNEONForSinglePrecisionFP()) 1094 Cost = 2; 1095 break; 1096 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1097 case MVT::v4f32: case MVT::v2f64: 1098 RRC = &ARM::DPRRegClass; 1099 Cost = 2; 1100 break; 1101 case MVT::v4i64: 1102 RRC = &ARM::DPRRegClass; 1103 Cost = 4; 1104 break; 1105 case MVT::v8i64: 1106 RRC = &ARM::DPRRegClass; 1107 Cost = 8; 1108 break; 1109 } 1110 return std::make_pair(RRC, Cost); 1111 } 1112 1113 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1114 switch ((ARMISD::NodeType)Opcode) { 1115 case ARMISD::FIRST_NUMBER: break; 1116 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1117 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1118 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1119 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1120 case ARMISD::CALL: return "ARMISD::CALL"; 1121 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1122 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1123 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1124 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1125 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1126 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1127 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1128 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1129 case ARMISD::CMP: return "ARMISD::CMP"; 1130 case ARMISD::CMN: return "ARMISD::CMN"; 1131 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1132 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1133 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1134 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1135 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1136 1137 case ARMISD::CMOV: return "ARMISD::CMOV"; 1138 1139 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1140 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1141 case ARMISD::RRX: return "ARMISD::RRX"; 1142 1143 case ARMISD::ADDC: return "ARMISD::ADDC"; 1144 case ARMISD::ADDE: return "ARMISD::ADDE"; 1145 case ARMISD::SUBC: return "ARMISD::SUBC"; 1146 case ARMISD::SUBE: return "ARMISD::SUBE"; 1147 1148 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1149 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1150 1151 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1152 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1153 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1154 1155 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1156 1157 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1158 1159 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1160 1161 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1162 1163 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1164 1165 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1166 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1167 1168 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1169 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1170 case ARMISD::VCGE: return "ARMISD::VCGE"; 1171 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1172 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1173 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1174 case ARMISD::VCGT: return "ARMISD::VCGT"; 1175 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1176 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1177 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1178 case ARMISD::VTST: return "ARMISD::VTST"; 1179 1180 case ARMISD::VSHL: return "ARMISD::VSHL"; 1181 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1182 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1183 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1184 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1185 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1186 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1187 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1188 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1189 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1190 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1191 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1192 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1193 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1194 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1195 case ARMISD::VSLI: return "ARMISD::VSLI"; 1196 case ARMISD::VSRI: return "ARMISD::VSRI"; 1197 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1198 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1199 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1200 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1201 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1202 case ARMISD::VDUP: return "ARMISD::VDUP"; 1203 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1204 case ARMISD::VEXT: return "ARMISD::VEXT"; 1205 case ARMISD::VREV64: return "ARMISD::VREV64"; 1206 case ARMISD::VREV32: return "ARMISD::VREV32"; 1207 case ARMISD::VREV16: return "ARMISD::VREV16"; 1208 case ARMISD::VZIP: return "ARMISD::VZIP"; 1209 case ARMISD::VUZP: return "ARMISD::VUZP"; 1210 case ARMISD::VTRN: return "ARMISD::VTRN"; 1211 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1212 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1213 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1214 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1215 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1216 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1217 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1218 case ARMISD::BFI: return "ARMISD::BFI"; 1219 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1220 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1221 case ARMISD::VBSL: return "ARMISD::VBSL"; 1222 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1223 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1224 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1225 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1226 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1227 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1228 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1229 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1230 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1231 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1232 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1233 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1234 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1235 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1236 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1237 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1238 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1239 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1240 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1241 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1242 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1243 } 1244 return nullptr; 1245 } 1246 1247 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1248 EVT VT) const { 1249 if (!VT.isVector()) 1250 return getPointerTy(DL); 1251 return VT.changeVectorElementTypeToInteger(); 1252 } 1253 1254 /// getRegClassFor - Return the register class that should be used for the 1255 /// specified value type. 1256 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1257 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1258 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1259 // load / store 4 to 8 consecutive D registers. 1260 if (Subtarget->hasNEON()) { 1261 if (VT == MVT::v4i64) 1262 return &ARM::QQPRRegClass; 1263 if (VT == MVT::v8i64) 1264 return &ARM::QQQQPRRegClass; 1265 } 1266 return TargetLowering::getRegClassFor(VT); 1267 } 1268 1269 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1270 // source/dest is aligned and the copy size is large enough. We therefore want 1271 // to align such objects passed to memory intrinsics. 1272 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1273 unsigned &PrefAlign) const { 1274 if (!isa<MemIntrinsic>(CI)) 1275 return false; 1276 MinSize = 8; 1277 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1278 // cycle faster than 4-byte aligned LDM. 1279 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1280 return true; 1281 } 1282 1283 // Create a fast isel object. 1284 FastISel * 1285 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1286 const TargetLibraryInfo *libInfo) const { 1287 return ARM::createFastISel(funcInfo, libInfo); 1288 } 1289 1290 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1291 unsigned NumVals = N->getNumValues(); 1292 if (!NumVals) 1293 return Sched::RegPressure; 1294 1295 for (unsigned i = 0; i != NumVals; ++i) { 1296 EVT VT = N->getValueType(i); 1297 if (VT == MVT::Glue || VT == MVT::Other) 1298 continue; 1299 if (VT.isFloatingPoint() || VT.isVector()) 1300 return Sched::ILP; 1301 } 1302 1303 if (!N->isMachineOpcode()) 1304 return Sched::RegPressure; 1305 1306 // Load are scheduled for latency even if there instruction itinerary 1307 // is not available. 1308 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1309 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1310 1311 if (MCID.getNumDefs() == 0) 1312 return Sched::RegPressure; 1313 if (!Itins->isEmpty() && 1314 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1315 return Sched::ILP; 1316 1317 return Sched::RegPressure; 1318 } 1319 1320 //===----------------------------------------------------------------------===// 1321 // Lowering Code 1322 //===----------------------------------------------------------------------===// 1323 1324 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1325 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1326 switch (CC) { 1327 default: llvm_unreachable("Unknown condition code!"); 1328 case ISD::SETNE: return ARMCC::NE; 1329 case ISD::SETEQ: return ARMCC::EQ; 1330 case ISD::SETGT: return ARMCC::GT; 1331 case ISD::SETGE: return ARMCC::GE; 1332 case ISD::SETLT: return ARMCC::LT; 1333 case ISD::SETLE: return ARMCC::LE; 1334 case ISD::SETUGT: return ARMCC::HI; 1335 case ISD::SETUGE: return ARMCC::HS; 1336 case ISD::SETULT: return ARMCC::LO; 1337 case ISD::SETULE: return ARMCC::LS; 1338 } 1339 } 1340 1341 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1342 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1343 ARMCC::CondCodes &CondCode2) { 1344 CondCode2 = ARMCC::AL; 1345 switch (CC) { 1346 default: llvm_unreachable("Unknown FP condition!"); 1347 case ISD::SETEQ: 1348 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1349 case ISD::SETGT: 1350 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1351 case ISD::SETGE: 1352 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1353 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1354 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1355 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1356 case ISD::SETO: CondCode = ARMCC::VC; break; 1357 case ISD::SETUO: CondCode = ARMCC::VS; break; 1358 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1359 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1360 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1361 case ISD::SETLT: 1362 case ISD::SETULT: CondCode = ARMCC::LT; break; 1363 case ISD::SETLE: 1364 case ISD::SETULE: CondCode = ARMCC::LE; break; 1365 case ISD::SETNE: 1366 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1367 } 1368 } 1369 1370 //===----------------------------------------------------------------------===// 1371 // Calling Convention Implementation 1372 //===----------------------------------------------------------------------===// 1373 1374 #include "ARMGenCallingConv.inc" 1375 1376 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1377 /// account presence of floating point hardware and calling convention 1378 /// limitations, such as support for variadic functions. 1379 CallingConv::ID 1380 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1381 bool isVarArg) const { 1382 switch (CC) { 1383 default: 1384 llvm_unreachable("Unsupported calling convention"); 1385 case CallingConv::ARM_AAPCS: 1386 case CallingConv::ARM_APCS: 1387 case CallingConv::GHC: 1388 return CC; 1389 case CallingConv::PreserveMost: 1390 return CallingConv::PreserveMost; 1391 case CallingConv::ARM_AAPCS_VFP: 1392 case CallingConv::Swift: 1393 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1394 case CallingConv::C: 1395 if (!Subtarget->isAAPCS_ABI()) 1396 return CallingConv::ARM_APCS; 1397 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1398 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1399 !isVarArg) 1400 return CallingConv::ARM_AAPCS_VFP; 1401 else 1402 return CallingConv::ARM_AAPCS; 1403 case CallingConv::Fast: 1404 case CallingConv::CXX_FAST_TLS: 1405 if (!Subtarget->isAAPCS_ABI()) { 1406 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1407 return CallingConv::Fast; 1408 return CallingConv::ARM_APCS; 1409 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1410 return CallingConv::ARM_AAPCS_VFP; 1411 else 1412 return CallingConv::ARM_AAPCS; 1413 } 1414 } 1415 1416 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1417 /// CallingConvention. 1418 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1419 bool Return, 1420 bool isVarArg) const { 1421 switch (getEffectiveCallingConv(CC, isVarArg)) { 1422 default: 1423 llvm_unreachable("Unsupported calling convention"); 1424 case CallingConv::ARM_APCS: 1425 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1426 case CallingConv::ARM_AAPCS: 1427 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1428 case CallingConv::ARM_AAPCS_VFP: 1429 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1430 case CallingConv::Fast: 1431 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1432 case CallingConv::GHC: 1433 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1434 case CallingConv::PreserveMost: 1435 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1436 } 1437 } 1438 1439 /// LowerCallResult - Lower the result values of a call into the 1440 /// appropriate copies out of appropriate physical registers. 1441 SDValue 1442 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1443 CallingConv::ID CallConv, bool isVarArg, 1444 const SmallVectorImpl<ISD::InputArg> &Ins, 1445 SDLoc dl, SelectionDAG &DAG, 1446 SmallVectorImpl<SDValue> &InVals, 1447 bool isThisReturn, SDValue ThisVal) const { 1448 1449 // Assign locations to each value returned by this call. 1450 SmallVector<CCValAssign, 16> RVLocs; 1451 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1452 *DAG.getContext(), Call); 1453 CCInfo.AnalyzeCallResult(Ins, 1454 CCAssignFnForNode(CallConv, /* Return*/ true, 1455 isVarArg)); 1456 1457 // Copy all of the result registers out of their specified physreg. 1458 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1459 CCValAssign VA = RVLocs[i]; 1460 1461 // Pass 'this' value directly from the argument to return value, to avoid 1462 // reg unit interference 1463 if (i == 0 && isThisReturn) { 1464 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1465 "unexpected return calling convention register assignment"); 1466 InVals.push_back(ThisVal); 1467 continue; 1468 } 1469 1470 SDValue Val; 1471 if (VA.needsCustom()) { 1472 // Handle f64 or half of a v2f64. 1473 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1474 InFlag); 1475 Chain = Lo.getValue(1); 1476 InFlag = Lo.getValue(2); 1477 VA = RVLocs[++i]; // skip ahead to next loc 1478 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1479 InFlag); 1480 Chain = Hi.getValue(1); 1481 InFlag = Hi.getValue(2); 1482 if (!Subtarget->isLittle()) 1483 std::swap (Lo, Hi); 1484 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1485 1486 if (VA.getLocVT() == MVT::v2f64) { 1487 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1488 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1489 DAG.getConstant(0, dl, MVT::i32)); 1490 1491 VA = RVLocs[++i]; // skip ahead to next loc 1492 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1493 Chain = Lo.getValue(1); 1494 InFlag = Lo.getValue(2); 1495 VA = RVLocs[++i]; // skip ahead to next loc 1496 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1497 Chain = Hi.getValue(1); 1498 InFlag = Hi.getValue(2); 1499 if (!Subtarget->isLittle()) 1500 std::swap (Lo, Hi); 1501 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1502 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1503 DAG.getConstant(1, dl, MVT::i32)); 1504 } 1505 } else { 1506 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1507 InFlag); 1508 Chain = Val.getValue(1); 1509 InFlag = Val.getValue(2); 1510 } 1511 1512 switch (VA.getLocInfo()) { 1513 default: llvm_unreachable("Unknown loc info!"); 1514 case CCValAssign::Full: break; 1515 case CCValAssign::BCvt: 1516 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1517 break; 1518 } 1519 1520 InVals.push_back(Val); 1521 } 1522 1523 return Chain; 1524 } 1525 1526 /// LowerMemOpCallTo - Store the argument to the stack. 1527 SDValue 1528 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1529 SDValue StackPtr, SDValue Arg, 1530 SDLoc dl, SelectionDAG &DAG, 1531 const CCValAssign &VA, 1532 ISD::ArgFlagsTy Flags) const { 1533 unsigned LocMemOffset = VA.getLocMemOffset(); 1534 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1535 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1536 StackPtr, PtrOff); 1537 return DAG.getStore( 1538 Chain, dl, Arg, PtrOff, 1539 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset), 1540 false, false, 0); 1541 } 1542 1543 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1544 SDValue Chain, SDValue &Arg, 1545 RegsToPassVector &RegsToPass, 1546 CCValAssign &VA, CCValAssign &NextVA, 1547 SDValue &StackPtr, 1548 SmallVectorImpl<SDValue> &MemOpChains, 1549 ISD::ArgFlagsTy Flags) const { 1550 1551 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1552 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1553 unsigned id = Subtarget->isLittle() ? 0 : 1; 1554 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1555 1556 if (NextVA.isRegLoc()) 1557 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1558 else { 1559 assert(NextVA.isMemLoc()); 1560 if (!StackPtr.getNode()) 1561 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1562 getPointerTy(DAG.getDataLayout())); 1563 1564 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1565 dl, DAG, NextVA, 1566 Flags)); 1567 } 1568 } 1569 1570 /// LowerCall - Lowering a call into a callseq_start <- 1571 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1572 /// nodes. 1573 SDValue 1574 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1575 SmallVectorImpl<SDValue> &InVals) const { 1576 SelectionDAG &DAG = CLI.DAG; 1577 SDLoc &dl = CLI.DL; 1578 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1579 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1580 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1581 SDValue Chain = CLI.Chain; 1582 SDValue Callee = CLI.Callee; 1583 bool &isTailCall = CLI.IsTailCall; 1584 CallingConv::ID CallConv = CLI.CallConv; 1585 bool doesNotRet = CLI.DoesNotReturn; 1586 bool isVarArg = CLI.IsVarArg; 1587 1588 MachineFunction &MF = DAG.getMachineFunction(); 1589 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1590 bool isThisReturn = false; 1591 bool isSibCall = false; 1592 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1593 1594 // Disable tail calls if they're not supported. 1595 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1596 isTailCall = false; 1597 1598 if (isTailCall) { 1599 // Check if it's really possible to do a tail call. 1600 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1601 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1602 Outs, OutVals, Ins, DAG); 1603 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1604 report_fatal_error("failed to perform tail call elimination on a call " 1605 "site marked musttail"); 1606 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1607 // detected sibcalls. 1608 if (isTailCall) { 1609 ++NumTailCalls; 1610 isSibCall = true; 1611 } 1612 } 1613 1614 // Analyze operands of the call, assigning locations to each operand. 1615 SmallVector<CCValAssign, 16> ArgLocs; 1616 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1617 *DAG.getContext(), Call); 1618 CCInfo.AnalyzeCallOperands(Outs, 1619 CCAssignFnForNode(CallConv, /* Return*/ false, 1620 isVarArg)); 1621 1622 // Get a count of how many bytes are to be pushed on the stack. 1623 unsigned NumBytes = CCInfo.getNextStackOffset(); 1624 1625 // For tail calls, memory operands are available in our caller's stack. 1626 if (isSibCall) 1627 NumBytes = 0; 1628 1629 // Adjust the stack pointer for the new arguments... 1630 // These operations are automatically eliminated by the prolog/epilog pass 1631 if (!isSibCall) 1632 Chain = DAG.getCALLSEQ_START(Chain, 1633 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1634 1635 SDValue StackPtr = 1636 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1637 1638 RegsToPassVector RegsToPass; 1639 SmallVector<SDValue, 8> MemOpChains; 1640 1641 // Walk the register/memloc assignments, inserting copies/loads. In the case 1642 // of tail call optimization, arguments are handled later. 1643 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1644 i != e; 1645 ++i, ++realArgIdx) { 1646 CCValAssign &VA = ArgLocs[i]; 1647 SDValue Arg = OutVals[realArgIdx]; 1648 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1649 bool isByVal = Flags.isByVal(); 1650 1651 // Promote the value if needed. 1652 switch (VA.getLocInfo()) { 1653 default: llvm_unreachable("Unknown loc info!"); 1654 case CCValAssign::Full: break; 1655 case CCValAssign::SExt: 1656 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1657 break; 1658 case CCValAssign::ZExt: 1659 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1660 break; 1661 case CCValAssign::AExt: 1662 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1663 break; 1664 case CCValAssign::BCvt: 1665 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1666 break; 1667 } 1668 1669 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1670 if (VA.needsCustom()) { 1671 if (VA.getLocVT() == MVT::v2f64) { 1672 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1673 DAG.getConstant(0, dl, MVT::i32)); 1674 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1675 DAG.getConstant(1, dl, MVT::i32)); 1676 1677 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1678 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1679 1680 VA = ArgLocs[++i]; // skip ahead to next loc 1681 if (VA.isRegLoc()) { 1682 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1683 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1684 } else { 1685 assert(VA.isMemLoc()); 1686 1687 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1688 dl, DAG, VA, Flags)); 1689 } 1690 } else { 1691 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1692 StackPtr, MemOpChains, Flags); 1693 } 1694 } else if (VA.isRegLoc()) { 1695 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1696 assert(VA.getLocVT() == MVT::i32 && 1697 "unexpected calling convention register assignment"); 1698 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1699 "unexpected use of 'returned'"); 1700 isThisReturn = true; 1701 } 1702 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1703 } else if (isByVal) { 1704 assert(VA.isMemLoc()); 1705 unsigned offset = 0; 1706 1707 // True if this byval aggregate will be split between registers 1708 // and memory. 1709 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1710 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1711 1712 if (CurByValIdx < ByValArgsCount) { 1713 1714 unsigned RegBegin, RegEnd; 1715 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1716 1717 EVT PtrVT = 1718 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1719 unsigned int i, j; 1720 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1721 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1722 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1723 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1724 MachinePointerInfo(), 1725 false, false, false, 1726 DAG.InferPtrAlignment(AddArg)); 1727 MemOpChains.push_back(Load.getValue(1)); 1728 RegsToPass.push_back(std::make_pair(j, Load)); 1729 } 1730 1731 // If parameter size outsides register area, "offset" value 1732 // helps us to calculate stack slot for remained part properly. 1733 offset = RegEnd - RegBegin; 1734 1735 CCInfo.nextInRegsParam(); 1736 } 1737 1738 if (Flags.getByValSize() > 4*offset) { 1739 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1740 unsigned LocMemOffset = VA.getLocMemOffset(); 1741 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1742 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1743 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1744 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1745 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1746 MVT::i32); 1747 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1748 MVT::i32); 1749 1750 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1751 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1752 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1753 Ops)); 1754 } 1755 } else if (!isSibCall) { 1756 assert(VA.isMemLoc()); 1757 1758 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1759 dl, DAG, VA, Flags)); 1760 } 1761 } 1762 1763 if (!MemOpChains.empty()) 1764 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1765 1766 // Build a sequence of copy-to-reg nodes chained together with token chain 1767 // and flag operands which copy the outgoing args into the appropriate regs. 1768 SDValue InFlag; 1769 // Tail call byval lowering might overwrite argument registers so in case of 1770 // tail call optimization the copies to registers are lowered later. 1771 if (!isTailCall) 1772 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1773 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1774 RegsToPass[i].second, InFlag); 1775 InFlag = Chain.getValue(1); 1776 } 1777 1778 // For tail calls lower the arguments to the 'real' stack slot. 1779 if (isTailCall) { 1780 // Force all the incoming stack arguments to be loaded from the stack 1781 // before any new outgoing arguments are stored to the stack, because the 1782 // outgoing stack slots may alias the incoming argument stack slots, and 1783 // the alias isn't otherwise explicit. This is slightly more conservative 1784 // than necessary, because it means that each store effectively depends 1785 // on every argument instead of just those arguments it would clobber. 1786 1787 // Do not flag preceding copytoreg stuff together with the following stuff. 1788 InFlag = SDValue(); 1789 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1790 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1791 RegsToPass[i].second, InFlag); 1792 InFlag = Chain.getValue(1); 1793 } 1794 InFlag = SDValue(); 1795 } 1796 1797 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1798 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1799 // node so that legalize doesn't hack it. 1800 bool isDirect = false; 1801 bool isARMFunc = false; 1802 bool isLocalARMFunc = false; 1803 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1804 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1805 1806 if (Subtarget->genLongCalls()) { 1807 assert((Subtarget->isTargetWindows() || 1808 getTargetMachine().getRelocationModel() == Reloc::Static) && 1809 "long-calls with non-static relocation model!"); 1810 // Handle a global address or an external symbol. If it's not one of 1811 // those, the target's already in a register, so we don't need to do 1812 // anything extra. 1813 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1814 const GlobalValue *GV = G->getGlobal(); 1815 // Create a constant pool entry for the callee address 1816 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1817 ARMConstantPoolValue *CPV = 1818 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1819 1820 // Get the address of the callee into a register 1821 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1822 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1823 Callee = DAG.getLoad( 1824 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1825 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1826 false, false, 0); 1827 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1828 const char *Sym = S->getSymbol(); 1829 1830 // Create a constant pool entry for the callee address 1831 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1832 ARMConstantPoolValue *CPV = 1833 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1834 ARMPCLabelIndex, 0); 1835 // Get the address of the callee into a register 1836 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1837 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1838 Callee = DAG.getLoad( 1839 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1840 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1841 false, false, 0); 1842 } 1843 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1844 const GlobalValue *GV = G->getGlobal(); 1845 isDirect = true; 1846 bool isDef = GV->isStrongDefinitionForLinker(); 1847 const TargetMachine &TM = getTargetMachine(); 1848 Reloc::Model RM = TM.getRelocationModel(); 1849 const Triple &TargetTriple = TM.getTargetTriple(); 1850 bool isStub = 1851 !shouldAssumeDSOLocal(RM, TargetTriple, *GV->getParent(), GV) && 1852 Subtarget->isTargetMachO(); 1853 1854 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1855 // ARM call to a local ARM function is predicable. 1856 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1857 // tBX takes a register source operand. 1858 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1859 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1860 Callee = DAG.getNode( 1861 ARMISD::WrapperPIC, dl, PtrVt, 1862 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1863 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1864 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1865 false, false, true, 0); 1866 } else if (Subtarget->isTargetCOFF()) { 1867 assert(Subtarget->isTargetWindows() && 1868 "Windows is the only supported COFF target"); 1869 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1870 ? ARMII::MO_DLLIMPORT 1871 : ARMII::MO_NO_FLAG; 1872 Callee = 1873 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags); 1874 if (GV->hasDLLImportStorageClass()) 1875 Callee = 1876 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1877 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1878 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1879 false, false, false, 0); 1880 } else { 1881 // On ELF targets for PIC code, direct calls should go through the PLT 1882 unsigned OpFlags = 0; 1883 if (Subtarget->isTargetELF() && 1884 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1885 OpFlags = ARMII::MO_PLT; 1886 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags); 1887 } 1888 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1889 isDirect = true; 1890 bool isStub = Subtarget->isTargetMachO() && 1891 getTargetMachine().getRelocationModel() != Reloc::Static; 1892 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1893 // tBX takes a register source operand. 1894 const char *Sym = S->getSymbol(); 1895 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1896 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1897 ARMConstantPoolValue *CPV = 1898 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1899 ARMPCLabelIndex, 4); 1900 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1901 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1902 Callee = DAG.getLoad( 1903 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1904 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1905 false, false, 0); 1906 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1907 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1908 } else { 1909 unsigned OpFlags = 0; 1910 // On ELF targets for PIC code, direct calls should go through the PLT 1911 if (Subtarget->isTargetELF() && 1912 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1913 OpFlags = ARMII::MO_PLT; 1914 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags); 1915 } 1916 } 1917 1918 // FIXME: handle tail calls differently. 1919 unsigned CallOpc; 1920 if (Subtarget->isThumb()) { 1921 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1922 CallOpc = ARMISD::CALL_NOLINK; 1923 else 1924 CallOpc = ARMISD::CALL; 1925 } else { 1926 if (!isDirect && !Subtarget->hasV5TOps()) 1927 CallOpc = ARMISD::CALL_NOLINK; 1928 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1929 // Emit regular call when code size is the priority 1930 !MF.getFunction()->optForMinSize()) 1931 // "mov lr, pc; b _foo" to avoid confusing the RSP 1932 CallOpc = ARMISD::CALL_NOLINK; 1933 else 1934 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1935 } 1936 1937 std::vector<SDValue> Ops; 1938 Ops.push_back(Chain); 1939 Ops.push_back(Callee); 1940 1941 // Add argument registers to the end of the list so that they are known live 1942 // into the call. 1943 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1944 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1945 RegsToPass[i].second.getValueType())); 1946 1947 // Add a register mask operand representing the call-preserved registers. 1948 if (!isTailCall) { 1949 const uint32_t *Mask; 1950 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1951 if (isThisReturn) { 1952 // For 'this' returns, use the R0-preserving mask if applicable 1953 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1954 if (!Mask) { 1955 // Set isThisReturn to false if the calling convention is not one that 1956 // allows 'returned' to be modeled in this way, so LowerCallResult does 1957 // not try to pass 'this' straight through 1958 isThisReturn = false; 1959 Mask = ARI->getCallPreservedMask(MF, CallConv); 1960 } 1961 } else 1962 Mask = ARI->getCallPreservedMask(MF, CallConv); 1963 1964 assert(Mask && "Missing call preserved mask for calling convention"); 1965 Ops.push_back(DAG.getRegisterMask(Mask)); 1966 } 1967 1968 if (InFlag.getNode()) 1969 Ops.push_back(InFlag); 1970 1971 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1972 if (isTailCall) { 1973 MF.getFrameInfo()->setHasTailCall(); 1974 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1975 } 1976 1977 // Returns a chain and a flag for retval copy to use. 1978 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1979 InFlag = Chain.getValue(1); 1980 1981 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1982 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1983 if (!Ins.empty()) 1984 InFlag = Chain.getValue(1); 1985 1986 // Handle result values, copying them out of physregs into vregs that we 1987 // return. 1988 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1989 InVals, isThisReturn, 1990 isThisReturn ? OutVals[0] : SDValue()); 1991 } 1992 1993 /// HandleByVal - Every parameter *after* a byval parameter is passed 1994 /// on the stack. Remember the next parameter register to allocate, 1995 /// and then confiscate the rest of the parameter registers to insure 1996 /// this. 1997 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1998 unsigned Align) const { 1999 assert((State->getCallOrPrologue() == Prologue || 2000 State->getCallOrPrologue() == Call) && 2001 "unhandled ParmContext"); 2002 2003 // Byval (as with any stack) slots are always at least 4 byte aligned. 2004 Align = std::max(Align, 4U); 2005 2006 unsigned Reg = State->AllocateReg(GPRArgRegs); 2007 if (!Reg) 2008 return; 2009 2010 unsigned AlignInRegs = Align / 4; 2011 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2012 for (unsigned i = 0; i < Waste; ++i) 2013 Reg = State->AllocateReg(GPRArgRegs); 2014 2015 if (!Reg) 2016 return; 2017 2018 unsigned Excess = 4 * (ARM::R4 - Reg); 2019 2020 // Special case when NSAA != SP and parameter size greater than size of 2021 // all remained GPR regs. In that case we can't split parameter, we must 2022 // send it to stack. We also must set NCRN to R4, so waste all 2023 // remained registers. 2024 const unsigned NSAAOffset = State->getNextStackOffset(); 2025 if (NSAAOffset != 0 && Size > Excess) { 2026 while (State->AllocateReg(GPRArgRegs)) 2027 ; 2028 return; 2029 } 2030 2031 // First register for byval parameter is the first register that wasn't 2032 // allocated before this method call, so it would be "reg". 2033 // If parameter is small enough to be saved in range [reg, r4), then 2034 // the end (first after last) register would be reg + param-size-in-regs, 2035 // else parameter would be splitted between registers and stack, 2036 // end register would be r4 in this case. 2037 unsigned ByValRegBegin = Reg; 2038 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2039 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2040 // Note, first register is allocated in the beginning of function already, 2041 // allocate remained amount of registers we need. 2042 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2043 State->AllocateReg(GPRArgRegs); 2044 // A byval parameter that is split between registers and memory needs its 2045 // size truncated here. 2046 // In the case where the entire structure fits in registers, we set the 2047 // size in memory to zero. 2048 Size = std::max<int>(Size - Excess, 0); 2049 } 2050 2051 /// MatchingStackOffset - Return true if the given stack call argument is 2052 /// already available in the same position (relatively) of the caller's 2053 /// incoming argument stack. 2054 static 2055 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2056 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2057 const TargetInstrInfo *TII) { 2058 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2059 int FI = INT_MAX; 2060 if (Arg.getOpcode() == ISD::CopyFromReg) { 2061 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2062 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2063 return false; 2064 MachineInstr *Def = MRI->getVRegDef(VR); 2065 if (!Def) 2066 return false; 2067 if (!Flags.isByVal()) { 2068 if (!TII->isLoadFromStackSlot(Def, FI)) 2069 return false; 2070 } else { 2071 return false; 2072 } 2073 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2074 if (Flags.isByVal()) 2075 // ByVal argument is passed in as a pointer but it's now being 2076 // dereferenced. e.g. 2077 // define @foo(%struct.X* %A) { 2078 // tail call @bar(%struct.X* byval %A) 2079 // } 2080 return false; 2081 SDValue Ptr = Ld->getBasePtr(); 2082 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2083 if (!FINode) 2084 return false; 2085 FI = FINode->getIndex(); 2086 } else 2087 return false; 2088 2089 assert(FI != INT_MAX); 2090 if (!MFI->isFixedObjectIndex(FI)) 2091 return false; 2092 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2093 } 2094 2095 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2096 /// for tail call optimization. Targets which want to do tail call 2097 /// optimization should implement this function. 2098 bool 2099 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2100 CallingConv::ID CalleeCC, 2101 bool isVarArg, 2102 bool isCalleeStructRet, 2103 bool isCallerStructRet, 2104 const SmallVectorImpl<ISD::OutputArg> &Outs, 2105 const SmallVectorImpl<SDValue> &OutVals, 2106 const SmallVectorImpl<ISD::InputArg> &Ins, 2107 SelectionDAG& DAG) const { 2108 MachineFunction &MF = DAG.getMachineFunction(); 2109 const Function *CallerF = MF.getFunction(); 2110 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2111 2112 assert(Subtarget->supportsTailCall()); 2113 2114 // Look for obvious safe cases to perform tail call optimization that do not 2115 // require ABI changes. This is what gcc calls sibcall. 2116 2117 // Do not sibcall optimize vararg calls unless the call site is not passing 2118 // any arguments. 2119 if (isVarArg && !Outs.empty()) 2120 return false; 2121 2122 // Exception-handling functions need a special set of instructions to indicate 2123 // a return to the hardware. Tail-calling another function would probably 2124 // break this. 2125 if (CallerF->hasFnAttribute("interrupt")) 2126 return false; 2127 2128 // Also avoid sibcall optimization if either caller or callee uses struct 2129 // return semantics. 2130 if (isCalleeStructRet || isCallerStructRet) 2131 return false; 2132 2133 // Externally-defined functions with weak linkage should not be 2134 // tail-called on ARM when the OS does not support dynamic 2135 // pre-emption of symbols, as the AAELF spec requires normal calls 2136 // to undefined weak functions to be replaced with a NOP or jump to the 2137 // next instruction. The behaviour of branch instructions in this 2138 // situation (as used for tail calls) is implementation-defined, so we 2139 // cannot rely on the linker replacing the tail call with a return. 2140 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2141 const GlobalValue *GV = G->getGlobal(); 2142 const Triple &TT = getTargetMachine().getTargetTriple(); 2143 if (GV->hasExternalWeakLinkage() && 2144 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2145 return false; 2146 } 2147 2148 // Check that the call results are passed in the same way. 2149 LLVMContext &C = *DAG.getContext(); 2150 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2151 CCAssignFnForNode(CalleeCC, true, isVarArg), 2152 CCAssignFnForNode(CallerCC, true, isVarArg))) 2153 return false; 2154 // The callee has to preserve all registers the caller needs to preserve. 2155 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2156 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2157 if (CalleeCC != CallerCC) { 2158 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2159 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2160 return false; 2161 } 2162 2163 // If Caller's vararg or byval argument has been split between registers and 2164 // stack, do not perform tail call, since part of the argument is in caller's 2165 // local frame. 2166 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2167 if (AFI_Caller->getArgRegsSaveSize()) 2168 return false; 2169 2170 // If the callee takes no arguments then go on to check the results of the 2171 // call. 2172 if (!Outs.empty()) { 2173 // Check if stack adjustment is needed. For now, do not do this if any 2174 // argument is passed on the stack. 2175 SmallVector<CCValAssign, 16> ArgLocs; 2176 ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call); 2177 CCInfo.AnalyzeCallOperands(Outs, 2178 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2179 if (CCInfo.getNextStackOffset()) { 2180 // Check if the arguments are already laid out in the right way as 2181 // the caller's fixed stack objects. 2182 MachineFrameInfo *MFI = MF.getFrameInfo(); 2183 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2184 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2185 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2186 i != e; 2187 ++i, ++realArgIdx) { 2188 CCValAssign &VA = ArgLocs[i]; 2189 EVT RegVT = VA.getLocVT(); 2190 SDValue Arg = OutVals[realArgIdx]; 2191 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2192 if (VA.getLocInfo() == CCValAssign::Indirect) 2193 return false; 2194 if (VA.needsCustom()) { 2195 // f64 and vector types are split into multiple registers or 2196 // register/stack-slot combinations. The types will not match 2197 // the registers; give up on memory f64 refs until we figure 2198 // out what to do about this. 2199 if (!VA.isRegLoc()) 2200 return false; 2201 if (!ArgLocs[++i].isRegLoc()) 2202 return false; 2203 if (RegVT == MVT::v2f64) { 2204 if (!ArgLocs[++i].isRegLoc()) 2205 return false; 2206 if (!ArgLocs[++i].isRegLoc()) 2207 return false; 2208 } 2209 } else if (!VA.isRegLoc()) { 2210 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2211 MFI, MRI, TII)) 2212 return false; 2213 } 2214 } 2215 } 2216 2217 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2218 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2219 return false; 2220 } 2221 2222 return true; 2223 } 2224 2225 bool 2226 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2227 MachineFunction &MF, bool isVarArg, 2228 const SmallVectorImpl<ISD::OutputArg> &Outs, 2229 LLVMContext &Context) const { 2230 SmallVector<CCValAssign, 16> RVLocs; 2231 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2232 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2233 isVarArg)); 2234 } 2235 2236 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2237 SDLoc DL, SelectionDAG &DAG) { 2238 const MachineFunction &MF = DAG.getMachineFunction(); 2239 const Function *F = MF.getFunction(); 2240 2241 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2242 2243 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2244 // version of the "preferred return address". These offsets affect the return 2245 // instruction if this is a return from PL1 without hypervisor extensions. 2246 // IRQ/FIQ: +4 "subs pc, lr, #4" 2247 // SWI: 0 "subs pc, lr, #0" 2248 // ABORT: +4 "subs pc, lr, #4" 2249 // UNDEF: +4/+2 "subs pc, lr, #0" 2250 // UNDEF varies depending on where the exception came from ARM or Thumb 2251 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2252 2253 int64_t LROffset; 2254 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2255 IntKind == "ABORT") 2256 LROffset = 4; 2257 else if (IntKind == "SWI" || IntKind == "UNDEF") 2258 LROffset = 0; 2259 else 2260 report_fatal_error("Unsupported interrupt attribute. If present, value " 2261 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2262 2263 RetOps.insert(RetOps.begin() + 1, 2264 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2265 2266 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2267 } 2268 2269 SDValue 2270 ARMTargetLowering::LowerReturn(SDValue Chain, 2271 CallingConv::ID CallConv, bool isVarArg, 2272 const SmallVectorImpl<ISD::OutputArg> &Outs, 2273 const SmallVectorImpl<SDValue> &OutVals, 2274 SDLoc dl, SelectionDAG &DAG) const { 2275 2276 // CCValAssign - represent the assignment of the return value to a location. 2277 SmallVector<CCValAssign, 16> RVLocs; 2278 2279 // CCState - Info about the registers and stack slots. 2280 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2281 *DAG.getContext(), Call); 2282 2283 // Analyze outgoing return values. 2284 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2285 isVarArg)); 2286 2287 SDValue Flag; 2288 SmallVector<SDValue, 4> RetOps; 2289 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2290 bool isLittleEndian = Subtarget->isLittle(); 2291 2292 MachineFunction &MF = DAG.getMachineFunction(); 2293 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2294 AFI->setReturnRegsCount(RVLocs.size()); 2295 2296 // Copy the result values into the output registers. 2297 for (unsigned i = 0, realRVLocIdx = 0; 2298 i != RVLocs.size(); 2299 ++i, ++realRVLocIdx) { 2300 CCValAssign &VA = RVLocs[i]; 2301 assert(VA.isRegLoc() && "Can only return in registers!"); 2302 2303 SDValue Arg = OutVals[realRVLocIdx]; 2304 2305 switch (VA.getLocInfo()) { 2306 default: llvm_unreachable("Unknown loc info!"); 2307 case CCValAssign::Full: break; 2308 case CCValAssign::BCvt: 2309 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2310 break; 2311 } 2312 2313 if (VA.needsCustom()) { 2314 if (VA.getLocVT() == MVT::v2f64) { 2315 // Extract the first half and return it in two registers. 2316 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2317 DAG.getConstant(0, dl, MVT::i32)); 2318 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2319 DAG.getVTList(MVT::i32, MVT::i32), Half); 2320 2321 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2322 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2323 Flag); 2324 Flag = Chain.getValue(1); 2325 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2326 VA = RVLocs[++i]; // skip ahead to next loc 2327 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2328 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2329 Flag); 2330 Flag = Chain.getValue(1); 2331 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2332 VA = RVLocs[++i]; // skip ahead to next loc 2333 2334 // Extract the 2nd half and fall through to handle it as an f64 value. 2335 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2336 DAG.getConstant(1, dl, MVT::i32)); 2337 } 2338 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2339 // available. 2340 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2341 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2342 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2343 fmrrd.getValue(isLittleEndian ? 0 : 1), 2344 Flag); 2345 Flag = Chain.getValue(1); 2346 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2347 VA = RVLocs[++i]; // skip ahead to next loc 2348 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2349 fmrrd.getValue(isLittleEndian ? 1 : 0), 2350 Flag); 2351 } else 2352 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2353 2354 // Guarantee that all emitted copies are 2355 // stuck together, avoiding something bad. 2356 Flag = Chain.getValue(1); 2357 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2358 } 2359 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2360 const MCPhysReg *I = 2361 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2362 if (I) { 2363 for (; *I; ++I) { 2364 if (ARM::GPRRegClass.contains(*I)) 2365 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2366 else if (ARM::DPRRegClass.contains(*I)) 2367 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2368 else 2369 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2370 } 2371 } 2372 2373 // Update chain and glue. 2374 RetOps[0] = Chain; 2375 if (Flag.getNode()) 2376 RetOps.push_back(Flag); 2377 2378 // CPUs which aren't M-class use a special sequence to return from 2379 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2380 // though we use "subs pc, lr, #N"). 2381 // 2382 // M-class CPUs actually use a normal return sequence with a special 2383 // (hardware-provided) value in LR, so the normal code path works. 2384 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2385 !Subtarget->isMClass()) { 2386 if (Subtarget->isThumb1Only()) 2387 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2388 return LowerInterruptReturn(RetOps, dl, DAG); 2389 } 2390 2391 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2392 } 2393 2394 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2395 if (N->getNumValues() != 1) 2396 return false; 2397 if (!N->hasNUsesOfValue(1, 0)) 2398 return false; 2399 2400 SDValue TCChain = Chain; 2401 SDNode *Copy = *N->use_begin(); 2402 if (Copy->getOpcode() == ISD::CopyToReg) { 2403 // If the copy has a glue operand, we conservatively assume it isn't safe to 2404 // perform a tail call. 2405 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2406 return false; 2407 TCChain = Copy->getOperand(0); 2408 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2409 SDNode *VMov = Copy; 2410 // f64 returned in a pair of GPRs. 2411 SmallPtrSet<SDNode*, 2> Copies; 2412 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2413 UI != UE; ++UI) { 2414 if (UI->getOpcode() != ISD::CopyToReg) 2415 return false; 2416 Copies.insert(*UI); 2417 } 2418 if (Copies.size() > 2) 2419 return false; 2420 2421 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2422 UI != UE; ++UI) { 2423 SDValue UseChain = UI->getOperand(0); 2424 if (Copies.count(UseChain.getNode())) 2425 // Second CopyToReg 2426 Copy = *UI; 2427 else { 2428 // We are at the top of this chain. 2429 // If the copy has a glue operand, we conservatively assume it 2430 // isn't safe to perform a tail call. 2431 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2432 return false; 2433 // First CopyToReg 2434 TCChain = UseChain; 2435 } 2436 } 2437 } else if (Copy->getOpcode() == ISD::BITCAST) { 2438 // f32 returned in a single GPR. 2439 if (!Copy->hasOneUse()) 2440 return false; 2441 Copy = *Copy->use_begin(); 2442 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2443 return false; 2444 // If the copy has a glue operand, we conservatively assume it isn't safe to 2445 // perform a tail call. 2446 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2447 return false; 2448 TCChain = Copy->getOperand(0); 2449 } else { 2450 return false; 2451 } 2452 2453 bool HasRet = false; 2454 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2455 UI != UE; ++UI) { 2456 if (UI->getOpcode() != ARMISD::RET_FLAG && 2457 UI->getOpcode() != ARMISD::INTRET_FLAG) 2458 return false; 2459 HasRet = true; 2460 } 2461 2462 if (!HasRet) 2463 return false; 2464 2465 Chain = TCChain; 2466 return true; 2467 } 2468 2469 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2470 if (!Subtarget->supportsTailCall()) 2471 return false; 2472 2473 auto Attr = 2474 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2475 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2476 return false; 2477 2478 return true; 2479 } 2480 2481 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2482 // and pass the lower and high parts through. 2483 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2484 SDLoc DL(Op); 2485 SDValue WriteValue = Op->getOperand(2); 2486 2487 // This function is only supposed to be called for i64 type argument. 2488 assert(WriteValue.getValueType() == MVT::i64 2489 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2490 2491 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2492 DAG.getConstant(0, DL, MVT::i32)); 2493 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2494 DAG.getConstant(1, DL, MVT::i32)); 2495 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2496 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2497 } 2498 2499 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2500 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2501 // one of the above mentioned nodes. It has to be wrapped because otherwise 2502 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2503 // be used to form addressing mode. These wrapped nodes will be selected 2504 // into MOVi. 2505 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2506 EVT PtrVT = Op.getValueType(); 2507 // FIXME there is no actual debug info here 2508 SDLoc dl(Op); 2509 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2510 SDValue Res; 2511 if (CP->isMachineConstantPoolEntry()) 2512 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2513 CP->getAlignment()); 2514 else 2515 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2516 CP->getAlignment()); 2517 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2518 } 2519 2520 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2521 return MachineJumpTableInfo::EK_Inline; 2522 } 2523 2524 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2525 SelectionDAG &DAG) const { 2526 MachineFunction &MF = DAG.getMachineFunction(); 2527 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2528 unsigned ARMPCLabelIndex = 0; 2529 SDLoc DL(Op); 2530 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2531 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2532 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2533 SDValue CPAddr; 2534 if (RelocM == Reloc::Static) { 2535 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2536 } else { 2537 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2538 ARMPCLabelIndex = AFI->createPICLabelUId(); 2539 ARMConstantPoolValue *CPV = 2540 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2541 ARMCP::CPBlockAddress, PCAdj); 2542 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2543 } 2544 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2545 SDValue Result = 2546 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2547 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2548 false, false, false, 0); 2549 if (RelocM == Reloc::Static) 2550 return Result; 2551 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2552 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2553 } 2554 2555 /// \brief Convert a TLS address reference into the correct sequence of loads 2556 /// and calls to compute the variable's address for Darwin, and return an 2557 /// SDValue containing the final node. 2558 2559 /// Darwin only has one TLS scheme which must be capable of dealing with the 2560 /// fully general situation, in the worst case. This means: 2561 /// + "extern __thread" declaration. 2562 /// + Defined in a possibly unknown dynamic library. 2563 /// 2564 /// The general system is that each __thread variable has a [3 x i32] descriptor 2565 /// which contains information used by the runtime to calculate the address. The 2566 /// only part of this the compiler needs to know about is the first word, which 2567 /// contains a function pointer that must be called with the address of the 2568 /// entire descriptor in "r0". 2569 /// 2570 /// Since this descriptor may be in a different unit, in general access must 2571 /// proceed along the usual ARM rules. A common sequence to produce is: 2572 /// 2573 /// movw rT1, :lower16:_var$non_lazy_ptr 2574 /// movt rT1, :upper16:_var$non_lazy_ptr 2575 /// ldr r0, [rT1] 2576 /// ldr rT2, [r0] 2577 /// blx rT2 2578 /// [...address now in r0...] 2579 SDValue 2580 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2581 SelectionDAG &DAG) const { 2582 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2583 SDLoc DL(Op); 2584 2585 // First step is to get the address of the actua global symbol. This is where 2586 // the TLS descriptor lives. 2587 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2588 2589 // The first entry in the descriptor is a function pointer that we must call 2590 // to obtain the address of the variable. 2591 SDValue Chain = DAG.getEntryNode(); 2592 SDValue FuncTLVGet = 2593 DAG.getLoad(MVT::i32, DL, Chain, DescAddr, 2594 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2595 false, true, true, 4); 2596 Chain = FuncTLVGet.getValue(1); 2597 2598 MachineFunction &F = DAG.getMachineFunction(); 2599 MachineFrameInfo *MFI = F.getFrameInfo(); 2600 MFI->setAdjustsStack(true); 2601 2602 // TLS calls preserve all registers except those that absolutely must be 2603 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2604 // silly). 2605 auto TRI = 2606 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2607 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2608 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2609 2610 // Finally, we can make the call. This is just a degenerate version of a 2611 // normal AArch64 call node: r0 takes the address of the descriptor, and 2612 // returns the address of the variable in this thread. 2613 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2614 Chain = 2615 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2616 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2617 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2618 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2619 } 2620 2621 SDValue 2622 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2623 SelectionDAG &DAG) const { 2624 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2625 SDValue Chain = DAG.getEntryNode(); 2626 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2627 SDLoc DL(Op); 2628 2629 // Load the current TEB (thread environment block) 2630 SDValue Ops[] = {Chain, 2631 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2632 DAG.getConstant(15, DL, MVT::i32), 2633 DAG.getConstant(0, DL, MVT::i32), 2634 DAG.getConstant(13, DL, MVT::i32), 2635 DAG.getConstant(0, DL, MVT::i32), 2636 DAG.getConstant(2, DL, MVT::i32)}; 2637 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2638 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2639 2640 SDValue TEB = CurrentTEB.getValue(0); 2641 Chain = CurrentTEB.getValue(1); 2642 2643 // Load the ThreadLocalStoragePointer from the TEB 2644 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2645 SDValue TLSArray = 2646 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2647 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo(), 2648 false, false, false, 0); 2649 2650 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2651 // offset into the TLSArray. 2652 2653 // Load the TLS index from the C runtime 2654 SDValue TLSIndex = 2655 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2656 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2657 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo(), 2658 false, false, false, 0); 2659 2660 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2661 DAG.getConstant(2, DL, MVT::i32)); 2662 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2663 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2664 MachinePointerInfo(), false, false, false, 0); 2665 2666 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, 2667 LowerGlobalAddressWindows(Op, DAG)); 2668 } 2669 2670 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2671 SDValue 2672 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2673 SelectionDAG &DAG) const { 2674 SDLoc dl(GA); 2675 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2676 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2677 MachineFunction &MF = DAG.getMachineFunction(); 2678 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2679 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2680 ARMConstantPoolValue *CPV = 2681 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2682 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2683 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2684 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2685 Argument = 2686 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2687 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2688 false, false, false, 0); 2689 SDValue Chain = Argument.getValue(1); 2690 2691 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2692 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2693 2694 // call __tls_get_addr. 2695 ArgListTy Args; 2696 ArgListEntry Entry; 2697 Entry.Node = Argument; 2698 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2699 Args.push_back(Entry); 2700 2701 // FIXME: is there useful debug info available here? 2702 TargetLowering::CallLoweringInfo CLI(DAG); 2703 CLI.setDebugLoc(dl).setChain(Chain) 2704 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2705 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args), 2706 0); 2707 2708 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2709 return CallResult.first; 2710 } 2711 2712 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2713 // "local exec" model. 2714 SDValue 2715 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2716 SelectionDAG &DAG, 2717 TLSModel::Model model) const { 2718 const GlobalValue *GV = GA->getGlobal(); 2719 SDLoc dl(GA); 2720 SDValue Offset; 2721 SDValue Chain = DAG.getEntryNode(); 2722 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2723 // Get the Thread Pointer 2724 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2725 2726 if (model == TLSModel::InitialExec) { 2727 MachineFunction &MF = DAG.getMachineFunction(); 2728 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2729 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2730 // Initial exec model. 2731 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2732 ARMConstantPoolValue *CPV = 2733 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2734 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2735 true); 2736 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2737 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2738 Offset = DAG.getLoad( 2739 PtrVT, dl, Chain, Offset, 2740 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2741 false, false, 0); 2742 Chain = Offset.getValue(1); 2743 2744 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2745 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2746 2747 Offset = DAG.getLoad( 2748 PtrVT, dl, Chain, Offset, 2749 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2750 false, false, 0); 2751 } else { 2752 // local exec model 2753 assert(model == TLSModel::LocalExec); 2754 ARMConstantPoolValue *CPV = 2755 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2756 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2757 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2758 Offset = DAG.getLoad( 2759 PtrVT, dl, Chain, Offset, 2760 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2761 false, false, 0); 2762 } 2763 2764 // The address of the thread local variable is the add of the thread 2765 // pointer with the offset of the variable. 2766 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2767 } 2768 2769 SDValue 2770 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2771 if (Subtarget->isTargetDarwin()) 2772 return LowerGlobalTLSAddressDarwin(Op, DAG); 2773 2774 if (Subtarget->isTargetWindows()) 2775 return LowerGlobalTLSAddressWindows(Op, DAG); 2776 2777 // TODO: implement the "local dynamic" model 2778 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2779 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2780 if (DAG.getTarget().Options.EmulatedTLS) 2781 return LowerToTLSEmulatedModel(GA, DAG); 2782 2783 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2784 2785 switch (model) { 2786 case TLSModel::GeneralDynamic: 2787 case TLSModel::LocalDynamic: 2788 return LowerToTLSGeneralDynamicModel(GA, DAG); 2789 case TLSModel::InitialExec: 2790 case TLSModel::LocalExec: 2791 return LowerToTLSExecModels(GA, DAG, model); 2792 } 2793 llvm_unreachable("bogus TLS model"); 2794 } 2795 2796 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2797 SelectionDAG &DAG) const { 2798 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2799 SDLoc dl(Op); 2800 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2801 const TargetMachine &TM = getTargetMachine(); 2802 Reloc::Model RM = TM.getRelocationModel(); 2803 const Triple &TargetTriple = TM.getTargetTriple(); 2804 if (RM == Reloc::PIC_) { 2805 bool UseGOT_PREL = 2806 !shouldAssumeDSOLocal(RM, TargetTriple, *GV->getParent(), GV); 2807 2808 MachineFunction &MF = DAG.getMachineFunction(); 2809 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2810 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2811 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2812 SDLoc dl(Op); 2813 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2814 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2815 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2816 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2817 /*AddCurrentAddress=*/UseGOT_PREL); 2818 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2819 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2820 SDValue Result = DAG.getLoad( 2821 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2822 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2823 false, false, 0); 2824 SDValue Chain = Result.getValue(1); 2825 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2826 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2827 if (UseGOT_PREL) 2828 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2829 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2830 false, false, false, 0); 2831 return Result; 2832 } 2833 2834 // If we have T2 ops, we can materialize the address directly via movt/movw 2835 // pair. This is always cheaper. 2836 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2837 ++NumMovwMovt; 2838 // FIXME: Once remat is capable of dealing with instructions with register 2839 // operands, expand this into two nodes. 2840 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2841 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2842 } else { 2843 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2844 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2845 return DAG.getLoad( 2846 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2847 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2848 false, false, 0); 2849 } 2850 } 2851 2852 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2853 SelectionDAG &DAG) const { 2854 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2855 SDLoc dl(Op); 2856 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2857 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2858 2859 if (Subtarget->useMovt(DAG.getMachineFunction())) 2860 ++NumMovwMovt; 2861 2862 // FIXME: Once remat is capable of dealing with instructions with register 2863 // operands, expand this into multiple nodes 2864 unsigned Wrapper = 2865 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2866 2867 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2868 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2869 2870 if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) 2871 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2872 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2873 false, false, false, 0); 2874 return Result; 2875 } 2876 2877 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2878 SelectionDAG &DAG) const { 2879 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2880 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2881 "Windows on ARM expects to use movw/movt"); 2882 2883 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2884 const ARMII::TOF TargetFlags = 2885 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2886 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2887 SDValue Result; 2888 SDLoc DL(Op); 2889 2890 ++NumMovwMovt; 2891 2892 // FIXME: Once remat is capable of dealing with instructions with register 2893 // operands, expand this into two nodes. 2894 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2895 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2896 TargetFlags)); 2897 if (GV->hasDLLImportStorageClass()) 2898 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2899 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2900 false, false, false, 0); 2901 return Result; 2902 } 2903 2904 SDValue 2905 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2906 SDLoc dl(Op); 2907 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 2908 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2909 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2910 Op.getOperand(1), Val); 2911 } 2912 2913 SDValue 2914 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2915 SDLoc dl(Op); 2916 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2917 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 2918 } 2919 2920 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 2921 SelectionDAG &DAG) const { 2922 SDLoc dl(Op); 2923 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 2924 Op.getOperand(0)); 2925 } 2926 2927 SDValue 2928 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2929 const ARMSubtarget *Subtarget) const { 2930 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2931 SDLoc dl(Op); 2932 switch (IntNo) { 2933 default: return SDValue(); // Don't custom lower most intrinsics. 2934 case Intrinsic::arm_rbit: { 2935 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2936 "RBIT intrinsic must have i32 type!"); 2937 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 2938 } 2939 case Intrinsic::thread_pointer: { 2940 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2941 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2942 } 2943 case Intrinsic::eh_sjlj_lsda: { 2944 MachineFunction &MF = DAG.getMachineFunction(); 2945 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2946 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2947 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2948 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2949 SDValue CPAddr; 2950 unsigned PCAdj = (RelocM != Reloc::PIC_) 2951 ? 0 : (Subtarget->isThumb() ? 4 : 8); 2952 ARMConstantPoolValue *CPV = 2953 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2954 ARMCP::CPLSDA, PCAdj); 2955 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2956 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2957 SDValue Result = DAG.getLoad( 2958 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2959 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2960 false, false, 0); 2961 2962 if (RelocM == Reloc::PIC_) { 2963 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2964 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2965 } 2966 return Result; 2967 } 2968 case Intrinsic::arm_neon_vmulls: 2969 case Intrinsic::arm_neon_vmullu: { 2970 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2971 ? ARMISD::VMULLs : ARMISD::VMULLu; 2972 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2973 Op.getOperand(1), Op.getOperand(2)); 2974 } 2975 case Intrinsic::arm_neon_vminnm: 2976 case Intrinsic::arm_neon_vmaxnm: { 2977 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 2978 ? ISD::FMINNUM : ISD::FMAXNUM; 2979 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2980 Op.getOperand(1), Op.getOperand(2)); 2981 } 2982 case Intrinsic::arm_neon_vminu: 2983 case Intrinsic::arm_neon_vmaxu: { 2984 if (Op.getValueType().isFloatingPoint()) 2985 return SDValue(); 2986 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 2987 ? ISD::UMIN : ISD::UMAX; 2988 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2989 Op.getOperand(1), Op.getOperand(2)); 2990 } 2991 case Intrinsic::arm_neon_vmins: 2992 case Intrinsic::arm_neon_vmaxs: { 2993 // v{min,max}s is overloaded between signed integers and floats. 2994 if (!Op.getValueType().isFloatingPoint()) { 2995 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2996 ? ISD::SMIN : ISD::SMAX; 2997 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2998 Op.getOperand(1), Op.getOperand(2)); 2999 } 3000 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3001 ? ISD::FMINNAN : ISD::FMAXNAN; 3002 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3003 Op.getOperand(1), Op.getOperand(2)); 3004 } 3005 } 3006 } 3007 3008 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3009 const ARMSubtarget *Subtarget) { 3010 // FIXME: handle "fence singlethread" more efficiently. 3011 SDLoc dl(Op); 3012 if (!Subtarget->hasDataBarrier()) { 3013 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3014 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3015 // here. 3016 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3017 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3018 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3019 DAG.getConstant(0, dl, MVT::i32)); 3020 } 3021 3022 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3023 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3024 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3025 if (Subtarget->isMClass()) { 3026 // Only a full system barrier exists in the M-class architectures. 3027 Domain = ARM_MB::SY; 3028 } else if (Subtarget->isSwift() && Ord == AtomicOrdering::Release) { 3029 // Swift happens to implement ISHST barriers in a way that's compatible with 3030 // Release semantics but weaker than ISH so we'd be fools not to use 3031 // it. Beware: other processors probably don't! 3032 Domain = ARM_MB::ISHST; 3033 } 3034 3035 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3036 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3037 DAG.getConstant(Domain, dl, MVT::i32)); 3038 } 3039 3040 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3041 const ARMSubtarget *Subtarget) { 3042 // ARM pre v5TE and Thumb1 does not have preload instructions. 3043 if (!(Subtarget->isThumb2() || 3044 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3045 // Just preserve the chain. 3046 return Op.getOperand(0); 3047 3048 SDLoc dl(Op); 3049 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3050 if (!isRead && 3051 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3052 // ARMv7 with MP extension has PLDW. 3053 return Op.getOperand(0); 3054 3055 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3056 if (Subtarget->isThumb()) { 3057 // Invert the bits. 3058 isRead = ~isRead & 1; 3059 isData = ~isData & 1; 3060 } 3061 3062 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3063 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3064 DAG.getConstant(isData, dl, MVT::i32)); 3065 } 3066 3067 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3068 MachineFunction &MF = DAG.getMachineFunction(); 3069 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3070 3071 // vastart just stores the address of the VarArgsFrameIndex slot into the 3072 // memory location argument. 3073 SDLoc dl(Op); 3074 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3075 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3076 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3077 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3078 MachinePointerInfo(SV), false, false, 0); 3079 } 3080 3081 SDValue 3082 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA, 3083 SDValue &Root, SelectionDAG &DAG, 3084 SDLoc dl) const { 3085 MachineFunction &MF = DAG.getMachineFunction(); 3086 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3087 3088 const TargetRegisterClass *RC; 3089 if (AFI->isThumb1OnlyFunction()) 3090 RC = &ARM::tGPRRegClass; 3091 else 3092 RC = &ARM::GPRRegClass; 3093 3094 // Transform the arguments stored in physical registers into virtual ones. 3095 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3096 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3097 3098 SDValue ArgValue2; 3099 if (NextVA.isMemLoc()) { 3100 MachineFrameInfo *MFI = MF.getFrameInfo(); 3101 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3102 3103 // Create load node to retrieve arguments from the stack. 3104 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3105 ArgValue2 = DAG.getLoad( 3106 MVT::i32, dl, Root, FIN, 3107 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false, 3108 false, false, 0); 3109 } else { 3110 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3111 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3112 } 3113 if (!Subtarget->isLittle()) 3114 std::swap (ArgValue, ArgValue2); 3115 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3116 } 3117 3118 // The remaining GPRs hold either the beginning of variable-argument 3119 // data, or the beginning of an aggregate passed by value (usually 3120 // byval). Either way, we allocate stack slots adjacent to the data 3121 // provided by our caller, and store the unallocated registers there. 3122 // If this is a variadic function, the va_list pointer will begin with 3123 // these values; otherwise, this reassembles a (byval) structure that 3124 // was split between registers and memory. 3125 // Return: The frame index registers were stored into. 3126 int 3127 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3128 SDLoc dl, SDValue &Chain, 3129 const Value *OrigArg, 3130 unsigned InRegsParamRecordIdx, 3131 int ArgOffset, 3132 unsigned ArgSize) const { 3133 // Currently, two use-cases possible: 3134 // Case #1. Non-var-args function, and we meet first byval parameter. 3135 // Setup first unallocated register as first byval register; 3136 // eat all remained registers 3137 // (these two actions are performed by HandleByVal method). 3138 // Then, here, we initialize stack frame with 3139 // "store-reg" instructions. 3140 // Case #2. Var-args function, that doesn't contain byval parameters. 3141 // The same: eat all remained unallocated registers, 3142 // initialize stack frame. 3143 3144 MachineFunction &MF = DAG.getMachineFunction(); 3145 MachineFrameInfo *MFI = MF.getFrameInfo(); 3146 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3147 unsigned RBegin, REnd; 3148 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3149 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3150 } else { 3151 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3152 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3153 REnd = ARM::R4; 3154 } 3155 3156 if (REnd != RBegin) 3157 ArgOffset = -4 * (ARM::R4 - RBegin); 3158 3159 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3160 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false); 3161 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3162 3163 SmallVector<SDValue, 4> MemOps; 3164 const TargetRegisterClass *RC = 3165 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3166 3167 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3168 unsigned VReg = MF.addLiveIn(Reg, RC); 3169 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3170 SDValue Store = 3171 DAG.getStore(Val.getValue(1), dl, Val, FIN, 3172 MachinePointerInfo(OrigArg, 4 * i), false, false, 0); 3173 MemOps.push_back(Store); 3174 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3175 } 3176 3177 if (!MemOps.empty()) 3178 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3179 return FrameIndex; 3180 } 3181 3182 // Setup stack frame, the va_list pointer will start from. 3183 void 3184 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3185 SDLoc dl, SDValue &Chain, 3186 unsigned ArgOffset, 3187 unsigned TotalArgRegsSaveSize, 3188 bool ForceMutable) const { 3189 MachineFunction &MF = DAG.getMachineFunction(); 3190 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3191 3192 // Try to store any remaining integer argument regs 3193 // to their spots on the stack so that they may be loaded by deferencing 3194 // the result of va_next. 3195 // If there is no regs to be stored, just point address after last 3196 // argument passed via stack. 3197 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3198 CCInfo.getInRegsParamsCount(), 3199 CCInfo.getNextStackOffset(), 4); 3200 AFI->setVarArgsFrameIndex(FrameIndex); 3201 } 3202 3203 SDValue 3204 ARMTargetLowering::LowerFormalArguments(SDValue Chain, 3205 CallingConv::ID CallConv, bool isVarArg, 3206 const SmallVectorImpl<ISD::InputArg> 3207 &Ins, 3208 SDLoc dl, SelectionDAG &DAG, 3209 SmallVectorImpl<SDValue> &InVals) 3210 const { 3211 MachineFunction &MF = DAG.getMachineFunction(); 3212 MachineFrameInfo *MFI = MF.getFrameInfo(); 3213 3214 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3215 3216 // Assign locations to all of the incoming arguments. 3217 SmallVector<CCValAssign, 16> ArgLocs; 3218 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3219 *DAG.getContext(), Prologue); 3220 CCInfo.AnalyzeFormalArguments(Ins, 3221 CCAssignFnForNode(CallConv, /* Return*/ false, 3222 isVarArg)); 3223 3224 SmallVector<SDValue, 16> ArgValues; 3225 SDValue ArgValue; 3226 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3227 unsigned CurArgIdx = 0; 3228 3229 // Initially ArgRegsSaveSize is zero. 3230 // Then we increase this value each time we meet byval parameter. 3231 // We also increase this value in case of varargs function. 3232 AFI->setArgRegsSaveSize(0); 3233 3234 // Calculate the amount of stack space that we need to allocate to store 3235 // byval and variadic arguments that are passed in registers. 3236 // We need to know this before we allocate the first byval or variadic 3237 // argument, as they will be allocated a stack slot below the CFA (Canonical 3238 // Frame Address, the stack pointer at entry to the function). 3239 unsigned ArgRegBegin = ARM::R4; 3240 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3241 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3242 break; 3243 3244 CCValAssign &VA = ArgLocs[i]; 3245 unsigned Index = VA.getValNo(); 3246 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3247 if (!Flags.isByVal()) 3248 continue; 3249 3250 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3251 unsigned RBegin, REnd; 3252 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3253 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3254 3255 CCInfo.nextInRegsParam(); 3256 } 3257 CCInfo.rewindByValRegsInfo(); 3258 3259 int lastInsIndex = -1; 3260 if (isVarArg && MFI->hasVAStart()) { 3261 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3262 if (RegIdx != array_lengthof(GPRArgRegs)) 3263 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3264 } 3265 3266 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3267 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3268 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3269 3270 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3271 CCValAssign &VA = ArgLocs[i]; 3272 if (Ins[VA.getValNo()].isOrigArg()) { 3273 std::advance(CurOrigArg, 3274 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3275 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3276 } 3277 // Arguments stored in registers. 3278 if (VA.isRegLoc()) { 3279 EVT RegVT = VA.getLocVT(); 3280 3281 if (VA.needsCustom()) { 3282 // f64 and vector types are split up into multiple registers or 3283 // combinations of registers and stack slots. 3284 if (VA.getLocVT() == MVT::v2f64) { 3285 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3286 Chain, DAG, dl); 3287 VA = ArgLocs[++i]; // skip ahead to next loc 3288 SDValue ArgValue2; 3289 if (VA.isMemLoc()) { 3290 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 3291 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3292 ArgValue2 = DAG.getLoad( 3293 MVT::f64, dl, Chain, FIN, 3294 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3295 false, false, false, 0); 3296 } else { 3297 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3298 Chain, DAG, dl); 3299 } 3300 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3301 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3302 ArgValue, ArgValue1, 3303 DAG.getIntPtrConstant(0, dl)); 3304 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3305 ArgValue, ArgValue2, 3306 DAG.getIntPtrConstant(1, dl)); 3307 } else 3308 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3309 3310 } else { 3311 const TargetRegisterClass *RC; 3312 3313 if (RegVT == MVT::f32) 3314 RC = &ARM::SPRRegClass; 3315 else if (RegVT == MVT::f64) 3316 RC = &ARM::DPRRegClass; 3317 else if (RegVT == MVT::v2f64) 3318 RC = &ARM::QPRRegClass; 3319 else if (RegVT == MVT::i32) 3320 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3321 : &ARM::GPRRegClass; 3322 else 3323 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3324 3325 // Transform the arguments in physical registers into virtual ones. 3326 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3327 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3328 } 3329 3330 // If this is an 8 or 16-bit value, it is really passed promoted 3331 // to 32 bits. Insert an assert[sz]ext to capture this, then 3332 // truncate to the right size. 3333 switch (VA.getLocInfo()) { 3334 default: llvm_unreachable("Unknown loc info!"); 3335 case CCValAssign::Full: break; 3336 case CCValAssign::BCvt: 3337 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3338 break; 3339 case CCValAssign::SExt: 3340 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3341 DAG.getValueType(VA.getValVT())); 3342 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3343 break; 3344 case CCValAssign::ZExt: 3345 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3346 DAG.getValueType(VA.getValVT())); 3347 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3348 break; 3349 } 3350 3351 InVals.push_back(ArgValue); 3352 3353 } else { // VA.isRegLoc() 3354 3355 // sanity check 3356 assert(VA.isMemLoc()); 3357 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3358 3359 int index = VA.getValNo(); 3360 3361 // Some Ins[] entries become multiple ArgLoc[] entries. 3362 // Process them only once. 3363 if (index != lastInsIndex) 3364 { 3365 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3366 // FIXME: For now, all byval parameter objects are marked mutable. 3367 // This can be changed with more analysis. 3368 // In case of tail call optimization mark all arguments mutable. 3369 // Since they could be overwritten by lowering of arguments in case of 3370 // a tail call. 3371 if (Flags.isByVal()) { 3372 assert(Ins[index].isOrigArg() && 3373 "Byval arguments cannot be implicit"); 3374 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3375 3376 int FrameIndex = StoreByValRegs( 3377 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3378 VA.getLocMemOffset(), Flags.getByValSize()); 3379 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3380 CCInfo.nextInRegsParam(); 3381 } else { 3382 unsigned FIOffset = VA.getLocMemOffset(); 3383 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3384 FIOffset, true); 3385 3386 // Create load nodes to retrieve arguments from the stack. 3387 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3388 InVals.push_back(DAG.getLoad( 3389 VA.getValVT(), dl, Chain, FIN, 3390 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3391 false, false, false, 0)); 3392 } 3393 lastInsIndex = index; 3394 } 3395 } 3396 } 3397 3398 // varargs 3399 if (isVarArg && MFI->hasVAStart()) 3400 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3401 CCInfo.getNextStackOffset(), 3402 TotalArgRegsSaveSize); 3403 3404 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3405 3406 return Chain; 3407 } 3408 3409 /// isFloatingPointZero - Return true if this is +0.0. 3410 static bool isFloatingPointZero(SDValue Op) { 3411 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3412 return CFP->getValueAPF().isPosZero(); 3413 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3414 // Maybe this has already been legalized into the constant pool? 3415 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3416 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3417 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3418 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3419 return CFP->getValueAPF().isPosZero(); 3420 } 3421 } else if (Op->getOpcode() == ISD::BITCAST && 3422 Op->getValueType(0) == MVT::f64) { 3423 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3424 // created by LowerConstantFP(). 3425 SDValue BitcastOp = Op->getOperand(0); 3426 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3427 isNullConstant(BitcastOp->getOperand(0))) 3428 return true; 3429 } 3430 return false; 3431 } 3432 3433 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3434 /// the given operands. 3435 SDValue 3436 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3437 SDValue &ARMcc, SelectionDAG &DAG, 3438 SDLoc dl) const { 3439 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3440 unsigned C = RHSC->getZExtValue(); 3441 if (!isLegalICmpImmediate(C)) { 3442 // Constant does not fit, try adjusting it by one? 3443 switch (CC) { 3444 default: break; 3445 case ISD::SETLT: 3446 case ISD::SETGE: 3447 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3448 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3449 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3450 } 3451 break; 3452 case ISD::SETULT: 3453 case ISD::SETUGE: 3454 if (C != 0 && isLegalICmpImmediate(C-1)) { 3455 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3456 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3457 } 3458 break; 3459 case ISD::SETLE: 3460 case ISD::SETGT: 3461 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3462 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3463 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3464 } 3465 break; 3466 case ISD::SETULE: 3467 case ISD::SETUGT: 3468 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3469 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3470 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3471 } 3472 break; 3473 } 3474 } 3475 } 3476 3477 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3478 ARMISD::NodeType CompareType; 3479 switch (CondCode) { 3480 default: 3481 CompareType = ARMISD::CMP; 3482 break; 3483 case ARMCC::EQ: 3484 case ARMCC::NE: 3485 // Uses only Z Flag 3486 CompareType = ARMISD::CMPZ; 3487 break; 3488 } 3489 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3490 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3491 } 3492 3493 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3494 SDValue 3495 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG, 3496 SDLoc dl) const { 3497 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3498 SDValue Cmp; 3499 if (!isFloatingPointZero(RHS)) 3500 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3501 else 3502 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3503 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3504 } 3505 3506 /// duplicateCmp - Glue values can have only one use, so this function 3507 /// duplicates a comparison node. 3508 SDValue 3509 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3510 unsigned Opc = Cmp.getOpcode(); 3511 SDLoc DL(Cmp); 3512 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3513 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3514 3515 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3516 Cmp = Cmp.getOperand(0); 3517 Opc = Cmp.getOpcode(); 3518 if (Opc == ARMISD::CMPFP) 3519 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3520 else { 3521 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3522 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3523 } 3524 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3525 } 3526 3527 std::pair<SDValue, SDValue> 3528 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3529 SDValue &ARMcc) const { 3530 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3531 3532 SDValue Value, OverflowCmp; 3533 SDValue LHS = Op.getOperand(0); 3534 SDValue RHS = Op.getOperand(1); 3535 SDLoc dl(Op); 3536 3537 // FIXME: We are currently always generating CMPs because we don't support 3538 // generating CMN through the backend. This is not as good as the natural 3539 // CMP case because it causes a register dependency and cannot be folded 3540 // later. 3541 3542 switch (Op.getOpcode()) { 3543 default: 3544 llvm_unreachable("Unknown overflow instruction!"); 3545 case ISD::SADDO: 3546 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3547 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3548 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3549 break; 3550 case ISD::UADDO: 3551 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3552 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3553 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3554 break; 3555 case ISD::SSUBO: 3556 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3557 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3558 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3559 break; 3560 case ISD::USUBO: 3561 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3562 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3563 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3564 break; 3565 } // switch (...) 3566 3567 return std::make_pair(Value, OverflowCmp); 3568 } 3569 3570 3571 SDValue 3572 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3573 // Let legalize expand this if it isn't a legal type yet. 3574 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3575 return SDValue(); 3576 3577 SDValue Value, OverflowCmp; 3578 SDValue ARMcc; 3579 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3580 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3581 SDLoc dl(Op); 3582 // We use 0 and 1 as false and true values. 3583 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3584 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3585 EVT VT = Op.getValueType(); 3586 3587 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3588 ARMcc, CCR, OverflowCmp); 3589 3590 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3591 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3592 } 3593 3594 3595 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3596 SDValue Cond = Op.getOperand(0); 3597 SDValue SelectTrue = Op.getOperand(1); 3598 SDValue SelectFalse = Op.getOperand(2); 3599 SDLoc dl(Op); 3600 unsigned Opc = Cond.getOpcode(); 3601 3602 if (Cond.getResNo() == 1 && 3603 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3604 Opc == ISD::USUBO)) { 3605 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3606 return SDValue(); 3607 3608 SDValue Value, OverflowCmp; 3609 SDValue ARMcc; 3610 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3611 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3612 EVT VT = Op.getValueType(); 3613 3614 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3615 OverflowCmp, DAG); 3616 } 3617 3618 // Convert: 3619 // 3620 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3621 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3622 // 3623 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3624 const ConstantSDNode *CMOVTrue = 3625 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3626 const ConstantSDNode *CMOVFalse = 3627 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3628 3629 if (CMOVTrue && CMOVFalse) { 3630 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3631 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3632 3633 SDValue True; 3634 SDValue False; 3635 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3636 True = SelectTrue; 3637 False = SelectFalse; 3638 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3639 True = SelectFalse; 3640 False = SelectTrue; 3641 } 3642 3643 if (True.getNode() && False.getNode()) { 3644 EVT VT = Op.getValueType(); 3645 SDValue ARMcc = Cond.getOperand(2); 3646 SDValue CCR = Cond.getOperand(3); 3647 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3648 assert(True.getValueType() == VT); 3649 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3650 } 3651 } 3652 } 3653 3654 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3655 // undefined bits before doing a full-word comparison with zero. 3656 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3657 DAG.getConstant(1, dl, Cond.getValueType())); 3658 3659 return DAG.getSelectCC(dl, Cond, 3660 DAG.getConstant(0, dl, Cond.getValueType()), 3661 SelectTrue, SelectFalse, ISD::SETNE); 3662 } 3663 3664 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3665 bool &swpCmpOps, bool &swpVselOps) { 3666 // Start by selecting the GE condition code for opcodes that return true for 3667 // 'equality' 3668 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3669 CC == ISD::SETULE) 3670 CondCode = ARMCC::GE; 3671 3672 // and GT for opcodes that return false for 'equality'. 3673 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3674 CC == ISD::SETULT) 3675 CondCode = ARMCC::GT; 3676 3677 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3678 // to swap the compare operands. 3679 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3680 CC == ISD::SETULT) 3681 swpCmpOps = true; 3682 3683 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3684 // If we have an unordered opcode, we need to swap the operands to the VSEL 3685 // instruction (effectively negating the condition). 3686 // 3687 // This also has the effect of swapping which one of 'less' or 'greater' 3688 // returns true, so we also swap the compare operands. It also switches 3689 // whether we return true for 'equality', so we compensate by picking the 3690 // opposite condition code to our original choice. 3691 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3692 CC == ISD::SETUGT) { 3693 swpCmpOps = !swpCmpOps; 3694 swpVselOps = !swpVselOps; 3695 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3696 } 3697 3698 // 'ordered' is 'anything but unordered', so use the VS condition code and 3699 // swap the VSEL operands. 3700 if (CC == ISD::SETO) { 3701 CondCode = ARMCC::VS; 3702 swpVselOps = true; 3703 } 3704 3705 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3706 // code and swap the VSEL operands. 3707 if (CC == ISD::SETUNE) { 3708 CondCode = ARMCC::EQ; 3709 swpVselOps = true; 3710 } 3711 } 3712 3713 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal, 3714 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3715 SDValue Cmp, SelectionDAG &DAG) const { 3716 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3717 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3718 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3719 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3720 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3721 3722 SDValue TrueLow = TrueVal.getValue(0); 3723 SDValue TrueHigh = TrueVal.getValue(1); 3724 SDValue FalseLow = FalseVal.getValue(0); 3725 SDValue FalseHigh = FalseVal.getValue(1); 3726 3727 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3728 ARMcc, CCR, Cmp); 3729 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3730 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3731 3732 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3733 } else { 3734 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3735 Cmp); 3736 } 3737 } 3738 3739 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3740 EVT VT = Op.getValueType(); 3741 SDValue LHS = Op.getOperand(0); 3742 SDValue RHS = Op.getOperand(1); 3743 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3744 SDValue TrueVal = Op.getOperand(2); 3745 SDValue FalseVal = Op.getOperand(3); 3746 SDLoc dl(Op); 3747 3748 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3749 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3750 dl); 3751 3752 // If softenSetCCOperands only returned one value, we should compare it to 3753 // zero. 3754 if (!RHS.getNode()) { 3755 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3756 CC = ISD::SETNE; 3757 } 3758 } 3759 3760 if (LHS.getValueType() == MVT::i32) { 3761 // Try to generate VSEL on ARMv8. 3762 // The VSEL instruction can't use all the usual ARM condition 3763 // codes: it only has two bits to select the condition code, so it's 3764 // constrained to use only GE, GT, VS and EQ. 3765 // 3766 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3767 // swap the operands of the previous compare instruction (effectively 3768 // inverting the compare condition, swapping 'less' and 'greater') and 3769 // sometimes need to swap the operands to the VSEL (which inverts the 3770 // condition in the sense of firing whenever the previous condition didn't) 3771 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3772 TrueVal.getValueType() == MVT::f64)) { 3773 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3774 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3775 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3776 CC = ISD::getSetCCInverse(CC, true); 3777 std::swap(TrueVal, FalseVal); 3778 } 3779 } 3780 3781 SDValue ARMcc; 3782 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3783 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3784 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3785 } 3786 3787 ARMCC::CondCodes CondCode, CondCode2; 3788 FPCCToARMCC(CC, CondCode, CondCode2); 3789 3790 // Try to generate VMAXNM/VMINNM on ARMv8. 3791 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3792 TrueVal.getValueType() == MVT::f64)) { 3793 bool swpCmpOps = false; 3794 bool swpVselOps = false; 3795 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3796 3797 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3798 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3799 if (swpCmpOps) 3800 std::swap(LHS, RHS); 3801 if (swpVselOps) 3802 std::swap(TrueVal, FalseVal); 3803 } 3804 } 3805 3806 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3807 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3808 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3809 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3810 if (CondCode2 != ARMCC::AL) { 3811 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 3812 // FIXME: Needs another CMP because flag can have but one use. 3813 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3814 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3815 } 3816 return Result; 3817 } 3818 3819 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3820 /// to morph to an integer compare sequence. 3821 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3822 const ARMSubtarget *Subtarget) { 3823 SDNode *N = Op.getNode(); 3824 if (!N->hasOneUse()) 3825 // Otherwise it requires moving the value from fp to integer registers. 3826 return false; 3827 if (!N->getNumValues()) 3828 return false; 3829 EVT VT = Op.getValueType(); 3830 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3831 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3832 // vmrs are very slow, e.g. cortex-a8. 3833 return false; 3834 3835 if (isFloatingPointZero(Op)) { 3836 SeenZero = true; 3837 return true; 3838 } 3839 return ISD::isNormalLoad(N); 3840 } 3841 3842 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3843 if (isFloatingPointZero(Op)) 3844 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 3845 3846 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3847 return DAG.getLoad(MVT::i32, SDLoc(Op), 3848 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3849 Ld->isVolatile(), Ld->isNonTemporal(), 3850 Ld->isInvariant(), Ld->getAlignment()); 3851 3852 llvm_unreachable("Unknown VFP cmp argument!"); 3853 } 3854 3855 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3856 SDValue &RetVal1, SDValue &RetVal2) { 3857 SDLoc dl(Op); 3858 3859 if (isFloatingPointZero(Op)) { 3860 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 3861 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 3862 return; 3863 } 3864 3865 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3866 SDValue Ptr = Ld->getBasePtr(); 3867 RetVal1 = DAG.getLoad(MVT::i32, dl, 3868 Ld->getChain(), Ptr, 3869 Ld->getPointerInfo(), 3870 Ld->isVolatile(), Ld->isNonTemporal(), 3871 Ld->isInvariant(), Ld->getAlignment()); 3872 3873 EVT PtrType = Ptr.getValueType(); 3874 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3875 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 3876 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 3877 RetVal2 = DAG.getLoad(MVT::i32, dl, 3878 Ld->getChain(), NewPtr, 3879 Ld->getPointerInfo().getWithOffset(4), 3880 Ld->isVolatile(), Ld->isNonTemporal(), 3881 Ld->isInvariant(), NewAlign); 3882 return; 3883 } 3884 3885 llvm_unreachable("Unknown VFP cmp argument!"); 3886 } 3887 3888 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 3889 /// f32 and even f64 comparisons to integer ones. 3890 SDValue 3891 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 3892 SDValue Chain = Op.getOperand(0); 3893 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3894 SDValue LHS = Op.getOperand(2); 3895 SDValue RHS = Op.getOperand(3); 3896 SDValue Dest = Op.getOperand(4); 3897 SDLoc dl(Op); 3898 3899 bool LHSSeenZero = false; 3900 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 3901 bool RHSSeenZero = false; 3902 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 3903 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 3904 // If unsafe fp math optimization is enabled and there are no other uses of 3905 // the CMP operands, and the condition code is EQ or NE, we can optimize it 3906 // to an integer comparison. 3907 if (CC == ISD::SETOEQ) 3908 CC = ISD::SETEQ; 3909 else if (CC == ISD::SETUNE) 3910 CC = ISD::SETNE; 3911 3912 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 3913 SDValue ARMcc; 3914 if (LHS.getValueType() == MVT::f32) { 3915 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3916 bitcastf32Toi32(LHS, DAG), Mask); 3917 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3918 bitcastf32Toi32(RHS, DAG), Mask); 3919 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3920 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3921 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3922 Chain, Dest, ARMcc, CCR, Cmp); 3923 } 3924 3925 SDValue LHS1, LHS2; 3926 SDValue RHS1, RHS2; 3927 expandf64Toi32(LHS, DAG, LHS1, LHS2); 3928 expandf64Toi32(RHS, DAG, RHS1, RHS2); 3929 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 3930 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 3931 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3932 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3933 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3934 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 3935 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 3936 } 3937 3938 return SDValue(); 3939 } 3940 3941 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3942 SDValue Chain = Op.getOperand(0); 3943 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3944 SDValue LHS = Op.getOperand(2); 3945 SDValue RHS = Op.getOperand(3); 3946 SDValue Dest = Op.getOperand(4); 3947 SDLoc dl(Op); 3948 3949 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3950 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3951 dl); 3952 3953 // If softenSetCCOperands only returned one value, we should compare it to 3954 // zero. 3955 if (!RHS.getNode()) { 3956 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3957 CC = ISD::SETNE; 3958 } 3959 } 3960 3961 if (LHS.getValueType() == MVT::i32) { 3962 SDValue ARMcc; 3963 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3964 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3965 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3966 Chain, Dest, ARMcc, CCR, Cmp); 3967 } 3968 3969 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3970 3971 if (getTargetMachine().Options.UnsafeFPMath && 3972 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 3973 CC == ISD::SETNE || CC == ISD::SETUNE)) { 3974 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 3975 return Result; 3976 } 3977 3978 ARMCC::CondCodes CondCode, CondCode2; 3979 FPCCToARMCC(CC, CondCode, CondCode2); 3980 3981 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3982 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3983 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3984 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3985 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 3986 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3987 if (CondCode2 != ARMCC::AL) { 3988 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 3989 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 3990 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3991 } 3992 return Res; 3993 } 3994 3995 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 3996 SDValue Chain = Op.getOperand(0); 3997 SDValue Table = Op.getOperand(1); 3998 SDValue Index = Op.getOperand(2); 3999 SDLoc dl(Op); 4000 4001 EVT PTy = getPointerTy(DAG.getDataLayout()); 4002 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4003 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4004 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4005 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4006 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4007 if (Subtarget->isThumb2()) { 4008 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 4009 // which does another jump to the destination. This also makes it easier 4010 // to translate it to TBB / TBH later. 4011 // FIXME: This might not work if the function is extremely large. 4012 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4013 Addr, Op.getOperand(2), JTI); 4014 } 4015 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 4016 Addr = 4017 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4018 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4019 false, false, false, 0); 4020 Chain = Addr.getValue(1); 4021 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4022 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4023 } else { 4024 Addr = 4025 DAG.getLoad(PTy, dl, Chain, Addr, 4026 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4027 false, false, false, 0); 4028 Chain = Addr.getValue(1); 4029 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4030 } 4031 } 4032 4033 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4034 EVT VT = Op.getValueType(); 4035 SDLoc dl(Op); 4036 4037 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4038 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4039 return Op; 4040 return DAG.UnrollVectorOp(Op.getNode()); 4041 } 4042 4043 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4044 "Invalid type for custom lowering!"); 4045 if (VT != MVT::v4i16) 4046 return DAG.UnrollVectorOp(Op.getNode()); 4047 4048 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4049 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4050 } 4051 4052 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4053 EVT VT = Op.getValueType(); 4054 if (VT.isVector()) 4055 return LowerVectorFP_TO_INT(Op, DAG); 4056 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4057 RTLIB::Libcall LC; 4058 if (Op.getOpcode() == ISD::FP_TO_SINT) 4059 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4060 Op.getValueType()); 4061 else 4062 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4063 Op.getValueType()); 4064 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4065 /*isSigned*/ false, SDLoc(Op)).first; 4066 } 4067 4068 return Op; 4069 } 4070 4071 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4072 EVT VT = Op.getValueType(); 4073 SDLoc dl(Op); 4074 4075 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4076 if (VT.getVectorElementType() == MVT::f32) 4077 return Op; 4078 return DAG.UnrollVectorOp(Op.getNode()); 4079 } 4080 4081 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4082 "Invalid type for custom lowering!"); 4083 if (VT != MVT::v4f32) 4084 return DAG.UnrollVectorOp(Op.getNode()); 4085 4086 unsigned CastOpc; 4087 unsigned Opc; 4088 switch (Op.getOpcode()) { 4089 default: llvm_unreachable("Invalid opcode!"); 4090 case ISD::SINT_TO_FP: 4091 CastOpc = ISD::SIGN_EXTEND; 4092 Opc = ISD::SINT_TO_FP; 4093 break; 4094 case ISD::UINT_TO_FP: 4095 CastOpc = ISD::ZERO_EXTEND; 4096 Opc = ISD::UINT_TO_FP; 4097 break; 4098 } 4099 4100 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4101 return DAG.getNode(Opc, dl, VT, Op); 4102 } 4103 4104 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4105 EVT VT = Op.getValueType(); 4106 if (VT.isVector()) 4107 return LowerVectorINT_TO_FP(Op, DAG); 4108 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4109 RTLIB::Libcall LC; 4110 if (Op.getOpcode() == ISD::SINT_TO_FP) 4111 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4112 Op.getValueType()); 4113 else 4114 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4115 Op.getValueType()); 4116 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4117 /*isSigned*/ false, SDLoc(Op)).first; 4118 } 4119 4120 return Op; 4121 } 4122 4123 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4124 // Implement fcopysign with a fabs and a conditional fneg. 4125 SDValue Tmp0 = Op.getOperand(0); 4126 SDValue Tmp1 = Op.getOperand(1); 4127 SDLoc dl(Op); 4128 EVT VT = Op.getValueType(); 4129 EVT SrcVT = Tmp1.getValueType(); 4130 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4131 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4132 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4133 4134 if (UseNEON) { 4135 // Use VBSL to copy the sign bit. 4136 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4137 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4138 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4139 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4140 if (VT == MVT::f64) 4141 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4142 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4143 DAG.getConstant(32, dl, MVT::i32)); 4144 else /*if (VT == MVT::f32)*/ 4145 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4146 if (SrcVT == MVT::f32) { 4147 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4148 if (VT == MVT::f64) 4149 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4150 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4151 DAG.getConstant(32, dl, MVT::i32)); 4152 } else if (VT == MVT::f32) 4153 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4154 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4155 DAG.getConstant(32, dl, MVT::i32)); 4156 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4157 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4158 4159 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4160 dl, MVT::i32); 4161 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4162 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4163 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4164 4165 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4166 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4167 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4168 if (VT == MVT::f32) { 4169 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4170 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4171 DAG.getConstant(0, dl, MVT::i32)); 4172 } else { 4173 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4174 } 4175 4176 return Res; 4177 } 4178 4179 // Bitcast operand 1 to i32. 4180 if (SrcVT == MVT::f64) 4181 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4182 Tmp1).getValue(1); 4183 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4184 4185 // Or in the signbit with integer operations. 4186 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4187 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4188 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4189 if (VT == MVT::f32) { 4190 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4191 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4192 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4193 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4194 } 4195 4196 // f64: Or the high part with signbit and then combine two parts. 4197 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4198 Tmp0); 4199 SDValue Lo = Tmp0.getValue(0); 4200 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4201 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4202 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4203 } 4204 4205 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4206 MachineFunction &MF = DAG.getMachineFunction(); 4207 MachineFrameInfo *MFI = MF.getFrameInfo(); 4208 MFI->setReturnAddressIsTaken(true); 4209 4210 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4211 return SDValue(); 4212 4213 EVT VT = Op.getValueType(); 4214 SDLoc dl(Op); 4215 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4216 if (Depth) { 4217 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4218 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4219 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4220 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4221 MachinePointerInfo(), false, false, false, 0); 4222 } 4223 4224 // Return LR, which contains the return address. Mark it an implicit live-in. 4225 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4226 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4227 } 4228 4229 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4230 const ARMBaseRegisterInfo &ARI = 4231 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4232 MachineFunction &MF = DAG.getMachineFunction(); 4233 MachineFrameInfo *MFI = MF.getFrameInfo(); 4234 MFI->setFrameAddressIsTaken(true); 4235 4236 EVT VT = Op.getValueType(); 4237 SDLoc dl(Op); // FIXME probably not meaningful 4238 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4239 unsigned FrameReg = ARI.getFrameRegister(MF); 4240 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4241 while (Depth--) 4242 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4243 MachinePointerInfo(), 4244 false, false, false, 0); 4245 return FrameAddr; 4246 } 4247 4248 // FIXME? Maybe this could be a TableGen attribute on some registers and 4249 // this table could be generated automatically from RegInfo. 4250 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4251 SelectionDAG &DAG) const { 4252 unsigned Reg = StringSwitch<unsigned>(RegName) 4253 .Case("sp", ARM::SP) 4254 .Default(0); 4255 if (Reg) 4256 return Reg; 4257 report_fatal_error(Twine("Invalid register name \"" 4258 + StringRef(RegName) + "\".")); 4259 } 4260 4261 // Result is 64 bit value so split into two 32 bit values and return as a 4262 // pair of values. 4263 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4264 SelectionDAG &DAG) { 4265 SDLoc DL(N); 4266 4267 // This function is only supposed to be called for i64 type destination. 4268 assert(N->getValueType(0) == MVT::i64 4269 && "ExpandREAD_REGISTER called for non-i64 type result."); 4270 4271 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4272 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4273 N->getOperand(0), 4274 N->getOperand(1)); 4275 4276 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4277 Read.getValue(1))); 4278 Results.push_back(Read.getOperand(0)); 4279 } 4280 4281 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4282 /// When \p DstVT, the destination type of \p BC, is on the vector 4283 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4284 /// it might be possible to combine them, such that everything stays on the 4285 /// vector register bank. 4286 /// \p return The node that would replace \p BT, if the combine 4287 /// is possible. 4288 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4289 SelectionDAG &DAG) { 4290 SDValue Op = BC->getOperand(0); 4291 EVT DstVT = BC->getValueType(0); 4292 4293 // The only vector instruction that can produce a scalar (remember, 4294 // since the bitcast was about to be turned into VMOVDRR, the source 4295 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4296 // Moreover, we can do this combine only if there is one use. 4297 // Finally, if the destination type is not a vector, there is not 4298 // much point on forcing everything on the vector bank. 4299 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4300 !Op.hasOneUse()) 4301 return SDValue(); 4302 4303 // If the index is not constant, we will introduce an additional 4304 // multiply that will stick. 4305 // Give up in that case. 4306 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4307 if (!Index) 4308 return SDValue(); 4309 unsigned DstNumElt = DstVT.getVectorNumElements(); 4310 4311 // Compute the new index. 4312 const APInt &APIntIndex = Index->getAPIntValue(); 4313 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4314 NewIndex *= APIntIndex; 4315 // Check if the new constant index fits into i32. 4316 if (NewIndex.getBitWidth() > 32) 4317 return SDValue(); 4318 4319 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4320 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4321 SDLoc dl(Op); 4322 SDValue ExtractSrc = Op.getOperand(0); 4323 EVT VecVT = EVT::getVectorVT( 4324 *DAG.getContext(), DstVT.getScalarType(), 4325 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4326 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4327 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4328 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4329 } 4330 4331 /// ExpandBITCAST - If the target supports VFP, this function is called to 4332 /// expand a bit convert where either the source or destination type is i64 to 4333 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4334 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4335 /// vectors), since the legalizer won't know what to do with that. 4336 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4337 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4338 SDLoc dl(N); 4339 SDValue Op = N->getOperand(0); 4340 4341 // This function is only supposed to be called for i64 types, either as the 4342 // source or destination of the bit convert. 4343 EVT SrcVT = Op.getValueType(); 4344 EVT DstVT = N->getValueType(0); 4345 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4346 "ExpandBITCAST called for non-i64 type"); 4347 4348 // Turn i64->f64 into VMOVDRR. 4349 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4350 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4351 // if we can combine the bitcast with its source. 4352 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4353 return Val; 4354 4355 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4356 DAG.getConstant(0, dl, MVT::i32)); 4357 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4358 DAG.getConstant(1, dl, MVT::i32)); 4359 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4360 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4361 } 4362 4363 // Turn f64->i64 into VMOVRRD. 4364 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4365 SDValue Cvt; 4366 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4367 SrcVT.getVectorNumElements() > 1) 4368 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4369 DAG.getVTList(MVT::i32, MVT::i32), 4370 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4371 else 4372 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4373 DAG.getVTList(MVT::i32, MVT::i32), Op); 4374 // Merge the pieces into a single i64 value. 4375 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4376 } 4377 4378 return SDValue(); 4379 } 4380 4381 /// getZeroVector - Returns a vector of specified type with all zero elements. 4382 /// Zero vectors are used to represent vector negation and in those cases 4383 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4384 /// not support i64 elements, so sometimes the zero vectors will need to be 4385 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4386 /// zero vector. 4387 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) { 4388 assert(VT.isVector() && "Expected a vector type"); 4389 // The canonical modified immediate encoding of a zero vector is....0! 4390 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4391 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4392 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4393 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4394 } 4395 4396 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4397 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4398 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4399 SelectionDAG &DAG) const { 4400 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4401 EVT VT = Op.getValueType(); 4402 unsigned VTBits = VT.getSizeInBits(); 4403 SDLoc dl(Op); 4404 SDValue ShOpLo = Op.getOperand(0); 4405 SDValue ShOpHi = Op.getOperand(1); 4406 SDValue ShAmt = Op.getOperand(2); 4407 SDValue ARMcc; 4408 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4409 4410 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4411 4412 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4413 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4414 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4415 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4416 DAG.getConstant(VTBits, dl, MVT::i32)); 4417 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4418 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4419 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4420 4421 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4422 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4423 ISD::SETGE, ARMcc, DAG, dl); 4424 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4425 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4426 CCR, Cmp); 4427 4428 SDValue Ops[2] = { Lo, Hi }; 4429 return DAG.getMergeValues(Ops, dl); 4430 } 4431 4432 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4433 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4434 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4435 SelectionDAG &DAG) const { 4436 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4437 EVT VT = Op.getValueType(); 4438 unsigned VTBits = VT.getSizeInBits(); 4439 SDLoc dl(Op); 4440 SDValue ShOpLo = Op.getOperand(0); 4441 SDValue ShOpHi = Op.getOperand(1); 4442 SDValue ShAmt = Op.getOperand(2); 4443 SDValue ARMcc; 4444 4445 assert(Op.getOpcode() == ISD::SHL_PARTS); 4446 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4447 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4448 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4449 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4450 DAG.getConstant(VTBits, dl, MVT::i32)); 4451 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4452 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4453 4454 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4455 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4456 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4457 ISD::SETGE, ARMcc, DAG, dl); 4458 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4459 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4460 CCR, Cmp); 4461 4462 SDValue Ops[2] = { Lo, Hi }; 4463 return DAG.getMergeValues(Ops, dl); 4464 } 4465 4466 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4467 SelectionDAG &DAG) const { 4468 // The rounding mode is in bits 23:22 of the FPSCR. 4469 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4470 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4471 // so that the shift + and get folded into a bitfield extract. 4472 SDLoc dl(Op); 4473 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4474 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4475 MVT::i32)); 4476 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4477 DAG.getConstant(1U << 22, dl, MVT::i32)); 4478 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4479 DAG.getConstant(22, dl, MVT::i32)); 4480 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4481 DAG.getConstant(3, dl, MVT::i32)); 4482 } 4483 4484 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4485 const ARMSubtarget *ST) { 4486 SDLoc dl(N); 4487 EVT VT = N->getValueType(0); 4488 if (VT.isVector()) { 4489 assert(ST->hasNEON()); 4490 4491 // Compute the least significant set bit: LSB = X & -X 4492 SDValue X = N->getOperand(0); 4493 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4494 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4495 4496 EVT ElemTy = VT.getVectorElementType(); 4497 4498 if (ElemTy == MVT::i8) { 4499 // Compute with: cttz(x) = ctpop(lsb - 1) 4500 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4501 DAG.getTargetConstant(1, dl, ElemTy)); 4502 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4503 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4504 } 4505 4506 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4507 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4508 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4509 unsigned NumBits = ElemTy.getSizeInBits(); 4510 SDValue WidthMinus1 = 4511 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4512 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4513 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4514 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4515 } 4516 4517 // Compute with: cttz(x) = ctpop(lsb - 1) 4518 4519 // Since we can only compute the number of bits in a byte with vcnt.8, we 4520 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4521 // and i64. 4522 4523 // Compute LSB - 1. 4524 SDValue Bits; 4525 if (ElemTy == MVT::i64) { 4526 // Load constant 0xffff'ffff'ffff'ffff to register. 4527 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4528 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4529 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4530 } else { 4531 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4532 DAG.getTargetConstant(1, dl, ElemTy)); 4533 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4534 } 4535 4536 // Count #bits with vcnt.8. 4537 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4538 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4539 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4540 4541 // Gather the #bits with vpaddl (pairwise add.) 4542 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4543 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4544 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4545 Cnt8); 4546 if (ElemTy == MVT::i16) 4547 return Cnt16; 4548 4549 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4550 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4551 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4552 Cnt16); 4553 if (ElemTy == MVT::i32) 4554 return Cnt32; 4555 4556 assert(ElemTy == MVT::i64); 4557 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4558 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4559 Cnt32); 4560 return Cnt64; 4561 } 4562 4563 if (!ST->hasV6T2Ops()) 4564 return SDValue(); 4565 4566 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4567 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4568 } 4569 4570 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4571 /// for each 16-bit element from operand, repeated. The basic idea is to 4572 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4573 /// 4574 /// Trace for v4i16: 4575 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4576 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4577 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4578 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4579 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4580 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4581 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4582 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4583 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4584 EVT VT = N->getValueType(0); 4585 SDLoc DL(N); 4586 4587 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4588 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4589 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4590 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4591 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4592 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4593 } 4594 4595 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4596 /// bit-count for each 16-bit element from the operand. We need slightly 4597 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4598 /// 64/128-bit registers. 4599 /// 4600 /// Trace for v4i16: 4601 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4602 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4603 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4604 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4605 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4606 EVT VT = N->getValueType(0); 4607 SDLoc DL(N); 4608 4609 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4610 if (VT.is64BitVector()) { 4611 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4612 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4613 DAG.getIntPtrConstant(0, DL)); 4614 } else { 4615 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4616 BitCounts, DAG.getIntPtrConstant(0, DL)); 4617 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4618 } 4619 } 4620 4621 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4622 /// bit-count for each 32-bit element from the operand. The idea here is 4623 /// to split the vector into 16-bit elements, leverage the 16-bit count 4624 /// routine, and then combine the results. 4625 /// 4626 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4627 /// input = [v0 v1 ] (vi: 32-bit elements) 4628 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4629 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4630 /// vrev: N0 = [k1 k0 k3 k2 ] 4631 /// [k0 k1 k2 k3 ] 4632 /// N1 =+[k1 k0 k3 k2 ] 4633 /// [k0 k2 k1 k3 ] 4634 /// N2 =+[k1 k3 k0 k2 ] 4635 /// [k0 k2 k1 k3 ] 4636 /// Extended =+[k1 k3 k0 k2 ] 4637 /// [k0 k2 ] 4638 /// Extracted=+[k1 k3 ] 4639 /// 4640 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4641 EVT VT = N->getValueType(0); 4642 SDLoc DL(N); 4643 4644 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4645 4646 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4647 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4648 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4649 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4650 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4651 4652 if (VT.is64BitVector()) { 4653 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4654 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4655 DAG.getIntPtrConstant(0, DL)); 4656 } else { 4657 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4658 DAG.getIntPtrConstant(0, DL)); 4659 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4660 } 4661 } 4662 4663 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4664 const ARMSubtarget *ST) { 4665 EVT VT = N->getValueType(0); 4666 4667 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4668 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4669 VT == MVT::v4i16 || VT == MVT::v8i16) && 4670 "Unexpected type for custom ctpop lowering"); 4671 4672 if (VT.getVectorElementType() == MVT::i32) 4673 return lowerCTPOP32BitElements(N, DAG); 4674 else 4675 return lowerCTPOP16BitElements(N, DAG); 4676 } 4677 4678 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4679 const ARMSubtarget *ST) { 4680 EVT VT = N->getValueType(0); 4681 SDLoc dl(N); 4682 4683 if (!VT.isVector()) 4684 return SDValue(); 4685 4686 // Lower vector shifts on NEON to use VSHL. 4687 assert(ST->hasNEON() && "unexpected vector shift"); 4688 4689 // Left shifts translate directly to the vshiftu intrinsic. 4690 if (N->getOpcode() == ISD::SHL) 4691 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4692 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4693 MVT::i32), 4694 N->getOperand(0), N->getOperand(1)); 4695 4696 assert((N->getOpcode() == ISD::SRA || 4697 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4698 4699 // NEON uses the same intrinsics for both left and right shifts. For 4700 // right shifts, the shift amounts are negative, so negate the vector of 4701 // shift amounts. 4702 EVT ShiftVT = N->getOperand(1).getValueType(); 4703 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4704 getZeroVector(ShiftVT, DAG, dl), 4705 N->getOperand(1)); 4706 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4707 Intrinsic::arm_neon_vshifts : 4708 Intrinsic::arm_neon_vshiftu); 4709 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4710 DAG.getConstant(vshiftInt, dl, MVT::i32), 4711 N->getOperand(0), NegatedCount); 4712 } 4713 4714 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4715 const ARMSubtarget *ST) { 4716 EVT VT = N->getValueType(0); 4717 SDLoc dl(N); 4718 4719 // We can get here for a node like i32 = ISD::SHL i32, i64 4720 if (VT != MVT::i64) 4721 return SDValue(); 4722 4723 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4724 "Unknown shift to lower!"); 4725 4726 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4727 if (!isOneConstant(N->getOperand(1))) 4728 return SDValue(); 4729 4730 // If we are in thumb mode, we don't have RRX. 4731 if (ST->isThumb1Only()) return SDValue(); 4732 4733 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4734 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4735 DAG.getConstant(0, dl, MVT::i32)); 4736 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4737 DAG.getConstant(1, dl, MVT::i32)); 4738 4739 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4740 // captures the result into a carry flag. 4741 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4742 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4743 4744 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4745 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4746 4747 // Merge the pieces into a single i64 value. 4748 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4749 } 4750 4751 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4752 SDValue TmpOp0, TmpOp1; 4753 bool Invert = false; 4754 bool Swap = false; 4755 unsigned Opc = 0; 4756 4757 SDValue Op0 = Op.getOperand(0); 4758 SDValue Op1 = Op.getOperand(1); 4759 SDValue CC = Op.getOperand(2); 4760 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 4761 EVT VT = Op.getValueType(); 4762 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4763 SDLoc dl(Op); 4764 4765 if (CmpVT.getVectorElementType() == MVT::i64) 4766 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 4767 // but it's possible that our operands are 64-bit but our result is 32-bit. 4768 // Bail in this case. 4769 return SDValue(); 4770 4771 if (Op1.getValueType().isFloatingPoint()) { 4772 switch (SetCCOpcode) { 4773 default: llvm_unreachable("Illegal FP comparison"); 4774 case ISD::SETUNE: 4775 case ISD::SETNE: Invert = true; // Fallthrough 4776 case ISD::SETOEQ: 4777 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4778 case ISD::SETOLT: 4779 case ISD::SETLT: Swap = true; // Fallthrough 4780 case ISD::SETOGT: 4781 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4782 case ISD::SETOLE: 4783 case ISD::SETLE: Swap = true; // Fallthrough 4784 case ISD::SETOGE: 4785 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4786 case ISD::SETUGE: Swap = true; // Fallthrough 4787 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4788 case ISD::SETUGT: Swap = true; // Fallthrough 4789 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4790 case ISD::SETUEQ: Invert = true; // Fallthrough 4791 case ISD::SETONE: 4792 // Expand this to (OLT | OGT). 4793 TmpOp0 = Op0; 4794 TmpOp1 = Op1; 4795 Opc = ISD::OR; 4796 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4797 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 4798 break; 4799 case ISD::SETUO: Invert = true; // Fallthrough 4800 case ISD::SETO: 4801 // Expand this to (OLT | OGE). 4802 TmpOp0 = Op0; 4803 TmpOp1 = Op1; 4804 Opc = ISD::OR; 4805 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4806 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 4807 break; 4808 } 4809 } else { 4810 // Integer comparisons. 4811 switch (SetCCOpcode) { 4812 default: llvm_unreachable("Illegal integer comparison"); 4813 case ISD::SETNE: Invert = true; 4814 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4815 case ISD::SETLT: Swap = true; 4816 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4817 case ISD::SETLE: Swap = true; 4818 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4819 case ISD::SETULT: Swap = true; 4820 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4821 case ISD::SETULE: Swap = true; 4822 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4823 } 4824 4825 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4826 if (Opc == ARMISD::VCEQ) { 4827 4828 SDValue AndOp; 4829 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4830 AndOp = Op0; 4831 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4832 AndOp = Op1; 4833 4834 // Ignore bitconvert. 4835 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4836 AndOp = AndOp.getOperand(0); 4837 4838 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4839 Opc = ARMISD::VTST; 4840 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 4841 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 4842 Invert = !Invert; 4843 } 4844 } 4845 } 4846 4847 if (Swap) 4848 std::swap(Op0, Op1); 4849 4850 // If one of the operands is a constant vector zero, attempt to fold the 4851 // comparison to a specialized compare-against-zero form. 4852 SDValue SingleOp; 4853 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4854 SingleOp = Op0; 4855 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4856 if (Opc == ARMISD::VCGE) 4857 Opc = ARMISD::VCLEZ; 4858 else if (Opc == ARMISD::VCGT) 4859 Opc = ARMISD::VCLTZ; 4860 SingleOp = Op1; 4861 } 4862 4863 SDValue Result; 4864 if (SingleOp.getNode()) { 4865 switch (Opc) { 4866 case ARMISD::VCEQ: 4867 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 4868 case ARMISD::VCGE: 4869 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 4870 case ARMISD::VCLEZ: 4871 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 4872 case ARMISD::VCGT: 4873 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 4874 case ARMISD::VCLTZ: 4875 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 4876 default: 4877 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4878 } 4879 } else { 4880 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4881 } 4882 4883 Result = DAG.getSExtOrTrunc(Result, dl, VT); 4884 4885 if (Invert) 4886 Result = DAG.getNOT(dl, Result, VT); 4887 4888 return Result; 4889 } 4890 4891 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 4892 SDValue LHS = Op.getOperand(0); 4893 SDValue RHS = Op.getOperand(1); 4894 SDValue Carry = Op.getOperand(2); 4895 SDValue Cond = Op.getOperand(3); 4896 SDLoc DL(Op); 4897 4898 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 4899 4900 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 4901 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 4902 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 4903 4904 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 4905 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 4906 SDValue ARMcc = DAG.getConstant( 4907 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 4908 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4909 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 4910 Cmp.getValue(1), SDValue()); 4911 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 4912 CCR, Chain.getValue(1)); 4913 } 4914 4915 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4916 /// valid vector constant for a NEON instruction with a "modified immediate" 4917 /// operand (e.g., VMOV). If so, return the encoded value. 4918 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4919 unsigned SplatBitSize, SelectionDAG &DAG, 4920 SDLoc dl, EVT &VT, bool is128Bits, 4921 NEONModImmType type) { 4922 unsigned OpCmode, Imm; 4923 4924 // SplatBitSize is set to the smallest size that splats the vector, so a 4925 // zero vector will always have SplatBitSize == 8. However, NEON modified 4926 // immediate instructions others than VMOV do not support the 8-bit encoding 4927 // of a zero vector, and the default encoding of zero is supposed to be the 4928 // 32-bit version. 4929 if (SplatBits == 0) 4930 SplatBitSize = 32; 4931 4932 switch (SplatBitSize) { 4933 case 8: 4934 if (type != VMOVModImm) 4935 return SDValue(); 4936 // Any 1-byte value is OK. Op=0, Cmode=1110. 4937 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4938 OpCmode = 0xe; 4939 Imm = SplatBits; 4940 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4941 break; 4942 4943 case 16: 4944 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4945 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4946 if ((SplatBits & ~0xff) == 0) { 4947 // Value = 0x00nn: Op=x, Cmode=100x. 4948 OpCmode = 0x8; 4949 Imm = SplatBits; 4950 break; 4951 } 4952 if ((SplatBits & ~0xff00) == 0) { 4953 // Value = 0xnn00: Op=x, Cmode=101x. 4954 OpCmode = 0xa; 4955 Imm = SplatBits >> 8; 4956 break; 4957 } 4958 return SDValue(); 4959 4960 case 32: 4961 // NEON's 32-bit VMOV supports splat values where: 4962 // * only one byte is nonzero, or 4963 // * the least significant byte is 0xff and the second byte is nonzero, or 4964 // * the least significant 2 bytes are 0xff and the third is nonzero. 4965 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4966 if ((SplatBits & ~0xff) == 0) { 4967 // Value = 0x000000nn: Op=x, Cmode=000x. 4968 OpCmode = 0; 4969 Imm = SplatBits; 4970 break; 4971 } 4972 if ((SplatBits & ~0xff00) == 0) { 4973 // Value = 0x0000nn00: Op=x, Cmode=001x. 4974 OpCmode = 0x2; 4975 Imm = SplatBits >> 8; 4976 break; 4977 } 4978 if ((SplatBits & ~0xff0000) == 0) { 4979 // Value = 0x00nn0000: Op=x, Cmode=010x. 4980 OpCmode = 0x4; 4981 Imm = SplatBits >> 16; 4982 break; 4983 } 4984 if ((SplatBits & ~0xff000000) == 0) { 4985 // Value = 0xnn000000: Op=x, Cmode=011x. 4986 OpCmode = 0x6; 4987 Imm = SplatBits >> 24; 4988 break; 4989 } 4990 4991 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 4992 if (type == OtherModImm) return SDValue(); 4993 4994 if ((SplatBits & ~0xffff) == 0 && 4995 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 4996 // Value = 0x0000nnff: Op=x, Cmode=1100. 4997 OpCmode = 0xc; 4998 Imm = SplatBits >> 8; 4999 break; 5000 } 5001 5002 if ((SplatBits & ~0xffffff) == 0 && 5003 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5004 // Value = 0x00nnffff: Op=x, Cmode=1101. 5005 OpCmode = 0xd; 5006 Imm = SplatBits >> 16; 5007 break; 5008 } 5009 5010 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5011 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5012 // VMOV.I32. A (very) minor optimization would be to replicate the value 5013 // and fall through here to test for a valid 64-bit splat. But, then the 5014 // caller would also need to check and handle the change in size. 5015 return SDValue(); 5016 5017 case 64: { 5018 if (type != VMOVModImm) 5019 return SDValue(); 5020 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5021 uint64_t BitMask = 0xff; 5022 uint64_t Val = 0; 5023 unsigned ImmMask = 1; 5024 Imm = 0; 5025 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5026 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5027 Val |= BitMask; 5028 Imm |= ImmMask; 5029 } else if ((SplatBits & BitMask) != 0) { 5030 return SDValue(); 5031 } 5032 BitMask <<= 8; 5033 ImmMask <<= 1; 5034 } 5035 5036 if (DAG.getDataLayout().isBigEndian()) 5037 // swap higher and lower 32 bit word 5038 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5039 5040 // Op=1, Cmode=1110. 5041 OpCmode = 0x1e; 5042 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5043 break; 5044 } 5045 5046 default: 5047 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5048 } 5049 5050 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5051 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5052 } 5053 5054 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5055 const ARMSubtarget *ST) const { 5056 if (!ST->hasVFP3()) 5057 return SDValue(); 5058 5059 bool IsDouble = Op.getValueType() == MVT::f64; 5060 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5061 5062 // Use the default (constant pool) lowering for double constants when we have 5063 // an SP-only FPU 5064 if (IsDouble && Subtarget->isFPOnlySP()) 5065 return SDValue(); 5066 5067 // Try splatting with a VMOV.f32... 5068 APFloat FPVal = CFP->getValueAPF(); 5069 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5070 5071 if (ImmVal != -1) { 5072 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5073 // We have code in place to select a valid ConstantFP already, no need to 5074 // do any mangling. 5075 return Op; 5076 } 5077 5078 // It's a float and we are trying to use NEON operations where 5079 // possible. Lower it to a splat followed by an extract. 5080 SDLoc DL(Op); 5081 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5082 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5083 NewVal); 5084 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5085 DAG.getConstant(0, DL, MVT::i32)); 5086 } 5087 5088 // The rest of our options are NEON only, make sure that's allowed before 5089 // proceeding.. 5090 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5091 return SDValue(); 5092 5093 EVT VMovVT; 5094 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5095 5096 // It wouldn't really be worth bothering for doubles except for one very 5097 // important value, which does happen to match: 0.0. So make sure we don't do 5098 // anything stupid. 5099 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5100 return SDValue(); 5101 5102 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5103 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5104 VMovVT, false, VMOVModImm); 5105 if (NewVal != SDValue()) { 5106 SDLoc DL(Op); 5107 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5108 NewVal); 5109 if (IsDouble) 5110 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5111 5112 // It's a float: cast and extract a vector element. 5113 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5114 VecConstant); 5115 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5116 DAG.getConstant(0, DL, MVT::i32)); 5117 } 5118 5119 // Finally, try a VMVN.i32 5120 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5121 false, VMVNModImm); 5122 if (NewVal != SDValue()) { 5123 SDLoc DL(Op); 5124 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5125 5126 if (IsDouble) 5127 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5128 5129 // It's a float: cast and extract a vector element. 5130 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5131 VecConstant); 5132 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5133 DAG.getConstant(0, DL, MVT::i32)); 5134 } 5135 5136 return SDValue(); 5137 } 5138 5139 // check if an VEXT instruction can handle the shuffle mask when the 5140 // vector sources of the shuffle are the same. 5141 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5142 unsigned NumElts = VT.getVectorNumElements(); 5143 5144 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5145 if (M[0] < 0) 5146 return false; 5147 5148 Imm = M[0]; 5149 5150 // If this is a VEXT shuffle, the immediate value is the index of the first 5151 // element. The other shuffle indices must be the successive elements after 5152 // the first one. 5153 unsigned ExpectedElt = Imm; 5154 for (unsigned i = 1; i < NumElts; ++i) { 5155 // Increment the expected index. If it wraps around, just follow it 5156 // back to index zero and keep going. 5157 ++ExpectedElt; 5158 if (ExpectedElt == NumElts) 5159 ExpectedElt = 0; 5160 5161 if (M[i] < 0) continue; // ignore UNDEF indices 5162 if (ExpectedElt != static_cast<unsigned>(M[i])) 5163 return false; 5164 } 5165 5166 return true; 5167 } 5168 5169 5170 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5171 bool &ReverseVEXT, unsigned &Imm) { 5172 unsigned NumElts = VT.getVectorNumElements(); 5173 ReverseVEXT = false; 5174 5175 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5176 if (M[0] < 0) 5177 return false; 5178 5179 Imm = M[0]; 5180 5181 // If this is a VEXT shuffle, the immediate value is the index of the first 5182 // element. The other shuffle indices must be the successive elements after 5183 // the first one. 5184 unsigned ExpectedElt = Imm; 5185 for (unsigned i = 1; i < NumElts; ++i) { 5186 // Increment the expected index. If it wraps around, it may still be 5187 // a VEXT but the source vectors must be swapped. 5188 ExpectedElt += 1; 5189 if (ExpectedElt == NumElts * 2) { 5190 ExpectedElt = 0; 5191 ReverseVEXT = true; 5192 } 5193 5194 if (M[i] < 0) continue; // ignore UNDEF indices 5195 if (ExpectedElt != static_cast<unsigned>(M[i])) 5196 return false; 5197 } 5198 5199 // Adjust the index value if the source operands will be swapped. 5200 if (ReverseVEXT) 5201 Imm -= NumElts; 5202 5203 return true; 5204 } 5205 5206 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5207 /// instruction with the specified blocksize. (The order of the elements 5208 /// within each block of the vector is reversed.) 5209 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5210 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5211 "Only possible block sizes for VREV are: 16, 32, 64"); 5212 5213 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5214 if (EltSz == 64) 5215 return false; 5216 5217 unsigned NumElts = VT.getVectorNumElements(); 5218 unsigned BlockElts = M[0] + 1; 5219 // If the first shuffle index is UNDEF, be optimistic. 5220 if (M[0] < 0) 5221 BlockElts = BlockSize / EltSz; 5222 5223 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5224 return false; 5225 5226 for (unsigned i = 0; i < NumElts; ++i) { 5227 if (M[i] < 0) continue; // ignore UNDEF indices 5228 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5229 return false; 5230 } 5231 5232 return true; 5233 } 5234 5235 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5236 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5237 // range, then 0 is placed into the resulting vector. So pretty much any mask 5238 // of 8 elements can work here. 5239 return VT == MVT::v8i8 && M.size() == 8; 5240 } 5241 5242 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5243 // checking that pairs of elements in the shuffle mask represent the same index 5244 // in each vector, incrementing the expected index by 2 at each step. 5245 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5246 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5247 // v2={e,f,g,h} 5248 // WhichResult gives the offset for each element in the mask based on which 5249 // of the two results it belongs to. 5250 // 5251 // The transpose can be represented either as: 5252 // result1 = shufflevector v1, v2, result1_shuffle_mask 5253 // result2 = shufflevector v1, v2, result2_shuffle_mask 5254 // where v1/v2 and the shuffle masks have the same number of elements 5255 // (here WhichResult (see below) indicates which result is being checked) 5256 // 5257 // or as: 5258 // results = shufflevector v1, v2, shuffle_mask 5259 // where both results are returned in one vector and the shuffle mask has twice 5260 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5261 // want to check the low half and high half of the shuffle mask as if it were 5262 // the other case 5263 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5264 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5265 if (EltSz == 64) 5266 return false; 5267 5268 unsigned NumElts = VT.getVectorNumElements(); 5269 if (M.size() != NumElts && M.size() != NumElts*2) 5270 return false; 5271 5272 // If the mask is twice as long as the input vector then we need to check the 5273 // upper and lower parts of the mask with a matching value for WhichResult 5274 // FIXME: A mask with only even values will be rejected in case the first 5275 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5276 // M[0] is used to determine WhichResult 5277 for (unsigned i = 0; i < M.size(); i += NumElts) { 5278 if (M.size() == NumElts * 2) 5279 WhichResult = i / NumElts; 5280 else 5281 WhichResult = M[i] == 0 ? 0 : 1; 5282 for (unsigned j = 0; j < NumElts; j += 2) { 5283 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5284 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5285 return false; 5286 } 5287 } 5288 5289 if (M.size() == NumElts*2) 5290 WhichResult = 0; 5291 5292 return true; 5293 } 5294 5295 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5296 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5297 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5298 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5299 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5300 if (EltSz == 64) 5301 return false; 5302 5303 unsigned NumElts = VT.getVectorNumElements(); 5304 if (M.size() != NumElts && M.size() != NumElts*2) 5305 return false; 5306 5307 for (unsigned i = 0; i < M.size(); i += NumElts) { 5308 if (M.size() == NumElts * 2) 5309 WhichResult = i / NumElts; 5310 else 5311 WhichResult = M[i] == 0 ? 0 : 1; 5312 for (unsigned j = 0; j < NumElts; j += 2) { 5313 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5314 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5315 return false; 5316 } 5317 } 5318 5319 if (M.size() == NumElts*2) 5320 WhichResult = 0; 5321 5322 return true; 5323 } 5324 5325 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5326 // that the mask elements are either all even and in steps of size 2 or all odd 5327 // and in steps of size 2. 5328 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5329 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5330 // v2={e,f,g,h} 5331 // Requires similar checks to that of isVTRNMask with 5332 // respect the how results are returned. 5333 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5334 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5335 if (EltSz == 64) 5336 return false; 5337 5338 unsigned NumElts = VT.getVectorNumElements(); 5339 if (M.size() != NumElts && M.size() != NumElts*2) 5340 return false; 5341 5342 for (unsigned i = 0; i < M.size(); i += NumElts) { 5343 WhichResult = M[i] == 0 ? 0 : 1; 5344 for (unsigned j = 0; j < NumElts; ++j) { 5345 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5346 return false; 5347 } 5348 } 5349 5350 if (M.size() == NumElts*2) 5351 WhichResult = 0; 5352 5353 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5354 if (VT.is64BitVector() && EltSz == 32) 5355 return false; 5356 5357 return true; 5358 } 5359 5360 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5361 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5362 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5363 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5364 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5365 if (EltSz == 64) 5366 return false; 5367 5368 unsigned NumElts = VT.getVectorNumElements(); 5369 if (M.size() != NumElts && M.size() != NumElts*2) 5370 return false; 5371 5372 unsigned Half = NumElts / 2; 5373 for (unsigned i = 0; i < M.size(); i += NumElts) { 5374 WhichResult = M[i] == 0 ? 0 : 1; 5375 for (unsigned j = 0; j < NumElts; j += Half) { 5376 unsigned Idx = WhichResult; 5377 for (unsigned k = 0; k < Half; ++k) { 5378 int MIdx = M[i + j + k]; 5379 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5380 return false; 5381 Idx += 2; 5382 } 5383 } 5384 } 5385 5386 if (M.size() == NumElts*2) 5387 WhichResult = 0; 5388 5389 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5390 if (VT.is64BitVector() && EltSz == 32) 5391 return false; 5392 5393 return true; 5394 } 5395 5396 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5397 // that pairs of elements of the shufflemask represent the same index in each 5398 // vector incrementing sequentially through the vectors. 5399 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5400 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5401 // v2={e,f,g,h} 5402 // Requires similar checks to that of isVTRNMask with respect the how results 5403 // are returned. 5404 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5405 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5406 if (EltSz == 64) 5407 return false; 5408 5409 unsigned NumElts = VT.getVectorNumElements(); 5410 if (M.size() != NumElts && M.size() != NumElts*2) 5411 return false; 5412 5413 for (unsigned i = 0; i < M.size(); i += NumElts) { 5414 WhichResult = M[i] == 0 ? 0 : 1; 5415 unsigned Idx = WhichResult * NumElts / 2; 5416 for (unsigned j = 0; j < NumElts; j += 2) { 5417 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5418 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5419 return false; 5420 Idx += 1; 5421 } 5422 } 5423 5424 if (M.size() == NumElts*2) 5425 WhichResult = 0; 5426 5427 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5428 if (VT.is64BitVector() && EltSz == 32) 5429 return false; 5430 5431 return true; 5432 } 5433 5434 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5435 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5436 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5437 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5438 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5439 if (EltSz == 64) 5440 return false; 5441 5442 unsigned NumElts = VT.getVectorNumElements(); 5443 if (M.size() != NumElts && M.size() != NumElts*2) 5444 return false; 5445 5446 for (unsigned i = 0; i < M.size(); i += NumElts) { 5447 WhichResult = M[i] == 0 ? 0 : 1; 5448 unsigned Idx = WhichResult * NumElts / 2; 5449 for (unsigned j = 0; j < NumElts; j += 2) { 5450 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5451 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5452 return false; 5453 Idx += 1; 5454 } 5455 } 5456 5457 if (M.size() == NumElts*2) 5458 WhichResult = 0; 5459 5460 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5461 if (VT.is64BitVector() && EltSz == 32) 5462 return false; 5463 5464 return true; 5465 } 5466 5467 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5468 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5469 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5470 unsigned &WhichResult, 5471 bool &isV_UNDEF) { 5472 isV_UNDEF = false; 5473 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5474 return ARMISD::VTRN; 5475 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5476 return ARMISD::VUZP; 5477 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5478 return ARMISD::VZIP; 5479 5480 isV_UNDEF = true; 5481 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5482 return ARMISD::VTRN; 5483 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5484 return ARMISD::VUZP; 5485 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5486 return ARMISD::VZIP; 5487 5488 return 0; 5489 } 5490 5491 /// \return true if this is a reverse operation on an vector. 5492 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5493 unsigned NumElts = VT.getVectorNumElements(); 5494 // Make sure the mask has the right size. 5495 if (NumElts != M.size()) 5496 return false; 5497 5498 // Look for <15, ..., 3, -1, 1, 0>. 5499 for (unsigned i = 0; i != NumElts; ++i) 5500 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5501 return false; 5502 5503 return true; 5504 } 5505 5506 // If N is an integer constant that can be moved into a register in one 5507 // instruction, return an SDValue of such a constant (will become a MOV 5508 // instruction). Otherwise return null. 5509 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5510 const ARMSubtarget *ST, SDLoc dl) { 5511 uint64_t Val; 5512 if (!isa<ConstantSDNode>(N)) 5513 return SDValue(); 5514 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5515 5516 if (ST->isThumb1Only()) { 5517 if (Val <= 255 || ~Val <= 255) 5518 return DAG.getConstant(Val, dl, MVT::i32); 5519 } else { 5520 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5521 return DAG.getConstant(Val, dl, MVT::i32); 5522 } 5523 return SDValue(); 5524 } 5525 5526 // If this is a case we can't handle, return null and let the default 5527 // expansion code take care of it. 5528 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5529 const ARMSubtarget *ST) const { 5530 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5531 SDLoc dl(Op); 5532 EVT VT = Op.getValueType(); 5533 5534 APInt SplatBits, SplatUndef; 5535 unsigned SplatBitSize; 5536 bool HasAnyUndefs; 5537 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5538 if (SplatBitSize <= 64) { 5539 // Check if an immediate VMOV works. 5540 EVT VmovVT; 5541 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5542 SplatUndef.getZExtValue(), SplatBitSize, 5543 DAG, dl, VmovVT, VT.is128BitVector(), 5544 VMOVModImm); 5545 if (Val.getNode()) { 5546 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5547 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5548 } 5549 5550 // Try an immediate VMVN. 5551 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5552 Val = isNEONModifiedImm(NegatedImm, 5553 SplatUndef.getZExtValue(), SplatBitSize, 5554 DAG, dl, VmovVT, VT.is128BitVector(), 5555 VMVNModImm); 5556 if (Val.getNode()) { 5557 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5558 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5559 } 5560 5561 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5562 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5563 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5564 if (ImmVal != -1) { 5565 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5566 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5567 } 5568 } 5569 } 5570 } 5571 5572 // Scan through the operands to see if only one value is used. 5573 // 5574 // As an optimisation, even if more than one value is used it may be more 5575 // profitable to splat with one value then change some lanes. 5576 // 5577 // Heuristically we decide to do this if the vector has a "dominant" value, 5578 // defined as splatted to more than half of the lanes. 5579 unsigned NumElts = VT.getVectorNumElements(); 5580 bool isOnlyLowElement = true; 5581 bool usesOnlyOneValue = true; 5582 bool hasDominantValue = false; 5583 bool isConstant = true; 5584 5585 // Map of the number of times a particular SDValue appears in the 5586 // element list. 5587 DenseMap<SDValue, unsigned> ValueCounts; 5588 SDValue Value; 5589 for (unsigned i = 0; i < NumElts; ++i) { 5590 SDValue V = Op.getOperand(i); 5591 if (V.isUndef()) 5592 continue; 5593 if (i > 0) 5594 isOnlyLowElement = false; 5595 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5596 isConstant = false; 5597 5598 ValueCounts.insert(std::make_pair(V, 0)); 5599 unsigned &Count = ValueCounts[V]; 5600 5601 // Is this value dominant? (takes up more than half of the lanes) 5602 if (++Count > (NumElts / 2)) { 5603 hasDominantValue = true; 5604 Value = V; 5605 } 5606 } 5607 if (ValueCounts.size() != 1) 5608 usesOnlyOneValue = false; 5609 if (!Value.getNode() && ValueCounts.size() > 0) 5610 Value = ValueCounts.begin()->first; 5611 5612 if (ValueCounts.size() == 0) 5613 return DAG.getUNDEF(VT); 5614 5615 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5616 // Keep going if we are hitting this case. 5617 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5618 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5619 5620 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5621 5622 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5623 // i32 and try again. 5624 if (hasDominantValue && EltSize <= 32) { 5625 if (!isConstant) { 5626 SDValue N; 5627 5628 // If we are VDUPing a value that comes directly from a vector, that will 5629 // cause an unnecessary move to and from a GPR, where instead we could 5630 // just use VDUPLANE. We can only do this if the lane being extracted 5631 // is at a constant index, as the VDUP from lane instructions only have 5632 // constant-index forms. 5633 ConstantSDNode *constIndex; 5634 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5635 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5636 // We need to create a new undef vector to use for the VDUPLANE if the 5637 // size of the vector from which we get the value is different than the 5638 // size of the vector that we need to create. We will insert the element 5639 // such that the register coalescer will remove unnecessary copies. 5640 if (VT != Value->getOperand(0).getValueType()) { 5641 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5642 VT.getVectorNumElements(); 5643 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5644 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5645 Value, DAG.getConstant(index, dl, MVT::i32)), 5646 DAG.getConstant(index, dl, MVT::i32)); 5647 } else 5648 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5649 Value->getOperand(0), Value->getOperand(1)); 5650 } else 5651 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5652 5653 if (!usesOnlyOneValue) { 5654 // The dominant value was splatted as 'N', but we now have to insert 5655 // all differing elements. 5656 for (unsigned I = 0; I < NumElts; ++I) { 5657 if (Op.getOperand(I) == Value) 5658 continue; 5659 SmallVector<SDValue, 3> Ops; 5660 Ops.push_back(N); 5661 Ops.push_back(Op.getOperand(I)); 5662 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5663 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5664 } 5665 } 5666 return N; 5667 } 5668 if (VT.getVectorElementType().isFloatingPoint()) { 5669 SmallVector<SDValue, 8> Ops; 5670 for (unsigned i = 0; i < NumElts; ++i) 5671 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5672 Op.getOperand(i))); 5673 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5674 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 5675 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5676 if (Val.getNode()) 5677 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5678 } 5679 if (usesOnlyOneValue) { 5680 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5681 if (isConstant && Val.getNode()) 5682 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5683 } 5684 } 5685 5686 // If all elements are constants and the case above didn't get hit, fall back 5687 // to the default expansion, which will generate a load from the constant 5688 // pool. 5689 if (isConstant) 5690 return SDValue(); 5691 5692 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5693 if (NumElts >= 4) { 5694 SDValue shuffle = ReconstructShuffle(Op, DAG); 5695 if (shuffle != SDValue()) 5696 return shuffle; 5697 } 5698 5699 // Vectors with 32- or 64-bit elements can be built by directly assigning 5700 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5701 // will be legalized. 5702 if (EltSize >= 32) { 5703 // Do the expansion with floating-point types, since that is what the VFP 5704 // registers are defined to use, and since i64 is not legal. 5705 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5706 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5707 SmallVector<SDValue, 8> Ops; 5708 for (unsigned i = 0; i < NumElts; ++i) 5709 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5710 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5711 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5712 } 5713 5714 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5715 // know the default expansion would otherwise fall back on something even 5716 // worse. For a vector with one or two non-undef values, that's 5717 // scalar_to_vector for the elements followed by a shuffle (provided the 5718 // shuffle is valid for the target) and materialization element by element 5719 // on the stack followed by a load for everything else. 5720 if (!isConstant && !usesOnlyOneValue) { 5721 SDValue Vec = DAG.getUNDEF(VT); 5722 for (unsigned i = 0 ; i < NumElts; ++i) { 5723 SDValue V = Op.getOperand(i); 5724 if (V.isUndef()) 5725 continue; 5726 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5727 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5728 } 5729 return Vec; 5730 } 5731 5732 return SDValue(); 5733 } 5734 5735 // Gather data to see if the operation can be modelled as a 5736 // shuffle in combination with VEXTs. 5737 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5738 SelectionDAG &DAG) const { 5739 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5740 SDLoc dl(Op); 5741 EVT VT = Op.getValueType(); 5742 unsigned NumElts = VT.getVectorNumElements(); 5743 5744 struct ShuffleSourceInfo { 5745 SDValue Vec; 5746 unsigned MinElt; 5747 unsigned MaxElt; 5748 5749 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5750 // be compatible with the shuffle we intend to construct. As a result 5751 // ShuffleVec will be some sliding window into the original Vec. 5752 SDValue ShuffleVec; 5753 5754 // Code should guarantee that element i in Vec starts at element "WindowBase 5755 // + i * WindowScale in ShuffleVec". 5756 int WindowBase; 5757 int WindowScale; 5758 5759 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5760 ShuffleSourceInfo(SDValue Vec) 5761 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5762 WindowScale(1) {} 5763 }; 5764 5765 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5766 // node. 5767 SmallVector<ShuffleSourceInfo, 2> Sources; 5768 for (unsigned i = 0; i < NumElts; ++i) { 5769 SDValue V = Op.getOperand(i); 5770 if (V.isUndef()) 5771 continue; 5772 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5773 // A shuffle can only come from building a vector from various 5774 // elements of other vectors. 5775 return SDValue(); 5776 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 5777 // Furthermore, shuffles require a constant mask, whereas extractelts 5778 // accept variable indices. 5779 return SDValue(); 5780 } 5781 5782 // Add this element source to the list if it's not already there. 5783 SDValue SourceVec = V.getOperand(0); 5784 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 5785 if (Source == Sources.end()) 5786 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5787 5788 // Update the minimum and maximum lane number seen. 5789 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5790 Source->MinElt = std::min(Source->MinElt, EltNo); 5791 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5792 } 5793 5794 // Currently only do something sane when at most two source vectors 5795 // are involved. 5796 if (Sources.size() > 2) 5797 return SDValue(); 5798 5799 // Find out the smallest element size among result and two sources, and use 5800 // it as element size to build the shuffle_vector. 5801 EVT SmallestEltTy = VT.getVectorElementType(); 5802 for (auto &Source : Sources) { 5803 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5804 if (SrcEltTy.bitsLT(SmallestEltTy)) 5805 SmallestEltTy = SrcEltTy; 5806 } 5807 unsigned ResMultiplier = 5808 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5809 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5810 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5811 5812 // If the source vector is too wide or too narrow, we may nevertheless be able 5813 // to construct a compatible shuffle either by concatenating it with UNDEF or 5814 // extracting a suitable range of elements. 5815 for (auto &Src : Sources) { 5816 EVT SrcVT = Src.ShuffleVec.getValueType(); 5817 5818 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5819 continue; 5820 5821 // This stage of the search produces a source with the same element type as 5822 // the original, but with a total width matching the BUILD_VECTOR output. 5823 EVT EltVT = SrcVT.getVectorElementType(); 5824 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5825 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5826 5827 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5828 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 5829 return SDValue(); 5830 // We can pad out the smaller vector for free, so if it's part of a 5831 // shuffle... 5832 Src.ShuffleVec = 5833 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5834 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5835 continue; 5836 } 5837 5838 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 5839 return SDValue(); 5840 5841 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5842 // Span too large for a VEXT to cope 5843 return SDValue(); 5844 } 5845 5846 if (Src.MinElt >= NumSrcElts) { 5847 // The extraction can just take the second half 5848 Src.ShuffleVec = 5849 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5850 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5851 Src.WindowBase = -NumSrcElts; 5852 } else if (Src.MaxElt < NumSrcElts) { 5853 // The extraction can just take the first half 5854 Src.ShuffleVec = 5855 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5856 DAG.getConstant(0, dl, MVT::i32)); 5857 } else { 5858 // An actual VEXT is needed 5859 SDValue VEXTSrc1 = 5860 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5861 DAG.getConstant(0, dl, MVT::i32)); 5862 SDValue VEXTSrc2 = 5863 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5864 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5865 5866 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 5867 VEXTSrc2, 5868 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 5869 Src.WindowBase = -Src.MinElt; 5870 } 5871 } 5872 5873 // Another possible incompatibility occurs from the vector element types. We 5874 // can fix this by bitcasting the source vectors to the same type we intend 5875 // for the shuffle. 5876 for (auto &Src : Sources) { 5877 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5878 if (SrcEltTy == SmallestEltTy) 5879 continue; 5880 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5881 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5882 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5883 Src.WindowBase *= Src.WindowScale; 5884 } 5885 5886 // Final sanity check before we try to actually produce a shuffle. 5887 DEBUG( 5888 for (auto Src : Sources) 5889 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5890 ); 5891 5892 // The stars all align, our next step is to produce the mask for the shuffle. 5893 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5894 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5895 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5896 SDValue Entry = Op.getOperand(i); 5897 if (Entry.isUndef()) 5898 continue; 5899 5900 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5901 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5902 5903 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5904 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5905 // segment. 5906 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5907 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5908 VT.getVectorElementType().getSizeInBits()); 5909 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5910 5911 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5912 // starting at the appropriate offset. 5913 int *LaneMask = &Mask[i * ResMultiplier]; 5914 5915 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5916 ExtractBase += NumElts * (Src - Sources.begin()); 5917 for (int j = 0; j < LanesDefined; ++j) 5918 LaneMask[j] = ExtractBase + j; 5919 } 5920 5921 // Final check before we try to produce nonsense... 5922 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5923 return SDValue(); 5924 5925 // We can't handle more than two sources. This should have already 5926 // been checked before this point. 5927 assert(Sources.size() <= 2 && "Too many sources!"); 5928 5929 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5930 for (unsigned i = 0; i < Sources.size(); ++i) 5931 ShuffleOps[i] = Sources[i].ShuffleVec; 5932 5933 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5934 ShuffleOps[1], &Mask[0]); 5935 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5936 } 5937 5938 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5939 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5940 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5941 /// are assumed to be legal. 5942 bool 5943 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5944 EVT VT) const { 5945 if (VT.getVectorNumElements() == 4 && 5946 (VT.is128BitVector() || VT.is64BitVector())) { 5947 unsigned PFIndexes[4]; 5948 for (unsigned i = 0; i != 4; ++i) { 5949 if (M[i] < 0) 5950 PFIndexes[i] = 8; 5951 else 5952 PFIndexes[i] = M[i]; 5953 } 5954 5955 // Compute the index in the perfect shuffle table. 5956 unsigned PFTableIndex = 5957 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5958 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5959 unsigned Cost = (PFEntry >> 30); 5960 5961 if (Cost <= 4) 5962 return true; 5963 } 5964 5965 bool ReverseVEXT, isV_UNDEF; 5966 unsigned Imm, WhichResult; 5967 5968 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5969 return (EltSize >= 32 || 5970 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5971 isVREVMask(M, VT, 64) || 5972 isVREVMask(M, VT, 32) || 5973 isVREVMask(M, VT, 16) || 5974 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5975 isVTBLMask(M, VT) || 5976 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 5977 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5978 } 5979 5980 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5981 /// the specified operations to build the shuffle. 5982 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5983 SDValue RHS, SelectionDAG &DAG, 5984 SDLoc dl) { 5985 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5986 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5987 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5988 5989 enum { 5990 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5991 OP_VREV, 5992 OP_VDUP0, 5993 OP_VDUP1, 5994 OP_VDUP2, 5995 OP_VDUP3, 5996 OP_VEXT1, 5997 OP_VEXT2, 5998 OP_VEXT3, 5999 OP_VUZPL, // VUZP, left result 6000 OP_VUZPR, // VUZP, right result 6001 OP_VZIPL, // VZIP, left result 6002 OP_VZIPR, // VZIP, right result 6003 OP_VTRNL, // VTRN, left result 6004 OP_VTRNR // VTRN, right result 6005 }; 6006 6007 if (OpNum == OP_COPY) { 6008 if (LHSID == (1*9+2)*9+3) return LHS; 6009 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6010 return RHS; 6011 } 6012 6013 SDValue OpLHS, OpRHS; 6014 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6015 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6016 EVT VT = OpLHS.getValueType(); 6017 6018 switch (OpNum) { 6019 default: llvm_unreachable("Unknown shuffle opcode!"); 6020 case OP_VREV: 6021 // VREV divides the vector in half and swaps within the half. 6022 if (VT.getVectorElementType() == MVT::i32 || 6023 VT.getVectorElementType() == MVT::f32) 6024 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6025 // vrev <4 x i16> -> VREV32 6026 if (VT.getVectorElementType() == MVT::i16) 6027 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6028 // vrev <4 x i8> -> VREV16 6029 assert(VT.getVectorElementType() == MVT::i8); 6030 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6031 case OP_VDUP0: 6032 case OP_VDUP1: 6033 case OP_VDUP2: 6034 case OP_VDUP3: 6035 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6036 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6037 case OP_VEXT1: 6038 case OP_VEXT2: 6039 case OP_VEXT3: 6040 return DAG.getNode(ARMISD::VEXT, dl, VT, 6041 OpLHS, OpRHS, 6042 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6043 case OP_VUZPL: 6044 case OP_VUZPR: 6045 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6046 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6047 case OP_VZIPL: 6048 case OP_VZIPR: 6049 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6050 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6051 case OP_VTRNL: 6052 case OP_VTRNR: 6053 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6054 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6055 } 6056 } 6057 6058 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6059 ArrayRef<int> ShuffleMask, 6060 SelectionDAG &DAG) { 6061 // Check to see if we can use the VTBL instruction. 6062 SDValue V1 = Op.getOperand(0); 6063 SDValue V2 = Op.getOperand(1); 6064 SDLoc DL(Op); 6065 6066 SmallVector<SDValue, 8> VTBLMask; 6067 for (ArrayRef<int>::iterator 6068 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6069 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6070 6071 if (V2.getNode()->isUndef()) 6072 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6073 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6074 6075 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6076 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6077 } 6078 6079 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6080 SelectionDAG &DAG) { 6081 SDLoc DL(Op); 6082 SDValue OpLHS = Op.getOperand(0); 6083 EVT VT = OpLHS.getValueType(); 6084 6085 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6086 "Expect an v8i16/v16i8 type"); 6087 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6088 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6089 // extract the first 8 bytes into the top double word and the last 8 bytes 6090 // into the bottom double word. The v8i16 case is similar. 6091 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6092 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6093 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6094 } 6095 6096 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6097 SDValue V1 = Op.getOperand(0); 6098 SDValue V2 = Op.getOperand(1); 6099 SDLoc dl(Op); 6100 EVT VT = Op.getValueType(); 6101 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6102 6103 // Convert shuffles that are directly supported on NEON to target-specific 6104 // DAG nodes, instead of keeping them as shuffles and matching them again 6105 // during code selection. This is more efficient and avoids the possibility 6106 // of inconsistencies between legalization and selection. 6107 // FIXME: floating-point vectors should be canonicalized to integer vectors 6108 // of the same time so that they get CSEd properly. 6109 ArrayRef<int> ShuffleMask = SVN->getMask(); 6110 6111 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6112 if (EltSize <= 32) { 6113 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 6114 int Lane = SVN->getSplatIndex(); 6115 // If this is undef splat, generate it via "just" vdup, if possible. 6116 if (Lane == -1) Lane = 0; 6117 6118 // Test if V1 is a SCALAR_TO_VECTOR. 6119 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6120 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6121 } 6122 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6123 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6124 // reaches it). 6125 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6126 !isa<ConstantSDNode>(V1.getOperand(0))) { 6127 bool IsScalarToVector = true; 6128 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6129 if (!V1.getOperand(i).isUndef()) { 6130 IsScalarToVector = false; 6131 break; 6132 } 6133 if (IsScalarToVector) 6134 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6135 } 6136 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6137 DAG.getConstant(Lane, dl, MVT::i32)); 6138 } 6139 6140 bool ReverseVEXT; 6141 unsigned Imm; 6142 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6143 if (ReverseVEXT) 6144 std::swap(V1, V2); 6145 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6146 DAG.getConstant(Imm, dl, MVT::i32)); 6147 } 6148 6149 if (isVREVMask(ShuffleMask, VT, 64)) 6150 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6151 if (isVREVMask(ShuffleMask, VT, 32)) 6152 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6153 if (isVREVMask(ShuffleMask, VT, 16)) 6154 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6155 6156 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6157 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6158 DAG.getConstant(Imm, dl, MVT::i32)); 6159 } 6160 6161 // Check for Neon shuffles that modify both input vectors in place. 6162 // If both results are used, i.e., if there are two shuffles with the same 6163 // source operands and with masks corresponding to both results of one of 6164 // these operations, DAG memoization will ensure that a single node is 6165 // used for both shuffles. 6166 unsigned WhichResult; 6167 bool isV_UNDEF; 6168 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6169 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6170 if (isV_UNDEF) 6171 V2 = V1; 6172 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6173 .getValue(WhichResult); 6174 } 6175 6176 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6177 // shuffles that produce a result larger than their operands with: 6178 // shuffle(concat(v1, undef), concat(v2, undef)) 6179 // -> 6180 // shuffle(concat(v1, v2), undef) 6181 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6182 // 6183 // This is useful in the general case, but there are special cases where 6184 // native shuffles produce larger results: the two-result ops. 6185 // 6186 // Look through the concat when lowering them: 6187 // shuffle(concat(v1, v2), undef) 6188 // -> 6189 // concat(VZIP(v1, v2):0, :1) 6190 // 6191 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6192 SDValue SubV1 = V1->getOperand(0); 6193 SDValue SubV2 = V1->getOperand(1); 6194 EVT SubVT = SubV1.getValueType(); 6195 6196 // We expect these to have been canonicalized to -1. 6197 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) { 6198 return i < (int)VT.getVectorNumElements(); 6199 }) && "Unexpected shuffle index into UNDEF operand!"); 6200 6201 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6202 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6203 if (isV_UNDEF) 6204 SubV2 = SubV1; 6205 assert((WhichResult == 0) && 6206 "In-place shuffle of concat can only have one result!"); 6207 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6208 SubV1, SubV2); 6209 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6210 Res.getValue(1)); 6211 } 6212 } 6213 } 6214 6215 // If the shuffle is not directly supported and it has 4 elements, use 6216 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6217 unsigned NumElts = VT.getVectorNumElements(); 6218 if (NumElts == 4) { 6219 unsigned PFIndexes[4]; 6220 for (unsigned i = 0; i != 4; ++i) { 6221 if (ShuffleMask[i] < 0) 6222 PFIndexes[i] = 8; 6223 else 6224 PFIndexes[i] = ShuffleMask[i]; 6225 } 6226 6227 // Compute the index in the perfect shuffle table. 6228 unsigned PFTableIndex = 6229 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6230 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6231 unsigned Cost = (PFEntry >> 30); 6232 6233 if (Cost <= 4) 6234 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6235 } 6236 6237 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6238 if (EltSize >= 32) { 6239 // Do the expansion with floating-point types, since that is what the VFP 6240 // registers are defined to use, and since i64 is not legal. 6241 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6242 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6243 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6244 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6245 SmallVector<SDValue, 8> Ops; 6246 for (unsigned i = 0; i < NumElts; ++i) { 6247 if (ShuffleMask[i] < 0) 6248 Ops.push_back(DAG.getUNDEF(EltVT)); 6249 else 6250 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6251 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6252 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6253 dl, MVT::i32))); 6254 } 6255 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6256 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6257 } 6258 6259 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6260 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6261 6262 if (VT == MVT::v8i8) 6263 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6264 return NewOp; 6265 6266 return SDValue(); 6267 } 6268 6269 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6270 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6271 SDValue Lane = Op.getOperand(2); 6272 if (!isa<ConstantSDNode>(Lane)) 6273 return SDValue(); 6274 6275 return Op; 6276 } 6277 6278 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6279 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6280 SDValue Lane = Op.getOperand(1); 6281 if (!isa<ConstantSDNode>(Lane)) 6282 return SDValue(); 6283 6284 SDValue Vec = Op.getOperand(0); 6285 if (Op.getValueType() == MVT::i32 && 6286 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6287 SDLoc dl(Op); 6288 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6289 } 6290 6291 return Op; 6292 } 6293 6294 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6295 // The only time a CONCAT_VECTORS operation can have legal types is when 6296 // two 64-bit vectors are concatenated to a 128-bit vector. 6297 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6298 "unexpected CONCAT_VECTORS"); 6299 SDLoc dl(Op); 6300 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6301 SDValue Op0 = Op.getOperand(0); 6302 SDValue Op1 = Op.getOperand(1); 6303 if (!Op0.isUndef()) 6304 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6305 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6306 DAG.getIntPtrConstant(0, dl)); 6307 if (!Op1.isUndef()) 6308 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6309 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6310 DAG.getIntPtrConstant(1, dl)); 6311 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6312 } 6313 6314 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6315 /// element has been zero/sign-extended, depending on the isSigned parameter, 6316 /// from an integer type half its size. 6317 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6318 bool isSigned) { 6319 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6320 EVT VT = N->getValueType(0); 6321 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6322 SDNode *BVN = N->getOperand(0).getNode(); 6323 if (BVN->getValueType(0) != MVT::v4i32 || 6324 BVN->getOpcode() != ISD::BUILD_VECTOR) 6325 return false; 6326 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6327 unsigned HiElt = 1 - LoElt; 6328 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6329 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6330 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6331 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6332 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6333 return false; 6334 if (isSigned) { 6335 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6336 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6337 return true; 6338 } else { 6339 if (Hi0->isNullValue() && Hi1->isNullValue()) 6340 return true; 6341 } 6342 return false; 6343 } 6344 6345 if (N->getOpcode() != ISD::BUILD_VECTOR) 6346 return false; 6347 6348 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6349 SDNode *Elt = N->getOperand(i).getNode(); 6350 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6351 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6352 unsigned HalfSize = EltSize / 2; 6353 if (isSigned) { 6354 if (!isIntN(HalfSize, C->getSExtValue())) 6355 return false; 6356 } else { 6357 if (!isUIntN(HalfSize, C->getZExtValue())) 6358 return false; 6359 } 6360 continue; 6361 } 6362 return false; 6363 } 6364 6365 return true; 6366 } 6367 6368 /// isSignExtended - Check if a node is a vector value that is sign-extended 6369 /// or a constant BUILD_VECTOR with sign-extended elements. 6370 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6371 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6372 return true; 6373 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6374 return true; 6375 return false; 6376 } 6377 6378 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6379 /// or a constant BUILD_VECTOR with zero-extended elements. 6380 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6381 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6382 return true; 6383 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6384 return true; 6385 return false; 6386 } 6387 6388 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6389 if (OrigVT.getSizeInBits() >= 64) 6390 return OrigVT; 6391 6392 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6393 6394 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6395 switch (OrigSimpleTy) { 6396 default: llvm_unreachable("Unexpected Vector Type"); 6397 case MVT::v2i8: 6398 case MVT::v2i16: 6399 return MVT::v2i32; 6400 case MVT::v4i8: 6401 return MVT::v4i16; 6402 } 6403 } 6404 6405 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6406 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6407 /// We insert the required extension here to get the vector to fill a D register. 6408 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6409 const EVT &OrigTy, 6410 const EVT &ExtTy, 6411 unsigned ExtOpcode) { 6412 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6413 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6414 // 64-bits we need to insert a new extension so that it will be 64-bits. 6415 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6416 if (OrigTy.getSizeInBits() >= 64) 6417 return N; 6418 6419 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6420 EVT NewVT = getExtensionTo64Bits(OrigTy); 6421 6422 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6423 } 6424 6425 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6426 /// does not do any sign/zero extension. If the original vector is less 6427 /// than 64 bits, an appropriate extension will be added after the load to 6428 /// reach a total size of 64 bits. We have to add the extension separately 6429 /// because ARM does not have a sign/zero extending load for vectors. 6430 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6431 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6432 6433 // The load already has the right type. 6434 if (ExtendedTy == LD->getMemoryVT()) 6435 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6436 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 6437 LD->isNonTemporal(), LD->isInvariant(), 6438 LD->getAlignment()); 6439 6440 // We need to create a zextload/sextload. We cannot just create a load 6441 // followed by a zext/zext node because LowerMUL is also run during normal 6442 // operation legalization where we can't create illegal types. 6443 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6444 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6445 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 6446 LD->isNonTemporal(), LD->getAlignment()); 6447 } 6448 6449 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6450 /// extending load, or BUILD_VECTOR with extended elements, return the 6451 /// unextended value. The unextended vector should be 64 bits so that it can 6452 /// be used as an operand to a VMULL instruction. If the original vector size 6453 /// before extension is less than 64 bits we add a an extension to resize 6454 /// the vector to 64 bits. 6455 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6456 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6457 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6458 N->getOperand(0)->getValueType(0), 6459 N->getValueType(0), 6460 N->getOpcode()); 6461 6462 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6463 return SkipLoadExtensionForVMULL(LD, DAG); 6464 6465 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6466 // have been legalized as a BITCAST from v4i32. 6467 if (N->getOpcode() == ISD::BITCAST) { 6468 SDNode *BVN = N->getOperand(0).getNode(); 6469 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6470 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6471 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6472 return DAG.getBuildVector( 6473 MVT::v2i32, SDLoc(N), 6474 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 6475 } 6476 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6477 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6478 EVT VT = N->getValueType(0); 6479 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6480 unsigned NumElts = VT.getVectorNumElements(); 6481 MVT TruncVT = MVT::getIntegerVT(EltSize); 6482 SmallVector<SDValue, 8> Ops; 6483 SDLoc dl(N); 6484 for (unsigned i = 0; i != NumElts; ++i) { 6485 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6486 const APInt &CInt = C->getAPIntValue(); 6487 // Element types smaller than 32 bits are not legal, so use i32 elements. 6488 // The values are implicitly truncated so sext vs. zext doesn't matter. 6489 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6490 } 6491 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 6492 } 6493 6494 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6495 unsigned Opcode = N->getOpcode(); 6496 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6497 SDNode *N0 = N->getOperand(0).getNode(); 6498 SDNode *N1 = N->getOperand(1).getNode(); 6499 return N0->hasOneUse() && N1->hasOneUse() && 6500 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6501 } 6502 return false; 6503 } 6504 6505 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6506 unsigned Opcode = N->getOpcode(); 6507 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6508 SDNode *N0 = N->getOperand(0).getNode(); 6509 SDNode *N1 = N->getOperand(1).getNode(); 6510 return N0->hasOneUse() && N1->hasOneUse() && 6511 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6512 } 6513 return false; 6514 } 6515 6516 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6517 // Multiplications are only custom-lowered for 128-bit vectors so that 6518 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6519 EVT VT = Op.getValueType(); 6520 assert(VT.is128BitVector() && VT.isInteger() && 6521 "unexpected type for custom-lowering ISD::MUL"); 6522 SDNode *N0 = Op.getOperand(0).getNode(); 6523 SDNode *N1 = Op.getOperand(1).getNode(); 6524 unsigned NewOpc = 0; 6525 bool isMLA = false; 6526 bool isN0SExt = isSignExtended(N0, DAG); 6527 bool isN1SExt = isSignExtended(N1, DAG); 6528 if (isN0SExt && isN1SExt) 6529 NewOpc = ARMISD::VMULLs; 6530 else { 6531 bool isN0ZExt = isZeroExtended(N0, DAG); 6532 bool isN1ZExt = isZeroExtended(N1, DAG); 6533 if (isN0ZExt && isN1ZExt) 6534 NewOpc = ARMISD::VMULLu; 6535 else if (isN1SExt || isN1ZExt) { 6536 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6537 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6538 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6539 NewOpc = ARMISD::VMULLs; 6540 isMLA = true; 6541 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6542 NewOpc = ARMISD::VMULLu; 6543 isMLA = true; 6544 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6545 std::swap(N0, N1); 6546 NewOpc = ARMISD::VMULLu; 6547 isMLA = true; 6548 } 6549 } 6550 6551 if (!NewOpc) { 6552 if (VT == MVT::v2i64) 6553 // Fall through to expand this. It is not legal. 6554 return SDValue(); 6555 else 6556 // Other vector multiplications are legal. 6557 return Op; 6558 } 6559 } 6560 6561 // Legalize to a VMULL instruction. 6562 SDLoc DL(Op); 6563 SDValue Op0; 6564 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6565 if (!isMLA) { 6566 Op0 = SkipExtensionForVMULL(N0, DAG); 6567 assert(Op0.getValueType().is64BitVector() && 6568 Op1.getValueType().is64BitVector() && 6569 "unexpected types for extended operands to VMULL"); 6570 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6571 } 6572 6573 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6574 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6575 // vmull q0, d4, d6 6576 // vmlal q0, d5, d6 6577 // is faster than 6578 // vaddl q0, d4, d5 6579 // vmovl q1, d6 6580 // vmul q0, q0, q1 6581 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6582 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6583 EVT Op1VT = Op1.getValueType(); 6584 return DAG.getNode(N0->getOpcode(), DL, VT, 6585 DAG.getNode(NewOpc, DL, VT, 6586 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6587 DAG.getNode(NewOpc, DL, VT, 6588 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6589 } 6590 6591 static SDValue 6592 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 6593 // TODO: Should this propagate fast-math-flags? 6594 6595 // Convert to float 6596 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6597 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6598 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6599 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6600 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6601 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6602 // Get reciprocal estimate. 6603 // float4 recip = vrecpeq_f32(yf); 6604 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6605 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6606 Y); 6607 // Because char has a smaller range than uchar, we can actually get away 6608 // without any newton steps. This requires that we use a weird bias 6609 // of 0xb000, however (again, this has been exhaustively tested). 6610 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6611 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6612 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6613 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 6614 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6615 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6616 // Convert back to short. 6617 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6618 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6619 return X; 6620 } 6621 6622 static SDValue 6623 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 6624 // TODO: Should this propagate fast-math-flags? 6625 6626 SDValue N2; 6627 // Convert to float. 6628 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6629 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6630 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6631 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6632 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6633 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6634 6635 // Use reciprocal estimate and one refinement step. 6636 // float4 recip = vrecpeq_f32(yf); 6637 // recip *= vrecpsq_f32(yf, recip); 6638 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6639 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6640 N1); 6641 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6642 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6643 N1, N2); 6644 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6645 // Because short has a smaller range than ushort, we can actually get away 6646 // with only a single newton step. This requires that we use a weird bias 6647 // of 89, however (again, this has been exhaustively tested). 6648 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6649 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6650 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6651 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 6652 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6653 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6654 // Convert back to integer and return. 6655 // return vmovn_s32(vcvt_s32_f32(result)); 6656 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6657 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6658 return N0; 6659 } 6660 6661 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6662 EVT VT = Op.getValueType(); 6663 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6664 "unexpected type for custom-lowering ISD::SDIV"); 6665 6666 SDLoc dl(Op); 6667 SDValue N0 = Op.getOperand(0); 6668 SDValue N1 = Op.getOperand(1); 6669 SDValue N2, N3; 6670 6671 if (VT == MVT::v8i8) { 6672 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6673 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6674 6675 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6676 DAG.getIntPtrConstant(4, dl)); 6677 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6678 DAG.getIntPtrConstant(4, dl)); 6679 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6680 DAG.getIntPtrConstant(0, dl)); 6681 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6682 DAG.getIntPtrConstant(0, dl)); 6683 6684 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6685 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6686 6687 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6688 N0 = LowerCONCAT_VECTORS(N0, DAG); 6689 6690 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6691 return N0; 6692 } 6693 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6694 } 6695 6696 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6697 // TODO: Should this propagate fast-math-flags? 6698 EVT VT = Op.getValueType(); 6699 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6700 "unexpected type for custom-lowering ISD::UDIV"); 6701 6702 SDLoc dl(Op); 6703 SDValue N0 = Op.getOperand(0); 6704 SDValue N1 = Op.getOperand(1); 6705 SDValue N2, N3; 6706 6707 if (VT == MVT::v8i8) { 6708 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6709 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6710 6711 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6712 DAG.getIntPtrConstant(4, dl)); 6713 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6714 DAG.getIntPtrConstant(4, dl)); 6715 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6716 DAG.getIntPtrConstant(0, dl)); 6717 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6718 DAG.getIntPtrConstant(0, dl)); 6719 6720 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6721 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6722 6723 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6724 N0 = LowerCONCAT_VECTORS(N0, DAG); 6725 6726 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6727 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6728 MVT::i32), 6729 N0); 6730 return N0; 6731 } 6732 6733 // v4i16 sdiv ... Convert to float. 6734 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6735 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6736 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6737 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6738 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6739 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6740 6741 // Use reciprocal estimate and two refinement steps. 6742 // float4 recip = vrecpeq_f32(yf); 6743 // recip *= vrecpsq_f32(yf, recip); 6744 // recip *= vrecpsq_f32(yf, recip); 6745 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6746 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6747 BN1); 6748 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6749 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6750 BN1, N2); 6751 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6752 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6753 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6754 BN1, N2); 6755 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6756 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6757 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6758 // and that it will never cause us to return an answer too large). 6759 // float4 result = as_float4(as_int4(xf*recip) + 2); 6760 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6761 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6762 N1 = DAG.getConstant(2, dl, MVT::v4i32); 6763 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6764 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6765 // Convert back to integer and return. 6766 // return vmovn_u32(vcvt_s32_f32(result)); 6767 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6768 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6769 return N0; 6770 } 6771 6772 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6773 EVT VT = Op.getNode()->getValueType(0); 6774 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6775 6776 unsigned Opc; 6777 bool ExtraOp = false; 6778 switch (Op.getOpcode()) { 6779 default: llvm_unreachable("Invalid code"); 6780 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6781 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6782 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6783 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6784 } 6785 6786 if (!ExtraOp) 6787 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6788 Op.getOperand(1)); 6789 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6790 Op.getOperand(1), Op.getOperand(2)); 6791 } 6792 6793 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6794 assert(Subtarget->isTargetDarwin()); 6795 6796 // For iOS, we want to call an alternative entry point: __sincos_stret, 6797 // return values are passed via sret. 6798 SDLoc dl(Op); 6799 SDValue Arg = Op.getOperand(0); 6800 EVT ArgVT = Arg.getValueType(); 6801 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6802 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6803 6804 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6805 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6806 6807 // Pair of floats / doubles used to pass the result. 6808 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6809 auto &DL = DAG.getDataLayout(); 6810 6811 ArgListTy Args; 6812 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 6813 SDValue SRet; 6814 if (ShouldUseSRet) { 6815 // Create stack object for sret. 6816 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6817 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6818 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6819 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 6820 6821 ArgListEntry Entry; 6822 Entry.Node = SRet; 6823 Entry.Ty = RetTy->getPointerTo(); 6824 Entry.isSExt = false; 6825 Entry.isZExt = false; 6826 Entry.isSRet = true; 6827 Args.push_back(Entry); 6828 RetTy = Type::getVoidTy(*DAG.getContext()); 6829 } 6830 6831 ArgListEntry Entry; 6832 Entry.Node = Arg; 6833 Entry.Ty = ArgTy; 6834 Entry.isSExt = false; 6835 Entry.isZExt = false; 6836 Args.push_back(Entry); 6837 6838 const char *LibcallName = 6839 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 6840 RTLIB::Libcall LC = 6841 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 6842 CallingConv::ID CC = getLibcallCallingConv(LC); 6843 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6844 6845 TargetLowering::CallLoweringInfo CLI(DAG); 6846 CLI.setDebugLoc(dl) 6847 .setChain(DAG.getEntryNode()) 6848 .setCallee(CC, RetTy, Callee, std::move(Args), 0) 6849 .setDiscardResult(ShouldUseSRet); 6850 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6851 6852 if (!ShouldUseSRet) 6853 return CallResult.first; 6854 6855 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6856 MachinePointerInfo(), false, false, false, 0); 6857 6858 // Address of cos field. 6859 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6860 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6861 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6862 MachinePointerInfo(), false, false, false, 0); 6863 6864 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6865 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6866 LoadSin.getValue(0), LoadCos.getValue(0)); 6867 } 6868 6869 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 6870 bool Signed, 6871 SDValue &Chain) const { 6872 EVT VT = Op.getValueType(); 6873 assert((VT == MVT::i32 || VT == MVT::i64) && 6874 "unexpected type for custom lowering DIV"); 6875 SDLoc dl(Op); 6876 6877 const auto &DL = DAG.getDataLayout(); 6878 const auto &TLI = DAG.getTargetLoweringInfo(); 6879 6880 const char *Name = nullptr; 6881 if (Signed) 6882 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 6883 else 6884 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 6885 6886 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 6887 6888 ARMTargetLowering::ArgListTy Args; 6889 6890 for (auto AI : {1, 0}) { 6891 ArgListEntry Arg; 6892 Arg.Node = Op.getOperand(AI); 6893 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 6894 Args.push_back(Arg); 6895 } 6896 6897 CallLoweringInfo CLI(DAG); 6898 CLI.setDebugLoc(dl) 6899 .setChain(Chain) 6900 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 6901 ES, std::move(Args), 0); 6902 6903 return LowerCallTo(CLI).first; 6904 } 6905 6906 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 6907 bool Signed) const { 6908 assert(Op.getValueType() == MVT::i32 && 6909 "unexpected type for custom lowering DIV"); 6910 SDLoc dl(Op); 6911 6912 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 6913 DAG.getEntryNode(), Op.getOperand(1)); 6914 6915 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6916 } 6917 6918 void ARMTargetLowering::ExpandDIV_Windows( 6919 SDValue Op, SelectionDAG &DAG, bool Signed, 6920 SmallVectorImpl<SDValue> &Results) const { 6921 const auto &DL = DAG.getDataLayout(); 6922 const auto &TLI = DAG.getTargetLoweringInfo(); 6923 6924 assert(Op.getValueType() == MVT::i64 && 6925 "unexpected type for custom lowering DIV"); 6926 SDLoc dl(Op); 6927 6928 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6929 DAG.getConstant(0, dl, MVT::i32)); 6930 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6931 DAG.getConstant(1, dl, MVT::i32)); 6932 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 6933 6934 SDValue DBZCHK = 6935 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 6936 6937 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6938 6939 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 6940 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 6941 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 6942 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 6943 6944 Results.push_back(Lower); 6945 Results.push_back(Upper); 6946 } 6947 6948 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 6949 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 6950 // Acquire/Release load/store is not legal for targets without a dmb or 6951 // equivalent available. 6952 return SDValue(); 6953 6954 // Monotonic load/store is legal for all targets. 6955 return Op; 6956 } 6957 6958 static void ReplaceREADCYCLECOUNTER(SDNode *N, 6959 SmallVectorImpl<SDValue> &Results, 6960 SelectionDAG &DAG, 6961 const ARMSubtarget *Subtarget) { 6962 SDLoc DL(N); 6963 // Under Power Management extensions, the cycle-count is: 6964 // mrc p15, #0, <Rt>, c9, c13, #0 6965 SDValue Ops[] = { N->getOperand(0), // Chain 6966 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 6967 DAG.getConstant(15, DL, MVT::i32), 6968 DAG.getConstant(0, DL, MVT::i32), 6969 DAG.getConstant(9, DL, MVT::i32), 6970 DAG.getConstant(13, DL, MVT::i32), 6971 DAG.getConstant(0, DL, MVT::i32) 6972 }; 6973 6974 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6975 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6976 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 6977 DAG.getConstant(0, DL, MVT::i32))); 6978 Results.push_back(Cycles32.getValue(1)); 6979 } 6980 6981 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 6982 SDLoc dl(V.getNode()); 6983 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 6984 SDValue VHi = DAG.getAnyExtOrTrunc( 6985 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 6986 dl, MVT::i32); 6987 SDValue RegClass = 6988 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 6989 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 6990 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 6991 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 6992 return SDValue( 6993 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 6994 } 6995 6996 static void ReplaceCMP_SWAP_64Results(SDNode *N, 6997 SmallVectorImpl<SDValue> & Results, 6998 SelectionDAG &DAG) { 6999 assert(N->getValueType(0) == MVT::i64 && 7000 "AtomicCmpSwap on types less than 64 should be legal"); 7001 SDValue Ops[] = {N->getOperand(1), 7002 createGPRPairNode(DAG, N->getOperand(2)), 7003 createGPRPairNode(DAG, N->getOperand(3)), 7004 N->getOperand(0)}; 7005 SDNode *CmpSwap = DAG.getMachineNode( 7006 ARM::CMP_SWAP_64, SDLoc(N), 7007 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7008 7009 MachineFunction &MF = DAG.getMachineFunction(); 7010 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7011 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7012 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7013 7014 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7015 SDValue(CmpSwap, 0))); 7016 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7017 SDValue(CmpSwap, 0))); 7018 Results.push_back(SDValue(CmpSwap, 2)); 7019 } 7020 7021 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7022 switch (Op.getOpcode()) { 7023 default: llvm_unreachable("Don't know how to custom lower this!"); 7024 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7025 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7026 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7027 case ISD::GlobalAddress: 7028 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7029 default: llvm_unreachable("unknown object format"); 7030 case Triple::COFF: 7031 return LowerGlobalAddressWindows(Op, DAG); 7032 case Triple::ELF: 7033 return LowerGlobalAddressELF(Op, DAG); 7034 case Triple::MachO: 7035 return LowerGlobalAddressDarwin(Op, DAG); 7036 } 7037 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7038 case ISD::SELECT: return LowerSELECT(Op, DAG); 7039 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7040 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7041 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7042 case ISD::VASTART: return LowerVASTART(Op, DAG); 7043 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7044 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7045 case ISD::SINT_TO_FP: 7046 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7047 case ISD::FP_TO_SINT: 7048 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7049 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7050 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7051 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7052 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7053 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7054 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7055 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7056 Subtarget); 7057 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7058 case ISD::SHL: 7059 case ISD::SRL: 7060 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7061 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7062 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7063 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7064 case ISD::SRL_PARTS: 7065 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7066 case ISD::CTTZ: 7067 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7068 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7069 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7070 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7071 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7072 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7073 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7074 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7075 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7076 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7077 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7078 case ISD::MUL: return LowerMUL(Op, DAG); 7079 case ISD::SDIV: 7080 if (Subtarget->isTargetWindows()) 7081 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7082 return LowerSDIV(Op, DAG); 7083 case ISD::UDIV: 7084 if (Subtarget->isTargetWindows()) 7085 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7086 return LowerUDIV(Op, DAG); 7087 case ISD::ADDC: 7088 case ISD::ADDE: 7089 case ISD::SUBC: 7090 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7091 case ISD::SADDO: 7092 case ISD::UADDO: 7093 case ISD::SSUBO: 7094 case ISD::USUBO: 7095 return LowerXALUO(Op, DAG); 7096 case ISD::ATOMIC_LOAD: 7097 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7098 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7099 case ISD::SDIVREM: 7100 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7101 case ISD::DYNAMIC_STACKALLOC: 7102 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7103 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7104 llvm_unreachable("Don't know how to custom lower this!"); 7105 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7106 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7107 case ARMISD::WIN__DBZCHK: return SDValue(); 7108 } 7109 } 7110 7111 /// ReplaceNodeResults - Replace the results of node with an illegal result 7112 /// type with new values built out of custom code. 7113 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7114 SmallVectorImpl<SDValue> &Results, 7115 SelectionDAG &DAG) const { 7116 SDValue Res; 7117 switch (N->getOpcode()) { 7118 default: 7119 llvm_unreachable("Don't know how to custom expand this!"); 7120 case ISD::READ_REGISTER: 7121 ExpandREAD_REGISTER(N, Results, DAG); 7122 break; 7123 case ISD::BITCAST: 7124 Res = ExpandBITCAST(N, DAG); 7125 break; 7126 case ISD::SRL: 7127 case ISD::SRA: 7128 Res = Expand64BitShift(N, DAG, Subtarget); 7129 break; 7130 case ISD::SREM: 7131 case ISD::UREM: 7132 Res = LowerREM(N, DAG); 7133 break; 7134 case ISD::SDIVREM: 7135 case ISD::UDIVREM: 7136 Res = LowerDivRem(SDValue(N, 0), DAG); 7137 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7138 Results.push_back(Res.getValue(0)); 7139 Results.push_back(Res.getValue(1)); 7140 return; 7141 case ISD::READCYCLECOUNTER: 7142 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7143 return; 7144 case ISD::UDIV: 7145 case ISD::SDIV: 7146 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7147 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7148 Results); 7149 case ISD::ATOMIC_CMP_SWAP: 7150 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7151 return; 7152 } 7153 if (Res.getNode()) 7154 Results.push_back(Res); 7155 } 7156 7157 //===----------------------------------------------------------------------===// 7158 // ARM Scheduler Hooks 7159 //===----------------------------------------------------------------------===// 7160 7161 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7162 /// registers the function context. 7163 void ARMTargetLowering:: 7164 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 7165 MachineBasicBlock *DispatchBB, int FI) const { 7166 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7167 DebugLoc dl = MI->getDebugLoc(); 7168 MachineFunction *MF = MBB->getParent(); 7169 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7170 MachineConstantPool *MCP = MF->getConstantPool(); 7171 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7172 const Function *F = MF->getFunction(); 7173 7174 bool isThumb = Subtarget->isThumb(); 7175 bool isThumb2 = Subtarget->isThumb2(); 7176 7177 unsigned PCLabelId = AFI->createPICLabelUId(); 7178 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7179 ARMConstantPoolValue *CPV = 7180 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7181 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7182 7183 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7184 : &ARM::GPRRegClass; 7185 7186 // Grab constant pool and fixed stack memory operands. 7187 MachineMemOperand *CPMMO = 7188 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7189 MachineMemOperand::MOLoad, 4, 4); 7190 7191 MachineMemOperand *FIMMOSt = 7192 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7193 MachineMemOperand::MOStore, 4, 4); 7194 7195 // Load the address of the dispatch MBB into the jump buffer. 7196 if (isThumb2) { 7197 // Incoming value: jbuf 7198 // ldr.n r5, LCPI1_1 7199 // orr r5, r5, #1 7200 // add r5, pc 7201 // str r5, [$jbuf, #+4] ; &jbuf[1] 7202 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7203 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7204 .addConstantPoolIndex(CPI) 7205 .addMemOperand(CPMMO)); 7206 // Set the low bit because of thumb mode. 7207 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7208 AddDefaultCC( 7209 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7210 .addReg(NewVReg1, RegState::Kill) 7211 .addImm(0x01))); 7212 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7213 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7214 .addReg(NewVReg2, RegState::Kill) 7215 .addImm(PCLabelId); 7216 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7217 .addReg(NewVReg3, RegState::Kill) 7218 .addFrameIndex(FI) 7219 .addImm(36) // &jbuf[1] :: pc 7220 .addMemOperand(FIMMOSt)); 7221 } else if (isThumb) { 7222 // Incoming value: jbuf 7223 // ldr.n r1, LCPI1_4 7224 // add r1, pc 7225 // mov r2, #1 7226 // orrs r1, r2 7227 // add r2, $jbuf, #+4 ; &jbuf[1] 7228 // str r1, [r2] 7229 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7230 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7231 .addConstantPoolIndex(CPI) 7232 .addMemOperand(CPMMO)); 7233 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7234 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7235 .addReg(NewVReg1, RegState::Kill) 7236 .addImm(PCLabelId); 7237 // Set the low bit because of thumb mode. 7238 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7239 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7240 .addReg(ARM::CPSR, RegState::Define) 7241 .addImm(1)); 7242 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7243 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7244 .addReg(ARM::CPSR, RegState::Define) 7245 .addReg(NewVReg2, RegState::Kill) 7246 .addReg(NewVReg3, RegState::Kill)); 7247 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7248 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7249 .addFrameIndex(FI) 7250 .addImm(36); // &jbuf[1] :: pc 7251 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7252 .addReg(NewVReg4, RegState::Kill) 7253 .addReg(NewVReg5, RegState::Kill) 7254 .addImm(0) 7255 .addMemOperand(FIMMOSt)); 7256 } else { 7257 // Incoming value: jbuf 7258 // ldr r1, LCPI1_1 7259 // add r1, pc, r1 7260 // str r1, [$jbuf, #+4] ; &jbuf[1] 7261 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7262 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7263 .addConstantPoolIndex(CPI) 7264 .addImm(0) 7265 .addMemOperand(CPMMO)); 7266 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7267 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7268 .addReg(NewVReg1, RegState::Kill) 7269 .addImm(PCLabelId)); 7270 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7271 .addReg(NewVReg2, RegState::Kill) 7272 .addFrameIndex(FI) 7273 .addImm(36) // &jbuf[1] :: pc 7274 .addMemOperand(FIMMOSt)); 7275 } 7276 } 7277 7278 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI, 7279 MachineBasicBlock *MBB) const { 7280 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7281 DebugLoc dl = MI->getDebugLoc(); 7282 MachineFunction *MF = MBB->getParent(); 7283 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7284 MachineFrameInfo *MFI = MF->getFrameInfo(); 7285 int FI = MFI->getFunctionContextIndex(); 7286 7287 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7288 : &ARM::GPRnopcRegClass; 7289 7290 // Get a mapping of the call site numbers to all of the landing pads they're 7291 // associated with. 7292 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7293 unsigned MaxCSNum = 0; 7294 MachineModuleInfo &MMI = MF->getMMI(); 7295 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7296 ++BB) { 7297 if (!BB->isEHPad()) continue; 7298 7299 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7300 // pad. 7301 for (MachineBasicBlock::iterator 7302 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7303 if (!II->isEHLabel()) continue; 7304 7305 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7306 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7307 7308 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7309 for (SmallVectorImpl<unsigned>::iterator 7310 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7311 CSI != CSE; ++CSI) { 7312 CallSiteNumToLPad[*CSI].push_back(&*BB); 7313 MaxCSNum = std::max(MaxCSNum, *CSI); 7314 } 7315 break; 7316 } 7317 } 7318 7319 // Get an ordered list of the machine basic blocks for the jump table. 7320 std::vector<MachineBasicBlock*> LPadList; 7321 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7322 LPadList.reserve(CallSiteNumToLPad.size()); 7323 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7324 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7325 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7326 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7327 LPadList.push_back(*II); 7328 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7329 } 7330 } 7331 7332 assert(!LPadList.empty() && 7333 "No landing pad destinations for the dispatch jump table!"); 7334 7335 // Create the jump table and associated information. 7336 MachineJumpTableInfo *JTI = 7337 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7338 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7339 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 7340 7341 // Create the MBBs for the dispatch code. 7342 7343 // Shove the dispatch's address into the return slot in the function context. 7344 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7345 DispatchBB->setIsEHPad(); 7346 7347 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7348 unsigned trap_opcode; 7349 if (Subtarget->isThumb()) 7350 trap_opcode = ARM::tTRAP; 7351 else 7352 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7353 7354 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7355 DispatchBB->addSuccessor(TrapBB); 7356 7357 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7358 DispatchBB->addSuccessor(DispContBB); 7359 7360 // Insert and MBBs. 7361 MF->insert(MF->end(), DispatchBB); 7362 MF->insert(MF->end(), DispContBB); 7363 MF->insert(MF->end(), TrapBB); 7364 7365 // Insert code into the entry block that creates and registers the function 7366 // context. 7367 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7368 7369 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7370 MachinePointerInfo::getFixedStack(*MF, FI), 7371 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7372 7373 MachineInstrBuilder MIB; 7374 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7375 7376 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7377 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7378 7379 // Add a register mask with no preserved registers. This results in all 7380 // registers being marked as clobbered. 7381 MIB.addRegMask(RI.getNoPreservedMask()); 7382 7383 unsigned NumLPads = LPadList.size(); 7384 if (Subtarget->isThumb2()) { 7385 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7386 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7387 .addFrameIndex(FI) 7388 .addImm(4) 7389 .addMemOperand(FIMMOLd)); 7390 7391 if (NumLPads < 256) { 7392 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7393 .addReg(NewVReg1) 7394 .addImm(LPadList.size())); 7395 } else { 7396 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7397 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7398 .addImm(NumLPads & 0xFFFF)); 7399 7400 unsigned VReg2 = VReg1; 7401 if ((NumLPads & 0xFFFF0000) != 0) { 7402 VReg2 = MRI->createVirtualRegister(TRC); 7403 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7404 .addReg(VReg1) 7405 .addImm(NumLPads >> 16)); 7406 } 7407 7408 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7409 .addReg(NewVReg1) 7410 .addReg(VReg2)); 7411 } 7412 7413 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7414 .addMBB(TrapBB) 7415 .addImm(ARMCC::HI) 7416 .addReg(ARM::CPSR); 7417 7418 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7419 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7420 .addJumpTableIndex(MJTI)); 7421 7422 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7423 AddDefaultCC( 7424 AddDefaultPred( 7425 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7426 .addReg(NewVReg3, RegState::Kill) 7427 .addReg(NewVReg1) 7428 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7429 7430 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7431 .addReg(NewVReg4, RegState::Kill) 7432 .addReg(NewVReg1) 7433 .addJumpTableIndex(MJTI); 7434 } else if (Subtarget->isThumb()) { 7435 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7436 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7437 .addFrameIndex(FI) 7438 .addImm(1) 7439 .addMemOperand(FIMMOLd)); 7440 7441 if (NumLPads < 256) { 7442 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7443 .addReg(NewVReg1) 7444 .addImm(NumLPads)); 7445 } else { 7446 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7447 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7448 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7449 7450 // MachineConstantPool wants an explicit alignment. 7451 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7452 if (Align == 0) 7453 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7454 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7455 7456 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7457 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7458 .addReg(VReg1, RegState::Define) 7459 .addConstantPoolIndex(Idx)); 7460 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7461 .addReg(NewVReg1) 7462 .addReg(VReg1)); 7463 } 7464 7465 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7466 .addMBB(TrapBB) 7467 .addImm(ARMCC::HI) 7468 .addReg(ARM::CPSR); 7469 7470 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7471 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7472 .addReg(ARM::CPSR, RegState::Define) 7473 .addReg(NewVReg1) 7474 .addImm(2)); 7475 7476 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7477 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7478 .addJumpTableIndex(MJTI)); 7479 7480 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7481 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7482 .addReg(ARM::CPSR, RegState::Define) 7483 .addReg(NewVReg2, RegState::Kill) 7484 .addReg(NewVReg3)); 7485 7486 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7487 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7488 7489 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7490 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7491 .addReg(NewVReg4, RegState::Kill) 7492 .addImm(0) 7493 .addMemOperand(JTMMOLd)); 7494 7495 unsigned NewVReg6 = NewVReg5; 7496 if (RelocM == Reloc::PIC_) { 7497 NewVReg6 = MRI->createVirtualRegister(TRC); 7498 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7499 .addReg(ARM::CPSR, RegState::Define) 7500 .addReg(NewVReg5, RegState::Kill) 7501 .addReg(NewVReg3)); 7502 } 7503 7504 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7505 .addReg(NewVReg6, RegState::Kill) 7506 .addJumpTableIndex(MJTI); 7507 } else { 7508 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7509 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7510 .addFrameIndex(FI) 7511 .addImm(4) 7512 .addMemOperand(FIMMOLd)); 7513 7514 if (NumLPads < 256) { 7515 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7516 .addReg(NewVReg1) 7517 .addImm(NumLPads)); 7518 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7519 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7520 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7521 .addImm(NumLPads & 0xFFFF)); 7522 7523 unsigned VReg2 = VReg1; 7524 if ((NumLPads & 0xFFFF0000) != 0) { 7525 VReg2 = MRI->createVirtualRegister(TRC); 7526 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7527 .addReg(VReg1) 7528 .addImm(NumLPads >> 16)); 7529 } 7530 7531 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7532 .addReg(NewVReg1) 7533 .addReg(VReg2)); 7534 } else { 7535 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7536 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7537 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7538 7539 // MachineConstantPool wants an explicit alignment. 7540 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7541 if (Align == 0) 7542 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7543 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7544 7545 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7546 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7547 .addReg(VReg1, RegState::Define) 7548 .addConstantPoolIndex(Idx) 7549 .addImm(0)); 7550 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7551 .addReg(NewVReg1) 7552 .addReg(VReg1, RegState::Kill)); 7553 } 7554 7555 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7556 .addMBB(TrapBB) 7557 .addImm(ARMCC::HI) 7558 .addReg(ARM::CPSR); 7559 7560 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7561 AddDefaultCC( 7562 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7563 .addReg(NewVReg1) 7564 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7565 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7566 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7567 .addJumpTableIndex(MJTI)); 7568 7569 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7570 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7571 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7572 AddDefaultPred( 7573 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7574 .addReg(NewVReg3, RegState::Kill) 7575 .addReg(NewVReg4) 7576 .addImm(0) 7577 .addMemOperand(JTMMOLd)); 7578 7579 if (RelocM == Reloc::PIC_) { 7580 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7581 .addReg(NewVReg5, RegState::Kill) 7582 .addReg(NewVReg4) 7583 .addJumpTableIndex(MJTI); 7584 } else { 7585 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7586 .addReg(NewVReg5, RegState::Kill) 7587 .addJumpTableIndex(MJTI); 7588 } 7589 } 7590 7591 // Add the jump table entries as successors to the MBB. 7592 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7593 for (std::vector<MachineBasicBlock*>::iterator 7594 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7595 MachineBasicBlock *CurMBB = *I; 7596 if (SeenMBBs.insert(CurMBB).second) 7597 DispContBB->addSuccessor(CurMBB); 7598 } 7599 7600 // N.B. the order the invoke BBs are processed in doesn't matter here. 7601 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7602 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7603 for (MachineBasicBlock *BB : InvokeBBs) { 7604 7605 // Remove the landing pad successor from the invoke block and replace it 7606 // with the new dispatch block. 7607 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7608 BB->succ_end()); 7609 while (!Successors.empty()) { 7610 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7611 if (SMBB->isEHPad()) { 7612 BB->removeSuccessor(SMBB); 7613 MBBLPads.push_back(SMBB); 7614 } 7615 } 7616 7617 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7618 BB->normalizeSuccProbs(); 7619 7620 // Find the invoke call and mark all of the callee-saved registers as 7621 // 'implicit defined' so that they're spilled. This prevents code from 7622 // moving instructions to before the EH block, where they will never be 7623 // executed. 7624 for (MachineBasicBlock::reverse_iterator 7625 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7626 if (!II->isCall()) continue; 7627 7628 DenseMap<unsigned, bool> DefRegs; 7629 for (MachineInstr::mop_iterator 7630 OI = II->operands_begin(), OE = II->operands_end(); 7631 OI != OE; ++OI) { 7632 if (!OI->isReg()) continue; 7633 DefRegs[OI->getReg()] = true; 7634 } 7635 7636 MachineInstrBuilder MIB(*MF, &*II); 7637 7638 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7639 unsigned Reg = SavedRegs[i]; 7640 if (Subtarget->isThumb2() && 7641 !ARM::tGPRRegClass.contains(Reg) && 7642 !ARM::hGPRRegClass.contains(Reg)) 7643 continue; 7644 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7645 continue; 7646 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7647 continue; 7648 if (!DefRegs[Reg]) 7649 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7650 } 7651 7652 break; 7653 } 7654 } 7655 7656 // Mark all former landing pads as non-landing pads. The dispatch is the only 7657 // landing pad now. 7658 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7659 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7660 (*I)->setIsEHPad(false); 7661 7662 // The instruction is gone now. 7663 MI->eraseFromParent(); 7664 } 7665 7666 static 7667 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7668 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7669 E = MBB->succ_end(); I != E; ++I) 7670 if (*I != Succ) 7671 return *I; 7672 llvm_unreachable("Expecting a BB with two successors!"); 7673 } 7674 7675 /// Return the load opcode for a given load size. If load size >= 8, 7676 /// neon opcode will be returned. 7677 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7678 if (LdSize >= 8) 7679 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7680 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7681 if (IsThumb1) 7682 return LdSize == 4 ? ARM::tLDRi 7683 : LdSize == 2 ? ARM::tLDRHi 7684 : LdSize == 1 ? ARM::tLDRBi : 0; 7685 if (IsThumb2) 7686 return LdSize == 4 ? ARM::t2LDR_POST 7687 : LdSize == 2 ? ARM::t2LDRH_POST 7688 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7689 return LdSize == 4 ? ARM::LDR_POST_IMM 7690 : LdSize == 2 ? ARM::LDRH_POST 7691 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7692 } 7693 7694 /// Return the store opcode for a given store size. If store size >= 8, 7695 /// neon opcode will be returned. 7696 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7697 if (StSize >= 8) 7698 return StSize == 16 ? ARM::VST1q32wb_fixed 7699 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7700 if (IsThumb1) 7701 return StSize == 4 ? ARM::tSTRi 7702 : StSize == 2 ? ARM::tSTRHi 7703 : StSize == 1 ? ARM::tSTRBi : 0; 7704 if (IsThumb2) 7705 return StSize == 4 ? ARM::t2STR_POST 7706 : StSize == 2 ? ARM::t2STRH_POST 7707 : StSize == 1 ? ARM::t2STRB_POST : 0; 7708 return StSize == 4 ? ARM::STR_POST_IMM 7709 : StSize == 2 ? ARM::STRH_POST 7710 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7711 } 7712 7713 /// Emit a post-increment load operation with given size. The instructions 7714 /// will be added to BB at Pos. 7715 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7716 const TargetInstrInfo *TII, DebugLoc dl, 7717 unsigned LdSize, unsigned Data, unsigned AddrIn, 7718 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7719 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7720 assert(LdOpc != 0 && "Should have a load opcode"); 7721 if (LdSize >= 8) { 7722 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7723 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7724 .addImm(0)); 7725 } else if (IsThumb1) { 7726 // load + update AddrIn 7727 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7728 .addReg(AddrIn).addImm(0)); 7729 MachineInstrBuilder MIB = 7730 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7731 MIB = AddDefaultT1CC(MIB); 7732 MIB.addReg(AddrIn).addImm(LdSize); 7733 AddDefaultPred(MIB); 7734 } else if (IsThumb2) { 7735 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7736 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7737 .addImm(LdSize)); 7738 } else { // arm 7739 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7740 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7741 .addReg(0).addImm(LdSize)); 7742 } 7743 } 7744 7745 /// Emit a post-increment store operation with given size. The instructions 7746 /// will be added to BB at Pos. 7747 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7748 const TargetInstrInfo *TII, DebugLoc dl, 7749 unsigned StSize, unsigned Data, unsigned AddrIn, 7750 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7751 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7752 assert(StOpc != 0 && "Should have a store opcode"); 7753 if (StSize >= 8) { 7754 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7755 .addReg(AddrIn).addImm(0).addReg(Data)); 7756 } else if (IsThumb1) { 7757 // store + update AddrIn 7758 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7759 .addReg(AddrIn).addImm(0)); 7760 MachineInstrBuilder MIB = 7761 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7762 MIB = AddDefaultT1CC(MIB); 7763 MIB.addReg(AddrIn).addImm(StSize); 7764 AddDefaultPred(MIB); 7765 } else if (IsThumb2) { 7766 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7767 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7768 } else { // arm 7769 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7770 .addReg(Data).addReg(AddrIn).addReg(0) 7771 .addImm(StSize)); 7772 } 7773 } 7774 7775 MachineBasicBlock * 7776 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7777 MachineBasicBlock *BB) const { 7778 // This pseudo instruction has 3 operands: dst, src, size 7779 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7780 // Otherwise, we will generate unrolled scalar copies. 7781 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7782 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7783 MachineFunction::iterator It = ++BB->getIterator(); 7784 7785 unsigned dest = MI->getOperand(0).getReg(); 7786 unsigned src = MI->getOperand(1).getReg(); 7787 unsigned SizeVal = MI->getOperand(2).getImm(); 7788 unsigned Align = MI->getOperand(3).getImm(); 7789 DebugLoc dl = MI->getDebugLoc(); 7790 7791 MachineFunction *MF = BB->getParent(); 7792 MachineRegisterInfo &MRI = MF->getRegInfo(); 7793 unsigned UnitSize = 0; 7794 const TargetRegisterClass *TRC = nullptr; 7795 const TargetRegisterClass *VecTRC = nullptr; 7796 7797 bool IsThumb1 = Subtarget->isThumb1Only(); 7798 bool IsThumb2 = Subtarget->isThumb2(); 7799 7800 if (Align & 1) { 7801 UnitSize = 1; 7802 } else if (Align & 2) { 7803 UnitSize = 2; 7804 } else { 7805 // Check whether we can use NEON instructions. 7806 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7807 Subtarget->hasNEON()) { 7808 if ((Align % 16 == 0) && SizeVal >= 16) 7809 UnitSize = 16; 7810 else if ((Align % 8 == 0) && SizeVal >= 8) 7811 UnitSize = 8; 7812 } 7813 // Can't use NEON instructions. 7814 if (UnitSize == 0) 7815 UnitSize = 4; 7816 } 7817 7818 // Select the correct opcode and register class for unit size load/store 7819 bool IsNeon = UnitSize >= 8; 7820 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7821 if (IsNeon) 7822 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7823 : UnitSize == 8 ? &ARM::DPRRegClass 7824 : nullptr; 7825 7826 unsigned BytesLeft = SizeVal % UnitSize; 7827 unsigned LoopSize = SizeVal - BytesLeft; 7828 7829 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7830 // Use LDR and STR to copy. 7831 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7832 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7833 unsigned srcIn = src; 7834 unsigned destIn = dest; 7835 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7836 unsigned srcOut = MRI.createVirtualRegister(TRC); 7837 unsigned destOut = MRI.createVirtualRegister(TRC); 7838 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7839 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7840 IsThumb1, IsThumb2); 7841 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7842 IsThumb1, IsThumb2); 7843 srcIn = srcOut; 7844 destIn = destOut; 7845 } 7846 7847 // Handle the leftover bytes with LDRB and STRB. 7848 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7849 // [destOut] = STRB_POST(scratch, destIn, 1) 7850 for (unsigned i = 0; i < BytesLeft; i++) { 7851 unsigned srcOut = MRI.createVirtualRegister(TRC); 7852 unsigned destOut = MRI.createVirtualRegister(TRC); 7853 unsigned scratch = MRI.createVirtualRegister(TRC); 7854 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7855 IsThumb1, IsThumb2); 7856 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7857 IsThumb1, IsThumb2); 7858 srcIn = srcOut; 7859 destIn = destOut; 7860 } 7861 MI->eraseFromParent(); // The instruction is gone now. 7862 return BB; 7863 } 7864 7865 // Expand the pseudo op to a loop. 7866 // thisMBB: 7867 // ... 7868 // movw varEnd, # --> with thumb2 7869 // movt varEnd, # 7870 // ldrcp varEnd, idx --> without thumb2 7871 // fallthrough --> loopMBB 7872 // loopMBB: 7873 // PHI varPhi, varEnd, varLoop 7874 // PHI srcPhi, src, srcLoop 7875 // PHI destPhi, dst, destLoop 7876 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7877 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7878 // subs varLoop, varPhi, #UnitSize 7879 // bne loopMBB 7880 // fallthrough --> exitMBB 7881 // exitMBB: 7882 // epilogue to handle left-over bytes 7883 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7884 // [destOut] = STRB_POST(scratch, destLoop, 1) 7885 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7886 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7887 MF->insert(It, loopMBB); 7888 MF->insert(It, exitMBB); 7889 7890 // Transfer the remainder of BB and its successor edges to exitMBB. 7891 exitMBB->splice(exitMBB->begin(), BB, 7892 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7893 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7894 7895 // Load an immediate to varEnd. 7896 unsigned varEnd = MRI.createVirtualRegister(TRC); 7897 if (Subtarget->useMovt(*MF)) { 7898 unsigned Vtmp = varEnd; 7899 if ((LoopSize & 0xFFFF0000) != 0) 7900 Vtmp = MRI.createVirtualRegister(TRC); 7901 AddDefaultPred(BuildMI(BB, dl, 7902 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16), 7903 Vtmp).addImm(LoopSize & 0xFFFF)); 7904 7905 if ((LoopSize & 0xFFFF0000) != 0) 7906 AddDefaultPred(BuildMI(BB, dl, 7907 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16), 7908 varEnd) 7909 .addReg(Vtmp) 7910 .addImm(LoopSize >> 16)); 7911 } else { 7912 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7913 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7914 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 7915 7916 // MachineConstantPool wants an explicit alignment. 7917 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7918 if (Align == 0) 7919 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7920 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7921 7922 if (IsThumb1) 7923 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 7924 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 7925 else 7926 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 7927 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 7928 } 7929 BB->addSuccessor(loopMBB); 7930 7931 // Generate the loop body: 7932 // varPhi = PHI(varLoop, varEnd) 7933 // srcPhi = PHI(srcLoop, src) 7934 // destPhi = PHI(destLoop, dst) 7935 MachineBasicBlock *entryBB = BB; 7936 BB = loopMBB; 7937 unsigned varLoop = MRI.createVirtualRegister(TRC); 7938 unsigned varPhi = MRI.createVirtualRegister(TRC); 7939 unsigned srcLoop = MRI.createVirtualRegister(TRC); 7940 unsigned srcPhi = MRI.createVirtualRegister(TRC); 7941 unsigned destLoop = MRI.createVirtualRegister(TRC); 7942 unsigned destPhi = MRI.createVirtualRegister(TRC); 7943 7944 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 7945 .addReg(varLoop).addMBB(loopMBB) 7946 .addReg(varEnd).addMBB(entryBB); 7947 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 7948 .addReg(srcLoop).addMBB(loopMBB) 7949 .addReg(src).addMBB(entryBB); 7950 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 7951 .addReg(destLoop).addMBB(loopMBB) 7952 .addReg(dest).addMBB(entryBB); 7953 7954 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7955 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 7956 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7957 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 7958 IsThumb1, IsThumb2); 7959 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 7960 IsThumb1, IsThumb2); 7961 7962 // Decrement loop variable by UnitSize. 7963 if (IsThumb1) { 7964 MachineInstrBuilder MIB = 7965 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 7966 MIB = AddDefaultT1CC(MIB); 7967 MIB.addReg(varPhi).addImm(UnitSize); 7968 AddDefaultPred(MIB); 7969 } else { 7970 MachineInstrBuilder MIB = 7971 BuildMI(*BB, BB->end(), dl, 7972 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 7973 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 7974 MIB->getOperand(5).setReg(ARM::CPSR); 7975 MIB->getOperand(5).setIsDef(true); 7976 } 7977 BuildMI(*BB, BB->end(), dl, 7978 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7979 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 7980 7981 // loopMBB can loop back to loopMBB or fall through to exitMBB. 7982 BB->addSuccessor(loopMBB); 7983 BB->addSuccessor(exitMBB); 7984 7985 // Add epilogue to handle BytesLeft. 7986 BB = exitMBB; 7987 MachineInstr *StartOfExit = exitMBB->begin(); 7988 7989 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7990 // [destOut] = STRB_POST(scratch, destLoop, 1) 7991 unsigned srcIn = srcLoop; 7992 unsigned destIn = destLoop; 7993 for (unsigned i = 0; i < BytesLeft; i++) { 7994 unsigned srcOut = MRI.createVirtualRegister(TRC); 7995 unsigned destOut = MRI.createVirtualRegister(TRC); 7996 unsigned scratch = MRI.createVirtualRegister(TRC); 7997 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 7998 IsThumb1, IsThumb2); 7999 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8000 IsThumb1, IsThumb2); 8001 srcIn = srcOut; 8002 destIn = destOut; 8003 } 8004 8005 MI->eraseFromParent(); // The instruction is gone now. 8006 return BB; 8007 } 8008 8009 MachineBasicBlock * 8010 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 8011 MachineBasicBlock *MBB) const { 8012 const TargetMachine &TM = getTargetMachine(); 8013 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8014 DebugLoc DL = MI->getDebugLoc(); 8015 8016 assert(Subtarget->isTargetWindows() && 8017 "__chkstk is only supported on Windows"); 8018 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8019 8020 // __chkstk takes the number of words to allocate on the stack in R4, and 8021 // returns the stack adjustment in number of bytes in R4. This will not 8022 // clober any other registers (other than the obvious lr). 8023 // 8024 // Although, technically, IP should be considered a register which may be 8025 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8026 // thumb-2 environment, so there is no interworking required. As a result, we 8027 // do not expect a veneer to be emitted by the linker, clobbering IP. 8028 // 8029 // Each module receives its own copy of __chkstk, so no import thunk is 8030 // required, again, ensuring that IP is not clobbered. 8031 // 8032 // Finally, although some linkers may theoretically provide a trampoline for 8033 // out of range calls (which is quite common due to a 32M range limitation of 8034 // branches for Thumb), we can generate the long-call version via 8035 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8036 // IP. 8037 8038 switch (TM.getCodeModel()) { 8039 case CodeModel::Small: 8040 case CodeModel::Medium: 8041 case CodeModel::Default: 8042 case CodeModel::Kernel: 8043 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8044 .addImm((unsigned)ARMCC::AL).addReg(0) 8045 .addExternalSymbol("__chkstk") 8046 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8047 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8048 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8049 break; 8050 case CodeModel::Large: 8051 case CodeModel::JITDefault: { 8052 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8053 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8054 8055 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8056 .addExternalSymbol("__chkstk"); 8057 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8058 .addImm((unsigned)ARMCC::AL).addReg(0) 8059 .addReg(Reg, RegState::Kill) 8060 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8061 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8062 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8063 break; 8064 } 8065 } 8066 8067 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 8068 ARM::SP) 8069 .addReg(ARM::SP, RegState::Kill) 8070 .addReg(ARM::R4, RegState::Kill) 8071 .setMIFlags(MachineInstr::FrameSetup))); 8072 8073 MI->eraseFromParent(); 8074 return MBB; 8075 } 8076 8077 MachineBasicBlock * 8078 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI, 8079 MachineBasicBlock *MBB) const { 8080 DebugLoc DL = MI->getDebugLoc(); 8081 MachineFunction *MF = MBB->getParent(); 8082 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8083 8084 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8085 MF->insert(++MBB->getIterator(), ContBB); 8086 ContBB->splice(ContBB->begin(), MBB, 8087 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8088 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8089 8090 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8091 MF->push_back(TrapBB); 8092 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 8093 MBB->addSuccessor(TrapBB); 8094 8095 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 8096 .addReg(MI->getOperand(0).getReg()) 8097 .addMBB(TrapBB); 8098 AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB)); 8099 MBB->addSuccessor(ContBB); 8100 8101 MI->eraseFromParent(); 8102 return ContBB; 8103 } 8104 8105 MachineBasicBlock * 8106 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 8107 MachineBasicBlock *BB) const { 8108 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8109 DebugLoc dl = MI->getDebugLoc(); 8110 bool isThumb2 = Subtarget->isThumb2(); 8111 switch (MI->getOpcode()) { 8112 default: { 8113 MI->dump(); 8114 llvm_unreachable("Unexpected instr type to insert"); 8115 } 8116 // The Thumb2 pre-indexed stores have the same MI operands, they just 8117 // define them differently in the .td files from the isel patterns, so 8118 // they need pseudos. 8119 case ARM::t2STR_preidx: 8120 MI->setDesc(TII->get(ARM::t2STR_PRE)); 8121 return BB; 8122 case ARM::t2STRB_preidx: 8123 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 8124 return BB; 8125 case ARM::t2STRH_preidx: 8126 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 8127 return BB; 8128 8129 case ARM::STRi_preidx: 8130 case ARM::STRBi_preidx: { 8131 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 8132 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 8133 // Decode the offset. 8134 unsigned Offset = MI->getOperand(4).getImm(); 8135 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8136 Offset = ARM_AM::getAM2Offset(Offset); 8137 if (isSub) 8138 Offset = -Offset; 8139 8140 MachineMemOperand *MMO = *MI->memoperands_begin(); 8141 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8142 .addOperand(MI->getOperand(0)) // Rn_wb 8143 .addOperand(MI->getOperand(1)) // Rt 8144 .addOperand(MI->getOperand(2)) // Rn 8145 .addImm(Offset) // offset (skip GPR==zero_reg) 8146 .addOperand(MI->getOperand(5)) // pred 8147 .addOperand(MI->getOperand(6)) 8148 .addMemOperand(MMO); 8149 MI->eraseFromParent(); 8150 return BB; 8151 } 8152 case ARM::STRr_preidx: 8153 case ARM::STRBr_preidx: 8154 case ARM::STRH_preidx: { 8155 unsigned NewOpc; 8156 switch (MI->getOpcode()) { 8157 default: llvm_unreachable("unexpected opcode!"); 8158 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8159 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8160 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8161 } 8162 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8163 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 8164 MIB.addOperand(MI->getOperand(i)); 8165 MI->eraseFromParent(); 8166 return BB; 8167 } 8168 8169 case ARM::tMOVCCr_pseudo: { 8170 // To "insert" a SELECT_CC instruction, we actually have to insert the 8171 // diamond control-flow pattern. The incoming instruction knows the 8172 // destination vreg to set, the condition code register to branch on, the 8173 // true/false values to select between, and a branch opcode to use. 8174 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8175 MachineFunction::iterator It = ++BB->getIterator(); 8176 8177 // thisMBB: 8178 // ... 8179 // TrueVal = ... 8180 // cmpTY ccX, r1, r2 8181 // bCC copy1MBB 8182 // fallthrough --> copy0MBB 8183 MachineBasicBlock *thisMBB = BB; 8184 MachineFunction *F = BB->getParent(); 8185 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8186 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8187 F->insert(It, copy0MBB); 8188 F->insert(It, sinkMBB); 8189 8190 // Transfer the remainder of BB and its successor edges to sinkMBB. 8191 sinkMBB->splice(sinkMBB->begin(), BB, 8192 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8193 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8194 8195 BB->addSuccessor(copy0MBB); 8196 BB->addSuccessor(sinkMBB); 8197 8198 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 8199 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 8200 8201 // copy0MBB: 8202 // %FalseValue = ... 8203 // # fallthrough to sinkMBB 8204 BB = copy0MBB; 8205 8206 // Update machine-CFG edges 8207 BB->addSuccessor(sinkMBB); 8208 8209 // sinkMBB: 8210 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8211 // ... 8212 BB = sinkMBB; 8213 BuildMI(*BB, BB->begin(), dl, 8214 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 8215 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 8216 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 8217 8218 MI->eraseFromParent(); // The pseudo instruction is gone now. 8219 return BB; 8220 } 8221 8222 case ARM::BCCi64: 8223 case ARM::BCCZi64: { 8224 // If there is an unconditional branch to the other successor, remove it. 8225 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8226 8227 // Compare both parts that make up the double comparison separately for 8228 // equality. 8229 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 8230 8231 unsigned LHS1 = MI->getOperand(1).getReg(); 8232 unsigned LHS2 = MI->getOperand(2).getReg(); 8233 if (RHSisZero) { 8234 AddDefaultPred(BuildMI(BB, dl, 8235 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8236 .addReg(LHS1).addImm(0)); 8237 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8238 .addReg(LHS2).addImm(0) 8239 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8240 } else { 8241 unsigned RHS1 = MI->getOperand(3).getReg(); 8242 unsigned RHS2 = MI->getOperand(4).getReg(); 8243 AddDefaultPred(BuildMI(BB, dl, 8244 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8245 .addReg(LHS1).addReg(RHS1)); 8246 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8247 .addReg(LHS2).addReg(RHS2) 8248 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8249 } 8250 8251 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 8252 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8253 if (MI->getOperand(0).getImm() == ARMCC::NE) 8254 std::swap(destMBB, exitMBB); 8255 8256 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8257 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8258 if (isThumb2) 8259 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8260 else 8261 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8262 8263 MI->eraseFromParent(); // The pseudo instruction is gone now. 8264 return BB; 8265 } 8266 8267 case ARM::Int_eh_sjlj_setjmp: 8268 case ARM::Int_eh_sjlj_setjmp_nofp: 8269 case ARM::tInt_eh_sjlj_setjmp: 8270 case ARM::t2Int_eh_sjlj_setjmp: 8271 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8272 return BB; 8273 8274 case ARM::Int_eh_sjlj_setup_dispatch: 8275 EmitSjLjDispatchBlock(MI, BB); 8276 return BB; 8277 8278 case ARM::ABS: 8279 case ARM::t2ABS: { 8280 // To insert an ABS instruction, we have to insert the 8281 // diamond control-flow pattern. The incoming instruction knows the 8282 // source vreg to test against 0, the destination vreg to set, 8283 // the condition code register to branch on, the 8284 // true/false values to select between, and a branch opcode to use. 8285 // It transforms 8286 // V1 = ABS V0 8287 // into 8288 // V2 = MOVS V0 8289 // BCC (branch to SinkBB if V0 >= 0) 8290 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8291 // SinkBB: V1 = PHI(V2, V3) 8292 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8293 MachineFunction::iterator BBI = ++BB->getIterator(); 8294 MachineFunction *Fn = BB->getParent(); 8295 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8296 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8297 Fn->insert(BBI, RSBBB); 8298 Fn->insert(BBI, SinkBB); 8299 8300 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 8301 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 8302 bool ABSSrcKIll = MI->getOperand(1).isKill(); 8303 bool isThumb2 = Subtarget->isThumb2(); 8304 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8305 // In Thumb mode S must not be specified if source register is the SP or 8306 // PC and if destination register is the SP, so restrict register class 8307 unsigned NewRsbDstReg = 8308 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8309 8310 // Transfer the remainder of BB and its successor edges to sinkMBB. 8311 SinkBB->splice(SinkBB->begin(), BB, 8312 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8313 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8314 8315 BB->addSuccessor(RSBBB); 8316 BB->addSuccessor(SinkBB); 8317 8318 // fall through to SinkMBB 8319 RSBBB->addSuccessor(SinkBB); 8320 8321 // insert a cmp at the end of BB 8322 AddDefaultPred(BuildMI(BB, dl, 8323 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8324 .addReg(ABSSrcReg).addImm(0)); 8325 8326 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8327 BuildMI(BB, dl, 8328 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8329 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8330 8331 // insert rsbri in RSBBB 8332 // Note: BCC and rsbri will be converted into predicated rsbmi 8333 // by if-conversion pass 8334 BuildMI(*RSBBB, RSBBB->begin(), dl, 8335 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8336 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8337 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8338 8339 // insert PHI in SinkBB, 8340 // reuse ABSDstReg to not change uses of ABS instruction 8341 BuildMI(*SinkBB, SinkBB->begin(), dl, 8342 TII->get(ARM::PHI), ABSDstReg) 8343 .addReg(NewRsbDstReg).addMBB(RSBBB) 8344 .addReg(ABSSrcReg).addMBB(BB); 8345 8346 // remove ABS instruction 8347 MI->eraseFromParent(); 8348 8349 // return last added BB 8350 return SinkBB; 8351 } 8352 case ARM::COPY_STRUCT_BYVAL_I32: 8353 ++NumLoopByVals; 8354 return EmitStructByval(MI, BB); 8355 case ARM::WIN__CHKSTK: 8356 return EmitLowered__chkstk(MI, BB); 8357 case ARM::WIN__DBZCHK: 8358 return EmitLowered__dbzchk(MI, BB); 8359 } 8360 } 8361 8362 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8363 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8364 /// instead of as a custom inserter because we need the use list from the SDNode. 8365 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8366 MachineInstr *MI, const SDNode *Node) { 8367 bool isThumb1 = Subtarget->isThumb1Only(); 8368 8369 DebugLoc DL = MI->getDebugLoc(); 8370 MachineFunction *MF = MI->getParent()->getParent(); 8371 MachineRegisterInfo &MRI = MF->getRegInfo(); 8372 MachineInstrBuilder MIB(*MF, MI); 8373 8374 // If the new dst/src is unused mark it as dead. 8375 if (!Node->hasAnyUseOfValue(0)) { 8376 MI->getOperand(0).setIsDead(true); 8377 } 8378 if (!Node->hasAnyUseOfValue(1)) { 8379 MI->getOperand(1).setIsDead(true); 8380 } 8381 8382 // The MEMCPY both defines and kills the scratch registers. 8383 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) { 8384 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8385 : &ARM::GPRRegClass); 8386 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8387 } 8388 } 8389 8390 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 8391 SDNode *Node) const { 8392 if (MI->getOpcode() == ARM::MEMCPY) { 8393 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8394 return; 8395 } 8396 8397 const MCInstrDesc *MCID = &MI->getDesc(); 8398 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8399 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8400 // operand is still set to noreg. If needed, set the optional operand's 8401 // register to CPSR, and remove the redundant implicit def. 8402 // 8403 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8404 8405 // Rename pseudo opcodes. 8406 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 8407 if (NewOpc) { 8408 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8409 MCID = &TII->get(NewOpc); 8410 8411 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 8412 "converted opcode should be the same except for cc_out"); 8413 8414 MI->setDesc(*MCID); 8415 8416 // Add the optional cc_out operand 8417 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8418 } 8419 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8420 8421 // Any ARM instruction that sets the 's' bit should specify an optional 8422 // "cc_out" operand in the last operand position. 8423 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8424 assert(!NewOpc && "Optional cc_out operand required"); 8425 return; 8426 } 8427 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8428 // since we already have an optional CPSR def. 8429 bool definesCPSR = false; 8430 bool deadCPSR = false; 8431 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 8432 i != e; ++i) { 8433 const MachineOperand &MO = MI->getOperand(i); 8434 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8435 definesCPSR = true; 8436 if (MO.isDead()) 8437 deadCPSR = true; 8438 MI->RemoveOperand(i); 8439 break; 8440 } 8441 } 8442 if (!definesCPSR) { 8443 assert(!NewOpc && "Optional cc_out operand required"); 8444 return; 8445 } 8446 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8447 if (deadCPSR) { 8448 assert(!MI->getOperand(ccOutIdx).getReg() && 8449 "expect uninitialized optional cc_out operand"); 8450 return; 8451 } 8452 8453 // If this instruction was defined with an optional CPSR def and its dag node 8454 // had a live implicit CPSR def, then activate the optional CPSR def. 8455 MachineOperand &MO = MI->getOperand(ccOutIdx); 8456 MO.setReg(ARM::CPSR); 8457 MO.setIsDef(true); 8458 } 8459 8460 //===----------------------------------------------------------------------===// 8461 // ARM Optimization Hooks 8462 //===----------------------------------------------------------------------===// 8463 8464 // Helper function that checks if N is a null or all ones constant. 8465 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8466 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8467 } 8468 8469 // Return true if N is conditionally 0 or all ones. 8470 // Detects these expressions where cc is an i1 value: 8471 // 8472 // (select cc 0, y) [AllOnes=0] 8473 // (select cc y, 0) [AllOnes=0] 8474 // (zext cc) [AllOnes=0] 8475 // (sext cc) [AllOnes=0/1] 8476 // (select cc -1, y) [AllOnes=1] 8477 // (select cc y, -1) [AllOnes=1] 8478 // 8479 // Invert is set when N is the null/all ones constant when CC is false. 8480 // OtherOp is set to the alternative value of N. 8481 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8482 SDValue &CC, bool &Invert, 8483 SDValue &OtherOp, 8484 SelectionDAG &DAG) { 8485 switch (N->getOpcode()) { 8486 default: return false; 8487 case ISD::SELECT: { 8488 CC = N->getOperand(0); 8489 SDValue N1 = N->getOperand(1); 8490 SDValue N2 = N->getOperand(2); 8491 if (isZeroOrAllOnes(N1, AllOnes)) { 8492 Invert = false; 8493 OtherOp = N2; 8494 return true; 8495 } 8496 if (isZeroOrAllOnes(N2, AllOnes)) { 8497 Invert = true; 8498 OtherOp = N1; 8499 return true; 8500 } 8501 return false; 8502 } 8503 case ISD::ZERO_EXTEND: 8504 // (zext cc) can never be the all ones value. 8505 if (AllOnes) 8506 return false; 8507 // Fall through. 8508 case ISD::SIGN_EXTEND: { 8509 SDLoc dl(N); 8510 EVT VT = N->getValueType(0); 8511 CC = N->getOperand(0); 8512 if (CC.getValueType() != MVT::i1) 8513 return false; 8514 Invert = !AllOnes; 8515 if (AllOnes) 8516 // When looking for an AllOnes constant, N is an sext, and the 'other' 8517 // value is 0. 8518 OtherOp = DAG.getConstant(0, dl, VT); 8519 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8520 // When looking for a 0 constant, N can be zext or sext. 8521 OtherOp = DAG.getConstant(1, dl, VT); 8522 else 8523 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8524 VT); 8525 return true; 8526 } 8527 } 8528 } 8529 8530 // Combine a constant select operand into its use: 8531 // 8532 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8533 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8534 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8535 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8536 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8537 // 8538 // The transform is rejected if the select doesn't have a constant operand that 8539 // is null, or all ones when AllOnes is set. 8540 // 8541 // Also recognize sext/zext from i1: 8542 // 8543 // (add (zext cc), x) -> (select cc (add x, 1), x) 8544 // (add (sext cc), x) -> (select cc (add x, -1), x) 8545 // 8546 // These transformations eventually create predicated instructions. 8547 // 8548 // @param N The node to transform. 8549 // @param Slct The N operand that is a select. 8550 // @param OtherOp The other N operand (x above). 8551 // @param DCI Context. 8552 // @param AllOnes Require the select constant to be all ones instead of null. 8553 // @returns The new node, or SDValue() on failure. 8554 static 8555 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8556 TargetLowering::DAGCombinerInfo &DCI, 8557 bool AllOnes = false) { 8558 SelectionDAG &DAG = DCI.DAG; 8559 EVT VT = N->getValueType(0); 8560 SDValue NonConstantVal; 8561 SDValue CCOp; 8562 bool SwapSelectOps; 8563 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8564 NonConstantVal, DAG)) 8565 return SDValue(); 8566 8567 // Slct is now know to be the desired identity constant when CC is true. 8568 SDValue TrueVal = OtherOp; 8569 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8570 OtherOp, NonConstantVal); 8571 // Unless SwapSelectOps says CC should be false. 8572 if (SwapSelectOps) 8573 std::swap(TrueVal, FalseVal); 8574 8575 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8576 CCOp, TrueVal, FalseVal); 8577 } 8578 8579 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8580 static 8581 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8582 TargetLowering::DAGCombinerInfo &DCI) { 8583 SDValue N0 = N->getOperand(0); 8584 SDValue N1 = N->getOperand(1); 8585 if (N0.getNode()->hasOneUse()) 8586 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 8587 return Result; 8588 if (N1.getNode()->hasOneUse()) 8589 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 8590 return Result; 8591 return SDValue(); 8592 } 8593 8594 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8595 // (only after legalization). 8596 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8597 TargetLowering::DAGCombinerInfo &DCI, 8598 const ARMSubtarget *Subtarget) { 8599 8600 // Only perform optimization if after legalize, and if NEON is available. We 8601 // also expected both operands to be BUILD_VECTORs. 8602 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8603 || N0.getOpcode() != ISD::BUILD_VECTOR 8604 || N1.getOpcode() != ISD::BUILD_VECTOR) 8605 return SDValue(); 8606 8607 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8608 EVT VT = N->getValueType(0); 8609 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8610 return SDValue(); 8611 8612 // Check that the vector operands are of the right form. 8613 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8614 // operands, where N is the size of the formed vector. 8615 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8616 // index such that we have a pair wise add pattern. 8617 8618 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8619 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8620 return SDValue(); 8621 SDValue Vec = N0->getOperand(0)->getOperand(0); 8622 SDNode *V = Vec.getNode(); 8623 unsigned nextIndex = 0; 8624 8625 // For each operands to the ADD which are BUILD_VECTORs, 8626 // check to see if each of their operands are an EXTRACT_VECTOR with 8627 // the same vector and appropriate index. 8628 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8629 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8630 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8631 8632 SDValue ExtVec0 = N0->getOperand(i); 8633 SDValue ExtVec1 = N1->getOperand(i); 8634 8635 // First operand is the vector, verify its the same. 8636 if (V != ExtVec0->getOperand(0).getNode() || 8637 V != ExtVec1->getOperand(0).getNode()) 8638 return SDValue(); 8639 8640 // Second is the constant, verify its correct. 8641 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8642 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8643 8644 // For the constant, we want to see all the even or all the odd. 8645 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8646 || C1->getZExtValue() != nextIndex+1) 8647 return SDValue(); 8648 8649 // Increment index. 8650 nextIndex+=2; 8651 } else 8652 return SDValue(); 8653 } 8654 8655 // Create VPADDL node. 8656 SelectionDAG &DAG = DCI.DAG; 8657 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8658 8659 SDLoc dl(N); 8660 8661 // Build operand list. 8662 SmallVector<SDValue, 8> Ops; 8663 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8664 TLI.getPointerTy(DAG.getDataLayout()))); 8665 8666 // Input is the vector. 8667 Ops.push_back(Vec); 8668 8669 // Get widened type and narrowed type. 8670 MVT widenType; 8671 unsigned numElem = VT.getVectorNumElements(); 8672 8673 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8674 switch (inputLaneType.getSimpleVT().SimpleTy) { 8675 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8676 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8677 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8678 default: 8679 llvm_unreachable("Invalid vector element type for padd optimization."); 8680 } 8681 8682 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8683 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8684 return DAG.getNode(ExtOp, dl, VT, tmp); 8685 } 8686 8687 static SDValue findMUL_LOHI(SDValue V) { 8688 if (V->getOpcode() == ISD::UMUL_LOHI || 8689 V->getOpcode() == ISD::SMUL_LOHI) 8690 return V; 8691 return SDValue(); 8692 } 8693 8694 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8695 TargetLowering::DAGCombinerInfo &DCI, 8696 const ARMSubtarget *Subtarget) { 8697 8698 if (Subtarget->isThumb1Only()) return SDValue(); 8699 8700 // Only perform the checks after legalize when the pattern is available. 8701 if (DCI.isBeforeLegalize()) return SDValue(); 8702 8703 // Look for multiply add opportunities. 8704 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8705 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8706 // a glue link from the first add to the second add. 8707 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8708 // a S/UMLAL instruction. 8709 // UMUL_LOHI 8710 // / :lo \ :hi 8711 // / \ [no multiline comment] 8712 // loAdd -> ADDE | 8713 // \ :glue / 8714 // \ / 8715 // ADDC <- hiAdd 8716 // 8717 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8718 SDValue AddcOp0 = AddcNode->getOperand(0); 8719 SDValue AddcOp1 = AddcNode->getOperand(1); 8720 8721 // Check if the two operands are from the same mul_lohi node. 8722 if (AddcOp0.getNode() == AddcOp1.getNode()) 8723 return SDValue(); 8724 8725 assert(AddcNode->getNumValues() == 2 && 8726 AddcNode->getValueType(0) == MVT::i32 && 8727 "Expect ADDC with two result values. First: i32"); 8728 8729 // Check that we have a glued ADDC node. 8730 if (AddcNode->getValueType(1) != MVT::Glue) 8731 return SDValue(); 8732 8733 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8734 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8735 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8736 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8737 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8738 return SDValue(); 8739 8740 // Look for the glued ADDE. 8741 SDNode* AddeNode = AddcNode->getGluedUser(); 8742 if (!AddeNode) 8743 return SDValue(); 8744 8745 // Make sure it is really an ADDE. 8746 if (AddeNode->getOpcode() != ISD::ADDE) 8747 return SDValue(); 8748 8749 assert(AddeNode->getNumOperands() == 3 && 8750 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8751 "ADDE node has the wrong inputs"); 8752 8753 // Check for the triangle shape. 8754 SDValue AddeOp0 = AddeNode->getOperand(0); 8755 SDValue AddeOp1 = AddeNode->getOperand(1); 8756 8757 // Make sure that the ADDE operands are not coming from the same node. 8758 if (AddeOp0.getNode() == AddeOp1.getNode()) 8759 return SDValue(); 8760 8761 // Find the MUL_LOHI node walking up ADDE's operands. 8762 bool IsLeftOperandMUL = false; 8763 SDValue MULOp = findMUL_LOHI(AddeOp0); 8764 if (MULOp == SDValue()) 8765 MULOp = findMUL_LOHI(AddeOp1); 8766 else 8767 IsLeftOperandMUL = true; 8768 if (MULOp == SDValue()) 8769 return SDValue(); 8770 8771 // Figure out the right opcode. 8772 unsigned Opc = MULOp->getOpcode(); 8773 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8774 8775 // Figure out the high and low input values to the MLAL node. 8776 SDValue* HiAdd = nullptr; 8777 SDValue* LoMul = nullptr; 8778 SDValue* LowAdd = nullptr; 8779 8780 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8781 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8782 return SDValue(); 8783 8784 if (IsLeftOperandMUL) 8785 HiAdd = &AddeOp1; 8786 else 8787 HiAdd = &AddeOp0; 8788 8789 8790 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8791 // whose low result is fed to the ADDC we are checking. 8792 8793 if (AddcOp0 == MULOp.getValue(0)) { 8794 LoMul = &AddcOp0; 8795 LowAdd = &AddcOp1; 8796 } 8797 if (AddcOp1 == MULOp.getValue(0)) { 8798 LoMul = &AddcOp1; 8799 LowAdd = &AddcOp0; 8800 } 8801 8802 if (!LoMul) 8803 return SDValue(); 8804 8805 // Create the merged node. 8806 SelectionDAG &DAG = DCI.DAG; 8807 8808 // Build operand list. 8809 SmallVector<SDValue, 8> Ops; 8810 Ops.push_back(LoMul->getOperand(0)); 8811 Ops.push_back(LoMul->getOperand(1)); 8812 Ops.push_back(*LowAdd); 8813 Ops.push_back(*HiAdd); 8814 8815 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8816 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8817 8818 // Replace the ADDs' nodes uses by the MLA node's values. 8819 SDValue HiMLALResult(MLALNode.getNode(), 1); 8820 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8821 8822 SDValue LoMLALResult(MLALNode.getNode(), 0); 8823 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8824 8825 // Return original node to notify the driver to stop replacing. 8826 SDValue resNode(AddcNode, 0); 8827 return resNode; 8828 } 8829 8830 /// PerformADDCCombine - Target-specific dag combine transform from 8831 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 8832 static SDValue PerformADDCCombine(SDNode *N, 8833 TargetLowering::DAGCombinerInfo &DCI, 8834 const ARMSubtarget *Subtarget) { 8835 8836 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 8837 8838 } 8839 8840 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 8841 /// operands N0 and N1. This is a helper for PerformADDCombine that is 8842 /// called with the default operands, and if that fails, with commuted 8843 /// operands. 8844 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 8845 TargetLowering::DAGCombinerInfo &DCI, 8846 const ARMSubtarget *Subtarget){ 8847 8848 // Attempt to create vpaddl for this add. 8849 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget)) 8850 return Result; 8851 8852 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8853 if (N0.getNode()->hasOneUse()) 8854 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 8855 return Result; 8856 return SDValue(); 8857 } 8858 8859 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 8860 /// 8861 static SDValue PerformADDCombine(SDNode *N, 8862 TargetLowering::DAGCombinerInfo &DCI, 8863 const ARMSubtarget *Subtarget) { 8864 SDValue N0 = N->getOperand(0); 8865 SDValue N1 = N->getOperand(1); 8866 8867 // First try with the default operand order. 8868 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 8869 return Result; 8870 8871 // If that didn't work, try again with the operands commuted. 8872 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 8873 } 8874 8875 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 8876 /// 8877 static SDValue PerformSUBCombine(SDNode *N, 8878 TargetLowering::DAGCombinerInfo &DCI) { 8879 SDValue N0 = N->getOperand(0); 8880 SDValue N1 = N->getOperand(1); 8881 8882 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8883 if (N1.getNode()->hasOneUse()) 8884 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 8885 return Result; 8886 8887 return SDValue(); 8888 } 8889 8890 /// PerformVMULCombine 8891 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 8892 /// special multiplier accumulator forwarding. 8893 /// vmul d3, d0, d2 8894 /// vmla d3, d1, d2 8895 /// is faster than 8896 /// vadd d3, d0, d1 8897 /// vmul d3, d3, d2 8898 // However, for (A + B) * (A + B), 8899 // vadd d2, d0, d1 8900 // vmul d3, d0, d2 8901 // vmla d3, d1, d2 8902 // is slower than 8903 // vadd d2, d0, d1 8904 // vmul d3, d2, d2 8905 static SDValue PerformVMULCombine(SDNode *N, 8906 TargetLowering::DAGCombinerInfo &DCI, 8907 const ARMSubtarget *Subtarget) { 8908 if (!Subtarget->hasVMLxForwarding()) 8909 return SDValue(); 8910 8911 SelectionDAG &DAG = DCI.DAG; 8912 SDValue N0 = N->getOperand(0); 8913 SDValue N1 = N->getOperand(1); 8914 unsigned Opcode = N0.getOpcode(); 8915 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8916 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 8917 Opcode = N1.getOpcode(); 8918 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8919 Opcode != ISD::FADD && Opcode != ISD::FSUB) 8920 return SDValue(); 8921 std::swap(N0, N1); 8922 } 8923 8924 if (N0 == N1) 8925 return SDValue(); 8926 8927 EVT VT = N->getValueType(0); 8928 SDLoc DL(N); 8929 SDValue N00 = N0->getOperand(0); 8930 SDValue N01 = N0->getOperand(1); 8931 return DAG.getNode(Opcode, DL, VT, 8932 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 8933 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 8934 } 8935 8936 static SDValue PerformMULCombine(SDNode *N, 8937 TargetLowering::DAGCombinerInfo &DCI, 8938 const ARMSubtarget *Subtarget) { 8939 SelectionDAG &DAG = DCI.DAG; 8940 8941 if (Subtarget->isThumb1Only()) 8942 return SDValue(); 8943 8944 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8945 return SDValue(); 8946 8947 EVT VT = N->getValueType(0); 8948 if (VT.is64BitVector() || VT.is128BitVector()) 8949 return PerformVMULCombine(N, DCI, Subtarget); 8950 if (VT != MVT::i32) 8951 return SDValue(); 8952 8953 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8954 if (!C) 8955 return SDValue(); 8956 8957 int64_t MulAmt = C->getSExtValue(); 8958 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 8959 8960 ShiftAmt = ShiftAmt & (32 - 1); 8961 SDValue V = N->getOperand(0); 8962 SDLoc DL(N); 8963 8964 SDValue Res; 8965 MulAmt >>= ShiftAmt; 8966 8967 if (MulAmt >= 0) { 8968 if (isPowerOf2_32(MulAmt - 1)) { 8969 // (mul x, 2^N + 1) => (add (shl x, N), x) 8970 Res = DAG.getNode(ISD::ADD, DL, VT, 8971 V, 8972 DAG.getNode(ISD::SHL, DL, VT, 8973 V, 8974 DAG.getConstant(Log2_32(MulAmt - 1), DL, 8975 MVT::i32))); 8976 } else if (isPowerOf2_32(MulAmt + 1)) { 8977 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8978 Res = DAG.getNode(ISD::SUB, DL, VT, 8979 DAG.getNode(ISD::SHL, DL, VT, 8980 V, 8981 DAG.getConstant(Log2_32(MulAmt + 1), DL, 8982 MVT::i32)), 8983 V); 8984 } else 8985 return SDValue(); 8986 } else { 8987 uint64_t MulAmtAbs = -MulAmt; 8988 if (isPowerOf2_32(MulAmtAbs + 1)) { 8989 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8990 Res = DAG.getNode(ISD::SUB, DL, VT, 8991 V, 8992 DAG.getNode(ISD::SHL, DL, VT, 8993 V, 8994 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 8995 MVT::i32))); 8996 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 8997 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8998 Res = DAG.getNode(ISD::ADD, DL, VT, 8999 V, 9000 DAG.getNode(ISD::SHL, DL, VT, 9001 V, 9002 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 9003 MVT::i32))); 9004 Res = DAG.getNode(ISD::SUB, DL, VT, 9005 DAG.getConstant(0, DL, MVT::i32), Res); 9006 9007 } else 9008 return SDValue(); 9009 } 9010 9011 if (ShiftAmt != 0) 9012 Res = DAG.getNode(ISD::SHL, DL, VT, 9013 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 9014 9015 // Do not add new nodes to DAG combiner worklist. 9016 DCI.CombineTo(N, Res, false); 9017 return SDValue(); 9018 } 9019 9020 static SDValue PerformANDCombine(SDNode *N, 9021 TargetLowering::DAGCombinerInfo &DCI, 9022 const ARMSubtarget *Subtarget) { 9023 9024 // Attempt to use immediate-form VBIC 9025 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9026 SDLoc dl(N); 9027 EVT VT = N->getValueType(0); 9028 SelectionDAG &DAG = DCI.DAG; 9029 9030 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9031 return SDValue(); 9032 9033 APInt SplatBits, SplatUndef; 9034 unsigned SplatBitSize; 9035 bool HasAnyUndefs; 9036 if (BVN && 9037 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9038 if (SplatBitSize <= 64) { 9039 EVT VbicVT; 9040 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9041 SplatUndef.getZExtValue(), SplatBitSize, 9042 DAG, dl, VbicVT, VT.is128BitVector(), 9043 OtherModImm); 9044 if (Val.getNode()) { 9045 SDValue Input = 9046 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9047 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9048 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9049 } 9050 } 9051 } 9052 9053 if (!Subtarget->isThumb1Only()) { 9054 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9055 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9056 return Result; 9057 } 9058 9059 return SDValue(); 9060 } 9061 9062 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9063 static SDValue PerformORCombine(SDNode *N, 9064 TargetLowering::DAGCombinerInfo &DCI, 9065 const ARMSubtarget *Subtarget) { 9066 // Attempt to use immediate-form VORR 9067 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9068 SDLoc dl(N); 9069 EVT VT = N->getValueType(0); 9070 SelectionDAG &DAG = DCI.DAG; 9071 9072 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9073 return SDValue(); 9074 9075 APInt SplatBits, SplatUndef; 9076 unsigned SplatBitSize; 9077 bool HasAnyUndefs; 9078 if (BVN && Subtarget->hasNEON() && 9079 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9080 if (SplatBitSize <= 64) { 9081 EVT VorrVT; 9082 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9083 SplatUndef.getZExtValue(), SplatBitSize, 9084 DAG, dl, VorrVT, VT.is128BitVector(), 9085 OtherModImm); 9086 if (Val.getNode()) { 9087 SDValue Input = 9088 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9089 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9090 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9091 } 9092 } 9093 } 9094 9095 if (!Subtarget->isThumb1Only()) { 9096 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9097 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9098 return Result; 9099 } 9100 9101 // The code below optimizes (or (and X, Y), Z). 9102 // The AND operand needs to have a single user to make these optimizations 9103 // profitable. 9104 SDValue N0 = N->getOperand(0); 9105 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9106 return SDValue(); 9107 SDValue N1 = N->getOperand(1); 9108 9109 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9110 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9111 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9112 APInt SplatUndef; 9113 unsigned SplatBitSize; 9114 bool HasAnyUndefs; 9115 9116 APInt SplatBits0, SplatBits1; 9117 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9118 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9119 // Ensure that the second operand of both ands are constants 9120 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9121 HasAnyUndefs) && !HasAnyUndefs) { 9122 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9123 HasAnyUndefs) && !HasAnyUndefs) { 9124 // Ensure that the bit width of the constants are the same and that 9125 // the splat arguments are logical inverses as per the pattern we 9126 // are trying to simplify. 9127 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9128 SplatBits0 == ~SplatBits1) { 9129 // Canonicalize the vector type to make instruction selection 9130 // simpler. 9131 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9132 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9133 N0->getOperand(1), 9134 N0->getOperand(0), 9135 N1->getOperand(0)); 9136 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9137 } 9138 } 9139 } 9140 } 9141 9142 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9143 // reasonable. 9144 9145 // BFI is only available on V6T2+ 9146 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9147 return SDValue(); 9148 9149 SDLoc DL(N); 9150 // 1) or (and A, mask), val => ARMbfi A, val, mask 9151 // iff (val & mask) == val 9152 // 9153 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9154 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9155 // && mask == ~mask2 9156 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9157 // && ~mask == mask2 9158 // (i.e., copy a bitfield value into another bitfield of the same width) 9159 9160 if (VT != MVT::i32) 9161 return SDValue(); 9162 9163 SDValue N00 = N0.getOperand(0); 9164 9165 // The value and the mask need to be constants so we can verify this is 9166 // actually a bitfield set. If the mask is 0xffff, we can do better 9167 // via a movt instruction, so don't use BFI in that case. 9168 SDValue MaskOp = N0.getOperand(1); 9169 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9170 if (!MaskC) 9171 return SDValue(); 9172 unsigned Mask = MaskC->getZExtValue(); 9173 if (Mask == 0xffff) 9174 return SDValue(); 9175 SDValue Res; 9176 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9177 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9178 if (N1C) { 9179 unsigned Val = N1C->getZExtValue(); 9180 if ((Val & ~Mask) != Val) 9181 return SDValue(); 9182 9183 if (ARM::isBitFieldInvertedMask(Mask)) { 9184 Val >>= countTrailingZeros(~Mask); 9185 9186 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9187 DAG.getConstant(Val, DL, MVT::i32), 9188 DAG.getConstant(Mask, DL, MVT::i32)); 9189 9190 // Do not add new nodes to DAG combiner worklist. 9191 DCI.CombineTo(N, Res, false); 9192 return SDValue(); 9193 } 9194 } else if (N1.getOpcode() == ISD::AND) { 9195 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9196 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9197 if (!N11C) 9198 return SDValue(); 9199 unsigned Mask2 = N11C->getZExtValue(); 9200 9201 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9202 // as is to match. 9203 if (ARM::isBitFieldInvertedMask(Mask) && 9204 (Mask == ~Mask2)) { 9205 // The pack halfword instruction works better for masks that fit it, 9206 // so use that when it's available. 9207 if (Subtarget->hasT2ExtractPack() && 9208 (Mask == 0xffff || Mask == 0xffff0000)) 9209 return SDValue(); 9210 // 2a 9211 unsigned amt = countTrailingZeros(Mask2); 9212 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9213 DAG.getConstant(amt, DL, MVT::i32)); 9214 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9215 DAG.getConstant(Mask, DL, MVT::i32)); 9216 // Do not add new nodes to DAG combiner worklist. 9217 DCI.CombineTo(N, Res, false); 9218 return SDValue(); 9219 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9220 (~Mask == Mask2)) { 9221 // The pack halfword instruction works better for masks that fit it, 9222 // so use that when it's available. 9223 if (Subtarget->hasT2ExtractPack() && 9224 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9225 return SDValue(); 9226 // 2b 9227 unsigned lsb = countTrailingZeros(Mask); 9228 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9229 DAG.getConstant(lsb, DL, MVT::i32)); 9230 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9231 DAG.getConstant(Mask2, DL, MVT::i32)); 9232 // Do not add new nodes to DAG combiner worklist. 9233 DCI.CombineTo(N, Res, false); 9234 return SDValue(); 9235 } 9236 } 9237 9238 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9239 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9240 ARM::isBitFieldInvertedMask(~Mask)) { 9241 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9242 // where lsb(mask) == #shamt and masked bits of B are known zero. 9243 SDValue ShAmt = N00.getOperand(1); 9244 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9245 unsigned LSB = countTrailingZeros(Mask); 9246 if (ShAmtC != LSB) 9247 return SDValue(); 9248 9249 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9250 DAG.getConstant(~Mask, DL, MVT::i32)); 9251 9252 // Do not add new nodes to DAG combiner worklist. 9253 DCI.CombineTo(N, Res, false); 9254 } 9255 9256 return SDValue(); 9257 } 9258 9259 static SDValue PerformXORCombine(SDNode *N, 9260 TargetLowering::DAGCombinerInfo &DCI, 9261 const ARMSubtarget *Subtarget) { 9262 EVT VT = N->getValueType(0); 9263 SelectionDAG &DAG = DCI.DAG; 9264 9265 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9266 return SDValue(); 9267 9268 if (!Subtarget->isThumb1Only()) { 9269 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9270 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9271 return Result; 9272 } 9273 9274 return SDValue(); 9275 } 9276 9277 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9278 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9279 // their position in "to" (Rd). 9280 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9281 assert(N->getOpcode() == ARMISD::BFI); 9282 9283 SDValue From = N->getOperand(1); 9284 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9285 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9286 9287 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9288 // #C in the base of the SHR. 9289 if (From->getOpcode() == ISD::SRL && 9290 isa<ConstantSDNode>(From->getOperand(1))) { 9291 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9292 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9293 FromMask <<= Shift.getLimitedValue(31); 9294 From = From->getOperand(0); 9295 } 9296 9297 return From; 9298 } 9299 9300 // If A and B contain one contiguous set of bits, does A | B == A . B? 9301 // 9302 // Neither A nor B must be zero. 9303 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9304 unsigned LastActiveBitInA = A.countTrailingZeros(); 9305 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9306 return LastActiveBitInA - 1 == FirstActiveBitInB; 9307 } 9308 9309 static SDValue FindBFIToCombineWith(SDNode *N) { 9310 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9311 // if one exists. 9312 APInt ToMask, FromMask; 9313 SDValue From = ParseBFI(N, ToMask, FromMask); 9314 SDValue To = N->getOperand(0); 9315 9316 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9317 // aren't compatible, but not if they set the same bit in their destination as 9318 // we do (or that of any BFI we're going to combine with). 9319 SDValue V = To; 9320 APInt CombinedToMask = ToMask; 9321 while (V.getOpcode() == ARMISD::BFI) { 9322 APInt NewToMask, NewFromMask; 9323 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9324 if (NewFrom != From) { 9325 // This BFI has a different base. Keep going. 9326 CombinedToMask |= NewToMask; 9327 V = V.getOperand(0); 9328 continue; 9329 } 9330 9331 // Do the written bits conflict with any we've seen so far? 9332 if ((NewToMask & CombinedToMask).getBoolValue()) 9333 // Conflicting bits - bail out because going further is unsafe. 9334 return SDValue(); 9335 9336 // Are the new bits contiguous when combined with the old bits? 9337 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9338 BitsProperlyConcatenate(FromMask, NewFromMask)) 9339 return V; 9340 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9341 BitsProperlyConcatenate(NewFromMask, FromMask)) 9342 return V; 9343 9344 // We've seen a write to some bits, so track it. 9345 CombinedToMask |= NewToMask; 9346 // Keep going... 9347 V = V.getOperand(0); 9348 } 9349 9350 return SDValue(); 9351 } 9352 9353 static SDValue PerformBFICombine(SDNode *N, 9354 TargetLowering::DAGCombinerInfo &DCI) { 9355 SDValue N1 = N->getOperand(1); 9356 if (N1.getOpcode() == ISD::AND) { 9357 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9358 // the bits being cleared by the AND are not demanded by the BFI. 9359 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9360 if (!N11C) 9361 return SDValue(); 9362 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9363 unsigned LSB = countTrailingZeros(~InvMask); 9364 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9365 assert(Width < 9366 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9367 "undefined behavior"); 9368 unsigned Mask = (1u << Width) - 1; 9369 unsigned Mask2 = N11C->getZExtValue(); 9370 if ((Mask & (~Mask2)) == 0) 9371 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9372 N->getOperand(0), N1.getOperand(0), 9373 N->getOperand(2)); 9374 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9375 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9376 // Keep track of any consecutive bits set that all come from the same base 9377 // value. We can combine these together into a single BFI. 9378 SDValue CombineBFI = FindBFIToCombineWith(N); 9379 if (CombineBFI == SDValue()) 9380 return SDValue(); 9381 9382 // We've found a BFI. 9383 APInt ToMask1, FromMask1; 9384 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9385 9386 APInt ToMask2, FromMask2; 9387 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9388 assert(From1 == From2); 9389 (void)From2; 9390 9391 // First, unlink CombineBFI. 9392 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9393 // Then create a new BFI, combining the two together. 9394 APInt NewFromMask = FromMask1 | FromMask2; 9395 APInt NewToMask = ToMask1 | ToMask2; 9396 9397 EVT VT = N->getValueType(0); 9398 SDLoc dl(N); 9399 9400 if (NewFromMask[0] == 0) 9401 From1 = DCI.DAG.getNode( 9402 ISD::SRL, dl, VT, From1, 9403 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9404 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9405 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9406 } 9407 return SDValue(); 9408 } 9409 9410 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9411 /// ARMISD::VMOVRRD. 9412 static SDValue PerformVMOVRRDCombine(SDNode *N, 9413 TargetLowering::DAGCombinerInfo &DCI, 9414 const ARMSubtarget *Subtarget) { 9415 // vmovrrd(vmovdrr x, y) -> x,y 9416 SDValue InDouble = N->getOperand(0); 9417 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9418 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9419 9420 // vmovrrd(load f64) -> (load i32), (load i32) 9421 SDNode *InNode = InDouble.getNode(); 9422 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9423 InNode->getValueType(0) == MVT::f64 && 9424 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9425 !cast<LoadSDNode>(InNode)->isVolatile()) { 9426 // TODO: Should this be done for non-FrameIndex operands? 9427 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9428 9429 SelectionDAG &DAG = DCI.DAG; 9430 SDLoc DL(LD); 9431 SDValue BasePtr = LD->getBasePtr(); 9432 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 9433 LD->getPointerInfo(), LD->isVolatile(), 9434 LD->isNonTemporal(), LD->isInvariant(), 9435 LD->getAlignment()); 9436 9437 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9438 DAG.getConstant(4, DL, MVT::i32)); 9439 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 9440 LD->getPointerInfo(), LD->isVolatile(), 9441 LD->isNonTemporal(), LD->isInvariant(), 9442 std::min(4U, LD->getAlignment() / 2)); 9443 9444 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9445 if (DCI.DAG.getDataLayout().isBigEndian()) 9446 std::swap (NewLD1, NewLD2); 9447 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9448 return Result; 9449 } 9450 9451 return SDValue(); 9452 } 9453 9454 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9455 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9456 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9457 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9458 SDValue Op0 = N->getOperand(0); 9459 SDValue Op1 = N->getOperand(1); 9460 if (Op0.getOpcode() == ISD::BITCAST) 9461 Op0 = Op0.getOperand(0); 9462 if (Op1.getOpcode() == ISD::BITCAST) 9463 Op1 = Op1.getOperand(0); 9464 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9465 Op0.getNode() == Op1.getNode() && 9466 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9467 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9468 N->getValueType(0), Op0.getOperand(0)); 9469 return SDValue(); 9470 } 9471 9472 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9473 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9474 /// i64 vector to have f64 elements, since the value can then be loaded 9475 /// directly into a VFP register. 9476 static bool hasNormalLoadOperand(SDNode *N) { 9477 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9478 for (unsigned i = 0; i < NumElts; ++i) { 9479 SDNode *Elt = N->getOperand(i).getNode(); 9480 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9481 return true; 9482 } 9483 return false; 9484 } 9485 9486 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9487 /// ISD::BUILD_VECTOR. 9488 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9489 TargetLowering::DAGCombinerInfo &DCI, 9490 const ARMSubtarget *Subtarget) { 9491 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9492 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9493 // into a pair of GPRs, which is fine when the value is used as a scalar, 9494 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9495 SelectionDAG &DAG = DCI.DAG; 9496 if (N->getNumOperands() == 2) 9497 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 9498 return RV; 9499 9500 // Load i64 elements as f64 values so that type legalization does not split 9501 // them up into i32 values. 9502 EVT VT = N->getValueType(0); 9503 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9504 return SDValue(); 9505 SDLoc dl(N); 9506 SmallVector<SDValue, 8> Ops; 9507 unsigned NumElts = VT.getVectorNumElements(); 9508 for (unsigned i = 0; i < NumElts; ++i) { 9509 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9510 Ops.push_back(V); 9511 // Make the DAGCombiner fold the bitcast. 9512 DCI.AddToWorklist(V.getNode()); 9513 } 9514 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9515 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 9516 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9517 } 9518 9519 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9520 static SDValue 9521 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9522 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9523 // At that time, we may have inserted bitcasts from integer to float. 9524 // If these bitcasts have survived DAGCombine, change the lowering of this 9525 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9526 // force to use floating point types. 9527 9528 // Make sure we can change the type of the vector. 9529 // This is possible iff: 9530 // 1. The vector is only used in a bitcast to a integer type. I.e., 9531 // 1.1. Vector is used only once. 9532 // 1.2. Use is a bit convert to an integer type. 9533 // 2. The size of its operands are 32-bits (64-bits are not legal). 9534 EVT VT = N->getValueType(0); 9535 EVT EltVT = VT.getVectorElementType(); 9536 9537 // Check 1.1. and 2. 9538 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9539 return SDValue(); 9540 9541 // By construction, the input type must be float. 9542 assert(EltVT == MVT::f32 && "Unexpected type!"); 9543 9544 // Check 1.2. 9545 SDNode *Use = *N->use_begin(); 9546 if (Use->getOpcode() != ISD::BITCAST || 9547 Use->getValueType(0).isFloatingPoint()) 9548 return SDValue(); 9549 9550 // Check profitability. 9551 // Model is, if more than half of the relevant operands are bitcast from 9552 // i32, turn the build_vector into a sequence of insert_vector_elt. 9553 // Relevant operands are everything that is not statically 9554 // (i.e., at compile time) bitcasted. 9555 unsigned NumOfBitCastedElts = 0; 9556 unsigned NumElts = VT.getVectorNumElements(); 9557 unsigned NumOfRelevantElts = NumElts; 9558 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9559 SDValue Elt = N->getOperand(Idx); 9560 if (Elt->getOpcode() == ISD::BITCAST) { 9561 // Assume only bit cast to i32 will go away. 9562 if (Elt->getOperand(0).getValueType() == MVT::i32) 9563 ++NumOfBitCastedElts; 9564 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 9565 // Constants are statically casted, thus do not count them as 9566 // relevant operands. 9567 --NumOfRelevantElts; 9568 } 9569 9570 // Check if more than half of the elements require a non-free bitcast. 9571 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9572 return SDValue(); 9573 9574 SelectionDAG &DAG = DCI.DAG; 9575 // Create the new vector type. 9576 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9577 // Check if the type is legal. 9578 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9579 if (!TLI.isTypeLegal(VecVT)) 9580 return SDValue(); 9581 9582 // Combine: 9583 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9584 // => BITCAST INSERT_VECTOR_ELT 9585 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9586 // (BITCAST EN), N. 9587 SDValue Vec = DAG.getUNDEF(VecVT); 9588 SDLoc dl(N); 9589 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9590 SDValue V = N->getOperand(Idx); 9591 if (V.isUndef()) 9592 continue; 9593 if (V.getOpcode() == ISD::BITCAST && 9594 V->getOperand(0).getValueType() == MVT::i32) 9595 // Fold obvious case. 9596 V = V.getOperand(0); 9597 else { 9598 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9599 // Make the DAGCombiner fold the bitcasts. 9600 DCI.AddToWorklist(V.getNode()); 9601 } 9602 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9603 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9604 } 9605 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9606 // Make the DAGCombiner fold the bitcasts. 9607 DCI.AddToWorklist(Vec.getNode()); 9608 return Vec; 9609 } 9610 9611 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9612 /// ISD::INSERT_VECTOR_ELT. 9613 static SDValue PerformInsertEltCombine(SDNode *N, 9614 TargetLowering::DAGCombinerInfo &DCI) { 9615 // Bitcast an i64 load inserted into a vector to f64. 9616 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9617 EVT VT = N->getValueType(0); 9618 SDNode *Elt = N->getOperand(1).getNode(); 9619 if (VT.getVectorElementType() != MVT::i64 || 9620 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9621 return SDValue(); 9622 9623 SelectionDAG &DAG = DCI.DAG; 9624 SDLoc dl(N); 9625 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9626 VT.getVectorNumElements()); 9627 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9628 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9629 // Make the DAGCombiner fold the bitcasts. 9630 DCI.AddToWorklist(Vec.getNode()); 9631 DCI.AddToWorklist(V.getNode()); 9632 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9633 Vec, V, N->getOperand(2)); 9634 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9635 } 9636 9637 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9638 /// ISD::VECTOR_SHUFFLE. 9639 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9640 // The LLVM shufflevector instruction does not require the shuffle mask 9641 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9642 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9643 // operands do not match the mask length, they are extended by concatenating 9644 // them with undef vectors. That is probably the right thing for other 9645 // targets, but for NEON it is better to concatenate two double-register 9646 // size vector operands into a single quad-register size vector. Do that 9647 // transformation here: 9648 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9649 // shuffle(concat(v1, v2), undef) 9650 SDValue Op0 = N->getOperand(0); 9651 SDValue Op1 = N->getOperand(1); 9652 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9653 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9654 Op0.getNumOperands() != 2 || 9655 Op1.getNumOperands() != 2) 9656 return SDValue(); 9657 SDValue Concat0Op1 = Op0.getOperand(1); 9658 SDValue Concat1Op1 = Op1.getOperand(1); 9659 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 9660 return SDValue(); 9661 // Skip the transformation if any of the types are illegal. 9662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9663 EVT VT = N->getValueType(0); 9664 if (!TLI.isTypeLegal(VT) || 9665 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9666 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9667 return SDValue(); 9668 9669 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9670 Op0.getOperand(0), Op1.getOperand(0)); 9671 // Translate the shuffle mask. 9672 SmallVector<int, 16> NewMask; 9673 unsigned NumElts = VT.getVectorNumElements(); 9674 unsigned HalfElts = NumElts/2; 9675 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9676 for (unsigned n = 0; n < NumElts; ++n) { 9677 int MaskElt = SVN->getMaskElt(n); 9678 int NewElt = -1; 9679 if (MaskElt < (int)HalfElts) 9680 NewElt = MaskElt; 9681 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9682 NewElt = HalfElts + MaskElt - NumElts; 9683 NewMask.push_back(NewElt); 9684 } 9685 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9686 DAG.getUNDEF(VT), NewMask.data()); 9687 } 9688 9689 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9690 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9691 /// base address updates. 9692 /// For generic load/stores, the memory type is assumed to be a vector. 9693 /// The caller is assumed to have checked legality. 9694 static SDValue CombineBaseUpdate(SDNode *N, 9695 TargetLowering::DAGCombinerInfo &DCI) { 9696 SelectionDAG &DAG = DCI.DAG; 9697 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9698 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9699 const bool isStore = N->getOpcode() == ISD::STORE; 9700 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9701 SDValue Addr = N->getOperand(AddrOpIdx); 9702 MemSDNode *MemN = cast<MemSDNode>(N); 9703 SDLoc dl(N); 9704 9705 // Search for a use of the address operand that is an increment. 9706 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9707 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9708 SDNode *User = *UI; 9709 if (User->getOpcode() != ISD::ADD || 9710 UI.getUse().getResNo() != Addr.getResNo()) 9711 continue; 9712 9713 // Check that the add is independent of the load/store. Otherwise, folding 9714 // it would create a cycle. 9715 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9716 continue; 9717 9718 // Find the new opcode for the updating load/store. 9719 bool isLoadOp = true; 9720 bool isLaneOp = false; 9721 unsigned NewOpc = 0; 9722 unsigned NumVecs = 0; 9723 if (isIntrinsic) { 9724 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9725 switch (IntNo) { 9726 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9727 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9728 NumVecs = 1; break; 9729 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9730 NumVecs = 2; break; 9731 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9732 NumVecs = 3; break; 9733 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9734 NumVecs = 4; break; 9735 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9736 NumVecs = 2; isLaneOp = true; break; 9737 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9738 NumVecs = 3; isLaneOp = true; break; 9739 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9740 NumVecs = 4; isLaneOp = true; break; 9741 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9742 NumVecs = 1; isLoadOp = false; break; 9743 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9744 NumVecs = 2; isLoadOp = false; break; 9745 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9746 NumVecs = 3; isLoadOp = false; break; 9747 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9748 NumVecs = 4; isLoadOp = false; break; 9749 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9750 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9751 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9752 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9753 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9754 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9755 } 9756 } else { 9757 isLaneOp = true; 9758 switch (N->getOpcode()) { 9759 default: llvm_unreachable("unexpected opcode for Neon base update"); 9760 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9761 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9762 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9763 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9764 NumVecs = 1; isLaneOp = false; break; 9765 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9766 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9767 } 9768 } 9769 9770 // Find the size of memory referenced by the load/store. 9771 EVT VecTy; 9772 if (isLoadOp) { 9773 VecTy = N->getValueType(0); 9774 } else if (isIntrinsic) { 9775 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 9776 } else { 9777 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 9778 VecTy = N->getOperand(1).getValueType(); 9779 } 9780 9781 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9782 if (isLaneOp) 9783 NumBytes /= VecTy.getVectorNumElements(); 9784 9785 // If the increment is a constant, it must match the memory ref size. 9786 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9787 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9788 uint64_t IncVal = CInc->getZExtValue(); 9789 if (IncVal != NumBytes) 9790 continue; 9791 } else if (NumBytes >= 3 * 16) { 9792 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 9793 // separate instructions that make it harder to use a non-constant update. 9794 continue; 9795 } 9796 9797 // OK, we found an ADD we can fold into the base update. 9798 // Now, create a _UPD node, taking care of not breaking alignment. 9799 9800 EVT AlignedVecTy = VecTy; 9801 unsigned Alignment = MemN->getAlignment(); 9802 9803 // If this is a less-than-standard-aligned load/store, change the type to 9804 // match the standard alignment. 9805 // The alignment is overlooked when selecting _UPD variants; and it's 9806 // easier to introduce bitcasts here than fix that. 9807 // There are 3 ways to get to this base-update combine: 9808 // - intrinsics: they are assumed to be properly aligned (to the standard 9809 // alignment of the memory type), so we don't need to do anything. 9810 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 9811 // intrinsics, so, likewise, there's nothing to do. 9812 // - generic load/store instructions: the alignment is specified as an 9813 // explicit operand, rather than implicitly as the standard alignment 9814 // of the memory type (like the intrisics). We need to change the 9815 // memory type to match the explicit alignment. That way, we don't 9816 // generate non-standard-aligned ARMISD::VLDx nodes. 9817 if (isa<LSBaseSDNode>(N)) { 9818 if (Alignment == 0) 9819 Alignment = 1; 9820 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 9821 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 9822 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 9823 assert(!isLaneOp && "Unexpected generic load/store lane."); 9824 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 9825 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 9826 } 9827 // Don't set an explicit alignment on regular load/stores that we want 9828 // to transform to VLD/VST 1_UPD nodes. 9829 // This matches the behavior of regular load/stores, which only get an 9830 // explicit alignment if the MMO alignment is larger than the standard 9831 // alignment of the memory type. 9832 // Intrinsics, however, always get an explicit alignment, set to the 9833 // alignment of the MMO. 9834 Alignment = 1; 9835 } 9836 9837 // Create the new updating load/store node. 9838 // First, create an SDVTList for the new updating node's results. 9839 EVT Tys[6]; 9840 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 9841 unsigned n; 9842 for (n = 0; n < NumResultVecs; ++n) 9843 Tys[n] = AlignedVecTy; 9844 Tys[n++] = MVT::i32; 9845 Tys[n] = MVT::Other; 9846 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 9847 9848 // Then, gather the new node's operands. 9849 SmallVector<SDValue, 8> Ops; 9850 Ops.push_back(N->getOperand(0)); // incoming chain 9851 Ops.push_back(N->getOperand(AddrOpIdx)); 9852 Ops.push_back(Inc); 9853 9854 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 9855 // Try to match the intrinsic's signature 9856 Ops.push_back(StN->getValue()); 9857 } else { 9858 // Loads (and of course intrinsics) match the intrinsics' signature, 9859 // so just add all but the alignment operand. 9860 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 9861 Ops.push_back(N->getOperand(i)); 9862 } 9863 9864 // For all node types, the alignment operand is always the last one. 9865 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 9866 9867 // If this is a non-standard-aligned STORE, the penultimate operand is the 9868 // stored value. Bitcast it to the aligned type. 9869 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 9870 SDValue &StVal = Ops[Ops.size()-2]; 9871 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 9872 } 9873 9874 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 9875 Ops, AlignedVecTy, 9876 MemN->getMemOperand()); 9877 9878 // Update the uses. 9879 SmallVector<SDValue, 5> NewResults; 9880 for (unsigned i = 0; i < NumResultVecs; ++i) 9881 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9882 9883 // If this is an non-standard-aligned LOAD, the first result is the loaded 9884 // value. Bitcast it to the expected result type. 9885 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 9886 SDValue &LdVal = NewResults[0]; 9887 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 9888 } 9889 9890 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 9891 DCI.CombineTo(N, NewResults); 9892 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9893 9894 break; 9895 } 9896 return SDValue(); 9897 } 9898 9899 static SDValue PerformVLDCombine(SDNode *N, 9900 TargetLowering::DAGCombinerInfo &DCI) { 9901 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9902 return SDValue(); 9903 9904 return CombineBaseUpdate(N, DCI); 9905 } 9906 9907 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 9908 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 9909 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 9910 /// return true. 9911 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9912 SelectionDAG &DAG = DCI.DAG; 9913 EVT VT = N->getValueType(0); 9914 // vldN-dup instructions only support 64-bit vectors for N > 1. 9915 if (!VT.is64BitVector()) 9916 return false; 9917 9918 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 9919 SDNode *VLD = N->getOperand(0).getNode(); 9920 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 9921 return false; 9922 unsigned NumVecs = 0; 9923 unsigned NewOpc = 0; 9924 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 9925 if (IntNo == Intrinsic::arm_neon_vld2lane) { 9926 NumVecs = 2; 9927 NewOpc = ARMISD::VLD2DUP; 9928 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 9929 NumVecs = 3; 9930 NewOpc = ARMISD::VLD3DUP; 9931 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 9932 NumVecs = 4; 9933 NewOpc = ARMISD::VLD4DUP; 9934 } else { 9935 return false; 9936 } 9937 9938 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 9939 // numbers match the load. 9940 unsigned VLDLaneNo = 9941 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 9942 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9943 UI != UE; ++UI) { 9944 // Ignore uses of the chain result. 9945 if (UI.getUse().getResNo() == NumVecs) 9946 continue; 9947 SDNode *User = *UI; 9948 if (User->getOpcode() != ARMISD::VDUPLANE || 9949 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 9950 return false; 9951 } 9952 9953 // Create the vldN-dup node. 9954 EVT Tys[5]; 9955 unsigned n; 9956 for (n = 0; n < NumVecs; ++n) 9957 Tys[n] = VT; 9958 Tys[n] = MVT::Other; 9959 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 9960 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 9961 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 9962 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 9963 Ops, VLDMemInt->getMemoryVT(), 9964 VLDMemInt->getMemOperand()); 9965 9966 // Update the uses. 9967 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9968 UI != UE; ++UI) { 9969 unsigned ResNo = UI.getUse().getResNo(); 9970 // Ignore uses of the chain result. 9971 if (ResNo == NumVecs) 9972 continue; 9973 SDNode *User = *UI; 9974 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 9975 } 9976 9977 // Now the vldN-lane intrinsic is dead except for its chain result. 9978 // Update uses of the chain. 9979 std::vector<SDValue> VLDDupResults; 9980 for (unsigned n = 0; n < NumVecs; ++n) 9981 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 9982 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 9983 DCI.CombineTo(VLD, VLDDupResults); 9984 9985 return true; 9986 } 9987 9988 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 9989 /// ARMISD::VDUPLANE. 9990 static SDValue PerformVDUPLANECombine(SDNode *N, 9991 TargetLowering::DAGCombinerInfo &DCI) { 9992 SDValue Op = N->getOperand(0); 9993 9994 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 9995 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 9996 if (CombineVLDDUP(N, DCI)) 9997 return SDValue(N, 0); 9998 9999 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 10000 // redundant. Ignore bit_converts for now; element sizes are checked below. 10001 while (Op.getOpcode() == ISD::BITCAST) 10002 Op = Op.getOperand(0); 10003 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 10004 return SDValue(); 10005 10006 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 10007 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 10008 // The canonical VMOV for a zero vector uses a 32-bit element size. 10009 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10010 unsigned EltBits; 10011 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 10012 EltSize = 8; 10013 EVT VT = N->getValueType(0); 10014 if (EltSize > VT.getVectorElementType().getSizeInBits()) 10015 return SDValue(); 10016 10017 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 10018 } 10019 10020 static SDValue PerformLOADCombine(SDNode *N, 10021 TargetLowering::DAGCombinerInfo &DCI) { 10022 EVT VT = N->getValueType(0); 10023 10024 // If this is a legal vector load, try to combine it into a VLD1_UPD. 10025 if (ISD::isNormalLoad(N) && VT.isVector() && 10026 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10027 return CombineBaseUpdate(N, DCI); 10028 10029 return SDValue(); 10030 } 10031 10032 /// PerformSTORECombine - Target-specific dag combine xforms for 10033 /// ISD::STORE. 10034 static SDValue PerformSTORECombine(SDNode *N, 10035 TargetLowering::DAGCombinerInfo &DCI) { 10036 StoreSDNode *St = cast<StoreSDNode>(N); 10037 if (St->isVolatile()) 10038 return SDValue(); 10039 10040 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10041 // pack all of the elements in one place. Next, store to memory in fewer 10042 // chunks. 10043 SDValue StVal = St->getValue(); 10044 EVT VT = StVal.getValueType(); 10045 if (St->isTruncatingStore() && VT.isVector()) { 10046 SelectionDAG &DAG = DCI.DAG; 10047 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10048 EVT StVT = St->getMemoryVT(); 10049 unsigned NumElems = VT.getVectorNumElements(); 10050 assert(StVT != VT && "Cannot truncate to the same type"); 10051 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 10052 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 10053 10054 // From, To sizes and ElemCount must be pow of two 10055 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10056 10057 // We are going to use the original vector elt for storing. 10058 // Accumulated smaller vector elements must be a multiple of the store size. 10059 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10060 10061 unsigned SizeRatio = FromEltSz / ToEltSz; 10062 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10063 10064 // Create a type on which we perform the shuffle. 10065 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10066 NumElems*SizeRatio); 10067 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10068 10069 SDLoc DL(St); 10070 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10071 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10072 for (unsigned i = 0; i < NumElems; ++i) 10073 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10074 ? (i + 1) * SizeRatio - 1 10075 : i * SizeRatio; 10076 10077 // Can't shuffle using an illegal type. 10078 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10079 10080 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10081 DAG.getUNDEF(WideVec.getValueType()), 10082 ShuffleVec.data()); 10083 // At this point all of the data is stored at the bottom of the 10084 // register. We now need to save it to mem. 10085 10086 // Find the largest store unit 10087 MVT StoreType = MVT::i8; 10088 for (MVT Tp : MVT::integer_valuetypes()) { 10089 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10090 StoreType = Tp; 10091 } 10092 // Didn't find a legal store type. 10093 if (!TLI.isTypeLegal(StoreType)) 10094 return SDValue(); 10095 10096 // Bitcast the original vector into a vector of store-size units 10097 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10098 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10099 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10100 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10101 SmallVector<SDValue, 8> Chains; 10102 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10103 TLI.getPointerTy(DAG.getDataLayout())); 10104 SDValue BasePtr = St->getBasePtr(); 10105 10106 // Perform one or more big stores into memory. 10107 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10108 for (unsigned I = 0; I < E; I++) { 10109 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10110 StoreType, ShuffWide, 10111 DAG.getIntPtrConstant(I, DL)); 10112 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10113 St->getPointerInfo(), St->isVolatile(), 10114 St->isNonTemporal(), St->getAlignment()); 10115 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10116 Increment); 10117 Chains.push_back(Ch); 10118 } 10119 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10120 } 10121 10122 if (!ISD::isNormalStore(St)) 10123 return SDValue(); 10124 10125 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10126 // ARM stores of arguments in the same cache line. 10127 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10128 StVal.getNode()->hasOneUse()) { 10129 SelectionDAG &DAG = DCI.DAG; 10130 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10131 SDLoc DL(St); 10132 SDValue BasePtr = St->getBasePtr(); 10133 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 10134 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 10135 BasePtr, St->getPointerInfo(), St->isVolatile(), 10136 St->isNonTemporal(), St->getAlignment()); 10137 10138 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10139 DAG.getConstant(4, DL, MVT::i32)); 10140 return DAG.getStore(NewST1.getValue(0), DL, 10141 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10142 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 10143 St->isNonTemporal(), 10144 std::min(4U, St->getAlignment() / 2)); 10145 } 10146 10147 if (StVal.getValueType() == MVT::i64 && 10148 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10149 10150 // Bitcast an i64 store extracted from a vector to f64. 10151 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10152 SelectionDAG &DAG = DCI.DAG; 10153 SDLoc dl(StVal); 10154 SDValue IntVec = StVal.getOperand(0); 10155 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10156 IntVec.getValueType().getVectorNumElements()); 10157 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10158 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10159 Vec, StVal.getOperand(1)); 10160 dl = SDLoc(N); 10161 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10162 // Make the DAGCombiner fold the bitcasts. 10163 DCI.AddToWorklist(Vec.getNode()); 10164 DCI.AddToWorklist(ExtElt.getNode()); 10165 DCI.AddToWorklist(V.getNode()); 10166 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10167 St->getPointerInfo(), St->isVolatile(), 10168 St->isNonTemporal(), St->getAlignment(), 10169 St->getAAInfo()); 10170 } 10171 10172 // If this is a legal vector store, try to combine it into a VST1_UPD. 10173 if (ISD::isNormalStore(N) && VT.isVector() && 10174 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10175 return CombineBaseUpdate(N, DCI); 10176 10177 return SDValue(); 10178 } 10179 10180 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10181 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10182 /// when the VMUL has a constant operand that is a power of 2. 10183 /// 10184 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10185 /// vmul.f32 d16, d17, d16 10186 /// vcvt.s32.f32 d16, d16 10187 /// becomes: 10188 /// vcvt.s32.f32 d16, d16, #3 10189 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10190 const ARMSubtarget *Subtarget) { 10191 if (!Subtarget->hasNEON()) 10192 return SDValue(); 10193 10194 SDValue Op = N->getOperand(0); 10195 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10196 Op.getOpcode() != ISD::FMUL) 10197 return SDValue(); 10198 10199 SDValue ConstVec = Op->getOperand(1); 10200 if (!isa<BuildVectorSDNode>(ConstVec)) 10201 return SDValue(); 10202 10203 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10204 uint32_t FloatBits = FloatTy.getSizeInBits(); 10205 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10206 uint32_t IntBits = IntTy.getSizeInBits(); 10207 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10208 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10209 // These instructions only exist converting from f32 to i32. We can handle 10210 // smaller integers by generating an extra truncate, but larger ones would 10211 // be lossy. We also can't handle more then 4 lanes, since these intructions 10212 // only support v2i32/v4i32 types. 10213 return SDValue(); 10214 } 10215 10216 BitVector UndefElements; 10217 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10218 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10219 if (C == -1 || C == 0 || C > 32) 10220 return SDValue(); 10221 10222 SDLoc dl(N); 10223 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10224 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10225 Intrinsic::arm_neon_vcvtfp2fxu; 10226 SDValue FixConv = DAG.getNode( 10227 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10228 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10229 DAG.getConstant(C, dl, MVT::i32)); 10230 10231 if (IntBits < FloatBits) 10232 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10233 10234 return FixConv; 10235 } 10236 10237 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10238 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10239 /// when the VDIV has a constant operand that is a power of 2. 10240 /// 10241 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10242 /// vcvt.f32.s32 d16, d16 10243 /// vdiv.f32 d16, d17, d16 10244 /// becomes: 10245 /// vcvt.f32.s32 d16, d16, #3 10246 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10247 const ARMSubtarget *Subtarget) { 10248 if (!Subtarget->hasNEON()) 10249 return SDValue(); 10250 10251 SDValue Op = N->getOperand(0); 10252 unsigned OpOpcode = Op.getNode()->getOpcode(); 10253 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 10254 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10255 return SDValue(); 10256 10257 SDValue ConstVec = N->getOperand(1); 10258 if (!isa<BuildVectorSDNode>(ConstVec)) 10259 return SDValue(); 10260 10261 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10262 uint32_t FloatBits = FloatTy.getSizeInBits(); 10263 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10264 uint32_t IntBits = IntTy.getSizeInBits(); 10265 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10266 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10267 // These instructions only exist converting from i32 to f32. We can handle 10268 // smaller integers by generating an extra extend, but larger ones would 10269 // be lossy. We also can't handle more then 4 lanes, since these intructions 10270 // only support v2i32/v4i32 types. 10271 return SDValue(); 10272 } 10273 10274 BitVector UndefElements; 10275 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10276 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10277 if (C == -1 || C == 0 || C > 32) 10278 return SDValue(); 10279 10280 SDLoc dl(N); 10281 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10282 SDValue ConvInput = Op.getOperand(0); 10283 if (IntBits < FloatBits) 10284 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10285 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10286 ConvInput); 10287 10288 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10289 Intrinsic::arm_neon_vcvtfxu2fp; 10290 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10291 Op.getValueType(), 10292 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10293 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10294 } 10295 10296 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10297 /// operand of a vector shift operation, where all the elements of the 10298 /// build_vector must have the same constant integer value. 10299 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10300 // Ignore bit_converts. 10301 while (Op.getOpcode() == ISD::BITCAST) 10302 Op = Op.getOperand(0); 10303 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10304 APInt SplatBits, SplatUndef; 10305 unsigned SplatBitSize; 10306 bool HasAnyUndefs; 10307 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10308 HasAnyUndefs, ElementBits) || 10309 SplatBitSize > ElementBits) 10310 return false; 10311 Cnt = SplatBits.getSExtValue(); 10312 return true; 10313 } 10314 10315 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10316 /// operand of a vector shift left operation. That value must be in the range: 10317 /// 0 <= Value < ElementBits for a left shift; or 10318 /// 0 <= Value <= ElementBits for a long left shift. 10319 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10320 assert(VT.isVector() && "vector shift count is not a vector type"); 10321 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10322 if (! getVShiftImm(Op, ElementBits, Cnt)) 10323 return false; 10324 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10325 } 10326 10327 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10328 /// operand of a vector shift right operation. For a shift opcode, the value 10329 /// is positive, but for an intrinsic the value count must be negative. The 10330 /// absolute value must be in the range: 10331 /// 1 <= |Value| <= ElementBits for a right shift; or 10332 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10333 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10334 int64_t &Cnt) { 10335 assert(VT.isVector() && "vector shift count is not a vector type"); 10336 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10337 if (! getVShiftImm(Op, ElementBits, Cnt)) 10338 return false; 10339 if (!isIntrinsic) 10340 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10341 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10342 Cnt = -Cnt; 10343 return true; 10344 } 10345 return false; 10346 } 10347 10348 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10349 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10350 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10351 switch (IntNo) { 10352 default: 10353 // Don't do anything for most intrinsics. 10354 break; 10355 10356 // Vector shifts: check for immediate versions and lower them. 10357 // Note: This is done during DAG combining instead of DAG legalizing because 10358 // the build_vectors for 64-bit vector element shift counts are generally 10359 // not legal, and it is hard to see their values after they get legalized to 10360 // loads from a constant pool. 10361 case Intrinsic::arm_neon_vshifts: 10362 case Intrinsic::arm_neon_vshiftu: 10363 case Intrinsic::arm_neon_vrshifts: 10364 case Intrinsic::arm_neon_vrshiftu: 10365 case Intrinsic::arm_neon_vrshiftn: 10366 case Intrinsic::arm_neon_vqshifts: 10367 case Intrinsic::arm_neon_vqshiftu: 10368 case Intrinsic::arm_neon_vqshiftsu: 10369 case Intrinsic::arm_neon_vqshiftns: 10370 case Intrinsic::arm_neon_vqshiftnu: 10371 case Intrinsic::arm_neon_vqshiftnsu: 10372 case Intrinsic::arm_neon_vqrshiftns: 10373 case Intrinsic::arm_neon_vqrshiftnu: 10374 case Intrinsic::arm_neon_vqrshiftnsu: { 10375 EVT VT = N->getOperand(1).getValueType(); 10376 int64_t Cnt; 10377 unsigned VShiftOpc = 0; 10378 10379 switch (IntNo) { 10380 case Intrinsic::arm_neon_vshifts: 10381 case Intrinsic::arm_neon_vshiftu: 10382 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10383 VShiftOpc = ARMISD::VSHL; 10384 break; 10385 } 10386 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10387 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10388 ARMISD::VSHRs : ARMISD::VSHRu); 10389 break; 10390 } 10391 return SDValue(); 10392 10393 case Intrinsic::arm_neon_vrshifts: 10394 case Intrinsic::arm_neon_vrshiftu: 10395 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10396 break; 10397 return SDValue(); 10398 10399 case Intrinsic::arm_neon_vqshifts: 10400 case Intrinsic::arm_neon_vqshiftu: 10401 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10402 break; 10403 return SDValue(); 10404 10405 case Intrinsic::arm_neon_vqshiftsu: 10406 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10407 break; 10408 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10409 10410 case Intrinsic::arm_neon_vrshiftn: 10411 case Intrinsic::arm_neon_vqshiftns: 10412 case Intrinsic::arm_neon_vqshiftnu: 10413 case Intrinsic::arm_neon_vqshiftnsu: 10414 case Intrinsic::arm_neon_vqrshiftns: 10415 case Intrinsic::arm_neon_vqrshiftnu: 10416 case Intrinsic::arm_neon_vqrshiftnsu: 10417 // Narrowing shifts require an immediate right shift. 10418 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10419 break; 10420 llvm_unreachable("invalid shift count for narrowing vector shift " 10421 "intrinsic"); 10422 10423 default: 10424 llvm_unreachable("unhandled vector shift"); 10425 } 10426 10427 switch (IntNo) { 10428 case Intrinsic::arm_neon_vshifts: 10429 case Intrinsic::arm_neon_vshiftu: 10430 // Opcode already set above. 10431 break; 10432 case Intrinsic::arm_neon_vrshifts: 10433 VShiftOpc = ARMISD::VRSHRs; break; 10434 case Intrinsic::arm_neon_vrshiftu: 10435 VShiftOpc = ARMISD::VRSHRu; break; 10436 case Intrinsic::arm_neon_vrshiftn: 10437 VShiftOpc = ARMISD::VRSHRN; break; 10438 case Intrinsic::arm_neon_vqshifts: 10439 VShiftOpc = ARMISD::VQSHLs; break; 10440 case Intrinsic::arm_neon_vqshiftu: 10441 VShiftOpc = ARMISD::VQSHLu; break; 10442 case Intrinsic::arm_neon_vqshiftsu: 10443 VShiftOpc = ARMISD::VQSHLsu; break; 10444 case Intrinsic::arm_neon_vqshiftns: 10445 VShiftOpc = ARMISD::VQSHRNs; break; 10446 case Intrinsic::arm_neon_vqshiftnu: 10447 VShiftOpc = ARMISD::VQSHRNu; break; 10448 case Intrinsic::arm_neon_vqshiftnsu: 10449 VShiftOpc = ARMISD::VQSHRNsu; break; 10450 case Intrinsic::arm_neon_vqrshiftns: 10451 VShiftOpc = ARMISD::VQRSHRNs; break; 10452 case Intrinsic::arm_neon_vqrshiftnu: 10453 VShiftOpc = ARMISD::VQRSHRNu; break; 10454 case Intrinsic::arm_neon_vqrshiftnsu: 10455 VShiftOpc = ARMISD::VQRSHRNsu; break; 10456 } 10457 10458 SDLoc dl(N); 10459 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10460 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10461 } 10462 10463 case Intrinsic::arm_neon_vshiftins: { 10464 EVT VT = N->getOperand(1).getValueType(); 10465 int64_t Cnt; 10466 unsigned VShiftOpc = 0; 10467 10468 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10469 VShiftOpc = ARMISD::VSLI; 10470 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10471 VShiftOpc = ARMISD::VSRI; 10472 else { 10473 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10474 } 10475 10476 SDLoc dl(N); 10477 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10478 N->getOperand(1), N->getOperand(2), 10479 DAG.getConstant(Cnt, dl, MVT::i32)); 10480 } 10481 10482 case Intrinsic::arm_neon_vqrshifts: 10483 case Intrinsic::arm_neon_vqrshiftu: 10484 // No immediate versions of these to check for. 10485 break; 10486 } 10487 10488 return SDValue(); 10489 } 10490 10491 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10492 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10493 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10494 /// vector element shift counts are generally not legal, and it is hard to see 10495 /// their values after they get legalized to loads from a constant pool. 10496 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10497 const ARMSubtarget *ST) { 10498 EVT VT = N->getValueType(0); 10499 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10500 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10501 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10502 SDValue N1 = N->getOperand(1); 10503 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10504 SDValue N0 = N->getOperand(0); 10505 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10506 DAG.MaskedValueIsZero(N0.getOperand(0), 10507 APInt::getHighBitsSet(32, 16))) 10508 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10509 } 10510 } 10511 10512 // Nothing to be done for scalar shifts. 10513 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10514 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10515 return SDValue(); 10516 10517 assert(ST->hasNEON() && "unexpected vector shift"); 10518 int64_t Cnt; 10519 10520 switch (N->getOpcode()) { 10521 default: llvm_unreachable("unexpected shift opcode"); 10522 10523 case ISD::SHL: 10524 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10525 SDLoc dl(N); 10526 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10527 DAG.getConstant(Cnt, dl, MVT::i32)); 10528 } 10529 break; 10530 10531 case ISD::SRA: 10532 case ISD::SRL: 10533 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10534 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10535 ARMISD::VSHRs : ARMISD::VSHRu); 10536 SDLoc dl(N); 10537 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10538 DAG.getConstant(Cnt, dl, MVT::i32)); 10539 } 10540 } 10541 return SDValue(); 10542 } 10543 10544 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10545 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10546 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10547 const ARMSubtarget *ST) { 10548 SDValue N0 = N->getOperand(0); 10549 10550 // Check for sign- and zero-extensions of vector extract operations of 8- 10551 // and 16-bit vector elements. NEON supports these directly. They are 10552 // handled during DAG combining because type legalization will promote them 10553 // to 32-bit types and it is messy to recognize the operations after that. 10554 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10555 SDValue Vec = N0.getOperand(0); 10556 SDValue Lane = N0.getOperand(1); 10557 EVT VT = N->getValueType(0); 10558 EVT EltVT = N0.getValueType(); 10559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10560 10561 if (VT == MVT::i32 && 10562 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10563 TLI.isTypeLegal(Vec.getValueType()) && 10564 isa<ConstantSDNode>(Lane)) { 10565 10566 unsigned Opc = 0; 10567 switch (N->getOpcode()) { 10568 default: llvm_unreachable("unexpected opcode"); 10569 case ISD::SIGN_EXTEND: 10570 Opc = ARMISD::VGETLANEs; 10571 break; 10572 case ISD::ZERO_EXTEND: 10573 case ISD::ANY_EXTEND: 10574 Opc = ARMISD::VGETLANEu; 10575 break; 10576 } 10577 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10578 } 10579 } 10580 10581 return SDValue(); 10582 } 10583 10584 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10585 APInt &KnownOne) { 10586 if (Op.getOpcode() == ARMISD::BFI) { 10587 // Conservatively, we can recurse down the first operand 10588 // and just mask out all affected bits. 10589 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10590 10591 // The operand to BFI is already a mask suitable for removing the bits it 10592 // sets. 10593 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10594 APInt Mask = CI->getAPIntValue(); 10595 KnownZero &= Mask; 10596 KnownOne &= Mask; 10597 return; 10598 } 10599 if (Op.getOpcode() == ARMISD::CMOV) { 10600 APInt KZ2(KnownZero.getBitWidth(), 0); 10601 APInt KO2(KnownOne.getBitWidth(), 0); 10602 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 10603 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 10604 10605 KnownZero &= KZ2; 10606 KnownOne &= KO2; 10607 return; 10608 } 10609 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 10610 } 10611 10612 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 10613 // If we have a CMOV, OR and AND combination such as: 10614 // if (x & CN) 10615 // y |= CM; 10616 // 10617 // And: 10618 // * CN is a single bit; 10619 // * All bits covered by CM are known zero in y 10620 // 10621 // Then we can convert this into a sequence of BFI instructions. This will 10622 // always be a win if CM is a single bit, will always be no worse than the 10623 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 10624 // three bits (due to the extra IT instruction). 10625 10626 SDValue Op0 = CMOV->getOperand(0); 10627 SDValue Op1 = CMOV->getOperand(1); 10628 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 10629 auto CC = CCNode->getAPIntValue().getLimitedValue(); 10630 SDValue CmpZ = CMOV->getOperand(4); 10631 10632 // The compare must be against zero. 10633 if (!isNullConstant(CmpZ->getOperand(1))) 10634 return SDValue(); 10635 10636 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 10637 SDValue And = CmpZ->getOperand(0); 10638 if (And->getOpcode() != ISD::AND) 10639 return SDValue(); 10640 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 10641 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 10642 return SDValue(); 10643 SDValue X = And->getOperand(0); 10644 10645 if (CC == ARMCC::EQ) { 10646 // We're performing an "equal to zero" compare. Swap the operands so we 10647 // canonicalize on a "not equal to zero" compare. 10648 std::swap(Op0, Op1); 10649 } else { 10650 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 10651 } 10652 10653 if (Op1->getOpcode() != ISD::OR) 10654 return SDValue(); 10655 10656 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 10657 if (!OrC) 10658 return SDValue(); 10659 SDValue Y = Op1->getOperand(0); 10660 10661 if (Op0 != Y) 10662 return SDValue(); 10663 10664 // Now, is it profitable to continue? 10665 APInt OrCI = OrC->getAPIntValue(); 10666 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 10667 if (OrCI.countPopulation() > Heuristic) 10668 return SDValue(); 10669 10670 // Lastly, can we determine that the bits defined by OrCI 10671 // are zero in Y? 10672 APInt KnownZero, KnownOne; 10673 computeKnownBits(DAG, Y, KnownZero, KnownOne); 10674 if ((OrCI & KnownZero) != OrCI) 10675 return SDValue(); 10676 10677 // OK, we can do the combine. 10678 SDValue V = Y; 10679 SDLoc dl(X); 10680 EVT VT = X.getValueType(); 10681 unsigned BitInX = AndC->getAPIntValue().logBase2(); 10682 10683 if (BitInX != 0) { 10684 // We must shift X first. 10685 X = DAG.getNode(ISD::SRL, dl, VT, X, 10686 DAG.getConstant(BitInX, dl, VT)); 10687 } 10688 10689 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 10690 BitInY < NumActiveBits; ++BitInY) { 10691 if (OrCI[BitInY] == 0) 10692 continue; 10693 APInt Mask(VT.getSizeInBits(), 0); 10694 Mask.setBit(BitInY); 10695 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 10696 // Confusingly, the operand is an *inverted* mask. 10697 DAG.getConstant(~Mask, dl, VT)); 10698 } 10699 10700 return V; 10701 } 10702 10703 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 10704 SDValue 10705 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 10706 SDValue Cmp = N->getOperand(4); 10707 if (Cmp.getOpcode() != ARMISD::CMPZ) 10708 // Only looking at NE cases. 10709 return SDValue(); 10710 10711 EVT VT = N->getValueType(0); 10712 SDLoc dl(N); 10713 SDValue LHS = Cmp.getOperand(0); 10714 SDValue RHS = Cmp.getOperand(1); 10715 SDValue Chain = N->getOperand(0); 10716 SDValue BB = N->getOperand(1); 10717 SDValue ARMcc = N->getOperand(2); 10718 ARMCC::CondCodes CC = 10719 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10720 10721 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 10722 // -> (brcond Chain BB CC CPSR Cmp) 10723 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 10724 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 10725 LHS->getOperand(0)->hasOneUse()) { 10726 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 10727 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 10728 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10729 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10730 if ((LHS00C && LHS00C->getZExtValue() == 0) && 10731 (LHS01C && LHS01C->getZExtValue() == 1) && 10732 (LHS1C && LHS1C->getZExtValue() == 1) && 10733 (RHSC && RHSC->getZExtValue() == 0)) { 10734 return DAG.getNode( 10735 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 10736 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 10737 } 10738 } 10739 10740 return SDValue(); 10741 } 10742 10743 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10744 SDValue 10745 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10746 SDValue Cmp = N->getOperand(4); 10747 if (Cmp.getOpcode() != ARMISD::CMPZ) 10748 // Only looking at EQ and NE cases. 10749 return SDValue(); 10750 10751 EVT VT = N->getValueType(0); 10752 SDLoc dl(N); 10753 SDValue LHS = Cmp.getOperand(0); 10754 SDValue RHS = Cmp.getOperand(1); 10755 SDValue FalseVal = N->getOperand(0); 10756 SDValue TrueVal = N->getOperand(1); 10757 SDValue ARMcc = N->getOperand(2); 10758 ARMCC::CondCodes CC = 10759 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10760 10761 // BFI is only available on V6T2+. 10762 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 10763 SDValue R = PerformCMOVToBFICombine(N, DAG); 10764 if (R) 10765 return R; 10766 } 10767 10768 // Simplify 10769 // mov r1, r0 10770 // cmp r1, x 10771 // mov r0, y 10772 // moveq r0, x 10773 // to 10774 // cmp r0, x 10775 // movne r0, y 10776 // 10777 // mov r1, r0 10778 // cmp r1, x 10779 // mov r0, x 10780 // movne r0, y 10781 // to 10782 // cmp r0, x 10783 // movne r0, y 10784 /// FIXME: Turn this into a target neutral optimization? 10785 SDValue Res; 10786 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 10787 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 10788 N->getOperand(3), Cmp); 10789 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 10790 SDValue ARMcc; 10791 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 10792 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 10793 N->getOperand(3), NewCmp); 10794 } 10795 10796 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 10797 // -> (cmov F T CC CPSR Cmp) 10798 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 10799 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 10800 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10801 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10802 if ((LHS0C && LHS0C->getZExtValue() == 0) && 10803 (LHS1C && LHS1C->getZExtValue() == 1) && 10804 (RHSC && RHSC->getZExtValue() == 0)) { 10805 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 10806 LHS->getOperand(2), LHS->getOperand(3), 10807 LHS->getOperand(4)); 10808 } 10809 } 10810 10811 if (Res.getNode()) { 10812 APInt KnownZero, KnownOne; 10813 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 10814 // Capture demanded bits information that would be otherwise lost. 10815 if (KnownZero == 0xfffffffe) 10816 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10817 DAG.getValueType(MVT::i1)); 10818 else if (KnownZero == 0xffffff00) 10819 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10820 DAG.getValueType(MVT::i8)); 10821 else if (KnownZero == 0xffff0000) 10822 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10823 DAG.getValueType(MVT::i16)); 10824 } 10825 10826 return Res; 10827 } 10828 10829 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 10830 DAGCombinerInfo &DCI) const { 10831 switch (N->getOpcode()) { 10832 default: break; 10833 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 10834 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 10835 case ISD::SUB: return PerformSUBCombine(N, DCI); 10836 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 10837 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 10838 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 10839 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 10840 case ARMISD::BFI: return PerformBFICombine(N, DCI); 10841 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 10842 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 10843 case ISD::STORE: return PerformSTORECombine(N, DCI); 10844 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 10845 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 10846 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 10847 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 10848 case ISD::FP_TO_SINT: 10849 case ISD::FP_TO_UINT: 10850 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 10851 case ISD::FDIV: 10852 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 10853 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 10854 case ISD::SHL: 10855 case ISD::SRA: 10856 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 10857 case ISD::SIGN_EXTEND: 10858 case ISD::ZERO_EXTEND: 10859 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 10860 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 10861 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 10862 case ISD::LOAD: return PerformLOADCombine(N, DCI); 10863 case ARMISD::VLD2DUP: 10864 case ARMISD::VLD3DUP: 10865 case ARMISD::VLD4DUP: 10866 return PerformVLDCombine(N, DCI); 10867 case ARMISD::BUILD_VECTOR: 10868 return PerformARMBUILD_VECTORCombine(N, DCI); 10869 case ISD::INTRINSIC_VOID: 10870 case ISD::INTRINSIC_W_CHAIN: 10871 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10872 case Intrinsic::arm_neon_vld1: 10873 case Intrinsic::arm_neon_vld2: 10874 case Intrinsic::arm_neon_vld3: 10875 case Intrinsic::arm_neon_vld4: 10876 case Intrinsic::arm_neon_vld2lane: 10877 case Intrinsic::arm_neon_vld3lane: 10878 case Intrinsic::arm_neon_vld4lane: 10879 case Intrinsic::arm_neon_vst1: 10880 case Intrinsic::arm_neon_vst2: 10881 case Intrinsic::arm_neon_vst3: 10882 case Intrinsic::arm_neon_vst4: 10883 case Intrinsic::arm_neon_vst2lane: 10884 case Intrinsic::arm_neon_vst3lane: 10885 case Intrinsic::arm_neon_vst4lane: 10886 return PerformVLDCombine(N, DCI); 10887 default: break; 10888 } 10889 break; 10890 } 10891 return SDValue(); 10892 } 10893 10894 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 10895 EVT VT) const { 10896 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 10897 } 10898 10899 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 10900 unsigned, 10901 unsigned, 10902 bool *Fast) const { 10903 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 10904 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 10905 10906 switch (VT.getSimpleVT().SimpleTy) { 10907 default: 10908 return false; 10909 case MVT::i8: 10910 case MVT::i16: 10911 case MVT::i32: { 10912 // Unaligned access can use (for example) LRDB, LRDH, LDR 10913 if (AllowsUnaligned) { 10914 if (Fast) 10915 *Fast = Subtarget->hasV7Ops(); 10916 return true; 10917 } 10918 return false; 10919 } 10920 case MVT::f64: 10921 case MVT::v2f64: { 10922 // For any little-endian targets with neon, we can support unaligned ld/st 10923 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 10924 // A big-endian target may also explicitly support unaligned accesses 10925 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 10926 if (Fast) 10927 *Fast = true; 10928 return true; 10929 } 10930 return false; 10931 } 10932 } 10933 } 10934 10935 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 10936 unsigned AlignCheck) { 10937 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 10938 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 10939 } 10940 10941 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 10942 unsigned DstAlign, unsigned SrcAlign, 10943 bool IsMemset, bool ZeroMemset, 10944 bool MemcpyStrSrc, 10945 MachineFunction &MF) const { 10946 const Function *F = MF.getFunction(); 10947 10948 // See if we can use NEON instructions for this... 10949 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 10950 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 10951 bool Fast; 10952 if (Size >= 16 && 10953 (memOpAlign(SrcAlign, DstAlign, 16) || 10954 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 10955 return MVT::v2f64; 10956 } else if (Size >= 8 && 10957 (memOpAlign(SrcAlign, DstAlign, 8) || 10958 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 10959 Fast))) { 10960 return MVT::f64; 10961 } 10962 } 10963 10964 // Lowering to i32/i16 if the size permits. 10965 if (Size >= 4) 10966 return MVT::i32; 10967 else if (Size >= 2) 10968 return MVT::i16; 10969 10970 // Let the target-independent logic figure it out. 10971 return MVT::Other; 10972 } 10973 10974 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10975 if (Val.getOpcode() != ISD::LOAD) 10976 return false; 10977 10978 EVT VT1 = Val.getValueType(); 10979 if (!VT1.isSimple() || !VT1.isInteger() || 10980 !VT2.isSimple() || !VT2.isInteger()) 10981 return false; 10982 10983 switch (VT1.getSimpleVT().SimpleTy) { 10984 default: break; 10985 case MVT::i1: 10986 case MVT::i8: 10987 case MVT::i16: 10988 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 10989 return true; 10990 } 10991 10992 return false; 10993 } 10994 10995 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 10996 EVT VT = ExtVal.getValueType(); 10997 10998 if (!isTypeLegal(VT)) 10999 return false; 11000 11001 // Don't create a loadext if we can fold the extension into a wide/long 11002 // instruction. 11003 // If there's more than one user instruction, the loadext is desirable no 11004 // matter what. There can be two uses by the same instruction. 11005 if (ExtVal->use_empty() || 11006 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 11007 return true; 11008 11009 SDNode *U = *ExtVal->use_begin(); 11010 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 11011 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 11012 return false; 11013 11014 return true; 11015 } 11016 11017 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 11018 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11019 return false; 11020 11021 if (!isTypeLegal(EVT::getEVT(Ty1))) 11022 return false; 11023 11024 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 11025 11026 // Assuming the caller doesn't have a zeroext or signext return parameter, 11027 // truncation all the way down to i1 is valid. 11028 return true; 11029 } 11030 11031 11032 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11033 if (V < 0) 11034 return false; 11035 11036 unsigned Scale = 1; 11037 switch (VT.getSimpleVT().SimpleTy) { 11038 default: return false; 11039 case MVT::i1: 11040 case MVT::i8: 11041 // Scale == 1; 11042 break; 11043 case MVT::i16: 11044 // Scale == 2; 11045 Scale = 2; 11046 break; 11047 case MVT::i32: 11048 // Scale == 4; 11049 Scale = 4; 11050 break; 11051 } 11052 11053 if ((V & (Scale - 1)) != 0) 11054 return false; 11055 V /= Scale; 11056 return V == (V & ((1LL << 5) - 1)); 11057 } 11058 11059 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11060 const ARMSubtarget *Subtarget) { 11061 bool isNeg = false; 11062 if (V < 0) { 11063 isNeg = true; 11064 V = - V; 11065 } 11066 11067 switch (VT.getSimpleVT().SimpleTy) { 11068 default: return false; 11069 case MVT::i1: 11070 case MVT::i8: 11071 case MVT::i16: 11072 case MVT::i32: 11073 // + imm12 or - imm8 11074 if (isNeg) 11075 return V == (V & ((1LL << 8) - 1)); 11076 return V == (V & ((1LL << 12) - 1)); 11077 case MVT::f32: 11078 case MVT::f64: 11079 // Same as ARM mode. FIXME: NEON? 11080 if (!Subtarget->hasVFP2()) 11081 return false; 11082 if ((V & 3) != 0) 11083 return false; 11084 V >>= 2; 11085 return V == (V & ((1LL << 8) - 1)); 11086 } 11087 } 11088 11089 /// isLegalAddressImmediate - Return true if the integer value can be used 11090 /// as the offset of the target addressing mode for load / store of the 11091 /// given type. 11092 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11093 const ARMSubtarget *Subtarget) { 11094 if (V == 0) 11095 return true; 11096 11097 if (!VT.isSimple()) 11098 return false; 11099 11100 if (Subtarget->isThumb1Only()) 11101 return isLegalT1AddressImmediate(V, VT); 11102 else if (Subtarget->isThumb2()) 11103 return isLegalT2AddressImmediate(V, VT, Subtarget); 11104 11105 // ARM mode. 11106 if (V < 0) 11107 V = - V; 11108 switch (VT.getSimpleVT().SimpleTy) { 11109 default: return false; 11110 case MVT::i1: 11111 case MVT::i8: 11112 case MVT::i32: 11113 // +- imm12 11114 return V == (V & ((1LL << 12) - 1)); 11115 case MVT::i16: 11116 // +- imm8 11117 return V == (V & ((1LL << 8) - 1)); 11118 case MVT::f32: 11119 case MVT::f64: 11120 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11121 return false; 11122 if ((V & 3) != 0) 11123 return false; 11124 V >>= 2; 11125 return V == (V & ((1LL << 8) - 1)); 11126 } 11127 } 11128 11129 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11130 EVT VT) const { 11131 int Scale = AM.Scale; 11132 if (Scale < 0) 11133 return false; 11134 11135 switch (VT.getSimpleVT().SimpleTy) { 11136 default: return false; 11137 case MVT::i1: 11138 case MVT::i8: 11139 case MVT::i16: 11140 case MVT::i32: 11141 if (Scale == 1) 11142 return true; 11143 // r + r << imm 11144 Scale = Scale & ~1; 11145 return Scale == 2 || Scale == 4 || Scale == 8; 11146 case MVT::i64: 11147 // r + r 11148 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11149 return true; 11150 return false; 11151 case MVT::isVoid: 11152 // Note, we allow "void" uses (basically, uses that aren't loads or 11153 // stores), because arm allows folding a scale into many arithmetic 11154 // operations. This should be made more precise and revisited later. 11155 11156 // Allow r << imm, but the imm has to be a multiple of two. 11157 if (Scale & 1) return false; 11158 return isPowerOf2_32(Scale); 11159 } 11160 } 11161 11162 /// isLegalAddressingMode - Return true if the addressing mode represented 11163 /// by AM is legal for this target, for a load/store of the specified type. 11164 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11165 const AddrMode &AM, Type *Ty, 11166 unsigned AS) const { 11167 EVT VT = getValueType(DL, Ty, true); 11168 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 11169 return false; 11170 11171 // Can never fold addr of global into load/store. 11172 if (AM.BaseGV) 11173 return false; 11174 11175 switch (AM.Scale) { 11176 case 0: // no scale reg, must be "r+i" or "r", or "i". 11177 break; 11178 case 1: 11179 if (Subtarget->isThumb1Only()) 11180 return false; 11181 // FALL THROUGH. 11182 default: 11183 // ARM doesn't support any R+R*scale+imm addr modes. 11184 if (AM.BaseOffs) 11185 return false; 11186 11187 if (!VT.isSimple()) 11188 return false; 11189 11190 if (Subtarget->isThumb2()) 11191 return isLegalT2ScaledAddressingMode(AM, VT); 11192 11193 int Scale = AM.Scale; 11194 switch (VT.getSimpleVT().SimpleTy) { 11195 default: return false; 11196 case MVT::i1: 11197 case MVT::i8: 11198 case MVT::i32: 11199 if (Scale < 0) Scale = -Scale; 11200 if (Scale == 1) 11201 return true; 11202 // r + r << imm 11203 return isPowerOf2_32(Scale & ~1); 11204 case MVT::i16: 11205 case MVT::i64: 11206 // r + r 11207 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11208 return true; 11209 return false; 11210 11211 case MVT::isVoid: 11212 // Note, we allow "void" uses (basically, uses that aren't loads or 11213 // stores), because arm allows folding a scale into many arithmetic 11214 // operations. This should be made more precise and revisited later. 11215 11216 // Allow r << imm, but the imm has to be a multiple of two. 11217 if (Scale & 1) return false; 11218 return isPowerOf2_32(Scale); 11219 } 11220 } 11221 return true; 11222 } 11223 11224 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11225 /// icmp immediate, that is the target has icmp instructions which can compare 11226 /// a register against the immediate without having to materialize the 11227 /// immediate into a register. 11228 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11229 // Thumb2 and ARM modes can use cmn for negative immediates. 11230 if (!Subtarget->isThumb()) 11231 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11232 if (Subtarget->isThumb2()) 11233 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11234 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11235 return Imm >= 0 && Imm <= 255; 11236 } 11237 11238 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11239 /// *or sub* immediate, that is the target has add or sub instructions which can 11240 /// add a register with the immediate without having to materialize the 11241 /// immediate into a register. 11242 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11243 // Same encoding for add/sub, just flip the sign. 11244 int64_t AbsImm = std::abs(Imm); 11245 if (!Subtarget->isThumb()) 11246 return ARM_AM::getSOImmVal(AbsImm) != -1; 11247 if (Subtarget->isThumb2()) 11248 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11249 // Thumb1 only has 8-bit unsigned immediate. 11250 return AbsImm >= 0 && AbsImm <= 255; 11251 } 11252 11253 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11254 bool isSEXTLoad, SDValue &Base, 11255 SDValue &Offset, bool &isInc, 11256 SelectionDAG &DAG) { 11257 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11258 return false; 11259 11260 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11261 // AddressingMode 3 11262 Base = Ptr->getOperand(0); 11263 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11264 int RHSC = (int)RHS->getZExtValue(); 11265 if (RHSC < 0 && RHSC > -256) { 11266 assert(Ptr->getOpcode() == ISD::ADD); 11267 isInc = false; 11268 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11269 return true; 11270 } 11271 } 11272 isInc = (Ptr->getOpcode() == ISD::ADD); 11273 Offset = Ptr->getOperand(1); 11274 return true; 11275 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11276 // AddressingMode 2 11277 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11278 int RHSC = (int)RHS->getZExtValue(); 11279 if (RHSC < 0 && RHSC > -0x1000) { 11280 assert(Ptr->getOpcode() == ISD::ADD); 11281 isInc = false; 11282 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11283 Base = Ptr->getOperand(0); 11284 return true; 11285 } 11286 } 11287 11288 if (Ptr->getOpcode() == ISD::ADD) { 11289 isInc = true; 11290 ARM_AM::ShiftOpc ShOpcVal= 11291 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11292 if (ShOpcVal != ARM_AM::no_shift) { 11293 Base = Ptr->getOperand(1); 11294 Offset = Ptr->getOperand(0); 11295 } else { 11296 Base = Ptr->getOperand(0); 11297 Offset = Ptr->getOperand(1); 11298 } 11299 return true; 11300 } 11301 11302 isInc = (Ptr->getOpcode() == ISD::ADD); 11303 Base = Ptr->getOperand(0); 11304 Offset = Ptr->getOperand(1); 11305 return true; 11306 } 11307 11308 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11309 return false; 11310 } 11311 11312 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11313 bool isSEXTLoad, SDValue &Base, 11314 SDValue &Offset, bool &isInc, 11315 SelectionDAG &DAG) { 11316 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11317 return false; 11318 11319 Base = Ptr->getOperand(0); 11320 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11321 int RHSC = (int)RHS->getZExtValue(); 11322 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11323 assert(Ptr->getOpcode() == ISD::ADD); 11324 isInc = false; 11325 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11326 return true; 11327 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11328 isInc = Ptr->getOpcode() == ISD::ADD; 11329 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11330 return true; 11331 } 11332 } 11333 11334 return false; 11335 } 11336 11337 /// getPreIndexedAddressParts - returns true by value, base pointer and 11338 /// offset pointer and addressing mode by reference if the node's address 11339 /// can be legally represented as pre-indexed load / store address. 11340 bool 11341 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11342 SDValue &Offset, 11343 ISD::MemIndexedMode &AM, 11344 SelectionDAG &DAG) const { 11345 if (Subtarget->isThumb1Only()) 11346 return false; 11347 11348 EVT VT; 11349 SDValue Ptr; 11350 bool isSEXTLoad = false; 11351 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11352 Ptr = LD->getBasePtr(); 11353 VT = LD->getMemoryVT(); 11354 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11355 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11356 Ptr = ST->getBasePtr(); 11357 VT = ST->getMemoryVT(); 11358 } else 11359 return false; 11360 11361 bool isInc; 11362 bool isLegal = false; 11363 if (Subtarget->isThumb2()) 11364 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11365 Offset, isInc, DAG); 11366 else 11367 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11368 Offset, isInc, DAG); 11369 if (!isLegal) 11370 return false; 11371 11372 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11373 return true; 11374 } 11375 11376 /// getPostIndexedAddressParts - returns true by value, base pointer and 11377 /// offset pointer and addressing mode by reference if this node can be 11378 /// combined with a load / store to form a post-indexed load / store. 11379 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11380 SDValue &Base, 11381 SDValue &Offset, 11382 ISD::MemIndexedMode &AM, 11383 SelectionDAG &DAG) const { 11384 if (Subtarget->isThumb1Only()) 11385 return false; 11386 11387 EVT VT; 11388 SDValue Ptr; 11389 bool isSEXTLoad = false; 11390 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11391 VT = LD->getMemoryVT(); 11392 Ptr = LD->getBasePtr(); 11393 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11394 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11395 VT = ST->getMemoryVT(); 11396 Ptr = ST->getBasePtr(); 11397 } else 11398 return false; 11399 11400 bool isInc; 11401 bool isLegal = false; 11402 if (Subtarget->isThumb2()) 11403 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11404 isInc, DAG); 11405 else 11406 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11407 isInc, DAG); 11408 if (!isLegal) 11409 return false; 11410 11411 if (Ptr != Base) { 11412 // Swap base ptr and offset to catch more post-index load / store when 11413 // it's legal. In Thumb2 mode, offset must be an immediate. 11414 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11415 !Subtarget->isThumb2()) 11416 std::swap(Base, Offset); 11417 11418 // Post-indexed load / store update the base pointer. 11419 if (Ptr != Base) 11420 return false; 11421 } 11422 11423 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11424 return true; 11425 } 11426 11427 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11428 APInt &KnownZero, 11429 APInt &KnownOne, 11430 const SelectionDAG &DAG, 11431 unsigned Depth) const { 11432 unsigned BitWidth = KnownOne.getBitWidth(); 11433 KnownZero = KnownOne = APInt(BitWidth, 0); 11434 switch (Op.getOpcode()) { 11435 default: break; 11436 case ARMISD::ADDC: 11437 case ARMISD::ADDE: 11438 case ARMISD::SUBC: 11439 case ARMISD::SUBE: 11440 // These nodes' second result is a boolean 11441 if (Op.getResNo() == 0) 11442 break; 11443 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11444 break; 11445 case ARMISD::CMOV: { 11446 // Bits are known zero/one if known on the LHS and RHS. 11447 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11448 if (KnownZero == 0 && KnownOne == 0) return; 11449 11450 APInt KnownZeroRHS, KnownOneRHS; 11451 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11452 KnownZero &= KnownZeroRHS; 11453 KnownOne &= KnownOneRHS; 11454 return; 11455 } 11456 case ISD::INTRINSIC_W_CHAIN: { 11457 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11458 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11459 switch (IntID) { 11460 default: return; 11461 case Intrinsic::arm_ldaex: 11462 case Intrinsic::arm_ldrex: { 11463 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11464 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11465 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11466 return; 11467 } 11468 } 11469 } 11470 } 11471 } 11472 11473 //===----------------------------------------------------------------------===// 11474 // ARM Inline Assembly Support 11475 //===----------------------------------------------------------------------===// 11476 11477 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11478 // Looking for "rev" which is V6+. 11479 if (!Subtarget->hasV6Ops()) 11480 return false; 11481 11482 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11483 std::string AsmStr = IA->getAsmString(); 11484 SmallVector<StringRef, 4> AsmPieces; 11485 SplitString(AsmStr, AsmPieces, ";\n"); 11486 11487 switch (AsmPieces.size()) { 11488 default: return false; 11489 case 1: 11490 AsmStr = AsmPieces[0]; 11491 AsmPieces.clear(); 11492 SplitString(AsmStr, AsmPieces, " \t,"); 11493 11494 // rev $0, $1 11495 if (AsmPieces.size() == 3 && 11496 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11497 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11498 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11499 if (Ty && Ty->getBitWidth() == 32) 11500 return IntrinsicLowering::LowerToByteSwap(CI); 11501 } 11502 break; 11503 } 11504 11505 return false; 11506 } 11507 11508 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 11509 // At this point, we have to lower this constraint to something else, so we 11510 // lower it to an "r" or "w". However, by doing this we will force the result 11511 // to be in register, while the X constraint is much more permissive. 11512 // 11513 // Although we are correct (we are free to emit anything, without 11514 // constraints), we might break use cases that would expect us to be more 11515 // efficient and emit something else. 11516 if (!Subtarget->hasVFP2()) 11517 return "r"; 11518 if (ConstraintVT.isFloatingPoint()) 11519 return "w"; 11520 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 11521 (ConstraintVT.getSizeInBits() == 64 || 11522 ConstraintVT.getSizeInBits() == 128)) 11523 return "w"; 11524 11525 return "r"; 11526 } 11527 11528 /// getConstraintType - Given a constraint letter, return the type of 11529 /// constraint it is for this target. 11530 ARMTargetLowering::ConstraintType 11531 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11532 if (Constraint.size() == 1) { 11533 switch (Constraint[0]) { 11534 default: break; 11535 case 'l': return C_RegisterClass; 11536 case 'w': return C_RegisterClass; 11537 case 'h': return C_RegisterClass; 11538 case 'x': return C_RegisterClass; 11539 case 't': return C_RegisterClass; 11540 case 'j': return C_Other; // Constant for movw. 11541 // An address with a single base register. Due to the way we 11542 // currently handle addresses it is the same as an 'r' memory constraint. 11543 case 'Q': return C_Memory; 11544 } 11545 } else if (Constraint.size() == 2) { 11546 switch (Constraint[0]) { 11547 default: break; 11548 // All 'U+' constraints are addresses. 11549 case 'U': return C_Memory; 11550 } 11551 } 11552 return TargetLowering::getConstraintType(Constraint); 11553 } 11554 11555 /// Examine constraint type and operand type and determine a weight value. 11556 /// This object must already have been set up with the operand type 11557 /// and the current alternative constraint selected. 11558 TargetLowering::ConstraintWeight 11559 ARMTargetLowering::getSingleConstraintMatchWeight( 11560 AsmOperandInfo &info, const char *constraint) const { 11561 ConstraintWeight weight = CW_Invalid; 11562 Value *CallOperandVal = info.CallOperandVal; 11563 // If we don't have a value, we can't do a match, 11564 // but allow it at the lowest weight. 11565 if (!CallOperandVal) 11566 return CW_Default; 11567 Type *type = CallOperandVal->getType(); 11568 // Look at the constraint type. 11569 switch (*constraint) { 11570 default: 11571 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11572 break; 11573 case 'l': 11574 if (type->isIntegerTy()) { 11575 if (Subtarget->isThumb()) 11576 weight = CW_SpecificReg; 11577 else 11578 weight = CW_Register; 11579 } 11580 break; 11581 case 'w': 11582 if (type->isFloatingPointTy()) 11583 weight = CW_Register; 11584 break; 11585 } 11586 return weight; 11587 } 11588 11589 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 11590 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 11591 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 11592 if (Constraint.size() == 1) { 11593 // GCC ARM Constraint Letters 11594 switch (Constraint[0]) { 11595 case 'l': // Low regs or general regs. 11596 if (Subtarget->isThumb()) 11597 return RCPair(0U, &ARM::tGPRRegClass); 11598 return RCPair(0U, &ARM::GPRRegClass); 11599 case 'h': // High regs or no regs. 11600 if (Subtarget->isThumb()) 11601 return RCPair(0U, &ARM::hGPRRegClass); 11602 break; 11603 case 'r': 11604 if (Subtarget->isThumb1Only()) 11605 return RCPair(0U, &ARM::tGPRRegClass); 11606 return RCPair(0U, &ARM::GPRRegClass); 11607 case 'w': 11608 if (VT == MVT::Other) 11609 break; 11610 if (VT == MVT::f32) 11611 return RCPair(0U, &ARM::SPRRegClass); 11612 if (VT.getSizeInBits() == 64) 11613 return RCPair(0U, &ARM::DPRRegClass); 11614 if (VT.getSizeInBits() == 128) 11615 return RCPair(0U, &ARM::QPRRegClass); 11616 break; 11617 case 'x': 11618 if (VT == MVT::Other) 11619 break; 11620 if (VT == MVT::f32) 11621 return RCPair(0U, &ARM::SPR_8RegClass); 11622 if (VT.getSizeInBits() == 64) 11623 return RCPair(0U, &ARM::DPR_8RegClass); 11624 if (VT.getSizeInBits() == 128) 11625 return RCPair(0U, &ARM::QPR_8RegClass); 11626 break; 11627 case 't': 11628 if (VT == MVT::f32) 11629 return RCPair(0U, &ARM::SPRRegClass); 11630 break; 11631 } 11632 } 11633 if (StringRef("{cc}").equals_lower(Constraint)) 11634 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 11635 11636 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11637 } 11638 11639 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 11640 /// vector. If it is invalid, don't add anything to Ops. 11641 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11642 std::string &Constraint, 11643 std::vector<SDValue>&Ops, 11644 SelectionDAG &DAG) const { 11645 SDValue Result; 11646 11647 // Currently only support length 1 constraints. 11648 if (Constraint.length() != 1) return; 11649 11650 char ConstraintLetter = Constraint[0]; 11651 switch (ConstraintLetter) { 11652 default: break; 11653 case 'j': 11654 case 'I': case 'J': case 'K': case 'L': 11655 case 'M': case 'N': case 'O': 11656 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11657 if (!C) 11658 return; 11659 11660 int64_t CVal64 = C->getSExtValue(); 11661 int CVal = (int) CVal64; 11662 // None of these constraints allow values larger than 32 bits. Check 11663 // that the value fits in an int. 11664 if (CVal != CVal64) 11665 return; 11666 11667 switch (ConstraintLetter) { 11668 case 'j': 11669 // Constant suitable for movw, must be between 0 and 11670 // 65535. 11671 if (Subtarget->hasV6T2Ops()) 11672 if (CVal >= 0 && CVal <= 65535) 11673 break; 11674 return; 11675 case 'I': 11676 if (Subtarget->isThumb1Only()) { 11677 // This must be a constant between 0 and 255, for ADD 11678 // immediates. 11679 if (CVal >= 0 && CVal <= 255) 11680 break; 11681 } else if (Subtarget->isThumb2()) { 11682 // A constant that can be used as an immediate value in a 11683 // data-processing instruction. 11684 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11685 break; 11686 } else { 11687 // A constant that can be used as an immediate value in a 11688 // data-processing instruction. 11689 if (ARM_AM::getSOImmVal(CVal) != -1) 11690 break; 11691 } 11692 return; 11693 11694 case 'J': 11695 if (Subtarget->isThumb1Only()) { 11696 // This must be a constant between -255 and -1, for negated ADD 11697 // immediates. This can be used in GCC with an "n" modifier that 11698 // prints the negated value, for use with SUB instructions. It is 11699 // not useful otherwise but is implemented for compatibility. 11700 if (CVal >= -255 && CVal <= -1) 11701 break; 11702 } else { 11703 // This must be a constant between -4095 and 4095. It is not clear 11704 // what this constraint is intended for. Implemented for 11705 // compatibility with GCC. 11706 if (CVal >= -4095 && CVal <= 4095) 11707 break; 11708 } 11709 return; 11710 11711 case 'K': 11712 if (Subtarget->isThumb1Only()) { 11713 // A 32-bit value where only one byte has a nonzero value. Exclude 11714 // zero to match GCC. This constraint is used by GCC internally for 11715 // constants that can be loaded with a move/shift combination. 11716 // It is not useful otherwise but is implemented for compatibility. 11717 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11718 break; 11719 } else if (Subtarget->isThumb2()) { 11720 // A constant whose bitwise inverse can be used as an immediate 11721 // value in a data-processing instruction. This can be used in GCC 11722 // with a "B" modifier that prints the inverted value, for use with 11723 // BIC and MVN instructions. It is not useful otherwise but is 11724 // implemented for compatibility. 11725 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11726 break; 11727 } else { 11728 // A constant whose bitwise inverse can be used as an immediate 11729 // value in a data-processing instruction. This can be used in GCC 11730 // with a "B" modifier that prints the inverted value, for use with 11731 // BIC and MVN instructions. It is not useful otherwise but is 11732 // implemented for compatibility. 11733 if (ARM_AM::getSOImmVal(~CVal) != -1) 11734 break; 11735 } 11736 return; 11737 11738 case 'L': 11739 if (Subtarget->isThumb1Only()) { 11740 // This must be a constant between -7 and 7, 11741 // for 3-operand ADD/SUB immediate instructions. 11742 if (CVal >= -7 && CVal < 7) 11743 break; 11744 } else if (Subtarget->isThumb2()) { 11745 // A constant whose negation can be used as an immediate value in a 11746 // data-processing instruction. This can be used in GCC with an "n" 11747 // modifier that prints the negated value, for use with SUB 11748 // instructions. It is not useful otherwise but is implemented for 11749 // compatibility. 11750 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11751 break; 11752 } else { 11753 // A constant whose negation can be used as an immediate value in a 11754 // data-processing instruction. This can be used in GCC with an "n" 11755 // modifier that prints the negated value, for use with SUB 11756 // instructions. It is not useful otherwise but is implemented for 11757 // compatibility. 11758 if (ARM_AM::getSOImmVal(-CVal) != -1) 11759 break; 11760 } 11761 return; 11762 11763 case 'M': 11764 if (Subtarget->isThumb1Only()) { 11765 // This must be a multiple of 4 between 0 and 1020, for 11766 // ADD sp + immediate. 11767 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 11768 break; 11769 } else { 11770 // A power of two or a constant between 0 and 32. This is used in 11771 // GCC for the shift amount on shifted register operands, but it is 11772 // useful in general for any shift amounts. 11773 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 11774 break; 11775 } 11776 return; 11777 11778 case 'N': 11779 if (Subtarget->isThumb()) { // FIXME thumb2 11780 // This must be a constant between 0 and 31, for shift amounts. 11781 if (CVal >= 0 && CVal <= 31) 11782 break; 11783 } 11784 return; 11785 11786 case 'O': 11787 if (Subtarget->isThumb()) { // FIXME thumb2 11788 // This must be a multiple of 4 between -508 and 508, for 11789 // ADD/SUB sp = sp + immediate. 11790 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 11791 break; 11792 } 11793 return; 11794 } 11795 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 11796 break; 11797 } 11798 11799 if (Result.getNode()) { 11800 Ops.push_back(Result); 11801 return; 11802 } 11803 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11804 } 11805 11806 static RTLIB::Libcall getDivRemLibcall( 11807 const SDNode *N, MVT::SimpleValueType SVT) { 11808 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11809 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11810 "Unhandled Opcode in getDivRemLibcall"); 11811 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11812 N->getOpcode() == ISD::SREM; 11813 RTLIB::Libcall LC; 11814 switch (SVT) { 11815 default: llvm_unreachable("Unexpected request for libcall!"); 11816 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 11817 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 11818 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 11819 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 11820 } 11821 return LC; 11822 } 11823 11824 static TargetLowering::ArgListTy getDivRemArgList( 11825 const SDNode *N, LLVMContext *Context) { 11826 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11827 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11828 "Unhandled Opcode in getDivRemArgList"); 11829 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11830 N->getOpcode() == ISD::SREM; 11831 TargetLowering::ArgListTy Args; 11832 TargetLowering::ArgListEntry Entry; 11833 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11834 EVT ArgVT = N->getOperand(i).getValueType(); 11835 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 11836 Entry.Node = N->getOperand(i); 11837 Entry.Ty = ArgTy; 11838 Entry.isSExt = isSigned; 11839 Entry.isZExt = !isSigned; 11840 Args.push_back(Entry); 11841 } 11842 return Args; 11843 } 11844 11845 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 11846 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 11847 Subtarget->isTargetGNUAEABI()) && 11848 "Register-based DivRem lowering only"); 11849 unsigned Opcode = Op->getOpcode(); 11850 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 11851 "Invalid opcode for Div/Rem lowering"); 11852 bool isSigned = (Opcode == ISD::SDIVREM); 11853 EVT VT = Op->getValueType(0); 11854 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 11855 11856 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 11857 VT.getSimpleVT().SimpleTy); 11858 SDValue InChain = DAG.getEntryNode(); 11859 11860 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 11861 DAG.getContext()); 11862 11863 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11864 getPointerTy(DAG.getDataLayout())); 11865 11866 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 11867 11868 SDLoc dl(Op); 11869 TargetLowering::CallLoweringInfo CLI(DAG); 11870 CLI.setDebugLoc(dl).setChain(InChain) 11871 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 11872 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 11873 11874 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 11875 return CallInfo.first; 11876 } 11877 11878 // Lowers REM using divmod helpers 11879 // see RTABI section 4.2/4.3 11880 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 11881 // Build return types (div and rem) 11882 std::vector<Type*> RetTyParams; 11883 Type *RetTyElement; 11884 11885 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 11886 default: llvm_unreachable("Unexpected request for libcall!"); 11887 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 11888 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 11889 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 11890 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 11891 } 11892 11893 RetTyParams.push_back(RetTyElement); 11894 RetTyParams.push_back(RetTyElement); 11895 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 11896 Type *RetTy = StructType::get(*DAG.getContext(), ret); 11897 11898 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 11899 SimpleTy); 11900 SDValue InChain = DAG.getEntryNode(); 11901 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 11902 bool isSigned = N->getOpcode() == ISD::SREM; 11903 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11904 getPointerTy(DAG.getDataLayout())); 11905 11906 // Lower call 11907 CallLoweringInfo CLI(DAG); 11908 CLI.setChain(InChain) 11909 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0) 11910 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 11911 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 11912 11913 // Return second (rem) result operand (first contains div) 11914 SDNode *ResNode = CallResult.first.getNode(); 11915 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 11916 return ResNode->getOperand(1); 11917 } 11918 11919 SDValue 11920 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 11921 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 11922 SDLoc DL(Op); 11923 11924 // Get the inputs. 11925 SDValue Chain = Op.getOperand(0); 11926 SDValue Size = Op.getOperand(1); 11927 11928 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 11929 DAG.getConstant(2, DL, MVT::i32)); 11930 11931 SDValue Flag; 11932 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 11933 Flag = Chain.getValue(1); 11934 11935 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11936 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 11937 11938 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 11939 Chain = NewSP.getValue(1); 11940 11941 SDValue Ops[2] = { NewSP, Chain }; 11942 return DAG.getMergeValues(Ops, DL); 11943 } 11944 11945 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11946 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 11947 "Unexpected type for custom-lowering FP_EXTEND"); 11948 11949 RTLIB::Libcall LC; 11950 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 11951 11952 SDValue SrcVal = Op.getOperand(0); 11953 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11954 SDLoc(Op)).first; 11955 } 11956 11957 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11958 assert(Op.getOperand(0).getValueType() == MVT::f64 && 11959 Subtarget->isFPOnlySP() && 11960 "Unexpected type for custom-lowering FP_ROUND"); 11961 11962 RTLIB::Libcall LC; 11963 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 11964 11965 SDValue SrcVal = Op.getOperand(0); 11966 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11967 SDLoc(Op)).first; 11968 } 11969 11970 bool 11971 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 11972 // The ARM target isn't yet aware of offsets. 11973 return false; 11974 } 11975 11976 bool ARM::isBitFieldInvertedMask(unsigned v) { 11977 if (v == 0xffffffff) 11978 return false; 11979 11980 // there can be 1's on either or both "outsides", all the "inside" 11981 // bits must be 0's 11982 return isShiftedMask_32(~v); 11983 } 11984 11985 /// isFPImmLegal - Returns true if the target can instruction select the 11986 /// specified FP immediate natively. If false, the legalizer will 11987 /// materialize the FP immediate as a load from a constant pool. 11988 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 11989 if (!Subtarget->hasVFP3()) 11990 return false; 11991 if (VT == MVT::f32) 11992 return ARM_AM::getFP32Imm(Imm) != -1; 11993 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 11994 return ARM_AM::getFP64Imm(Imm) != -1; 11995 return false; 11996 } 11997 11998 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 11999 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 12000 /// specified in the intrinsic calls. 12001 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12002 const CallInst &I, 12003 unsigned Intrinsic) const { 12004 switch (Intrinsic) { 12005 case Intrinsic::arm_neon_vld1: 12006 case Intrinsic::arm_neon_vld2: 12007 case Intrinsic::arm_neon_vld3: 12008 case Intrinsic::arm_neon_vld4: 12009 case Intrinsic::arm_neon_vld2lane: 12010 case Intrinsic::arm_neon_vld3lane: 12011 case Intrinsic::arm_neon_vld4lane: { 12012 Info.opc = ISD::INTRINSIC_W_CHAIN; 12013 // Conservatively set memVT to the entire set of vectors loaded. 12014 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12015 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 12016 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12017 Info.ptrVal = I.getArgOperand(0); 12018 Info.offset = 0; 12019 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12020 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12021 Info.vol = false; // volatile loads with NEON intrinsics not supported 12022 Info.readMem = true; 12023 Info.writeMem = false; 12024 return true; 12025 } 12026 case Intrinsic::arm_neon_vst1: 12027 case Intrinsic::arm_neon_vst2: 12028 case Intrinsic::arm_neon_vst3: 12029 case Intrinsic::arm_neon_vst4: 12030 case Intrinsic::arm_neon_vst2lane: 12031 case Intrinsic::arm_neon_vst3lane: 12032 case Intrinsic::arm_neon_vst4lane: { 12033 Info.opc = ISD::INTRINSIC_VOID; 12034 // Conservatively set memVT to the entire set of vectors stored. 12035 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12036 unsigned NumElts = 0; 12037 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 12038 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 12039 if (!ArgTy->isVectorTy()) 12040 break; 12041 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 12042 } 12043 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12044 Info.ptrVal = I.getArgOperand(0); 12045 Info.offset = 0; 12046 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12047 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12048 Info.vol = false; // volatile stores with NEON intrinsics not supported 12049 Info.readMem = false; 12050 Info.writeMem = true; 12051 return true; 12052 } 12053 case Intrinsic::arm_ldaex: 12054 case Intrinsic::arm_ldrex: { 12055 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12056 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12057 Info.opc = ISD::INTRINSIC_W_CHAIN; 12058 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12059 Info.ptrVal = I.getArgOperand(0); 12060 Info.offset = 0; 12061 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12062 Info.vol = true; 12063 Info.readMem = true; 12064 Info.writeMem = false; 12065 return true; 12066 } 12067 case Intrinsic::arm_stlex: 12068 case Intrinsic::arm_strex: { 12069 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12070 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12071 Info.opc = ISD::INTRINSIC_W_CHAIN; 12072 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12073 Info.ptrVal = I.getArgOperand(1); 12074 Info.offset = 0; 12075 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12076 Info.vol = true; 12077 Info.readMem = false; 12078 Info.writeMem = true; 12079 return true; 12080 } 12081 case Intrinsic::arm_stlexd: 12082 case Intrinsic::arm_strexd: { 12083 Info.opc = ISD::INTRINSIC_W_CHAIN; 12084 Info.memVT = MVT::i64; 12085 Info.ptrVal = I.getArgOperand(2); 12086 Info.offset = 0; 12087 Info.align = 8; 12088 Info.vol = true; 12089 Info.readMem = false; 12090 Info.writeMem = true; 12091 return true; 12092 } 12093 case Intrinsic::arm_ldaexd: 12094 case Intrinsic::arm_ldrexd: { 12095 Info.opc = ISD::INTRINSIC_W_CHAIN; 12096 Info.memVT = MVT::i64; 12097 Info.ptrVal = I.getArgOperand(0); 12098 Info.offset = 0; 12099 Info.align = 8; 12100 Info.vol = true; 12101 Info.readMem = true; 12102 Info.writeMem = false; 12103 return true; 12104 } 12105 default: 12106 break; 12107 } 12108 12109 return false; 12110 } 12111 12112 /// \brief Returns true if it is beneficial to convert a load of a constant 12113 /// to just the constant itself. 12114 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12115 Type *Ty) const { 12116 assert(Ty->isIntegerTy()); 12117 12118 unsigned Bits = Ty->getPrimitiveSizeInBits(); 12119 if (Bits == 0 || Bits > 32) 12120 return false; 12121 return true; 12122 } 12123 12124 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 12125 ARM_MB::MemBOpt Domain) const { 12126 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12127 12128 // First, if the target has no DMB, see what fallback we can use. 12129 if (!Subtarget->hasDataBarrier()) { 12130 // Some ARMv6 cpus can support data barriers with an mcr instruction. 12131 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 12132 // here. 12133 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 12134 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 12135 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 12136 Builder.getInt32(0), Builder.getInt32(7), 12137 Builder.getInt32(10), Builder.getInt32(5)}; 12138 return Builder.CreateCall(MCR, args); 12139 } else { 12140 // Instead of using barriers, atomic accesses on these subtargets use 12141 // libcalls. 12142 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 12143 } 12144 } else { 12145 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 12146 // Only a full system barrier exists in the M-class architectures. 12147 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 12148 Constant *CDomain = Builder.getInt32(Domain); 12149 return Builder.CreateCall(DMB, CDomain); 12150 } 12151 } 12152 12153 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 12154 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 12155 AtomicOrdering Ord, bool IsStore, 12156 bool IsLoad) const { 12157 switch (Ord) { 12158 case AtomicOrdering::NotAtomic: 12159 case AtomicOrdering::Unordered: 12160 llvm_unreachable("Invalid fence: unordered/non-atomic"); 12161 case AtomicOrdering::Monotonic: 12162 case AtomicOrdering::Acquire: 12163 return nullptr; // Nothing to do 12164 case AtomicOrdering::SequentiallyConsistent: 12165 if (!IsStore) 12166 return nullptr; // Nothing to do 12167 /*FALLTHROUGH*/ 12168 case AtomicOrdering::Release: 12169 case AtomicOrdering::AcquireRelease: 12170 if (Subtarget->isSwift()) 12171 return makeDMB(Builder, ARM_MB::ISHST); 12172 // FIXME: add a comment with a link to documentation justifying this. 12173 else 12174 return makeDMB(Builder, ARM_MB::ISH); 12175 } 12176 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 12177 } 12178 12179 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 12180 AtomicOrdering Ord, bool IsStore, 12181 bool IsLoad) const { 12182 switch (Ord) { 12183 case AtomicOrdering::NotAtomic: 12184 case AtomicOrdering::Unordered: 12185 llvm_unreachable("Invalid fence: unordered/not-atomic"); 12186 case AtomicOrdering::Monotonic: 12187 case AtomicOrdering::Release: 12188 return nullptr; // Nothing to do 12189 case AtomicOrdering::Acquire: 12190 case AtomicOrdering::AcquireRelease: 12191 case AtomicOrdering::SequentiallyConsistent: 12192 return makeDMB(Builder, ARM_MB::ISH); 12193 } 12194 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 12195 } 12196 12197 // Loads and stores less than 64-bits are already atomic; ones above that 12198 // are doomed anyway, so defer to the default libcall and blame the OS when 12199 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12200 // anything for those. 12201 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12202 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12203 return (Size == 64) && !Subtarget->isMClass(); 12204 } 12205 12206 // Loads and stores less than 64-bits are already atomic; ones above that 12207 // are doomed anyway, so defer to the default libcall and blame the OS when 12208 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12209 // anything for those. 12210 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12211 // guarantee, see DDI0406C ARM architecture reference manual, 12212 // sections A8.8.72-74 LDRD) 12213 TargetLowering::AtomicExpansionKind 12214 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12215 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12216 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12217 : AtomicExpansionKind::None; 12218 } 12219 12220 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12221 // and up to 64 bits on the non-M profiles 12222 TargetLowering::AtomicExpansionKind 12223 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12224 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12225 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12226 ? AtomicExpansionKind::LLSC 12227 : AtomicExpansionKind::None; 12228 } 12229 12230 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12231 AtomicCmpXchgInst *AI) const { 12232 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 12233 // implement cmpxchg without spilling. If the address being exchanged is also 12234 // on the stack and close enough to the spill slot, this can lead to a 12235 // situation where the monitor always gets cleared and the atomic operation 12236 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 12237 return getTargetMachine().getOptLevel() != 0; 12238 } 12239 12240 bool ARMTargetLowering::shouldInsertFencesForAtomic( 12241 const Instruction *I) const { 12242 return InsertFencesForAtomic; 12243 } 12244 12245 // This has so far only been implemented for MachO. 12246 bool ARMTargetLowering::useLoadStackGuardNode() const { 12247 return Subtarget->isTargetMachO(); 12248 } 12249 12250 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12251 unsigned &Cost) const { 12252 // If we do not have NEON, vector types are not natively supported. 12253 if (!Subtarget->hasNEON()) 12254 return false; 12255 12256 // Floating point values and vector values map to the same register file. 12257 // Therefore, although we could do a store extract of a vector type, this is 12258 // better to leave at float as we have more freedom in the addressing mode for 12259 // those. 12260 if (VectorTy->isFPOrFPVectorTy()) 12261 return false; 12262 12263 // If the index is unknown at compile time, this is very expensive to lower 12264 // and it is not possible to combine the store with the extract. 12265 if (!isa<ConstantInt>(Idx)) 12266 return false; 12267 12268 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12269 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12270 // We can do a store + vector extract on any vector that fits perfectly in a D 12271 // or Q register. 12272 if (BitWidth == 64 || BitWidth == 128) { 12273 Cost = 0; 12274 return true; 12275 } 12276 return false; 12277 } 12278 12279 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12280 return Subtarget->hasV6T2Ops(); 12281 } 12282 12283 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12284 return Subtarget->hasV6T2Ops(); 12285 } 12286 12287 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12288 AtomicOrdering Ord) const { 12289 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12290 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12291 bool IsAcquire = isAcquireOrStronger(Ord); 12292 12293 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12294 // intrinsic must return {i32, i32} and we have to recombine them into a 12295 // single i64 here. 12296 if (ValTy->getPrimitiveSizeInBits() == 64) { 12297 Intrinsic::ID Int = 12298 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12299 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12300 12301 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12302 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12303 12304 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12305 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12306 if (!Subtarget->isLittle()) 12307 std::swap (Lo, Hi); 12308 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12309 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12310 return Builder.CreateOr( 12311 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12312 } 12313 12314 Type *Tys[] = { Addr->getType() }; 12315 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12316 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12317 12318 return Builder.CreateTruncOrBitCast( 12319 Builder.CreateCall(Ldrex, Addr), 12320 cast<PointerType>(Addr->getType())->getElementType()); 12321 } 12322 12323 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12324 IRBuilder<> &Builder) const { 12325 if (!Subtarget->hasV7Ops()) 12326 return; 12327 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12328 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12329 } 12330 12331 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12332 Value *Addr, 12333 AtomicOrdering Ord) const { 12334 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12335 bool IsRelease = isReleaseOrStronger(Ord); 12336 12337 // Since the intrinsics must have legal type, the i64 intrinsics take two 12338 // parameters: "i32, i32". We must marshal Val into the appropriate form 12339 // before the call. 12340 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12341 Intrinsic::ID Int = 12342 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12343 Function *Strex = Intrinsic::getDeclaration(M, Int); 12344 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12345 12346 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12347 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12348 if (!Subtarget->isLittle()) 12349 std::swap (Lo, Hi); 12350 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12351 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12352 } 12353 12354 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12355 Type *Tys[] = { Addr->getType() }; 12356 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12357 12358 return Builder.CreateCall( 12359 Strex, {Builder.CreateZExtOrBitCast( 12360 Val, Strex->getFunctionType()->getParamType(0)), 12361 Addr}); 12362 } 12363 12364 /// \brief Lower an interleaved load into a vldN intrinsic. 12365 /// 12366 /// E.g. Lower an interleaved load (Factor = 2): 12367 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12368 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12369 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12370 /// 12371 /// Into: 12372 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12373 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12374 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12375 bool ARMTargetLowering::lowerInterleavedLoad( 12376 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12377 ArrayRef<unsigned> Indices, unsigned Factor) const { 12378 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12379 "Invalid interleave factor"); 12380 assert(!Shuffles.empty() && "Empty shufflevector input"); 12381 assert(Shuffles.size() == Indices.size() && 12382 "Unmatched number of shufflevectors and indices"); 12383 12384 VectorType *VecTy = Shuffles[0]->getType(); 12385 Type *EltTy = VecTy->getVectorElementType(); 12386 12387 const DataLayout &DL = LI->getModule()->getDataLayout(); 12388 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12389 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12390 12391 // Skip if we do not have NEON and skip illegal vector types and vector types 12392 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12393 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12394 return false; 12395 12396 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12397 // load integer vectors first and then convert to pointer vectors. 12398 if (EltTy->isPointerTy()) 12399 VecTy = 12400 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12401 12402 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12403 Intrinsic::arm_neon_vld3, 12404 Intrinsic::arm_neon_vld4}; 12405 12406 IRBuilder<> Builder(LI); 12407 SmallVector<Value *, 2> Ops; 12408 12409 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12410 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12411 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12412 12413 Type *Tys[] = { VecTy, Int8Ptr }; 12414 Function *VldnFunc = 12415 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12416 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12417 12418 // Replace uses of each shufflevector with the corresponding vector loaded 12419 // by ldN. 12420 for (unsigned i = 0; i < Shuffles.size(); i++) { 12421 ShuffleVectorInst *SV = Shuffles[i]; 12422 unsigned Index = Indices[i]; 12423 12424 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12425 12426 // Convert the integer vector to pointer vector if the element is pointer. 12427 if (EltTy->isPointerTy()) 12428 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12429 12430 SV->replaceAllUsesWith(SubVec); 12431 } 12432 12433 return true; 12434 } 12435 12436 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12437 /// 12438 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12439 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12440 unsigned NumElts) { 12441 SmallVector<Constant *, 16> Mask; 12442 for (unsigned i = 0; i < NumElts; i++) 12443 Mask.push_back(Builder.getInt32(Start + i)); 12444 12445 return ConstantVector::get(Mask); 12446 } 12447 12448 /// \brief Lower an interleaved store into a vstN intrinsic. 12449 /// 12450 /// E.g. Lower an interleaved store (Factor = 3): 12451 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12452 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12453 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12454 /// 12455 /// Into: 12456 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12457 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12458 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12459 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12460 /// 12461 /// Note that the new shufflevectors will be removed and we'll only generate one 12462 /// vst3 instruction in CodeGen. 12463 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12464 ShuffleVectorInst *SVI, 12465 unsigned Factor) const { 12466 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12467 "Invalid interleave factor"); 12468 12469 VectorType *VecTy = SVI->getType(); 12470 assert(VecTy->getVectorNumElements() % Factor == 0 && 12471 "Invalid interleaved store"); 12472 12473 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12474 Type *EltTy = VecTy->getVectorElementType(); 12475 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12476 12477 const DataLayout &DL = SI->getModule()->getDataLayout(); 12478 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12479 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12480 12481 // Skip if we do not have NEON and skip illegal vector types and vector types 12482 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12483 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12484 EltIs64Bits) 12485 return false; 12486 12487 Value *Op0 = SVI->getOperand(0); 12488 Value *Op1 = SVI->getOperand(1); 12489 IRBuilder<> Builder(SI); 12490 12491 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12492 // vectors to integer vectors. 12493 if (EltTy->isPointerTy()) { 12494 Type *IntTy = DL.getIntPtrType(EltTy); 12495 12496 // Convert to the corresponding integer vector. 12497 Type *IntVecTy = 12498 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12499 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12500 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12501 12502 SubVecTy = VectorType::get(IntTy, NumSubElts); 12503 } 12504 12505 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12506 Intrinsic::arm_neon_vst3, 12507 Intrinsic::arm_neon_vst4}; 12508 SmallVector<Value *, 6> Ops; 12509 12510 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12511 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12512 12513 Type *Tys[] = { Int8Ptr, SubVecTy }; 12514 Function *VstNFunc = Intrinsic::getDeclaration( 12515 SI->getModule(), StoreInts[Factor - 2], Tys); 12516 12517 // Split the shufflevector operands into sub vectors for the new vstN call. 12518 for (unsigned i = 0; i < Factor; i++) 12519 Ops.push_back(Builder.CreateShuffleVector( 12520 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12521 12522 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12523 Builder.CreateCall(VstNFunc, Ops); 12524 return true; 12525 } 12526 12527 enum HABaseType { 12528 HA_UNKNOWN = 0, 12529 HA_FLOAT, 12530 HA_DOUBLE, 12531 HA_VECT64, 12532 HA_VECT128 12533 }; 12534 12535 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12536 uint64_t &Members) { 12537 if (auto *ST = dyn_cast<StructType>(Ty)) { 12538 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12539 uint64_t SubMembers = 0; 12540 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12541 return false; 12542 Members += SubMembers; 12543 } 12544 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12545 uint64_t SubMembers = 0; 12546 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12547 return false; 12548 Members += SubMembers * AT->getNumElements(); 12549 } else if (Ty->isFloatTy()) { 12550 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12551 return false; 12552 Members = 1; 12553 Base = HA_FLOAT; 12554 } else if (Ty->isDoubleTy()) { 12555 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12556 return false; 12557 Members = 1; 12558 Base = HA_DOUBLE; 12559 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12560 Members = 1; 12561 switch (Base) { 12562 case HA_FLOAT: 12563 case HA_DOUBLE: 12564 return false; 12565 case HA_VECT64: 12566 return VT->getBitWidth() == 64; 12567 case HA_VECT128: 12568 return VT->getBitWidth() == 128; 12569 case HA_UNKNOWN: 12570 switch (VT->getBitWidth()) { 12571 case 64: 12572 Base = HA_VECT64; 12573 return true; 12574 case 128: 12575 Base = HA_VECT128; 12576 return true; 12577 default: 12578 return false; 12579 } 12580 } 12581 } 12582 12583 return (Members > 0 && Members <= 4); 12584 } 12585 12586 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 12587 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 12588 /// passing according to AAPCS rules. 12589 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 12590 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12591 if (getEffectiveCallingConv(CallConv, isVarArg) != 12592 CallingConv::ARM_AAPCS_VFP) 12593 return false; 12594 12595 HABaseType Base = HA_UNKNOWN; 12596 uint64_t Members = 0; 12597 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 12598 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 12599 12600 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 12601 return IsHA || IsIntArray; 12602 } 12603 12604 unsigned ARMTargetLowering::getExceptionPointerRegister( 12605 const Constant *PersonalityFn) const { 12606 // Platforms which do not use SjLj EH may return values in these registers 12607 // via the personality function. 12608 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 12609 } 12610 12611 unsigned ARMTargetLowering::getExceptionSelectorRegister( 12612 const Constant *PersonalityFn) const { 12613 // Platforms which do not use SjLj EH may return values in these registers 12614 // via the personality function. 12615 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 12616 } 12617 12618 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12619 // Update IsSplitCSR in ARMFunctionInfo. 12620 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 12621 AFI->setIsSplitCSR(true); 12622 } 12623 12624 void ARMTargetLowering::insertCopiesSplitCSR( 12625 MachineBasicBlock *Entry, 12626 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12627 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12628 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12629 if (!IStart) 12630 return; 12631 12632 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 12633 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12634 MachineBasicBlock::iterator MBBI = Entry->begin(); 12635 for (const MCPhysReg *I = IStart; *I; ++I) { 12636 const TargetRegisterClass *RC = nullptr; 12637 if (ARM::GPRRegClass.contains(*I)) 12638 RC = &ARM::GPRRegClass; 12639 else if (ARM::DPRRegClass.contains(*I)) 12640 RC = &ARM::DPRRegClass; 12641 else 12642 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12643 12644 unsigned NewVR = MRI->createVirtualRegister(RC); 12645 // Create copy from CSR to a virtual register. 12646 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12647 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12648 // nounwind. If we want to generalize this later, we may need to emit 12649 // CFI pseudo-instructions. 12650 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12651 Attribute::NoUnwind) && 12652 "Function should be nounwind in insertCopiesSplitCSR!"); 12653 Entry->addLiveIn(*I); 12654 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12655 .addReg(*I); 12656 12657 // Insert the copy-back instructions right before the terminator. 12658 for (auto *Exit : Exits) 12659 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12660 TII->get(TargetOpcode::COPY), *I) 12661 .addReg(NewVR); 12662 } 12663 } 12664