1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMCallingConv.h" 17 #include "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMPerfectShuffle.h" 20 #include "ARMSubtarget.h" 21 #include "ARMTargetMachine.h" 22 #include "ARMTargetObjectFile.h" 23 #include "MCTargetDesc/ARMAddressingModes.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringSwitch.h" 27 #include "llvm/CodeGen/CallingConvLower.h" 28 #include "llvm/CodeGen/IntrinsicLowering.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineJumpTableInfo.h" 34 #include "llvm/CodeGen/MachineModuleInfo.h" 35 #include "llvm/CodeGen/MachineRegisterInfo.h" 36 #include "llvm/CodeGen/SelectionDAG.h" 37 #include "llvm/IR/CallingConv.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/IRBuilder.h" 42 #include "llvm/IR/Instruction.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/MC/MCSectionMachO.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/MathExtras.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include <utility> 55 using namespace llvm; 56 57 #define DEBUG_TYPE "arm-isel" 58 59 STATISTIC(NumTailCalls, "Number of tail calls"); 60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 62 63 static cl::opt<bool> 64 ARMInterworking("arm-interworking", cl::Hidden, 65 cl::desc("Enable / disable ARM interworking (for debugging only)"), 66 cl::init(true)); 67 68 namespace { 69 class ARMCCState : public CCState { 70 public: 71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 73 ParmContext PC) 74 : CCState(CC, isVarArg, MF, locs, C) { 75 assert(((PC == Call) || (PC == Prologue)) && 76 "ARMCCState users must specify whether their context is call" 77 "or prologue generation."); 78 CallOrPrologue = PC; 79 } 80 }; 81 } 82 83 void ARMTargetLowering::InitLibcallCallingConvs() { 84 // The builtins on ARM always use AAPCS, irrespective of wheter C is AAPCS or 85 // AAPCS_VFP. 86 for (const auto LC : { 87 RTLIB::SHL_I16, 88 RTLIB::SHL_I32, 89 RTLIB::SHL_I64, 90 RTLIB::SHL_I128, 91 RTLIB::SRL_I16, 92 RTLIB::SRL_I32, 93 RTLIB::SRL_I64, 94 RTLIB::SRL_I128, 95 RTLIB::SRA_I16, 96 RTLIB::SRA_I32, 97 RTLIB::SRA_I64, 98 RTLIB::SRA_I128, 99 RTLIB::MUL_I8, 100 RTLIB::MUL_I16, 101 RTLIB::MUL_I32, 102 RTLIB::MUL_I64, 103 RTLIB::MUL_I128, 104 RTLIB::MULO_I32, 105 RTLIB::MULO_I64, 106 RTLIB::MULO_I128, 107 RTLIB::SDIV_I8, 108 RTLIB::SDIV_I16, 109 RTLIB::SDIV_I32, 110 RTLIB::SDIV_I64, 111 RTLIB::SDIV_I128, 112 RTLIB::UDIV_I8, 113 RTLIB::UDIV_I16, 114 RTLIB::UDIV_I32, 115 RTLIB::UDIV_I64, 116 RTLIB::UDIV_I128, 117 RTLIB::SREM_I8, 118 RTLIB::SREM_I16, 119 RTLIB::SREM_I32, 120 RTLIB::SREM_I64, 121 RTLIB::SREM_I128, 122 RTLIB::UREM_I8, 123 RTLIB::UREM_I16, 124 RTLIB::UREM_I32, 125 RTLIB::UREM_I64, 126 RTLIB::UREM_I128, 127 RTLIB::SDIVREM_I8, 128 RTLIB::SDIVREM_I16, 129 RTLIB::SDIVREM_I32, 130 RTLIB::SDIVREM_I64, 131 RTLIB::SDIVREM_I128, 132 RTLIB::UDIVREM_I8, 133 RTLIB::UDIVREM_I16, 134 RTLIB::UDIVREM_I32, 135 RTLIB::UDIVREM_I64, 136 RTLIB::UDIVREM_I128, 137 RTLIB::NEG_I32, 138 RTLIB::NEG_I64, 139 RTLIB::ADD_F32, 140 RTLIB::ADD_F64, 141 RTLIB::ADD_F80, 142 RTLIB::ADD_F128, 143 RTLIB::SUB_F32, 144 RTLIB::SUB_F64, 145 RTLIB::SUB_F80, 146 RTLIB::SUB_F128, 147 RTLIB::MUL_F32, 148 RTLIB::MUL_F64, 149 RTLIB::MUL_F80, 150 RTLIB::MUL_F128, 151 RTLIB::DIV_F32, 152 RTLIB::DIV_F64, 153 RTLIB::DIV_F80, 154 RTLIB::DIV_F128, 155 RTLIB::POWI_F32, 156 RTLIB::POWI_F64, 157 RTLIB::POWI_F80, 158 RTLIB::POWI_F128, 159 RTLIB::FPEXT_F64_F128, 160 RTLIB::FPEXT_F32_F128, 161 RTLIB::FPEXT_F32_F64, 162 RTLIB::FPEXT_F16_F32, 163 RTLIB::FPROUND_F32_F16, 164 RTLIB::FPROUND_F64_F16, 165 RTLIB::FPROUND_F80_F16, 166 RTLIB::FPROUND_F128_F16, 167 RTLIB::FPROUND_F64_F32, 168 RTLIB::FPROUND_F80_F32, 169 RTLIB::FPROUND_F128_F32, 170 RTLIB::FPROUND_F80_F64, 171 RTLIB::FPROUND_F128_F64, 172 RTLIB::FPTOSINT_F32_I32, 173 RTLIB::FPTOSINT_F32_I64, 174 RTLIB::FPTOSINT_F32_I128, 175 RTLIB::FPTOSINT_F64_I32, 176 RTLIB::FPTOSINT_F64_I64, 177 RTLIB::FPTOSINT_F64_I128, 178 RTLIB::FPTOSINT_F80_I32, 179 RTLIB::FPTOSINT_F80_I64, 180 RTLIB::FPTOSINT_F80_I128, 181 RTLIB::FPTOSINT_F128_I32, 182 RTLIB::FPTOSINT_F128_I64, 183 RTLIB::FPTOSINT_F128_I128, 184 RTLIB::FPTOUINT_F32_I32, 185 RTLIB::FPTOUINT_F32_I64, 186 RTLIB::FPTOUINT_F32_I128, 187 RTLIB::FPTOUINT_F64_I32, 188 RTLIB::FPTOUINT_F64_I64, 189 RTLIB::FPTOUINT_F64_I128, 190 RTLIB::FPTOUINT_F80_I32, 191 RTLIB::FPTOUINT_F80_I64, 192 RTLIB::FPTOUINT_F80_I128, 193 RTLIB::FPTOUINT_F128_I32, 194 RTLIB::FPTOUINT_F128_I64, 195 RTLIB::FPTOUINT_F128_I128, 196 RTLIB::SINTTOFP_I32_F32, 197 RTLIB::SINTTOFP_I32_F64, 198 RTLIB::SINTTOFP_I32_F80, 199 RTLIB::SINTTOFP_I32_F128, 200 RTLIB::SINTTOFP_I64_F32, 201 RTLIB::SINTTOFP_I64_F64, 202 RTLIB::SINTTOFP_I64_F80, 203 RTLIB::SINTTOFP_I64_F128, 204 RTLIB::SINTTOFP_I128_F32, 205 RTLIB::SINTTOFP_I128_F64, 206 RTLIB::SINTTOFP_I128_F80, 207 RTLIB::SINTTOFP_I128_F128, 208 RTLIB::UINTTOFP_I32_F32, 209 RTLIB::UINTTOFP_I32_F64, 210 RTLIB::UINTTOFP_I32_F80, 211 RTLIB::UINTTOFP_I32_F128, 212 RTLIB::UINTTOFP_I64_F32, 213 RTLIB::UINTTOFP_I64_F64, 214 RTLIB::UINTTOFP_I64_F80, 215 RTLIB::UINTTOFP_I64_F128, 216 RTLIB::UINTTOFP_I128_F32, 217 RTLIB::UINTTOFP_I128_F64, 218 RTLIB::UINTTOFP_I128_F80, 219 RTLIB::UINTTOFP_I128_F128, 220 RTLIB::OEQ_F32, 221 RTLIB::OEQ_F64, 222 RTLIB::OEQ_F128, 223 RTLIB::UNE_F32, 224 RTLIB::UNE_F64, 225 RTLIB::UNE_F128, 226 RTLIB::OGE_F32, 227 RTLIB::OGE_F64, 228 RTLIB::OGE_F128, 229 RTLIB::OLT_F32, 230 RTLIB::OLT_F64, 231 RTLIB::OLT_F128, 232 RTLIB::OLE_F32, 233 RTLIB::OLE_F64, 234 RTLIB::OLE_F128, 235 RTLIB::OGT_F32, 236 RTLIB::OGT_F64, 237 RTLIB::OGT_F128, 238 RTLIB::UO_F32, 239 RTLIB::UO_F64, 240 RTLIB::UO_F128, 241 RTLIB::O_F32, 242 RTLIB::O_F64, 243 RTLIB::O_F128, 244 }) 245 setLibcallCallingConv(LC, CallingConv::ARM_AAPCS); 246 } 247 248 // The APCS parameter registers. 249 static const MCPhysReg GPRArgRegs[] = { 250 ARM::R0, ARM::R1, ARM::R2, ARM::R3 251 }; 252 253 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 254 MVT PromotedBitwiseVT) { 255 if (VT != PromotedLdStVT) { 256 setOperationAction(ISD::LOAD, VT, Promote); 257 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 258 259 setOperationAction(ISD::STORE, VT, Promote); 260 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 261 } 262 263 MVT ElemTy = VT.getVectorElementType(); 264 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 265 setOperationAction(ISD::SETCC, VT, Custom); 266 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 267 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 268 if (ElemTy == MVT::i32) { 269 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 270 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 271 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 272 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 273 } else { 274 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 275 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 276 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 277 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 278 } 279 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 280 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 281 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 282 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 283 setOperationAction(ISD::SELECT, VT, Expand); 284 setOperationAction(ISD::SELECT_CC, VT, Expand); 285 setOperationAction(ISD::VSELECT, VT, Expand); 286 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 287 if (VT.isInteger()) { 288 setOperationAction(ISD::SHL, VT, Custom); 289 setOperationAction(ISD::SRA, VT, Custom); 290 setOperationAction(ISD::SRL, VT, Custom); 291 } 292 293 // Promote all bit-wise operations. 294 if (VT.isInteger() && VT != PromotedBitwiseVT) { 295 setOperationAction(ISD::AND, VT, Promote); 296 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 297 setOperationAction(ISD::OR, VT, Promote); 298 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 299 setOperationAction(ISD::XOR, VT, Promote); 300 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 301 } 302 303 // Neon does not support vector divide/remainder operations. 304 setOperationAction(ISD::SDIV, VT, Expand); 305 setOperationAction(ISD::UDIV, VT, Expand); 306 setOperationAction(ISD::FDIV, VT, Expand); 307 setOperationAction(ISD::SREM, VT, Expand); 308 setOperationAction(ISD::UREM, VT, Expand); 309 setOperationAction(ISD::FREM, VT, Expand); 310 311 if (!VT.isFloatingPoint() && 312 VT != MVT::v2i64 && VT != MVT::v1i64) 313 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 314 setOperationAction(Opcode, VT, Legal); 315 } 316 317 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 318 addRegisterClass(VT, &ARM::DPRRegClass); 319 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 320 } 321 322 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 323 addRegisterClass(VT, &ARM::DPairRegClass); 324 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 325 } 326 327 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 328 const ARMSubtarget &STI) 329 : TargetLowering(TM), Subtarget(&STI) { 330 RegInfo = Subtarget->getRegisterInfo(); 331 Itins = Subtarget->getInstrItineraryData(); 332 333 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 334 335 InitLibcallCallingConvs(); 336 337 if (Subtarget->isTargetMachO()) { 338 // Uses VFP for Thumb libfuncs if available. 339 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 340 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 341 static const struct { 342 const RTLIB::Libcall Op; 343 const char * const Name; 344 const ISD::CondCode Cond; 345 } LibraryCalls[] = { 346 // Single-precision floating-point arithmetic. 347 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 348 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 349 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 350 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 351 352 // Double-precision floating-point arithmetic. 353 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 354 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 355 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 356 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 357 358 // Single-precision comparisons. 359 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 360 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 361 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 362 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 363 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 364 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 365 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 366 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 367 368 // Double-precision comparisons. 369 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 370 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 371 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 372 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 373 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 374 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 375 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 376 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 377 378 // Floating-point to integer conversions. 379 // i64 conversions are done via library routines even when generating VFP 380 // instructions, so use the same ones. 381 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 382 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 383 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 384 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 385 386 // Conversions between floating types. 387 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 388 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 389 390 // Integer to floating-point conversions. 391 // i64 conversions are done via library routines even when generating VFP 392 // instructions, so use the same ones. 393 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 394 // e.g., __floatunsidf vs. __floatunssidfvfp. 395 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 396 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 397 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 398 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 399 }; 400 401 for (const auto &LC : LibraryCalls) { 402 setLibcallName(LC.Op, LC.Name); 403 if (LC.Cond != ISD::SETCC_INVALID) 404 setCmpLibcallCC(LC.Op, LC.Cond); 405 } 406 } 407 408 // Set the correct calling convention for ARMv7k WatchOS. It's just 409 // AAPCS_VFP for functions as simple as libcalls. 410 if (Subtarget->isTargetWatchABI()) { 411 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 412 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 413 } 414 } 415 416 // These libcalls are not available in 32-bit. 417 setLibcallName(RTLIB::SHL_I128, nullptr); 418 setLibcallName(RTLIB::SRL_I128, nullptr); 419 setLibcallName(RTLIB::SRA_I128, nullptr); 420 421 // RTLIB 422 if (Subtarget->isAAPCS_ABI() && 423 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 424 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 425 static const struct { 426 const RTLIB::Libcall Op; 427 const char * const Name; 428 const CallingConv::ID CC; 429 const ISD::CondCode Cond; 430 } LibraryCalls[] = { 431 // Double-precision floating-point arithmetic helper functions 432 // RTABI chapter 4.1.2, Table 2 433 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 434 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 435 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 436 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 437 438 // Double-precision floating-point comparison helper functions 439 // RTABI chapter 4.1.2, Table 3 440 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 441 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 442 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 443 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 444 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 445 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 446 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 447 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 448 449 // Single-precision floating-point arithmetic helper functions 450 // RTABI chapter 4.1.2, Table 4 451 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 452 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 453 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 454 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 455 456 // Single-precision floating-point comparison helper functions 457 // RTABI chapter 4.1.2, Table 5 458 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 459 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 460 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 461 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 462 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 463 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 464 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 465 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 466 467 // Floating-point to integer conversions. 468 // RTABI chapter 4.1.2, Table 6 469 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 470 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 471 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 472 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 473 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 474 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 475 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 476 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 477 478 // Conversions between floating types. 479 // RTABI chapter 4.1.2, Table 7 480 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 481 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 482 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 483 484 // Integer to floating-point conversions. 485 // RTABI chapter 4.1.2, Table 8 486 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 487 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 488 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 489 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 490 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 491 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 492 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 493 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 494 495 // Long long helper functions 496 // RTABI chapter 4.2, Table 9 497 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 498 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 499 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 500 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 501 502 // Integer division functions 503 // RTABI chapter 4.3.1 504 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 505 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 506 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 507 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 508 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 509 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 510 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 511 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 512 }; 513 514 for (const auto &LC : LibraryCalls) { 515 setLibcallName(LC.Op, LC.Name); 516 setLibcallCallingConv(LC.Op, LC.CC); 517 if (LC.Cond != ISD::SETCC_INVALID) 518 setCmpLibcallCC(LC.Op, LC.Cond); 519 } 520 521 // EABI dependent RTLIB 522 if (TM.Options.EABIVersion == EABI::EABI4 || 523 TM.Options.EABIVersion == EABI::EABI5) { 524 static const struct { 525 const RTLIB::Libcall Op; 526 const char *const Name; 527 const CallingConv::ID CC; 528 const ISD::CondCode Cond; 529 } MemOpsLibraryCalls[] = { 530 // Memory operations 531 // RTABI chapter 4.3.4 532 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 533 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 534 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 535 }; 536 537 for (const auto &LC : MemOpsLibraryCalls) { 538 setLibcallName(LC.Op, LC.Name); 539 setLibcallCallingConv(LC.Op, LC.CC); 540 if (LC.Cond != ISD::SETCC_INVALID) 541 setCmpLibcallCC(LC.Op, LC.Cond); 542 } 543 } 544 } 545 546 if (Subtarget->isTargetWindows()) { 547 static const struct { 548 const RTLIB::Libcall Op; 549 const char * const Name; 550 const CallingConv::ID CC; 551 } LibraryCalls[] = { 552 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 553 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 554 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 555 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 556 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 557 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 558 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 559 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 560 }; 561 562 for (const auto &LC : LibraryCalls) { 563 setLibcallName(LC.Op, LC.Name); 564 setLibcallCallingConv(LC.Op, LC.CC); 565 } 566 } 567 568 // Use divmod compiler-rt calls for iOS 5.0 and later. 569 if (Subtarget->isTargetWatchOS() || 570 (Subtarget->isTargetIOS() && 571 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 572 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 573 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 574 } 575 576 // The half <-> float conversion functions are always soft-float on 577 // non-watchos platforms, but are needed for some targets which use a 578 // hard-float calling convention by default. 579 if (!Subtarget->isTargetWatchABI()) { 580 if (Subtarget->isAAPCS_ABI()) { 581 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 582 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 583 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 584 } else { 585 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 586 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 587 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 588 } 589 } 590 591 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 592 // a __gnu_ prefix (which is the default). 593 if (Subtarget->isTargetAEABI()) { 594 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 595 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 596 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 597 } 598 599 if (Subtarget->isThumb1Only()) 600 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 601 else 602 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 603 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 604 !Subtarget->isThumb1Only()) { 605 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 606 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 607 } 608 609 for (MVT VT : MVT::vector_valuetypes()) { 610 for (MVT InnerVT : MVT::vector_valuetypes()) { 611 setTruncStoreAction(VT, InnerVT, Expand); 612 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 613 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 614 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 615 } 616 617 setOperationAction(ISD::MULHS, VT, Expand); 618 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 619 setOperationAction(ISD::MULHU, VT, Expand); 620 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 621 622 setOperationAction(ISD::BSWAP, VT, Expand); 623 } 624 625 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 626 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 627 628 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 629 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 630 631 if (Subtarget->hasNEON()) { 632 addDRTypeForNEON(MVT::v2f32); 633 addDRTypeForNEON(MVT::v8i8); 634 addDRTypeForNEON(MVT::v4i16); 635 addDRTypeForNEON(MVT::v2i32); 636 addDRTypeForNEON(MVT::v1i64); 637 638 addQRTypeForNEON(MVT::v4f32); 639 addQRTypeForNEON(MVT::v2f64); 640 addQRTypeForNEON(MVT::v16i8); 641 addQRTypeForNEON(MVT::v8i16); 642 addQRTypeForNEON(MVT::v4i32); 643 addQRTypeForNEON(MVT::v2i64); 644 645 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 646 // neither Neon nor VFP support any arithmetic operations on it. 647 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 648 // supported for v4f32. 649 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 650 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 651 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 652 // FIXME: Code duplication: FDIV and FREM are expanded always, see 653 // ARMTargetLowering::addTypeForNEON method for details. 654 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 655 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 656 // FIXME: Create unittest. 657 // In another words, find a way when "copysign" appears in DAG with vector 658 // operands. 659 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 660 // FIXME: Code duplication: SETCC has custom operation action, see 661 // ARMTargetLowering::addTypeForNEON method for details. 662 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 663 // FIXME: Create unittest for FNEG and for FABS. 664 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 665 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 666 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 667 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 668 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 669 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 670 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 671 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 672 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 673 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 674 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 675 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 676 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 677 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 678 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 679 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 680 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 681 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 682 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 683 684 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 685 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 686 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 687 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 688 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 689 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 690 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 691 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 692 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 693 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 694 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 695 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 696 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 697 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 698 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 699 700 // Mark v2f32 intrinsics. 701 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 702 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 703 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 704 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 705 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 706 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 707 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 708 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 709 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 710 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 711 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 712 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 713 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 714 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 715 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 716 717 // Neon does not support some operations on v1i64 and v2i64 types. 718 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 719 // Custom handling for some quad-vector types to detect VMULL. 720 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 721 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 722 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 723 // Custom handling for some vector types to avoid expensive expansions 724 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 725 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 726 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 727 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 728 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 729 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 730 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 731 // a destination type that is wider than the source, and nor does 732 // it have a FP_TO_[SU]INT instruction with a narrower destination than 733 // source. 734 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 735 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 736 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 737 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 738 739 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 740 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 741 742 // NEON does not have single instruction CTPOP for vectors with element 743 // types wider than 8-bits. However, custom lowering can leverage the 744 // v8i8/v16i8 vcnt instruction. 745 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 746 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 747 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 748 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 749 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 750 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 751 752 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 753 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 754 755 // NEON does not have single instruction CTTZ for vectors. 756 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 757 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 758 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 759 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 760 761 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 762 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 763 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 764 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 765 766 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 767 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 768 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 769 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 770 771 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 772 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 773 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 774 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 775 776 // NEON only has FMA instructions as of VFP4. 777 if (!Subtarget->hasVFP4()) { 778 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 779 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 780 } 781 782 setTargetDAGCombine(ISD::INTRINSIC_VOID); 783 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 784 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 785 setTargetDAGCombine(ISD::SHL); 786 setTargetDAGCombine(ISD::SRL); 787 setTargetDAGCombine(ISD::SRA); 788 setTargetDAGCombine(ISD::SIGN_EXTEND); 789 setTargetDAGCombine(ISD::ZERO_EXTEND); 790 setTargetDAGCombine(ISD::ANY_EXTEND); 791 setTargetDAGCombine(ISD::BUILD_VECTOR); 792 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 793 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 794 setTargetDAGCombine(ISD::STORE); 795 setTargetDAGCombine(ISD::FP_TO_SINT); 796 setTargetDAGCombine(ISD::FP_TO_UINT); 797 setTargetDAGCombine(ISD::FDIV); 798 setTargetDAGCombine(ISD::LOAD); 799 800 // It is legal to extload from v4i8 to v4i16 or v4i32. 801 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 802 MVT::v2i32}) { 803 for (MVT VT : MVT::integer_vector_valuetypes()) { 804 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 805 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 806 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 807 } 808 } 809 } 810 811 // ARM and Thumb2 support UMLAL/SMLAL. 812 if (!Subtarget->isThumb1Only()) 813 setTargetDAGCombine(ISD::ADDC); 814 815 if (Subtarget->isFPOnlySP()) { 816 // When targeting a floating-point unit with only single-precision 817 // operations, f64 is legal for the few double-precision instructions which 818 // are present However, no double-precision operations other than moves, 819 // loads and stores are provided by the hardware. 820 setOperationAction(ISD::FADD, MVT::f64, Expand); 821 setOperationAction(ISD::FSUB, MVT::f64, Expand); 822 setOperationAction(ISD::FMUL, MVT::f64, Expand); 823 setOperationAction(ISD::FMA, MVT::f64, Expand); 824 setOperationAction(ISD::FDIV, MVT::f64, Expand); 825 setOperationAction(ISD::FREM, MVT::f64, Expand); 826 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 827 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 828 setOperationAction(ISD::FNEG, MVT::f64, Expand); 829 setOperationAction(ISD::FABS, MVT::f64, Expand); 830 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 831 setOperationAction(ISD::FSIN, MVT::f64, Expand); 832 setOperationAction(ISD::FCOS, MVT::f64, Expand); 833 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 834 setOperationAction(ISD::FPOW, MVT::f64, Expand); 835 setOperationAction(ISD::FLOG, MVT::f64, Expand); 836 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 837 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 838 setOperationAction(ISD::FEXP, MVT::f64, Expand); 839 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 840 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 841 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 842 setOperationAction(ISD::FRINT, MVT::f64, Expand); 843 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 844 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 845 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 846 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 847 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 848 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 849 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 850 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 851 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 852 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 853 } 854 855 computeRegisterProperties(Subtarget->getRegisterInfo()); 856 857 // ARM does not have floating-point extending loads. 858 for (MVT VT : MVT::fp_valuetypes()) { 859 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 860 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 861 } 862 863 // ... or truncating stores 864 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 865 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 866 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 867 868 // ARM does not have i1 sign extending load. 869 for (MVT VT : MVT::integer_valuetypes()) 870 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 871 872 // ARM supports all 4 flavors of integer indexed load / store. 873 if (!Subtarget->isThumb1Only()) { 874 for (unsigned im = (unsigned)ISD::PRE_INC; 875 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 876 setIndexedLoadAction(im, MVT::i1, Legal); 877 setIndexedLoadAction(im, MVT::i8, Legal); 878 setIndexedLoadAction(im, MVT::i16, Legal); 879 setIndexedLoadAction(im, MVT::i32, Legal); 880 setIndexedStoreAction(im, MVT::i1, Legal); 881 setIndexedStoreAction(im, MVT::i8, Legal); 882 setIndexedStoreAction(im, MVT::i16, Legal); 883 setIndexedStoreAction(im, MVT::i32, Legal); 884 } 885 } else { 886 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 887 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 888 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 889 } 890 891 setOperationAction(ISD::SADDO, MVT::i32, Custom); 892 setOperationAction(ISD::UADDO, MVT::i32, Custom); 893 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 894 setOperationAction(ISD::USUBO, MVT::i32, Custom); 895 896 // i64 operation support. 897 setOperationAction(ISD::MUL, MVT::i64, Expand); 898 setOperationAction(ISD::MULHU, MVT::i32, Expand); 899 if (Subtarget->isThumb1Only()) { 900 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 901 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 902 } 903 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 904 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 905 setOperationAction(ISD::MULHS, MVT::i32, Expand); 906 907 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 908 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 909 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 910 setOperationAction(ISD::SRL, MVT::i64, Custom); 911 setOperationAction(ISD::SRA, MVT::i64, Custom); 912 913 if (!Subtarget->isThumb1Only()) { 914 // FIXME: We should do this for Thumb1 as well. 915 setOperationAction(ISD::ADDC, MVT::i32, Custom); 916 setOperationAction(ISD::ADDE, MVT::i32, Custom); 917 setOperationAction(ISD::SUBC, MVT::i32, Custom); 918 setOperationAction(ISD::SUBE, MVT::i32, Custom); 919 } 920 921 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 922 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 923 924 // ARM does not have ROTL. 925 setOperationAction(ISD::ROTL, MVT::i32, Expand); 926 for (MVT VT : MVT::vector_valuetypes()) { 927 setOperationAction(ISD::ROTL, VT, Expand); 928 setOperationAction(ISD::ROTR, VT, Expand); 929 } 930 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 931 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 932 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 933 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 934 935 // @llvm.readcyclecounter requires the Performance Monitors extension. 936 // Default to the 0 expansion on unsupported platforms. 937 // FIXME: Technically there are older ARM CPUs that have 938 // implementation-specific ways of obtaining this information. 939 if (Subtarget->hasPerfMon()) 940 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 941 942 // Only ARMv6 has BSWAP. 943 if (!Subtarget->hasV6Ops()) 944 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 945 946 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 947 : Subtarget->hasDivideInARMMode(); 948 if (!hasDivide) { 949 // These are expanded into libcalls if the cpu doesn't have HW divider. 950 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 951 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 952 } 953 954 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 955 setOperationAction(ISD::SDIV, MVT::i32, Custom); 956 setOperationAction(ISD::UDIV, MVT::i32, Custom); 957 958 setOperationAction(ISD::SDIV, MVT::i64, Custom); 959 setOperationAction(ISD::UDIV, MVT::i64, Custom); 960 } 961 962 setOperationAction(ISD::SREM, MVT::i32, Expand); 963 setOperationAction(ISD::UREM, MVT::i32, Expand); 964 // Register based DivRem for AEABI (RTABI 4.2) 965 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 966 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) { 967 setOperationAction(ISD::SREM, MVT::i64, Custom); 968 setOperationAction(ISD::UREM, MVT::i64, Custom); 969 HasStandaloneRem = false; 970 971 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 972 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 973 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 974 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 975 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 976 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 977 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 978 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 979 980 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 981 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 982 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 983 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 984 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 985 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 986 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 987 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 988 989 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 990 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 991 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 992 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 993 } else { 994 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 995 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 996 } 997 998 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 999 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1000 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1001 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1002 1003 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1004 1005 // Use the default implementation. 1006 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1007 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1008 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1009 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1010 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1011 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1012 1013 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 1014 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1015 else 1016 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1017 1018 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1019 // the default expansion. 1020 InsertFencesForAtomic = false; 1021 if (Subtarget->hasAnyDataBarrier() && 1022 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1023 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1024 // to ldrex/strex loops already. 1025 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1026 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1027 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1028 1029 // On v8, we have particularly efficient implementations of atomic fences 1030 // if they can be combined with nearby atomic loads and stores. 1031 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 1032 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1033 InsertFencesForAtomic = true; 1034 } 1035 } else { 1036 // If there's anything we can use as a barrier, go through custom lowering 1037 // for ATOMIC_FENCE. 1038 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1039 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1040 1041 // Set them all for expansion, which will force libcalls. 1042 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1043 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1044 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1045 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1046 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1047 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1048 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1049 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1050 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1051 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1052 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1053 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1054 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1055 // Unordered/Monotonic case. 1056 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1057 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1058 } 1059 1060 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1061 1062 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1063 if (!Subtarget->hasV6Ops()) { 1064 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1065 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1066 } 1067 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1068 1069 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1070 !Subtarget->isThumb1Only()) { 1071 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1072 // iff target supports vfp2. 1073 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1074 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1075 } 1076 1077 // We want to custom lower some of our intrinsics. 1078 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1079 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1080 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1081 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1082 if (Subtarget->useSjLjEH()) 1083 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1084 1085 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1086 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1087 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1088 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1089 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1090 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1091 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1092 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1093 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1094 1095 // Thumb-1 cannot currently select ARMISD::SUBE. 1096 if (!Subtarget->isThumb1Only()) 1097 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1098 1099 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 1100 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1101 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1102 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1103 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1104 1105 // We don't support sin/cos/fmod/copysign/pow 1106 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1107 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1108 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1109 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1110 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1111 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1112 setOperationAction(ISD::FREM, MVT::f64, Expand); 1113 setOperationAction(ISD::FREM, MVT::f32, Expand); 1114 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1115 !Subtarget->isThumb1Only()) { 1116 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1117 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1118 } 1119 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1120 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1121 1122 if (!Subtarget->hasVFP4()) { 1123 setOperationAction(ISD::FMA, MVT::f64, Expand); 1124 setOperationAction(ISD::FMA, MVT::f32, Expand); 1125 } 1126 1127 // Various VFP goodness 1128 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1129 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1130 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1131 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1132 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1133 } 1134 1135 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1136 if (!Subtarget->hasFP16()) { 1137 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1138 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1139 } 1140 } 1141 1142 // Combine sin / cos into one node or libcall if possible. 1143 if (Subtarget->hasSinCos()) { 1144 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1145 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1146 if (Subtarget->isTargetWatchABI()) { 1147 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 1148 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 1149 } 1150 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 1151 // For iOS, we don't want to the normal expansion of a libcall to 1152 // sincos. We want to issue a libcall to __sincos_stret. 1153 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1154 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1155 } 1156 } 1157 1158 // FP-ARMv8 implements a lot of rounding-like FP operations. 1159 if (Subtarget->hasFPARMv8()) { 1160 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1161 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1162 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1163 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1164 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1165 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1166 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1167 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1168 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1169 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1170 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1171 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1172 1173 if (!Subtarget->isFPOnlySP()) { 1174 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1175 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1176 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1177 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1178 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1179 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1180 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1181 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1182 } 1183 } 1184 1185 if (Subtarget->hasNEON()) { 1186 // vmin and vmax aren't available in a scalar form, so we use 1187 // a NEON instruction with an undef lane instead. 1188 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1189 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1190 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1191 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1192 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1193 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1194 } 1195 1196 // We have target-specific dag combine patterns for the following nodes: 1197 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1198 setTargetDAGCombine(ISD::ADD); 1199 setTargetDAGCombine(ISD::SUB); 1200 setTargetDAGCombine(ISD::MUL); 1201 setTargetDAGCombine(ISD::AND); 1202 setTargetDAGCombine(ISD::OR); 1203 setTargetDAGCombine(ISD::XOR); 1204 1205 if (Subtarget->hasV6Ops()) 1206 setTargetDAGCombine(ISD::SRL); 1207 1208 setStackPointerRegisterToSaveRestore(ARM::SP); 1209 1210 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1211 !Subtarget->hasVFP2()) 1212 setSchedulingPreference(Sched::RegPressure); 1213 else 1214 setSchedulingPreference(Sched::Hybrid); 1215 1216 //// temporary - rewrite interface to use type 1217 MaxStoresPerMemset = 8; 1218 MaxStoresPerMemsetOptSize = 4; 1219 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1220 MaxStoresPerMemcpyOptSize = 2; 1221 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1222 MaxStoresPerMemmoveOptSize = 2; 1223 1224 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1225 // are at least 4 bytes aligned. 1226 setMinStackArgumentAlignment(4); 1227 1228 // Prefer likely predicted branches to selects on out-of-order cores. 1229 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1230 1231 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1232 } 1233 1234 bool ARMTargetLowering::useSoftFloat() const { 1235 return Subtarget->useSoftFloat(); 1236 } 1237 1238 // FIXME: It might make sense to define the representative register class as the 1239 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1240 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1241 // SPR's representative would be DPR_VFP2. This should work well if register 1242 // pressure tracking were modified such that a register use would increment the 1243 // pressure of the register class's representative and all of it's super 1244 // classes' representatives transitively. We have not implemented this because 1245 // of the difficulty prior to coalescing of modeling operand register classes 1246 // due to the common occurrence of cross class copies and subregister insertions 1247 // and extractions. 1248 std::pair<const TargetRegisterClass *, uint8_t> 1249 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1250 MVT VT) const { 1251 const TargetRegisterClass *RRC = nullptr; 1252 uint8_t Cost = 1; 1253 switch (VT.SimpleTy) { 1254 default: 1255 return TargetLowering::findRepresentativeClass(TRI, VT); 1256 // Use DPR as representative register class for all floating point 1257 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1258 // the cost is 1 for both f32 and f64. 1259 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1260 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1261 RRC = &ARM::DPRRegClass; 1262 // When NEON is used for SP, only half of the register file is available 1263 // because operations that define both SP and DP results will be constrained 1264 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1265 // coalescing by double-counting the SP regs. See the FIXME above. 1266 if (Subtarget->useNEONForSinglePrecisionFP()) 1267 Cost = 2; 1268 break; 1269 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1270 case MVT::v4f32: case MVT::v2f64: 1271 RRC = &ARM::DPRRegClass; 1272 Cost = 2; 1273 break; 1274 case MVT::v4i64: 1275 RRC = &ARM::DPRRegClass; 1276 Cost = 4; 1277 break; 1278 case MVT::v8i64: 1279 RRC = &ARM::DPRRegClass; 1280 Cost = 8; 1281 break; 1282 } 1283 return std::make_pair(RRC, Cost); 1284 } 1285 1286 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1287 switch ((ARMISD::NodeType)Opcode) { 1288 case ARMISD::FIRST_NUMBER: break; 1289 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1290 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1291 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1292 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1293 case ARMISD::CALL: return "ARMISD::CALL"; 1294 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1295 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1296 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1297 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1298 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1299 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1300 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1301 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1302 case ARMISD::CMP: return "ARMISD::CMP"; 1303 case ARMISD::CMN: return "ARMISD::CMN"; 1304 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1305 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1306 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1307 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1308 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1309 1310 case ARMISD::CMOV: return "ARMISD::CMOV"; 1311 1312 case ARMISD::SSAT: return "ARMISD::SSAT"; 1313 1314 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1315 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1316 case ARMISD::RRX: return "ARMISD::RRX"; 1317 1318 case ARMISD::ADDC: return "ARMISD::ADDC"; 1319 case ARMISD::ADDE: return "ARMISD::ADDE"; 1320 case ARMISD::SUBC: return "ARMISD::SUBC"; 1321 case ARMISD::SUBE: return "ARMISD::SUBE"; 1322 1323 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1324 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1325 1326 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1327 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1328 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1329 1330 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1331 1332 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1333 1334 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1335 1336 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1337 1338 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1339 1340 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1341 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1342 1343 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1344 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1345 case ARMISD::VCGE: return "ARMISD::VCGE"; 1346 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1347 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1348 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1349 case ARMISD::VCGT: return "ARMISD::VCGT"; 1350 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1351 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1352 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1353 case ARMISD::VTST: return "ARMISD::VTST"; 1354 1355 case ARMISD::VSHL: return "ARMISD::VSHL"; 1356 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1357 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1358 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1359 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1360 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1361 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1362 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1363 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1364 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1365 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1366 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1367 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1368 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1369 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1370 case ARMISD::VSLI: return "ARMISD::VSLI"; 1371 case ARMISD::VSRI: return "ARMISD::VSRI"; 1372 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1373 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1374 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1375 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1376 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1377 case ARMISD::VDUP: return "ARMISD::VDUP"; 1378 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1379 case ARMISD::VEXT: return "ARMISD::VEXT"; 1380 case ARMISD::VREV64: return "ARMISD::VREV64"; 1381 case ARMISD::VREV32: return "ARMISD::VREV32"; 1382 case ARMISD::VREV16: return "ARMISD::VREV16"; 1383 case ARMISD::VZIP: return "ARMISD::VZIP"; 1384 case ARMISD::VUZP: return "ARMISD::VUZP"; 1385 case ARMISD::VTRN: return "ARMISD::VTRN"; 1386 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1387 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1388 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1389 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1390 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1391 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1392 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1393 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1394 case ARMISD::BFI: return "ARMISD::BFI"; 1395 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1396 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1397 case ARMISD::VBSL: return "ARMISD::VBSL"; 1398 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1399 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1400 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1401 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1402 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1403 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1404 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1405 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1406 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1407 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1408 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1409 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1410 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1411 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1412 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1413 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1414 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1415 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1416 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1417 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1418 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1419 } 1420 return nullptr; 1421 } 1422 1423 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1424 EVT VT) const { 1425 if (!VT.isVector()) 1426 return getPointerTy(DL); 1427 return VT.changeVectorElementTypeToInteger(); 1428 } 1429 1430 /// getRegClassFor - Return the register class that should be used for the 1431 /// specified value type. 1432 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1433 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1434 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1435 // load / store 4 to 8 consecutive D registers. 1436 if (Subtarget->hasNEON()) { 1437 if (VT == MVT::v4i64) 1438 return &ARM::QQPRRegClass; 1439 if (VT == MVT::v8i64) 1440 return &ARM::QQQQPRRegClass; 1441 } 1442 return TargetLowering::getRegClassFor(VT); 1443 } 1444 1445 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1446 // source/dest is aligned and the copy size is large enough. We therefore want 1447 // to align such objects passed to memory intrinsics. 1448 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1449 unsigned &PrefAlign) const { 1450 if (!isa<MemIntrinsic>(CI)) 1451 return false; 1452 MinSize = 8; 1453 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1454 // cycle faster than 4-byte aligned LDM. 1455 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1456 return true; 1457 } 1458 1459 // Create a fast isel object. 1460 FastISel * 1461 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1462 const TargetLibraryInfo *libInfo) const { 1463 return ARM::createFastISel(funcInfo, libInfo); 1464 } 1465 1466 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1467 unsigned NumVals = N->getNumValues(); 1468 if (!NumVals) 1469 return Sched::RegPressure; 1470 1471 for (unsigned i = 0; i != NumVals; ++i) { 1472 EVT VT = N->getValueType(i); 1473 if (VT == MVT::Glue || VT == MVT::Other) 1474 continue; 1475 if (VT.isFloatingPoint() || VT.isVector()) 1476 return Sched::ILP; 1477 } 1478 1479 if (!N->isMachineOpcode()) 1480 return Sched::RegPressure; 1481 1482 // Load are scheduled for latency even if there instruction itinerary 1483 // is not available. 1484 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1485 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1486 1487 if (MCID.getNumDefs() == 0) 1488 return Sched::RegPressure; 1489 if (!Itins->isEmpty() && 1490 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1491 return Sched::ILP; 1492 1493 return Sched::RegPressure; 1494 } 1495 1496 //===----------------------------------------------------------------------===// 1497 // Lowering Code 1498 //===----------------------------------------------------------------------===// 1499 1500 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1501 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1502 switch (CC) { 1503 default: llvm_unreachable("Unknown condition code!"); 1504 case ISD::SETNE: return ARMCC::NE; 1505 case ISD::SETEQ: return ARMCC::EQ; 1506 case ISD::SETGT: return ARMCC::GT; 1507 case ISD::SETGE: return ARMCC::GE; 1508 case ISD::SETLT: return ARMCC::LT; 1509 case ISD::SETLE: return ARMCC::LE; 1510 case ISD::SETUGT: return ARMCC::HI; 1511 case ISD::SETUGE: return ARMCC::HS; 1512 case ISD::SETULT: return ARMCC::LO; 1513 case ISD::SETULE: return ARMCC::LS; 1514 } 1515 } 1516 1517 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1518 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1519 ARMCC::CondCodes &CondCode2) { 1520 CondCode2 = ARMCC::AL; 1521 switch (CC) { 1522 default: llvm_unreachable("Unknown FP condition!"); 1523 case ISD::SETEQ: 1524 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1525 case ISD::SETGT: 1526 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1527 case ISD::SETGE: 1528 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1529 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1530 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1531 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1532 case ISD::SETO: CondCode = ARMCC::VC; break; 1533 case ISD::SETUO: CondCode = ARMCC::VS; break; 1534 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1535 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1536 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1537 case ISD::SETLT: 1538 case ISD::SETULT: CondCode = ARMCC::LT; break; 1539 case ISD::SETLE: 1540 case ISD::SETULE: CondCode = ARMCC::LE; break; 1541 case ISD::SETNE: 1542 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1543 } 1544 } 1545 1546 //===----------------------------------------------------------------------===// 1547 // Calling Convention Implementation 1548 //===----------------------------------------------------------------------===// 1549 1550 #include "ARMGenCallingConv.inc" 1551 1552 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1553 /// account presence of floating point hardware and calling convention 1554 /// limitations, such as support for variadic functions. 1555 CallingConv::ID 1556 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1557 bool isVarArg) const { 1558 switch (CC) { 1559 default: 1560 llvm_unreachable("Unsupported calling convention"); 1561 case CallingConv::ARM_AAPCS: 1562 case CallingConv::ARM_APCS: 1563 case CallingConv::GHC: 1564 return CC; 1565 case CallingConv::PreserveMost: 1566 return CallingConv::PreserveMost; 1567 case CallingConv::ARM_AAPCS_VFP: 1568 case CallingConv::Swift: 1569 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1570 case CallingConv::C: 1571 if (!Subtarget->isAAPCS_ABI()) 1572 return CallingConv::ARM_APCS; 1573 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1574 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1575 !isVarArg) 1576 return CallingConv::ARM_AAPCS_VFP; 1577 else 1578 return CallingConv::ARM_AAPCS; 1579 case CallingConv::Fast: 1580 case CallingConv::CXX_FAST_TLS: 1581 if (!Subtarget->isAAPCS_ABI()) { 1582 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1583 return CallingConv::Fast; 1584 return CallingConv::ARM_APCS; 1585 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1586 return CallingConv::ARM_AAPCS_VFP; 1587 else 1588 return CallingConv::ARM_AAPCS; 1589 } 1590 } 1591 1592 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1593 /// CallingConvention. 1594 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1595 bool Return, 1596 bool isVarArg) const { 1597 switch (getEffectiveCallingConv(CC, isVarArg)) { 1598 default: 1599 llvm_unreachable("Unsupported calling convention"); 1600 case CallingConv::ARM_APCS: 1601 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1602 case CallingConv::ARM_AAPCS: 1603 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1604 case CallingConv::ARM_AAPCS_VFP: 1605 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1606 case CallingConv::Fast: 1607 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1608 case CallingConv::GHC: 1609 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1610 case CallingConv::PreserveMost: 1611 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1612 } 1613 } 1614 1615 /// LowerCallResult - Lower the result values of a call into the 1616 /// appropriate copies out of appropriate physical registers. 1617 SDValue ARMTargetLowering::LowerCallResult( 1618 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1619 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1620 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1621 SDValue ThisVal) const { 1622 1623 // Assign locations to each value returned by this call. 1624 SmallVector<CCValAssign, 16> RVLocs; 1625 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1626 *DAG.getContext(), Call); 1627 CCInfo.AnalyzeCallResult(Ins, 1628 CCAssignFnForNode(CallConv, /* Return*/ true, 1629 isVarArg)); 1630 1631 // Copy all of the result registers out of their specified physreg. 1632 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1633 CCValAssign VA = RVLocs[i]; 1634 1635 // Pass 'this' value directly from the argument to return value, to avoid 1636 // reg unit interference 1637 if (i == 0 && isThisReturn) { 1638 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1639 "unexpected return calling convention register assignment"); 1640 InVals.push_back(ThisVal); 1641 continue; 1642 } 1643 1644 SDValue Val; 1645 if (VA.needsCustom()) { 1646 // Handle f64 or half of a v2f64. 1647 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1648 InFlag); 1649 Chain = Lo.getValue(1); 1650 InFlag = Lo.getValue(2); 1651 VA = RVLocs[++i]; // skip ahead to next loc 1652 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1653 InFlag); 1654 Chain = Hi.getValue(1); 1655 InFlag = Hi.getValue(2); 1656 if (!Subtarget->isLittle()) 1657 std::swap (Lo, Hi); 1658 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1659 1660 if (VA.getLocVT() == MVT::v2f64) { 1661 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1662 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1663 DAG.getConstant(0, dl, MVT::i32)); 1664 1665 VA = RVLocs[++i]; // skip ahead to next loc 1666 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1667 Chain = Lo.getValue(1); 1668 InFlag = Lo.getValue(2); 1669 VA = RVLocs[++i]; // skip ahead to next loc 1670 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1671 Chain = Hi.getValue(1); 1672 InFlag = Hi.getValue(2); 1673 if (!Subtarget->isLittle()) 1674 std::swap (Lo, Hi); 1675 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1676 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1677 DAG.getConstant(1, dl, MVT::i32)); 1678 } 1679 } else { 1680 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1681 InFlag); 1682 Chain = Val.getValue(1); 1683 InFlag = Val.getValue(2); 1684 } 1685 1686 switch (VA.getLocInfo()) { 1687 default: llvm_unreachable("Unknown loc info!"); 1688 case CCValAssign::Full: break; 1689 case CCValAssign::BCvt: 1690 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1691 break; 1692 } 1693 1694 InVals.push_back(Val); 1695 } 1696 1697 return Chain; 1698 } 1699 1700 /// LowerMemOpCallTo - Store the argument to the stack. 1701 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1702 SDValue Arg, const SDLoc &dl, 1703 SelectionDAG &DAG, 1704 const CCValAssign &VA, 1705 ISD::ArgFlagsTy Flags) const { 1706 unsigned LocMemOffset = VA.getLocMemOffset(); 1707 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1708 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1709 StackPtr, PtrOff); 1710 return DAG.getStore( 1711 Chain, dl, Arg, PtrOff, 1712 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1713 } 1714 1715 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1716 SDValue Chain, SDValue &Arg, 1717 RegsToPassVector &RegsToPass, 1718 CCValAssign &VA, CCValAssign &NextVA, 1719 SDValue &StackPtr, 1720 SmallVectorImpl<SDValue> &MemOpChains, 1721 ISD::ArgFlagsTy Flags) const { 1722 1723 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1724 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1725 unsigned id = Subtarget->isLittle() ? 0 : 1; 1726 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1727 1728 if (NextVA.isRegLoc()) 1729 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1730 else { 1731 assert(NextVA.isMemLoc()); 1732 if (!StackPtr.getNode()) 1733 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1734 getPointerTy(DAG.getDataLayout())); 1735 1736 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1737 dl, DAG, NextVA, 1738 Flags)); 1739 } 1740 } 1741 1742 /// LowerCall - Lowering a call into a callseq_start <- 1743 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1744 /// nodes. 1745 SDValue 1746 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1747 SmallVectorImpl<SDValue> &InVals) const { 1748 SelectionDAG &DAG = CLI.DAG; 1749 SDLoc &dl = CLI.DL; 1750 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1751 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1752 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1753 SDValue Chain = CLI.Chain; 1754 SDValue Callee = CLI.Callee; 1755 bool &isTailCall = CLI.IsTailCall; 1756 CallingConv::ID CallConv = CLI.CallConv; 1757 bool doesNotRet = CLI.DoesNotReturn; 1758 bool isVarArg = CLI.IsVarArg; 1759 1760 MachineFunction &MF = DAG.getMachineFunction(); 1761 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1762 bool isThisReturn = false; 1763 bool isSibCall = false; 1764 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1765 1766 // Disable tail calls if they're not supported. 1767 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1768 isTailCall = false; 1769 1770 if (isTailCall) { 1771 // Check if it's really possible to do a tail call. 1772 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1773 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1774 Outs, OutVals, Ins, DAG); 1775 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1776 report_fatal_error("failed to perform tail call elimination on a call " 1777 "site marked musttail"); 1778 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1779 // detected sibcalls. 1780 if (isTailCall) { 1781 ++NumTailCalls; 1782 isSibCall = true; 1783 } 1784 } 1785 1786 // Analyze operands of the call, assigning locations to each operand. 1787 SmallVector<CCValAssign, 16> ArgLocs; 1788 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1789 *DAG.getContext(), Call); 1790 CCInfo.AnalyzeCallOperands(Outs, 1791 CCAssignFnForNode(CallConv, /* Return*/ false, 1792 isVarArg)); 1793 1794 // Get a count of how many bytes are to be pushed on the stack. 1795 unsigned NumBytes = CCInfo.getNextStackOffset(); 1796 1797 // For tail calls, memory operands are available in our caller's stack. 1798 if (isSibCall) 1799 NumBytes = 0; 1800 1801 // Adjust the stack pointer for the new arguments... 1802 // These operations are automatically eliminated by the prolog/epilog pass 1803 if (!isSibCall) 1804 Chain = DAG.getCALLSEQ_START(Chain, 1805 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1806 1807 SDValue StackPtr = 1808 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1809 1810 RegsToPassVector RegsToPass; 1811 SmallVector<SDValue, 8> MemOpChains; 1812 1813 // Walk the register/memloc assignments, inserting copies/loads. In the case 1814 // of tail call optimization, arguments are handled later. 1815 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1816 i != e; 1817 ++i, ++realArgIdx) { 1818 CCValAssign &VA = ArgLocs[i]; 1819 SDValue Arg = OutVals[realArgIdx]; 1820 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1821 bool isByVal = Flags.isByVal(); 1822 1823 // Promote the value if needed. 1824 switch (VA.getLocInfo()) { 1825 default: llvm_unreachable("Unknown loc info!"); 1826 case CCValAssign::Full: break; 1827 case CCValAssign::SExt: 1828 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1829 break; 1830 case CCValAssign::ZExt: 1831 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1832 break; 1833 case CCValAssign::AExt: 1834 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1835 break; 1836 case CCValAssign::BCvt: 1837 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1838 break; 1839 } 1840 1841 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1842 if (VA.needsCustom()) { 1843 if (VA.getLocVT() == MVT::v2f64) { 1844 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1845 DAG.getConstant(0, dl, MVT::i32)); 1846 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1847 DAG.getConstant(1, dl, MVT::i32)); 1848 1849 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1850 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1851 1852 VA = ArgLocs[++i]; // skip ahead to next loc 1853 if (VA.isRegLoc()) { 1854 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1855 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1856 } else { 1857 assert(VA.isMemLoc()); 1858 1859 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1860 dl, DAG, VA, Flags)); 1861 } 1862 } else { 1863 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1864 StackPtr, MemOpChains, Flags); 1865 } 1866 } else if (VA.isRegLoc()) { 1867 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1868 assert(VA.getLocVT() == MVT::i32 && 1869 "unexpected calling convention register assignment"); 1870 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1871 "unexpected use of 'returned'"); 1872 isThisReturn = true; 1873 } 1874 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1875 } else if (isByVal) { 1876 assert(VA.isMemLoc()); 1877 unsigned offset = 0; 1878 1879 // True if this byval aggregate will be split between registers 1880 // and memory. 1881 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1882 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1883 1884 if (CurByValIdx < ByValArgsCount) { 1885 1886 unsigned RegBegin, RegEnd; 1887 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1888 1889 EVT PtrVT = 1890 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1891 unsigned int i, j; 1892 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1893 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1894 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1895 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1896 MachinePointerInfo(), 1897 DAG.InferPtrAlignment(AddArg)); 1898 MemOpChains.push_back(Load.getValue(1)); 1899 RegsToPass.push_back(std::make_pair(j, Load)); 1900 } 1901 1902 // If parameter size outsides register area, "offset" value 1903 // helps us to calculate stack slot for remained part properly. 1904 offset = RegEnd - RegBegin; 1905 1906 CCInfo.nextInRegsParam(); 1907 } 1908 1909 if (Flags.getByValSize() > 4*offset) { 1910 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1911 unsigned LocMemOffset = VA.getLocMemOffset(); 1912 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1913 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1914 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1915 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1916 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1917 MVT::i32); 1918 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1919 MVT::i32); 1920 1921 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1922 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1923 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1924 Ops)); 1925 } 1926 } else if (!isSibCall) { 1927 assert(VA.isMemLoc()); 1928 1929 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1930 dl, DAG, VA, Flags)); 1931 } 1932 } 1933 1934 if (!MemOpChains.empty()) 1935 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1936 1937 // Build a sequence of copy-to-reg nodes chained together with token chain 1938 // and flag operands which copy the outgoing args into the appropriate regs. 1939 SDValue InFlag; 1940 // Tail call byval lowering might overwrite argument registers so in case of 1941 // tail call optimization the copies to registers are lowered later. 1942 if (!isTailCall) 1943 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1944 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1945 RegsToPass[i].second, InFlag); 1946 InFlag = Chain.getValue(1); 1947 } 1948 1949 // For tail calls lower the arguments to the 'real' stack slot. 1950 if (isTailCall) { 1951 // Force all the incoming stack arguments to be loaded from the stack 1952 // before any new outgoing arguments are stored to the stack, because the 1953 // outgoing stack slots may alias the incoming argument stack slots, and 1954 // the alias isn't otherwise explicit. This is slightly more conservative 1955 // than necessary, because it means that each store effectively depends 1956 // on every argument instead of just those arguments it would clobber. 1957 1958 // Do not flag preceding copytoreg stuff together with the following stuff. 1959 InFlag = SDValue(); 1960 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1961 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1962 RegsToPass[i].second, InFlag); 1963 InFlag = Chain.getValue(1); 1964 } 1965 InFlag = SDValue(); 1966 } 1967 1968 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1969 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1970 // node so that legalize doesn't hack it. 1971 bool isDirect = false; 1972 1973 const TargetMachine &TM = getTargetMachine(); 1974 const Module *Mod = MF.getFunction()->getParent(); 1975 const GlobalValue *GV = nullptr; 1976 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1977 GV = G->getGlobal(); 1978 bool isStub = 1979 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1980 1981 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1982 bool isLocalARMFunc = false; 1983 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1984 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1985 1986 if (Subtarget->genLongCalls()) { 1987 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1988 "long-calls codegen is not position independent!"); 1989 // Handle a global address or an external symbol. If it's not one of 1990 // those, the target's already in a register, so we don't need to do 1991 // anything extra. 1992 if (isa<GlobalAddressSDNode>(Callee)) { 1993 // Create a constant pool entry for the callee address 1994 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1995 ARMConstantPoolValue *CPV = 1996 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1997 1998 // Get the address of the callee into a register 1999 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2000 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2001 Callee = DAG.getLoad( 2002 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2003 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2004 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2005 const char *Sym = S->getSymbol(); 2006 2007 // Create a constant pool entry for the callee address 2008 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2009 ARMConstantPoolValue *CPV = 2010 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2011 ARMPCLabelIndex, 0); 2012 // Get the address of the callee into a register 2013 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2014 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2015 Callee = DAG.getLoad( 2016 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2017 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2018 } 2019 } else if (isa<GlobalAddressSDNode>(Callee)) { 2020 // If we're optimizing for minimum size and the function is called three or 2021 // more times in this block, we can improve codesize by calling indirectly 2022 // as BLXr has a 16-bit encoding. 2023 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2024 auto *BB = CLI.CS->getParent(); 2025 bool PreferIndirect = 2026 Subtarget->isThumb() && MF.getFunction()->optForMinSize() && 2027 count_if(GV->users(), [&BB](const User *U) { 2028 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2029 }) > 2; 2030 2031 if (!PreferIndirect) { 2032 isDirect = true; 2033 bool isDef = GV->isStrongDefinitionForLinker(); 2034 2035 // ARM call to a local ARM function is predicable. 2036 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2037 // tBX takes a register source operand. 2038 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2039 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2040 Callee = DAG.getNode( 2041 ARMISD::WrapperPIC, dl, PtrVt, 2042 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2043 Callee = 2044 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 2045 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2046 /* Alignment = */ 0, MachineMemOperand::MOInvariant); 2047 } else if (Subtarget->isTargetCOFF()) { 2048 assert(Subtarget->isTargetWindows() && 2049 "Windows is the only supported COFF target"); 2050 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2051 ? ARMII::MO_DLLIMPORT 2052 : ARMII::MO_NO_FLAG; 2053 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2054 TargetFlags); 2055 if (GV->hasDLLImportStorageClass()) 2056 Callee = 2057 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2058 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2059 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2060 } else { 2061 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2062 } 2063 } 2064 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2065 isDirect = true; 2066 // tBX takes a register source operand. 2067 const char *Sym = S->getSymbol(); 2068 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2069 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2070 ARMConstantPoolValue *CPV = 2071 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2072 ARMPCLabelIndex, 4); 2073 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2074 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2075 Callee = DAG.getLoad( 2076 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2077 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2078 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2079 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2080 } else { 2081 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2082 } 2083 } 2084 2085 // FIXME: handle tail calls differently. 2086 unsigned CallOpc; 2087 if (Subtarget->isThumb()) { 2088 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2089 CallOpc = ARMISD::CALL_NOLINK; 2090 else 2091 CallOpc = ARMISD::CALL; 2092 } else { 2093 if (!isDirect && !Subtarget->hasV5TOps()) 2094 CallOpc = ARMISD::CALL_NOLINK; 2095 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2096 // Emit regular call when code size is the priority 2097 !MF.getFunction()->optForMinSize()) 2098 // "mov lr, pc; b _foo" to avoid confusing the RSP 2099 CallOpc = ARMISD::CALL_NOLINK; 2100 else 2101 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2102 } 2103 2104 std::vector<SDValue> Ops; 2105 Ops.push_back(Chain); 2106 Ops.push_back(Callee); 2107 2108 // Add argument registers to the end of the list so that they are known live 2109 // into the call. 2110 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2111 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2112 RegsToPass[i].second.getValueType())); 2113 2114 // Add a register mask operand representing the call-preserved registers. 2115 if (!isTailCall) { 2116 const uint32_t *Mask; 2117 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2118 if (isThisReturn) { 2119 // For 'this' returns, use the R0-preserving mask if applicable 2120 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2121 if (!Mask) { 2122 // Set isThisReturn to false if the calling convention is not one that 2123 // allows 'returned' to be modeled in this way, so LowerCallResult does 2124 // not try to pass 'this' straight through 2125 isThisReturn = false; 2126 Mask = ARI->getCallPreservedMask(MF, CallConv); 2127 } 2128 } else 2129 Mask = ARI->getCallPreservedMask(MF, CallConv); 2130 2131 assert(Mask && "Missing call preserved mask for calling convention"); 2132 Ops.push_back(DAG.getRegisterMask(Mask)); 2133 } 2134 2135 if (InFlag.getNode()) 2136 Ops.push_back(InFlag); 2137 2138 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2139 if (isTailCall) { 2140 MF.getFrameInfo().setHasTailCall(); 2141 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2142 } 2143 2144 // Returns a chain and a flag for retval copy to use. 2145 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2146 InFlag = Chain.getValue(1); 2147 2148 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2149 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2150 if (!Ins.empty()) 2151 InFlag = Chain.getValue(1); 2152 2153 // Handle result values, copying them out of physregs into vregs that we 2154 // return. 2155 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2156 InVals, isThisReturn, 2157 isThisReturn ? OutVals[0] : SDValue()); 2158 } 2159 2160 /// HandleByVal - Every parameter *after* a byval parameter is passed 2161 /// on the stack. Remember the next parameter register to allocate, 2162 /// and then confiscate the rest of the parameter registers to insure 2163 /// this. 2164 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2165 unsigned Align) const { 2166 assert((State->getCallOrPrologue() == Prologue || 2167 State->getCallOrPrologue() == Call) && 2168 "unhandled ParmContext"); 2169 2170 // Byval (as with any stack) slots are always at least 4 byte aligned. 2171 Align = std::max(Align, 4U); 2172 2173 unsigned Reg = State->AllocateReg(GPRArgRegs); 2174 if (!Reg) 2175 return; 2176 2177 unsigned AlignInRegs = Align / 4; 2178 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2179 for (unsigned i = 0; i < Waste; ++i) 2180 Reg = State->AllocateReg(GPRArgRegs); 2181 2182 if (!Reg) 2183 return; 2184 2185 unsigned Excess = 4 * (ARM::R4 - Reg); 2186 2187 // Special case when NSAA != SP and parameter size greater than size of 2188 // all remained GPR regs. In that case we can't split parameter, we must 2189 // send it to stack. We also must set NCRN to R4, so waste all 2190 // remained registers. 2191 const unsigned NSAAOffset = State->getNextStackOffset(); 2192 if (NSAAOffset != 0 && Size > Excess) { 2193 while (State->AllocateReg(GPRArgRegs)) 2194 ; 2195 return; 2196 } 2197 2198 // First register for byval parameter is the first register that wasn't 2199 // allocated before this method call, so it would be "reg". 2200 // If parameter is small enough to be saved in range [reg, r4), then 2201 // the end (first after last) register would be reg + param-size-in-regs, 2202 // else parameter would be splitted between registers and stack, 2203 // end register would be r4 in this case. 2204 unsigned ByValRegBegin = Reg; 2205 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2206 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2207 // Note, first register is allocated in the beginning of function already, 2208 // allocate remained amount of registers we need. 2209 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2210 State->AllocateReg(GPRArgRegs); 2211 // A byval parameter that is split between registers and memory needs its 2212 // size truncated here. 2213 // In the case where the entire structure fits in registers, we set the 2214 // size in memory to zero. 2215 Size = std::max<int>(Size - Excess, 0); 2216 } 2217 2218 /// MatchingStackOffset - Return true if the given stack call argument is 2219 /// already available in the same position (relatively) of the caller's 2220 /// incoming argument stack. 2221 static 2222 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2223 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2224 const TargetInstrInfo *TII) { 2225 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2226 int FI = INT_MAX; 2227 if (Arg.getOpcode() == ISD::CopyFromReg) { 2228 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2229 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2230 return false; 2231 MachineInstr *Def = MRI->getVRegDef(VR); 2232 if (!Def) 2233 return false; 2234 if (!Flags.isByVal()) { 2235 if (!TII->isLoadFromStackSlot(*Def, FI)) 2236 return false; 2237 } else { 2238 return false; 2239 } 2240 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2241 if (Flags.isByVal()) 2242 // ByVal argument is passed in as a pointer but it's now being 2243 // dereferenced. e.g. 2244 // define @foo(%struct.X* %A) { 2245 // tail call @bar(%struct.X* byval %A) 2246 // } 2247 return false; 2248 SDValue Ptr = Ld->getBasePtr(); 2249 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2250 if (!FINode) 2251 return false; 2252 FI = FINode->getIndex(); 2253 } else 2254 return false; 2255 2256 assert(FI != INT_MAX); 2257 if (!MFI.isFixedObjectIndex(FI)) 2258 return false; 2259 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2260 } 2261 2262 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2263 /// for tail call optimization. Targets which want to do tail call 2264 /// optimization should implement this function. 2265 bool 2266 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2267 CallingConv::ID CalleeCC, 2268 bool isVarArg, 2269 bool isCalleeStructRet, 2270 bool isCallerStructRet, 2271 const SmallVectorImpl<ISD::OutputArg> &Outs, 2272 const SmallVectorImpl<SDValue> &OutVals, 2273 const SmallVectorImpl<ISD::InputArg> &Ins, 2274 SelectionDAG& DAG) const { 2275 MachineFunction &MF = DAG.getMachineFunction(); 2276 const Function *CallerF = MF.getFunction(); 2277 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2278 2279 assert(Subtarget->supportsTailCall()); 2280 2281 // Look for obvious safe cases to perform tail call optimization that do not 2282 // require ABI changes. This is what gcc calls sibcall. 2283 2284 // Do not sibcall optimize vararg calls unless the call site is not passing 2285 // any arguments. 2286 if (isVarArg && !Outs.empty()) 2287 return false; 2288 2289 // Exception-handling functions need a special set of instructions to indicate 2290 // a return to the hardware. Tail-calling another function would probably 2291 // break this. 2292 if (CallerF->hasFnAttribute("interrupt")) 2293 return false; 2294 2295 // Also avoid sibcall optimization if either caller or callee uses struct 2296 // return semantics. 2297 if (isCalleeStructRet || isCallerStructRet) 2298 return false; 2299 2300 // Externally-defined functions with weak linkage should not be 2301 // tail-called on ARM when the OS does not support dynamic 2302 // pre-emption of symbols, as the AAELF spec requires normal calls 2303 // to undefined weak functions to be replaced with a NOP or jump to the 2304 // next instruction. The behaviour of branch instructions in this 2305 // situation (as used for tail calls) is implementation-defined, so we 2306 // cannot rely on the linker replacing the tail call with a return. 2307 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2308 const GlobalValue *GV = G->getGlobal(); 2309 const Triple &TT = getTargetMachine().getTargetTriple(); 2310 if (GV->hasExternalWeakLinkage() && 2311 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2312 return false; 2313 } 2314 2315 // Check that the call results are passed in the same way. 2316 LLVMContext &C = *DAG.getContext(); 2317 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2318 CCAssignFnForNode(CalleeCC, true, isVarArg), 2319 CCAssignFnForNode(CallerCC, true, isVarArg))) 2320 return false; 2321 // The callee has to preserve all registers the caller needs to preserve. 2322 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2323 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2324 if (CalleeCC != CallerCC) { 2325 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2326 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2327 return false; 2328 } 2329 2330 // If Caller's vararg or byval argument has been split between registers and 2331 // stack, do not perform tail call, since part of the argument is in caller's 2332 // local frame. 2333 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2334 if (AFI_Caller->getArgRegsSaveSize()) 2335 return false; 2336 2337 // If the callee takes no arguments then go on to check the results of the 2338 // call. 2339 if (!Outs.empty()) { 2340 // Check if stack adjustment is needed. For now, do not do this if any 2341 // argument is passed on the stack. 2342 SmallVector<CCValAssign, 16> ArgLocs; 2343 ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call); 2344 CCInfo.AnalyzeCallOperands(Outs, 2345 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2346 if (CCInfo.getNextStackOffset()) { 2347 // Check if the arguments are already laid out in the right way as 2348 // the caller's fixed stack objects. 2349 MachineFrameInfo &MFI = MF.getFrameInfo(); 2350 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2351 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2352 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2353 i != e; 2354 ++i, ++realArgIdx) { 2355 CCValAssign &VA = ArgLocs[i]; 2356 EVT RegVT = VA.getLocVT(); 2357 SDValue Arg = OutVals[realArgIdx]; 2358 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2359 if (VA.getLocInfo() == CCValAssign::Indirect) 2360 return false; 2361 if (VA.needsCustom()) { 2362 // f64 and vector types are split into multiple registers or 2363 // register/stack-slot combinations. The types will not match 2364 // the registers; give up on memory f64 refs until we figure 2365 // out what to do about this. 2366 if (!VA.isRegLoc()) 2367 return false; 2368 if (!ArgLocs[++i].isRegLoc()) 2369 return false; 2370 if (RegVT == MVT::v2f64) { 2371 if (!ArgLocs[++i].isRegLoc()) 2372 return false; 2373 if (!ArgLocs[++i].isRegLoc()) 2374 return false; 2375 } 2376 } else if (!VA.isRegLoc()) { 2377 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2378 MFI, MRI, TII)) 2379 return false; 2380 } 2381 } 2382 } 2383 2384 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2385 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2386 return false; 2387 } 2388 2389 return true; 2390 } 2391 2392 bool 2393 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2394 MachineFunction &MF, bool isVarArg, 2395 const SmallVectorImpl<ISD::OutputArg> &Outs, 2396 LLVMContext &Context) const { 2397 SmallVector<CCValAssign, 16> RVLocs; 2398 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2399 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2400 isVarArg)); 2401 } 2402 2403 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2404 const SDLoc &DL, SelectionDAG &DAG) { 2405 const MachineFunction &MF = DAG.getMachineFunction(); 2406 const Function *F = MF.getFunction(); 2407 2408 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2409 2410 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2411 // version of the "preferred return address". These offsets affect the return 2412 // instruction if this is a return from PL1 without hypervisor extensions. 2413 // IRQ/FIQ: +4 "subs pc, lr, #4" 2414 // SWI: 0 "subs pc, lr, #0" 2415 // ABORT: +4 "subs pc, lr, #4" 2416 // UNDEF: +4/+2 "subs pc, lr, #0" 2417 // UNDEF varies depending on where the exception came from ARM or Thumb 2418 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2419 2420 int64_t LROffset; 2421 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2422 IntKind == "ABORT") 2423 LROffset = 4; 2424 else if (IntKind == "SWI" || IntKind == "UNDEF") 2425 LROffset = 0; 2426 else 2427 report_fatal_error("Unsupported interrupt attribute. If present, value " 2428 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2429 2430 RetOps.insert(RetOps.begin() + 1, 2431 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2432 2433 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2434 } 2435 2436 SDValue 2437 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2438 bool isVarArg, 2439 const SmallVectorImpl<ISD::OutputArg> &Outs, 2440 const SmallVectorImpl<SDValue> &OutVals, 2441 const SDLoc &dl, SelectionDAG &DAG) const { 2442 2443 // CCValAssign - represent the assignment of the return value to a location. 2444 SmallVector<CCValAssign, 16> RVLocs; 2445 2446 // CCState - Info about the registers and stack slots. 2447 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2448 *DAG.getContext(), Call); 2449 2450 // Analyze outgoing return values. 2451 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2452 isVarArg)); 2453 2454 SDValue Flag; 2455 SmallVector<SDValue, 4> RetOps; 2456 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2457 bool isLittleEndian = Subtarget->isLittle(); 2458 2459 MachineFunction &MF = DAG.getMachineFunction(); 2460 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2461 AFI->setReturnRegsCount(RVLocs.size()); 2462 2463 // Copy the result values into the output registers. 2464 for (unsigned i = 0, realRVLocIdx = 0; 2465 i != RVLocs.size(); 2466 ++i, ++realRVLocIdx) { 2467 CCValAssign &VA = RVLocs[i]; 2468 assert(VA.isRegLoc() && "Can only return in registers!"); 2469 2470 SDValue Arg = OutVals[realRVLocIdx]; 2471 2472 switch (VA.getLocInfo()) { 2473 default: llvm_unreachable("Unknown loc info!"); 2474 case CCValAssign::Full: break; 2475 case CCValAssign::BCvt: 2476 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2477 break; 2478 } 2479 2480 if (VA.needsCustom()) { 2481 if (VA.getLocVT() == MVT::v2f64) { 2482 // Extract the first half and return it in two registers. 2483 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2484 DAG.getConstant(0, dl, MVT::i32)); 2485 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2486 DAG.getVTList(MVT::i32, MVT::i32), Half); 2487 2488 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2489 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2490 Flag); 2491 Flag = Chain.getValue(1); 2492 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2493 VA = RVLocs[++i]; // skip ahead to next loc 2494 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2495 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2496 Flag); 2497 Flag = Chain.getValue(1); 2498 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2499 VA = RVLocs[++i]; // skip ahead to next loc 2500 2501 // Extract the 2nd half and fall through to handle it as an f64 value. 2502 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2503 DAG.getConstant(1, dl, MVT::i32)); 2504 } 2505 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2506 // available. 2507 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2508 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2509 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2510 fmrrd.getValue(isLittleEndian ? 0 : 1), 2511 Flag); 2512 Flag = Chain.getValue(1); 2513 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2514 VA = RVLocs[++i]; // skip ahead to next loc 2515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2516 fmrrd.getValue(isLittleEndian ? 1 : 0), 2517 Flag); 2518 } else 2519 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2520 2521 // Guarantee that all emitted copies are 2522 // stuck together, avoiding something bad. 2523 Flag = Chain.getValue(1); 2524 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2525 } 2526 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2527 const MCPhysReg *I = 2528 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2529 if (I) { 2530 for (; *I; ++I) { 2531 if (ARM::GPRRegClass.contains(*I)) 2532 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2533 else if (ARM::DPRRegClass.contains(*I)) 2534 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2535 else 2536 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2537 } 2538 } 2539 2540 // Update chain and glue. 2541 RetOps[0] = Chain; 2542 if (Flag.getNode()) 2543 RetOps.push_back(Flag); 2544 2545 // CPUs which aren't M-class use a special sequence to return from 2546 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2547 // though we use "subs pc, lr, #N"). 2548 // 2549 // M-class CPUs actually use a normal return sequence with a special 2550 // (hardware-provided) value in LR, so the normal code path works. 2551 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2552 !Subtarget->isMClass()) { 2553 if (Subtarget->isThumb1Only()) 2554 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2555 return LowerInterruptReturn(RetOps, dl, DAG); 2556 } 2557 2558 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2559 } 2560 2561 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2562 if (N->getNumValues() != 1) 2563 return false; 2564 if (!N->hasNUsesOfValue(1, 0)) 2565 return false; 2566 2567 SDValue TCChain = Chain; 2568 SDNode *Copy = *N->use_begin(); 2569 if (Copy->getOpcode() == ISD::CopyToReg) { 2570 // If the copy has a glue operand, we conservatively assume it isn't safe to 2571 // perform a tail call. 2572 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2573 return false; 2574 TCChain = Copy->getOperand(0); 2575 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2576 SDNode *VMov = Copy; 2577 // f64 returned in a pair of GPRs. 2578 SmallPtrSet<SDNode*, 2> Copies; 2579 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2580 UI != UE; ++UI) { 2581 if (UI->getOpcode() != ISD::CopyToReg) 2582 return false; 2583 Copies.insert(*UI); 2584 } 2585 if (Copies.size() > 2) 2586 return false; 2587 2588 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2589 UI != UE; ++UI) { 2590 SDValue UseChain = UI->getOperand(0); 2591 if (Copies.count(UseChain.getNode())) 2592 // Second CopyToReg 2593 Copy = *UI; 2594 else { 2595 // We are at the top of this chain. 2596 // If the copy has a glue operand, we conservatively assume it 2597 // isn't safe to perform a tail call. 2598 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2599 return false; 2600 // First CopyToReg 2601 TCChain = UseChain; 2602 } 2603 } 2604 } else if (Copy->getOpcode() == ISD::BITCAST) { 2605 // f32 returned in a single GPR. 2606 if (!Copy->hasOneUse()) 2607 return false; 2608 Copy = *Copy->use_begin(); 2609 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2610 return false; 2611 // If the copy has a glue operand, we conservatively assume it isn't safe to 2612 // perform a tail call. 2613 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2614 return false; 2615 TCChain = Copy->getOperand(0); 2616 } else { 2617 return false; 2618 } 2619 2620 bool HasRet = false; 2621 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2622 UI != UE; ++UI) { 2623 if (UI->getOpcode() != ARMISD::RET_FLAG && 2624 UI->getOpcode() != ARMISD::INTRET_FLAG) 2625 return false; 2626 HasRet = true; 2627 } 2628 2629 if (!HasRet) 2630 return false; 2631 2632 Chain = TCChain; 2633 return true; 2634 } 2635 2636 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2637 if (!Subtarget->supportsTailCall()) 2638 return false; 2639 2640 auto Attr = 2641 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2642 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2643 return false; 2644 2645 return true; 2646 } 2647 2648 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2649 // and pass the lower and high parts through. 2650 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2651 SDLoc DL(Op); 2652 SDValue WriteValue = Op->getOperand(2); 2653 2654 // This function is only supposed to be called for i64 type argument. 2655 assert(WriteValue.getValueType() == MVT::i64 2656 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2657 2658 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2659 DAG.getConstant(0, DL, MVT::i32)); 2660 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2661 DAG.getConstant(1, DL, MVT::i32)); 2662 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2663 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2664 } 2665 2666 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2667 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2668 // one of the above mentioned nodes. It has to be wrapped because otherwise 2669 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2670 // be used to form addressing mode. These wrapped nodes will be selected 2671 // into MOVi. 2672 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2673 EVT PtrVT = Op.getValueType(); 2674 // FIXME there is no actual debug info here 2675 SDLoc dl(Op); 2676 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2677 SDValue Res; 2678 if (CP->isMachineConstantPoolEntry()) 2679 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2680 CP->getAlignment()); 2681 else 2682 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2683 CP->getAlignment()); 2684 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2685 } 2686 2687 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2688 return MachineJumpTableInfo::EK_Inline; 2689 } 2690 2691 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2692 SelectionDAG &DAG) const { 2693 MachineFunction &MF = DAG.getMachineFunction(); 2694 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2695 unsigned ARMPCLabelIndex = 0; 2696 SDLoc DL(Op); 2697 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2698 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2699 SDValue CPAddr; 2700 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2701 if (!IsPositionIndependent) { 2702 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2703 } else { 2704 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2705 ARMPCLabelIndex = AFI->createPICLabelUId(); 2706 ARMConstantPoolValue *CPV = 2707 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2708 ARMCP::CPBlockAddress, PCAdj); 2709 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2710 } 2711 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2712 SDValue Result = DAG.getLoad( 2713 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2714 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2715 if (!IsPositionIndependent) 2716 return Result; 2717 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2718 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2719 } 2720 2721 /// \brief Convert a TLS address reference into the correct sequence of loads 2722 /// and calls to compute the variable's address for Darwin, and return an 2723 /// SDValue containing the final node. 2724 2725 /// Darwin only has one TLS scheme which must be capable of dealing with the 2726 /// fully general situation, in the worst case. This means: 2727 /// + "extern __thread" declaration. 2728 /// + Defined in a possibly unknown dynamic library. 2729 /// 2730 /// The general system is that each __thread variable has a [3 x i32] descriptor 2731 /// which contains information used by the runtime to calculate the address. The 2732 /// only part of this the compiler needs to know about is the first word, which 2733 /// contains a function pointer that must be called with the address of the 2734 /// entire descriptor in "r0". 2735 /// 2736 /// Since this descriptor may be in a different unit, in general access must 2737 /// proceed along the usual ARM rules. A common sequence to produce is: 2738 /// 2739 /// movw rT1, :lower16:_var$non_lazy_ptr 2740 /// movt rT1, :upper16:_var$non_lazy_ptr 2741 /// ldr r0, [rT1] 2742 /// ldr rT2, [r0] 2743 /// blx rT2 2744 /// [...address now in r0...] 2745 SDValue 2746 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2747 SelectionDAG &DAG) const { 2748 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2749 SDLoc DL(Op); 2750 2751 // First step is to get the address of the actua global symbol. This is where 2752 // the TLS descriptor lives. 2753 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2754 2755 // The first entry in the descriptor is a function pointer that we must call 2756 // to obtain the address of the variable. 2757 SDValue Chain = DAG.getEntryNode(); 2758 SDValue FuncTLVGet = 2759 DAG.getLoad(MVT::i32, DL, Chain, DescAddr, 2760 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2761 /* Alignment = */ 4, MachineMemOperand::MONonTemporal | 2762 MachineMemOperand::MOInvariant); 2763 Chain = FuncTLVGet.getValue(1); 2764 2765 MachineFunction &F = DAG.getMachineFunction(); 2766 MachineFrameInfo &MFI = F.getFrameInfo(); 2767 MFI.setAdjustsStack(true); 2768 2769 // TLS calls preserve all registers except those that absolutely must be 2770 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2771 // silly). 2772 auto TRI = 2773 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2774 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2775 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2776 2777 // Finally, we can make the call. This is just a degenerate version of a 2778 // normal AArch64 call node: r0 takes the address of the descriptor, and 2779 // returns the address of the variable in this thread. 2780 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2781 Chain = 2782 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2783 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2784 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2785 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2786 } 2787 2788 SDValue 2789 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2790 SelectionDAG &DAG) const { 2791 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2792 2793 SDValue Chain = DAG.getEntryNode(); 2794 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2795 SDLoc DL(Op); 2796 2797 // Load the current TEB (thread environment block) 2798 SDValue Ops[] = {Chain, 2799 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2800 DAG.getConstant(15, DL, MVT::i32), 2801 DAG.getConstant(0, DL, MVT::i32), 2802 DAG.getConstant(13, DL, MVT::i32), 2803 DAG.getConstant(0, DL, MVT::i32), 2804 DAG.getConstant(2, DL, MVT::i32)}; 2805 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2806 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2807 2808 SDValue TEB = CurrentTEB.getValue(0); 2809 Chain = CurrentTEB.getValue(1); 2810 2811 // Load the ThreadLocalStoragePointer from the TEB 2812 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2813 SDValue TLSArray = 2814 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2815 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2816 2817 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2818 // offset into the TLSArray. 2819 2820 // Load the TLS index from the C runtime 2821 SDValue TLSIndex = 2822 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2823 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2824 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2825 2826 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2827 DAG.getConstant(2, DL, MVT::i32)); 2828 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2829 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2830 MachinePointerInfo()); 2831 2832 // Get the offset of the start of the .tls section (section base) 2833 const auto *GA = cast<GlobalAddressSDNode>(Op); 2834 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2835 SDValue Offset = DAG.getLoad( 2836 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2837 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2838 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2839 2840 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2841 } 2842 2843 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2844 SDValue 2845 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2846 SelectionDAG &DAG) const { 2847 SDLoc dl(GA); 2848 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2849 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2850 MachineFunction &MF = DAG.getMachineFunction(); 2851 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2852 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2853 ARMConstantPoolValue *CPV = 2854 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2855 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2856 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2857 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2858 Argument = DAG.getLoad( 2859 PtrVT, dl, DAG.getEntryNode(), Argument, 2860 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2861 SDValue Chain = Argument.getValue(1); 2862 2863 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2864 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2865 2866 // call __tls_get_addr. 2867 ArgListTy Args; 2868 ArgListEntry Entry; 2869 Entry.Node = Argument; 2870 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2871 Args.push_back(Entry); 2872 2873 // FIXME: is there useful debug info available here? 2874 TargetLowering::CallLoweringInfo CLI(DAG); 2875 CLI.setDebugLoc(dl).setChain(Chain) 2876 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2877 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2878 2879 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2880 return CallResult.first; 2881 } 2882 2883 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2884 // "local exec" model. 2885 SDValue 2886 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2887 SelectionDAG &DAG, 2888 TLSModel::Model model) const { 2889 const GlobalValue *GV = GA->getGlobal(); 2890 SDLoc dl(GA); 2891 SDValue Offset; 2892 SDValue Chain = DAG.getEntryNode(); 2893 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2894 // Get the Thread Pointer 2895 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2896 2897 if (model == TLSModel::InitialExec) { 2898 MachineFunction &MF = DAG.getMachineFunction(); 2899 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2900 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2901 // Initial exec model. 2902 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2903 ARMConstantPoolValue *CPV = 2904 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2905 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2906 true); 2907 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2908 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2909 Offset = DAG.getLoad( 2910 PtrVT, dl, Chain, Offset, 2911 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2912 Chain = Offset.getValue(1); 2913 2914 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2915 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2916 2917 Offset = DAG.getLoad( 2918 PtrVT, dl, Chain, Offset, 2919 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2920 } else { 2921 // local exec model 2922 assert(model == TLSModel::LocalExec); 2923 ARMConstantPoolValue *CPV = 2924 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2925 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2926 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2927 Offset = DAG.getLoad( 2928 PtrVT, dl, Chain, Offset, 2929 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2930 } 2931 2932 // The address of the thread local variable is the add of the thread 2933 // pointer with the offset of the variable. 2934 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2935 } 2936 2937 SDValue 2938 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2939 if (Subtarget->isTargetDarwin()) 2940 return LowerGlobalTLSAddressDarwin(Op, DAG); 2941 2942 if (Subtarget->isTargetWindows()) 2943 return LowerGlobalTLSAddressWindows(Op, DAG); 2944 2945 // TODO: implement the "local dynamic" model 2946 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2947 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2948 if (DAG.getTarget().Options.EmulatedTLS) 2949 return LowerToTLSEmulatedModel(GA, DAG); 2950 2951 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2952 2953 switch (model) { 2954 case TLSModel::GeneralDynamic: 2955 case TLSModel::LocalDynamic: 2956 return LowerToTLSGeneralDynamicModel(GA, DAG); 2957 case TLSModel::InitialExec: 2958 case TLSModel::LocalExec: 2959 return LowerToTLSExecModels(GA, DAG, model); 2960 } 2961 llvm_unreachable("bogus TLS model"); 2962 } 2963 2964 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2965 SelectionDAG &DAG) const { 2966 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2967 SDLoc dl(Op); 2968 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2969 const TargetMachine &TM = getTargetMachine(); 2970 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 2971 GV = GA->getBaseObject(); 2972 bool IsRO = 2973 (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 2974 isa<Function>(GV); 2975 if (isPositionIndependent()) { 2976 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 2977 2978 MachineFunction &MF = DAG.getMachineFunction(); 2979 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2980 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2981 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2982 SDLoc dl(Op); 2983 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2984 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2985 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2986 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2987 /*AddCurrentAddress=*/UseGOT_PREL); 2988 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2989 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2990 SDValue Result = DAG.getLoad( 2991 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2992 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2993 SDValue Chain = Result.getValue(1); 2994 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2995 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2996 if (UseGOT_PREL) 2997 Result = 2998 DAG.getLoad(PtrVT, dl, Chain, Result, 2999 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3000 return Result; 3001 } else if (Subtarget->isROPI() && IsRO) { 3002 // PC-relative. 3003 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3004 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3005 return Result; 3006 } else if (Subtarget->isRWPI() && !IsRO) { 3007 // SB-relative. 3008 ARMConstantPoolValue *CPV = 3009 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3010 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3011 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3012 SDValue G = DAG.getLoad( 3013 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3014 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3015 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3016 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, G); 3017 return Result; 3018 } 3019 3020 // If we have T2 ops, we can materialize the address directly via movt/movw 3021 // pair. This is always cheaper. 3022 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3023 ++NumMovwMovt; 3024 // FIXME: Once remat is capable of dealing with instructions with register 3025 // operands, expand this into two nodes. 3026 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3027 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3028 } else { 3029 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3030 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3031 return DAG.getLoad( 3032 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3033 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3034 } 3035 } 3036 3037 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3038 SelectionDAG &DAG) const { 3039 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3040 "ROPI/RWPI not currently supported for Darwin"); 3041 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3042 SDLoc dl(Op); 3043 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3044 3045 if (Subtarget->useMovt(DAG.getMachineFunction())) 3046 ++NumMovwMovt; 3047 3048 // FIXME: Once remat is capable of dealing with instructions with register 3049 // operands, expand this into multiple nodes 3050 unsigned Wrapper = 3051 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3052 3053 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3054 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3055 3056 if (Subtarget->isGVIndirectSymbol(GV)) 3057 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3058 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3059 return Result; 3060 } 3061 3062 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3063 SelectionDAG &DAG) const { 3064 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3065 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3066 "Windows on ARM expects to use movw/movt"); 3067 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3068 "ROPI/RWPI not currently supported for Windows"); 3069 3070 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3071 const ARMII::TOF TargetFlags = 3072 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3073 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3074 SDValue Result; 3075 SDLoc DL(Op); 3076 3077 ++NumMovwMovt; 3078 3079 // FIXME: Once remat is capable of dealing with instructions with register 3080 // operands, expand this into two nodes. 3081 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3082 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3083 TargetFlags)); 3084 if (GV->hasDLLImportStorageClass()) 3085 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3086 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3087 return Result; 3088 } 3089 3090 SDValue 3091 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3092 SDLoc dl(Op); 3093 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3094 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3095 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3096 Op.getOperand(1), Val); 3097 } 3098 3099 SDValue 3100 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3101 SDLoc dl(Op); 3102 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3103 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3104 } 3105 3106 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3107 SelectionDAG &DAG) const { 3108 SDLoc dl(Op); 3109 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3110 Op.getOperand(0)); 3111 } 3112 3113 SDValue 3114 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3115 const ARMSubtarget *Subtarget) const { 3116 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3117 SDLoc dl(Op); 3118 switch (IntNo) { 3119 default: return SDValue(); // Don't custom lower most intrinsics. 3120 case Intrinsic::arm_rbit: { 3121 assert(Op.getOperand(1).getValueType() == MVT::i32 && 3122 "RBIT intrinsic must have i32 type!"); 3123 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 3124 } 3125 case Intrinsic::thread_pointer: { 3126 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3127 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3128 } 3129 case Intrinsic::eh_sjlj_lsda: { 3130 MachineFunction &MF = DAG.getMachineFunction(); 3131 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3132 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3133 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3134 SDValue CPAddr; 3135 bool IsPositionIndependent = isPositionIndependent(); 3136 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3137 ARMConstantPoolValue *CPV = 3138 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 3139 ARMCP::CPLSDA, PCAdj); 3140 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3141 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3142 SDValue Result = DAG.getLoad( 3143 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3144 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3145 3146 if (IsPositionIndependent) { 3147 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3148 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3149 } 3150 return Result; 3151 } 3152 case Intrinsic::arm_neon_vmulls: 3153 case Intrinsic::arm_neon_vmullu: { 3154 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3155 ? ARMISD::VMULLs : ARMISD::VMULLu; 3156 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3157 Op.getOperand(1), Op.getOperand(2)); 3158 } 3159 case Intrinsic::arm_neon_vminnm: 3160 case Intrinsic::arm_neon_vmaxnm: { 3161 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3162 ? ISD::FMINNUM : ISD::FMAXNUM; 3163 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3164 Op.getOperand(1), Op.getOperand(2)); 3165 } 3166 case Intrinsic::arm_neon_vminu: 3167 case Intrinsic::arm_neon_vmaxu: { 3168 if (Op.getValueType().isFloatingPoint()) 3169 return SDValue(); 3170 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3171 ? ISD::UMIN : ISD::UMAX; 3172 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3173 Op.getOperand(1), Op.getOperand(2)); 3174 } 3175 case Intrinsic::arm_neon_vmins: 3176 case Intrinsic::arm_neon_vmaxs: { 3177 // v{min,max}s is overloaded between signed integers and floats. 3178 if (!Op.getValueType().isFloatingPoint()) { 3179 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3180 ? ISD::SMIN : ISD::SMAX; 3181 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3182 Op.getOperand(1), Op.getOperand(2)); 3183 } 3184 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3185 ? ISD::FMINNAN : ISD::FMAXNAN; 3186 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3187 Op.getOperand(1), Op.getOperand(2)); 3188 } 3189 } 3190 } 3191 3192 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3193 const ARMSubtarget *Subtarget) { 3194 // FIXME: handle "fence singlethread" more efficiently. 3195 SDLoc dl(Op); 3196 if (!Subtarget->hasDataBarrier()) { 3197 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3198 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3199 // here. 3200 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3201 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3202 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3203 DAG.getConstant(0, dl, MVT::i32)); 3204 } 3205 3206 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3207 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3208 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3209 if (Subtarget->isMClass()) { 3210 // Only a full system barrier exists in the M-class architectures. 3211 Domain = ARM_MB::SY; 3212 } else if (Subtarget->preferISHSTBarriers() && 3213 Ord == AtomicOrdering::Release) { 3214 // Swift happens to implement ISHST barriers in a way that's compatible with 3215 // Release semantics but weaker than ISH so we'd be fools not to use 3216 // it. Beware: other processors probably don't! 3217 Domain = ARM_MB::ISHST; 3218 } 3219 3220 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3221 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3222 DAG.getConstant(Domain, dl, MVT::i32)); 3223 } 3224 3225 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3226 const ARMSubtarget *Subtarget) { 3227 // ARM pre v5TE and Thumb1 does not have preload instructions. 3228 if (!(Subtarget->isThumb2() || 3229 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3230 // Just preserve the chain. 3231 return Op.getOperand(0); 3232 3233 SDLoc dl(Op); 3234 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3235 if (!isRead && 3236 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3237 // ARMv7 with MP extension has PLDW. 3238 return Op.getOperand(0); 3239 3240 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3241 if (Subtarget->isThumb()) { 3242 // Invert the bits. 3243 isRead = ~isRead & 1; 3244 isData = ~isData & 1; 3245 } 3246 3247 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3248 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3249 DAG.getConstant(isData, dl, MVT::i32)); 3250 } 3251 3252 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3253 MachineFunction &MF = DAG.getMachineFunction(); 3254 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3255 3256 // vastart just stores the address of the VarArgsFrameIndex slot into the 3257 // memory location argument. 3258 SDLoc dl(Op); 3259 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3260 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3261 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3262 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3263 MachinePointerInfo(SV)); 3264 } 3265 3266 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3267 CCValAssign &NextVA, 3268 SDValue &Root, 3269 SelectionDAG &DAG, 3270 const SDLoc &dl) const { 3271 MachineFunction &MF = DAG.getMachineFunction(); 3272 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3273 3274 const TargetRegisterClass *RC; 3275 if (AFI->isThumb1OnlyFunction()) 3276 RC = &ARM::tGPRRegClass; 3277 else 3278 RC = &ARM::GPRRegClass; 3279 3280 // Transform the arguments stored in physical registers into virtual ones. 3281 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3282 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3283 3284 SDValue ArgValue2; 3285 if (NextVA.isMemLoc()) { 3286 MachineFrameInfo &MFI = MF.getFrameInfo(); 3287 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3288 3289 // Create load node to retrieve arguments from the stack. 3290 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3291 ArgValue2 = DAG.getLoad( 3292 MVT::i32, dl, Root, FIN, 3293 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3294 } else { 3295 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3296 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3297 } 3298 if (!Subtarget->isLittle()) 3299 std::swap (ArgValue, ArgValue2); 3300 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3301 } 3302 3303 // The remaining GPRs hold either the beginning of variable-argument 3304 // data, or the beginning of an aggregate passed by value (usually 3305 // byval). Either way, we allocate stack slots adjacent to the data 3306 // provided by our caller, and store the unallocated registers there. 3307 // If this is a variadic function, the va_list pointer will begin with 3308 // these values; otherwise, this reassembles a (byval) structure that 3309 // was split between registers and memory. 3310 // Return: The frame index registers were stored into. 3311 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3312 const SDLoc &dl, SDValue &Chain, 3313 const Value *OrigArg, 3314 unsigned InRegsParamRecordIdx, 3315 int ArgOffset, unsigned ArgSize) const { 3316 // Currently, two use-cases possible: 3317 // Case #1. Non-var-args function, and we meet first byval parameter. 3318 // Setup first unallocated register as first byval register; 3319 // eat all remained registers 3320 // (these two actions are performed by HandleByVal method). 3321 // Then, here, we initialize stack frame with 3322 // "store-reg" instructions. 3323 // Case #2. Var-args function, that doesn't contain byval parameters. 3324 // The same: eat all remained unallocated registers, 3325 // initialize stack frame. 3326 3327 MachineFunction &MF = DAG.getMachineFunction(); 3328 MachineFrameInfo &MFI = MF.getFrameInfo(); 3329 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3330 unsigned RBegin, REnd; 3331 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3332 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3333 } else { 3334 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3335 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3336 REnd = ARM::R4; 3337 } 3338 3339 if (REnd != RBegin) 3340 ArgOffset = -4 * (ARM::R4 - RBegin); 3341 3342 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3343 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3344 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3345 3346 SmallVector<SDValue, 4> MemOps; 3347 const TargetRegisterClass *RC = 3348 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3349 3350 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3351 unsigned VReg = MF.addLiveIn(Reg, RC); 3352 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3353 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3354 MachinePointerInfo(OrigArg, 4 * i)); 3355 MemOps.push_back(Store); 3356 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3357 } 3358 3359 if (!MemOps.empty()) 3360 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3361 return FrameIndex; 3362 } 3363 3364 // Setup stack frame, the va_list pointer will start from. 3365 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3366 const SDLoc &dl, SDValue &Chain, 3367 unsigned ArgOffset, 3368 unsigned TotalArgRegsSaveSize, 3369 bool ForceMutable) const { 3370 MachineFunction &MF = DAG.getMachineFunction(); 3371 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3372 3373 // Try to store any remaining integer argument regs 3374 // to their spots on the stack so that they may be loaded by dereferencing 3375 // the result of va_next. 3376 // If there is no regs to be stored, just point address after last 3377 // argument passed via stack. 3378 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3379 CCInfo.getInRegsParamsCount(), 3380 CCInfo.getNextStackOffset(), 4); 3381 AFI->setVarArgsFrameIndex(FrameIndex); 3382 } 3383 3384 SDValue ARMTargetLowering::LowerFormalArguments( 3385 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3386 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3387 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3388 MachineFunction &MF = DAG.getMachineFunction(); 3389 MachineFrameInfo &MFI = MF.getFrameInfo(); 3390 3391 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3392 3393 // Assign locations to all of the incoming arguments. 3394 SmallVector<CCValAssign, 16> ArgLocs; 3395 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3396 *DAG.getContext(), Prologue); 3397 CCInfo.AnalyzeFormalArguments(Ins, 3398 CCAssignFnForNode(CallConv, /* Return*/ false, 3399 isVarArg)); 3400 3401 SmallVector<SDValue, 16> ArgValues; 3402 SDValue ArgValue; 3403 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3404 unsigned CurArgIdx = 0; 3405 3406 // Initially ArgRegsSaveSize is zero. 3407 // Then we increase this value each time we meet byval parameter. 3408 // We also increase this value in case of varargs function. 3409 AFI->setArgRegsSaveSize(0); 3410 3411 // Calculate the amount of stack space that we need to allocate to store 3412 // byval and variadic arguments that are passed in registers. 3413 // We need to know this before we allocate the first byval or variadic 3414 // argument, as they will be allocated a stack slot below the CFA (Canonical 3415 // Frame Address, the stack pointer at entry to the function). 3416 unsigned ArgRegBegin = ARM::R4; 3417 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3418 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3419 break; 3420 3421 CCValAssign &VA = ArgLocs[i]; 3422 unsigned Index = VA.getValNo(); 3423 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3424 if (!Flags.isByVal()) 3425 continue; 3426 3427 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3428 unsigned RBegin, REnd; 3429 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3430 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3431 3432 CCInfo.nextInRegsParam(); 3433 } 3434 CCInfo.rewindByValRegsInfo(); 3435 3436 int lastInsIndex = -1; 3437 if (isVarArg && MFI.hasVAStart()) { 3438 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3439 if (RegIdx != array_lengthof(GPRArgRegs)) 3440 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3441 } 3442 3443 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3444 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3445 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3446 3447 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3448 CCValAssign &VA = ArgLocs[i]; 3449 if (Ins[VA.getValNo()].isOrigArg()) { 3450 std::advance(CurOrigArg, 3451 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3452 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3453 } 3454 // Arguments stored in registers. 3455 if (VA.isRegLoc()) { 3456 EVT RegVT = VA.getLocVT(); 3457 3458 if (VA.needsCustom()) { 3459 // f64 and vector types are split up into multiple registers or 3460 // combinations of registers and stack slots. 3461 if (VA.getLocVT() == MVT::v2f64) { 3462 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3463 Chain, DAG, dl); 3464 VA = ArgLocs[++i]; // skip ahead to next loc 3465 SDValue ArgValue2; 3466 if (VA.isMemLoc()) { 3467 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3468 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3469 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3470 MachinePointerInfo::getFixedStack( 3471 DAG.getMachineFunction(), FI)); 3472 } else { 3473 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3474 Chain, DAG, dl); 3475 } 3476 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3477 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3478 ArgValue, ArgValue1, 3479 DAG.getIntPtrConstant(0, dl)); 3480 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3481 ArgValue, ArgValue2, 3482 DAG.getIntPtrConstant(1, dl)); 3483 } else 3484 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3485 3486 } else { 3487 const TargetRegisterClass *RC; 3488 3489 if (RegVT == MVT::f32) 3490 RC = &ARM::SPRRegClass; 3491 else if (RegVT == MVT::f64) 3492 RC = &ARM::DPRRegClass; 3493 else if (RegVT == MVT::v2f64) 3494 RC = &ARM::QPRRegClass; 3495 else if (RegVT == MVT::i32) 3496 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3497 : &ARM::GPRRegClass; 3498 else 3499 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3500 3501 // Transform the arguments in physical registers into virtual ones. 3502 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3503 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3504 } 3505 3506 // If this is an 8 or 16-bit value, it is really passed promoted 3507 // to 32 bits. Insert an assert[sz]ext to capture this, then 3508 // truncate to the right size. 3509 switch (VA.getLocInfo()) { 3510 default: llvm_unreachable("Unknown loc info!"); 3511 case CCValAssign::Full: break; 3512 case CCValAssign::BCvt: 3513 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3514 break; 3515 case CCValAssign::SExt: 3516 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3517 DAG.getValueType(VA.getValVT())); 3518 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3519 break; 3520 case CCValAssign::ZExt: 3521 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3522 DAG.getValueType(VA.getValVT())); 3523 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3524 break; 3525 } 3526 3527 InVals.push_back(ArgValue); 3528 3529 } else { // VA.isRegLoc() 3530 3531 // sanity check 3532 assert(VA.isMemLoc()); 3533 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3534 3535 int index = VA.getValNo(); 3536 3537 // Some Ins[] entries become multiple ArgLoc[] entries. 3538 // Process them only once. 3539 if (index != lastInsIndex) 3540 { 3541 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3542 // FIXME: For now, all byval parameter objects are marked mutable. 3543 // This can be changed with more analysis. 3544 // In case of tail call optimization mark all arguments mutable. 3545 // Since they could be overwritten by lowering of arguments in case of 3546 // a tail call. 3547 if (Flags.isByVal()) { 3548 assert(Ins[index].isOrigArg() && 3549 "Byval arguments cannot be implicit"); 3550 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3551 3552 int FrameIndex = StoreByValRegs( 3553 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3554 VA.getLocMemOffset(), Flags.getByValSize()); 3555 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3556 CCInfo.nextInRegsParam(); 3557 } else { 3558 unsigned FIOffset = VA.getLocMemOffset(); 3559 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3560 FIOffset, true); 3561 3562 // Create load nodes to retrieve arguments from the stack. 3563 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3564 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3565 MachinePointerInfo::getFixedStack( 3566 DAG.getMachineFunction(), FI))); 3567 } 3568 lastInsIndex = index; 3569 } 3570 } 3571 } 3572 3573 // varargs 3574 if (isVarArg && MFI.hasVAStart()) 3575 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3576 CCInfo.getNextStackOffset(), 3577 TotalArgRegsSaveSize); 3578 3579 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3580 3581 return Chain; 3582 } 3583 3584 /// isFloatingPointZero - Return true if this is +0.0. 3585 static bool isFloatingPointZero(SDValue Op) { 3586 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3587 return CFP->getValueAPF().isPosZero(); 3588 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3589 // Maybe this has already been legalized into the constant pool? 3590 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3591 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3592 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3593 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3594 return CFP->getValueAPF().isPosZero(); 3595 } 3596 } else if (Op->getOpcode() == ISD::BITCAST && 3597 Op->getValueType(0) == MVT::f64) { 3598 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3599 // created by LowerConstantFP(). 3600 SDValue BitcastOp = Op->getOperand(0); 3601 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3602 isNullConstant(BitcastOp->getOperand(0))) 3603 return true; 3604 } 3605 return false; 3606 } 3607 3608 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3609 /// the given operands. 3610 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3611 SDValue &ARMcc, SelectionDAG &DAG, 3612 const SDLoc &dl) const { 3613 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3614 unsigned C = RHSC->getZExtValue(); 3615 if (!isLegalICmpImmediate(C)) { 3616 // Constant does not fit, try adjusting it by one? 3617 switch (CC) { 3618 default: break; 3619 case ISD::SETLT: 3620 case ISD::SETGE: 3621 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3622 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3623 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3624 } 3625 break; 3626 case ISD::SETULT: 3627 case ISD::SETUGE: 3628 if (C != 0 && isLegalICmpImmediate(C-1)) { 3629 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3630 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3631 } 3632 break; 3633 case ISD::SETLE: 3634 case ISD::SETGT: 3635 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3636 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3637 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3638 } 3639 break; 3640 case ISD::SETULE: 3641 case ISD::SETUGT: 3642 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3643 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3644 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3645 } 3646 break; 3647 } 3648 } 3649 } 3650 3651 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3652 ARMISD::NodeType CompareType; 3653 switch (CondCode) { 3654 default: 3655 CompareType = ARMISD::CMP; 3656 break; 3657 case ARMCC::EQ: 3658 case ARMCC::NE: 3659 // Uses only Z Flag 3660 CompareType = ARMISD::CMPZ; 3661 break; 3662 } 3663 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3664 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3665 } 3666 3667 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3668 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3669 SelectionDAG &DAG, const SDLoc &dl) const { 3670 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3671 SDValue Cmp; 3672 if (!isFloatingPointZero(RHS)) 3673 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3674 else 3675 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3676 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3677 } 3678 3679 /// duplicateCmp - Glue values can have only one use, so this function 3680 /// duplicates a comparison node. 3681 SDValue 3682 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3683 unsigned Opc = Cmp.getOpcode(); 3684 SDLoc DL(Cmp); 3685 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3686 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3687 3688 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3689 Cmp = Cmp.getOperand(0); 3690 Opc = Cmp.getOpcode(); 3691 if (Opc == ARMISD::CMPFP) 3692 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3693 else { 3694 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3695 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3696 } 3697 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3698 } 3699 3700 std::pair<SDValue, SDValue> 3701 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3702 SDValue &ARMcc) const { 3703 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3704 3705 SDValue Value, OverflowCmp; 3706 SDValue LHS = Op.getOperand(0); 3707 SDValue RHS = Op.getOperand(1); 3708 SDLoc dl(Op); 3709 3710 // FIXME: We are currently always generating CMPs because we don't support 3711 // generating CMN through the backend. This is not as good as the natural 3712 // CMP case because it causes a register dependency and cannot be folded 3713 // later. 3714 3715 switch (Op.getOpcode()) { 3716 default: 3717 llvm_unreachable("Unknown overflow instruction!"); 3718 case ISD::SADDO: 3719 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3720 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3721 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3722 break; 3723 case ISD::UADDO: 3724 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3725 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3726 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3727 break; 3728 case ISD::SSUBO: 3729 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3730 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3731 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3732 break; 3733 case ISD::USUBO: 3734 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3735 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3736 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3737 break; 3738 } // switch (...) 3739 3740 return std::make_pair(Value, OverflowCmp); 3741 } 3742 3743 3744 SDValue 3745 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3746 // Let legalize expand this if it isn't a legal type yet. 3747 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3748 return SDValue(); 3749 3750 SDValue Value, OverflowCmp; 3751 SDValue ARMcc; 3752 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3753 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3754 SDLoc dl(Op); 3755 // We use 0 and 1 as false and true values. 3756 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3757 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3758 EVT VT = Op.getValueType(); 3759 3760 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3761 ARMcc, CCR, OverflowCmp); 3762 3763 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3764 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3765 } 3766 3767 3768 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3769 SDValue Cond = Op.getOperand(0); 3770 SDValue SelectTrue = Op.getOperand(1); 3771 SDValue SelectFalse = Op.getOperand(2); 3772 SDLoc dl(Op); 3773 unsigned Opc = Cond.getOpcode(); 3774 3775 if (Cond.getResNo() == 1 && 3776 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3777 Opc == ISD::USUBO)) { 3778 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3779 return SDValue(); 3780 3781 SDValue Value, OverflowCmp; 3782 SDValue ARMcc; 3783 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3784 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3785 EVT VT = Op.getValueType(); 3786 3787 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3788 OverflowCmp, DAG); 3789 } 3790 3791 // Convert: 3792 // 3793 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3794 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3795 // 3796 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3797 const ConstantSDNode *CMOVTrue = 3798 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3799 const ConstantSDNode *CMOVFalse = 3800 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3801 3802 if (CMOVTrue && CMOVFalse) { 3803 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3804 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3805 3806 SDValue True; 3807 SDValue False; 3808 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3809 True = SelectTrue; 3810 False = SelectFalse; 3811 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3812 True = SelectFalse; 3813 False = SelectTrue; 3814 } 3815 3816 if (True.getNode() && False.getNode()) { 3817 EVT VT = Op.getValueType(); 3818 SDValue ARMcc = Cond.getOperand(2); 3819 SDValue CCR = Cond.getOperand(3); 3820 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3821 assert(True.getValueType() == VT); 3822 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3823 } 3824 } 3825 } 3826 3827 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3828 // undefined bits before doing a full-word comparison with zero. 3829 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3830 DAG.getConstant(1, dl, Cond.getValueType())); 3831 3832 return DAG.getSelectCC(dl, Cond, 3833 DAG.getConstant(0, dl, Cond.getValueType()), 3834 SelectTrue, SelectFalse, ISD::SETNE); 3835 } 3836 3837 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3838 bool &swpCmpOps, bool &swpVselOps) { 3839 // Start by selecting the GE condition code for opcodes that return true for 3840 // 'equality' 3841 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3842 CC == ISD::SETULE) 3843 CondCode = ARMCC::GE; 3844 3845 // and GT for opcodes that return false for 'equality'. 3846 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3847 CC == ISD::SETULT) 3848 CondCode = ARMCC::GT; 3849 3850 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3851 // to swap the compare operands. 3852 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3853 CC == ISD::SETULT) 3854 swpCmpOps = true; 3855 3856 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3857 // If we have an unordered opcode, we need to swap the operands to the VSEL 3858 // instruction (effectively negating the condition). 3859 // 3860 // This also has the effect of swapping which one of 'less' or 'greater' 3861 // returns true, so we also swap the compare operands. It also switches 3862 // whether we return true for 'equality', so we compensate by picking the 3863 // opposite condition code to our original choice. 3864 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3865 CC == ISD::SETUGT) { 3866 swpCmpOps = !swpCmpOps; 3867 swpVselOps = !swpVselOps; 3868 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3869 } 3870 3871 // 'ordered' is 'anything but unordered', so use the VS condition code and 3872 // swap the VSEL operands. 3873 if (CC == ISD::SETO) { 3874 CondCode = ARMCC::VS; 3875 swpVselOps = true; 3876 } 3877 3878 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3879 // code and swap the VSEL operands. 3880 if (CC == ISD::SETUNE) { 3881 CondCode = ARMCC::EQ; 3882 swpVselOps = true; 3883 } 3884 } 3885 3886 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 3887 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3888 SDValue Cmp, SelectionDAG &DAG) const { 3889 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3890 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3891 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3892 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3893 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3894 3895 SDValue TrueLow = TrueVal.getValue(0); 3896 SDValue TrueHigh = TrueVal.getValue(1); 3897 SDValue FalseLow = FalseVal.getValue(0); 3898 SDValue FalseHigh = FalseVal.getValue(1); 3899 3900 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3901 ARMcc, CCR, Cmp); 3902 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3903 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3904 3905 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3906 } else { 3907 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3908 Cmp); 3909 } 3910 } 3911 3912 static bool isGTorGE(ISD::CondCode CC) { 3913 return CC == ISD::SETGT || CC == ISD::SETGE; 3914 } 3915 3916 static bool isLTorLE(ISD::CondCode CC) { 3917 return CC == ISD::SETLT || CC == ISD::SETLE; 3918 } 3919 3920 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 3921 // All of these conditions (and their <= and >= counterparts) will do: 3922 // x < k ? k : x 3923 // x > k ? x : k 3924 // k < x ? x : k 3925 // k > x ? k : x 3926 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 3927 const SDValue TrueVal, const SDValue FalseVal, 3928 const ISD::CondCode CC, const SDValue K) { 3929 return (isGTorGE(CC) && 3930 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 3931 (isLTorLE(CC) && 3932 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 3933 } 3934 3935 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 3936 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 3937 const SDValue TrueVal, const SDValue FalseVal, 3938 const ISD::CondCode CC, const SDValue K) { 3939 return (isGTorGE(CC) && 3940 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 3941 (isLTorLE(CC) && 3942 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 3943 } 3944 3945 // Check if two chained conditionals could be converted into SSAT. 3946 // 3947 // SSAT can replace a set of two conditional selectors that bound a number to an 3948 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 3949 // 3950 // x < -k ? -k : (x > k ? k : x) 3951 // x < -k ? -k : (x < k ? x : k) 3952 // x > -k ? (x > k ? k : x) : -k 3953 // x < k ? (x < -k ? -k : x) : k 3954 // etc. 3955 // 3956 // It returns true if the conversion can be done, false otherwise. 3957 // Additionally, the variable is returned in parameter V and the constant in K. 3958 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 3959 uint64_t &K) { 3960 3961 SDValue LHS1 = Op.getOperand(0); 3962 SDValue RHS1 = Op.getOperand(1); 3963 SDValue TrueVal1 = Op.getOperand(2); 3964 SDValue FalseVal1 = Op.getOperand(3); 3965 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3966 3967 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 3968 if (Op2.getOpcode() != ISD::SELECT_CC) 3969 return false; 3970 3971 SDValue LHS2 = Op2.getOperand(0); 3972 SDValue RHS2 = Op2.getOperand(1); 3973 SDValue TrueVal2 = Op2.getOperand(2); 3974 SDValue FalseVal2 = Op2.getOperand(3); 3975 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 3976 3977 // Find out which are the constants and which are the variables 3978 // in each conditional 3979 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 3980 ? &RHS1 3981 : NULL; 3982 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 3983 ? &RHS2 3984 : NULL; 3985 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 3986 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 3987 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 3988 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 3989 3990 // We must detect cases where the original operations worked with 16- or 3991 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 3992 // must work with sign-extended values but the select operations return 3993 // the original non-extended value. 3994 SDValue V2TmpReg = V2Tmp; 3995 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 3996 V2TmpReg = V2Tmp->getOperand(0); 3997 3998 // Check that the registers and the constants have the correct values 3999 // in both conditionals 4000 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4001 V2TmpReg != V2) 4002 return false; 4003 4004 // Figure out which conditional is saturating the lower/upper bound. 4005 const SDValue *LowerCheckOp = 4006 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4007 ? &Op 4008 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2 4009 : NULL; 4010 const SDValue *UpperCheckOp = 4011 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4012 ? &Op 4013 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2 4014 : NULL; 4015 4016 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4017 return false; 4018 4019 // Check that the constant in the lower-bound check is 4020 // the opposite of the constant in the upper-bound check 4021 // in 1's complement. 4022 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4023 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4024 int64_t PosVal = std::max(Val1, Val2); 4025 4026 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4027 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4028 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 4029 4030 V = V2; 4031 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4032 return true; 4033 } 4034 4035 return false; 4036 } 4037 4038 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4039 4040 EVT VT = Op.getValueType(); 4041 SDLoc dl(Op); 4042 4043 // Try to convert two saturating conditional selects into a single SSAT 4044 SDValue SatValue; 4045 uint64_t SatConstant; 4046 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4047 isSaturatingConditional(Op, SatValue, SatConstant)) 4048 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4049 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4050 4051 SDValue LHS = Op.getOperand(0); 4052 SDValue RHS = Op.getOperand(1); 4053 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4054 SDValue TrueVal = Op.getOperand(2); 4055 SDValue FalseVal = Op.getOperand(3); 4056 4057 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4058 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4059 dl); 4060 4061 // If softenSetCCOperands only returned one value, we should compare it to 4062 // zero. 4063 if (!RHS.getNode()) { 4064 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4065 CC = ISD::SETNE; 4066 } 4067 } 4068 4069 if (LHS.getValueType() == MVT::i32) { 4070 // Try to generate VSEL on ARMv8. 4071 // The VSEL instruction can't use all the usual ARM condition 4072 // codes: it only has two bits to select the condition code, so it's 4073 // constrained to use only GE, GT, VS and EQ. 4074 // 4075 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4076 // swap the operands of the previous compare instruction (effectively 4077 // inverting the compare condition, swapping 'less' and 'greater') and 4078 // sometimes need to swap the operands to the VSEL (which inverts the 4079 // condition in the sense of firing whenever the previous condition didn't) 4080 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4081 TrueVal.getValueType() == MVT::f64)) { 4082 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4083 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4084 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4085 CC = ISD::getSetCCInverse(CC, true); 4086 std::swap(TrueVal, FalseVal); 4087 } 4088 } 4089 4090 SDValue ARMcc; 4091 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4092 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4093 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4094 } 4095 4096 ARMCC::CondCodes CondCode, CondCode2; 4097 FPCCToARMCC(CC, CondCode, CondCode2); 4098 4099 // Try to generate VMAXNM/VMINNM on ARMv8. 4100 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4101 TrueVal.getValueType() == MVT::f64)) { 4102 bool swpCmpOps = false; 4103 bool swpVselOps = false; 4104 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4105 4106 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4107 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4108 if (swpCmpOps) 4109 std::swap(LHS, RHS); 4110 if (swpVselOps) 4111 std::swap(TrueVal, FalseVal); 4112 } 4113 } 4114 4115 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4116 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 4117 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4118 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4119 if (CondCode2 != ARMCC::AL) { 4120 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4121 // FIXME: Needs another CMP because flag can have but one use. 4122 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 4123 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4124 } 4125 return Result; 4126 } 4127 4128 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4129 /// to morph to an integer compare sequence. 4130 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4131 const ARMSubtarget *Subtarget) { 4132 SDNode *N = Op.getNode(); 4133 if (!N->hasOneUse()) 4134 // Otherwise it requires moving the value from fp to integer registers. 4135 return false; 4136 if (!N->getNumValues()) 4137 return false; 4138 EVT VT = Op.getValueType(); 4139 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4140 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4141 // vmrs are very slow, e.g. cortex-a8. 4142 return false; 4143 4144 if (isFloatingPointZero(Op)) { 4145 SeenZero = true; 4146 return true; 4147 } 4148 return ISD::isNormalLoad(N); 4149 } 4150 4151 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4152 if (isFloatingPointZero(Op)) 4153 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4154 4155 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4156 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4157 Ld->getPointerInfo(), Ld->getAlignment(), 4158 Ld->getMemOperand()->getFlags()); 4159 4160 llvm_unreachable("Unknown VFP cmp argument!"); 4161 } 4162 4163 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4164 SDValue &RetVal1, SDValue &RetVal2) { 4165 SDLoc dl(Op); 4166 4167 if (isFloatingPointZero(Op)) { 4168 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4169 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4170 return; 4171 } 4172 4173 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4174 SDValue Ptr = Ld->getBasePtr(); 4175 RetVal1 = 4176 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4177 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4178 4179 EVT PtrType = Ptr.getValueType(); 4180 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4181 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4182 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4183 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4184 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4185 Ld->getMemOperand()->getFlags()); 4186 return; 4187 } 4188 4189 llvm_unreachable("Unknown VFP cmp argument!"); 4190 } 4191 4192 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4193 /// f32 and even f64 comparisons to integer ones. 4194 SDValue 4195 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4196 SDValue Chain = Op.getOperand(0); 4197 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4198 SDValue LHS = Op.getOperand(2); 4199 SDValue RHS = Op.getOperand(3); 4200 SDValue Dest = Op.getOperand(4); 4201 SDLoc dl(Op); 4202 4203 bool LHSSeenZero = false; 4204 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4205 bool RHSSeenZero = false; 4206 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4207 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4208 // If unsafe fp math optimization is enabled and there are no other uses of 4209 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4210 // to an integer comparison. 4211 if (CC == ISD::SETOEQ) 4212 CC = ISD::SETEQ; 4213 else if (CC == ISD::SETUNE) 4214 CC = ISD::SETNE; 4215 4216 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4217 SDValue ARMcc; 4218 if (LHS.getValueType() == MVT::f32) { 4219 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4220 bitcastf32Toi32(LHS, DAG), Mask); 4221 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4222 bitcastf32Toi32(RHS, DAG), Mask); 4223 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4224 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4225 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4226 Chain, Dest, ARMcc, CCR, Cmp); 4227 } 4228 4229 SDValue LHS1, LHS2; 4230 SDValue RHS1, RHS2; 4231 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4232 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4233 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4234 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4235 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4236 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4237 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4238 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4239 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4240 } 4241 4242 return SDValue(); 4243 } 4244 4245 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4246 SDValue Chain = Op.getOperand(0); 4247 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4248 SDValue LHS = Op.getOperand(2); 4249 SDValue RHS = Op.getOperand(3); 4250 SDValue Dest = Op.getOperand(4); 4251 SDLoc dl(Op); 4252 4253 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4254 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4255 dl); 4256 4257 // If softenSetCCOperands only returned one value, we should compare it to 4258 // zero. 4259 if (!RHS.getNode()) { 4260 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4261 CC = ISD::SETNE; 4262 } 4263 } 4264 4265 if (LHS.getValueType() == MVT::i32) { 4266 SDValue ARMcc; 4267 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4268 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4269 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4270 Chain, Dest, ARMcc, CCR, Cmp); 4271 } 4272 4273 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4274 4275 if (getTargetMachine().Options.UnsafeFPMath && 4276 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4277 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4278 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4279 return Result; 4280 } 4281 4282 ARMCC::CondCodes CondCode, CondCode2; 4283 FPCCToARMCC(CC, CondCode, CondCode2); 4284 4285 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4286 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 4287 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4288 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4289 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4290 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4291 if (CondCode2 != ARMCC::AL) { 4292 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4293 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4294 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4295 } 4296 return Res; 4297 } 4298 4299 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4300 SDValue Chain = Op.getOperand(0); 4301 SDValue Table = Op.getOperand(1); 4302 SDValue Index = Op.getOperand(2); 4303 SDLoc dl(Op); 4304 4305 EVT PTy = getPointerTy(DAG.getDataLayout()); 4306 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4307 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4308 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4309 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4310 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4311 if (Subtarget->isThumb2()) { 4312 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 4313 // which does another jump to the destination. This also makes it easier 4314 // to translate it to TBB / TBH later. 4315 // FIXME: This might not work if the function is extremely large. 4316 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4317 Addr, Op.getOperand(2), JTI); 4318 } 4319 if (isPositionIndependent() || Subtarget->isROPI()) { 4320 Addr = 4321 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4322 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4323 Chain = Addr.getValue(1); 4324 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4325 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4326 } else { 4327 Addr = 4328 DAG.getLoad(PTy, dl, Chain, Addr, 4329 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4330 Chain = Addr.getValue(1); 4331 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4332 } 4333 } 4334 4335 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4336 EVT VT = Op.getValueType(); 4337 SDLoc dl(Op); 4338 4339 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4340 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4341 return Op; 4342 return DAG.UnrollVectorOp(Op.getNode()); 4343 } 4344 4345 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4346 "Invalid type for custom lowering!"); 4347 if (VT != MVT::v4i16) 4348 return DAG.UnrollVectorOp(Op.getNode()); 4349 4350 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4351 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4352 } 4353 4354 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4355 EVT VT = Op.getValueType(); 4356 if (VT.isVector()) 4357 return LowerVectorFP_TO_INT(Op, DAG); 4358 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4359 RTLIB::Libcall LC; 4360 if (Op.getOpcode() == ISD::FP_TO_SINT) 4361 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4362 Op.getValueType()); 4363 else 4364 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4365 Op.getValueType()); 4366 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4367 /*isSigned*/ false, SDLoc(Op)).first; 4368 } 4369 4370 return Op; 4371 } 4372 4373 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4374 EVT VT = Op.getValueType(); 4375 SDLoc dl(Op); 4376 4377 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4378 if (VT.getVectorElementType() == MVT::f32) 4379 return Op; 4380 return DAG.UnrollVectorOp(Op.getNode()); 4381 } 4382 4383 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4384 "Invalid type for custom lowering!"); 4385 if (VT != MVT::v4f32) 4386 return DAG.UnrollVectorOp(Op.getNode()); 4387 4388 unsigned CastOpc; 4389 unsigned Opc; 4390 switch (Op.getOpcode()) { 4391 default: llvm_unreachable("Invalid opcode!"); 4392 case ISD::SINT_TO_FP: 4393 CastOpc = ISD::SIGN_EXTEND; 4394 Opc = ISD::SINT_TO_FP; 4395 break; 4396 case ISD::UINT_TO_FP: 4397 CastOpc = ISD::ZERO_EXTEND; 4398 Opc = ISD::UINT_TO_FP; 4399 break; 4400 } 4401 4402 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4403 return DAG.getNode(Opc, dl, VT, Op); 4404 } 4405 4406 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4407 EVT VT = Op.getValueType(); 4408 if (VT.isVector()) 4409 return LowerVectorINT_TO_FP(Op, DAG); 4410 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4411 RTLIB::Libcall LC; 4412 if (Op.getOpcode() == ISD::SINT_TO_FP) 4413 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4414 Op.getValueType()); 4415 else 4416 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4417 Op.getValueType()); 4418 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4419 /*isSigned*/ false, SDLoc(Op)).first; 4420 } 4421 4422 return Op; 4423 } 4424 4425 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4426 // Implement fcopysign with a fabs and a conditional fneg. 4427 SDValue Tmp0 = Op.getOperand(0); 4428 SDValue Tmp1 = Op.getOperand(1); 4429 SDLoc dl(Op); 4430 EVT VT = Op.getValueType(); 4431 EVT SrcVT = Tmp1.getValueType(); 4432 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4433 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4434 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4435 4436 if (UseNEON) { 4437 // Use VBSL to copy the sign bit. 4438 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4439 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4440 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4441 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4442 if (VT == MVT::f64) 4443 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4444 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4445 DAG.getConstant(32, dl, MVT::i32)); 4446 else /*if (VT == MVT::f32)*/ 4447 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4448 if (SrcVT == MVT::f32) { 4449 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4450 if (VT == MVT::f64) 4451 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4452 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4453 DAG.getConstant(32, dl, MVT::i32)); 4454 } else if (VT == MVT::f32) 4455 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4456 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4457 DAG.getConstant(32, dl, MVT::i32)); 4458 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4459 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4460 4461 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4462 dl, MVT::i32); 4463 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4464 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4465 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4466 4467 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4468 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4469 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4470 if (VT == MVT::f32) { 4471 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4472 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4473 DAG.getConstant(0, dl, MVT::i32)); 4474 } else { 4475 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4476 } 4477 4478 return Res; 4479 } 4480 4481 // Bitcast operand 1 to i32. 4482 if (SrcVT == MVT::f64) 4483 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4484 Tmp1).getValue(1); 4485 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4486 4487 // Or in the signbit with integer operations. 4488 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4489 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4490 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4491 if (VT == MVT::f32) { 4492 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4493 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4494 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4495 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4496 } 4497 4498 // f64: Or the high part with signbit and then combine two parts. 4499 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4500 Tmp0); 4501 SDValue Lo = Tmp0.getValue(0); 4502 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4503 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4504 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4505 } 4506 4507 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4508 MachineFunction &MF = DAG.getMachineFunction(); 4509 MachineFrameInfo &MFI = MF.getFrameInfo(); 4510 MFI.setReturnAddressIsTaken(true); 4511 4512 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4513 return SDValue(); 4514 4515 EVT VT = Op.getValueType(); 4516 SDLoc dl(Op); 4517 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4518 if (Depth) { 4519 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4520 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4521 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4522 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4523 MachinePointerInfo()); 4524 } 4525 4526 // Return LR, which contains the return address. Mark it an implicit live-in. 4527 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4528 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4529 } 4530 4531 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4532 const ARMBaseRegisterInfo &ARI = 4533 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4534 MachineFunction &MF = DAG.getMachineFunction(); 4535 MachineFrameInfo &MFI = MF.getFrameInfo(); 4536 MFI.setFrameAddressIsTaken(true); 4537 4538 EVT VT = Op.getValueType(); 4539 SDLoc dl(Op); // FIXME probably not meaningful 4540 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4541 unsigned FrameReg = ARI.getFrameRegister(MF); 4542 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4543 while (Depth--) 4544 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4545 MachinePointerInfo()); 4546 return FrameAddr; 4547 } 4548 4549 // FIXME? Maybe this could be a TableGen attribute on some registers and 4550 // this table could be generated automatically from RegInfo. 4551 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4552 SelectionDAG &DAG) const { 4553 unsigned Reg = StringSwitch<unsigned>(RegName) 4554 .Case("sp", ARM::SP) 4555 .Default(0); 4556 if (Reg) 4557 return Reg; 4558 report_fatal_error(Twine("Invalid register name \"" 4559 + StringRef(RegName) + "\".")); 4560 } 4561 4562 // Result is 64 bit value so split into two 32 bit values and return as a 4563 // pair of values. 4564 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4565 SelectionDAG &DAG) { 4566 SDLoc DL(N); 4567 4568 // This function is only supposed to be called for i64 type destination. 4569 assert(N->getValueType(0) == MVT::i64 4570 && "ExpandREAD_REGISTER called for non-i64 type result."); 4571 4572 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4573 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4574 N->getOperand(0), 4575 N->getOperand(1)); 4576 4577 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4578 Read.getValue(1))); 4579 Results.push_back(Read.getOperand(0)); 4580 } 4581 4582 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4583 /// When \p DstVT, the destination type of \p BC, is on the vector 4584 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4585 /// it might be possible to combine them, such that everything stays on the 4586 /// vector register bank. 4587 /// \p return The node that would replace \p BT, if the combine 4588 /// is possible. 4589 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4590 SelectionDAG &DAG) { 4591 SDValue Op = BC->getOperand(0); 4592 EVT DstVT = BC->getValueType(0); 4593 4594 // The only vector instruction that can produce a scalar (remember, 4595 // since the bitcast was about to be turned into VMOVDRR, the source 4596 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4597 // Moreover, we can do this combine only if there is one use. 4598 // Finally, if the destination type is not a vector, there is not 4599 // much point on forcing everything on the vector bank. 4600 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4601 !Op.hasOneUse()) 4602 return SDValue(); 4603 4604 // If the index is not constant, we will introduce an additional 4605 // multiply that will stick. 4606 // Give up in that case. 4607 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4608 if (!Index) 4609 return SDValue(); 4610 unsigned DstNumElt = DstVT.getVectorNumElements(); 4611 4612 // Compute the new index. 4613 const APInt &APIntIndex = Index->getAPIntValue(); 4614 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4615 NewIndex *= APIntIndex; 4616 // Check if the new constant index fits into i32. 4617 if (NewIndex.getBitWidth() > 32) 4618 return SDValue(); 4619 4620 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4621 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4622 SDLoc dl(Op); 4623 SDValue ExtractSrc = Op.getOperand(0); 4624 EVT VecVT = EVT::getVectorVT( 4625 *DAG.getContext(), DstVT.getScalarType(), 4626 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4627 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4628 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4629 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4630 } 4631 4632 /// ExpandBITCAST - If the target supports VFP, this function is called to 4633 /// expand a bit convert where either the source or destination type is i64 to 4634 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4635 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4636 /// vectors), since the legalizer won't know what to do with that. 4637 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4638 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4639 SDLoc dl(N); 4640 SDValue Op = N->getOperand(0); 4641 4642 // This function is only supposed to be called for i64 types, either as the 4643 // source or destination of the bit convert. 4644 EVT SrcVT = Op.getValueType(); 4645 EVT DstVT = N->getValueType(0); 4646 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4647 "ExpandBITCAST called for non-i64 type"); 4648 4649 // Turn i64->f64 into VMOVDRR. 4650 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4651 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4652 // if we can combine the bitcast with its source. 4653 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4654 return Val; 4655 4656 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4657 DAG.getConstant(0, dl, MVT::i32)); 4658 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4659 DAG.getConstant(1, dl, MVT::i32)); 4660 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4661 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4662 } 4663 4664 // Turn f64->i64 into VMOVRRD. 4665 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4666 SDValue Cvt; 4667 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4668 SrcVT.getVectorNumElements() > 1) 4669 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4670 DAG.getVTList(MVT::i32, MVT::i32), 4671 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4672 else 4673 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4674 DAG.getVTList(MVT::i32, MVT::i32), Op); 4675 // Merge the pieces into a single i64 value. 4676 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4677 } 4678 4679 return SDValue(); 4680 } 4681 4682 /// getZeroVector - Returns a vector of specified type with all zero elements. 4683 /// Zero vectors are used to represent vector negation and in those cases 4684 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4685 /// not support i64 elements, so sometimes the zero vectors will need to be 4686 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4687 /// zero vector. 4688 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4689 assert(VT.isVector() && "Expected a vector type"); 4690 // The canonical modified immediate encoding of a zero vector is....0! 4691 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4692 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4693 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4694 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4695 } 4696 4697 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4698 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4699 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4700 SelectionDAG &DAG) const { 4701 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4702 EVT VT = Op.getValueType(); 4703 unsigned VTBits = VT.getSizeInBits(); 4704 SDLoc dl(Op); 4705 SDValue ShOpLo = Op.getOperand(0); 4706 SDValue ShOpHi = Op.getOperand(1); 4707 SDValue ShAmt = Op.getOperand(2); 4708 SDValue ARMcc; 4709 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4710 4711 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4712 4713 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4714 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4715 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4716 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4717 DAG.getConstant(VTBits, dl, MVT::i32)); 4718 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4719 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4720 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4721 4722 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4723 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4724 ISD::SETGE, ARMcc, DAG, dl); 4725 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4726 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4727 CCR, Cmp); 4728 4729 SDValue Ops[2] = { Lo, Hi }; 4730 return DAG.getMergeValues(Ops, dl); 4731 } 4732 4733 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4734 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4735 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4736 SelectionDAG &DAG) const { 4737 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4738 EVT VT = Op.getValueType(); 4739 unsigned VTBits = VT.getSizeInBits(); 4740 SDLoc dl(Op); 4741 SDValue ShOpLo = Op.getOperand(0); 4742 SDValue ShOpHi = Op.getOperand(1); 4743 SDValue ShAmt = Op.getOperand(2); 4744 SDValue ARMcc; 4745 4746 assert(Op.getOpcode() == ISD::SHL_PARTS); 4747 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4748 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4749 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4750 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4751 DAG.getConstant(VTBits, dl, MVT::i32)); 4752 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4753 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4754 4755 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4756 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4757 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4758 ISD::SETGE, ARMcc, DAG, dl); 4759 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4760 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4761 CCR, Cmp); 4762 4763 SDValue Ops[2] = { Lo, Hi }; 4764 return DAG.getMergeValues(Ops, dl); 4765 } 4766 4767 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4768 SelectionDAG &DAG) const { 4769 // The rounding mode is in bits 23:22 of the FPSCR. 4770 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4771 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4772 // so that the shift + and get folded into a bitfield extract. 4773 SDLoc dl(Op); 4774 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4775 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4776 MVT::i32)); 4777 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4778 DAG.getConstant(1U << 22, dl, MVT::i32)); 4779 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4780 DAG.getConstant(22, dl, MVT::i32)); 4781 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4782 DAG.getConstant(3, dl, MVT::i32)); 4783 } 4784 4785 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4786 const ARMSubtarget *ST) { 4787 SDLoc dl(N); 4788 EVT VT = N->getValueType(0); 4789 if (VT.isVector()) { 4790 assert(ST->hasNEON()); 4791 4792 // Compute the least significant set bit: LSB = X & -X 4793 SDValue X = N->getOperand(0); 4794 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4795 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4796 4797 EVT ElemTy = VT.getVectorElementType(); 4798 4799 if (ElemTy == MVT::i8) { 4800 // Compute with: cttz(x) = ctpop(lsb - 1) 4801 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4802 DAG.getTargetConstant(1, dl, ElemTy)); 4803 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4804 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4805 } 4806 4807 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4808 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4809 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4810 unsigned NumBits = ElemTy.getSizeInBits(); 4811 SDValue WidthMinus1 = 4812 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4813 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4814 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4815 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4816 } 4817 4818 // Compute with: cttz(x) = ctpop(lsb - 1) 4819 4820 // Since we can only compute the number of bits in a byte with vcnt.8, we 4821 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4822 // and i64. 4823 4824 // Compute LSB - 1. 4825 SDValue Bits; 4826 if (ElemTy == MVT::i64) { 4827 // Load constant 0xffff'ffff'ffff'ffff to register. 4828 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4829 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4830 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4831 } else { 4832 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4833 DAG.getTargetConstant(1, dl, ElemTy)); 4834 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4835 } 4836 4837 // Count #bits with vcnt.8. 4838 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4839 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4840 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4841 4842 // Gather the #bits with vpaddl (pairwise add.) 4843 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4844 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4845 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4846 Cnt8); 4847 if (ElemTy == MVT::i16) 4848 return Cnt16; 4849 4850 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4851 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4852 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4853 Cnt16); 4854 if (ElemTy == MVT::i32) 4855 return Cnt32; 4856 4857 assert(ElemTy == MVT::i64); 4858 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4859 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4860 Cnt32); 4861 return Cnt64; 4862 } 4863 4864 if (!ST->hasV6T2Ops()) 4865 return SDValue(); 4866 4867 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4868 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4869 } 4870 4871 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4872 /// for each 16-bit element from operand, repeated. The basic idea is to 4873 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4874 /// 4875 /// Trace for v4i16: 4876 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4877 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4878 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4879 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4880 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4881 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4882 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4883 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4884 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4885 EVT VT = N->getValueType(0); 4886 SDLoc DL(N); 4887 4888 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4889 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4890 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4891 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4892 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4893 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4894 } 4895 4896 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4897 /// bit-count for each 16-bit element from the operand. We need slightly 4898 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4899 /// 64/128-bit registers. 4900 /// 4901 /// Trace for v4i16: 4902 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4903 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4904 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4905 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4906 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4907 EVT VT = N->getValueType(0); 4908 SDLoc DL(N); 4909 4910 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4911 if (VT.is64BitVector()) { 4912 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4913 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4914 DAG.getIntPtrConstant(0, DL)); 4915 } else { 4916 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4917 BitCounts, DAG.getIntPtrConstant(0, DL)); 4918 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4919 } 4920 } 4921 4922 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4923 /// bit-count for each 32-bit element from the operand. The idea here is 4924 /// to split the vector into 16-bit elements, leverage the 16-bit count 4925 /// routine, and then combine the results. 4926 /// 4927 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4928 /// input = [v0 v1 ] (vi: 32-bit elements) 4929 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4930 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4931 /// vrev: N0 = [k1 k0 k3 k2 ] 4932 /// [k0 k1 k2 k3 ] 4933 /// N1 =+[k1 k0 k3 k2 ] 4934 /// [k0 k2 k1 k3 ] 4935 /// N2 =+[k1 k3 k0 k2 ] 4936 /// [k0 k2 k1 k3 ] 4937 /// Extended =+[k1 k3 k0 k2 ] 4938 /// [k0 k2 ] 4939 /// Extracted=+[k1 k3 ] 4940 /// 4941 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4942 EVT VT = N->getValueType(0); 4943 SDLoc DL(N); 4944 4945 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4946 4947 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4948 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4949 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4950 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4951 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4952 4953 if (VT.is64BitVector()) { 4954 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4955 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4956 DAG.getIntPtrConstant(0, DL)); 4957 } else { 4958 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4959 DAG.getIntPtrConstant(0, DL)); 4960 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4961 } 4962 } 4963 4964 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4965 const ARMSubtarget *ST) { 4966 EVT VT = N->getValueType(0); 4967 4968 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4969 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4970 VT == MVT::v4i16 || VT == MVT::v8i16) && 4971 "Unexpected type for custom ctpop lowering"); 4972 4973 if (VT.getVectorElementType() == MVT::i32) 4974 return lowerCTPOP32BitElements(N, DAG); 4975 else 4976 return lowerCTPOP16BitElements(N, DAG); 4977 } 4978 4979 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4980 const ARMSubtarget *ST) { 4981 EVT VT = N->getValueType(0); 4982 SDLoc dl(N); 4983 4984 if (!VT.isVector()) 4985 return SDValue(); 4986 4987 // Lower vector shifts on NEON to use VSHL. 4988 assert(ST->hasNEON() && "unexpected vector shift"); 4989 4990 // Left shifts translate directly to the vshiftu intrinsic. 4991 if (N->getOpcode() == ISD::SHL) 4992 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4993 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4994 MVT::i32), 4995 N->getOperand(0), N->getOperand(1)); 4996 4997 assert((N->getOpcode() == ISD::SRA || 4998 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4999 5000 // NEON uses the same intrinsics for both left and right shifts. For 5001 // right shifts, the shift amounts are negative, so negate the vector of 5002 // shift amounts. 5003 EVT ShiftVT = N->getOperand(1).getValueType(); 5004 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5005 getZeroVector(ShiftVT, DAG, dl), 5006 N->getOperand(1)); 5007 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5008 Intrinsic::arm_neon_vshifts : 5009 Intrinsic::arm_neon_vshiftu); 5010 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5011 DAG.getConstant(vshiftInt, dl, MVT::i32), 5012 N->getOperand(0), NegatedCount); 5013 } 5014 5015 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5016 const ARMSubtarget *ST) { 5017 EVT VT = N->getValueType(0); 5018 SDLoc dl(N); 5019 5020 // We can get here for a node like i32 = ISD::SHL i32, i64 5021 if (VT != MVT::i64) 5022 return SDValue(); 5023 5024 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5025 "Unknown shift to lower!"); 5026 5027 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5028 if (!isOneConstant(N->getOperand(1))) 5029 return SDValue(); 5030 5031 // If we are in thumb mode, we don't have RRX. 5032 if (ST->isThumb1Only()) return SDValue(); 5033 5034 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5035 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5036 DAG.getConstant(0, dl, MVT::i32)); 5037 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5038 DAG.getConstant(1, dl, MVT::i32)); 5039 5040 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5041 // captures the result into a carry flag. 5042 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5043 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5044 5045 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5046 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5047 5048 // Merge the pieces into a single i64 value. 5049 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5050 } 5051 5052 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5053 SDValue TmpOp0, TmpOp1; 5054 bool Invert = false; 5055 bool Swap = false; 5056 unsigned Opc = 0; 5057 5058 SDValue Op0 = Op.getOperand(0); 5059 SDValue Op1 = Op.getOperand(1); 5060 SDValue CC = Op.getOperand(2); 5061 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5062 EVT VT = Op.getValueType(); 5063 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5064 SDLoc dl(Op); 5065 5066 if (CmpVT.getVectorElementType() == MVT::i64) 5067 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 5068 // but it's possible that our operands are 64-bit but our result is 32-bit. 5069 // Bail in this case. 5070 return SDValue(); 5071 5072 if (Op1.getValueType().isFloatingPoint()) { 5073 switch (SetCCOpcode) { 5074 default: llvm_unreachable("Illegal FP comparison"); 5075 case ISD::SETUNE: 5076 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5077 case ISD::SETOEQ: 5078 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5079 case ISD::SETOLT: 5080 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5081 case ISD::SETOGT: 5082 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5083 case ISD::SETOLE: 5084 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5085 case ISD::SETOGE: 5086 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5087 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5088 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5089 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5090 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5091 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5092 case ISD::SETONE: 5093 // Expand this to (OLT | OGT). 5094 TmpOp0 = Op0; 5095 TmpOp1 = Op1; 5096 Opc = ISD::OR; 5097 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5098 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5099 break; 5100 case ISD::SETUO: 5101 Invert = true; 5102 LLVM_FALLTHROUGH; 5103 case ISD::SETO: 5104 // Expand this to (OLT | OGE). 5105 TmpOp0 = Op0; 5106 TmpOp1 = Op1; 5107 Opc = ISD::OR; 5108 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5109 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5110 break; 5111 } 5112 } else { 5113 // Integer comparisons. 5114 switch (SetCCOpcode) { 5115 default: llvm_unreachable("Illegal integer comparison"); 5116 case ISD::SETNE: Invert = true; 5117 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5118 case ISD::SETLT: Swap = true; 5119 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5120 case ISD::SETLE: Swap = true; 5121 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5122 case ISD::SETULT: Swap = true; 5123 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5124 case ISD::SETULE: Swap = true; 5125 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5126 } 5127 5128 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5129 if (Opc == ARMISD::VCEQ) { 5130 5131 SDValue AndOp; 5132 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5133 AndOp = Op0; 5134 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5135 AndOp = Op1; 5136 5137 // Ignore bitconvert. 5138 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5139 AndOp = AndOp.getOperand(0); 5140 5141 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5142 Opc = ARMISD::VTST; 5143 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5144 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5145 Invert = !Invert; 5146 } 5147 } 5148 } 5149 5150 if (Swap) 5151 std::swap(Op0, Op1); 5152 5153 // If one of the operands is a constant vector zero, attempt to fold the 5154 // comparison to a specialized compare-against-zero form. 5155 SDValue SingleOp; 5156 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5157 SingleOp = Op0; 5158 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5159 if (Opc == ARMISD::VCGE) 5160 Opc = ARMISD::VCLEZ; 5161 else if (Opc == ARMISD::VCGT) 5162 Opc = ARMISD::VCLTZ; 5163 SingleOp = Op1; 5164 } 5165 5166 SDValue Result; 5167 if (SingleOp.getNode()) { 5168 switch (Opc) { 5169 case ARMISD::VCEQ: 5170 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5171 case ARMISD::VCGE: 5172 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5173 case ARMISD::VCLEZ: 5174 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5175 case ARMISD::VCGT: 5176 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5177 case ARMISD::VCLTZ: 5178 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5179 default: 5180 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5181 } 5182 } else { 5183 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5184 } 5185 5186 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5187 5188 if (Invert) 5189 Result = DAG.getNOT(dl, Result, VT); 5190 5191 return Result; 5192 } 5193 5194 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5195 SDValue LHS = Op.getOperand(0); 5196 SDValue RHS = Op.getOperand(1); 5197 SDValue Carry = Op.getOperand(2); 5198 SDValue Cond = Op.getOperand(3); 5199 SDLoc DL(Op); 5200 5201 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5202 5203 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5204 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5205 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5206 5207 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5208 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5209 SDValue ARMcc = DAG.getConstant( 5210 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5211 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5212 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5213 Cmp.getValue(1), SDValue()); 5214 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5215 CCR, Chain.getValue(1)); 5216 } 5217 5218 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5219 /// valid vector constant for a NEON instruction with a "modified immediate" 5220 /// operand (e.g., VMOV). If so, return the encoded value. 5221 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5222 unsigned SplatBitSize, SelectionDAG &DAG, 5223 const SDLoc &dl, EVT &VT, bool is128Bits, 5224 NEONModImmType type) { 5225 unsigned OpCmode, Imm; 5226 5227 // SplatBitSize is set to the smallest size that splats the vector, so a 5228 // zero vector will always have SplatBitSize == 8. However, NEON modified 5229 // immediate instructions others than VMOV do not support the 8-bit encoding 5230 // of a zero vector, and the default encoding of zero is supposed to be the 5231 // 32-bit version. 5232 if (SplatBits == 0) 5233 SplatBitSize = 32; 5234 5235 switch (SplatBitSize) { 5236 case 8: 5237 if (type != VMOVModImm) 5238 return SDValue(); 5239 // Any 1-byte value is OK. Op=0, Cmode=1110. 5240 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5241 OpCmode = 0xe; 5242 Imm = SplatBits; 5243 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5244 break; 5245 5246 case 16: 5247 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5248 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5249 if ((SplatBits & ~0xff) == 0) { 5250 // Value = 0x00nn: Op=x, Cmode=100x. 5251 OpCmode = 0x8; 5252 Imm = SplatBits; 5253 break; 5254 } 5255 if ((SplatBits & ~0xff00) == 0) { 5256 // Value = 0xnn00: Op=x, Cmode=101x. 5257 OpCmode = 0xa; 5258 Imm = SplatBits >> 8; 5259 break; 5260 } 5261 return SDValue(); 5262 5263 case 32: 5264 // NEON's 32-bit VMOV supports splat values where: 5265 // * only one byte is nonzero, or 5266 // * the least significant byte is 0xff and the second byte is nonzero, or 5267 // * the least significant 2 bytes are 0xff and the third is nonzero. 5268 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5269 if ((SplatBits & ~0xff) == 0) { 5270 // Value = 0x000000nn: Op=x, Cmode=000x. 5271 OpCmode = 0; 5272 Imm = SplatBits; 5273 break; 5274 } 5275 if ((SplatBits & ~0xff00) == 0) { 5276 // Value = 0x0000nn00: Op=x, Cmode=001x. 5277 OpCmode = 0x2; 5278 Imm = SplatBits >> 8; 5279 break; 5280 } 5281 if ((SplatBits & ~0xff0000) == 0) { 5282 // Value = 0x00nn0000: Op=x, Cmode=010x. 5283 OpCmode = 0x4; 5284 Imm = SplatBits >> 16; 5285 break; 5286 } 5287 if ((SplatBits & ~0xff000000) == 0) { 5288 // Value = 0xnn000000: Op=x, Cmode=011x. 5289 OpCmode = 0x6; 5290 Imm = SplatBits >> 24; 5291 break; 5292 } 5293 5294 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5295 if (type == OtherModImm) return SDValue(); 5296 5297 if ((SplatBits & ~0xffff) == 0 && 5298 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5299 // Value = 0x0000nnff: Op=x, Cmode=1100. 5300 OpCmode = 0xc; 5301 Imm = SplatBits >> 8; 5302 break; 5303 } 5304 5305 if ((SplatBits & ~0xffffff) == 0 && 5306 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5307 // Value = 0x00nnffff: Op=x, Cmode=1101. 5308 OpCmode = 0xd; 5309 Imm = SplatBits >> 16; 5310 break; 5311 } 5312 5313 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5314 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5315 // VMOV.I32. A (very) minor optimization would be to replicate the value 5316 // and fall through here to test for a valid 64-bit splat. But, then the 5317 // caller would also need to check and handle the change in size. 5318 return SDValue(); 5319 5320 case 64: { 5321 if (type != VMOVModImm) 5322 return SDValue(); 5323 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5324 uint64_t BitMask = 0xff; 5325 uint64_t Val = 0; 5326 unsigned ImmMask = 1; 5327 Imm = 0; 5328 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5329 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5330 Val |= BitMask; 5331 Imm |= ImmMask; 5332 } else if ((SplatBits & BitMask) != 0) { 5333 return SDValue(); 5334 } 5335 BitMask <<= 8; 5336 ImmMask <<= 1; 5337 } 5338 5339 if (DAG.getDataLayout().isBigEndian()) 5340 // swap higher and lower 32 bit word 5341 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5342 5343 // Op=1, Cmode=1110. 5344 OpCmode = 0x1e; 5345 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5346 break; 5347 } 5348 5349 default: 5350 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5351 } 5352 5353 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5354 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5355 } 5356 5357 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5358 const ARMSubtarget *ST) const { 5359 if (!ST->hasVFP3()) 5360 return SDValue(); 5361 5362 bool IsDouble = Op.getValueType() == MVT::f64; 5363 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5364 5365 // Use the default (constant pool) lowering for double constants when we have 5366 // an SP-only FPU 5367 if (IsDouble && Subtarget->isFPOnlySP()) 5368 return SDValue(); 5369 5370 // Try splatting with a VMOV.f32... 5371 const APFloat &FPVal = CFP->getValueAPF(); 5372 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5373 5374 if (ImmVal != -1) { 5375 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5376 // We have code in place to select a valid ConstantFP already, no need to 5377 // do any mangling. 5378 return Op; 5379 } 5380 5381 // It's a float and we are trying to use NEON operations where 5382 // possible. Lower it to a splat followed by an extract. 5383 SDLoc DL(Op); 5384 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5385 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5386 NewVal); 5387 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5388 DAG.getConstant(0, DL, MVT::i32)); 5389 } 5390 5391 // The rest of our options are NEON only, make sure that's allowed before 5392 // proceeding.. 5393 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5394 return SDValue(); 5395 5396 EVT VMovVT; 5397 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5398 5399 // It wouldn't really be worth bothering for doubles except for one very 5400 // important value, which does happen to match: 0.0. So make sure we don't do 5401 // anything stupid. 5402 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5403 return SDValue(); 5404 5405 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5406 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5407 VMovVT, false, VMOVModImm); 5408 if (NewVal != SDValue()) { 5409 SDLoc DL(Op); 5410 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5411 NewVal); 5412 if (IsDouble) 5413 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5414 5415 // It's a float: cast and extract a vector element. 5416 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5417 VecConstant); 5418 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5419 DAG.getConstant(0, DL, MVT::i32)); 5420 } 5421 5422 // Finally, try a VMVN.i32 5423 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5424 false, VMVNModImm); 5425 if (NewVal != SDValue()) { 5426 SDLoc DL(Op); 5427 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5428 5429 if (IsDouble) 5430 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5431 5432 // It's a float: cast and extract a vector element. 5433 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5434 VecConstant); 5435 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5436 DAG.getConstant(0, DL, MVT::i32)); 5437 } 5438 5439 return SDValue(); 5440 } 5441 5442 // check if an VEXT instruction can handle the shuffle mask when the 5443 // vector sources of the shuffle are the same. 5444 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5445 unsigned NumElts = VT.getVectorNumElements(); 5446 5447 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5448 if (M[0] < 0) 5449 return false; 5450 5451 Imm = M[0]; 5452 5453 // If this is a VEXT shuffle, the immediate value is the index of the first 5454 // element. The other shuffle indices must be the successive elements after 5455 // the first one. 5456 unsigned ExpectedElt = Imm; 5457 for (unsigned i = 1; i < NumElts; ++i) { 5458 // Increment the expected index. If it wraps around, just follow it 5459 // back to index zero and keep going. 5460 ++ExpectedElt; 5461 if (ExpectedElt == NumElts) 5462 ExpectedElt = 0; 5463 5464 if (M[i] < 0) continue; // ignore UNDEF indices 5465 if (ExpectedElt != static_cast<unsigned>(M[i])) 5466 return false; 5467 } 5468 5469 return true; 5470 } 5471 5472 5473 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5474 bool &ReverseVEXT, unsigned &Imm) { 5475 unsigned NumElts = VT.getVectorNumElements(); 5476 ReverseVEXT = false; 5477 5478 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5479 if (M[0] < 0) 5480 return false; 5481 5482 Imm = M[0]; 5483 5484 // If this is a VEXT shuffle, the immediate value is the index of the first 5485 // element. The other shuffle indices must be the successive elements after 5486 // the first one. 5487 unsigned ExpectedElt = Imm; 5488 for (unsigned i = 1; i < NumElts; ++i) { 5489 // Increment the expected index. If it wraps around, it may still be 5490 // a VEXT but the source vectors must be swapped. 5491 ExpectedElt += 1; 5492 if (ExpectedElt == NumElts * 2) { 5493 ExpectedElt = 0; 5494 ReverseVEXT = true; 5495 } 5496 5497 if (M[i] < 0) continue; // ignore UNDEF indices 5498 if (ExpectedElt != static_cast<unsigned>(M[i])) 5499 return false; 5500 } 5501 5502 // Adjust the index value if the source operands will be swapped. 5503 if (ReverseVEXT) 5504 Imm -= NumElts; 5505 5506 return true; 5507 } 5508 5509 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5510 /// instruction with the specified blocksize. (The order of the elements 5511 /// within each block of the vector is reversed.) 5512 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5513 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5514 "Only possible block sizes for VREV are: 16, 32, 64"); 5515 5516 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5517 if (EltSz == 64) 5518 return false; 5519 5520 unsigned NumElts = VT.getVectorNumElements(); 5521 unsigned BlockElts = M[0] + 1; 5522 // If the first shuffle index is UNDEF, be optimistic. 5523 if (M[0] < 0) 5524 BlockElts = BlockSize / EltSz; 5525 5526 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5527 return false; 5528 5529 for (unsigned i = 0; i < NumElts; ++i) { 5530 if (M[i] < 0) continue; // ignore UNDEF indices 5531 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5532 return false; 5533 } 5534 5535 return true; 5536 } 5537 5538 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5539 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5540 // range, then 0 is placed into the resulting vector. So pretty much any mask 5541 // of 8 elements can work here. 5542 return VT == MVT::v8i8 && M.size() == 8; 5543 } 5544 5545 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5546 // checking that pairs of elements in the shuffle mask represent the same index 5547 // in each vector, incrementing the expected index by 2 at each step. 5548 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5549 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5550 // v2={e,f,g,h} 5551 // WhichResult gives the offset for each element in the mask based on which 5552 // of the two results it belongs to. 5553 // 5554 // The transpose can be represented either as: 5555 // result1 = shufflevector v1, v2, result1_shuffle_mask 5556 // result2 = shufflevector v1, v2, result2_shuffle_mask 5557 // where v1/v2 and the shuffle masks have the same number of elements 5558 // (here WhichResult (see below) indicates which result is being checked) 5559 // 5560 // or as: 5561 // results = shufflevector v1, v2, shuffle_mask 5562 // where both results are returned in one vector and the shuffle mask has twice 5563 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5564 // want to check the low half and high half of the shuffle mask as if it were 5565 // the other case 5566 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5567 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5568 if (EltSz == 64) 5569 return false; 5570 5571 unsigned NumElts = VT.getVectorNumElements(); 5572 if (M.size() != NumElts && M.size() != NumElts*2) 5573 return false; 5574 5575 // If the mask is twice as long as the input vector then we need to check the 5576 // upper and lower parts of the mask with a matching value for WhichResult 5577 // FIXME: A mask with only even values will be rejected in case the first 5578 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5579 // M[0] is used to determine WhichResult 5580 for (unsigned i = 0; i < M.size(); i += NumElts) { 5581 if (M.size() == NumElts * 2) 5582 WhichResult = i / NumElts; 5583 else 5584 WhichResult = M[i] == 0 ? 0 : 1; 5585 for (unsigned j = 0; j < NumElts; j += 2) { 5586 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5587 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5588 return false; 5589 } 5590 } 5591 5592 if (M.size() == NumElts*2) 5593 WhichResult = 0; 5594 5595 return true; 5596 } 5597 5598 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5599 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5600 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5601 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5602 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5603 if (EltSz == 64) 5604 return false; 5605 5606 unsigned NumElts = VT.getVectorNumElements(); 5607 if (M.size() != NumElts && M.size() != NumElts*2) 5608 return false; 5609 5610 for (unsigned i = 0; i < M.size(); i += NumElts) { 5611 if (M.size() == NumElts * 2) 5612 WhichResult = i / NumElts; 5613 else 5614 WhichResult = M[i] == 0 ? 0 : 1; 5615 for (unsigned j = 0; j < NumElts; j += 2) { 5616 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5617 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5618 return false; 5619 } 5620 } 5621 5622 if (M.size() == NumElts*2) 5623 WhichResult = 0; 5624 5625 return true; 5626 } 5627 5628 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5629 // that the mask elements are either all even and in steps of size 2 or all odd 5630 // and in steps of size 2. 5631 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5632 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5633 // v2={e,f,g,h} 5634 // Requires similar checks to that of isVTRNMask with 5635 // respect the how results are returned. 5636 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5637 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5638 if (EltSz == 64) 5639 return false; 5640 5641 unsigned NumElts = VT.getVectorNumElements(); 5642 if (M.size() != NumElts && M.size() != NumElts*2) 5643 return false; 5644 5645 for (unsigned i = 0; i < M.size(); i += NumElts) { 5646 WhichResult = M[i] == 0 ? 0 : 1; 5647 for (unsigned j = 0; j < NumElts; ++j) { 5648 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5649 return false; 5650 } 5651 } 5652 5653 if (M.size() == NumElts*2) 5654 WhichResult = 0; 5655 5656 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5657 if (VT.is64BitVector() && EltSz == 32) 5658 return false; 5659 5660 return true; 5661 } 5662 5663 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5664 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5665 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5666 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5667 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5668 if (EltSz == 64) 5669 return false; 5670 5671 unsigned NumElts = VT.getVectorNumElements(); 5672 if (M.size() != NumElts && M.size() != NumElts*2) 5673 return false; 5674 5675 unsigned Half = NumElts / 2; 5676 for (unsigned i = 0; i < M.size(); i += NumElts) { 5677 WhichResult = M[i] == 0 ? 0 : 1; 5678 for (unsigned j = 0; j < NumElts; j += Half) { 5679 unsigned Idx = WhichResult; 5680 for (unsigned k = 0; k < Half; ++k) { 5681 int MIdx = M[i + j + k]; 5682 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5683 return false; 5684 Idx += 2; 5685 } 5686 } 5687 } 5688 5689 if (M.size() == NumElts*2) 5690 WhichResult = 0; 5691 5692 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5693 if (VT.is64BitVector() && EltSz == 32) 5694 return false; 5695 5696 return true; 5697 } 5698 5699 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5700 // that pairs of elements of the shufflemask represent the same index in each 5701 // vector incrementing sequentially through the vectors. 5702 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5703 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5704 // v2={e,f,g,h} 5705 // Requires similar checks to that of isVTRNMask with respect the how results 5706 // are returned. 5707 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5708 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5709 if (EltSz == 64) 5710 return false; 5711 5712 unsigned NumElts = VT.getVectorNumElements(); 5713 if (M.size() != NumElts && M.size() != NumElts*2) 5714 return false; 5715 5716 for (unsigned i = 0; i < M.size(); i += NumElts) { 5717 WhichResult = M[i] == 0 ? 0 : 1; 5718 unsigned Idx = WhichResult * NumElts / 2; 5719 for (unsigned j = 0; j < NumElts; j += 2) { 5720 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5721 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5722 return false; 5723 Idx += 1; 5724 } 5725 } 5726 5727 if (M.size() == NumElts*2) 5728 WhichResult = 0; 5729 5730 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5731 if (VT.is64BitVector() && EltSz == 32) 5732 return false; 5733 5734 return true; 5735 } 5736 5737 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5738 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5739 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5740 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5741 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5742 if (EltSz == 64) 5743 return false; 5744 5745 unsigned NumElts = VT.getVectorNumElements(); 5746 if (M.size() != NumElts && M.size() != NumElts*2) 5747 return false; 5748 5749 for (unsigned i = 0; i < M.size(); i += NumElts) { 5750 WhichResult = M[i] == 0 ? 0 : 1; 5751 unsigned Idx = WhichResult * NumElts / 2; 5752 for (unsigned j = 0; j < NumElts; j += 2) { 5753 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5754 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5755 return false; 5756 Idx += 1; 5757 } 5758 } 5759 5760 if (M.size() == NumElts*2) 5761 WhichResult = 0; 5762 5763 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5764 if (VT.is64BitVector() && EltSz == 32) 5765 return false; 5766 5767 return true; 5768 } 5769 5770 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5771 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5772 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5773 unsigned &WhichResult, 5774 bool &isV_UNDEF) { 5775 isV_UNDEF = false; 5776 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5777 return ARMISD::VTRN; 5778 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5779 return ARMISD::VUZP; 5780 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5781 return ARMISD::VZIP; 5782 5783 isV_UNDEF = true; 5784 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5785 return ARMISD::VTRN; 5786 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5787 return ARMISD::VUZP; 5788 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5789 return ARMISD::VZIP; 5790 5791 return 0; 5792 } 5793 5794 /// \return true if this is a reverse operation on an vector. 5795 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5796 unsigned NumElts = VT.getVectorNumElements(); 5797 // Make sure the mask has the right size. 5798 if (NumElts != M.size()) 5799 return false; 5800 5801 // Look for <15, ..., 3, -1, 1, 0>. 5802 for (unsigned i = 0; i != NumElts; ++i) 5803 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5804 return false; 5805 5806 return true; 5807 } 5808 5809 // If N is an integer constant that can be moved into a register in one 5810 // instruction, return an SDValue of such a constant (will become a MOV 5811 // instruction). Otherwise return null. 5812 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5813 const ARMSubtarget *ST, const SDLoc &dl) { 5814 uint64_t Val; 5815 if (!isa<ConstantSDNode>(N)) 5816 return SDValue(); 5817 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5818 5819 if (ST->isThumb1Only()) { 5820 if (Val <= 255 || ~Val <= 255) 5821 return DAG.getConstant(Val, dl, MVT::i32); 5822 } else { 5823 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5824 return DAG.getConstant(Val, dl, MVT::i32); 5825 } 5826 return SDValue(); 5827 } 5828 5829 // If this is a case we can't handle, return null and let the default 5830 // expansion code take care of it. 5831 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5832 const ARMSubtarget *ST) const { 5833 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5834 SDLoc dl(Op); 5835 EVT VT = Op.getValueType(); 5836 5837 APInt SplatBits, SplatUndef; 5838 unsigned SplatBitSize; 5839 bool HasAnyUndefs; 5840 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5841 if (SplatBitSize <= 64) { 5842 // Check if an immediate VMOV works. 5843 EVT VmovVT; 5844 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5845 SplatUndef.getZExtValue(), SplatBitSize, 5846 DAG, dl, VmovVT, VT.is128BitVector(), 5847 VMOVModImm); 5848 if (Val.getNode()) { 5849 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5850 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5851 } 5852 5853 // Try an immediate VMVN. 5854 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5855 Val = isNEONModifiedImm(NegatedImm, 5856 SplatUndef.getZExtValue(), SplatBitSize, 5857 DAG, dl, VmovVT, VT.is128BitVector(), 5858 VMVNModImm); 5859 if (Val.getNode()) { 5860 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5861 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5862 } 5863 5864 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5865 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5866 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5867 if (ImmVal != -1) { 5868 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5869 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5870 } 5871 } 5872 } 5873 } 5874 5875 // Scan through the operands to see if only one value is used. 5876 // 5877 // As an optimisation, even if more than one value is used it may be more 5878 // profitable to splat with one value then change some lanes. 5879 // 5880 // Heuristically we decide to do this if the vector has a "dominant" value, 5881 // defined as splatted to more than half of the lanes. 5882 unsigned NumElts = VT.getVectorNumElements(); 5883 bool isOnlyLowElement = true; 5884 bool usesOnlyOneValue = true; 5885 bool hasDominantValue = false; 5886 bool isConstant = true; 5887 5888 // Map of the number of times a particular SDValue appears in the 5889 // element list. 5890 DenseMap<SDValue, unsigned> ValueCounts; 5891 SDValue Value; 5892 for (unsigned i = 0; i < NumElts; ++i) { 5893 SDValue V = Op.getOperand(i); 5894 if (V.isUndef()) 5895 continue; 5896 if (i > 0) 5897 isOnlyLowElement = false; 5898 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5899 isConstant = false; 5900 5901 ValueCounts.insert(std::make_pair(V, 0)); 5902 unsigned &Count = ValueCounts[V]; 5903 5904 // Is this value dominant? (takes up more than half of the lanes) 5905 if (++Count > (NumElts / 2)) { 5906 hasDominantValue = true; 5907 Value = V; 5908 } 5909 } 5910 if (ValueCounts.size() != 1) 5911 usesOnlyOneValue = false; 5912 if (!Value.getNode() && ValueCounts.size() > 0) 5913 Value = ValueCounts.begin()->first; 5914 5915 if (ValueCounts.size() == 0) 5916 return DAG.getUNDEF(VT); 5917 5918 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5919 // Keep going if we are hitting this case. 5920 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5921 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5922 5923 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5924 5925 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5926 // i32 and try again. 5927 if (hasDominantValue && EltSize <= 32) { 5928 if (!isConstant) { 5929 SDValue N; 5930 5931 // If we are VDUPing a value that comes directly from a vector, that will 5932 // cause an unnecessary move to and from a GPR, where instead we could 5933 // just use VDUPLANE. We can only do this if the lane being extracted 5934 // is at a constant index, as the VDUP from lane instructions only have 5935 // constant-index forms. 5936 ConstantSDNode *constIndex; 5937 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5938 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5939 // We need to create a new undef vector to use for the VDUPLANE if the 5940 // size of the vector from which we get the value is different than the 5941 // size of the vector that we need to create. We will insert the element 5942 // such that the register coalescer will remove unnecessary copies. 5943 if (VT != Value->getOperand(0).getValueType()) { 5944 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5945 VT.getVectorNumElements(); 5946 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5947 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5948 Value, DAG.getConstant(index, dl, MVT::i32)), 5949 DAG.getConstant(index, dl, MVT::i32)); 5950 } else 5951 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5952 Value->getOperand(0), Value->getOperand(1)); 5953 } else 5954 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5955 5956 if (!usesOnlyOneValue) { 5957 // The dominant value was splatted as 'N', but we now have to insert 5958 // all differing elements. 5959 for (unsigned I = 0; I < NumElts; ++I) { 5960 if (Op.getOperand(I) == Value) 5961 continue; 5962 SmallVector<SDValue, 3> Ops; 5963 Ops.push_back(N); 5964 Ops.push_back(Op.getOperand(I)); 5965 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5966 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5967 } 5968 } 5969 return N; 5970 } 5971 if (VT.getVectorElementType().isFloatingPoint()) { 5972 SmallVector<SDValue, 8> Ops; 5973 for (unsigned i = 0; i < NumElts; ++i) 5974 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5975 Op.getOperand(i))); 5976 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5977 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 5978 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5979 if (Val.getNode()) 5980 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5981 } 5982 if (usesOnlyOneValue) { 5983 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5984 if (isConstant && Val.getNode()) 5985 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5986 } 5987 } 5988 5989 // If all elements are constants and the case above didn't get hit, fall back 5990 // to the default expansion, which will generate a load from the constant 5991 // pool. 5992 if (isConstant) 5993 return SDValue(); 5994 5995 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5996 if (NumElts >= 4) { 5997 SDValue shuffle = ReconstructShuffle(Op, DAG); 5998 if (shuffle != SDValue()) 5999 return shuffle; 6000 } 6001 6002 // Vectors with 32- or 64-bit elements can be built by directly assigning 6003 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6004 // will be legalized. 6005 if (EltSize >= 32) { 6006 // Do the expansion with floating-point types, since that is what the VFP 6007 // registers are defined to use, and since i64 is not legal. 6008 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6009 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6010 SmallVector<SDValue, 8> Ops; 6011 for (unsigned i = 0; i < NumElts; ++i) 6012 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6013 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6014 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6015 } 6016 6017 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6018 // know the default expansion would otherwise fall back on something even 6019 // worse. For a vector with one or two non-undef values, that's 6020 // scalar_to_vector for the elements followed by a shuffle (provided the 6021 // shuffle is valid for the target) and materialization element by element 6022 // on the stack followed by a load for everything else. 6023 if (!isConstant && !usesOnlyOneValue) { 6024 SDValue Vec = DAG.getUNDEF(VT); 6025 for (unsigned i = 0 ; i < NumElts; ++i) { 6026 SDValue V = Op.getOperand(i); 6027 if (V.isUndef()) 6028 continue; 6029 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6030 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6031 } 6032 return Vec; 6033 } 6034 6035 return SDValue(); 6036 } 6037 6038 // Gather data to see if the operation can be modelled as a 6039 // shuffle in combination with VEXTs. 6040 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6041 SelectionDAG &DAG) const { 6042 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6043 SDLoc dl(Op); 6044 EVT VT = Op.getValueType(); 6045 unsigned NumElts = VT.getVectorNumElements(); 6046 6047 struct ShuffleSourceInfo { 6048 SDValue Vec; 6049 unsigned MinElt; 6050 unsigned MaxElt; 6051 6052 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6053 // be compatible with the shuffle we intend to construct. As a result 6054 // ShuffleVec will be some sliding window into the original Vec. 6055 SDValue ShuffleVec; 6056 6057 // Code should guarantee that element i in Vec starts at element "WindowBase 6058 // + i * WindowScale in ShuffleVec". 6059 int WindowBase; 6060 int WindowScale; 6061 6062 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6063 ShuffleSourceInfo(SDValue Vec) 6064 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 6065 WindowScale(1) {} 6066 }; 6067 6068 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6069 // node. 6070 SmallVector<ShuffleSourceInfo, 2> Sources; 6071 for (unsigned i = 0; i < NumElts; ++i) { 6072 SDValue V = Op.getOperand(i); 6073 if (V.isUndef()) 6074 continue; 6075 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6076 // A shuffle can only come from building a vector from various 6077 // elements of other vectors. 6078 return SDValue(); 6079 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6080 // Furthermore, shuffles require a constant mask, whereas extractelts 6081 // accept variable indices. 6082 return SDValue(); 6083 } 6084 6085 // Add this element source to the list if it's not already there. 6086 SDValue SourceVec = V.getOperand(0); 6087 auto Source = find(Sources, SourceVec); 6088 if (Source == Sources.end()) 6089 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6090 6091 // Update the minimum and maximum lane number seen. 6092 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6093 Source->MinElt = std::min(Source->MinElt, EltNo); 6094 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6095 } 6096 6097 // Currently only do something sane when at most two source vectors 6098 // are involved. 6099 if (Sources.size() > 2) 6100 return SDValue(); 6101 6102 // Find out the smallest element size among result and two sources, and use 6103 // it as element size to build the shuffle_vector. 6104 EVT SmallestEltTy = VT.getVectorElementType(); 6105 for (auto &Source : Sources) { 6106 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6107 if (SrcEltTy.bitsLT(SmallestEltTy)) 6108 SmallestEltTy = SrcEltTy; 6109 } 6110 unsigned ResMultiplier = 6111 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 6112 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6113 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6114 6115 // If the source vector is too wide or too narrow, we may nevertheless be able 6116 // to construct a compatible shuffle either by concatenating it with UNDEF or 6117 // extracting a suitable range of elements. 6118 for (auto &Src : Sources) { 6119 EVT SrcVT = Src.ShuffleVec.getValueType(); 6120 6121 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6122 continue; 6123 6124 // This stage of the search produces a source with the same element type as 6125 // the original, but with a total width matching the BUILD_VECTOR output. 6126 EVT EltVT = SrcVT.getVectorElementType(); 6127 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6128 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6129 6130 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6131 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6132 return SDValue(); 6133 // We can pad out the smaller vector for free, so if it's part of a 6134 // shuffle... 6135 Src.ShuffleVec = 6136 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6137 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6138 continue; 6139 } 6140 6141 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6142 return SDValue(); 6143 6144 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6145 // Span too large for a VEXT to cope 6146 return SDValue(); 6147 } 6148 6149 if (Src.MinElt >= NumSrcElts) { 6150 // The extraction can just take the second half 6151 Src.ShuffleVec = 6152 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6153 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6154 Src.WindowBase = -NumSrcElts; 6155 } else if (Src.MaxElt < NumSrcElts) { 6156 // The extraction can just take the first half 6157 Src.ShuffleVec = 6158 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6159 DAG.getConstant(0, dl, MVT::i32)); 6160 } else { 6161 // An actual VEXT is needed 6162 SDValue VEXTSrc1 = 6163 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6164 DAG.getConstant(0, dl, MVT::i32)); 6165 SDValue VEXTSrc2 = 6166 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6167 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6168 6169 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6170 VEXTSrc2, 6171 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6172 Src.WindowBase = -Src.MinElt; 6173 } 6174 } 6175 6176 // Another possible incompatibility occurs from the vector element types. We 6177 // can fix this by bitcasting the source vectors to the same type we intend 6178 // for the shuffle. 6179 for (auto &Src : Sources) { 6180 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6181 if (SrcEltTy == SmallestEltTy) 6182 continue; 6183 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6184 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6185 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6186 Src.WindowBase *= Src.WindowScale; 6187 } 6188 6189 // Final sanity check before we try to actually produce a shuffle. 6190 DEBUG( 6191 for (auto Src : Sources) 6192 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6193 ); 6194 6195 // The stars all align, our next step is to produce the mask for the shuffle. 6196 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6197 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 6198 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6199 SDValue Entry = Op.getOperand(i); 6200 if (Entry.isUndef()) 6201 continue; 6202 6203 auto Src = find(Sources, Entry.getOperand(0)); 6204 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6205 6206 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6207 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6208 // segment. 6209 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6210 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6211 VT.getVectorElementType().getSizeInBits()); 6212 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6213 6214 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6215 // starting at the appropriate offset. 6216 int *LaneMask = &Mask[i * ResMultiplier]; 6217 6218 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6219 ExtractBase += NumElts * (Src - Sources.begin()); 6220 for (int j = 0; j < LanesDefined; ++j) 6221 LaneMask[j] = ExtractBase + j; 6222 } 6223 6224 // Final check before we try to produce nonsense... 6225 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6226 return SDValue(); 6227 6228 // We can't handle more than two sources. This should have already 6229 // been checked before this point. 6230 assert(Sources.size() <= 2 && "Too many sources!"); 6231 6232 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6233 for (unsigned i = 0; i < Sources.size(); ++i) 6234 ShuffleOps[i] = Sources[i].ShuffleVec; 6235 6236 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6237 ShuffleOps[1], Mask); 6238 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6239 } 6240 6241 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6242 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6243 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6244 /// are assumed to be legal. 6245 bool 6246 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6247 EVT VT) const { 6248 if (VT.getVectorNumElements() == 4 && 6249 (VT.is128BitVector() || VT.is64BitVector())) { 6250 unsigned PFIndexes[4]; 6251 for (unsigned i = 0; i != 4; ++i) { 6252 if (M[i] < 0) 6253 PFIndexes[i] = 8; 6254 else 6255 PFIndexes[i] = M[i]; 6256 } 6257 6258 // Compute the index in the perfect shuffle table. 6259 unsigned PFTableIndex = 6260 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6261 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6262 unsigned Cost = (PFEntry >> 30); 6263 6264 if (Cost <= 4) 6265 return true; 6266 } 6267 6268 bool ReverseVEXT, isV_UNDEF; 6269 unsigned Imm, WhichResult; 6270 6271 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6272 return (EltSize >= 32 || 6273 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6274 isVREVMask(M, VT, 64) || 6275 isVREVMask(M, VT, 32) || 6276 isVREVMask(M, VT, 16) || 6277 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6278 isVTBLMask(M, VT) || 6279 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6280 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6281 } 6282 6283 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6284 /// the specified operations to build the shuffle. 6285 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6286 SDValue RHS, SelectionDAG &DAG, 6287 const SDLoc &dl) { 6288 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6289 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6290 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6291 6292 enum { 6293 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6294 OP_VREV, 6295 OP_VDUP0, 6296 OP_VDUP1, 6297 OP_VDUP2, 6298 OP_VDUP3, 6299 OP_VEXT1, 6300 OP_VEXT2, 6301 OP_VEXT3, 6302 OP_VUZPL, // VUZP, left result 6303 OP_VUZPR, // VUZP, right result 6304 OP_VZIPL, // VZIP, left result 6305 OP_VZIPR, // VZIP, right result 6306 OP_VTRNL, // VTRN, left result 6307 OP_VTRNR // VTRN, right result 6308 }; 6309 6310 if (OpNum == OP_COPY) { 6311 if (LHSID == (1*9+2)*9+3) return LHS; 6312 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6313 return RHS; 6314 } 6315 6316 SDValue OpLHS, OpRHS; 6317 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6318 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6319 EVT VT = OpLHS.getValueType(); 6320 6321 switch (OpNum) { 6322 default: llvm_unreachable("Unknown shuffle opcode!"); 6323 case OP_VREV: 6324 // VREV divides the vector in half and swaps within the half. 6325 if (VT.getVectorElementType() == MVT::i32 || 6326 VT.getVectorElementType() == MVT::f32) 6327 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6328 // vrev <4 x i16> -> VREV32 6329 if (VT.getVectorElementType() == MVT::i16) 6330 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6331 // vrev <4 x i8> -> VREV16 6332 assert(VT.getVectorElementType() == MVT::i8); 6333 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6334 case OP_VDUP0: 6335 case OP_VDUP1: 6336 case OP_VDUP2: 6337 case OP_VDUP3: 6338 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6339 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6340 case OP_VEXT1: 6341 case OP_VEXT2: 6342 case OP_VEXT3: 6343 return DAG.getNode(ARMISD::VEXT, dl, VT, 6344 OpLHS, OpRHS, 6345 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6346 case OP_VUZPL: 6347 case OP_VUZPR: 6348 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6349 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6350 case OP_VZIPL: 6351 case OP_VZIPR: 6352 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6353 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6354 case OP_VTRNL: 6355 case OP_VTRNR: 6356 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6357 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6358 } 6359 } 6360 6361 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6362 ArrayRef<int> ShuffleMask, 6363 SelectionDAG &DAG) { 6364 // Check to see if we can use the VTBL instruction. 6365 SDValue V1 = Op.getOperand(0); 6366 SDValue V2 = Op.getOperand(1); 6367 SDLoc DL(Op); 6368 6369 SmallVector<SDValue, 8> VTBLMask; 6370 for (ArrayRef<int>::iterator 6371 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6372 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6373 6374 if (V2.getNode()->isUndef()) 6375 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6376 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6377 6378 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6379 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6380 } 6381 6382 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6383 SelectionDAG &DAG) { 6384 SDLoc DL(Op); 6385 SDValue OpLHS = Op.getOperand(0); 6386 EVT VT = OpLHS.getValueType(); 6387 6388 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6389 "Expect an v8i16/v16i8 type"); 6390 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6391 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6392 // extract the first 8 bytes into the top double word and the last 8 bytes 6393 // into the bottom double word. The v8i16 case is similar. 6394 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6395 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6396 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6397 } 6398 6399 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6400 SDValue V1 = Op.getOperand(0); 6401 SDValue V2 = Op.getOperand(1); 6402 SDLoc dl(Op); 6403 EVT VT = Op.getValueType(); 6404 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6405 6406 // Convert shuffles that are directly supported on NEON to target-specific 6407 // DAG nodes, instead of keeping them as shuffles and matching them again 6408 // during code selection. This is more efficient and avoids the possibility 6409 // of inconsistencies between legalization and selection. 6410 // FIXME: floating-point vectors should be canonicalized to integer vectors 6411 // of the same time so that they get CSEd properly. 6412 ArrayRef<int> ShuffleMask = SVN->getMask(); 6413 6414 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6415 if (EltSize <= 32) { 6416 if (SVN->isSplat()) { 6417 int Lane = SVN->getSplatIndex(); 6418 // If this is undef splat, generate it via "just" vdup, if possible. 6419 if (Lane == -1) Lane = 0; 6420 6421 // Test if V1 is a SCALAR_TO_VECTOR. 6422 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6423 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6424 } 6425 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6426 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6427 // reaches it). 6428 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6429 !isa<ConstantSDNode>(V1.getOperand(0))) { 6430 bool IsScalarToVector = true; 6431 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6432 if (!V1.getOperand(i).isUndef()) { 6433 IsScalarToVector = false; 6434 break; 6435 } 6436 if (IsScalarToVector) 6437 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6438 } 6439 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6440 DAG.getConstant(Lane, dl, MVT::i32)); 6441 } 6442 6443 bool ReverseVEXT; 6444 unsigned Imm; 6445 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6446 if (ReverseVEXT) 6447 std::swap(V1, V2); 6448 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6449 DAG.getConstant(Imm, dl, MVT::i32)); 6450 } 6451 6452 if (isVREVMask(ShuffleMask, VT, 64)) 6453 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6454 if (isVREVMask(ShuffleMask, VT, 32)) 6455 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6456 if (isVREVMask(ShuffleMask, VT, 16)) 6457 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6458 6459 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6460 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6461 DAG.getConstant(Imm, dl, MVT::i32)); 6462 } 6463 6464 // Check for Neon shuffles that modify both input vectors in place. 6465 // If both results are used, i.e., if there are two shuffles with the same 6466 // source operands and with masks corresponding to both results of one of 6467 // these operations, DAG memoization will ensure that a single node is 6468 // used for both shuffles. 6469 unsigned WhichResult; 6470 bool isV_UNDEF; 6471 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6472 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6473 if (isV_UNDEF) 6474 V2 = V1; 6475 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6476 .getValue(WhichResult); 6477 } 6478 6479 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6480 // shuffles that produce a result larger than their operands with: 6481 // shuffle(concat(v1, undef), concat(v2, undef)) 6482 // -> 6483 // shuffle(concat(v1, v2), undef) 6484 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6485 // 6486 // This is useful in the general case, but there are special cases where 6487 // native shuffles produce larger results: the two-result ops. 6488 // 6489 // Look through the concat when lowering them: 6490 // shuffle(concat(v1, v2), undef) 6491 // -> 6492 // concat(VZIP(v1, v2):0, :1) 6493 // 6494 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6495 SDValue SubV1 = V1->getOperand(0); 6496 SDValue SubV2 = V1->getOperand(1); 6497 EVT SubVT = SubV1.getValueType(); 6498 6499 // We expect these to have been canonicalized to -1. 6500 assert(all_of(ShuffleMask, [&](int i) { 6501 return i < (int)VT.getVectorNumElements(); 6502 }) && "Unexpected shuffle index into UNDEF operand!"); 6503 6504 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6505 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6506 if (isV_UNDEF) 6507 SubV2 = SubV1; 6508 assert((WhichResult == 0) && 6509 "In-place shuffle of concat can only have one result!"); 6510 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6511 SubV1, SubV2); 6512 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6513 Res.getValue(1)); 6514 } 6515 } 6516 } 6517 6518 // If the shuffle is not directly supported and it has 4 elements, use 6519 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6520 unsigned NumElts = VT.getVectorNumElements(); 6521 if (NumElts == 4) { 6522 unsigned PFIndexes[4]; 6523 for (unsigned i = 0; i != 4; ++i) { 6524 if (ShuffleMask[i] < 0) 6525 PFIndexes[i] = 8; 6526 else 6527 PFIndexes[i] = ShuffleMask[i]; 6528 } 6529 6530 // Compute the index in the perfect shuffle table. 6531 unsigned PFTableIndex = 6532 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6533 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6534 unsigned Cost = (PFEntry >> 30); 6535 6536 if (Cost <= 4) 6537 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6538 } 6539 6540 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6541 if (EltSize >= 32) { 6542 // Do the expansion with floating-point types, since that is what the VFP 6543 // registers are defined to use, and since i64 is not legal. 6544 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6545 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6546 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6547 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6548 SmallVector<SDValue, 8> Ops; 6549 for (unsigned i = 0; i < NumElts; ++i) { 6550 if (ShuffleMask[i] < 0) 6551 Ops.push_back(DAG.getUNDEF(EltVT)); 6552 else 6553 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6554 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6555 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6556 dl, MVT::i32))); 6557 } 6558 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6559 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6560 } 6561 6562 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6563 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6564 6565 if (VT == MVT::v8i8) 6566 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6567 return NewOp; 6568 6569 return SDValue(); 6570 } 6571 6572 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6573 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6574 SDValue Lane = Op.getOperand(2); 6575 if (!isa<ConstantSDNode>(Lane)) 6576 return SDValue(); 6577 6578 return Op; 6579 } 6580 6581 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6582 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6583 SDValue Lane = Op.getOperand(1); 6584 if (!isa<ConstantSDNode>(Lane)) 6585 return SDValue(); 6586 6587 SDValue Vec = Op.getOperand(0); 6588 if (Op.getValueType() == MVT::i32 && 6589 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6590 SDLoc dl(Op); 6591 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6592 } 6593 6594 return Op; 6595 } 6596 6597 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6598 // The only time a CONCAT_VECTORS operation can have legal types is when 6599 // two 64-bit vectors are concatenated to a 128-bit vector. 6600 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6601 "unexpected CONCAT_VECTORS"); 6602 SDLoc dl(Op); 6603 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6604 SDValue Op0 = Op.getOperand(0); 6605 SDValue Op1 = Op.getOperand(1); 6606 if (!Op0.isUndef()) 6607 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6608 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6609 DAG.getIntPtrConstant(0, dl)); 6610 if (!Op1.isUndef()) 6611 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6612 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6613 DAG.getIntPtrConstant(1, dl)); 6614 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6615 } 6616 6617 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6618 /// element has been zero/sign-extended, depending on the isSigned parameter, 6619 /// from an integer type half its size. 6620 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6621 bool isSigned) { 6622 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6623 EVT VT = N->getValueType(0); 6624 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6625 SDNode *BVN = N->getOperand(0).getNode(); 6626 if (BVN->getValueType(0) != MVT::v4i32 || 6627 BVN->getOpcode() != ISD::BUILD_VECTOR) 6628 return false; 6629 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6630 unsigned HiElt = 1 - LoElt; 6631 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6632 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6633 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6634 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6635 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6636 return false; 6637 if (isSigned) { 6638 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6639 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6640 return true; 6641 } else { 6642 if (Hi0->isNullValue() && Hi1->isNullValue()) 6643 return true; 6644 } 6645 return false; 6646 } 6647 6648 if (N->getOpcode() != ISD::BUILD_VECTOR) 6649 return false; 6650 6651 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6652 SDNode *Elt = N->getOperand(i).getNode(); 6653 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6654 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6655 unsigned HalfSize = EltSize / 2; 6656 if (isSigned) { 6657 if (!isIntN(HalfSize, C->getSExtValue())) 6658 return false; 6659 } else { 6660 if (!isUIntN(HalfSize, C->getZExtValue())) 6661 return false; 6662 } 6663 continue; 6664 } 6665 return false; 6666 } 6667 6668 return true; 6669 } 6670 6671 /// isSignExtended - Check if a node is a vector value that is sign-extended 6672 /// or a constant BUILD_VECTOR with sign-extended elements. 6673 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6674 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6675 return true; 6676 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6677 return true; 6678 return false; 6679 } 6680 6681 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6682 /// or a constant BUILD_VECTOR with zero-extended elements. 6683 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6684 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6685 return true; 6686 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6687 return true; 6688 return false; 6689 } 6690 6691 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6692 if (OrigVT.getSizeInBits() >= 64) 6693 return OrigVT; 6694 6695 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6696 6697 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6698 switch (OrigSimpleTy) { 6699 default: llvm_unreachable("Unexpected Vector Type"); 6700 case MVT::v2i8: 6701 case MVT::v2i16: 6702 return MVT::v2i32; 6703 case MVT::v4i8: 6704 return MVT::v4i16; 6705 } 6706 } 6707 6708 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6709 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6710 /// We insert the required extension here to get the vector to fill a D register. 6711 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6712 const EVT &OrigTy, 6713 const EVT &ExtTy, 6714 unsigned ExtOpcode) { 6715 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6716 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6717 // 64-bits we need to insert a new extension so that it will be 64-bits. 6718 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6719 if (OrigTy.getSizeInBits() >= 64) 6720 return N; 6721 6722 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6723 EVT NewVT = getExtensionTo64Bits(OrigTy); 6724 6725 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6726 } 6727 6728 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6729 /// does not do any sign/zero extension. If the original vector is less 6730 /// than 64 bits, an appropriate extension will be added after the load to 6731 /// reach a total size of 64 bits. We have to add the extension separately 6732 /// because ARM does not have a sign/zero extending load for vectors. 6733 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6734 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6735 6736 // The load already has the right type. 6737 if (ExtendedTy == LD->getMemoryVT()) 6738 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6739 LD->getBasePtr(), LD->getPointerInfo(), 6740 LD->getAlignment(), LD->getMemOperand()->getFlags()); 6741 6742 // We need to create a zextload/sextload. We cannot just create a load 6743 // followed by a zext/zext node because LowerMUL is also run during normal 6744 // operation legalization where we can't create illegal types. 6745 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6746 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6747 LD->getMemoryVT(), LD->getAlignment(), 6748 LD->getMemOperand()->getFlags()); 6749 } 6750 6751 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6752 /// extending load, or BUILD_VECTOR with extended elements, return the 6753 /// unextended value. The unextended vector should be 64 bits so that it can 6754 /// be used as an operand to a VMULL instruction. If the original vector size 6755 /// before extension is less than 64 bits we add a an extension to resize 6756 /// the vector to 64 bits. 6757 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6758 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6759 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6760 N->getOperand(0)->getValueType(0), 6761 N->getValueType(0), 6762 N->getOpcode()); 6763 6764 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6765 return SkipLoadExtensionForVMULL(LD, DAG); 6766 6767 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6768 // have been legalized as a BITCAST from v4i32. 6769 if (N->getOpcode() == ISD::BITCAST) { 6770 SDNode *BVN = N->getOperand(0).getNode(); 6771 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6772 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6773 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6774 return DAG.getBuildVector( 6775 MVT::v2i32, SDLoc(N), 6776 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 6777 } 6778 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6779 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6780 EVT VT = N->getValueType(0); 6781 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6782 unsigned NumElts = VT.getVectorNumElements(); 6783 MVT TruncVT = MVT::getIntegerVT(EltSize); 6784 SmallVector<SDValue, 8> Ops; 6785 SDLoc dl(N); 6786 for (unsigned i = 0; i != NumElts; ++i) { 6787 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6788 const APInt &CInt = C->getAPIntValue(); 6789 // Element types smaller than 32 bits are not legal, so use i32 elements. 6790 // The values are implicitly truncated so sext vs. zext doesn't matter. 6791 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6792 } 6793 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 6794 } 6795 6796 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6797 unsigned Opcode = N->getOpcode(); 6798 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6799 SDNode *N0 = N->getOperand(0).getNode(); 6800 SDNode *N1 = N->getOperand(1).getNode(); 6801 return N0->hasOneUse() && N1->hasOneUse() && 6802 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6803 } 6804 return false; 6805 } 6806 6807 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6808 unsigned Opcode = N->getOpcode(); 6809 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6810 SDNode *N0 = N->getOperand(0).getNode(); 6811 SDNode *N1 = N->getOperand(1).getNode(); 6812 return N0->hasOneUse() && N1->hasOneUse() && 6813 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6814 } 6815 return false; 6816 } 6817 6818 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6819 // Multiplications are only custom-lowered for 128-bit vectors so that 6820 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6821 EVT VT = Op.getValueType(); 6822 assert(VT.is128BitVector() && VT.isInteger() && 6823 "unexpected type for custom-lowering ISD::MUL"); 6824 SDNode *N0 = Op.getOperand(0).getNode(); 6825 SDNode *N1 = Op.getOperand(1).getNode(); 6826 unsigned NewOpc = 0; 6827 bool isMLA = false; 6828 bool isN0SExt = isSignExtended(N0, DAG); 6829 bool isN1SExt = isSignExtended(N1, DAG); 6830 if (isN0SExt && isN1SExt) 6831 NewOpc = ARMISD::VMULLs; 6832 else { 6833 bool isN0ZExt = isZeroExtended(N0, DAG); 6834 bool isN1ZExt = isZeroExtended(N1, DAG); 6835 if (isN0ZExt && isN1ZExt) 6836 NewOpc = ARMISD::VMULLu; 6837 else if (isN1SExt || isN1ZExt) { 6838 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6839 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6840 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6841 NewOpc = ARMISD::VMULLs; 6842 isMLA = true; 6843 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6844 NewOpc = ARMISD::VMULLu; 6845 isMLA = true; 6846 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6847 std::swap(N0, N1); 6848 NewOpc = ARMISD::VMULLu; 6849 isMLA = true; 6850 } 6851 } 6852 6853 if (!NewOpc) { 6854 if (VT == MVT::v2i64) 6855 // Fall through to expand this. It is not legal. 6856 return SDValue(); 6857 else 6858 // Other vector multiplications are legal. 6859 return Op; 6860 } 6861 } 6862 6863 // Legalize to a VMULL instruction. 6864 SDLoc DL(Op); 6865 SDValue Op0; 6866 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6867 if (!isMLA) { 6868 Op0 = SkipExtensionForVMULL(N0, DAG); 6869 assert(Op0.getValueType().is64BitVector() && 6870 Op1.getValueType().is64BitVector() && 6871 "unexpected types for extended operands to VMULL"); 6872 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6873 } 6874 6875 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6876 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6877 // vmull q0, d4, d6 6878 // vmlal q0, d5, d6 6879 // is faster than 6880 // vaddl q0, d4, d5 6881 // vmovl q1, d6 6882 // vmul q0, q0, q1 6883 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6884 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6885 EVT Op1VT = Op1.getValueType(); 6886 return DAG.getNode(N0->getOpcode(), DL, VT, 6887 DAG.getNode(NewOpc, DL, VT, 6888 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6889 DAG.getNode(NewOpc, DL, VT, 6890 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6891 } 6892 6893 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 6894 SelectionDAG &DAG) { 6895 // TODO: Should this propagate fast-math-flags? 6896 6897 // Convert to float 6898 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6899 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6900 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6901 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6902 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6903 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6904 // Get reciprocal estimate. 6905 // float4 recip = vrecpeq_f32(yf); 6906 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6907 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6908 Y); 6909 // Because char has a smaller range than uchar, we can actually get away 6910 // without any newton steps. This requires that we use a weird bias 6911 // of 0xb000, however (again, this has been exhaustively tested). 6912 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6913 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6914 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6915 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 6916 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6917 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6918 // Convert back to short. 6919 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6920 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6921 return X; 6922 } 6923 6924 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 6925 SelectionDAG &DAG) { 6926 // TODO: Should this propagate fast-math-flags? 6927 6928 SDValue N2; 6929 // Convert to float. 6930 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6931 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6932 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6933 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6934 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6935 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6936 6937 // Use reciprocal estimate and one refinement step. 6938 // float4 recip = vrecpeq_f32(yf); 6939 // recip *= vrecpsq_f32(yf, recip); 6940 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6941 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6942 N1); 6943 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6944 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6945 N1, N2); 6946 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6947 // Because short has a smaller range than ushort, we can actually get away 6948 // with only a single newton step. This requires that we use a weird bias 6949 // of 89, however (again, this has been exhaustively tested). 6950 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6951 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6952 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6953 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 6954 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6955 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6956 // Convert back to integer and return. 6957 // return vmovn_s32(vcvt_s32_f32(result)); 6958 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6959 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6960 return N0; 6961 } 6962 6963 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6964 EVT VT = Op.getValueType(); 6965 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6966 "unexpected type for custom-lowering ISD::SDIV"); 6967 6968 SDLoc dl(Op); 6969 SDValue N0 = Op.getOperand(0); 6970 SDValue N1 = Op.getOperand(1); 6971 SDValue N2, N3; 6972 6973 if (VT == MVT::v8i8) { 6974 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6975 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6976 6977 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6978 DAG.getIntPtrConstant(4, dl)); 6979 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6980 DAG.getIntPtrConstant(4, dl)); 6981 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6982 DAG.getIntPtrConstant(0, dl)); 6983 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6984 DAG.getIntPtrConstant(0, dl)); 6985 6986 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6987 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6988 6989 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6990 N0 = LowerCONCAT_VECTORS(N0, DAG); 6991 6992 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6993 return N0; 6994 } 6995 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6996 } 6997 6998 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6999 // TODO: Should this propagate fast-math-flags? 7000 EVT VT = Op.getValueType(); 7001 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7002 "unexpected type for custom-lowering ISD::UDIV"); 7003 7004 SDLoc dl(Op); 7005 SDValue N0 = Op.getOperand(0); 7006 SDValue N1 = Op.getOperand(1); 7007 SDValue N2, N3; 7008 7009 if (VT == MVT::v8i8) { 7010 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7011 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7012 7013 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7014 DAG.getIntPtrConstant(4, dl)); 7015 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7016 DAG.getIntPtrConstant(4, dl)); 7017 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7018 DAG.getIntPtrConstant(0, dl)); 7019 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7020 DAG.getIntPtrConstant(0, dl)); 7021 7022 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7023 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7024 7025 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7026 N0 = LowerCONCAT_VECTORS(N0, DAG); 7027 7028 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7029 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7030 MVT::i32), 7031 N0); 7032 return N0; 7033 } 7034 7035 // v4i16 sdiv ... Convert to float. 7036 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7037 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7038 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7039 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7040 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7041 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7042 7043 // Use reciprocal estimate and two refinement steps. 7044 // float4 recip = vrecpeq_f32(yf); 7045 // recip *= vrecpsq_f32(yf, recip); 7046 // recip *= vrecpsq_f32(yf, recip); 7047 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7048 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7049 BN1); 7050 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7051 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7052 BN1, N2); 7053 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7054 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7055 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7056 BN1, N2); 7057 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7058 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7059 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7060 // and that it will never cause us to return an answer too large). 7061 // float4 result = as_float4(as_int4(xf*recip) + 2); 7062 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7063 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7064 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7065 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7066 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7067 // Convert back to integer and return. 7068 // return vmovn_u32(vcvt_s32_f32(result)); 7069 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7070 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7071 return N0; 7072 } 7073 7074 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7075 EVT VT = Op.getNode()->getValueType(0); 7076 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7077 7078 unsigned Opc; 7079 bool ExtraOp = false; 7080 switch (Op.getOpcode()) { 7081 default: llvm_unreachable("Invalid code"); 7082 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7083 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7084 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7085 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7086 } 7087 7088 if (!ExtraOp) 7089 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7090 Op.getOperand(1)); 7091 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7092 Op.getOperand(1), Op.getOperand(2)); 7093 } 7094 7095 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7096 assert(Subtarget->isTargetDarwin()); 7097 7098 // For iOS, we want to call an alternative entry point: __sincos_stret, 7099 // return values are passed via sret. 7100 SDLoc dl(Op); 7101 SDValue Arg = Op.getOperand(0); 7102 EVT ArgVT = Arg.getValueType(); 7103 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7104 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7105 7106 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7107 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7108 7109 // Pair of floats / doubles used to pass the result. 7110 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 7111 auto &DL = DAG.getDataLayout(); 7112 7113 ArgListTy Args; 7114 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7115 SDValue SRet; 7116 if (ShouldUseSRet) { 7117 // Create stack object for sret. 7118 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7119 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7120 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7121 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7122 7123 ArgListEntry Entry; 7124 Entry.Node = SRet; 7125 Entry.Ty = RetTy->getPointerTo(); 7126 Entry.isSExt = false; 7127 Entry.isZExt = false; 7128 Entry.isSRet = true; 7129 Args.push_back(Entry); 7130 RetTy = Type::getVoidTy(*DAG.getContext()); 7131 } 7132 7133 ArgListEntry Entry; 7134 Entry.Node = Arg; 7135 Entry.Ty = ArgTy; 7136 Entry.isSExt = false; 7137 Entry.isZExt = false; 7138 Args.push_back(Entry); 7139 7140 const char *LibcallName = 7141 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 7142 RTLIB::Libcall LC = 7143 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 7144 CallingConv::ID CC = getLibcallCallingConv(LC); 7145 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7146 7147 TargetLowering::CallLoweringInfo CLI(DAG); 7148 CLI.setDebugLoc(dl) 7149 .setChain(DAG.getEntryNode()) 7150 .setCallee(CC, RetTy, Callee, std::move(Args)) 7151 .setDiscardResult(ShouldUseSRet); 7152 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7153 7154 if (!ShouldUseSRet) 7155 return CallResult.first; 7156 7157 SDValue LoadSin = 7158 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7159 7160 // Address of cos field. 7161 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7162 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7163 SDValue LoadCos = 7164 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7165 7166 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7167 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7168 LoadSin.getValue(0), LoadCos.getValue(0)); 7169 } 7170 7171 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7172 bool Signed, 7173 SDValue &Chain) const { 7174 EVT VT = Op.getValueType(); 7175 assert((VT == MVT::i32 || VT == MVT::i64) && 7176 "unexpected type for custom lowering DIV"); 7177 SDLoc dl(Op); 7178 7179 const auto &DL = DAG.getDataLayout(); 7180 const auto &TLI = DAG.getTargetLoweringInfo(); 7181 7182 const char *Name = nullptr; 7183 if (Signed) 7184 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7185 else 7186 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7187 7188 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7189 7190 ARMTargetLowering::ArgListTy Args; 7191 7192 for (auto AI : {1, 0}) { 7193 ArgListEntry Arg; 7194 Arg.Node = Op.getOperand(AI); 7195 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7196 Args.push_back(Arg); 7197 } 7198 7199 CallLoweringInfo CLI(DAG); 7200 CLI.setDebugLoc(dl) 7201 .setChain(Chain) 7202 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7203 ES, std::move(Args)); 7204 7205 return LowerCallTo(CLI).first; 7206 } 7207 7208 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7209 bool Signed) const { 7210 assert(Op.getValueType() == MVT::i32 && 7211 "unexpected type for custom lowering DIV"); 7212 SDLoc dl(Op); 7213 7214 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7215 DAG.getEntryNode(), Op.getOperand(1)); 7216 7217 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7218 } 7219 7220 void ARMTargetLowering::ExpandDIV_Windows( 7221 SDValue Op, SelectionDAG &DAG, bool Signed, 7222 SmallVectorImpl<SDValue> &Results) const { 7223 const auto &DL = DAG.getDataLayout(); 7224 const auto &TLI = DAG.getTargetLoweringInfo(); 7225 7226 assert(Op.getValueType() == MVT::i64 && 7227 "unexpected type for custom lowering DIV"); 7228 SDLoc dl(Op); 7229 7230 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 7231 DAG.getConstant(0, dl, MVT::i32)); 7232 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 7233 DAG.getConstant(1, dl, MVT::i32)); 7234 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 7235 7236 SDValue DBZCHK = 7237 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 7238 7239 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7240 7241 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7242 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7243 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7244 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7245 7246 Results.push_back(Lower); 7247 Results.push_back(Upper); 7248 } 7249 7250 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7251 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7252 // Acquire/Release load/store is not legal for targets without a dmb or 7253 // equivalent available. 7254 return SDValue(); 7255 7256 // Monotonic load/store is legal for all targets. 7257 return Op; 7258 } 7259 7260 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7261 SmallVectorImpl<SDValue> &Results, 7262 SelectionDAG &DAG, 7263 const ARMSubtarget *Subtarget) { 7264 SDLoc DL(N); 7265 // Under Power Management extensions, the cycle-count is: 7266 // mrc p15, #0, <Rt>, c9, c13, #0 7267 SDValue Ops[] = { N->getOperand(0), // Chain 7268 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7269 DAG.getConstant(15, DL, MVT::i32), 7270 DAG.getConstant(0, DL, MVT::i32), 7271 DAG.getConstant(9, DL, MVT::i32), 7272 DAG.getConstant(13, DL, MVT::i32), 7273 DAG.getConstant(0, DL, MVT::i32) 7274 }; 7275 7276 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7277 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7278 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7279 DAG.getConstant(0, DL, MVT::i32))); 7280 Results.push_back(Cycles32.getValue(1)); 7281 } 7282 7283 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7284 SDLoc dl(V.getNode()); 7285 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7286 SDValue VHi = DAG.getAnyExtOrTrunc( 7287 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7288 dl, MVT::i32); 7289 SDValue RegClass = 7290 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7291 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7292 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7293 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7294 return SDValue( 7295 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7296 } 7297 7298 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7299 SmallVectorImpl<SDValue> & Results, 7300 SelectionDAG &DAG) { 7301 assert(N->getValueType(0) == MVT::i64 && 7302 "AtomicCmpSwap on types less than 64 should be legal"); 7303 SDValue Ops[] = {N->getOperand(1), 7304 createGPRPairNode(DAG, N->getOperand(2)), 7305 createGPRPairNode(DAG, N->getOperand(3)), 7306 N->getOperand(0)}; 7307 SDNode *CmpSwap = DAG.getMachineNode( 7308 ARM::CMP_SWAP_64, SDLoc(N), 7309 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7310 7311 MachineFunction &MF = DAG.getMachineFunction(); 7312 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7313 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7314 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7315 7316 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7317 SDValue(CmpSwap, 0))); 7318 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7319 SDValue(CmpSwap, 0))); 7320 Results.push_back(SDValue(CmpSwap, 2)); 7321 } 7322 7323 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7324 switch (Op.getOpcode()) { 7325 default: llvm_unreachable("Don't know how to custom lower this!"); 7326 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7327 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7328 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7329 case ISD::GlobalAddress: 7330 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7331 default: llvm_unreachable("unknown object format"); 7332 case Triple::COFF: 7333 return LowerGlobalAddressWindows(Op, DAG); 7334 case Triple::ELF: 7335 return LowerGlobalAddressELF(Op, DAG); 7336 case Triple::MachO: 7337 return LowerGlobalAddressDarwin(Op, DAG); 7338 } 7339 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7340 case ISD::SELECT: return LowerSELECT(Op, DAG); 7341 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7342 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7343 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7344 case ISD::VASTART: return LowerVASTART(Op, DAG); 7345 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7346 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7347 case ISD::SINT_TO_FP: 7348 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7349 case ISD::FP_TO_SINT: 7350 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7351 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7352 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7353 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7354 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7355 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7356 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7357 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7358 Subtarget); 7359 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7360 case ISD::SHL: 7361 case ISD::SRL: 7362 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7363 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7364 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7365 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7366 case ISD::SRL_PARTS: 7367 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7368 case ISD::CTTZ: 7369 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7370 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7371 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7372 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7373 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7374 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7375 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7376 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7377 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7378 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7379 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7380 case ISD::MUL: return LowerMUL(Op, DAG); 7381 case ISD::SDIV: 7382 if (Subtarget->isTargetWindows()) 7383 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7384 return LowerSDIV(Op, DAG); 7385 case ISD::UDIV: 7386 if (Subtarget->isTargetWindows()) 7387 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7388 return LowerUDIV(Op, DAG); 7389 case ISD::ADDC: 7390 case ISD::ADDE: 7391 case ISD::SUBC: 7392 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7393 case ISD::SADDO: 7394 case ISD::UADDO: 7395 case ISD::SSUBO: 7396 case ISD::USUBO: 7397 return LowerXALUO(Op, DAG); 7398 case ISD::ATOMIC_LOAD: 7399 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7400 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7401 case ISD::SDIVREM: 7402 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7403 case ISD::DYNAMIC_STACKALLOC: 7404 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7405 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7406 llvm_unreachable("Don't know how to custom lower this!"); 7407 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7408 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7409 case ARMISD::WIN__DBZCHK: return SDValue(); 7410 } 7411 } 7412 7413 /// ReplaceNodeResults - Replace the results of node with an illegal result 7414 /// type with new values built out of custom code. 7415 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7416 SmallVectorImpl<SDValue> &Results, 7417 SelectionDAG &DAG) const { 7418 SDValue Res; 7419 switch (N->getOpcode()) { 7420 default: 7421 llvm_unreachable("Don't know how to custom expand this!"); 7422 case ISD::READ_REGISTER: 7423 ExpandREAD_REGISTER(N, Results, DAG); 7424 break; 7425 case ISD::BITCAST: 7426 Res = ExpandBITCAST(N, DAG); 7427 break; 7428 case ISD::SRL: 7429 case ISD::SRA: 7430 Res = Expand64BitShift(N, DAG, Subtarget); 7431 break; 7432 case ISD::SREM: 7433 case ISD::UREM: 7434 Res = LowerREM(N, DAG); 7435 break; 7436 case ISD::SDIVREM: 7437 case ISD::UDIVREM: 7438 Res = LowerDivRem(SDValue(N, 0), DAG); 7439 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7440 Results.push_back(Res.getValue(0)); 7441 Results.push_back(Res.getValue(1)); 7442 return; 7443 case ISD::READCYCLECOUNTER: 7444 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7445 return; 7446 case ISD::UDIV: 7447 case ISD::SDIV: 7448 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7449 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7450 Results); 7451 case ISD::ATOMIC_CMP_SWAP: 7452 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7453 return; 7454 } 7455 if (Res.getNode()) 7456 Results.push_back(Res); 7457 } 7458 7459 //===----------------------------------------------------------------------===// 7460 // ARM Scheduler Hooks 7461 //===----------------------------------------------------------------------===// 7462 7463 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7464 /// registers the function context. 7465 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7466 MachineBasicBlock *MBB, 7467 MachineBasicBlock *DispatchBB, 7468 int FI) const { 7469 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7470 "ROPI/RWPI not currently supported with SjLj"); 7471 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7472 DebugLoc dl = MI.getDebugLoc(); 7473 MachineFunction *MF = MBB->getParent(); 7474 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7475 MachineConstantPool *MCP = MF->getConstantPool(); 7476 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7477 const Function *F = MF->getFunction(); 7478 7479 bool isThumb = Subtarget->isThumb(); 7480 bool isThumb2 = Subtarget->isThumb2(); 7481 7482 unsigned PCLabelId = AFI->createPICLabelUId(); 7483 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7484 ARMConstantPoolValue *CPV = 7485 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7486 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7487 7488 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7489 : &ARM::GPRRegClass; 7490 7491 // Grab constant pool and fixed stack memory operands. 7492 MachineMemOperand *CPMMO = 7493 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7494 MachineMemOperand::MOLoad, 4, 4); 7495 7496 MachineMemOperand *FIMMOSt = 7497 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7498 MachineMemOperand::MOStore, 4, 4); 7499 7500 // Load the address of the dispatch MBB into the jump buffer. 7501 if (isThumb2) { 7502 // Incoming value: jbuf 7503 // ldr.n r5, LCPI1_1 7504 // orr r5, r5, #1 7505 // add r5, pc 7506 // str r5, [$jbuf, #+4] ; &jbuf[1] 7507 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7508 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7509 .addConstantPoolIndex(CPI) 7510 .addMemOperand(CPMMO)); 7511 // Set the low bit because of thumb mode. 7512 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7513 AddDefaultCC( 7514 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7515 .addReg(NewVReg1, RegState::Kill) 7516 .addImm(0x01))); 7517 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7518 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7519 .addReg(NewVReg2, RegState::Kill) 7520 .addImm(PCLabelId); 7521 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7522 .addReg(NewVReg3, RegState::Kill) 7523 .addFrameIndex(FI) 7524 .addImm(36) // &jbuf[1] :: pc 7525 .addMemOperand(FIMMOSt)); 7526 } else if (isThumb) { 7527 // Incoming value: jbuf 7528 // ldr.n r1, LCPI1_4 7529 // add r1, pc 7530 // mov r2, #1 7531 // orrs r1, r2 7532 // add r2, $jbuf, #+4 ; &jbuf[1] 7533 // str r1, [r2] 7534 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7535 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7536 .addConstantPoolIndex(CPI) 7537 .addMemOperand(CPMMO)); 7538 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7539 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7540 .addReg(NewVReg1, RegState::Kill) 7541 .addImm(PCLabelId); 7542 // Set the low bit because of thumb mode. 7543 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7544 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7545 .addReg(ARM::CPSR, RegState::Define) 7546 .addImm(1)); 7547 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7548 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7549 .addReg(ARM::CPSR, RegState::Define) 7550 .addReg(NewVReg2, RegState::Kill) 7551 .addReg(NewVReg3, RegState::Kill)); 7552 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7553 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7554 .addFrameIndex(FI) 7555 .addImm(36); // &jbuf[1] :: pc 7556 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7557 .addReg(NewVReg4, RegState::Kill) 7558 .addReg(NewVReg5, RegState::Kill) 7559 .addImm(0) 7560 .addMemOperand(FIMMOSt)); 7561 } else { 7562 // Incoming value: jbuf 7563 // ldr r1, LCPI1_1 7564 // add r1, pc, r1 7565 // str r1, [$jbuf, #+4] ; &jbuf[1] 7566 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7567 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7568 .addConstantPoolIndex(CPI) 7569 .addImm(0) 7570 .addMemOperand(CPMMO)); 7571 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7572 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7573 .addReg(NewVReg1, RegState::Kill) 7574 .addImm(PCLabelId)); 7575 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7576 .addReg(NewVReg2, RegState::Kill) 7577 .addFrameIndex(FI) 7578 .addImm(36) // &jbuf[1] :: pc 7579 .addMemOperand(FIMMOSt)); 7580 } 7581 } 7582 7583 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 7584 MachineBasicBlock *MBB) const { 7585 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7586 DebugLoc dl = MI.getDebugLoc(); 7587 MachineFunction *MF = MBB->getParent(); 7588 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7589 MachineFrameInfo &MFI = MF->getFrameInfo(); 7590 int FI = MFI.getFunctionContextIndex(); 7591 7592 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7593 : &ARM::GPRnopcRegClass; 7594 7595 // Get a mapping of the call site numbers to all of the landing pads they're 7596 // associated with. 7597 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7598 unsigned MaxCSNum = 0; 7599 MachineModuleInfo &MMI = MF->getMMI(); 7600 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7601 ++BB) { 7602 if (!BB->isEHPad()) continue; 7603 7604 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7605 // pad. 7606 for (MachineBasicBlock::iterator 7607 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7608 if (!II->isEHLabel()) continue; 7609 7610 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7611 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7612 7613 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7614 for (SmallVectorImpl<unsigned>::iterator 7615 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7616 CSI != CSE; ++CSI) { 7617 CallSiteNumToLPad[*CSI].push_back(&*BB); 7618 MaxCSNum = std::max(MaxCSNum, *CSI); 7619 } 7620 break; 7621 } 7622 } 7623 7624 // Get an ordered list of the machine basic blocks for the jump table. 7625 std::vector<MachineBasicBlock*> LPadList; 7626 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7627 LPadList.reserve(CallSiteNumToLPad.size()); 7628 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7629 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7630 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7631 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7632 LPadList.push_back(*II); 7633 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7634 } 7635 } 7636 7637 assert(!LPadList.empty() && 7638 "No landing pad destinations for the dispatch jump table!"); 7639 7640 // Create the jump table and associated information. 7641 MachineJumpTableInfo *JTI = 7642 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7643 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7644 7645 // Create the MBBs for the dispatch code. 7646 7647 // Shove the dispatch's address into the return slot in the function context. 7648 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7649 DispatchBB->setIsEHPad(); 7650 7651 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7652 unsigned trap_opcode; 7653 if (Subtarget->isThumb()) 7654 trap_opcode = ARM::tTRAP; 7655 else 7656 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7657 7658 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7659 DispatchBB->addSuccessor(TrapBB); 7660 7661 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7662 DispatchBB->addSuccessor(DispContBB); 7663 7664 // Insert and MBBs. 7665 MF->insert(MF->end(), DispatchBB); 7666 MF->insert(MF->end(), DispContBB); 7667 MF->insert(MF->end(), TrapBB); 7668 7669 // Insert code into the entry block that creates and registers the function 7670 // context. 7671 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7672 7673 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7674 MachinePointerInfo::getFixedStack(*MF, FI), 7675 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7676 7677 MachineInstrBuilder MIB; 7678 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7679 7680 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7681 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7682 7683 // Add a register mask with no preserved registers. This results in all 7684 // registers being marked as clobbered. 7685 MIB.addRegMask(RI.getNoPreservedMask()); 7686 7687 bool IsPositionIndependent = isPositionIndependent(); 7688 unsigned NumLPads = LPadList.size(); 7689 if (Subtarget->isThumb2()) { 7690 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7691 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7692 .addFrameIndex(FI) 7693 .addImm(4) 7694 .addMemOperand(FIMMOLd)); 7695 7696 if (NumLPads < 256) { 7697 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7698 .addReg(NewVReg1) 7699 .addImm(LPadList.size())); 7700 } else { 7701 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7702 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7703 .addImm(NumLPads & 0xFFFF)); 7704 7705 unsigned VReg2 = VReg1; 7706 if ((NumLPads & 0xFFFF0000) != 0) { 7707 VReg2 = MRI->createVirtualRegister(TRC); 7708 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7709 .addReg(VReg1) 7710 .addImm(NumLPads >> 16)); 7711 } 7712 7713 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7714 .addReg(NewVReg1) 7715 .addReg(VReg2)); 7716 } 7717 7718 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7719 .addMBB(TrapBB) 7720 .addImm(ARMCC::HI) 7721 .addReg(ARM::CPSR); 7722 7723 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7724 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7725 .addJumpTableIndex(MJTI)); 7726 7727 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7728 AddDefaultCC( 7729 AddDefaultPred( 7730 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7731 .addReg(NewVReg3, RegState::Kill) 7732 .addReg(NewVReg1) 7733 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7734 7735 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7736 .addReg(NewVReg4, RegState::Kill) 7737 .addReg(NewVReg1) 7738 .addJumpTableIndex(MJTI); 7739 } else if (Subtarget->isThumb()) { 7740 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7741 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7742 .addFrameIndex(FI) 7743 .addImm(1) 7744 .addMemOperand(FIMMOLd)); 7745 7746 if (NumLPads < 256) { 7747 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7748 .addReg(NewVReg1) 7749 .addImm(NumLPads)); 7750 } else { 7751 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7752 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7753 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7754 7755 // MachineConstantPool wants an explicit alignment. 7756 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7757 if (Align == 0) 7758 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7759 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7760 7761 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7762 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7763 .addReg(VReg1, RegState::Define) 7764 .addConstantPoolIndex(Idx)); 7765 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7766 .addReg(NewVReg1) 7767 .addReg(VReg1)); 7768 } 7769 7770 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7771 .addMBB(TrapBB) 7772 .addImm(ARMCC::HI) 7773 .addReg(ARM::CPSR); 7774 7775 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7776 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7777 .addReg(ARM::CPSR, RegState::Define) 7778 .addReg(NewVReg1) 7779 .addImm(2)); 7780 7781 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7782 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7783 .addJumpTableIndex(MJTI)); 7784 7785 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7786 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7787 .addReg(ARM::CPSR, RegState::Define) 7788 .addReg(NewVReg2, RegState::Kill) 7789 .addReg(NewVReg3)); 7790 7791 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7792 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7793 7794 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7795 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7796 .addReg(NewVReg4, RegState::Kill) 7797 .addImm(0) 7798 .addMemOperand(JTMMOLd)); 7799 7800 unsigned NewVReg6 = NewVReg5; 7801 if (IsPositionIndependent) { 7802 NewVReg6 = MRI->createVirtualRegister(TRC); 7803 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7804 .addReg(ARM::CPSR, RegState::Define) 7805 .addReg(NewVReg5, RegState::Kill) 7806 .addReg(NewVReg3)); 7807 } 7808 7809 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7810 .addReg(NewVReg6, RegState::Kill) 7811 .addJumpTableIndex(MJTI); 7812 } else { 7813 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7814 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7815 .addFrameIndex(FI) 7816 .addImm(4) 7817 .addMemOperand(FIMMOLd)); 7818 7819 if (NumLPads < 256) { 7820 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7821 .addReg(NewVReg1) 7822 .addImm(NumLPads)); 7823 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7824 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7825 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7826 .addImm(NumLPads & 0xFFFF)); 7827 7828 unsigned VReg2 = VReg1; 7829 if ((NumLPads & 0xFFFF0000) != 0) { 7830 VReg2 = MRI->createVirtualRegister(TRC); 7831 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7832 .addReg(VReg1) 7833 .addImm(NumLPads >> 16)); 7834 } 7835 7836 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7837 .addReg(NewVReg1) 7838 .addReg(VReg2)); 7839 } else { 7840 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7841 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7842 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7843 7844 // MachineConstantPool wants an explicit alignment. 7845 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7846 if (Align == 0) 7847 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7848 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7849 7850 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7851 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7852 .addReg(VReg1, RegState::Define) 7853 .addConstantPoolIndex(Idx) 7854 .addImm(0)); 7855 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7856 .addReg(NewVReg1) 7857 .addReg(VReg1, RegState::Kill)); 7858 } 7859 7860 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7861 .addMBB(TrapBB) 7862 .addImm(ARMCC::HI) 7863 .addReg(ARM::CPSR); 7864 7865 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7866 AddDefaultCC( 7867 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7868 .addReg(NewVReg1) 7869 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7870 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7871 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7872 .addJumpTableIndex(MJTI)); 7873 7874 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7875 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7876 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7877 AddDefaultPred( 7878 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7879 .addReg(NewVReg3, RegState::Kill) 7880 .addReg(NewVReg4) 7881 .addImm(0) 7882 .addMemOperand(JTMMOLd)); 7883 7884 if (IsPositionIndependent) { 7885 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7886 .addReg(NewVReg5, RegState::Kill) 7887 .addReg(NewVReg4) 7888 .addJumpTableIndex(MJTI); 7889 } else { 7890 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7891 .addReg(NewVReg5, RegState::Kill) 7892 .addJumpTableIndex(MJTI); 7893 } 7894 } 7895 7896 // Add the jump table entries as successors to the MBB. 7897 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7898 for (std::vector<MachineBasicBlock*>::iterator 7899 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7900 MachineBasicBlock *CurMBB = *I; 7901 if (SeenMBBs.insert(CurMBB).second) 7902 DispContBB->addSuccessor(CurMBB); 7903 } 7904 7905 // N.B. the order the invoke BBs are processed in doesn't matter here. 7906 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7907 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7908 for (MachineBasicBlock *BB : InvokeBBs) { 7909 7910 // Remove the landing pad successor from the invoke block and replace it 7911 // with the new dispatch block. 7912 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7913 BB->succ_end()); 7914 while (!Successors.empty()) { 7915 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7916 if (SMBB->isEHPad()) { 7917 BB->removeSuccessor(SMBB); 7918 MBBLPads.push_back(SMBB); 7919 } 7920 } 7921 7922 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7923 BB->normalizeSuccProbs(); 7924 7925 // Find the invoke call and mark all of the callee-saved registers as 7926 // 'implicit defined' so that they're spilled. This prevents code from 7927 // moving instructions to before the EH block, where they will never be 7928 // executed. 7929 for (MachineBasicBlock::reverse_iterator 7930 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7931 if (!II->isCall()) continue; 7932 7933 DenseMap<unsigned, bool> DefRegs; 7934 for (MachineInstr::mop_iterator 7935 OI = II->operands_begin(), OE = II->operands_end(); 7936 OI != OE; ++OI) { 7937 if (!OI->isReg()) continue; 7938 DefRegs[OI->getReg()] = true; 7939 } 7940 7941 MachineInstrBuilder MIB(*MF, &*II); 7942 7943 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7944 unsigned Reg = SavedRegs[i]; 7945 if (Subtarget->isThumb2() && 7946 !ARM::tGPRRegClass.contains(Reg) && 7947 !ARM::hGPRRegClass.contains(Reg)) 7948 continue; 7949 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7950 continue; 7951 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7952 continue; 7953 if (!DefRegs[Reg]) 7954 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7955 } 7956 7957 break; 7958 } 7959 } 7960 7961 // Mark all former landing pads as non-landing pads. The dispatch is the only 7962 // landing pad now. 7963 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7964 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7965 (*I)->setIsEHPad(false); 7966 7967 // The instruction is gone now. 7968 MI.eraseFromParent(); 7969 } 7970 7971 static 7972 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7973 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7974 E = MBB->succ_end(); I != E; ++I) 7975 if (*I != Succ) 7976 return *I; 7977 llvm_unreachable("Expecting a BB with two successors!"); 7978 } 7979 7980 /// Return the load opcode for a given load size. If load size >= 8, 7981 /// neon opcode will be returned. 7982 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7983 if (LdSize >= 8) 7984 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7985 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7986 if (IsThumb1) 7987 return LdSize == 4 ? ARM::tLDRi 7988 : LdSize == 2 ? ARM::tLDRHi 7989 : LdSize == 1 ? ARM::tLDRBi : 0; 7990 if (IsThumb2) 7991 return LdSize == 4 ? ARM::t2LDR_POST 7992 : LdSize == 2 ? ARM::t2LDRH_POST 7993 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7994 return LdSize == 4 ? ARM::LDR_POST_IMM 7995 : LdSize == 2 ? ARM::LDRH_POST 7996 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7997 } 7998 7999 /// Return the store opcode for a given store size. If store size >= 8, 8000 /// neon opcode will be returned. 8001 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8002 if (StSize >= 8) 8003 return StSize == 16 ? ARM::VST1q32wb_fixed 8004 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8005 if (IsThumb1) 8006 return StSize == 4 ? ARM::tSTRi 8007 : StSize == 2 ? ARM::tSTRHi 8008 : StSize == 1 ? ARM::tSTRBi : 0; 8009 if (IsThumb2) 8010 return StSize == 4 ? ARM::t2STR_POST 8011 : StSize == 2 ? ARM::t2STRH_POST 8012 : StSize == 1 ? ARM::t2STRB_POST : 0; 8013 return StSize == 4 ? ARM::STR_POST_IMM 8014 : StSize == 2 ? ARM::STRH_POST 8015 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8016 } 8017 8018 /// Emit a post-increment load operation with given size. The instructions 8019 /// will be added to BB at Pos. 8020 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8021 const TargetInstrInfo *TII, const DebugLoc &dl, 8022 unsigned LdSize, unsigned Data, unsigned AddrIn, 8023 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8024 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8025 assert(LdOpc != 0 && "Should have a load opcode"); 8026 if (LdSize >= 8) { 8027 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8028 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 8029 .addImm(0)); 8030 } else if (IsThumb1) { 8031 // load + update AddrIn 8032 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8033 .addReg(AddrIn).addImm(0)); 8034 MachineInstrBuilder MIB = 8035 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 8036 MIB = AddDefaultT1CC(MIB); 8037 MIB.addReg(AddrIn).addImm(LdSize); 8038 AddDefaultPred(MIB); 8039 } else if (IsThumb2) { 8040 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8041 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 8042 .addImm(LdSize)); 8043 } else { // arm 8044 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8045 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 8046 .addReg(0).addImm(LdSize)); 8047 } 8048 } 8049 8050 /// Emit a post-increment store operation with given size. The instructions 8051 /// will be added to BB at Pos. 8052 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8053 const TargetInstrInfo *TII, const DebugLoc &dl, 8054 unsigned StSize, unsigned Data, unsigned AddrIn, 8055 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8056 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8057 assert(StOpc != 0 && "Should have a store opcode"); 8058 if (StSize >= 8) { 8059 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8060 .addReg(AddrIn).addImm(0).addReg(Data)); 8061 } else if (IsThumb1) { 8062 // store + update AddrIn 8063 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 8064 .addReg(AddrIn).addImm(0)); 8065 MachineInstrBuilder MIB = 8066 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 8067 MIB = AddDefaultT1CC(MIB); 8068 MIB.addReg(AddrIn).addImm(StSize); 8069 AddDefaultPred(MIB); 8070 } else if (IsThumb2) { 8071 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8072 .addReg(Data).addReg(AddrIn).addImm(StSize)); 8073 } else { // arm 8074 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8075 .addReg(Data).addReg(AddrIn).addReg(0) 8076 .addImm(StSize)); 8077 } 8078 } 8079 8080 MachineBasicBlock * 8081 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8082 MachineBasicBlock *BB) const { 8083 // This pseudo instruction has 3 operands: dst, src, size 8084 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8085 // Otherwise, we will generate unrolled scalar copies. 8086 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8087 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8088 MachineFunction::iterator It = ++BB->getIterator(); 8089 8090 unsigned dest = MI.getOperand(0).getReg(); 8091 unsigned src = MI.getOperand(1).getReg(); 8092 unsigned SizeVal = MI.getOperand(2).getImm(); 8093 unsigned Align = MI.getOperand(3).getImm(); 8094 DebugLoc dl = MI.getDebugLoc(); 8095 8096 MachineFunction *MF = BB->getParent(); 8097 MachineRegisterInfo &MRI = MF->getRegInfo(); 8098 unsigned UnitSize = 0; 8099 const TargetRegisterClass *TRC = nullptr; 8100 const TargetRegisterClass *VecTRC = nullptr; 8101 8102 bool IsThumb1 = Subtarget->isThumb1Only(); 8103 bool IsThumb2 = Subtarget->isThumb2(); 8104 bool IsThumb = Subtarget->isThumb(); 8105 8106 if (Align & 1) { 8107 UnitSize = 1; 8108 } else if (Align & 2) { 8109 UnitSize = 2; 8110 } else { 8111 // Check whether we can use NEON instructions. 8112 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 8113 Subtarget->hasNEON()) { 8114 if ((Align % 16 == 0) && SizeVal >= 16) 8115 UnitSize = 16; 8116 else if ((Align % 8 == 0) && SizeVal >= 8) 8117 UnitSize = 8; 8118 } 8119 // Can't use NEON instructions. 8120 if (UnitSize == 0) 8121 UnitSize = 4; 8122 } 8123 8124 // Select the correct opcode and register class for unit size load/store 8125 bool IsNeon = UnitSize >= 8; 8126 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8127 if (IsNeon) 8128 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8129 : UnitSize == 8 ? &ARM::DPRRegClass 8130 : nullptr; 8131 8132 unsigned BytesLeft = SizeVal % UnitSize; 8133 unsigned LoopSize = SizeVal - BytesLeft; 8134 8135 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8136 // Use LDR and STR to copy. 8137 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8138 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8139 unsigned srcIn = src; 8140 unsigned destIn = dest; 8141 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8142 unsigned srcOut = MRI.createVirtualRegister(TRC); 8143 unsigned destOut = MRI.createVirtualRegister(TRC); 8144 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8145 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8146 IsThumb1, IsThumb2); 8147 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8148 IsThumb1, IsThumb2); 8149 srcIn = srcOut; 8150 destIn = destOut; 8151 } 8152 8153 // Handle the leftover bytes with LDRB and STRB. 8154 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8155 // [destOut] = STRB_POST(scratch, destIn, 1) 8156 for (unsigned i = 0; i < BytesLeft; i++) { 8157 unsigned srcOut = MRI.createVirtualRegister(TRC); 8158 unsigned destOut = MRI.createVirtualRegister(TRC); 8159 unsigned scratch = MRI.createVirtualRegister(TRC); 8160 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8161 IsThumb1, IsThumb2); 8162 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8163 IsThumb1, IsThumb2); 8164 srcIn = srcOut; 8165 destIn = destOut; 8166 } 8167 MI.eraseFromParent(); // The instruction is gone now. 8168 return BB; 8169 } 8170 8171 // Expand the pseudo op to a loop. 8172 // thisMBB: 8173 // ... 8174 // movw varEnd, # --> with thumb2 8175 // movt varEnd, # 8176 // ldrcp varEnd, idx --> without thumb2 8177 // fallthrough --> loopMBB 8178 // loopMBB: 8179 // PHI varPhi, varEnd, varLoop 8180 // PHI srcPhi, src, srcLoop 8181 // PHI destPhi, dst, destLoop 8182 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8183 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8184 // subs varLoop, varPhi, #UnitSize 8185 // bne loopMBB 8186 // fallthrough --> exitMBB 8187 // exitMBB: 8188 // epilogue to handle left-over bytes 8189 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8190 // [destOut] = STRB_POST(scratch, destLoop, 1) 8191 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8192 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8193 MF->insert(It, loopMBB); 8194 MF->insert(It, exitMBB); 8195 8196 // Transfer the remainder of BB and its successor edges to exitMBB. 8197 exitMBB->splice(exitMBB->begin(), BB, 8198 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8199 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8200 8201 // Load an immediate to varEnd. 8202 unsigned varEnd = MRI.createVirtualRegister(TRC); 8203 if (Subtarget->useMovt(*MF)) { 8204 unsigned Vtmp = varEnd; 8205 if ((LoopSize & 0xFFFF0000) != 0) 8206 Vtmp = MRI.createVirtualRegister(TRC); 8207 AddDefaultPred(BuildMI(BB, dl, 8208 TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), 8209 Vtmp).addImm(LoopSize & 0xFFFF)); 8210 8211 if ((LoopSize & 0xFFFF0000) != 0) 8212 AddDefaultPred(BuildMI(BB, dl, 8213 TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), 8214 varEnd) 8215 .addReg(Vtmp) 8216 .addImm(LoopSize >> 16)); 8217 } else { 8218 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8219 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8220 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8221 8222 // MachineConstantPool wants an explicit alignment. 8223 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8224 if (Align == 0) 8225 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8226 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8227 8228 if (IsThumb) 8229 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 8230 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 8231 else 8232 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 8233 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 8234 } 8235 BB->addSuccessor(loopMBB); 8236 8237 // Generate the loop body: 8238 // varPhi = PHI(varLoop, varEnd) 8239 // srcPhi = PHI(srcLoop, src) 8240 // destPhi = PHI(destLoop, dst) 8241 MachineBasicBlock *entryBB = BB; 8242 BB = loopMBB; 8243 unsigned varLoop = MRI.createVirtualRegister(TRC); 8244 unsigned varPhi = MRI.createVirtualRegister(TRC); 8245 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8246 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8247 unsigned destLoop = MRI.createVirtualRegister(TRC); 8248 unsigned destPhi = MRI.createVirtualRegister(TRC); 8249 8250 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8251 .addReg(varLoop).addMBB(loopMBB) 8252 .addReg(varEnd).addMBB(entryBB); 8253 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8254 .addReg(srcLoop).addMBB(loopMBB) 8255 .addReg(src).addMBB(entryBB); 8256 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8257 .addReg(destLoop).addMBB(loopMBB) 8258 .addReg(dest).addMBB(entryBB); 8259 8260 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8261 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8262 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8263 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8264 IsThumb1, IsThumb2); 8265 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8266 IsThumb1, IsThumb2); 8267 8268 // Decrement loop variable by UnitSize. 8269 if (IsThumb1) { 8270 MachineInstrBuilder MIB = 8271 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 8272 MIB = AddDefaultT1CC(MIB); 8273 MIB.addReg(varPhi).addImm(UnitSize); 8274 AddDefaultPred(MIB); 8275 } else { 8276 MachineInstrBuilder MIB = 8277 BuildMI(*BB, BB->end(), dl, 8278 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8279 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 8280 MIB->getOperand(5).setReg(ARM::CPSR); 8281 MIB->getOperand(5).setIsDef(true); 8282 } 8283 BuildMI(*BB, BB->end(), dl, 8284 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8285 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8286 8287 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8288 BB->addSuccessor(loopMBB); 8289 BB->addSuccessor(exitMBB); 8290 8291 // Add epilogue to handle BytesLeft. 8292 BB = exitMBB; 8293 auto StartOfExit = exitMBB->begin(); 8294 8295 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8296 // [destOut] = STRB_POST(scratch, destLoop, 1) 8297 unsigned srcIn = srcLoop; 8298 unsigned destIn = destLoop; 8299 for (unsigned i = 0; i < BytesLeft; i++) { 8300 unsigned srcOut = MRI.createVirtualRegister(TRC); 8301 unsigned destOut = MRI.createVirtualRegister(TRC); 8302 unsigned scratch = MRI.createVirtualRegister(TRC); 8303 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8304 IsThumb1, IsThumb2); 8305 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8306 IsThumb1, IsThumb2); 8307 srcIn = srcOut; 8308 destIn = destOut; 8309 } 8310 8311 MI.eraseFromParent(); // The instruction is gone now. 8312 return BB; 8313 } 8314 8315 MachineBasicBlock * 8316 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8317 MachineBasicBlock *MBB) const { 8318 const TargetMachine &TM = getTargetMachine(); 8319 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8320 DebugLoc DL = MI.getDebugLoc(); 8321 8322 assert(Subtarget->isTargetWindows() && 8323 "__chkstk is only supported on Windows"); 8324 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8325 8326 // __chkstk takes the number of words to allocate on the stack in R4, and 8327 // returns the stack adjustment in number of bytes in R4. This will not 8328 // clober any other registers (other than the obvious lr). 8329 // 8330 // Although, technically, IP should be considered a register which may be 8331 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8332 // thumb-2 environment, so there is no interworking required. As a result, we 8333 // do not expect a veneer to be emitted by the linker, clobbering IP. 8334 // 8335 // Each module receives its own copy of __chkstk, so no import thunk is 8336 // required, again, ensuring that IP is not clobbered. 8337 // 8338 // Finally, although some linkers may theoretically provide a trampoline for 8339 // out of range calls (which is quite common due to a 32M range limitation of 8340 // branches for Thumb), we can generate the long-call version via 8341 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8342 // IP. 8343 8344 switch (TM.getCodeModel()) { 8345 case CodeModel::Small: 8346 case CodeModel::Medium: 8347 case CodeModel::Default: 8348 case CodeModel::Kernel: 8349 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8350 .addImm((unsigned)ARMCC::AL).addReg(0) 8351 .addExternalSymbol("__chkstk") 8352 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8353 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8354 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8355 break; 8356 case CodeModel::Large: 8357 case CodeModel::JITDefault: { 8358 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8359 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8360 8361 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8362 .addExternalSymbol("__chkstk"); 8363 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8364 .addImm((unsigned)ARMCC::AL).addReg(0) 8365 .addReg(Reg, RegState::Kill) 8366 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8367 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8368 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8369 break; 8370 } 8371 } 8372 8373 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 8374 ARM::SP) 8375 .addReg(ARM::SP, RegState::Kill) 8376 .addReg(ARM::R4, RegState::Kill) 8377 .setMIFlags(MachineInstr::FrameSetup))); 8378 8379 MI.eraseFromParent(); 8380 return MBB; 8381 } 8382 8383 MachineBasicBlock * 8384 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8385 MachineBasicBlock *MBB) const { 8386 DebugLoc DL = MI.getDebugLoc(); 8387 MachineFunction *MF = MBB->getParent(); 8388 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8389 8390 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8391 MF->insert(++MBB->getIterator(), ContBB); 8392 ContBB->splice(ContBB->begin(), MBB, 8393 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8394 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8395 8396 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8397 MF->push_back(TrapBB); 8398 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 8399 MBB->addSuccessor(TrapBB); 8400 8401 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 8402 .addReg(MI.getOperand(0).getReg()) 8403 .addMBB(TrapBB); 8404 AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB)); 8405 MBB->addSuccessor(ContBB); 8406 8407 MI.eraseFromParent(); 8408 return ContBB; 8409 } 8410 8411 MachineBasicBlock * 8412 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8413 MachineBasicBlock *BB) const { 8414 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8415 DebugLoc dl = MI.getDebugLoc(); 8416 bool isThumb2 = Subtarget->isThumb2(); 8417 switch (MI.getOpcode()) { 8418 default: { 8419 MI.dump(); 8420 llvm_unreachable("Unexpected instr type to insert"); 8421 } 8422 8423 // Thumb1 post-indexed loads are really just single-register LDMs. 8424 case ARM::tLDR_postidx: { 8425 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8426 .addOperand(MI.getOperand(1)) // Rn_wb 8427 .addOperand(MI.getOperand(2)) // Rn 8428 .addOperand(MI.getOperand(3)) // PredImm 8429 .addOperand(MI.getOperand(4)) // PredReg 8430 .addOperand(MI.getOperand(0)); // Rt 8431 MI.eraseFromParent(); 8432 return BB; 8433 } 8434 8435 // The Thumb2 pre-indexed stores have the same MI operands, they just 8436 // define them differently in the .td files from the isel patterns, so 8437 // they need pseudos. 8438 case ARM::t2STR_preidx: 8439 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8440 return BB; 8441 case ARM::t2STRB_preidx: 8442 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 8443 return BB; 8444 case ARM::t2STRH_preidx: 8445 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 8446 return BB; 8447 8448 case ARM::STRi_preidx: 8449 case ARM::STRBi_preidx: { 8450 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 8451 : ARM::STRB_PRE_IMM; 8452 // Decode the offset. 8453 unsigned Offset = MI.getOperand(4).getImm(); 8454 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8455 Offset = ARM_AM::getAM2Offset(Offset); 8456 if (isSub) 8457 Offset = -Offset; 8458 8459 MachineMemOperand *MMO = *MI.memoperands_begin(); 8460 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8461 .addOperand(MI.getOperand(0)) // Rn_wb 8462 .addOperand(MI.getOperand(1)) // Rt 8463 .addOperand(MI.getOperand(2)) // Rn 8464 .addImm(Offset) // offset (skip GPR==zero_reg) 8465 .addOperand(MI.getOperand(5)) // pred 8466 .addOperand(MI.getOperand(6)) 8467 .addMemOperand(MMO); 8468 MI.eraseFromParent(); 8469 return BB; 8470 } 8471 case ARM::STRr_preidx: 8472 case ARM::STRBr_preidx: 8473 case ARM::STRH_preidx: { 8474 unsigned NewOpc; 8475 switch (MI.getOpcode()) { 8476 default: llvm_unreachable("unexpected opcode!"); 8477 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8478 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8479 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8480 } 8481 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8482 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 8483 MIB.addOperand(MI.getOperand(i)); 8484 MI.eraseFromParent(); 8485 return BB; 8486 } 8487 8488 case ARM::tMOVCCr_pseudo: { 8489 // To "insert" a SELECT_CC instruction, we actually have to insert the 8490 // diamond control-flow pattern. The incoming instruction knows the 8491 // destination vreg to set, the condition code register to branch on, the 8492 // true/false values to select between, and a branch opcode to use. 8493 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8494 MachineFunction::iterator It = ++BB->getIterator(); 8495 8496 // thisMBB: 8497 // ... 8498 // TrueVal = ... 8499 // cmpTY ccX, r1, r2 8500 // bCC copy1MBB 8501 // fallthrough --> copy0MBB 8502 MachineBasicBlock *thisMBB = BB; 8503 MachineFunction *F = BB->getParent(); 8504 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8505 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8506 F->insert(It, copy0MBB); 8507 F->insert(It, sinkMBB); 8508 8509 // Transfer the remainder of BB and its successor edges to sinkMBB. 8510 sinkMBB->splice(sinkMBB->begin(), BB, 8511 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8512 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8513 8514 BB->addSuccessor(copy0MBB); 8515 BB->addSuccessor(sinkMBB); 8516 8517 BuildMI(BB, dl, TII->get(ARM::tBcc)) 8518 .addMBB(sinkMBB) 8519 .addImm(MI.getOperand(3).getImm()) 8520 .addReg(MI.getOperand(4).getReg()); 8521 8522 // copy0MBB: 8523 // %FalseValue = ... 8524 // # fallthrough to sinkMBB 8525 BB = copy0MBB; 8526 8527 // Update machine-CFG edges 8528 BB->addSuccessor(sinkMBB); 8529 8530 // sinkMBB: 8531 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8532 // ... 8533 BB = sinkMBB; 8534 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 8535 .addReg(MI.getOperand(1).getReg()) 8536 .addMBB(copy0MBB) 8537 .addReg(MI.getOperand(2).getReg()) 8538 .addMBB(thisMBB); 8539 8540 MI.eraseFromParent(); // The pseudo instruction is gone now. 8541 return BB; 8542 } 8543 8544 case ARM::BCCi64: 8545 case ARM::BCCZi64: { 8546 // If there is an unconditional branch to the other successor, remove it. 8547 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8548 8549 // Compare both parts that make up the double comparison separately for 8550 // equality. 8551 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 8552 8553 unsigned LHS1 = MI.getOperand(1).getReg(); 8554 unsigned LHS2 = MI.getOperand(2).getReg(); 8555 if (RHSisZero) { 8556 AddDefaultPred(BuildMI(BB, dl, 8557 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8558 .addReg(LHS1).addImm(0)); 8559 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8560 .addReg(LHS2).addImm(0) 8561 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8562 } else { 8563 unsigned RHS1 = MI.getOperand(3).getReg(); 8564 unsigned RHS2 = MI.getOperand(4).getReg(); 8565 AddDefaultPred(BuildMI(BB, dl, 8566 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8567 .addReg(LHS1).addReg(RHS1)); 8568 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8569 .addReg(LHS2).addReg(RHS2) 8570 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8571 } 8572 8573 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 8574 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8575 if (MI.getOperand(0).getImm() == ARMCC::NE) 8576 std::swap(destMBB, exitMBB); 8577 8578 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8579 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8580 if (isThumb2) 8581 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8582 else 8583 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8584 8585 MI.eraseFromParent(); // The pseudo instruction is gone now. 8586 return BB; 8587 } 8588 8589 case ARM::Int_eh_sjlj_setjmp: 8590 case ARM::Int_eh_sjlj_setjmp_nofp: 8591 case ARM::tInt_eh_sjlj_setjmp: 8592 case ARM::t2Int_eh_sjlj_setjmp: 8593 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8594 return BB; 8595 8596 case ARM::Int_eh_sjlj_setup_dispatch: 8597 EmitSjLjDispatchBlock(MI, BB); 8598 return BB; 8599 8600 case ARM::ABS: 8601 case ARM::t2ABS: { 8602 // To insert an ABS instruction, we have to insert the 8603 // diamond control-flow pattern. The incoming instruction knows the 8604 // source vreg to test against 0, the destination vreg to set, 8605 // the condition code register to branch on, the 8606 // true/false values to select between, and a branch opcode to use. 8607 // It transforms 8608 // V1 = ABS V0 8609 // into 8610 // V2 = MOVS V0 8611 // BCC (branch to SinkBB if V0 >= 0) 8612 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8613 // SinkBB: V1 = PHI(V2, V3) 8614 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8615 MachineFunction::iterator BBI = ++BB->getIterator(); 8616 MachineFunction *Fn = BB->getParent(); 8617 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8618 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8619 Fn->insert(BBI, RSBBB); 8620 Fn->insert(BBI, SinkBB); 8621 8622 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 8623 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 8624 bool ABSSrcKIll = MI.getOperand(1).isKill(); 8625 bool isThumb2 = Subtarget->isThumb2(); 8626 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8627 // In Thumb mode S must not be specified if source register is the SP or 8628 // PC and if destination register is the SP, so restrict register class 8629 unsigned NewRsbDstReg = 8630 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8631 8632 // Transfer the remainder of BB and its successor edges to sinkMBB. 8633 SinkBB->splice(SinkBB->begin(), BB, 8634 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8635 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8636 8637 BB->addSuccessor(RSBBB); 8638 BB->addSuccessor(SinkBB); 8639 8640 // fall through to SinkMBB 8641 RSBBB->addSuccessor(SinkBB); 8642 8643 // insert a cmp at the end of BB 8644 AddDefaultPred(BuildMI(BB, dl, 8645 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8646 .addReg(ABSSrcReg).addImm(0)); 8647 8648 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8649 BuildMI(BB, dl, 8650 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8651 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8652 8653 // insert rsbri in RSBBB 8654 // Note: BCC and rsbri will be converted into predicated rsbmi 8655 // by if-conversion pass 8656 BuildMI(*RSBBB, RSBBB->begin(), dl, 8657 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8658 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8659 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8660 8661 // insert PHI in SinkBB, 8662 // reuse ABSDstReg to not change uses of ABS instruction 8663 BuildMI(*SinkBB, SinkBB->begin(), dl, 8664 TII->get(ARM::PHI), ABSDstReg) 8665 .addReg(NewRsbDstReg).addMBB(RSBBB) 8666 .addReg(ABSSrcReg).addMBB(BB); 8667 8668 // remove ABS instruction 8669 MI.eraseFromParent(); 8670 8671 // return last added BB 8672 return SinkBB; 8673 } 8674 case ARM::COPY_STRUCT_BYVAL_I32: 8675 ++NumLoopByVals; 8676 return EmitStructByval(MI, BB); 8677 case ARM::WIN__CHKSTK: 8678 return EmitLowered__chkstk(MI, BB); 8679 case ARM::WIN__DBZCHK: 8680 return EmitLowered__dbzchk(MI, BB); 8681 } 8682 } 8683 8684 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8685 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8686 /// instead of as a custom inserter because we need the use list from the SDNode. 8687 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8688 MachineInstr &MI, const SDNode *Node) { 8689 bool isThumb1 = Subtarget->isThumb1Only(); 8690 8691 DebugLoc DL = MI.getDebugLoc(); 8692 MachineFunction *MF = MI.getParent()->getParent(); 8693 MachineRegisterInfo &MRI = MF->getRegInfo(); 8694 MachineInstrBuilder MIB(*MF, MI); 8695 8696 // If the new dst/src is unused mark it as dead. 8697 if (!Node->hasAnyUseOfValue(0)) { 8698 MI.getOperand(0).setIsDead(true); 8699 } 8700 if (!Node->hasAnyUseOfValue(1)) { 8701 MI.getOperand(1).setIsDead(true); 8702 } 8703 8704 // The MEMCPY both defines and kills the scratch registers. 8705 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 8706 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8707 : &ARM::GPRRegClass); 8708 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8709 } 8710 } 8711 8712 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8713 SDNode *Node) const { 8714 if (MI.getOpcode() == ARM::MEMCPY) { 8715 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8716 return; 8717 } 8718 8719 const MCInstrDesc *MCID = &MI.getDesc(); 8720 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8721 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8722 // operand is still set to noreg. If needed, set the optional operand's 8723 // register to CPSR, and remove the redundant implicit def. 8724 // 8725 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8726 8727 // Rename pseudo opcodes. 8728 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 8729 if (NewOpc) { 8730 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8731 MCID = &TII->get(NewOpc); 8732 8733 assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 && 8734 "converted opcode should be the same except for cc_out"); 8735 8736 MI.setDesc(*MCID); 8737 8738 // Add the optional cc_out operand 8739 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8740 } 8741 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8742 8743 // Any ARM instruction that sets the 's' bit should specify an optional 8744 // "cc_out" operand in the last operand position. 8745 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8746 assert(!NewOpc && "Optional cc_out operand required"); 8747 return; 8748 } 8749 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8750 // since we already have an optional CPSR def. 8751 bool definesCPSR = false; 8752 bool deadCPSR = false; 8753 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 8754 ++i) { 8755 const MachineOperand &MO = MI.getOperand(i); 8756 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8757 definesCPSR = true; 8758 if (MO.isDead()) 8759 deadCPSR = true; 8760 MI.RemoveOperand(i); 8761 break; 8762 } 8763 } 8764 if (!definesCPSR) { 8765 assert(!NewOpc && "Optional cc_out operand required"); 8766 return; 8767 } 8768 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8769 if (deadCPSR) { 8770 assert(!MI.getOperand(ccOutIdx).getReg() && 8771 "expect uninitialized optional cc_out operand"); 8772 return; 8773 } 8774 8775 // If this instruction was defined with an optional CPSR def and its dag node 8776 // had a live implicit CPSR def, then activate the optional CPSR def. 8777 MachineOperand &MO = MI.getOperand(ccOutIdx); 8778 MO.setReg(ARM::CPSR); 8779 MO.setIsDef(true); 8780 } 8781 8782 //===----------------------------------------------------------------------===// 8783 // ARM Optimization Hooks 8784 //===----------------------------------------------------------------------===// 8785 8786 // Helper function that checks if N is a null or all ones constant. 8787 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8788 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8789 } 8790 8791 // Return true if N is conditionally 0 or all ones. 8792 // Detects these expressions where cc is an i1 value: 8793 // 8794 // (select cc 0, y) [AllOnes=0] 8795 // (select cc y, 0) [AllOnes=0] 8796 // (zext cc) [AllOnes=0] 8797 // (sext cc) [AllOnes=0/1] 8798 // (select cc -1, y) [AllOnes=1] 8799 // (select cc y, -1) [AllOnes=1] 8800 // 8801 // Invert is set when N is the null/all ones constant when CC is false. 8802 // OtherOp is set to the alternative value of N. 8803 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8804 SDValue &CC, bool &Invert, 8805 SDValue &OtherOp, 8806 SelectionDAG &DAG) { 8807 switch (N->getOpcode()) { 8808 default: return false; 8809 case ISD::SELECT: { 8810 CC = N->getOperand(0); 8811 SDValue N1 = N->getOperand(1); 8812 SDValue N2 = N->getOperand(2); 8813 if (isZeroOrAllOnes(N1, AllOnes)) { 8814 Invert = false; 8815 OtherOp = N2; 8816 return true; 8817 } 8818 if (isZeroOrAllOnes(N2, AllOnes)) { 8819 Invert = true; 8820 OtherOp = N1; 8821 return true; 8822 } 8823 return false; 8824 } 8825 case ISD::ZERO_EXTEND: 8826 // (zext cc) can never be the all ones value. 8827 if (AllOnes) 8828 return false; 8829 LLVM_FALLTHROUGH; 8830 case ISD::SIGN_EXTEND: { 8831 SDLoc dl(N); 8832 EVT VT = N->getValueType(0); 8833 CC = N->getOperand(0); 8834 if (CC.getValueType() != MVT::i1) 8835 return false; 8836 Invert = !AllOnes; 8837 if (AllOnes) 8838 // When looking for an AllOnes constant, N is an sext, and the 'other' 8839 // value is 0. 8840 OtherOp = DAG.getConstant(0, dl, VT); 8841 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8842 // When looking for a 0 constant, N can be zext or sext. 8843 OtherOp = DAG.getConstant(1, dl, VT); 8844 else 8845 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8846 VT); 8847 return true; 8848 } 8849 } 8850 } 8851 8852 // Combine a constant select operand into its use: 8853 // 8854 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8855 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8856 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8857 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8858 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8859 // 8860 // The transform is rejected if the select doesn't have a constant operand that 8861 // is null, or all ones when AllOnes is set. 8862 // 8863 // Also recognize sext/zext from i1: 8864 // 8865 // (add (zext cc), x) -> (select cc (add x, 1), x) 8866 // (add (sext cc), x) -> (select cc (add x, -1), x) 8867 // 8868 // These transformations eventually create predicated instructions. 8869 // 8870 // @param N The node to transform. 8871 // @param Slct The N operand that is a select. 8872 // @param OtherOp The other N operand (x above). 8873 // @param DCI Context. 8874 // @param AllOnes Require the select constant to be all ones instead of null. 8875 // @returns The new node, or SDValue() on failure. 8876 static 8877 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8878 TargetLowering::DAGCombinerInfo &DCI, 8879 bool AllOnes = false) { 8880 SelectionDAG &DAG = DCI.DAG; 8881 EVT VT = N->getValueType(0); 8882 SDValue NonConstantVal; 8883 SDValue CCOp; 8884 bool SwapSelectOps; 8885 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8886 NonConstantVal, DAG)) 8887 return SDValue(); 8888 8889 // Slct is now know to be the desired identity constant when CC is true. 8890 SDValue TrueVal = OtherOp; 8891 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8892 OtherOp, NonConstantVal); 8893 // Unless SwapSelectOps says CC should be false. 8894 if (SwapSelectOps) 8895 std::swap(TrueVal, FalseVal); 8896 8897 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8898 CCOp, TrueVal, FalseVal); 8899 } 8900 8901 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8902 static 8903 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8904 TargetLowering::DAGCombinerInfo &DCI) { 8905 SDValue N0 = N->getOperand(0); 8906 SDValue N1 = N->getOperand(1); 8907 if (N0.getNode()->hasOneUse()) 8908 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 8909 return Result; 8910 if (N1.getNode()->hasOneUse()) 8911 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 8912 return Result; 8913 return SDValue(); 8914 } 8915 8916 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8917 // (only after legalization). 8918 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8919 TargetLowering::DAGCombinerInfo &DCI, 8920 const ARMSubtarget *Subtarget) { 8921 8922 // Only perform optimization if after legalize, and if NEON is available. We 8923 // also expected both operands to be BUILD_VECTORs. 8924 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8925 || N0.getOpcode() != ISD::BUILD_VECTOR 8926 || N1.getOpcode() != ISD::BUILD_VECTOR) 8927 return SDValue(); 8928 8929 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8930 EVT VT = N->getValueType(0); 8931 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8932 return SDValue(); 8933 8934 // Check that the vector operands are of the right form. 8935 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8936 // operands, where N is the size of the formed vector. 8937 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8938 // index such that we have a pair wise add pattern. 8939 8940 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8941 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8942 return SDValue(); 8943 SDValue Vec = N0->getOperand(0)->getOperand(0); 8944 SDNode *V = Vec.getNode(); 8945 unsigned nextIndex = 0; 8946 8947 // For each operands to the ADD which are BUILD_VECTORs, 8948 // check to see if each of their operands are an EXTRACT_VECTOR with 8949 // the same vector and appropriate index. 8950 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8951 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8952 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8953 8954 SDValue ExtVec0 = N0->getOperand(i); 8955 SDValue ExtVec1 = N1->getOperand(i); 8956 8957 // First operand is the vector, verify its the same. 8958 if (V != ExtVec0->getOperand(0).getNode() || 8959 V != ExtVec1->getOperand(0).getNode()) 8960 return SDValue(); 8961 8962 // Second is the constant, verify its correct. 8963 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8964 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8965 8966 // For the constant, we want to see all the even or all the odd. 8967 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8968 || C1->getZExtValue() != nextIndex+1) 8969 return SDValue(); 8970 8971 // Increment index. 8972 nextIndex+=2; 8973 } else 8974 return SDValue(); 8975 } 8976 8977 // Create VPADDL node. 8978 SelectionDAG &DAG = DCI.DAG; 8979 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8980 8981 SDLoc dl(N); 8982 8983 // Build operand list. 8984 SmallVector<SDValue, 8> Ops; 8985 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8986 TLI.getPointerTy(DAG.getDataLayout()))); 8987 8988 // Input is the vector. 8989 Ops.push_back(Vec); 8990 8991 // Get widened type and narrowed type. 8992 MVT widenType; 8993 unsigned numElem = VT.getVectorNumElements(); 8994 8995 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8996 switch (inputLaneType.getSimpleVT().SimpleTy) { 8997 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8998 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8999 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9000 default: 9001 llvm_unreachable("Invalid vector element type for padd optimization."); 9002 } 9003 9004 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9005 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9006 return DAG.getNode(ExtOp, dl, VT, tmp); 9007 } 9008 9009 static SDValue findMUL_LOHI(SDValue V) { 9010 if (V->getOpcode() == ISD::UMUL_LOHI || 9011 V->getOpcode() == ISD::SMUL_LOHI) 9012 return V; 9013 return SDValue(); 9014 } 9015 9016 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 9017 TargetLowering::DAGCombinerInfo &DCI, 9018 const ARMSubtarget *Subtarget) { 9019 9020 // Look for multiply add opportunities. 9021 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9022 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9023 // a glue link from the first add to the second add. 9024 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9025 // a S/UMLAL instruction. 9026 // UMUL_LOHI 9027 // / :lo \ :hi 9028 // / \ [no multiline comment] 9029 // loAdd -> ADDE | 9030 // \ :glue / 9031 // \ / 9032 // ADDC <- hiAdd 9033 // 9034 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 9035 SDValue AddcOp0 = AddcNode->getOperand(0); 9036 SDValue AddcOp1 = AddcNode->getOperand(1); 9037 9038 // Check if the two operands are from the same mul_lohi node. 9039 if (AddcOp0.getNode() == AddcOp1.getNode()) 9040 return SDValue(); 9041 9042 assert(AddcNode->getNumValues() == 2 && 9043 AddcNode->getValueType(0) == MVT::i32 && 9044 "Expect ADDC with two result values. First: i32"); 9045 9046 // Check that we have a glued ADDC node. 9047 if (AddcNode->getValueType(1) != MVT::Glue) 9048 return SDValue(); 9049 9050 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 9051 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9052 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9053 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9054 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9055 return SDValue(); 9056 9057 // Look for the glued ADDE. 9058 SDNode* AddeNode = AddcNode->getGluedUser(); 9059 if (!AddeNode) 9060 return SDValue(); 9061 9062 // Make sure it is really an ADDE. 9063 if (AddeNode->getOpcode() != ISD::ADDE) 9064 return SDValue(); 9065 9066 assert(AddeNode->getNumOperands() == 3 && 9067 AddeNode->getOperand(2).getValueType() == MVT::Glue && 9068 "ADDE node has the wrong inputs"); 9069 9070 // Check for the triangle shape. 9071 SDValue AddeOp0 = AddeNode->getOperand(0); 9072 SDValue AddeOp1 = AddeNode->getOperand(1); 9073 9074 // Make sure that the ADDE operands are not coming from the same node. 9075 if (AddeOp0.getNode() == AddeOp1.getNode()) 9076 return SDValue(); 9077 9078 // Find the MUL_LOHI node walking up ADDE's operands. 9079 bool IsLeftOperandMUL = false; 9080 SDValue MULOp = findMUL_LOHI(AddeOp0); 9081 if (MULOp == SDValue()) 9082 MULOp = findMUL_LOHI(AddeOp1); 9083 else 9084 IsLeftOperandMUL = true; 9085 if (MULOp == SDValue()) 9086 return SDValue(); 9087 9088 // Figure out the right opcode. 9089 unsigned Opc = MULOp->getOpcode(); 9090 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9091 9092 // Figure out the high and low input values to the MLAL node. 9093 SDValue* HiAdd = nullptr; 9094 SDValue* LoMul = nullptr; 9095 SDValue* LowAdd = nullptr; 9096 9097 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 9098 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9099 return SDValue(); 9100 9101 if (IsLeftOperandMUL) 9102 HiAdd = &AddeOp1; 9103 else 9104 HiAdd = &AddeOp0; 9105 9106 9107 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9108 // whose low result is fed to the ADDC we are checking. 9109 9110 if (AddcOp0 == MULOp.getValue(0)) { 9111 LoMul = &AddcOp0; 9112 LowAdd = &AddcOp1; 9113 } 9114 if (AddcOp1 == MULOp.getValue(0)) { 9115 LoMul = &AddcOp1; 9116 LowAdd = &AddcOp0; 9117 } 9118 9119 if (!LoMul) 9120 return SDValue(); 9121 9122 // Create the merged node. 9123 SelectionDAG &DAG = DCI.DAG; 9124 9125 // Build operand list. 9126 SmallVector<SDValue, 8> Ops; 9127 Ops.push_back(LoMul->getOperand(0)); 9128 Ops.push_back(LoMul->getOperand(1)); 9129 Ops.push_back(*LowAdd); 9130 Ops.push_back(*HiAdd); 9131 9132 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9133 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9134 9135 // Replace the ADDs' nodes uses by the MLA node's values. 9136 SDValue HiMLALResult(MLALNode.getNode(), 1); 9137 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9138 9139 SDValue LoMLALResult(MLALNode.getNode(), 0); 9140 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9141 9142 // Return original node to notify the driver to stop replacing. 9143 SDValue resNode(AddcNode, 0); 9144 return resNode; 9145 } 9146 9147 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode, 9148 TargetLowering::DAGCombinerInfo &DCI, 9149 const ARMSubtarget *Subtarget) { 9150 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9151 // While trying to combine for the other MLAL nodes, first search for the 9152 // chance to use UMAAL. Check if Addc uses another addc node which can first 9153 // be combined into a UMLAL. The other pattern is AddcNode being combined 9154 // into an UMLAL and then using another addc is handled in ISelDAGToDAG. 9155 9156 if (!Subtarget->hasV6Ops() || 9157 (Subtarget->isThumb() && !Subtarget->hasThumb2())) 9158 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9159 9160 SDNode *PrevAddc = nullptr; 9161 if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC) 9162 PrevAddc = AddcNode->getOperand(0).getNode(); 9163 else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC) 9164 PrevAddc = AddcNode->getOperand(1).getNode(); 9165 9166 // If there's no addc chains, just return a search for any MLAL. 9167 if (PrevAddc == nullptr) 9168 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9169 9170 // Try to convert the addc operand to an MLAL and if that fails try to 9171 // combine AddcNode. 9172 SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget); 9173 if (MLAL != SDValue(PrevAddc, 0)) 9174 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9175 9176 // Find the converted UMAAL or quit if it doesn't exist. 9177 SDNode *UmlalNode = nullptr; 9178 SDValue AddHi; 9179 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9180 UmlalNode = AddcNode->getOperand(0).getNode(); 9181 AddHi = AddcNode->getOperand(1); 9182 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9183 UmlalNode = AddcNode->getOperand(1).getNode(); 9184 AddHi = AddcNode->getOperand(0); 9185 } else { 9186 return SDValue(); 9187 } 9188 9189 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9190 // the ADDC as well as Zero. 9191 auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3)); 9192 9193 if (!Zero || Zero->getZExtValue() != 0) 9194 return SDValue(); 9195 9196 // Check that we have a glued ADDC node. 9197 if (AddcNode->getValueType(1) != MVT::Glue) 9198 return SDValue(); 9199 9200 // Look for the glued ADDE. 9201 SDNode* AddeNode = AddcNode->getGluedUser(); 9202 if (!AddeNode) 9203 return SDValue(); 9204 9205 if ((AddeNode->getOperand(0).getNode() == Zero && 9206 AddeNode->getOperand(1).getNode() == UmlalNode) || 9207 (AddeNode->getOperand(0).getNode() == UmlalNode && 9208 AddeNode->getOperand(1).getNode() == Zero)) { 9209 9210 SelectionDAG &DAG = DCI.DAG; 9211 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9212 UmlalNode->getOperand(2), AddHi }; 9213 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9214 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9215 9216 // Replace the ADDs' nodes uses by the UMAAL node's values. 9217 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9218 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9219 9220 // Return original node to notify the driver to stop replacing. 9221 return SDValue(AddcNode, 0); 9222 } 9223 return SDValue(); 9224 } 9225 9226 /// PerformADDCCombine - Target-specific dag combine transform from 9227 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or 9228 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 9229 static SDValue PerformADDCCombine(SDNode *N, 9230 TargetLowering::DAGCombinerInfo &DCI, 9231 const ARMSubtarget *Subtarget) { 9232 9233 if (Subtarget->isThumb1Only()) return SDValue(); 9234 9235 // Only perform the checks after legalize when the pattern is available. 9236 if (DCI.isBeforeLegalize()) return SDValue(); 9237 9238 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 9239 } 9240 9241 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 9242 /// operands N0 and N1. This is a helper for PerformADDCombine that is 9243 /// called with the default operands, and if that fails, with commuted 9244 /// operands. 9245 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 9246 TargetLowering::DAGCombinerInfo &DCI, 9247 const ARMSubtarget *Subtarget){ 9248 9249 // Attempt to create vpaddl for this add. 9250 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget)) 9251 return Result; 9252 9253 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9254 if (N0.getNode()->hasOneUse()) 9255 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 9256 return Result; 9257 return SDValue(); 9258 } 9259 9260 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 9261 /// 9262 static SDValue PerformADDCombine(SDNode *N, 9263 TargetLowering::DAGCombinerInfo &DCI, 9264 const ARMSubtarget *Subtarget) { 9265 SDValue N0 = N->getOperand(0); 9266 SDValue N1 = N->getOperand(1); 9267 9268 // First try with the default operand order. 9269 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 9270 return Result; 9271 9272 // If that didn't work, try again with the operands commuted. 9273 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 9274 } 9275 9276 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 9277 /// 9278 static SDValue PerformSUBCombine(SDNode *N, 9279 TargetLowering::DAGCombinerInfo &DCI) { 9280 SDValue N0 = N->getOperand(0); 9281 SDValue N1 = N->getOperand(1); 9282 9283 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9284 if (N1.getNode()->hasOneUse()) 9285 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 9286 return Result; 9287 9288 return SDValue(); 9289 } 9290 9291 /// PerformVMULCombine 9292 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 9293 /// special multiplier accumulator forwarding. 9294 /// vmul d3, d0, d2 9295 /// vmla d3, d1, d2 9296 /// is faster than 9297 /// vadd d3, d0, d1 9298 /// vmul d3, d3, d2 9299 // However, for (A + B) * (A + B), 9300 // vadd d2, d0, d1 9301 // vmul d3, d0, d2 9302 // vmla d3, d1, d2 9303 // is slower than 9304 // vadd d2, d0, d1 9305 // vmul d3, d2, d2 9306 static SDValue PerformVMULCombine(SDNode *N, 9307 TargetLowering::DAGCombinerInfo &DCI, 9308 const ARMSubtarget *Subtarget) { 9309 if (!Subtarget->hasVMLxForwarding()) 9310 return SDValue(); 9311 9312 SelectionDAG &DAG = DCI.DAG; 9313 SDValue N0 = N->getOperand(0); 9314 SDValue N1 = N->getOperand(1); 9315 unsigned Opcode = N0.getOpcode(); 9316 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9317 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 9318 Opcode = N1.getOpcode(); 9319 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9320 Opcode != ISD::FADD && Opcode != ISD::FSUB) 9321 return SDValue(); 9322 std::swap(N0, N1); 9323 } 9324 9325 if (N0 == N1) 9326 return SDValue(); 9327 9328 EVT VT = N->getValueType(0); 9329 SDLoc DL(N); 9330 SDValue N00 = N0->getOperand(0); 9331 SDValue N01 = N0->getOperand(1); 9332 return DAG.getNode(Opcode, DL, VT, 9333 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 9334 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 9335 } 9336 9337 static SDValue PerformMULCombine(SDNode *N, 9338 TargetLowering::DAGCombinerInfo &DCI, 9339 const ARMSubtarget *Subtarget) { 9340 SelectionDAG &DAG = DCI.DAG; 9341 9342 if (Subtarget->isThumb1Only()) 9343 return SDValue(); 9344 9345 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9346 return SDValue(); 9347 9348 EVT VT = N->getValueType(0); 9349 if (VT.is64BitVector() || VT.is128BitVector()) 9350 return PerformVMULCombine(N, DCI, Subtarget); 9351 if (VT != MVT::i32) 9352 return SDValue(); 9353 9354 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9355 if (!C) 9356 return SDValue(); 9357 9358 int64_t MulAmt = C->getSExtValue(); 9359 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 9360 9361 ShiftAmt = ShiftAmt & (32 - 1); 9362 SDValue V = N->getOperand(0); 9363 SDLoc DL(N); 9364 9365 SDValue Res; 9366 MulAmt >>= ShiftAmt; 9367 9368 if (MulAmt >= 0) { 9369 if (isPowerOf2_32(MulAmt - 1)) { 9370 // (mul x, 2^N + 1) => (add (shl x, N), x) 9371 Res = DAG.getNode(ISD::ADD, DL, VT, 9372 V, 9373 DAG.getNode(ISD::SHL, DL, VT, 9374 V, 9375 DAG.getConstant(Log2_32(MulAmt - 1), DL, 9376 MVT::i32))); 9377 } else if (isPowerOf2_32(MulAmt + 1)) { 9378 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9379 Res = DAG.getNode(ISD::SUB, DL, VT, 9380 DAG.getNode(ISD::SHL, DL, VT, 9381 V, 9382 DAG.getConstant(Log2_32(MulAmt + 1), DL, 9383 MVT::i32)), 9384 V); 9385 } else 9386 return SDValue(); 9387 } else { 9388 uint64_t MulAmtAbs = -MulAmt; 9389 if (isPowerOf2_32(MulAmtAbs + 1)) { 9390 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 9391 Res = DAG.getNode(ISD::SUB, DL, VT, 9392 V, 9393 DAG.getNode(ISD::SHL, DL, VT, 9394 V, 9395 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 9396 MVT::i32))); 9397 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 9398 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 9399 Res = DAG.getNode(ISD::ADD, DL, VT, 9400 V, 9401 DAG.getNode(ISD::SHL, DL, VT, 9402 V, 9403 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 9404 MVT::i32))); 9405 Res = DAG.getNode(ISD::SUB, DL, VT, 9406 DAG.getConstant(0, DL, MVT::i32), Res); 9407 9408 } else 9409 return SDValue(); 9410 } 9411 9412 if (ShiftAmt != 0) 9413 Res = DAG.getNode(ISD::SHL, DL, VT, 9414 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 9415 9416 // Do not add new nodes to DAG combiner worklist. 9417 DCI.CombineTo(N, Res, false); 9418 return SDValue(); 9419 } 9420 9421 static SDValue PerformANDCombine(SDNode *N, 9422 TargetLowering::DAGCombinerInfo &DCI, 9423 const ARMSubtarget *Subtarget) { 9424 9425 // Attempt to use immediate-form VBIC 9426 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9427 SDLoc dl(N); 9428 EVT VT = N->getValueType(0); 9429 SelectionDAG &DAG = DCI.DAG; 9430 9431 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9432 return SDValue(); 9433 9434 APInt SplatBits, SplatUndef; 9435 unsigned SplatBitSize; 9436 bool HasAnyUndefs; 9437 if (BVN && 9438 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9439 if (SplatBitSize <= 64) { 9440 EVT VbicVT; 9441 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9442 SplatUndef.getZExtValue(), SplatBitSize, 9443 DAG, dl, VbicVT, VT.is128BitVector(), 9444 OtherModImm); 9445 if (Val.getNode()) { 9446 SDValue Input = 9447 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9448 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9449 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9450 } 9451 } 9452 } 9453 9454 if (!Subtarget->isThumb1Only()) { 9455 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9456 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9457 return Result; 9458 } 9459 9460 return SDValue(); 9461 } 9462 9463 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9464 static SDValue PerformORCombine(SDNode *N, 9465 TargetLowering::DAGCombinerInfo &DCI, 9466 const ARMSubtarget *Subtarget) { 9467 // Attempt to use immediate-form VORR 9468 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9469 SDLoc dl(N); 9470 EVT VT = N->getValueType(0); 9471 SelectionDAG &DAG = DCI.DAG; 9472 9473 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9474 return SDValue(); 9475 9476 APInt SplatBits, SplatUndef; 9477 unsigned SplatBitSize; 9478 bool HasAnyUndefs; 9479 if (BVN && Subtarget->hasNEON() && 9480 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9481 if (SplatBitSize <= 64) { 9482 EVT VorrVT; 9483 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9484 SplatUndef.getZExtValue(), SplatBitSize, 9485 DAG, dl, VorrVT, VT.is128BitVector(), 9486 OtherModImm); 9487 if (Val.getNode()) { 9488 SDValue Input = 9489 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9490 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9491 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9492 } 9493 } 9494 } 9495 9496 if (!Subtarget->isThumb1Only()) { 9497 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9498 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9499 return Result; 9500 } 9501 9502 // The code below optimizes (or (and X, Y), Z). 9503 // The AND operand needs to have a single user to make these optimizations 9504 // profitable. 9505 SDValue N0 = N->getOperand(0); 9506 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9507 return SDValue(); 9508 SDValue N1 = N->getOperand(1); 9509 9510 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9511 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9512 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9513 APInt SplatUndef; 9514 unsigned SplatBitSize; 9515 bool HasAnyUndefs; 9516 9517 APInt SplatBits0, SplatBits1; 9518 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9519 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9520 // Ensure that the second operand of both ands are constants 9521 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9522 HasAnyUndefs) && !HasAnyUndefs) { 9523 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9524 HasAnyUndefs) && !HasAnyUndefs) { 9525 // Ensure that the bit width of the constants are the same and that 9526 // the splat arguments are logical inverses as per the pattern we 9527 // are trying to simplify. 9528 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9529 SplatBits0 == ~SplatBits1) { 9530 // Canonicalize the vector type to make instruction selection 9531 // simpler. 9532 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9533 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9534 N0->getOperand(1), 9535 N0->getOperand(0), 9536 N1->getOperand(0)); 9537 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9538 } 9539 } 9540 } 9541 } 9542 9543 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9544 // reasonable. 9545 9546 // BFI is only available on V6T2+ 9547 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9548 return SDValue(); 9549 9550 SDLoc DL(N); 9551 // 1) or (and A, mask), val => ARMbfi A, val, mask 9552 // iff (val & mask) == val 9553 // 9554 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9555 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9556 // && mask == ~mask2 9557 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9558 // && ~mask == mask2 9559 // (i.e., copy a bitfield value into another bitfield of the same width) 9560 9561 if (VT != MVT::i32) 9562 return SDValue(); 9563 9564 SDValue N00 = N0.getOperand(0); 9565 9566 // The value and the mask need to be constants so we can verify this is 9567 // actually a bitfield set. If the mask is 0xffff, we can do better 9568 // via a movt instruction, so don't use BFI in that case. 9569 SDValue MaskOp = N0.getOperand(1); 9570 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9571 if (!MaskC) 9572 return SDValue(); 9573 unsigned Mask = MaskC->getZExtValue(); 9574 if (Mask == 0xffff) 9575 return SDValue(); 9576 SDValue Res; 9577 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9579 if (N1C) { 9580 unsigned Val = N1C->getZExtValue(); 9581 if ((Val & ~Mask) != Val) 9582 return SDValue(); 9583 9584 if (ARM::isBitFieldInvertedMask(Mask)) { 9585 Val >>= countTrailingZeros(~Mask); 9586 9587 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9588 DAG.getConstant(Val, DL, MVT::i32), 9589 DAG.getConstant(Mask, DL, MVT::i32)); 9590 9591 // Do not add new nodes to DAG combiner worklist. 9592 DCI.CombineTo(N, Res, false); 9593 return SDValue(); 9594 } 9595 } else if (N1.getOpcode() == ISD::AND) { 9596 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9597 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9598 if (!N11C) 9599 return SDValue(); 9600 unsigned Mask2 = N11C->getZExtValue(); 9601 9602 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9603 // as is to match. 9604 if (ARM::isBitFieldInvertedMask(Mask) && 9605 (Mask == ~Mask2)) { 9606 // The pack halfword instruction works better for masks that fit it, 9607 // so use that when it's available. 9608 if (Subtarget->hasT2ExtractPack() && 9609 (Mask == 0xffff || Mask == 0xffff0000)) 9610 return SDValue(); 9611 // 2a 9612 unsigned amt = countTrailingZeros(Mask2); 9613 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9614 DAG.getConstant(amt, DL, MVT::i32)); 9615 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9616 DAG.getConstant(Mask, DL, MVT::i32)); 9617 // Do not add new nodes to DAG combiner worklist. 9618 DCI.CombineTo(N, Res, false); 9619 return SDValue(); 9620 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9621 (~Mask == Mask2)) { 9622 // The pack halfword instruction works better for masks that fit it, 9623 // so use that when it's available. 9624 if (Subtarget->hasT2ExtractPack() && 9625 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9626 return SDValue(); 9627 // 2b 9628 unsigned lsb = countTrailingZeros(Mask); 9629 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9630 DAG.getConstant(lsb, DL, MVT::i32)); 9631 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9632 DAG.getConstant(Mask2, DL, MVT::i32)); 9633 // Do not add new nodes to DAG combiner worklist. 9634 DCI.CombineTo(N, Res, false); 9635 return SDValue(); 9636 } 9637 } 9638 9639 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9640 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9641 ARM::isBitFieldInvertedMask(~Mask)) { 9642 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9643 // where lsb(mask) == #shamt and masked bits of B are known zero. 9644 SDValue ShAmt = N00.getOperand(1); 9645 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9646 unsigned LSB = countTrailingZeros(Mask); 9647 if (ShAmtC != LSB) 9648 return SDValue(); 9649 9650 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9651 DAG.getConstant(~Mask, DL, MVT::i32)); 9652 9653 // Do not add new nodes to DAG combiner worklist. 9654 DCI.CombineTo(N, Res, false); 9655 } 9656 9657 return SDValue(); 9658 } 9659 9660 static SDValue PerformXORCombine(SDNode *N, 9661 TargetLowering::DAGCombinerInfo &DCI, 9662 const ARMSubtarget *Subtarget) { 9663 EVT VT = N->getValueType(0); 9664 SelectionDAG &DAG = DCI.DAG; 9665 9666 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9667 return SDValue(); 9668 9669 if (!Subtarget->isThumb1Only()) { 9670 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9671 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9672 return Result; 9673 } 9674 9675 return SDValue(); 9676 } 9677 9678 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9679 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9680 // their position in "to" (Rd). 9681 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9682 assert(N->getOpcode() == ARMISD::BFI); 9683 9684 SDValue From = N->getOperand(1); 9685 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9686 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9687 9688 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9689 // #C in the base of the SHR. 9690 if (From->getOpcode() == ISD::SRL && 9691 isa<ConstantSDNode>(From->getOperand(1))) { 9692 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9693 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9694 FromMask <<= Shift.getLimitedValue(31); 9695 From = From->getOperand(0); 9696 } 9697 9698 return From; 9699 } 9700 9701 // If A and B contain one contiguous set of bits, does A | B == A . B? 9702 // 9703 // Neither A nor B must be zero. 9704 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9705 unsigned LastActiveBitInA = A.countTrailingZeros(); 9706 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9707 return LastActiveBitInA - 1 == FirstActiveBitInB; 9708 } 9709 9710 static SDValue FindBFIToCombineWith(SDNode *N) { 9711 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9712 // if one exists. 9713 APInt ToMask, FromMask; 9714 SDValue From = ParseBFI(N, ToMask, FromMask); 9715 SDValue To = N->getOperand(0); 9716 9717 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9718 // aren't compatible, but not if they set the same bit in their destination as 9719 // we do (or that of any BFI we're going to combine with). 9720 SDValue V = To; 9721 APInt CombinedToMask = ToMask; 9722 while (V.getOpcode() == ARMISD::BFI) { 9723 APInt NewToMask, NewFromMask; 9724 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9725 if (NewFrom != From) { 9726 // This BFI has a different base. Keep going. 9727 CombinedToMask |= NewToMask; 9728 V = V.getOperand(0); 9729 continue; 9730 } 9731 9732 // Do the written bits conflict with any we've seen so far? 9733 if ((NewToMask & CombinedToMask).getBoolValue()) 9734 // Conflicting bits - bail out because going further is unsafe. 9735 return SDValue(); 9736 9737 // Are the new bits contiguous when combined with the old bits? 9738 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9739 BitsProperlyConcatenate(FromMask, NewFromMask)) 9740 return V; 9741 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9742 BitsProperlyConcatenate(NewFromMask, FromMask)) 9743 return V; 9744 9745 // We've seen a write to some bits, so track it. 9746 CombinedToMask |= NewToMask; 9747 // Keep going... 9748 V = V.getOperand(0); 9749 } 9750 9751 return SDValue(); 9752 } 9753 9754 static SDValue PerformBFICombine(SDNode *N, 9755 TargetLowering::DAGCombinerInfo &DCI) { 9756 SDValue N1 = N->getOperand(1); 9757 if (N1.getOpcode() == ISD::AND) { 9758 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9759 // the bits being cleared by the AND are not demanded by the BFI. 9760 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9761 if (!N11C) 9762 return SDValue(); 9763 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9764 unsigned LSB = countTrailingZeros(~InvMask); 9765 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9766 assert(Width < 9767 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9768 "undefined behavior"); 9769 unsigned Mask = (1u << Width) - 1; 9770 unsigned Mask2 = N11C->getZExtValue(); 9771 if ((Mask & (~Mask2)) == 0) 9772 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9773 N->getOperand(0), N1.getOperand(0), 9774 N->getOperand(2)); 9775 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9776 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9777 // Keep track of any consecutive bits set that all come from the same base 9778 // value. We can combine these together into a single BFI. 9779 SDValue CombineBFI = FindBFIToCombineWith(N); 9780 if (CombineBFI == SDValue()) 9781 return SDValue(); 9782 9783 // We've found a BFI. 9784 APInt ToMask1, FromMask1; 9785 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9786 9787 APInt ToMask2, FromMask2; 9788 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9789 assert(From1 == From2); 9790 (void)From2; 9791 9792 // First, unlink CombineBFI. 9793 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9794 // Then create a new BFI, combining the two together. 9795 APInt NewFromMask = FromMask1 | FromMask2; 9796 APInt NewToMask = ToMask1 | ToMask2; 9797 9798 EVT VT = N->getValueType(0); 9799 SDLoc dl(N); 9800 9801 if (NewFromMask[0] == 0) 9802 From1 = DCI.DAG.getNode( 9803 ISD::SRL, dl, VT, From1, 9804 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9805 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9806 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9807 } 9808 return SDValue(); 9809 } 9810 9811 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9812 /// ARMISD::VMOVRRD. 9813 static SDValue PerformVMOVRRDCombine(SDNode *N, 9814 TargetLowering::DAGCombinerInfo &DCI, 9815 const ARMSubtarget *Subtarget) { 9816 // vmovrrd(vmovdrr x, y) -> x,y 9817 SDValue InDouble = N->getOperand(0); 9818 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9819 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9820 9821 // vmovrrd(load f64) -> (load i32), (load i32) 9822 SDNode *InNode = InDouble.getNode(); 9823 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9824 InNode->getValueType(0) == MVT::f64 && 9825 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9826 !cast<LoadSDNode>(InNode)->isVolatile()) { 9827 // TODO: Should this be done for non-FrameIndex operands? 9828 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9829 9830 SelectionDAG &DAG = DCI.DAG; 9831 SDLoc DL(LD); 9832 SDValue BasePtr = LD->getBasePtr(); 9833 SDValue NewLD1 = 9834 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 9835 LD->getAlignment(), LD->getMemOperand()->getFlags()); 9836 9837 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9838 DAG.getConstant(4, DL, MVT::i32)); 9839 SDValue NewLD2 = DAG.getLoad( 9840 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 9841 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 9842 9843 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9844 if (DCI.DAG.getDataLayout().isBigEndian()) 9845 std::swap (NewLD1, NewLD2); 9846 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9847 return Result; 9848 } 9849 9850 return SDValue(); 9851 } 9852 9853 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9854 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9855 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9856 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9857 SDValue Op0 = N->getOperand(0); 9858 SDValue Op1 = N->getOperand(1); 9859 if (Op0.getOpcode() == ISD::BITCAST) 9860 Op0 = Op0.getOperand(0); 9861 if (Op1.getOpcode() == ISD::BITCAST) 9862 Op1 = Op1.getOperand(0); 9863 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9864 Op0.getNode() == Op1.getNode() && 9865 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9866 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9867 N->getValueType(0), Op0.getOperand(0)); 9868 return SDValue(); 9869 } 9870 9871 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9872 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9873 /// i64 vector to have f64 elements, since the value can then be loaded 9874 /// directly into a VFP register. 9875 static bool hasNormalLoadOperand(SDNode *N) { 9876 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9877 for (unsigned i = 0; i < NumElts; ++i) { 9878 SDNode *Elt = N->getOperand(i).getNode(); 9879 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9880 return true; 9881 } 9882 return false; 9883 } 9884 9885 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9886 /// ISD::BUILD_VECTOR. 9887 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9888 TargetLowering::DAGCombinerInfo &DCI, 9889 const ARMSubtarget *Subtarget) { 9890 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9891 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9892 // into a pair of GPRs, which is fine when the value is used as a scalar, 9893 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9894 SelectionDAG &DAG = DCI.DAG; 9895 if (N->getNumOperands() == 2) 9896 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 9897 return RV; 9898 9899 // Load i64 elements as f64 values so that type legalization does not split 9900 // them up into i32 values. 9901 EVT VT = N->getValueType(0); 9902 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9903 return SDValue(); 9904 SDLoc dl(N); 9905 SmallVector<SDValue, 8> Ops; 9906 unsigned NumElts = VT.getVectorNumElements(); 9907 for (unsigned i = 0; i < NumElts; ++i) { 9908 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9909 Ops.push_back(V); 9910 // Make the DAGCombiner fold the bitcast. 9911 DCI.AddToWorklist(V.getNode()); 9912 } 9913 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9914 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 9915 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9916 } 9917 9918 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9919 static SDValue 9920 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9921 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9922 // At that time, we may have inserted bitcasts from integer to float. 9923 // If these bitcasts have survived DAGCombine, change the lowering of this 9924 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9925 // force to use floating point types. 9926 9927 // Make sure we can change the type of the vector. 9928 // This is possible iff: 9929 // 1. The vector is only used in a bitcast to a integer type. I.e., 9930 // 1.1. Vector is used only once. 9931 // 1.2. Use is a bit convert to an integer type. 9932 // 2. The size of its operands are 32-bits (64-bits are not legal). 9933 EVT VT = N->getValueType(0); 9934 EVT EltVT = VT.getVectorElementType(); 9935 9936 // Check 1.1. and 2. 9937 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9938 return SDValue(); 9939 9940 // By construction, the input type must be float. 9941 assert(EltVT == MVT::f32 && "Unexpected type!"); 9942 9943 // Check 1.2. 9944 SDNode *Use = *N->use_begin(); 9945 if (Use->getOpcode() != ISD::BITCAST || 9946 Use->getValueType(0).isFloatingPoint()) 9947 return SDValue(); 9948 9949 // Check profitability. 9950 // Model is, if more than half of the relevant operands are bitcast from 9951 // i32, turn the build_vector into a sequence of insert_vector_elt. 9952 // Relevant operands are everything that is not statically 9953 // (i.e., at compile time) bitcasted. 9954 unsigned NumOfBitCastedElts = 0; 9955 unsigned NumElts = VT.getVectorNumElements(); 9956 unsigned NumOfRelevantElts = NumElts; 9957 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9958 SDValue Elt = N->getOperand(Idx); 9959 if (Elt->getOpcode() == ISD::BITCAST) { 9960 // Assume only bit cast to i32 will go away. 9961 if (Elt->getOperand(0).getValueType() == MVT::i32) 9962 ++NumOfBitCastedElts; 9963 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 9964 // Constants are statically casted, thus do not count them as 9965 // relevant operands. 9966 --NumOfRelevantElts; 9967 } 9968 9969 // Check if more than half of the elements require a non-free bitcast. 9970 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9971 return SDValue(); 9972 9973 SelectionDAG &DAG = DCI.DAG; 9974 // Create the new vector type. 9975 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9976 // Check if the type is legal. 9977 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9978 if (!TLI.isTypeLegal(VecVT)) 9979 return SDValue(); 9980 9981 // Combine: 9982 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9983 // => BITCAST INSERT_VECTOR_ELT 9984 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9985 // (BITCAST EN), N. 9986 SDValue Vec = DAG.getUNDEF(VecVT); 9987 SDLoc dl(N); 9988 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9989 SDValue V = N->getOperand(Idx); 9990 if (V.isUndef()) 9991 continue; 9992 if (V.getOpcode() == ISD::BITCAST && 9993 V->getOperand(0).getValueType() == MVT::i32) 9994 // Fold obvious case. 9995 V = V.getOperand(0); 9996 else { 9997 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9998 // Make the DAGCombiner fold the bitcasts. 9999 DCI.AddToWorklist(V.getNode()); 10000 } 10001 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 10002 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 10003 } 10004 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 10005 // Make the DAGCombiner fold the bitcasts. 10006 DCI.AddToWorklist(Vec.getNode()); 10007 return Vec; 10008 } 10009 10010 /// PerformInsertEltCombine - Target-specific dag combine xforms for 10011 /// ISD::INSERT_VECTOR_ELT. 10012 static SDValue PerformInsertEltCombine(SDNode *N, 10013 TargetLowering::DAGCombinerInfo &DCI) { 10014 // Bitcast an i64 load inserted into a vector to f64. 10015 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10016 EVT VT = N->getValueType(0); 10017 SDNode *Elt = N->getOperand(1).getNode(); 10018 if (VT.getVectorElementType() != MVT::i64 || 10019 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 10020 return SDValue(); 10021 10022 SelectionDAG &DAG = DCI.DAG; 10023 SDLoc dl(N); 10024 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10025 VT.getVectorNumElements()); 10026 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 10027 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 10028 // Make the DAGCombiner fold the bitcasts. 10029 DCI.AddToWorklist(Vec.getNode()); 10030 DCI.AddToWorklist(V.getNode()); 10031 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 10032 Vec, V, N->getOperand(2)); 10033 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 10034 } 10035 10036 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 10037 /// ISD::VECTOR_SHUFFLE. 10038 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 10039 // The LLVM shufflevector instruction does not require the shuffle mask 10040 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 10041 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 10042 // operands do not match the mask length, they are extended by concatenating 10043 // them with undef vectors. That is probably the right thing for other 10044 // targets, but for NEON it is better to concatenate two double-register 10045 // size vector operands into a single quad-register size vector. Do that 10046 // transformation here: 10047 // shuffle(concat(v1, undef), concat(v2, undef)) -> 10048 // shuffle(concat(v1, v2), undef) 10049 SDValue Op0 = N->getOperand(0); 10050 SDValue Op1 = N->getOperand(1); 10051 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 10052 Op1.getOpcode() != ISD::CONCAT_VECTORS || 10053 Op0.getNumOperands() != 2 || 10054 Op1.getNumOperands() != 2) 10055 return SDValue(); 10056 SDValue Concat0Op1 = Op0.getOperand(1); 10057 SDValue Concat1Op1 = Op1.getOperand(1); 10058 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 10059 return SDValue(); 10060 // Skip the transformation if any of the types are illegal. 10061 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10062 EVT VT = N->getValueType(0); 10063 if (!TLI.isTypeLegal(VT) || 10064 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 10065 !TLI.isTypeLegal(Concat1Op1.getValueType())) 10066 return SDValue(); 10067 10068 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10069 Op0.getOperand(0), Op1.getOperand(0)); 10070 // Translate the shuffle mask. 10071 SmallVector<int, 16> NewMask; 10072 unsigned NumElts = VT.getVectorNumElements(); 10073 unsigned HalfElts = NumElts/2; 10074 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10075 for (unsigned n = 0; n < NumElts; ++n) { 10076 int MaskElt = SVN->getMaskElt(n); 10077 int NewElt = -1; 10078 if (MaskElt < (int)HalfElts) 10079 NewElt = MaskElt; 10080 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 10081 NewElt = HalfElts + MaskElt - NumElts; 10082 NewMask.push_back(NewElt); 10083 } 10084 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 10085 DAG.getUNDEF(VT), NewMask); 10086 } 10087 10088 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 10089 /// NEON load/store intrinsics, and generic vector load/stores, to merge 10090 /// base address updates. 10091 /// For generic load/stores, the memory type is assumed to be a vector. 10092 /// The caller is assumed to have checked legality. 10093 static SDValue CombineBaseUpdate(SDNode *N, 10094 TargetLowering::DAGCombinerInfo &DCI) { 10095 SelectionDAG &DAG = DCI.DAG; 10096 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 10097 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 10098 const bool isStore = N->getOpcode() == ISD::STORE; 10099 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 10100 SDValue Addr = N->getOperand(AddrOpIdx); 10101 MemSDNode *MemN = cast<MemSDNode>(N); 10102 SDLoc dl(N); 10103 10104 // Search for a use of the address operand that is an increment. 10105 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 10106 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 10107 SDNode *User = *UI; 10108 if (User->getOpcode() != ISD::ADD || 10109 UI.getUse().getResNo() != Addr.getResNo()) 10110 continue; 10111 10112 // Check that the add is independent of the load/store. Otherwise, folding 10113 // it would create a cycle. 10114 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 10115 continue; 10116 10117 // Find the new opcode for the updating load/store. 10118 bool isLoadOp = true; 10119 bool isLaneOp = false; 10120 unsigned NewOpc = 0; 10121 unsigned NumVecs = 0; 10122 if (isIntrinsic) { 10123 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10124 switch (IntNo) { 10125 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 10126 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 10127 NumVecs = 1; break; 10128 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 10129 NumVecs = 2; break; 10130 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 10131 NumVecs = 3; break; 10132 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 10133 NumVecs = 4; break; 10134 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 10135 NumVecs = 2; isLaneOp = true; break; 10136 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 10137 NumVecs = 3; isLaneOp = true; break; 10138 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 10139 NumVecs = 4; isLaneOp = true; break; 10140 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 10141 NumVecs = 1; isLoadOp = false; break; 10142 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 10143 NumVecs = 2; isLoadOp = false; break; 10144 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 10145 NumVecs = 3; isLoadOp = false; break; 10146 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 10147 NumVecs = 4; isLoadOp = false; break; 10148 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 10149 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 10150 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 10151 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 10152 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 10153 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 10154 } 10155 } else { 10156 isLaneOp = true; 10157 switch (N->getOpcode()) { 10158 default: llvm_unreachable("unexpected opcode for Neon base update"); 10159 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 10160 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 10161 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 10162 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 10163 NumVecs = 1; isLaneOp = false; break; 10164 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 10165 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 10166 } 10167 } 10168 10169 // Find the size of memory referenced by the load/store. 10170 EVT VecTy; 10171 if (isLoadOp) { 10172 VecTy = N->getValueType(0); 10173 } else if (isIntrinsic) { 10174 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 10175 } else { 10176 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 10177 VecTy = N->getOperand(1).getValueType(); 10178 } 10179 10180 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 10181 if (isLaneOp) 10182 NumBytes /= VecTy.getVectorNumElements(); 10183 10184 // If the increment is a constant, it must match the memory ref size. 10185 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10186 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 10187 uint64_t IncVal = CInc->getZExtValue(); 10188 if (IncVal != NumBytes) 10189 continue; 10190 } else if (NumBytes >= 3 * 16) { 10191 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 10192 // separate instructions that make it harder to use a non-constant update. 10193 continue; 10194 } 10195 10196 // OK, we found an ADD we can fold into the base update. 10197 // Now, create a _UPD node, taking care of not breaking alignment. 10198 10199 EVT AlignedVecTy = VecTy; 10200 unsigned Alignment = MemN->getAlignment(); 10201 10202 // If this is a less-than-standard-aligned load/store, change the type to 10203 // match the standard alignment. 10204 // The alignment is overlooked when selecting _UPD variants; and it's 10205 // easier to introduce bitcasts here than fix that. 10206 // There are 3 ways to get to this base-update combine: 10207 // - intrinsics: they are assumed to be properly aligned (to the standard 10208 // alignment of the memory type), so we don't need to do anything. 10209 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 10210 // intrinsics, so, likewise, there's nothing to do. 10211 // - generic load/store instructions: the alignment is specified as an 10212 // explicit operand, rather than implicitly as the standard alignment 10213 // of the memory type (like the intrisics). We need to change the 10214 // memory type to match the explicit alignment. That way, we don't 10215 // generate non-standard-aligned ARMISD::VLDx nodes. 10216 if (isa<LSBaseSDNode>(N)) { 10217 if (Alignment == 0) 10218 Alignment = 1; 10219 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 10220 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 10221 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 10222 assert(!isLaneOp && "Unexpected generic load/store lane."); 10223 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 10224 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 10225 } 10226 // Don't set an explicit alignment on regular load/stores that we want 10227 // to transform to VLD/VST 1_UPD nodes. 10228 // This matches the behavior of regular load/stores, which only get an 10229 // explicit alignment if the MMO alignment is larger than the standard 10230 // alignment of the memory type. 10231 // Intrinsics, however, always get an explicit alignment, set to the 10232 // alignment of the MMO. 10233 Alignment = 1; 10234 } 10235 10236 // Create the new updating load/store node. 10237 // First, create an SDVTList for the new updating node's results. 10238 EVT Tys[6]; 10239 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 10240 unsigned n; 10241 for (n = 0; n < NumResultVecs; ++n) 10242 Tys[n] = AlignedVecTy; 10243 Tys[n++] = MVT::i32; 10244 Tys[n] = MVT::Other; 10245 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 10246 10247 // Then, gather the new node's operands. 10248 SmallVector<SDValue, 8> Ops; 10249 Ops.push_back(N->getOperand(0)); // incoming chain 10250 Ops.push_back(N->getOperand(AddrOpIdx)); 10251 Ops.push_back(Inc); 10252 10253 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 10254 // Try to match the intrinsic's signature 10255 Ops.push_back(StN->getValue()); 10256 } else { 10257 // Loads (and of course intrinsics) match the intrinsics' signature, 10258 // so just add all but the alignment operand. 10259 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 10260 Ops.push_back(N->getOperand(i)); 10261 } 10262 10263 // For all node types, the alignment operand is always the last one. 10264 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 10265 10266 // If this is a non-standard-aligned STORE, the penultimate operand is the 10267 // stored value. Bitcast it to the aligned type. 10268 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 10269 SDValue &StVal = Ops[Ops.size()-2]; 10270 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 10271 } 10272 10273 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 10274 Ops, AlignedVecTy, 10275 MemN->getMemOperand()); 10276 10277 // Update the uses. 10278 SmallVector<SDValue, 5> NewResults; 10279 for (unsigned i = 0; i < NumResultVecs; ++i) 10280 NewResults.push_back(SDValue(UpdN.getNode(), i)); 10281 10282 // If this is an non-standard-aligned LOAD, the first result is the loaded 10283 // value. Bitcast it to the expected result type. 10284 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 10285 SDValue &LdVal = NewResults[0]; 10286 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 10287 } 10288 10289 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 10290 DCI.CombineTo(N, NewResults); 10291 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 10292 10293 break; 10294 } 10295 return SDValue(); 10296 } 10297 10298 static SDValue PerformVLDCombine(SDNode *N, 10299 TargetLowering::DAGCombinerInfo &DCI) { 10300 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10301 return SDValue(); 10302 10303 return CombineBaseUpdate(N, DCI); 10304 } 10305 10306 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 10307 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 10308 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 10309 /// return true. 10310 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10311 SelectionDAG &DAG = DCI.DAG; 10312 EVT VT = N->getValueType(0); 10313 // vldN-dup instructions only support 64-bit vectors for N > 1. 10314 if (!VT.is64BitVector()) 10315 return false; 10316 10317 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 10318 SDNode *VLD = N->getOperand(0).getNode(); 10319 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 10320 return false; 10321 unsigned NumVecs = 0; 10322 unsigned NewOpc = 0; 10323 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 10324 if (IntNo == Intrinsic::arm_neon_vld2lane) { 10325 NumVecs = 2; 10326 NewOpc = ARMISD::VLD2DUP; 10327 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 10328 NumVecs = 3; 10329 NewOpc = ARMISD::VLD3DUP; 10330 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 10331 NumVecs = 4; 10332 NewOpc = ARMISD::VLD4DUP; 10333 } else { 10334 return false; 10335 } 10336 10337 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 10338 // numbers match the load. 10339 unsigned VLDLaneNo = 10340 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 10341 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10342 UI != UE; ++UI) { 10343 // Ignore uses of the chain result. 10344 if (UI.getUse().getResNo() == NumVecs) 10345 continue; 10346 SDNode *User = *UI; 10347 if (User->getOpcode() != ARMISD::VDUPLANE || 10348 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 10349 return false; 10350 } 10351 10352 // Create the vldN-dup node. 10353 EVT Tys[5]; 10354 unsigned n; 10355 for (n = 0; n < NumVecs; ++n) 10356 Tys[n] = VT; 10357 Tys[n] = MVT::Other; 10358 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 10359 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 10360 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 10361 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 10362 Ops, VLDMemInt->getMemoryVT(), 10363 VLDMemInt->getMemOperand()); 10364 10365 // Update the uses. 10366 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10367 UI != UE; ++UI) { 10368 unsigned ResNo = UI.getUse().getResNo(); 10369 // Ignore uses of the chain result. 10370 if (ResNo == NumVecs) 10371 continue; 10372 SDNode *User = *UI; 10373 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 10374 } 10375 10376 // Now the vldN-lane intrinsic is dead except for its chain result. 10377 // Update uses of the chain. 10378 std::vector<SDValue> VLDDupResults; 10379 for (unsigned n = 0; n < NumVecs; ++n) 10380 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 10381 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 10382 DCI.CombineTo(VLD, VLDDupResults); 10383 10384 return true; 10385 } 10386 10387 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 10388 /// ARMISD::VDUPLANE. 10389 static SDValue PerformVDUPLANECombine(SDNode *N, 10390 TargetLowering::DAGCombinerInfo &DCI) { 10391 SDValue Op = N->getOperand(0); 10392 10393 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 10394 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 10395 if (CombineVLDDUP(N, DCI)) 10396 return SDValue(N, 0); 10397 10398 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 10399 // redundant. Ignore bit_converts for now; element sizes are checked below. 10400 while (Op.getOpcode() == ISD::BITCAST) 10401 Op = Op.getOperand(0); 10402 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 10403 return SDValue(); 10404 10405 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 10406 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 10407 // The canonical VMOV for a zero vector uses a 32-bit element size. 10408 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10409 unsigned EltBits; 10410 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 10411 EltSize = 8; 10412 EVT VT = N->getValueType(0); 10413 if (EltSize > VT.getVectorElementType().getSizeInBits()) 10414 return SDValue(); 10415 10416 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 10417 } 10418 10419 static SDValue PerformLOADCombine(SDNode *N, 10420 TargetLowering::DAGCombinerInfo &DCI) { 10421 EVT VT = N->getValueType(0); 10422 10423 // If this is a legal vector load, try to combine it into a VLD1_UPD. 10424 if (ISD::isNormalLoad(N) && VT.isVector() && 10425 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10426 return CombineBaseUpdate(N, DCI); 10427 10428 return SDValue(); 10429 } 10430 10431 /// PerformSTORECombine - Target-specific dag combine xforms for 10432 /// ISD::STORE. 10433 static SDValue PerformSTORECombine(SDNode *N, 10434 TargetLowering::DAGCombinerInfo &DCI) { 10435 StoreSDNode *St = cast<StoreSDNode>(N); 10436 if (St->isVolatile()) 10437 return SDValue(); 10438 10439 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10440 // pack all of the elements in one place. Next, store to memory in fewer 10441 // chunks. 10442 SDValue StVal = St->getValue(); 10443 EVT VT = StVal.getValueType(); 10444 if (St->isTruncatingStore() && VT.isVector()) { 10445 SelectionDAG &DAG = DCI.DAG; 10446 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10447 EVT StVT = St->getMemoryVT(); 10448 unsigned NumElems = VT.getVectorNumElements(); 10449 assert(StVT != VT && "Cannot truncate to the same type"); 10450 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 10451 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 10452 10453 // From, To sizes and ElemCount must be pow of two 10454 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10455 10456 // We are going to use the original vector elt for storing. 10457 // Accumulated smaller vector elements must be a multiple of the store size. 10458 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10459 10460 unsigned SizeRatio = FromEltSz / ToEltSz; 10461 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10462 10463 // Create a type on which we perform the shuffle. 10464 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10465 NumElems*SizeRatio); 10466 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10467 10468 SDLoc DL(St); 10469 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10470 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10471 for (unsigned i = 0; i < NumElems; ++i) 10472 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10473 ? (i + 1) * SizeRatio - 1 10474 : i * SizeRatio; 10475 10476 // Can't shuffle using an illegal type. 10477 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10478 10479 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10480 DAG.getUNDEF(WideVec.getValueType()), 10481 ShuffleVec); 10482 // At this point all of the data is stored at the bottom of the 10483 // register. We now need to save it to mem. 10484 10485 // Find the largest store unit 10486 MVT StoreType = MVT::i8; 10487 for (MVT Tp : MVT::integer_valuetypes()) { 10488 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10489 StoreType = Tp; 10490 } 10491 // Didn't find a legal store type. 10492 if (!TLI.isTypeLegal(StoreType)) 10493 return SDValue(); 10494 10495 // Bitcast the original vector into a vector of store-size units 10496 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10497 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10498 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10499 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10500 SmallVector<SDValue, 8> Chains; 10501 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10502 TLI.getPointerTy(DAG.getDataLayout())); 10503 SDValue BasePtr = St->getBasePtr(); 10504 10505 // Perform one or more big stores into memory. 10506 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10507 for (unsigned I = 0; I < E; I++) { 10508 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10509 StoreType, ShuffWide, 10510 DAG.getIntPtrConstant(I, DL)); 10511 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10512 St->getPointerInfo(), St->getAlignment(), 10513 St->getMemOperand()->getFlags()); 10514 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10515 Increment); 10516 Chains.push_back(Ch); 10517 } 10518 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10519 } 10520 10521 if (!ISD::isNormalStore(St)) 10522 return SDValue(); 10523 10524 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10525 // ARM stores of arguments in the same cache line. 10526 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10527 StVal.getNode()->hasOneUse()) { 10528 SelectionDAG &DAG = DCI.DAG; 10529 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10530 SDLoc DL(St); 10531 SDValue BasePtr = St->getBasePtr(); 10532 SDValue NewST1 = DAG.getStore( 10533 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 10534 BasePtr, St->getPointerInfo(), St->getAlignment(), 10535 St->getMemOperand()->getFlags()); 10536 10537 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10538 DAG.getConstant(4, DL, MVT::i32)); 10539 return DAG.getStore(NewST1.getValue(0), DL, 10540 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10541 OffsetPtr, St->getPointerInfo(), 10542 std::min(4U, St->getAlignment() / 2), 10543 St->getMemOperand()->getFlags()); 10544 } 10545 10546 if (StVal.getValueType() == MVT::i64 && 10547 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10548 10549 // Bitcast an i64 store extracted from a vector to f64. 10550 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10551 SelectionDAG &DAG = DCI.DAG; 10552 SDLoc dl(StVal); 10553 SDValue IntVec = StVal.getOperand(0); 10554 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10555 IntVec.getValueType().getVectorNumElements()); 10556 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10557 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10558 Vec, StVal.getOperand(1)); 10559 dl = SDLoc(N); 10560 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10561 // Make the DAGCombiner fold the bitcasts. 10562 DCI.AddToWorklist(Vec.getNode()); 10563 DCI.AddToWorklist(ExtElt.getNode()); 10564 DCI.AddToWorklist(V.getNode()); 10565 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10566 St->getPointerInfo(), St->getAlignment(), 10567 St->getMemOperand()->getFlags(), St->getAAInfo()); 10568 } 10569 10570 // If this is a legal vector store, try to combine it into a VST1_UPD. 10571 if (ISD::isNormalStore(N) && VT.isVector() && 10572 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10573 return CombineBaseUpdate(N, DCI); 10574 10575 return SDValue(); 10576 } 10577 10578 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10579 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10580 /// when the VMUL has a constant operand that is a power of 2. 10581 /// 10582 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10583 /// vmul.f32 d16, d17, d16 10584 /// vcvt.s32.f32 d16, d16 10585 /// becomes: 10586 /// vcvt.s32.f32 d16, d16, #3 10587 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10588 const ARMSubtarget *Subtarget) { 10589 if (!Subtarget->hasNEON()) 10590 return SDValue(); 10591 10592 SDValue Op = N->getOperand(0); 10593 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10594 Op.getOpcode() != ISD::FMUL) 10595 return SDValue(); 10596 10597 SDValue ConstVec = Op->getOperand(1); 10598 if (!isa<BuildVectorSDNode>(ConstVec)) 10599 return SDValue(); 10600 10601 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10602 uint32_t FloatBits = FloatTy.getSizeInBits(); 10603 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10604 uint32_t IntBits = IntTy.getSizeInBits(); 10605 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10606 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10607 // These instructions only exist converting from f32 to i32. We can handle 10608 // smaller integers by generating an extra truncate, but larger ones would 10609 // be lossy. We also can't handle more then 4 lanes, since these intructions 10610 // only support v2i32/v4i32 types. 10611 return SDValue(); 10612 } 10613 10614 BitVector UndefElements; 10615 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10616 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10617 if (C == -1 || C == 0 || C > 32) 10618 return SDValue(); 10619 10620 SDLoc dl(N); 10621 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10622 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10623 Intrinsic::arm_neon_vcvtfp2fxu; 10624 SDValue FixConv = DAG.getNode( 10625 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10626 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10627 DAG.getConstant(C, dl, MVT::i32)); 10628 10629 if (IntBits < FloatBits) 10630 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10631 10632 return FixConv; 10633 } 10634 10635 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10636 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10637 /// when the VDIV has a constant operand that is a power of 2. 10638 /// 10639 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10640 /// vcvt.f32.s32 d16, d16 10641 /// vdiv.f32 d16, d17, d16 10642 /// becomes: 10643 /// vcvt.f32.s32 d16, d16, #3 10644 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10645 const ARMSubtarget *Subtarget) { 10646 if (!Subtarget->hasNEON()) 10647 return SDValue(); 10648 10649 SDValue Op = N->getOperand(0); 10650 unsigned OpOpcode = Op.getNode()->getOpcode(); 10651 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 10652 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10653 return SDValue(); 10654 10655 SDValue ConstVec = N->getOperand(1); 10656 if (!isa<BuildVectorSDNode>(ConstVec)) 10657 return SDValue(); 10658 10659 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10660 uint32_t FloatBits = FloatTy.getSizeInBits(); 10661 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10662 uint32_t IntBits = IntTy.getSizeInBits(); 10663 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10664 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10665 // These instructions only exist converting from i32 to f32. We can handle 10666 // smaller integers by generating an extra extend, but larger ones would 10667 // be lossy. We also can't handle more then 4 lanes, since these intructions 10668 // only support v2i32/v4i32 types. 10669 return SDValue(); 10670 } 10671 10672 BitVector UndefElements; 10673 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10674 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10675 if (C == -1 || C == 0 || C > 32) 10676 return SDValue(); 10677 10678 SDLoc dl(N); 10679 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10680 SDValue ConvInput = Op.getOperand(0); 10681 if (IntBits < FloatBits) 10682 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10683 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10684 ConvInput); 10685 10686 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10687 Intrinsic::arm_neon_vcvtfxu2fp; 10688 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10689 Op.getValueType(), 10690 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10691 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10692 } 10693 10694 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10695 /// operand of a vector shift operation, where all the elements of the 10696 /// build_vector must have the same constant integer value. 10697 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10698 // Ignore bit_converts. 10699 while (Op.getOpcode() == ISD::BITCAST) 10700 Op = Op.getOperand(0); 10701 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10702 APInt SplatBits, SplatUndef; 10703 unsigned SplatBitSize; 10704 bool HasAnyUndefs; 10705 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10706 HasAnyUndefs, ElementBits) || 10707 SplatBitSize > ElementBits) 10708 return false; 10709 Cnt = SplatBits.getSExtValue(); 10710 return true; 10711 } 10712 10713 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10714 /// operand of a vector shift left operation. That value must be in the range: 10715 /// 0 <= Value < ElementBits for a left shift; or 10716 /// 0 <= Value <= ElementBits for a long left shift. 10717 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10718 assert(VT.isVector() && "vector shift count is not a vector type"); 10719 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10720 if (! getVShiftImm(Op, ElementBits, Cnt)) 10721 return false; 10722 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10723 } 10724 10725 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10726 /// operand of a vector shift right operation. For a shift opcode, the value 10727 /// is positive, but for an intrinsic the value count must be negative. The 10728 /// absolute value must be in the range: 10729 /// 1 <= |Value| <= ElementBits for a right shift; or 10730 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10731 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10732 int64_t &Cnt) { 10733 assert(VT.isVector() && "vector shift count is not a vector type"); 10734 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10735 if (! getVShiftImm(Op, ElementBits, Cnt)) 10736 return false; 10737 if (!isIntrinsic) 10738 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10739 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10740 Cnt = -Cnt; 10741 return true; 10742 } 10743 return false; 10744 } 10745 10746 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10747 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10748 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10749 switch (IntNo) { 10750 default: 10751 // Don't do anything for most intrinsics. 10752 break; 10753 10754 // Vector shifts: check for immediate versions and lower them. 10755 // Note: This is done during DAG combining instead of DAG legalizing because 10756 // the build_vectors for 64-bit vector element shift counts are generally 10757 // not legal, and it is hard to see their values after they get legalized to 10758 // loads from a constant pool. 10759 case Intrinsic::arm_neon_vshifts: 10760 case Intrinsic::arm_neon_vshiftu: 10761 case Intrinsic::arm_neon_vrshifts: 10762 case Intrinsic::arm_neon_vrshiftu: 10763 case Intrinsic::arm_neon_vrshiftn: 10764 case Intrinsic::arm_neon_vqshifts: 10765 case Intrinsic::arm_neon_vqshiftu: 10766 case Intrinsic::arm_neon_vqshiftsu: 10767 case Intrinsic::arm_neon_vqshiftns: 10768 case Intrinsic::arm_neon_vqshiftnu: 10769 case Intrinsic::arm_neon_vqshiftnsu: 10770 case Intrinsic::arm_neon_vqrshiftns: 10771 case Intrinsic::arm_neon_vqrshiftnu: 10772 case Intrinsic::arm_neon_vqrshiftnsu: { 10773 EVT VT = N->getOperand(1).getValueType(); 10774 int64_t Cnt; 10775 unsigned VShiftOpc = 0; 10776 10777 switch (IntNo) { 10778 case Intrinsic::arm_neon_vshifts: 10779 case Intrinsic::arm_neon_vshiftu: 10780 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10781 VShiftOpc = ARMISD::VSHL; 10782 break; 10783 } 10784 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10785 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10786 ARMISD::VSHRs : ARMISD::VSHRu); 10787 break; 10788 } 10789 return SDValue(); 10790 10791 case Intrinsic::arm_neon_vrshifts: 10792 case Intrinsic::arm_neon_vrshiftu: 10793 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10794 break; 10795 return SDValue(); 10796 10797 case Intrinsic::arm_neon_vqshifts: 10798 case Intrinsic::arm_neon_vqshiftu: 10799 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10800 break; 10801 return SDValue(); 10802 10803 case Intrinsic::arm_neon_vqshiftsu: 10804 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10805 break; 10806 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10807 10808 case Intrinsic::arm_neon_vrshiftn: 10809 case Intrinsic::arm_neon_vqshiftns: 10810 case Intrinsic::arm_neon_vqshiftnu: 10811 case Intrinsic::arm_neon_vqshiftnsu: 10812 case Intrinsic::arm_neon_vqrshiftns: 10813 case Intrinsic::arm_neon_vqrshiftnu: 10814 case Intrinsic::arm_neon_vqrshiftnsu: 10815 // Narrowing shifts require an immediate right shift. 10816 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10817 break; 10818 llvm_unreachable("invalid shift count for narrowing vector shift " 10819 "intrinsic"); 10820 10821 default: 10822 llvm_unreachable("unhandled vector shift"); 10823 } 10824 10825 switch (IntNo) { 10826 case Intrinsic::arm_neon_vshifts: 10827 case Intrinsic::arm_neon_vshiftu: 10828 // Opcode already set above. 10829 break; 10830 case Intrinsic::arm_neon_vrshifts: 10831 VShiftOpc = ARMISD::VRSHRs; break; 10832 case Intrinsic::arm_neon_vrshiftu: 10833 VShiftOpc = ARMISD::VRSHRu; break; 10834 case Intrinsic::arm_neon_vrshiftn: 10835 VShiftOpc = ARMISD::VRSHRN; break; 10836 case Intrinsic::arm_neon_vqshifts: 10837 VShiftOpc = ARMISD::VQSHLs; break; 10838 case Intrinsic::arm_neon_vqshiftu: 10839 VShiftOpc = ARMISD::VQSHLu; break; 10840 case Intrinsic::arm_neon_vqshiftsu: 10841 VShiftOpc = ARMISD::VQSHLsu; break; 10842 case Intrinsic::arm_neon_vqshiftns: 10843 VShiftOpc = ARMISD::VQSHRNs; break; 10844 case Intrinsic::arm_neon_vqshiftnu: 10845 VShiftOpc = ARMISD::VQSHRNu; break; 10846 case Intrinsic::arm_neon_vqshiftnsu: 10847 VShiftOpc = ARMISD::VQSHRNsu; break; 10848 case Intrinsic::arm_neon_vqrshiftns: 10849 VShiftOpc = ARMISD::VQRSHRNs; break; 10850 case Intrinsic::arm_neon_vqrshiftnu: 10851 VShiftOpc = ARMISD::VQRSHRNu; break; 10852 case Intrinsic::arm_neon_vqrshiftnsu: 10853 VShiftOpc = ARMISD::VQRSHRNsu; break; 10854 } 10855 10856 SDLoc dl(N); 10857 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10858 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10859 } 10860 10861 case Intrinsic::arm_neon_vshiftins: { 10862 EVT VT = N->getOperand(1).getValueType(); 10863 int64_t Cnt; 10864 unsigned VShiftOpc = 0; 10865 10866 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10867 VShiftOpc = ARMISD::VSLI; 10868 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10869 VShiftOpc = ARMISD::VSRI; 10870 else { 10871 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10872 } 10873 10874 SDLoc dl(N); 10875 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10876 N->getOperand(1), N->getOperand(2), 10877 DAG.getConstant(Cnt, dl, MVT::i32)); 10878 } 10879 10880 case Intrinsic::arm_neon_vqrshifts: 10881 case Intrinsic::arm_neon_vqrshiftu: 10882 // No immediate versions of these to check for. 10883 break; 10884 } 10885 10886 return SDValue(); 10887 } 10888 10889 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10890 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10891 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10892 /// vector element shift counts are generally not legal, and it is hard to see 10893 /// their values after they get legalized to loads from a constant pool. 10894 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10895 const ARMSubtarget *ST) { 10896 EVT VT = N->getValueType(0); 10897 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10898 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10899 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10900 SDValue N1 = N->getOperand(1); 10901 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10902 SDValue N0 = N->getOperand(0); 10903 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10904 DAG.MaskedValueIsZero(N0.getOperand(0), 10905 APInt::getHighBitsSet(32, 16))) 10906 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10907 } 10908 } 10909 10910 // Nothing to be done for scalar shifts. 10911 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10912 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10913 return SDValue(); 10914 10915 assert(ST->hasNEON() && "unexpected vector shift"); 10916 int64_t Cnt; 10917 10918 switch (N->getOpcode()) { 10919 default: llvm_unreachable("unexpected shift opcode"); 10920 10921 case ISD::SHL: 10922 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10923 SDLoc dl(N); 10924 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10925 DAG.getConstant(Cnt, dl, MVT::i32)); 10926 } 10927 break; 10928 10929 case ISD::SRA: 10930 case ISD::SRL: 10931 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10932 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10933 ARMISD::VSHRs : ARMISD::VSHRu); 10934 SDLoc dl(N); 10935 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10936 DAG.getConstant(Cnt, dl, MVT::i32)); 10937 } 10938 } 10939 return SDValue(); 10940 } 10941 10942 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10943 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10944 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10945 const ARMSubtarget *ST) { 10946 SDValue N0 = N->getOperand(0); 10947 10948 // Check for sign- and zero-extensions of vector extract operations of 8- 10949 // and 16-bit vector elements. NEON supports these directly. They are 10950 // handled during DAG combining because type legalization will promote them 10951 // to 32-bit types and it is messy to recognize the operations after that. 10952 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10953 SDValue Vec = N0.getOperand(0); 10954 SDValue Lane = N0.getOperand(1); 10955 EVT VT = N->getValueType(0); 10956 EVT EltVT = N0.getValueType(); 10957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10958 10959 if (VT == MVT::i32 && 10960 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10961 TLI.isTypeLegal(Vec.getValueType()) && 10962 isa<ConstantSDNode>(Lane)) { 10963 10964 unsigned Opc = 0; 10965 switch (N->getOpcode()) { 10966 default: llvm_unreachable("unexpected opcode"); 10967 case ISD::SIGN_EXTEND: 10968 Opc = ARMISD::VGETLANEs; 10969 break; 10970 case ISD::ZERO_EXTEND: 10971 case ISD::ANY_EXTEND: 10972 Opc = ARMISD::VGETLANEu; 10973 break; 10974 } 10975 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10976 } 10977 } 10978 10979 return SDValue(); 10980 } 10981 10982 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10983 APInt &KnownOne) { 10984 if (Op.getOpcode() == ARMISD::BFI) { 10985 // Conservatively, we can recurse down the first operand 10986 // and just mask out all affected bits. 10987 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10988 10989 // The operand to BFI is already a mask suitable for removing the bits it 10990 // sets. 10991 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10992 const APInt &Mask = CI->getAPIntValue(); 10993 KnownZero &= Mask; 10994 KnownOne &= Mask; 10995 return; 10996 } 10997 if (Op.getOpcode() == ARMISD::CMOV) { 10998 APInt KZ2(KnownZero.getBitWidth(), 0); 10999 APInt KO2(KnownOne.getBitWidth(), 0); 11000 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 11001 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 11002 11003 KnownZero &= KZ2; 11004 KnownOne &= KO2; 11005 return; 11006 } 11007 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 11008 } 11009 11010 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 11011 // If we have a CMOV, OR and AND combination such as: 11012 // if (x & CN) 11013 // y |= CM; 11014 // 11015 // And: 11016 // * CN is a single bit; 11017 // * All bits covered by CM are known zero in y 11018 // 11019 // Then we can convert this into a sequence of BFI instructions. This will 11020 // always be a win if CM is a single bit, will always be no worse than the 11021 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 11022 // three bits (due to the extra IT instruction). 11023 11024 SDValue Op0 = CMOV->getOperand(0); 11025 SDValue Op1 = CMOV->getOperand(1); 11026 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 11027 auto CC = CCNode->getAPIntValue().getLimitedValue(); 11028 SDValue CmpZ = CMOV->getOperand(4); 11029 11030 // The compare must be against zero. 11031 if (!isNullConstant(CmpZ->getOperand(1))) 11032 return SDValue(); 11033 11034 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 11035 SDValue And = CmpZ->getOperand(0); 11036 if (And->getOpcode() != ISD::AND) 11037 return SDValue(); 11038 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 11039 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 11040 return SDValue(); 11041 SDValue X = And->getOperand(0); 11042 11043 if (CC == ARMCC::EQ) { 11044 // We're performing an "equal to zero" compare. Swap the operands so we 11045 // canonicalize on a "not equal to zero" compare. 11046 std::swap(Op0, Op1); 11047 } else { 11048 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 11049 } 11050 11051 if (Op1->getOpcode() != ISD::OR) 11052 return SDValue(); 11053 11054 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 11055 if (!OrC) 11056 return SDValue(); 11057 SDValue Y = Op1->getOperand(0); 11058 11059 if (Op0 != Y) 11060 return SDValue(); 11061 11062 // Now, is it profitable to continue? 11063 APInt OrCI = OrC->getAPIntValue(); 11064 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 11065 if (OrCI.countPopulation() > Heuristic) 11066 return SDValue(); 11067 11068 // Lastly, can we determine that the bits defined by OrCI 11069 // are zero in Y? 11070 APInt KnownZero, KnownOne; 11071 computeKnownBits(DAG, Y, KnownZero, KnownOne); 11072 if ((OrCI & KnownZero) != OrCI) 11073 return SDValue(); 11074 11075 // OK, we can do the combine. 11076 SDValue V = Y; 11077 SDLoc dl(X); 11078 EVT VT = X.getValueType(); 11079 unsigned BitInX = AndC->getAPIntValue().logBase2(); 11080 11081 if (BitInX != 0) { 11082 // We must shift X first. 11083 X = DAG.getNode(ISD::SRL, dl, VT, X, 11084 DAG.getConstant(BitInX, dl, VT)); 11085 } 11086 11087 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 11088 BitInY < NumActiveBits; ++BitInY) { 11089 if (OrCI[BitInY] == 0) 11090 continue; 11091 APInt Mask(VT.getSizeInBits(), 0); 11092 Mask.setBit(BitInY); 11093 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 11094 // Confusingly, the operand is an *inverted* mask. 11095 DAG.getConstant(~Mask, dl, VT)); 11096 } 11097 11098 return V; 11099 } 11100 11101 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 11102 SDValue 11103 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 11104 SDValue Cmp = N->getOperand(4); 11105 if (Cmp.getOpcode() != ARMISD::CMPZ) 11106 // Only looking at NE cases. 11107 return SDValue(); 11108 11109 EVT VT = N->getValueType(0); 11110 SDLoc dl(N); 11111 SDValue LHS = Cmp.getOperand(0); 11112 SDValue RHS = Cmp.getOperand(1); 11113 SDValue Chain = N->getOperand(0); 11114 SDValue BB = N->getOperand(1); 11115 SDValue ARMcc = N->getOperand(2); 11116 ARMCC::CondCodes CC = 11117 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11118 11119 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 11120 // -> (brcond Chain BB CC CPSR Cmp) 11121 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 11122 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 11123 LHS->getOperand(0)->hasOneUse()) { 11124 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 11125 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 11126 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11127 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11128 if ((LHS00C && LHS00C->getZExtValue() == 0) && 11129 (LHS01C && LHS01C->getZExtValue() == 1) && 11130 (LHS1C && LHS1C->getZExtValue() == 1) && 11131 (RHSC && RHSC->getZExtValue() == 0)) { 11132 return DAG.getNode( 11133 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 11134 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 11135 } 11136 } 11137 11138 return SDValue(); 11139 } 11140 11141 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 11142 SDValue 11143 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 11144 SDValue Cmp = N->getOperand(4); 11145 if (Cmp.getOpcode() != ARMISD::CMPZ) 11146 // Only looking at EQ and NE cases. 11147 return SDValue(); 11148 11149 EVT VT = N->getValueType(0); 11150 SDLoc dl(N); 11151 SDValue LHS = Cmp.getOperand(0); 11152 SDValue RHS = Cmp.getOperand(1); 11153 SDValue FalseVal = N->getOperand(0); 11154 SDValue TrueVal = N->getOperand(1); 11155 SDValue ARMcc = N->getOperand(2); 11156 ARMCC::CondCodes CC = 11157 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11158 11159 // BFI is only available on V6T2+. 11160 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 11161 SDValue R = PerformCMOVToBFICombine(N, DAG); 11162 if (R) 11163 return R; 11164 } 11165 11166 // Simplify 11167 // mov r1, r0 11168 // cmp r1, x 11169 // mov r0, y 11170 // moveq r0, x 11171 // to 11172 // cmp r0, x 11173 // movne r0, y 11174 // 11175 // mov r1, r0 11176 // cmp r1, x 11177 // mov r0, x 11178 // movne r0, y 11179 // to 11180 // cmp r0, x 11181 // movne r0, y 11182 /// FIXME: Turn this into a target neutral optimization? 11183 SDValue Res; 11184 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 11185 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 11186 N->getOperand(3), Cmp); 11187 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 11188 SDValue ARMcc; 11189 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 11190 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 11191 N->getOperand(3), NewCmp); 11192 } 11193 11194 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 11195 // -> (cmov F T CC CPSR Cmp) 11196 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 11197 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 11198 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11199 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11200 if ((LHS0C && LHS0C->getZExtValue() == 0) && 11201 (LHS1C && LHS1C->getZExtValue() == 1) && 11202 (RHSC && RHSC->getZExtValue() == 0)) { 11203 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 11204 LHS->getOperand(2), LHS->getOperand(3), 11205 LHS->getOperand(4)); 11206 } 11207 } 11208 11209 if (Res.getNode()) { 11210 APInt KnownZero, KnownOne; 11211 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 11212 // Capture demanded bits information that would be otherwise lost. 11213 if (KnownZero == 0xfffffffe) 11214 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11215 DAG.getValueType(MVT::i1)); 11216 else if (KnownZero == 0xffffff00) 11217 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11218 DAG.getValueType(MVT::i8)); 11219 else if (KnownZero == 0xffff0000) 11220 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11221 DAG.getValueType(MVT::i16)); 11222 } 11223 11224 return Res; 11225 } 11226 11227 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 11228 DAGCombinerInfo &DCI) const { 11229 switch (N->getOpcode()) { 11230 default: break; 11231 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 11232 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 11233 case ISD::SUB: return PerformSUBCombine(N, DCI); 11234 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 11235 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 11236 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 11237 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 11238 case ARMISD::BFI: return PerformBFICombine(N, DCI); 11239 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 11240 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 11241 case ISD::STORE: return PerformSTORECombine(N, DCI); 11242 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 11243 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 11244 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 11245 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 11246 case ISD::FP_TO_SINT: 11247 case ISD::FP_TO_UINT: 11248 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 11249 case ISD::FDIV: 11250 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 11251 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 11252 case ISD::SHL: 11253 case ISD::SRA: 11254 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 11255 case ISD::SIGN_EXTEND: 11256 case ISD::ZERO_EXTEND: 11257 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 11258 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 11259 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 11260 case ISD::LOAD: return PerformLOADCombine(N, DCI); 11261 case ARMISD::VLD2DUP: 11262 case ARMISD::VLD3DUP: 11263 case ARMISD::VLD4DUP: 11264 return PerformVLDCombine(N, DCI); 11265 case ARMISD::BUILD_VECTOR: 11266 return PerformARMBUILD_VECTORCombine(N, DCI); 11267 case ISD::INTRINSIC_VOID: 11268 case ISD::INTRINSIC_W_CHAIN: 11269 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11270 case Intrinsic::arm_neon_vld1: 11271 case Intrinsic::arm_neon_vld2: 11272 case Intrinsic::arm_neon_vld3: 11273 case Intrinsic::arm_neon_vld4: 11274 case Intrinsic::arm_neon_vld2lane: 11275 case Intrinsic::arm_neon_vld3lane: 11276 case Intrinsic::arm_neon_vld4lane: 11277 case Intrinsic::arm_neon_vst1: 11278 case Intrinsic::arm_neon_vst2: 11279 case Intrinsic::arm_neon_vst3: 11280 case Intrinsic::arm_neon_vst4: 11281 case Intrinsic::arm_neon_vst2lane: 11282 case Intrinsic::arm_neon_vst3lane: 11283 case Intrinsic::arm_neon_vst4lane: 11284 return PerformVLDCombine(N, DCI); 11285 default: break; 11286 } 11287 break; 11288 } 11289 return SDValue(); 11290 } 11291 11292 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 11293 EVT VT) const { 11294 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 11295 } 11296 11297 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 11298 unsigned, 11299 unsigned, 11300 bool *Fast) const { 11301 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 11302 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 11303 11304 switch (VT.getSimpleVT().SimpleTy) { 11305 default: 11306 return false; 11307 case MVT::i8: 11308 case MVT::i16: 11309 case MVT::i32: { 11310 // Unaligned access can use (for example) LRDB, LRDH, LDR 11311 if (AllowsUnaligned) { 11312 if (Fast) 11313 *Fast = Subtarget->hasV7Ops(); 11314 return true; 11315 } 11316 return false; 11317 } 11318 case MVT::f64: 11319 case MVT::v2f64: { 11320 // For any little-endian targets with neon, we can support unaligned ld/st 11321 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 11322 // A big-endian target may also explicitly support unaligned accesses 11323 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 11324 if (Fast) 11325 *Fast = true; 11326 return true; 11327 } 11328 return false; 11329 } 11330 } 11331 } 11332 11333 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 11334 unsigned AlignCheck) { 11335 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 11336 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 11337 } 11338 11339 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 11340 unsigned DstAlign, unsigned SrcAlign, 11341 bool IsMemset, bool ZeroMemset, 11342 bool MemcpyStrSrc, 11343 MachineFunction &MF) const { 11344 const Function *F = MF.getFunction(); 11345 11346 // See if we can use NEON instructions for this... 11347 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 11348 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 11349 bool Fast; 11350 if (Size >= 16 && 11351 (memOpAlign(SrcAlign, DstAlign, 16) || 11352 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 11353 return MVT::v2f64; 11354 } else if (Size >= 8 && 11355 (memOpAlign(SrcAlign, DstAlign, 8) || 11356 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 11357 Fast))) { 11358 return MVT::f64; 11359 } 11360 } 11361 11362 // Lowering to i32/i16 if the size permits. 11363 if (Size >= 4) 11364 return MVT::i32; 11365 else if (Size >= 2) 11366 return MVT::i16; 11367 11368 // Let the target-independent logic figure it out. 11369 return MVT::Other; 11370 } 11371 11372 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 11373 if (Val.getOpcode() != ISD::LOAD) 11374 return false; 11375 11376 EVT VT1 = Val.getValueType(); 11377 if (!VT1.isSimple() || !VT1.isInteger() || 11378 !VT2.isSimple() || !VT2.isInteger()) 11379 return false; 11380 11381 switch (VT1.getSimpleVT().SimpleTy) { 11382 default: break; 11383 case MVT::i1: 11384 case MVT::i8: 11385 case MVT::i16: 11386 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 11387 return true; 11388 } 11389 11390 return false; 11391 } 11392 11393 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 11394 EVT VT = ExtVal.getValueType(); 11395 11396 if (!isTypeLegal(VT)) 11397 return false; 11398 11399 // Don't create a loadext if we can fold the extension into a wide/long 11400 // instruction. 11401 // If there's more than one user instruction, the loadext is desirable no 11402 // matter what. There can be two uses by the same instruction. 11403 if (ExtVal->use_empty() || 11404 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 11405 return true; 11406 11407 SDNode *U = *ExtVal->use_begin(); 11408 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 11409 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 11410 return false; 11411 11412 return true; 11413 } 11414 11415 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 11416 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11417 return false; 11418 11419 if (!isTypeLegal(EVT::getEVT(Ty1))) 11420 return false; 11421 11422 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 11423 11424 // Assuming the caller doesn't have a zeroext or signext return parameter, 11425 // truncation all the way down to i1 is valid. 11426 return true; 11427 } 11428 11429 11430 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11431 if (V < 0) 11432 return false; 11433 11434 unsigned Scale = 1; 11435 switch (VT.getSimpleVT().SimpleTy) { 11436 default: return false; 11437 case MVT::i1: 11438 case MVT::i8: 11439 // Scale == 1; 11440 break; 11441 case MVT::i16: 11442 // Scale == 2; 11443 Scale = 2; 11444 break; 11445 case MVT::i32: 11446 // Scale == 4; 11447 Scale = 4; 11448 break; 11449 } 11450 11451 if ((V & (Scale - 1)) != 0) 11452 return false; 11453 V /= Scale; 11454 return V == (V & ((1LL << 5) - 1)); 11455 } 11456 11457 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11458 const ARMSubtarget *Subtarget) { 11459 bool isNeg = false; 11460 if (V < 0) { 11461 isNeg = true; 11462 V = - V; 11463 } 11464 11465 switch (VT.getSimpleVT().SimpleTy) { 11466 default: return false; 11467 case MVT::i1: 11468 case MVT::i8: 11469 case MVT::i16: 11470 case MVT::i32: 11471 // + imm12 or - imm8 11472 if (isNeg) 11473 return V == (V & ((1LL << 8) - 1)); 11474 return V == (V & ((1LL << 12) - 1)); 11475 case MVT::f32: 11476 case MVT::f64: 11477 // Same as ARM mode. FIXME: NEON? 11478 if (!Subtarget->hasVFP2()) 11479 return false; 11480 if ((V & 3) != 0) 11481 return false; 11482 V >>= 2; 11483 return V == (V & ((1LL << 8) - 1)); 11484 } 11485 } 11486 11487 /// isLegalAddressImmediate - Return true if the integer value can be used 11488 /// as the offset of the target addressing mode for load / store of the 11489 /// given type. 11490 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11491 const ARMSubtarget *Subtarget) { 11492 if (V == 0) 11493 return true; 11494 11495 if (!VT.isSimple()) 11496 return false; 11497 11498 if (Subtarget->isThumb1Only()) 11499 return isLegalT1AddressImmediate(V, VT); 11500 else if (Subtarget->isThumb2()) 11501 return isLegalT2AddressImmediate(V, VT, Subtarget); 11502 11503 // ARM mode. 11504 if (V < 0) 11505 V = - V; 11506 switch (VT.getSimpleVT().SimpleTy) { 11507 default: return false; 11508 case MVT::i1: 11509 case MVT::i8: 11510 case MVT::i32: 11511 // +- imm12 11512 return V == (V & ((1LL << 12) - 1)); 11513 case MVT::i16: 11514 // +- imm8 11515 return V == (V & ((1LL << 8) - 1)); 11516 case MVT::f32: 11517 case MVT::f64: 11518 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11519 return false; 11520 if ((V & 3) != 0) 11521 return false; 11522 V >>= 2; 11523 return V == (V & ((1LL << 8) - 1)); 11524 } 11525 } 11526 11527 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11528 EVT VT) const { 11529 int Scale = AM.Scale; 11530 if (Scale < 0) 11531 return false; 11532 11533 switch (VT.getSimpleVT().SimpleTy) { 11534 default: return false; 11535 case MVT::i1: 11536 case MVT::i8: 11537 case MVT::i16: 11538 case MVT::i32: 11539 if (Scale == 1) 11540 return true; 11541 // r + r << imm 11542 Scale = Scale & ~1; 11543 return Scale == 2 || Scale == 4 || Scale == 8; 11544 case MVT::i64: 11545 // r + r 11546 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11547 return true; 11548 return false; 11549 case MVT::isVoid: 11550 // Note, we allow "void" uses (basically, uses that aren't loads or 11551 // stores), because arm allows folding a scale into many arithmetic 11552 // operations. This should be made more precise and revisited later. 11553 11554 // Allow r << imm, but the imm has to be a multiple of two. 11555 if (Scale & 1) return false; 11556 return isPowerOf2_32(Scale); 11557 } 11558 } 11559 11560 /// isLegalAddressingMode - Return true if the addressing mode represented 11561 /// by AM is legal for this target, for a load/store of the specified type. 11562 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11563 const AddrMode &AM, Type *Ty, 11564 unsigned AS) const { 11565 EVT VT = getValueType(DL, Ty, true); 11566 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 11567 return false; 11568 11569 // Can never fold addr of global into load/store. 11570 if (AM.BaseGV) 11571 return false; 11572 11573 switch (AM.Scale) { 11574 case 0: // no scale reg, must be "r+i" or "r", or "i". 11575 break; 11576 case 1: 11577 if (Subtarget->isThumb1Only()) 11578 return false; 11579 LLVM_FALLTHROUGH; 11580 default: 11581 // ARM doesn't support any R+R*scale+imm addr modes. 11582 if (AM.BaseOffs) 11583 return false; 11584 11585 if (!VT.isSimple()) 11586 return false; 11587 11588 if (Subtarget->isThumb2()) 11589 return isLegalT2ScaledAddressingMode(AM, VT); 11590 11591 int Scale = AM.Scale; 11592 switch (VT.getSimpleVT().SimpleTy) { 11593 default: return false; 11594 case MVT::i1: 11595 case MVT::i8: 11596 case MVT::i32: 11597 if (Scale < 0) Scale = -Scale; 11598 if (Scale == 1) 11599 return true; 11600 // r + r << imm 11601 return isPowerOf2_32(Scale & ~1); 11602 case MVT::i16: 11603 case MVT::i64: 11604 // r + r 11605 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11606 return true; 11607 return false; 11608 11609 case MVT::isVoid: 11610 // Note, we allow "void" uses (basically, uses that aren't loads or 11611 // stores), because arm allows folding a scale into many arithmetic 11612 // operations. This should be made more precise and revisited later. 11613 11614 // Allow r << imm, but the imm has to be a multiple of two. 11615 if (Scale & 1) return false; 11616 return isPowerOf2_32(Scale); 11617 } 11618 } 11619 return true; 11620 } 11621 11622 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11623 /// icmp immediate, that is the target has icmp instructions which can compare 11624 /// a register against the immediate without having to materialize the 11625 /// immediate into a register. 11626 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11627 // Thumb2 and ARM modes can use cmn for negative immediates. 11628 if (!Subtarget->isThumb()) 11629 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11630 if (Subtarget->isThumb2()) 11631 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11632 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11633 return Imm >= 0 && Imm <= 255; 11634 } 11635 11636 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11637 /// *or sub* immediate, that is the target has add or sub instructions which can 11638 /// add a register with the immediate without having to materialize the 11639 /// immediate into a register. 11640 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11641 // Same encoding for add/sub, just flip the sign. 11642 int64_t AbsImm = std::abs(Imm); 11643 if (!Subtarget->isThumb()) 11644 return ARM_AM::getSOImmVal(AbsImm) != -1; 11645 if (Subtarget->isThumb2()) 11646 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11647 // Thumb1 only has 8-bit unsigned immediate. 11648 return AbsImm >= 0 && AbsImm <= 255; 11649 } 11650 11651 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11652 bool isSEXTLoad, SDValue &Base, 11653 SDValue &Offset, bool &isInc, 11654 SelectionDAG &DAG) { 11655 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11656 return false; 11657 11658 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11659 // AddressingMode 3 11660 Base = Ptr->getOperand(0); 11661 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11662 int RHSC = (int)RHS->getZExtValue(); 11663 if (RHSC < 0 && RHSC > -256) { 11664 assert(Ptr->getOpcode() == ISD::ADD); 11665 isInc = false; 11666 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11667 return true; 11668 } 11669 } 11670 isInc = (Ptr->getOpcode() == ISD::ADD); 11671 Offset = Ptr->getOperand(1); 11672 return true; 11673 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11674 // AddressingMode 2 11675 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11676 int RHSC = (int)RHS->getZExtValue(); 11677 if (RHSC < 0 && RHSC > -0x1000) { 11678 assert(Ptr->getOpcode() == ISD::ADD); 11679 isInc = false; 11680 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11681 Base = Ptr->getOperand(0); 11682 return true; 11683 } 11684 } 11685 11686 if (Ptr->getOpcode() == ISD::ADD) { 11687 isInc = true; 11688 ARM_AM::ShiftOpc ShOpcVal= 11689 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11690 if (ShOpcVal != ARM_AM::no_shift) { 11691 Base = Ptr->getOperand(1); 11692 Offset = Ptr->getOperand(0); 11693 } else { 11694 Base = Ptr->getOperand(0); 11695 Offset = Ptr->getOperand(1); 11696 } 11697 return true; 11698 } 11699 11700 isInc = (Ptr->getOpcode() == ISD::ADD); 11701 Base = Ptr->getOperand(0); 11702 Offset = Ptr->getOperand(1); 11703 return true; 11704 } 11705 11706 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11707 return false; 11708 } 11709 11710 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11711 bool isSEXTLoad, SDValue &Base, 11712 SDValue &Offset, bool &isInc, 11713 SelectionDAG &DAG) { 11714 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11715 return false; 11716 11717 Base = Ptr->getOperand(0); 11718 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11719 int RHSC = (int)RHS->getZExtValue(); 11720 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11721 assert(Ptr->getOpcode() == ISD::ADD); 11722 isInc = false; 11723 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11724 return true; 11725 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11726 isInc = Ptr->getOpcode() == ISD::ADD; 11727 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11728 return true; 11729 } 11730 } 11731 11732 return false; 11733 } 11734 11735 /// getPreIndexedAddressParts - returns true by value, base pointer and 11736 /// offset pointer and addressing mode by reference if the node's address 11737 /// can be legally represented as pre-indexed load / store address. 11738 bool 11739 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11740 SDValue &Offset, 11741 ISD::MemIndexedMode &AM, 11742 SelectionDAG &DAG) const { 11743 if (Subtarget->isThumb1Only()) 11744 return false; 11745 11746 EVT VT; 11747 SDValue Ptr; 11748 bool isSEXTLoad = false; 11749 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11750 Ptr = LD->getBasePtr(); 11751 VT = LD->getMemoryVT(); 11752 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11753 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11754 Ptr = ST->getBasePtr(); 11755 VT = ST->getMemoryVT(); 11756 } else 11757 return false; 11758 11759 bool isInc; 11760 bool isLegal = false; 11761 if (Subtarget->isThumb2()) 11762 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11763 Offset, isInc, DAG); 11764 else 11765 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11766 Offset, isInc, DAG); 11767 if (!isLegal) 11768 return false; 11769 11770 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11771 return true; 11772 } 11773 11774 /// getPostIndexedAddressParts - returns true by value, base pointer and 11775 /// offset pointer and addressing mode by reference if this node can be 11776 /// combined with a load / store to form a post-indexed load / store. 11777 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11778 SDValue &Base, 11779 SDValue &Offset, 11780 ISD::MemIndexedMode &AM, 11781 SelectionDAG &DAG) const { 11782 EVT VT; 11783 SDValue Ptr; 11784 bool isSEXTLoad = false, isNonExt; 11785 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11786 VT = LD->getMemoryVT(); 11787 Ptr = LD->getBasePtr(); 11788 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11789 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 11790 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11791 VT = ST->getMemoryVT(); 11792 Ptr = ST->getBasePtr(); 11793 isNonExt = !ST->isTruncatingStore(); 11794 } else 11795 return false; 11796 11797 if (Subtarget->isThumb1Only()) { 11798 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 11799 // must be non-extending/truncating, i32, with an offset of 4. 11800 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 11801 if (Op->getOpcode() != ISD::ADD || !isNonExt) 11802 return false; 11803 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 11804 if (!RHS || RHS->getZExtValue() != 4) 11805 return false; 11806 11807 Offset = Op->getOperand(1); 11808 Base = Op->getOperand(0); 11809 AM = ISD::POST_INC; 11810 return true; 11811 } 11812 11813 bool isInc; 11814 bool isLegal = false; 11815 if (Subtarget->isThumb2()) 11816 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11817 isInc, DAG); 11818 else 11819 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11820 isInc, DAG); 11821 if (!isLegal) 11822 return false; 11823 11824 if (Ptr != Base) { 11825 // Swap base ptr and offset to catch more post-index load / store when 11826 // it's legal. In Thumb2 mode, offset must be an immediate. 11827 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11828 !Subtarget->isThumb2()) 11829 std::swap(Base, Offset); 11830 11831 // Post-indexed load / store update the base pointer. 11832 if (Ptr != Base) 11833 return false; 11834 } 11835 11836 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11837 return true; 11838 } 11839 11840 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11841 APInt &KnownZero, 11842 APInt &KnownOne, 11843 const SelectionDAG &DAG, 11844 unsigned Depth) const { 11845 unsigned BitWidth = KnownOne.getBitWidth(); 11846 KnownZero = KnownOne = APInt(BitWidth, 0); 11847 switch (Op.getOpcode()) { 11848 default: break; 11849 case ARMISD::ADDC: 11850 case ARMISD::ADDE: 11851 case ARMISD::SUBC: 11852 case ARMISD::SUBE: 11853 // These nodes' second result is a boolean 11854 if (Op.getResNo() == 0) 11855 break; 11856 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11857 break; 11858 case ARMISD::CMOV: { 11859 // Bits are known zero/one if known on the LHS and RHS. 11860 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11861 if (KnownZero == 0 && KnownOne == 0) return; 11862 11863 APInt KnownZeroRHS, KnownOneRHS; 11864 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11865 KnownZero &= KnownZeroRHS; 11866 KnownOne &= KnownOneRHS; 11867 return; 11868 } 11869 case ISD::INTRINSIC_W_CHAIN: { 11870 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11871 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11872 switch (IntID) { 11873 default: return; 11874 case Intrinsic::arm_ldaex: 11875 case Intrinsic::arm_ldrex: { 11876 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11877 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11878 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11879 return; 11880 } 11881 } 11882 } 11883 } 11884 } 11885 11886 //===----------------------------------------------------------------------===// 11887 // ARM Inline Assembly Support 11888 //===----------------------------------------------------------------------===// 11889 11890 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11891 // Looking for "rev" which is V6+. 11892 if (!Subtarget->hasV6Ops()) 11893 return false; 11894 11895 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11896 std::string AsmStr = IA->getAsmString(); 11897 SmallVector<StringRef, 4> AsmPieces; 11898 SplitString(AsmStr, AsmPieces, ";\n"); 11899 11900 switch (AsmPieces.size()) { 11901 default: return false; 11902 case 1: 11903 AsmStr = AsmPieces[0]; 11904 AsmPieces.clear(); 11905 SplitString(AsmStr, AsmPieces, " \t,"); 11906 11907 // rev $0, $1 11908 if (AsmPieces.size() == 3 && 11909 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11910 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11911 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11912 if (Ty && Ty->getBitWidth() == 32) 11913 return IntrinsicLowering::LowerToByteSwap(CI); 11914 } 11915 break; 11916 } 11917 11918 return false; 11919 } 11920 11921 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 11922 // At this point, we have to lower this constraint to something else, so we 11923 // lower it to an "r" or "w". However, by doing this we will force the result 11924 // to be in register, while the X constraint is much more permissive. 11925 // 11926 // Although we are correct (we are free to emit anything, without 11927 // constraints), we might break use cases that would expect us to be more 11928 // efficient and emit something else. 11929 if (!Subtarget->hasVFP2()) 11930 return "r"; 11931 if (ConstraintVT.isFloatingPoint()) 11932 return "w"; 11933 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 11934 (ConstraintVT.getSizeInBits() == 64 || 11935 ConstraintVT.getSizeInBits() == 128)) 11936 return "w"; 11937 11938 return "r"; 11939 } 11940 11941 /// getConstraintType - Given a constraint letter, return the type of 11942 /// constraint it is for this target. 11943 ARMTargetLowering::ConstraintType 11944 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11945 if (Constraint.size() == 1) { 11946 switch (Constraint[0]) { 11947 default: break; 11948 case 'l': return C_RegisterClass; 11949 case 'w': return C_RegisterClass; 11950 case 'h': return C_RegisterClass; 11951 case 'x': return C_RegisterClass; 11952 case 't': return C_RegisterClass; 11953 case 'j': return C_Other; // Constant for movw. 11954 // An address with a single base register. Due to the way we 11955 // currently handle addresses it is the same as an 'r' memory constraint. 11956 case 'Q': return C_Memory; 11957 } 11958 } else if (Constraint.size() == 2) { 11959 switch (Constraint[0]) { 11960 default: break; 11961 // All 'U+' constraints are addresses. 11962 case 'U': return C_Memory; 11963 } 11964 } 11965 return TargetLowering::getConstraintType(Constraint); 11966 } 11967 11968 /// Examine constraint type and operand type and determine a weight value. 11969 /// This object must already have been set up with the operand type 11970 /// and the current alternative constraint selected. 11971 TargetLowering::ConstraintWeight 11972 ARMTargetLowering::getSingleConstraintMatchWeight( 11973 AsmOperandInfo &info, const char *constraint) const { 11974 ConstraintWeight weight = CW_Invalid; 11975 Value *CallOperandVal = info.CallOperandVal; 11976 // If we don't have a value, we can't do a match, 11977 // but allow it at the lowest weight. 11978 if (!CallOperandVal) 11979 return CW_Default; 11980 Type *type = CallOperandVal->getType(); 11981 // Look at the constraint type. 11982 switch (*constraint) { 11983 default: 11984 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11985 break; 11986 case 'l': 11987 if (type->isIntegerTy()) { 11988 if (Subtarget->isThumb()) 11989 weight = CW_SpecificReg; 11990 else 11991 weight = CW_Register; 11992 } 11993 break; 11994 case 'w': 11995 if (type->isFloatingPointTy()) 11996 weight = CW_Register; 11997 break; 11998 } 11999 return weight; 12000 } 12001 12002 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 12003 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 12004 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 12005 if (Constraint.size() == 1) { 12006 // GCC ARM Constraint Letters 12007 switch (Constraint[0]) { 12008 case 'l': // Low regs or general regs. 12009 if (Subtarget->isThumb()) 12010 return RCPair(0U, &ARM::tGPRRegClass); 12011 return RCPair(0U, &ARM::GPRRegClass); 12012 case 'h': // High regs or no regs. 12013 if (Subtarget->isThumb()) 12014 return RCPair(0U, &ARM::hGPRRegClass); 12015 break; 12016 case 'r': 12017 if (Subtarget->isThumb1Only()) 12018 return RCPair(0U, &ARM::tGPRRegClass); 12019 return RCPair(0U, &ARM::GPRRegClass); 12020 case 'w': 12021 if (VT == MVT::Other) 12022 break; 12023 if (VT == MVT::f32) 12024 return RCPair(0U, &ARM::SPRRegClass); 12025 if (VT.getSizeInBits() == 64) 12026 return RCPair(0U, &ARM::DPRRegClass); 12027 if (VT.getSizeInBits() == 128) 12028 return RCPair(0U, &ARM::QPRRegClass); 12029 break; 12030 case 'x': 12031 if (VT == MVT::Other) 12032 break; 12033 if (VT == MVT::f32) 12034 return RCPair(0U, &ARM::SPR_8RegClass); 12035 if (VT.getSizeInBits() == 64) 12036 return RCPair(0U, &ARM::DPR_8RegClass); 12037 if (VT.getSizeInBits() == 128) 12038 return RCPair(0U, &ARM::QPR_8RegClass); 12039 break; 12040 case 't': 12041 if (VT == MVT::f32) 12042 return RCPair(0U, &ARM::SPRRegClass); 12043 break; 12044 } 12045 } 12046 if (StringRef("{cc}").equals_lower(Constraint)) 12047 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 12048 12049 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12050 } 12051 12052 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12053 /// vector. If it is invalid, don't add anything to Ops. 12054 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12055 std::string &Constraint, 12056 std::vector<SDValue>&Ops, 12057 SelectionDAG &DAG) const { 12058 SDValue Result; 12059 12060 // Currently only support length 1 constraints. 12061 if (Constraint.length() != 1) return; 12062 12063 char ConstraintLetter = Constraint[0]; 12064 switch (ConstraintLetter) { 12065 default: break; 12066 case 'j': 12067 case 'I': case 'J': case 'K': case 'L': 12068 case 'M': case 'N': case 'O': 12069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 12070 if (!C) 12071 return; 12072 12073 int64_t CVal64 = C->getSExtValue(); 12074 int CVal = (int) CVal64; 12075 // None of these constraints allow values larger than 32 bits. Check 12076 // that the value fits in an int. 12077 if (CVal != CVal64) 12078 return; 12079 12080 switch (ConstraintLetter) { 12081 case 'j': 12082 // Constant suitable for movw, must be between 0 and 12083 // 65535. 12084 if (Subtarget->hasV6T2Ops()) 12085 if (CVal >= 0 && CVal <= 65535) 12086 break; 12087 return; 12088 case 'I': 12089 if (Subtarget->isThumb1Only()) { 12090 // This must be a constant between 0 and 255, for ADD 12091 // immediates. 12092 if (CVal >= 0 && CVal <= 255) 12093 break; 12094 } else if (Subtarget->isThumb2()) { 12095 // A constant that can be used as an immediate value in a 12096 // data-processing instruction. 12097 if (ARM_AM::getT2SOImmVal(CVal) != -1) 12098 break; 12099 } else { 12100 // A constant that can be used as an immediate value in a 12101 // data-processing instruction. 12102 if (ARM_AM::getSOImmVal(CVal) != -1) 12103 break; 12104 } 12105 return; 12106 12107 case 'J': 12108 if (Subtarget->isThumb1Only()) { 12109 // This must be a constant between -255 and -1, for negated ADD 12110 // immediates. This can be used in GCC with an "n" modifier that 12111 // prints the negated value, for use with SUB instructions. It is 12112 // not useful otherwise but is implemented for compatibility. 12113 if (CVal >= -255 && CVal <= -1) 12114 break; 12115 } else { 12116 // This must be a constant between -4095 and 4095. It is not clear 12117 // what this constraint is intended for. Implemented for 12118 // compatibility with GCC. 12119 if (CVal >= -4095 && CVal <= 4095) 12120 break; 12121 } 12122 return; 12123 12124 case 'K': 12125 if (Subtarget->isThumb1Only()) { 12126 // A 32-bit value where only one byte has a nonzero value. Exclude 12127 // zero to match GCC. This constraint is used by GCC internally for 12128 // constants that can be loaded with a move/shift combination. 12129 // It is not useful otherwise but is implemented for compatibility. 12130 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 12131 break; 12132 } else if (Subtarget->isThumb2()) { 12133 // A constant whose bitwise inverse can be used as an immediate 12134 // value in a data-processing instruction. This can be used in GCC 12135 // with a "B" modifier that prints the inverted value, for use with 12136 // BIC and MVN instructions. It is not useful otherwise but is 12137 // implemented for compatibility. 12138 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 12139 break; 12140 } else { 12141 // A constant whose bitwise inverse can be used as an immediate 12142 // value in a data-processing instruction. This can be used in GCC 12143 // with a "B" modifier that prints the inverted value, for use with 12144 // BIC and MVN instructions. It is not useful otherwise but is 12145 // implemented for compatibility. 12146 if (ARM_AM::getSOImmVal(~CVal) != -1) 12147 break; 12148 } 12149 return; 12150 12151 case 'L': 12152 if (Subtarget->isThumb1Only()) { 12153 // This must be a constant between -7 and 7, 12154 // for 3-operand ADD/SUB immediate instructions. 12155 if (CVal >= -7 && CVal < 7) 12156 break; 12157 } else if (Subtarget->isThumb2()) { 12158 // A constant whose negation can be used as an immediate value in a 12159 // data-processing instruction. This can be used in GCC with an "n" 12160 // modifier that prints the negated value, for use with SUB 12161 // instructions. It is not useful otherwise but is implemented for 12162 // compatibility. 12163 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 12164 break; 12165 } else { 12166 // A constant whose negation can be used as an immediate value in a 12167 // data-processing instruction. This can be used in GCC with an "n" 12168 // modifier that prints the negated value, for use with SUB 12169 // instructions. It is not useful otherwise but is implemented for 12170 // compatibility. 12171 if (ARM_AM::getSOImmVal(-CVal) != -1) 12172 break; 12173 } 12174 return; 12175 12176 case 'M': 12177 if (Subtarget->isThumb1Only()) { 12178 // This must be a multiple of 4 between 0 and 1020, for 12179 // ADD sp + immediate. 12180 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 12181 break; 12182 } else { 12183 // A power of two or a constant between 0 and 32. This is used in 12184 // GCC for the shift amount on shifted register operands, but it is 12185 // useful in general for any shift amounts. 12186 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 12187 break; 12188 } 12189 return; 12190 12191 case 'N': 12192 if (Subtarget->isThumb()) { // FIXME thumb2 12193 // This must be a constant between 0 and 31, for shift amounts. 12194 if (CVal >= 0 && CVal <= 31) 12195 break; 12196 } 12197 return; 12198 12199 case 'O': 12200 if (Subtarget->isThumb()) { // FIXME thumb2 12201 // This must be a multiple of 4 between -508 and 508, for 12202 // ADD/SUB sp = sp + immediate. 12203 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 12204 break; 12205 } 12206 return; 12207 } 12208 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 12209 break; 12210 } 12211 12212 if (Result.getNode()) { 12213 Ops.push_back(Result); 12214 return; 12215 } 12216 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12217 } 12218 12219 static RTLIB::Libcall getDivRemLibcall( 12220 const SDNode *N, MVT::SimpleValueType SVT) { 12221 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12222 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12223 "Unhandled Opcode in getDivRemLibcall"); 12224 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12225 N->getOpcode() == ISD::SREM; 12226 RTLIB::Libcall LC; 12227 switch (SVT) { 12228 default: llvm_unreachable("Unexpected request for libcall!"); 12229 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 12230 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 12231 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 12232 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 12233 } 12234 return LC; 12235 } 12236 12237 static TargetLowering::ArgListTy getDivRemArgList( 12238 const SDNode *N, LLVMContext *Context) { 12239 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12240 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12241 "Unhandled Opcode in getDivRemArgList"); 12242 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12243 N->getOpcode() == ISD::SREM; 12244 TargetLowering::ArgListTy Args; 12245 TargetLowering::ArgListEntry Entry; 12246 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12247 EVT ArgVT = N->getOperand(i).getValueType(); 12248 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 12249 Entry.Node = N->getOperand(i); 12250 Entry.Ty = ArgTy; 12251 Entry.isSExt = isSigned; 12252 Entry.isZExt = !isSigned; 12253 Args.push_back(Entry); 12254 } 12255 return Args; 12256 } 12257 12258 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 12259 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 12260 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) && 12261 "Register-based DivRem lowering only"); 12262 unsigned Opcode = Op->getOpcode(); 12263 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 12264 "Invalid opcode for Div/Rem lowering"); 12265 bool isSigned = (Opcode == ISD::SDIVREM); 12266 EVT VT = Op->getValueType(0); 12267 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 12268 12269 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 12270 VT.getSimpleVT().SimpleTy); 12271 SDValue InChain = DAG.getEntryNode(); 12272 12273 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 12274 DAG.getContext()); 12275 12276 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12277 getPointerTy(DAG.getDataLayout())); 12278 12279 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 12280 12281 SDLoc dl(Op); 12282 TargetLowering::CallLoweringInfo CLI(DAG); 12283 CLI.setDebugLoc(dl).setChain(InChain) 12284 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 12285 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 12286 12287 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 12288 return CallInfo.first; 12289 } 12290 12291 // Lowers REM using divmod helpers 12292 // see RTABI section 4.2/4.3 12293 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 12294 // Build return types (div and rem) 12295 std::vector<Type*> RetTyParams; 12296 Type *RetTyElement; 12297 12298 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 12299 default: llvm_unreachable("Unexpected request for libcall!"); 12300 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 12301 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 12302 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 12303 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 12304 } 12305 12306 RetTyParams.push_back(RetTyElement); 12307 RetTyParams.push_back(RetTyElement); 12308 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 12309 Type *RetTy = StructType::get(*DAG.getContext(), ret); 12310 12311 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 12312 SimpleTy); 12313 SDValue InChain = DAG.getEntryNode(); 12314 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 12315 bool isSigned = N->getOpcode() == ISD::SREM; 12316 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12317 getPointerTy(DAG.getDataLayout())); 12318 12319 // Lower call 12320 CallLoweringInfo CLI(DAG); 12321 CLI.setChain(InChain) 12322 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 12323 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 12324 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 12325 12326 // Return second (rem) result operand (first contains div) 12327 SDNode *ResNode = CallResult.first.getNode(); 12328 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 12329 return ResNode->getOperand(1); 12330 } 12331 12332 SDValue 12333 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 12334 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 12335 SDLoc DL(Op); 12336 12337 // Get the inputs. 12338 SDValue Chain = Op.getOperand(0); 12339 SDValue Size = Op.getOperand(1); 12340 12341 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 12342 DAG.getConstant(2, DL, MVT::i32)); 12343 12344 SDValue Flag; 12345 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 12346 Flag = Chain.getValue(1); 12347 12348 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 12349 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 12350 12351 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 12352 Chain = NewSP.getValue(1); 12353 12354 SDValue Ops[2] = { NewSP, Chain }; 12355 return DAG.getMergeValues(Ops, DL); 12356 } 12357 12358 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 12359 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 12360 "Unexpected type for custom-lowering FP_EXTEND"); 12361 12362 RTLIB::Libcall LC; 12363 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 12364 12365 SDValue SrcVal = Op.getOperand(0); 12366 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12367 SDLoc(Op)).first; 12368 } 12369 12370 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 12371 assert(Op.getOperand(0).getValueType() == MVT::f64 && 12372 Subtarget->isFPOnlySP() && 12373 "Unexpected type for custom-lowering FP_ROUND"); 12374 12375 RTLIB::Libcall LC; 12376 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 12377 12378 SDValue SrcVal = Op.getOperand(0); 12379 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12380 SDLoc(Op)).first; 12381 } 12382 12383 bool 12384 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12385 // The ARM target isn't yet aware of offsets. 12386 return false; 12387 } 12388 12389 bool ARM::isBitFieldInvertedMask(unsigned v) { 12390 if (v == 0xffffffff) 12391 return false; 12392 12393 // there can be 1's on either or both "outsides", all the "inside" 12394 // bits must be 0's 12395 return isShiftedMask_32(~v); 12396 } 12397 12398 /// isFPImmLegal - Returns true if the target can instruction select the 12399 /// specified FP immediate natively. If false, the legalizer will 12400 /// materialize the FP immediate as a load from a constant pool. 12401 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 12402 if (!Subtarget->hasVFP3()) 12403 return false; 12404 if (VT == MVT::f32) 12405 return ARM_AM::getFP32Imm(Imm) != -1; 12406 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 12407 return ARM_AM::getFP64Imm(Imm) != -1; 12408 return false; 12409 } 12410 12411 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 12412 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 12413 /// specified in the intrinsic calls. 12414 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12415 const CallInst &I, 12416 unsigned Intrinsic) const { 12417 switch (Intrinsic) { 12418 case Intrinsic::arm_neon_vld1: 12419 case Intrinsic::arm_neon_vld2: 12420 case Intrinsic::arm_neon_vld3: 12421 case Intrinsic::arm_neon_vld4: 12422 case Intrinsic::arm_neon_vld2lane: 12423 case Intrinsic::arm_neon_vld3lane: 12424 case Intrinsic::arm_neon_vld4lane: { 12425 Info.opc = ISD::INTRINSIC_W_CHAIN; 12426 // Conservatively set memVT to the entire set of vectors loaded. 12427 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12428 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 12429 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12430 Info.ptrVal = I.getArgOperand(0); 12431 Info.offset = 0; 12432 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12433 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12434 Info.vol = false; // volatile loads with NEON intrinsics not supported 12435 Info.readMem = true; 12436 Info.writeMem = false; 12437 return true; 12438 } 12439 case Intrinsic::arm_neon_vst1: 12440 case Intrinsic::arm_neon_vst2: 12441 case Intrinsic::arm_neon_vst3: 12442 case Intrinsic::arm_neon_vst4: 12443 case Intrinsic::arm_neon_vst2lane: 12444 case Intrinsic::arm_neon_vst3lane: 12445 case Intrinsic::arm_neon_vst4lane: { 12446 Info.opc = ISD::INTRINSIC_VOID; 12447 // Conservatively set memVT to the entire set of vectors stored. 12448 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12449 unsigned NumElts = 0; 12450 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 12451 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 12452 if (!ArgTy->isVectorTy()) 12453 break; 12454 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 12455 } 12456 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12457 Info.ptrVal = I.getArgOperand(0); 12458 Info.offset = 0; 12459 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12460 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12461 Info.vol = false; // volatile stores with NEON intrinsics not supported 12462 Info.readMem = false; 12463 Info.writeMem = true; 12464 return true; 12465 } 12466 case Intrinsic::arm_ldaex: 12467 case Intrinsic::arm_ldrex: { 12468 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12469 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12470 Info.opc = ISD::INTRINSIC_W_CHAIN; 12471 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12472 Info.ptrVal = I.getArgOperand(0); 12473 Info.offset = 0; 12474 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12475 Info.vol = true; 12476 Info.readMem = true; 12477 Info.writeMem = false; 12478 return true; 12479 } 12480 case Intrinsic::arm_stlex: 12481 case Intrinsic::arm_strex: { 12482 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12483 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12484 Info.opc = ISD::INTRINSIC_W_CHAIN; 12485 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12486 Info.ptrVal = I.getArgOperand(1); 12487 Info.offset = 0; 12488 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12489 Info.vol = true; 12490 Info.readMem = false; 12491 Info.writeMem = true; 12492 return true; 12493 } 12494 case Intrinsic::arm_stlexd: 12495 case Intrinsic::arm_strexd: { 12496 Info.opc = ISD::INTRINSIC_W_CHAIN; 12497 Info.memVT = MVT::i64; 12498 Info.ptrVal = I.getArgOperand(2); 12499 Info.offset = 0; 12500 Info.align = 8; 12501 Info.vol = true; 12502 Info.readMem = false; 12503 Info.writeMem = true; 12504 return true; 12505 } 12506 case Intrinsic::arm_ldaexd: 12507 case Intrinsic::arm_ldrexd: { 12508 Info.opc = ISD::INTRINSIC_W_CHAIN; 12509 Info.memVT = MVT::i64; 12510 Info.ptrVal = I.getArgOperand(0); 12511 Info.offset = 0; 12512 Info.align = 8; 12513 Info.vol = true; 12514 Info.readMem = true; 12515 Info.writeMem = false; 12516 return true; 12517 } 12518 default: 12519 break; 12520 } 12521 12522 return false; 12523 } 12524 12525 /// \brief Returns true if it is beneficial to convert a load of a constant 12526 /// to just the constant itself. 12527 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12528 Type *Ty) const { 12529 assert(Ty->isIntegerTy()); 12530 12531 unsigned Bits = Ty->getPrimitiveSizeInBits(); 12532 if (Bits == 0 || Bits > 32) 12533 return false; 12534 return true; 12535 } 12536 12537 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 12538 ARM_MB::MemBOpt Domain) const { 12539 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12540 12541 // First, if the target has no DMB, see what fallback we can use. 12542 if (!Subtarget->hasDataBarrier()) { 12543 // Some ARMv6 cpus can support data barriers with an mcr instruction. 12544 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 12545 // here. 12546 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 12547 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 12548 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 12549 Builder.getInt32(0), Builder.getInt32(7), 12550 Builder.getInt32(10), Builder.getInt32(5)}; 12551 return Builder.CreateCall(MCR, args); 12552 } else { 12553 // Instead of using barriers, atomic accesses on these subtargets use 12554 // libcalls. 12555 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 12556 } 12557 } else { 12558 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 12559 // Only a full system barrier exists in the M-class architectures. 12560 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 12561 Constant *CDomain = Builder.getInt32(Domain); 12562 return Builder.CreateCall(DMB, CDomain); 12563 } 12564 } 12565 12566 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 12567 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 12568 AtomicOrdering Ord, bool IsStore, 12569 bool IsLoad) const { 12570 switch (Ord) { 12571 case AtomicOrdering::NotAtomic: 12572 case AtomicOrdering::Unordered: 12573 llvm_unreachable("Invalid fence: unordered/non-atomic"); 12574 case AtomicOrdering::Monotonic: 12575 case AtomicOrdering::Acquire: 12576 return nullptr; // Nothing to do 12577 case AtomicOrdering::SequentiallyConsistent: 12578 if (!IsStore) 12579 return nullptr; // Nothing to do 12580 /*FALLTHROUGH*/ 12581 case AtomicOrdering::Release: 12582 case AtomicOrdering::AcquireRelease: 12583 if (Subtarget->preferISHSTBarriers()) 12584 return makeDMB(Builder, ARM_MB::ISHST); 12585 // FIXME: add a comment with a link to documentation justifying this. 12586 else 12587 return makeDMB(Builder, ARM_MB::ISH); 12588 } 12589 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 12590 } 12591 12592 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 12593 AtomicOrdering Ord, bool IsStore, 12594 bool IsLoad) const { 12595 switch (Ord) { 12596 case AtomicOrdering::NotAtomic: 12597 case AtomicOrdering::Unordered: 12598 llvm_unreachable("Invalid fence: unordered/not-atomic"); 12599 case AtomicOrdering::Monotonic: 12600 case AtomicOrdering::Release: 12601 return nullptr; // Nothing to do 12602 case AtomicOrdering::Acquire: 12603 case AtomicOrdering::AcquireRelease: 12604 case AtomicOrdering::SequentiallyConsistent: 12605 return makeDMB(Builder, ARM_MB::ISH); 12606 } 12607 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 12608 } 12609 12610 // Loads and stores less than 64-bits are already atomic; ones above that 12611 // are doomed anyway, so defer to the default libcall and blame the OS when 12612 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12613 // anything for those. 12614 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12615 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12616 return (Size == 64) && !Subtarget->isMClass(); 12617 } 12618 12619 // Loads and stores less than 64-bits are already atomic; ones above that 12620 // are doomed anyway, so defer to the default libcall and blame the OS when 12621 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12622 // anything for those. 12623 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12624 // guarantee, see DDI0406C ARM architecture reference manual, 12625 // sections A8.8.72-74 LDRD) 12626 TargetLowering::AtomicExpansionKind 12627 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12628 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12629 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12630 : AtomicExpansionKind::None; 12631 } 12632 12633 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12634 // and up to 64 bits on the non-M profiles 12635 TargetLowering::AtomicExpansionKind 12636 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12637 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12638 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12639 ? AtomicExpansionKind::LLSC 12640 : AtomicExpansionKind::None; 12641 } 12642 12643 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12644 AtomicCmpXchgInst *AI) const { 12645 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 12646 // implement cmpxchg without spilling. If the address being exchanged is also 12647 // on the stack and close enough to the spill slot, this can lead to a 12648 // situation where the monitor always gets cleared and the atomic operation 12649 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 12650 return getTargetMachine().getOptLevel() != 0; 12651 } 12652 12653 bool ARMTargetLowering::shouldInsertFencesForAtomic( 12654 const Instruction *I) const { 12655 return InsertFencesForAtomic; 12656 } 12657 12658 // This has so far only been implemented for MachO. 12659 bool ARMTargetLowering::useLoadStackGuardNode() const { 12660 return Subtarget->isTargetMachO(); 12661 } 12662 12663 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12664 unsigned &Cost) const { 12665 // If we do not have NEON, vector types are not natively supported. 12666 if (!Subtarget->hasNEON()) 12667 return false; 12668 12669 // Floating point values and vector values map to the same register file. 12670 // Therefore, although we could do a store extract of a vector type, this is 12671 // better to leave at float as we have more freedom in the addressing mode for 12672 // those. 12673 if (VectorTy->isFPOrFPVectorTy()) 12674 return false; 12675 12676 // If the index is unknown at compile time, this is very expensive to lower 12677 // and it is not possible to combine the store with the extract. 12678 if (!isa<ConstantInt>(Idx)) 12679 return false; 12680 12681 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12682 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12683 // We can do a store + vector extract on any vector that fits perfectly in a D 12684 // or Q register. 12685 if (BitWidth == 64 || BitWidth == 128) { 12686 Cost = 0; 12687 return true; 12688 } 12689 return false; 12690 } 12691 12692 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12693 return Subtarget->hasV6T2Ops(); 12694 } 12695 12696 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12697 return Subtarget->hasV6T2Ops(); 12698 } 12699 12700 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12701 AtomicOrdering Ord) const { 12702 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12703 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12704 bool IsAcquire = isAcquireOrStronger(Ord); 12705 12706 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12707 // intrinsic must return {i32, i32} and we have to recombine them into a 12708 // single i64 here. 12709 if (ValTy->getPrimitiveSizeInBits() == 64) { 12710 Intrinsic::ID Int = 12711 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12712 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12713 12714 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12715 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12716 12717 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12718 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12719 if (!Subtarget->isLittle()) 12720 std::swap (Lo, Hi); 12721 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12722 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12723 return Builder.CreateOr( 12724 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12725 } 12726 12727 Type *Tys[] = { Addr->getType() }; 12728 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12729 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12730 12731 return Builder.CreateTruncOrBitCast( 12732 Builder.CreateCall(Ldrex, Addr), 12733 cast<PointerType>(Addr->getType())->getElementType()); 12734 } 12735 12736 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12737 IRBuilder<> &Builder) const { 12738 if (!Subtarget->hasV7Ops()) 12739 return; 12740 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12741 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12742 } 12743 12744 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12745 Value *Addr, 12746 AtomicOrdering Ord) const { 12747 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12748 bool IsRelease = isReleaseOrStronger(Ord); 12749 12750 // Since the intrinsics must have legal type, the i64 intrinsics take two 12751 // parameters: "i32, i32". We must marshal Val into the appropriate form 12752 // before the call. 12753 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12754 Intrinsic::ID Int = 12755 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12756 Function *Strex = Intrinsic::getDeclaration(M, Int); 12757 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12758 12759 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12760 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12761 if (!Subtarget->isLittle()) 12762 std::swap (Lo, Hi); 12763 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12764 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12765 } 12766 12767 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12768 Type *Tys[] = { Addr->getType() }; 12769 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12770 12771 return Builder.CreateCall( 12772 Strex, {Builder.CreateZExtOrBitCast( 12773 Val, Strex->getFunctionType()->getParamType(0)), 12774 Addr}); 12775 } 12776 12777 /// \brief Lower an interleaved load into a vldN intrinsic. 12778 /// 12779 /// E.g. Lower an interleaved load (Factor = 2): 12780 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12781 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12782 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12783 /// 12784 /// Into: 12785 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12786 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12787 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12788 bool ARMTargetLowering::lowerInterleavedLoad( 12789 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12790 ArrayRef<unsigned> Indices, unsigned Factor) const { 12791 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12792 "Invalid interleave factor"); 12793 assert(!Shuffles.empty() && "Empty shufflevector input"); 12794 assert(Shuffles.size() == Indices.size() && 12795 "Unmatched number of shufflevectors and indices"); 12796 12797 VectorType *VecTy = Shuffles[0]->getType(); 12798 Type *EltTy = VecTy->getVectorElementType(); 12799 12800 const DataLayout &DL = LI->getModule()->getDataLayout(); 12801 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12802 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12803 12804 // Skip if we do not have NEON and skip illegal vector types and vector types 12805 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12806 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12807 return false; 12808 12809 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12810 // load integer vectors first and then convert to pointer vectors. 12811 if (EltTy->isPointerTy()) 12812 VecTy = 12813 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12814 12815 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12816 Intrinsic::arm_neon_vld3, 12817 Intrinsic::arm_neon_vld4}; 12818 12819 IRBuilder<> Builder(LI); 12820 SmallVector<Value *, 2> Ops; 12821 12822 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12823 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12824 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12825 12826 Type *Tys[] = { VecTy, Int8Ptr }; 12827 Function *VldnFunc = 12828 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12829 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12830 12831 // Replace uses of each shufflevector with the corresponding vector loaded 12832 // by ldN. 12833 for (unsigned i = 0; i < Shuffles.size(); i++) { 12834 ShuffleVectorInst *SV = Shuffles[i]; 12835 unsigned Index = Indices[i]; 12836 12837 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12838 12839 // Convert the integer vector to pointer vector if the element is pointer. 12840 if (EltTy->isPointerTy()) 12841 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12842 12843 SV->replaceAllUsesWith(SubVec); 12844 } 12845 12846 return true; 12847 } 12848 12849 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12850 /// 12851 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12852 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12853 unsigned NumElts) { 12854 SmallVector<Constant *, 16> Mask; 12855 for (unsigned i = 0; i < NumElts; i++) 12856 Mask.push_back(Builder.getInt32(Start + i)); 12857 12858 return ConstantVector::get(Mask); 12859 } 12860 12861 /// \brief Lower an interleaved store into a vstN intrinsic. 12862 /// 12863 /// E.g. Lower an interleaved store (Factor = 3): 12864 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12865 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12866 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12867 /// 12868 /// Into: 12869 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12870 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12871 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12872 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12873 /// 12874 /// Note that the new shufflevectors will be removed and we'll only generate one 12875 /// vst3 instruction in CodeGen. 12876 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12877 ShuffleVectorInst *SVI, 12878 unsigned Factor) const { 12879 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12880 "Invalid interleave factor"); 12881 12882 VectorType *VecTy = SVI->getType(); 12883 assert(VecTy->getVectorNumElements() % Factor == 0 && 12884 "Invalid interleaved store"); 12885 12886 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12887 Type *EltTy = VecTy->getVectorElementType(); 12888 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12889 12890 const DataLayout &DL = SI->getModule()->getDataLayout(); 12891 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12892 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12893 12894 // Skip if we do not have NEON and skip illegal vector types and vector types 12895 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12896 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12897 EltIs64Bits) 12898 return false; 12899 12900 Value *Op0 = SVI->getOperand(0); 12901 Value *Op1 = SVI->getOperand(1); 12902 IRBuilder<> Builder(SI); 12903 12904 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12905 // vectors to integer vectors. 12906 if (EltTy->isPointerTy()) { 12907 Type *IntTy = DL.getIntPtrType(EltTy); 12908 12909 // Convert to the corresponding integer vector. 12910 Type *IntVecTy = 12911 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12912 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12913 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12914 12915 SubVecTy = VectorType::get(IntTy, NumSubElts); 12916 } 12917 12918 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12919 Intrinsic::arm_neon_vst3, 12920 Intrinsic::arm_neon_vst4}; 12921 SmallVector<Value *, 6> Ops; 12922 12923 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12924 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12925 12926 Type *Tys[] = { Int8Ptr, SubVecTy }; 12927 Function *VstNFunc = Intrinsic::getDeclaration( 12928 SI->getModule(), StoreInts[Factor - 2], Tys); 12929 12930 // Split the shufflevector operands into sub vectors for the new vstN call. 12931 for (unsigned i = 0; i < Factor; i++) 12932 Ops.push_back(Builder.CreateShuffleVector( 12933 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12934 12935 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12936 Builder.CreateCall(VstNFunc, Ops); 12937 return true; 12938 } 12939 12940 enum HABaseType { 12941 HA_UNKNOWN = 0, 12942 HA_FLOAT, 12943 HA_DOUBLE, 12944 HA_VECT64, 12945 HA_VECT128 12946 }; 12947 12948 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12949 uint64_t &Members) { 12950 if (auto *ST = dyn_cast<StructType>(Ty)) { 12951 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12952 uint64_t SubMembers = 0; 12953 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12954 return false; 12955 Members += SubMembers; 12956 } 12957 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12958 uint64_t SubMembers = 0; 12959 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12960 return false; 12961 Members += SubMembers * AT->getNumElements(); 12962 } else if (Ty->isFloatTy()) { 12963 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12964 return false; 12965 Members = 1; 12966 Base = HA_FLOAT; 12967 } else if (Ty->isDoubleTy()) { 12968 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12969 return false; 12970 Members = 1; 12971 Base = HA_DOUBLE; 12972 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12973 Members = 1; 12974 switch (Base) { 12975 case HA_FLOAT: 12976 case HA_DOUBLE: 12977 return false; 12978 case HA_VECT64: 12979 return VT->getBitWidth() == 64; 12980 case HA_VECT128: 12981 return VT->getBitWidth() == 128; 12982 case HA_UNKNOWN: 12983 switch (VT->getBitWidth()) { 12984 case 64: 12985 Base = HA_VECT64; 12986 return true; 12987 case 128: 12988 Base = HA_VECT128; 12989 return true; 12990 default: 12991 return false; 12992 } 12993 } 12994 } 12995 12996 return (Members > 0 && Members <= 4); 12997 } 12998 12999 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 13000 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 13001 /// passing according to AAPCS rules. 13002 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 13003 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 13004 if (getEffectiveCallingConv(CallConv, isVarArg) != 13005 CallingConv::ARM_AAPCS_VFP) 13006 return false; 13007 13008 HABaseType Base = HA_UNKNOWN; 13009 uint64_t Members = 0; 13010 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 13011 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 13012 13013 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 13014 return IsHA || IsIntArray; 13015 } 13016 13017 unsigned ARMTargetLowering::getExceptionPointerRegister( 13018 const Constant *PersonalityFn) const { 13019 // Platforms which do not use SjLj EH may return values in these registers 13020 // via the personality function. 13021 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 13022 } 13023 13024 unsigned ARMTargetLowering::getExceptionSelectorRegister( 13025 const Constant *PersonalityFn) const { 13026 // Platforms which do not use SjLj EH may return values in these registers 13027 // via the personality function. 13028 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 13029 } 13030 13031 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13032 // Update IsSplitCSR in ARMFunctionInfo. 13033 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 13034 AFI->setIsSplitCSR(true); 13035 } 13036 13037 void ARMTargetLowering::insertCopiesSplitCSR( 13038 MachineBasicBlock *Entry, 13039 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13040 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 13041 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13042 if (!IStart) 13043 return; 13044 13045 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 13046 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13047 MachineBasicBlock::iterator MBBI = Entry->begin(); 13048 for (const MCPhysReg *I = IStart; *I; ++I) { 13049 const TargetRegisterClass *RC = nullptr; 13050 if (ARM::GPRRegClass.contains(*I)) 13051 RC = &ARM::GPRRegClass; 13052 else if (ARM::DPRRegClass.contains(*I)) 13053 RC = &ARM::DPRRegClass; 13054 else 13055 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13056 13057 unsigned NewVR = MRI->createVirtualRegister(RC); 13058 // Create copy from CSR to a virtual register. 13059 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13060 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13061 // nounwind. If we want to generalize this later, we may need to emit 13062 // CFI pseudo-instructions. 13063 assert(Entry->getParent()->getFunction()->hasFnAttribute( 13064 Attribute::NoUnwind) && 13065 "Function should be nounwind in insertCopiesSplitCSR!"); 13066 Entry->addLiveIn(*I); 13067 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13068 .addReg(*I); 13069 13070 // Insert the copy-back instructions right before the terminator. 13071 for (auto *Exit : Exits) 13072 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13073 TII->get(TargetOpcode::COPY), *I) 13074 .addReg(NewVR); 13075 } 13076 } 13077